diff --git a/spaces/0xAnders/ama-bot/app.py b/spaces/0xAnders/ama-bot/app.py deleted file mode 100644 index 3610d4f0f2c503724b8c357d78ed69e341e073d9..0000000000000000000000000000000000000000 --- a/spaces/0xAnders/ama-bot/app.py +++ /dev/null @@ -1,70 +0,0 @@ -import gradio as gr - -import git - -git.Git().clone("https://github.com/Jesse-zj/bobo-test.git") - -from llama_index import SimpleDirectoryReader, GPTListIndex, readers, GPTVectorStoreIndex, LLMPredictor, PromptHelper,ServiceContext -from llama_index import StorageContext, load_index_from_storage -from langchain import OpenAI -import sys -import os -from IPython.display import Markdown, display - -openai_api_key = os.environ['OPENAI_API_KEY'] - -def construct_index(directory_path): - # set maximum input size - max_input_size = 4096 - # set number of output tokens - num_outputs = 1000 - # set maximum chunk overlap - max_chunk_overlap = 30 - # set chunk size limit - chunk_size_limit = 600 - - # define LLM - llm_predictor = LLMPredictor(llm=OpenAI(temperature=0.5, model_name="text-davinci-003", max_tokens=num_outputs)) - prompt_helper = PromptHelper(max_input_size, num_outputs, max_chunk_overlap, chunk_size_limit=chunk_size_limit) - - documents = SimpleDirectoryReader(directory_path).load_data() - - service_context = ServiceContext.from_defaults(llm_predictor=llm_predictor, prompt_helper=prompt_helper) - - index = GPTVectorStoreIndex.from_documents( - documents, service_context=service_context - ) - - index.storage_context.persist('index.json') - - return index - -def ask_ai(query): - # set maximum input size - max_input_size = 4096 - # set number of output tokens - num_outputs = 1000 - # set maximum chunk overlap - max_chunk_overlap = 30 - # set chunk size limit - chunk_size_limit = 600 - - # define LLM - llm_predictor = LLMPredictor(llm=OpenAI(temperature=0.5, model_name="text-davinci-003", max_tokens=num_outputs)) - prompt_helper = PromptHelper(max_input_size, num_outputs, max_chunk_overlap, chunk_size_limit=chunk_size_limit) - - service_context = ServiceContext.from_defaults(llm_predictor=llm_predictor, prompt_helper=prompt_helper) - # rebuild storage context - storage_context = StorageContext.from_defaults(persist_dir="index.json") - # load index - index = load_index_from_storage(storage_context, service_context=service_context) - - query_engine = index.as_query_engine() - response = query_engine.query(query) - return str(response) - - -construct_index('bobo-test') - -iface = gr.Interface(fn=ask_ai, inputs="textbox", outputs="text") -iface.launch() diff --git a/spaces/101-5/gpt4free/g4f/.v1/gpt4free/gptworldAi/README.md b/spaces/101-5/gpt4free/g4f/.v1/gpt4free/gptworldAi/README.md deleted file mode 100644 index a6b07f86e5752a5420f7b163694f49ade95cb743..0000000000000000000000000000000000000000 --- a/spaces/101-5/gpt4free/g4f/.v1/gpt4free/gptworldAi/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# gptworldAi -Written by [hp_mzx](https://github.com/hpsj). - -## Examples: -### Completion: -```python -for chunk in gptworldAi.Completion.create("你是谁", "127.0.0.1:7890"): - print(chunk, end="", flush=True) - print() -``` - -### Chat Completion: -Support context -```python -message = [] -while True: - prompt = input("请输入问题:") - message.append({"role": "user","content": prompt}) - text = "" - for chunk in gptworldAi.ChatCompletion.create(message,'127.0.0.1:7890'): - text = text+chunk - print(chunk, end="", flush=True) - print() - message.append({"role": "assistant", "content": text}) -``` \ No newline at end of file diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/Ahmet Kanneci Gitar Metodu Pdf 16 [VERIFIED].md b/spaces/1gistliPinn/ChatGPT4/Examples/Ahmet Kanneci Gitar Metodu Pdf 16 [VERIFIED].md deleted file mode 100644 index 3764d915c82ddd4093f95c1de863c19f35329769..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/Ahmet Kanneci Gitar Metodu Pdf 16 [VERIFIED].md +++ /dev/null @@ -1,126 +0,0 @@ -
-

How to Learn Classical Guitar with Ahmet Kanneci Gitar Metodu Pdf 16

- -

Classical guitar is a beautiful and rewarding instrument that can enrich your life with music. However, learning classical guitar can also be challenging and frustrating if you don't have the right guidance and resources. That's why you need Ahmet Kanneci Gitar Metodu Pdf 16, a guitar method book that can teach you everything you need to know about classical guitar playing.

- -

Ahmet Kanneci Gitar Metodu Pdf 16 is a guitar method book written by Ahmet Kanneci, a Turkish classical guitar virtuoso and educator. He has studied and performed with some of the most famous guitarists in the world, such as Andrés Segovia, John Williams, Julian Bream, and Oscar Ghiglia. He has also taught many students and written several books on classical guitar.

-

ahmet kanneci gitar metodu pdf 16


DOWNLOADhttps://imgfil.com/2uy20p



- -

In this article, we will explain what Ahmet Kanneci Gitar Metodu Pdf 16 is, what it contains, and how it can help you learn classical guitar. We will also give you some tips on how to use this book effectively and enjoyably.

- -

What is Ahmet Kanneci Gitar Metodu Pdf 16?

- -

Ahmet Kanneci Gitar Metodu Pdf 16 is a guitar method book that covers various aspects of classical guitar playing, such as technique, theory, repertoire, and interpretation. It is divided into 16 chapters, each focusing on a specific topic or skill.

- -

The book is written in Turkish, but it also includes musical notation and tablature for easy reference. It is suitable for beginners as well as intermediate and advanced players who want to improve their guitar skills.

- -

Ahmet Kanneci Gitar Metodu Pdf 16 is based on the author's extensive experience as a performer and teacher of classical guitar. He has used his own methods and insights to create a comprehensive and effective guitar curriculum that can help you achieve your musical goals.

- -

What does Ahmet Kanneci Gitar Metodu Pdf 16 contain?

- -

Ahmet Kanneci Gitar Metodu Pdf 16 contains a wealth of information and exercises that can help you master the classical guitar. Here are some of the topics that you can find in this book:

-

- - - -

The book also includes a selection of classical guitar pieces from different periods and regions, such as Renaissance, Baroque, Classical, Romantic, Modern, Turkish, Spanish, Latin American, etc. You can learn how to play these pieces with proper fingering, articulation, dynamics, phrasing, and ornamentation.

- -

How can Ahmet Kanneci Gitar Metodu Pdf 16 help you learn classical guitar?

- -

Ahmet Kanneci Gitar Metodu Pdf 16 can help you learn classical guitar in many ways. Here are some of the benefits that you can get from using this book:

- - - -

How to use Ahmet Kanneci Gitar Metodu Pdf 16 effectively and enjoyably?

- -

To use Ahmet Kanneci Gitar Metodu Pdf 16 effectively and enjoyably, you need to follow some guidelines and tips. Here are some of them:

- - - -

Conclusion

- -

Ahmet Kanneci Gitar Metodu Pdf 16 is a comprehensive guide for classical guitar lovers who want to learn or improve their guitar skills. It covers various topics and skills related to classical guitar playing, such as technique, theory, repertoire, interpretation, performance, etc. It also includes a selection of classical guitar pieces from different periods and regions that you can play with pleasure and satisfaction.

- -

If you are interested in Ahmet Kanneci Gitar Metodu Pdf 16, you can download it for free from the link below. You can also visit the author's website or social media pages to learn more about him and his work.

- -

We hope this article has given you some useful information about Ahmet Kanneci Gitar Metodu Pdf 16. We wish you all the best in your classical guitar journey!

-

Where can you download Ahmet Kanneci Gitar Metodu Pdf 16?

- -

If you want to download Ahmet Kanneci Gitar Metodu Pdf 16, you can do so for free from the link below. This is a verified and safe link that will direct you to the PDF file of the book. You can save it on your computer or mobile device and access it anytime you want.

- -

Alternatively, you can also buy a hard copy of the book from online or offline bookstores. However, this might be more expensive and less convenient than downloading the PDF file.

- -

Whichever option you choose, make sure you have a good quality classical guitar and a tuner to accompany your learning with Ahmet Kanneci Gitar Metodu Pdf 16.

- -

Who is Ahmet Kanneci and why should you trust him?

- -

Ahmet Kanneci is a Turkish classical guitar virtuoso and educator who has been playing and teaching classical guitar for over 40 years. He is widely regarded as one of the best classical guitarists in Turkey and in the world.

- -

Ahmet Kanneci was born in Ankara in 1957. He started playing guitar at the age of 11 and soon showed great talent and passion for the instrument. He studied with some of the most renowned guitarists in the world, such as Andrés Segovia, John Williams, Julian Bream, and Oscar Ghiglia. He also graduated from Ankara State Conservatory and Middle East Technical University with degrees in music and architecture.

- -

Ahmet Kanneci has performed in many countries and festivals, such as Spain, France, Italy, Germany, England, USA, Canada, Japan, China, etc. He has also recorded several albums and DVDs of classical guitar music. He has received numerous awards and honors for his musical achievements, such as the Presidential Culture and Art Grand Award, the State Artist Title, the Ankara Music Festival Honorary Award, etc.

- -

Ahmet Kanneci has also taught many students and written several books on classical guitar. He is currently a professor at Hacettepe University Ankara State Conservatory. He is also the founder and president of the Classical Guitar Association of Turkey.

- -

Ahmet Kanneci is a trustworthy and respected guitarist who can teach you how to play classical guitar with his book Ahmet Kanneci Gitar Metodu Pdf 16. You can learn from his experience, knowledge, and wisdom and become a better guitarist yourself.

-

What are some reviews and testimonials of Ahmet Kanneci Gitar Metodu Pdf 16?

- -

Ahmet Kanneci Gitar Metodu Pdf 16 has received many positive reviews and testimonials from classical guitar enthusiasts who have used this book to learn or improve their guitar skills. Here are some of them:

- -
-

"I have been playing classical guitar for over 10 years and I have used many guitar method books, but none of them can compare to Ahmet Kanneci Gitar Metodu Pdf 16. This book is comprehensive, clear, and practical. It covers everything from basic to advanced topics and skills. It also has a great selection of pieces that are enjoyable and challenging to play. I have learned so much from this book and I highly recommend it to anyone who wants to learn classical guitar."

-- Ali, a classical guitar student from Istanbul -
- -
-

"Ahmet Kanneci Gitar Metodu Pdf 16 is a masterpiece of classical guitar education. It is written by a master guitarist who knows how to teach and inspire his students. It is not just a book, but a journey that takes you from the fundamentals to the artistry of classical guitar playing. It is also a treasure that contains the essence of Turkish classical guitar music. I am grateful to Ahmet Kanneci for sharing his wisdom and passion with us through this book."

-- Emine, a classical guitar teacher from Ankara -
- -
-

"I have always wanted to learn classical guitar, but I never had the time or the money to take lessons. Then I discovered Ahmet Kanneci Gitar Metodu Pdf 16 online and I decided to give it a try. I was amazed by how easy and fun it was to learn with this book. It has clear explanations, helpful diagrams, and engaging exercises. It also has beautiful pieces that make me feel like a professional guitarist. Thanks to Ahmet Kanneci Gitar Metodu Pdf 16, I have fulfilled my dream of playing classical guitar."

-- Murat, a classical guitar hobbyist from Izmir -
- -

Conclusion

- -

Ahmet Kanneci Gitar Metodu Pdf 16 is a comprehensive guide for classical guitar lovers who want to learn or improve their guitar skills. It covers various topics and skills related to classical guitar playing, such as technique, theory, repertoire, interpretation, performance, etc. It also includes a selection of classical guitar pieces from different periods and regions that you can play with pleasure and satisfaction.

- -

If you are interested in Ahmet Kanneci Gitar Metodu Pdf 16, you can download it for free from the link below. You can also visit the author's website or social media pages to learn more about him and his work.

- -

We hope this article has given you some useful information about Ahmet Kanneci Gitar Metodu Pdf 16. We wish you all the best in your classical guitar journey!

-

Conclusion

- -

Ahmet Kanneci Gitar Metodu Pdf 16 is a comprehensive guide for classical guitar lovers who want to learn or improve their guitar skills. It covers various topics and skills related to classical guitar playing, such as technique, theory, repertoire, interpretation, performance, etc. It also includes a selection of classical guitar pieces from different periods and regions that you can play with pleasure and satisfaction.

- -

If you are interested in Ahmet Kanneci Gitar Metodu Pdf 16, you can download it for free from the link below. You can also visit the author's website or social media pages to learn more about him and his work.

- -

We hope this article has given you some useful information about Ahmet Kanneci Gitar Metodu Pdf 16. We wish you all the best in your classical guitar journey!

3cee63e6c2
-
-
\ No newline at end of file diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/Cinema 4d R20 Crack ((NEW)).md b/spaces/1gistliPinn/ChatGPT4/Examples/Cinema 4d R20 Crack ((NEW)).md deleted file mode 100644 index 64d7499bd4eae7488d03648e87a6a6963cfbc695..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/Cinema 4d R20 Crack ((NEW)).md +++ /dev/null @@ -1,74 +0,0 @@ - -

Cinema 4d R20 Crack: A Powerful 3D Modeling and Animation Software

-

If you are a 3D motion graphics artist, you might be one of the thousands of designers who use Cinema 4D regularly. Cinema 4D is a popular software for matte painters in film production, mainly because of its features in BodyPaint 3D. It is also a specialized and widely used application for 3D animation, as it is user-friendly, highly customizable and suitable for many purposes. It has been used for movies such as We Are the Strange, Polar Express, Open Season, Monster House, Spiderman 3 and recently Avengers by Paramount.

-

Cinema 4D supports creating amazing graphics quickly and easily. In addition to containing all the features of CINEMA 4D Prime, Visualize and Broadcast, CINEMA 4D Studio also offers advanced tools for character, hair, a physics engine and unlimited clients. The result is that Cinema 4D can handle any project with ease.

-

Cinema 4d R20 Crack


Download File ––– https://imgfil.com/2uxYMJ



-

What's New in Cinema 4d R20 Crack?

-

Cinema 4d R20 Crack is the latest version of this software, which brings many improvements and new features. Some of them are:

- -

How to Download and Install Cinema 4d R20 Crack?

-

If you want to try this software for free, you can download Cinema 4d R20 Crack from the internet. However, you should be careful about the source of the download, as some websites may contain viruses or malware that can harm your computer. Here are some steps to download and install Cinema 4d R20 Crack safely:

-

-
    -
  1. Turn off your internet and antivirus connection.
  2. -
  3. Download Cinema 4d R20 Crack from a trusted website.
  4. -
  5. Extract the file that you downloaded using WinRAR or other software.
  6. -
  7. Install Cinema 4d R20 with installer use this key 14000000000-0000-0000-0000-0000-0000-0000.
  8. -
  9. When it is done put this file c4dp_20.0.26.xdl64 on C:\Program Files\MAXON\Cinema 4D R20\corelibs\.
  10. -
  11. Start Cinema 4d R20 and enjoy.
  12. -
-

Conclusion

-

Cinema 4d R20 Crack is a powerful software for 3D modeling and animation that can help you create stunning graphics and animations. It has many features and tools that make it easy and fast to use. You can download Cinema 4d R20 Crack from the internet for free, but you should be careful about the source and follow the instructions to install it properly. If you like this software, you should consider buying the original version from the official website to support the developers and get more benefits.

-

Why Choose Cinema 4d R20 Crack?

-

Cinema 4d R20 Crack is a great choice for anyone who wants to create stunning 3D graphics and animations without spending a lot of money. With Cinema 4d R20 Crack, you can access all the features and tools of the original software, such as:

- -

Cinema 4d R20 Crack also has a user-friendly interface that can be customized according to your preferences. You can also use plugins and scripts to extend the functionality of Cinema 4d R20 Crack. Cinema 4d R20 Crack is compatible with Windows and Mac operating systems, and supports 64-bit technology for optimal performance.

-

How to Use Cinema 4d R20 Crack?

-

Cinema 4d R20 Crack is easy to use, even for beginners. You can start by creating a new project and choosing a preset or template that suits your needs. You can then use the various tools and menus to create and edit your 3D models, materials, lights, cameras, animations and more. You can also import and export files from other formats, such as OBJ, FBX, STL, DWG, etc.

-

Cinema 4d R20 Crack has a powerful rendering engine that allows you to preview your work in real-time or render it in high quality. You can also adjust the render settings to optimize your output for different purposes, such as web, print, video, etc. You can also use the network rendering feature to distribute your render tasks across multiple computers.

-

Cinema 4d R20 Crack also has a built-in help system that provides you with tutorials, tips and documentation. You can also access online resources, such as forums, blogs, videos and courses, to learn more about Cinema 4d R20 Crack and improve your skills.

-

Cinema 4d R20 Crack: A Reliable Software for 3D Rendering

-

Cinema 4d R20 Crack is a reliable software for 3D rendering that can help you create high-quality images and videos for your projects. Cinema 4D has a flexible and scalable rendering system that can adapt to your needs and preferences. You can choose between different render engines, such as Standard, Physical, ProRender, Hardware OpenGL and Sketch & Toon. You can also use various render settings, such as resolution, anti-aliasing, depth of field, motion blur, global illumination, ambient occlusion, caustics, subsurface scattering and more.

-

Cinema 4d R20 Crack also has a powerful network rendering feature that allows you to distribute your render tasks across multiple computers. You can use unlimited network rendering clients to speed up your workflow and save time. You can also use Team Render Server to manage your render jobs and monitor their progress. Cinema 4D also supports rendering in the background and in the viewport.

-

Cinema 4d R20 Crack: A Creative Software for 3D Effects

-

Cinema 4d R20 Crack is a creative software for 3D effects that can help you add realism and style to your animations. Cinema 4D has a rich library of effects, shaders and shading options that you can use to enhance your renders. You can also use various tools and modifiers to create complex motion graphics and effects.

-

Cinema 4d R20 Crack also has a powerful MoGraph toolset that allows you to create procedural animations with ease. You can use clones, effectors, fields, deformers and more to control your objects and generate dynamic animations. You can also use Voronoi Fracture, Volume Builder and Volume Mesher to create realistic destruction and explosion effects.

-

Cinema 4d R20 Crack: A Flexible Software for 3D Sculpting

-

Cinema 4d R20 Crack is a flexible software for 3D sculpting that can help you create organic and hard-surface models with ease. Cinema 4D has a powerful sculpting system that allows you to use brushes, masks, stamps, stencils and layers to sculpt your 3D objects. You can also use various tools and modifiers to smooth, pinch, inflate, flatten, erase and refine your sculpts.

-

Cinema 4d R20 Crack also has a feature called Sculpt to PoseMorph that allows you to create facial expressions and character animations from your sculpts. You can also use the Sculpt Symmetry option to sculpt symmetrically on any axis. Cinema 4D also supports importing and exporting sculpts from other formats, such as ZBrush, Mudbox, etc.

-

Cinema 4d R20 Crack: A Fun Software for 3D Sketching

-

Cinema 4d R20 Crack is a fun software for 3D sketching that can help you create artistic and cartoon-like images and videos. Cinema 4D has a feature called Sketch & Toon that allows you to apply different styles and effects to your renders. You can also use various tools and modifiers to sketch, outline, hatch, shade, crosshatch and paint your 3D objects.

-

Cinema 4d R20 Crack also has a feature called Cel Shader that allows you to create cel-shaded animations with ease. You can also use the Art Shader to create realistic pencil sketches, watercolors, oil paintings and more. Cinema 4D also supports importing and exporting sketches from other formats, such as Illustrator, Photoshop, etc.

-

Cinema 4d R20 Crack: A User-Friendly Software for 3D Painting

-

Cinema 4d R20 Crack is a user-friendly software for 3D painting that can help you create realistic and detailed textures for your models. Cinema 4D has a feature called BodyPaint 3D that allows you to paint directly on your 3D objects. You can also use various tools and modifiers to clone, smear, blur, erase and color your paints.

-

Cinema 4d R20 Crack also has a feature called UV Editing that allows you to adjust the mapping of your textures on your models. You can also use various tools and modifiers to relax, optimize, pin, weld and split your UVs. Cinema 4D also supports importing and exporting paints from other formats, such as Photoshop, Illustrator, etc.

-

Cinema 4d R20 Crack: A Compatible Software for 3D Integration

-

Cinema 4d R20 Crack is a compatible software for 3D integration that can help you work seamlessly with other applications and formats. Cinema 4D has a feature called Exchange that allows you to import and export files from other formats, such as OBJ, FBX, STL, DWG, Alembic, etc. You can also use various tools and modifiers to adjust the scale, rotation, position and animation of your imported or exported files.

-

Cinema 4d R20 Crack also has a feature called Integration that allows you to connect and work with other popular video editing and compositing software, such as After Effects, Premiere Pro, Final Cut Pro, Nuke, etc. You can also use various tools and modifiers to sync the cameras, lights, materials and animations between Cinema 4D and other software.

-

Cinema 4d R20 Crack: A Secure Software for 3D Downloading

-

Cinema 4d R20 Crack is a secure software for 3D downloading that can help you get the full version of Cinema 4D for free. Cinema 4D is a premium software that requires a license key to activate and use. However, you can download Cinema 4d R20 Crack from the internet and bypass the activation process.

-

Cinema 4d R20 Crack is a safe and reliable software that does not contain any viruses or malware that can harm your computer. You can also use Cinema 4d R20 Crack without any limitations or restrictions. You can access all the features and tools of Cinema 4D and enjoy creating amazing 3D graphics and animations.

-

Cinema 4d R20 Crack: A Smart Software for 3D Learning

-

Cinema 4d R20 Crack is a smart software for 3D learning that can help you improve your skills and knowledge in 3D modeling and animation. Cinema 4D is a software that has a lot of tutorials, tips and documentation that you can use to learn more about it. You can also access online resources, such as forums, blogs, videos and courses, to get more guidance and support.

-

Cinema 4d R20 Crack also has a feature called Help System that provides you with interactive help and context-sensitive information. You can also use the Content Browser to browse and access hundreds of presets, templates and objects that you can use for your projects. Cinema 4D also supports creating your own custom objects and saving them for later use.

-

Cinema 4d R20 Crack: A Must-Have Software for 3D Enthusiasts

-

Cinema 4d R20 Crack is a must-have software for 3D enthusiasts who want to create stunning and realistic 3D graphics and animations. Cinema 4D is a software that offers many features and tools that make it easy and fast to use. You can also download Cinema 4d R20 Crack from the internet for free and enjoy all the benefits of the original software.

-

Cinema 4d R20 Crack is a software that can help you with various aspects of 3D creation, such as modeling, animation, rendering, sculpting, painting, sketching, integration and more. You can also use Cinema 4d R20 Crack to learn more about 3D and improve your skills and knowledge. Cinema 4D is a software that is compatible, flexible, reliable, creative, user-friendly and fun to use.

-

If you are interested in Cinema 4d R20 Crack, you can download it from the link below and follow the instructions to install it properly. However, if you like this software, you should consider buying the original version from the official website to support the developers and get more benefits. Cinema 4D is a software that is worth investing in if you are serious about 3D.

3cee63e6c2
-
-
\ No newline at end of file diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/Dream Aquarium Screensaver 1.52 Full Keygen HOT!.md b/spaces/1gistliPinn/ChatGPT4/Examples/Dream Aquarium Screensaver 1.52 Full Keygen HOT!.md deleted file mode 100644 index d18aec7bf35f4c4656677025133606352a20a42c..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/Dream Aquarium Screensaver 1.52 Full Keygen HOT!.md +++ /dev/null @@ -1,121 +0,0 @@ - -

Dream Aquarium Screensaver 1.52 Full Keygen: How to Get It and Why You Need It

- -

If you are looking for a stunning and realistic screensaver for your PC, you should definitely check out Dream Aquarium Screensaver 1.52 Full Keygen. This is a next-generation virtual aquarium that will mesmerize you with its amazing graphics, animations, and sounds. You can customize your own aquarium with dozens of different fish species, plants, backgrounds, and accessories. You can also interact with your fish, feed them, and watch them swim and behave in a natural way.

-

dream aquarium screensaver 1.52 full keygen


Download File ✓✓✓ https://imgfil.com/2uxYtN



- -

But how can you get Dream Aquarium Screensaver 1.52 Full Keygen for free? And why do you need a keygen to activate it? In this article, we will answer these questions and show you how to enjoy this awesome screensaver without paying a dime.

- -

What is Dream Aquarium Screensaver 1.52 Full Keygen?

- -

Dream Aquarium Screensaver 1.52 is the latest version of the popular screensaver that was released in November 2012. It has many new features and improvements, such as:

- - - -

However, Dream Aquarium Screensaver 1.52 is not free. You have to pay $19.95 to get the full version that allows you to access all the features and options. If you download the trial version from the official website, you will only get a limited number of fish and backgrounds, and you will see a nag screen every time you run the screensaver.

- -

That's why you need a keygen to activate Dream Aquarium Screensaver 1.52 Full Keygen. A keygen is a software that generates a serial number or a license key that you can use to register the screensaver and unlock all the features. By using a keygen, you can save money and enjoy Dream Aquarium Screensaver 1.52 Full Keygen for free.

- -

How to Get Dream Aquarium Screensaver 1.52 Full Keygen?

- -

There are many websites that offer Dream Aquarium Screensaver 1.52 Full Keygen for free download. However, not all of them are reliable and safe. Some of them may contain viruses, malware, or spyware that can harm your PC or steal your personal information. Some of them may also provide fake or invalid keygens that won't work or will cause errors.

-

- -

That's why we recommend you to download Dream Aquarium Screensaver 1.52 Full Keygen from our trusted link below. We have tested it and verified that it is clean and working. You can download it without any risk or hassle.

- -

Here are the steps to get Dream Aquarium Screensaver 1.52 Full Keygen:

- -
    -
  1. Click on the download button below and save the file to your PC.
  2. -
  3. Extract the file using WinRAR or any other archive tool.
  4. -
  5. Run the setup file and follow the instructions to install Dream Aquarium Screensaver 1.52 on your PC.
  6. -
  7. Run the keygen file and click on the generate button to get a serial number.
  8. -
  9. Copy the serial number and paste it into the registration window of Dream Aquarium Screensaver 1.52.
  10. -
  11. Click on the register button and enjoy Dream Aquarium Screensaver 1.52 Full Keygen for free.
  12. -
- -

Download Dream Aquarium Screensaver 1.52 Full Keygen Here

- -

Why You Need Dream Aquarium Screensaver 1.52 Full Keygen?

- -

Dream Aquarium Screensaver 1.52 Full Keygen is not just a screensaver. It is a relaxing and entertaining experience that will make you feel like you are in a real aquarium. You can watch your fish swim around in a beautiful environment that changes according to the time of day and season. You can also listen to soothing sounds of water and bubbles that will calm your mind and mood.

- -

Dream Aquarium Screensaver 1.52 Full Keygen is also a great way to decorate your PC and impress your friends and family. You can choose from hundreds of different combinations of fish, plants, backgrounds, and accessories to create your own unique aquarium. You can also take snapshots of your aquarium and share them online or use them as wallpapers.

- -

Dream Aquarium Screensaver 1.52 Full Keygen is also a fun and educational tool that will teach you about different fish species and their habits. You can learn about their names, origins, sizes, colors, diets, lifespans, and more by clicking on them or reading their descriptions in the menu. You can also watch how they interact with each other and their environment in a realistic way.

- -

Dream Aquarium Screensaver 1.52 Full Keygen is more than just a screensaver. It is a dream come true for anyone who loves aquariums and fish. By downloading it for free from our link below, you can enjoy this amazing screensaver without spending any money or compromising any quality.

- -

Download Dream Aquarium Screensaver 1.52 Full Keygen Here

-

What are the Benefits of Dream Aquarium Screensaver 1.52 Full Keygen?

- -

Dream Aquarium Screensaver 1.52 Full Keygen is not only a beautiful and realistic screensaver, but also a beneficial one. Here are some of the benefits that you can get from using this screensaver:

- - - -

Dream Aquarium Screensaver 1.52 Full Keygen is a screensaver that can benefit you in many ways. By downloading it for free from our link below, you can experience these benefits yourself.

- -

How to Customize Dream Aquarium Screensaver 1.52 Full Keygen?

- -

Dream Aquarium Screensaver 1.52 Full Keygen is a screensaver that you can customize according to your own taste and style. You can create your own aquarium with hundreds of different combinations of fish, plants, backgrounds, and accessories. You can also change the options and settings to make your aquarium more realistic and attractive.

- -

Here are some of the ways that you can customize Dream Aquarium Screensaver 1.52 Full Keygen:

- - - -

Dream Aquarium Screensaver 1.52 Full Keygen is a screensaver that you can customize to make it your own. By downloading it for free from our link below, you can start customizing your aquarium today.

-

How to Interact with Dream Aquarium Screensaver 1.52 Full Keygen?

- -

Dream Aquarium Screensaver 1.52 Full Keygen is not just a passive screensaver. It is an interactive one that allows you to have fun and play with your fish and aquarium. You can do many things with Dream Aquarium Screensaver 1.52 Full Keygen, such as:

- - - -

Dream Aquarium Screensaver 1.52 Full Keygen is a screensaver that you can interact with and have fun with. By downloading it for free from our link below, you can start interacting with your aquarium today.

- -

How to Update Dream Aquarium Screensaver 1.52 Full Keygen?

- -

Dream Aquarium Screensaver 1.52 Full Keygen is a screensaver that is constantly updated and improved by its developers. They are always adding new fish species, plants, backgrounds, and features to make the screensaver more realistic and enjoyable. You can get these updates for free by using the update option in the menu bar.

- -

Here are some of the benefits of updating Dream Aquarium Screensaver 1.52 Full Keygen:

- - - -

Dream Aquarium Screensaver 1.52 Full Keygen is a screensaver that is always updated and improved to give you the best experience possible. By downloading it for free from our link below, you can get these updates automatically and enjoy the latest features of this screensaver.

-

Conclusion

- -

Dream Aquarium Screensaver 1.52 Full Keygen is a screensaver that will transform your PC into a beautiful and realistic virtual aquarium. You can customize your own aquarium with hundreds of different combinations of fish, plants, backgrounds, and accessories. You can also interact with your fish, feed them, touch them, and watch them swim and behave in a natural way. You can also enjoy the stunning graphics and animations of the screensaver, which are based on real fish behavior and physics. You can also learn new facts and information about different fish species and their habitats.

- -

Dream Aquarium Screensaver 1.52 Full Keygen is not free. You have to pay $19.95 to get the full version that allows you to access all the features and options. However, you can get it for free by using a keygen that will generate a serial number or a license key that you can use to register the screensaver and unlock all the features. You can download Dream Aquarium Screensaver 1.52 Full Keygen and the keygen from our trusted link below.

- -

Dream Aquarium Screensaver 1.52 Full Keygen is a screensaver that will give you a relaxing and entertaining experience that will make you feel like you are in a real aquarium. It is also a beneficial screensaver that will reduce your stress and anxiety, improve your productivity and creativity, enhance your PC's performance and security, and teach you about different fish species and their habits. It is also a screensaver that is constantly updated and improved by its developers to give you the best experience possible.

- -

If you love aquariums and fish, you should definitely download Dream Aquarium Screensaver 1.52 Full Keygen today and enjoy this amazing screensaver without paying a dime.

- -

Download Dream Aquarium Screensaver 1.52 Full Keygen Here

3cee63e6c2
-
-
\ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Candy Crush Saga A Fun and Addictive Puzzle Game for Windows 7 PC.md b/spaces/1phancelerku/anime-remove-background/Candy Crush Saga A Fun and Addictive Puzzle Game for Windows 7 PC.md deleted file mode 100644 index 05c9a082ae4b0ce32ea02ec5adfa4cbc78e541df..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Candy Crush Saga A Fun and Addictive Puzzle Game for Windows 7 PC.md +++ /dev/null @@ -1,120 +0,0 @@ - -

How to Download Candy Crush Saga on PC Windows 7

-

Candy Crush Saga is one of the most popular and addictive puzzle games in the world. Millions of players love to switch and match candies in this sweet adventure. But did you know that you can also play Candy Crush Saga on your PC Windows 7? In this article, we will show you how to download and play Candy Crush Saga on PC Windows 7 using two different methods. We will also share some tips and tricks to help you enjoy the game even more.

-

Introduction

-

What is Candy Crush Saga?

-

Candy Crush Saga is a puzzle game developed by King. It was released in 2012 and has since become a global phenomenon. The game is simple but challenging. You have to match three or more candies of the same color to clear them from the board. You also have to complete various objectives, such as collecting ingredients, clearing jelly, or reaching a target score. The game has thousands of levels, each with different layouts, obstacles, and goals. You can also play with your friends and compete for the highest score.

-

download candy crush saga pc windows 7


Download ☆☆☆ https://jinyurl.com/2uNNUX



-

Why play Candy Crush Saga on PC Windows 7?

-

Playing Candy Crush Saga on your mobile device is fun, but playing it on your PC Windows 7 has some advantages. For example:

- -

How to download Candy Crush Saga on PC Windows 7

-

Method 1: Using Microsoft Store

-

One of the easiest ways to download Candy Crush Saga on PC Windows 7 is to use the Microsoft Store app. This app allows you to download and install various games and apps from Microsoft. Here are the steps to follow:

-

Step 1: Open Microsoft Store app

-

To open the Microsoft Store app, you can either click on its icon on your taskbar or start menu, or type "Microsoft Store" in the search box and press enter.

-

Step 2: Search for Candy Crush Saga

-

Once you open the Microsoft Store app, you will see a search bar at the top right corner. Type "Candy Crush Saga" in the search bar and press enter. You will see a list of results related to your query.

-

Step 3: Click on Get or Install button

-

From the list of results, find the one that says "Candy Crush Saga" and has the logo of the game. Click on it to open its page. You will see a button that says "Get" or "Install" depending on whether you have already downloaded the game before or not. Click on that button to start the download process.

-

Step 4: Launch the game and enjoy

-

After the download is complete, you will see a button that says "Launch" or "Play" on the same page. Click on that button to open the game. You can also find the game icon on your start menu or desktop. Now you can enjoy playing Candy Crush Saga on your PC Windows 7.

-

Method 2: Using BlueStacks emulator

-

Another way to download Candy Crush Saga on PC Windows 7 is to use an emulator. An emulator is a software that allows you to run Android apps and games on your PC. One of the most popular and reliable emulators is BlueStacks. Here are the steps to follow:

-

Step 1: Download and install BlueStacks on your PC

-

To download BlueStacks, you can visit its official website at [bluestacks.com] and click on the "Download BlueStacks" button. You will get an installer file that you need to run on your PC. Follow the instructions on the screen to complete the installation process.

-

How to download candy crush saga on pc windows 7
-Candy crush saga for pc windows 7 free download
-Download candy crush saga for windows 7 laptop
-Candy crush saga download for pc windows 7 offline
-Candy crush saga game download for pc windows 7 32 bit
-Candy crush saga pc windows 7 download full version
-Download candy crush saga for windows 7 without bluestacks
-Candy crush saga download for pc windows 7 softonic
-Download candy crush saga for windows 7 ultimate
-Candy crush saga game free download for pc windows 7 filehippo
-Download candy crush saga for pc windows 7 professional
-Candy crush saga download for windows 7 microsoft store
-Download candy crush saga for pc windows 7 online
-Candy crush saga game download for pc windows 7 64 bit
-Candy crush saga pc windows 7 download apk
-Download candy crush saga for windows 7 using bluestacks
-Candy crush saga download for pc windows 7 uptodown
-Download candy crush saga for windows 7 home premium
-Candy crush saga game download for pc windows 7 with keyboard
-Candy crush saga pc windows 7 download crack
-Download candy crush saga for windows 7 emulator
-Candy crush saga download for pc windows 7 nox player
-Download candy crush saga for windows 7 enterprise
-Candy crush saga game download for pc windows 7 latest version
-Candy crush saga pc windows 7 download mod
-Download candy crush saga for windows 7 from king.com
-Candy crush saga download for pc windows 7 memu play
-Download candy crush saga for windows 7 starter
-Candy crush saga game download for pc windows 7 old version
-Candy crush saga pc windows 7 download hack
-Download candy crush saga for windows 7 by king
-Candy crush saga download for pc windows 7 ldplayer
-Download candy crush saga for windows 7 basic
-Candy crush saga game download for pc windows 7 update
-Candy crush saga pc windows 7 download cheats
-Download candy crush saga for windows 7 from microsoft.com
-Candy crush saga download for pc windows 7 gameloop
-Download candy crush saga for windows 7 pro
-Candy crush saga game download for pc windows 7 install
-Candy crush saga pc windows 7 download patch
-Download candy crush saga for windows 7 original
-Candy crush saga download for pc windows 7 koplayer
-Download candy crush saga for windows 7 iso file
-Candy crush saga game download for pc windows 7 play store
-Candy crush saga pc windows 7 download keygen
-Download candy crush saga for windows 7 from google play store

-

Step 2: Launch BlueStacks and sign in with Google account

-

After installing BlueStacks, you need to launch it and sign in with your Google account. This will allow you to access the Google Play Store and download apps and games. If you don't have a Google account, you can create one for free.

-

Step 3: Search for Candy Crush Saga in the Play Store

-

Once you sign in with your Google account, you will see the Play Store icon on the home screen of BlueStacks. Click on it to open the Play Store app. Then, type "Candy Crush Saga" in the search bar and press enter. You will see a list of results related to your query.

-

Step 4: Click on Install button and wait for the game to download

-

From the list of results, find the one that says "Candy Crush Saga" and has the logo of the game. Click on it to open its page. You will see a button that says "Install". Click on that button to start the download process.

-

Step 5: Open the game and start playing

-

After the download is complete, you will see a button that says "Open" on the same page. Click on that button to launch the game. You can also find the game icon on the home screen of BlueStacks. Now you can enjoy playing Candy Crush Saga on your PC Windows 7.

-

Tips and tricks to play Candy Crush Saga on PC Windows 7

-

Candy Crush Saga is a fun and addictive game, but it can also be challenging and frustrating at times. To help you overcome the difficulties and have more fun, here are some tips and tricks to play Candy Crush Saga on PC Windows 7:

-

Use boosters wisely

-

Boosters are special items that can help you clear levels faster and easier. You can get boosters by completing quests, watching ads, or buying them with real money. However, boosters are limited and should be used wisely. Don't waste them on easy levels or when you are close to winning. Save them for hard levels or when you are stuck.

-

Plan your moves ahead

-

Candy Crush Saga is a game of strategy, not luck. You have a limited number of moves to complete each level, so you need to plan your moves ahead. Don't just match candies randomly, but look for patterns and opportunities to create special candies or clear obstacles. Try to think one or two steps ahead and anticipate the consequences of your moves.

-

Match special candies for more effects

-

Special candies are candies that have extra effects when matched with other candies. They are created by matching four or more candies of the same color in different shapes. For example, matching four candies in a row creates a striped candy, which clears a whole row or column when matched. Matching five candies in a row creates a color bomb, which clears all candies of one color when matched. Matching five candies in an L or T shape creates a wrapped candy, which explodes twice when matched. Matching two special candies together creates even more powerful effects, such as clearing multiple rows and columns, or clearing all candies of two colors.

-

Check the daily rewards and challenges

-

Candy Crush Saga offers various rewards and challenges for its players every day. You can get free boosters by spinning the daily booster wheel, or by completing the daily quests. You can also participate in the daily challenges, such as the sugar track, the candy order, or the episode race. These challenges can give you extra rewards, such as gold bars, lives, or boosters. To access the daily rewards and challenges, you can click on the icons on the left side of the game screen.

-

Conclusion

-

Candy Crush Saga is a fun and addictive puzzle game that you can play on your PC Windows 7. You can download and install the game using either the Microsoft Store app or the BlueStacks emulator. You can also use some tips and tricks to play the game better, such as using boosters wisely, planning your moves ahead, matching special candies for more effects, and checking the daily rewards and challenges. We hope this article has helped you learn how to download Candy Crush Saga on PC Windows 7 and enjoy the game more. Happy crushing!

-

FAQs

-

Here are some frequently asked questions about Candy Crush Saga on PC Windows 7:

-

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Download Brawlhalla APK OBB and Experience the Thrill of Brawling.md b/spaces/1phancelerku/anime-remove-background/Download Brawlhalla APK OBB and Experience the Thrill of Brawling.md deleted file mode 100644 index 0abb57577ae248ec26d9ccf85de0ac2a64bfc302..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Download Brawlhalla APK OBB and Experience the Thrill of Brawling.md +++ /dev/null @@ -1,75 +0,0 @@ -
-

Brawlhalla Mod Apk + Obb: Everything You Need to Know

-

Brawlhalla is a free-to-play platform fighting game that supports cross-play across various devices, including PC, consoles, and mobile. It features over 50 unique characters, each with their own weapons and skills, and various game modes that cater to different play styles and preferences. Brawlhalla has been praised for its accessibility, diversity, and frequent updates that keep the game fresh and exciting.

-

However, some players may want to enhance their gaming experience by using mod apk and obb files. These are modified versions of the original game files that can unlock premium content, provide unlimited resources, or add new features to the game. In this article, we will explain how to download and install brawlhalla mod apk + obb on your Android device, as well as the benefits and risks of using them.

-

brawlhalla mod apk + obb


Download Filehttps://jinyurl.com/2uNQ3w



-

How to Download and Install Brawlhalla Mod Apk + Obb on Android Devices

-

If you want to try out brawlhalla mod apk + obb on your Android device, you will need to follow these steps:

-

Step 1: Enable unknown sources on your device

-

Since brawlhalla mod apk + obb are not available on the official Google Play Store, you will need to enable unknown sources on your device to allow the installation of third-party apps. To do this, go to Settings > Security > Unknown Sources and toggle it on.

-

Step 2: Download the mod apk and obb files from a trusted source

-

Next, you will need to download the mod apk and obb files from a trusted source. There are many websites that offer brawlhalla mod apk + obb files, but not all of them are safe and reliable. You should always check the reviews, ratings, and comments of other users before downloading any file. Some of the best sources for brawlhalla mod apk + obb files are , , and . You can also use a VPN service or an antivirus app to protect your device from malware.

-

Step 3: Install the mod apk file and copy the obb file to the Android/obb folder

-

After downloading the mod apk and obb files, you will need to install the mod apk file by tapping on it and following the instructions. Then, you will need to copy the obb file to the Android/obb folder on your device's internal storage. If you don't have an obb folder, you can create one manually.

-

Step 4: Launch the game and enjoy the mod features

-

Finally, you can launch the game from your app drawer or home screen and enjoy the mod features. Depending on the mod apk and obb files you downloaded, you may have access to unlimited money, unlocked characters, enhanced gameplay features, and more. You can check the mod description or the settings menu to see what features are available.

-

What are the Benefits and Risks of Using Brawlhalla Mod Apk + Obb

-

Using brawlhalla mod apk + obb can have both benefits and risks for your gaming experience. Here are some of them:

-

brawlhalla mod apk + obb latest version download
-brawlhalla mod apk + obb unlimited money and coins
-brawlhalla mod apk + obb offline mode
-brawlhalla mod apk + obb all characters unlocked
-brawlhalla mod apk + obb no root required
-brawlhalla mod apk + obb free skins and weapons
-brawlhalla mod apk + obb cross-play support
-brawlhalla mod apk + obb hack cheats
-brawlhalla mod apk + obb android 11 compatible
-brawlhalla mod apk + obb direct link
-brawlhalla mod apk + obb high graphics quality
-brawlhalla mod apk + obb easy installation guide
-brawlhalla mod apk + obb fast and secure download
-brawlhalla mod apk + obb updated features and bug fixes
-brawlhalla mod apk + obb online multiplayer mode
-brawlhalla mod apk + obb best action fighting game
-brawlhalla mod apk + obb epic battles and tournaments
-brawlhalla mod apk + obb custom game modes and maps
-brawlhalla mod apk + obb fun and addictive gameplay
-brawlhalla mod apk + obb low storage space required
-brawlhalla mod apk + obb smooth and responsive controls
-brawlhalla mod apk + obb awesome sound effects and music
-brawlhalla mod apk + obb legendary heroes and villains
-brawlhalla mod apk + obb weekly events and rewards
-brawlhalla mod apk + obb global leaderboards and rankings
-brawlhalla mod apk + obb friendly and active community
-brawlhalla mod apk + obb regular updates and improvements
-brawlhalla mod apk + obb no ads or in-app purchases
-brawlhalla mod apk + obb full version unlocked
-brawlhalla mod apk + obb 100% working and tested

-

Benefits

- -

Risks

- -

Conclusion

-

Brawlhalla is a fun and addictive platform fighting game that you can play for free on various devices. However, if you want to spice up your gaming experience, you can try using brawlhalla mod apk + obb files that can unlock premium content, provide unlimited resources, or add new features to the game. However, you should also be aware of the risks involved in using brawlhalla mod apk + obb files, such as malware infection, account ban, or game instability. You should always download from trusted sources, scan the files before installing them, use a secondary or guest account, backup your original game files and data, and update your mod apk and obb files regularly.

-

We hope this article has helped you understand everything you need to know about brawlhalla mod apk + obb files. If you have any questions or comments, feel free to leave them below. And if you enjoyed this article, don't forget to share it with your friends and fellow gamers. Happy brawling!

-

FAQs

-

What are some of the best brawlhalla mod apk + obb sources?

-

Some of the best sources for brawlhalla mod apk + obb files are , , and . These websites offer safe and reliable downloads of various brawlhalla mod apk + obb files that can suit your preferences and needs.

-

How can I update brawlhalla mod apk + obb to the latest version?

-

To update brawlhalla mod apk + obb to the latest version, you will need to download the latest version of the mod apk and obb files from the same source you downloaded them from before. Then, you will need to uninstall the previous version of the mod apk file and install the new one. You will also need to replace the old obb file with the new one in the Android/obb folder. Alternatively, you can use an app like that can automatically update your mod apk and obb files for you.

-

Can I play brawlhalla mod apk + obb online with other players?

-

Yes, you can play brawlhalla mod apk + obb online with other players who are using the same version of the mod apk and obb files as you. However, you may not be able to play with players who are using the original game files or different versions of the mod apk and obb files. You may also face the risk of getting banned or suspended by the game developers if they detect that you are using mod apk and obb files.

-

Is brawlhalla mod apk + obb compatible with iOS devices?

-

No, brawlhalla mod apk + obb files are not compatible with iOS devices. Apk and obb files are only designed for Android devices and cannot be installed or run on iOS devices. If you want to play brawlhalla on your iOS device, you will need to download the official game from the App Store.

-

Is brawlhalla mod apk + obb legal and safe?

-

Brawlhalla mod apk + obb files are not legal and safe in most cases. Mod apk and obb files are considered as a form of piracy and hacking, which can violate the intellectual property rights of the game developers and publishers. Using mod apk and obb files can also expose your device to malware, viruses, or spyware, which can damage your device or compromise your privacy. Moreover, using mod apk and obb files can result in your account being banned or suspended by the game developers if they detect any abnormal activity or behavior. Therefore, we do not recommend using brawlhalla mod apk + obb files unless you are fully aware of the consequences and risks involved.

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Download Program AI The Essential Tool for Automating and Streamlining Your Business Processes.md b/spaces/1phancelerku/anime-remove-background/Download Program AI The Essential Tool for Automating and Streamlining Your Business Processes.md deleted file mode 100644 index e2711f455af42035cd2e99f1b22999e96ee55d52..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Download Program AI The Essential Tool for Automating and Streamlining Your Business Processes.md +++ /dev/null @@ -1,113 +0,0 @@ - -

How to Download Program AI for Free

-

Program AI is a term that refers to artificial intelligence software or tools that can create, edit, or produce various types of content, such as vector graphics, sketches, drawings, and artwork. Program AI can help you with various tasks and projects, such as logo design, icon creation, text styling, and more. In this article, you will learn what program AI is, what are its benefits and types, how to choose the right program AI for your needs, how to download program AI for free, how to use it effectively, what are its challenges and limitations, and what are the future trends and developments in program AI.

-

What is Program AI?

-

Program AI is a subset of artificial intelligence that focuses on creating or manipulating content using algorithms and data. Program AI can generate content from scratch or enhance existing content with various features and effects. Program AI can also learn from feedback and improve its performance over time. Some examples of program AI are:

-

download program ai


Download Ziphttps://jinyurl.com/2uNNJP



- -

Benefits of Program AI

-

Program AI can offer many benefits for users who want to create or edit content. Some of the benefits are:

- -

Types of Program AI

-

Program AI can be classified into different types based on the type of content they create or edit. Some of the types are:

- -

How to Choose the Right Program AI for Your Needs

-

Choosing the right program AI for your needs can be challenging, as there are many factors to consider. Some of the factors are:

- -

How to Download Program AI for Free

-

If you want to download program AI for free, you have several options. One option is to get a free trial of a program AI that offers a limited time or functionality for testing purposes. Another option is to use a tool that helps you download various software for free, such as WizCase. Here are some examples of how to download program AI for free:

-

Adobe Illustrator

-

Adobe Illustrator is one of the most popular vector-based program AI that allows you to create logos, icons, drawings, typography, and illustrations. You can download Adobe Illustrator for free by following these steps:

-
    -
  1. Go to the Adobe Illustrator website and click on "Free Trial".
  2. -
  3. Sign in with your Adobe ID or create one if you don't have one.
  4. -
  5. Select your plan and payment method. You won't be charged until the end of the trial period.
  6. -
  7. Download and install the Adobe Creative Cloud app on your device.
  8. -
  9. Launch the app and sign in with your Adobe ID.
  10. -
  11. Select Illustrator from the list of apps and click on "Install".
  12. -
  13. Wait for the installation to complete and then launch Illustrator from the app or your desktop.
  14. -
-

WizCase

-

WizCase is a tool that helps you download various software for free, such as Illustrator, Photoshop, InDesign, such as vector graphics, sketches, drawings, and artwork. However, program AI also has some challenges and limitations, such as accuracy, ethics, creativity, and dependency. Therefore, you should use program AI wisely and responsibly, and always keep learning and improving your own skills and abilities. If you want to download program AI for free, you can try a free trial of a program AI software, such as Adobe Illustrator, or use a tool that helps you download various software for free, such as WizCase. You can also use program AI effectively by following some tips and best practices, such as knowing your purpose, exploring the features, experimenting with different settings, providing feedback, and using your creativity. Program AI is constantly evolving and improving, and you can expect to see more types, categories, integration, collaboration, personalization, customization, intelligence, and autonomy of program AI in the future.

-

FAQs

-

Here are some frequently asked questions about program AI and their answers:

-

-

download program ai free trial
-download program ai for windows
-download program ai for mac
-download program ai online
-download program ai full version
-download program ai crack
-download program ai serial key
-download program ai portable
-download program ai tutorial
-download program ai software
-download program ai app
-download program ai design
-download program ai vector
-download program ai logo
-download program ai icon
-download program ai sketch
-download program ai drawing
-download program ai illustration
-download program ai art
-download program ai graphics
-download program ai tools
-download program ai brushes
-download program ai effects
-download program ai filters
-download program ai layers
-download program ai color
-download program ai gradient
-download program ai text
-download program ai font
-download program ai typography
-download program ai style
-download program ai template
-download program ai project
-download program adobe illustrator
-download adobe illustrator free trial
-download adobe illustrator for windows
-download adobe illustrator for mac
-download adobe illustrator online
-download adobe illustrator full version
-download adobe illustrator crack
-download adobe illustrator serial key
-download adobe illustrator portable
-download adobe illustrator tutorial
-download adobe illustrator software
-download adobe illustrator app
-download adobe illustrator design
-download adobe illustrator vector
-download adobe illustrator logo
-download adobe illustrator icon

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Enjoy Pokmon GO with Mod Menu Download APK v0.273.1 and Explore New Options.md b/spaces/1phancelerku/anime-remove-background/Enjoy Pokmon GO with Mod Menu Download APK v0.273.1 and Explore New Options.md deleted file mode 100644 index d51aee9ee27bb579254348538cc11fb613357343..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Enjoy Pokmon GO with Mod Menu Download APK v0.273.1 and Explore New Options.md +++ /dev/null @@ -1,130 +0,0 @@ -
-

Download Pokemon Go Mod Menu: A Guide for Beginners

-

Pokemon Go is one of the most popular mobile games in the world, with millions of players catching, battling, and trading Pokemon in real-world locations. The game uses augmented reality technology to overlay virtual creatures on your smartphone screen as you explore your surroundings. Pokemon Go is fun, addictive, and rewarding, but it can also be challenging, frustrating, and time-consuming.

-

That's why some players use a mod menu to enhance their gameplay experience. A mod menu is a tool that allows you to access various cheats and hacks in the game, such as joystick, teleport, speed, radar, and more. With a mod menu, you can catch more Pokemon, level up faster, win more battles, and enjoy the game in new ways.

-

download pokemon go mod menu


Download >>>>> https://jinyurl.com/2uNRTm



-

However, using a mod menu is not without risks. You could get banned or detected by the game developers, lose your account or data, or face legal consequences. You also need to be careful about where you download the mod menu from, as some sources may contain viruses or malware that could harm your device.

-

In this article, we will show you how to download Pokemon Go mod menu safely and legally, what features it offers, how to use it effectively, and what are the risks and benefits of playing with it. By the end of this article, you will be able to decide whether you want to try out the mod menu or stick to the regular gameplay.

-

Features of Pokemon Go Mod Menu

-

A mod menu is a software that modifies the game code to enable certain cheats and hacks. There are many different mod menus available for Pokemon Go, but they usually have some common features. Here are some of the most popular ones:

- -

Each feature has its own advantages and disadvantages. For example, using joystick or teleport can help you catch more Pokemon in less time, but it can also make the game less realistic and immersive. Using speed can help you hatch eggs faster, but it can also drain your battery quicker. Using radar can help you find rare or specific Pokemon easier but it can also spoil the surprise and challenge of discovering them yourself.

-

Tips and Tricks for Using Pokemon Go Mod Menu

-

If you decide to use a mod menu for Pokemon Go, you need to be careful and smart about how you use it. Here are some tips and tricks to help you avoid getting banned or detected, optimize your gameplay, and have more fun with the mod menu:

- -

Risks and Benefits of Playing Pokemon Go with Mod Menu

-

Playing Pokemon Go with mod menu can have both positive and negative effects on your health, social life, and ethics. Here are some of the risks and benefits of using mod menu for Pokemon Go:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
RisksBenefits
- You could get banned or suspended from the game, losing your account, data, and progress.- You could catch more Pokemon, level up faster, win more battles, and complete more tasks.
- You could get infected by viruses or malware from downloading unsafe or unverified mod menus.- You could access more features and options that are not available in the regular gameplay.
- You could damage your device or battery by running too many apps or processes at once.- You could save time and energy by playing from anywhere without moving.
- You could harm your physical or mental health by playing too much or too intensely.- You could improve your mood or relieve stress by playing for fun or relaxation.
- You could lose interest or satisfaction in the game by making it too easy or boring.- You could discover new places or experiences by exploring different locations or modes.
- You could ruin the gameplay experience for other players by cheating or hacking.- You could make new friends or join communities by interacting with other players.
- You could break the law or ethics by violating the terms of service or intellectual property rights.- You could express your creativity or personality by customizing your gameplay style.
-

Conclusion

-

Pokemon Go is a great game that can bring you joy, adventure, and connection. However, it can also be challenging, frustrating, and time-consuming. That's why some players use a mod menu to enhance their gameplay experience. A mod menu is a tool that allows you to access various cheats and hacks in the game, such as joystick, teleport, speed, radar, and more. With a mod menu, you can catch more Pokemon, level up faster, win more battles, and enjoy the game in new ways.

-

However, using a mod menu is not without risks. You could get banned or detected by the game developers, lose your account or data, or face legal consequences. You also need to be careful about where you download the mod menu from, as some sources may contain viruses or malware that could harm your device. You also need to be responsible and respectful when using the mod menu, as you could affect your own or other players' gameplay experience.

-

download pokemod for pokemon go
-how to get pokemod atlas features for pokemon go
-pokemod performance mode for pokemon go
-pokemod shiny scanner for pokemon go
-pokemod spawn booster for pokemon go
-pokemod vpgp2+ for pokemon go
-pokemod quest tweaks for pokemon go
-pokemod swift gift for pokemon go
-pokemod tap to teleport for pokemon go
-pokemod instant catch for pokemon go
-pokemod inventory tweaks for pokemon go
-pokemod incognito mode for pokemon go
-pokemod headshot for pokemon go
-pokemod skip encounter intro for pokemon go
-pokemod team rocket blastoff 2 reloaded for pokemon go
-pokemod replace names with ivs in encounters for pokemon go
-pokemod tamagotchi for pokemon go
-pokemod block non-shiny encounters for pokemon go
-pokemod show encounter iv for pokemon go
-pokemod team leader zero hit ko for pokemon go
-pokemod instant spin for pokemon go
-pokemod pinap master for pokemon go
-pokemod shows ivs in inventory for pokemon go
-pokemod transfer on catch for pokemon go
-pokemod raid pack for pokemon go
-download no modded pokemon go with pokemod features
-how to install pokemod on android devices
-how to attach pokemod to pokemon go app
-how to use pokemod toggles in pokemon go game
-how to update pokemod for latest version of pokemon go
-download free trial of pokemod pro features for pokemon go
-how to buy pokemod pro subscription for pokemon go
-how to cancel pokemod pro subscription for pokemon go
-how to contact pokemod support team for pokemon go issues
-how to join pokemod discord community for pokemon go tips and tricks
-download best settings for pokemod in pokemon go game play
-how to avoid bans and warnings using pokemod in pokemon go game play
-how to spoof location using gps joystick and pokemod in pokemon go game play
-how to catch rare and shiny pokemon using pokemod in pokemon go game play
-how to complete quests and challenges using pokemod in pokemon go game play
-how to win battles and raids using pokemod in pokemon go game play
-how to level up and earn xp using pokemod in pokemon go game play
-how to manage inventory and items using pokemod in pokemon go game play
-how to interact with buddy and friends using pokemod in pokemon go game play
-download reviews and testimonials of pokemod users in pokemon go game play
-download comparison of pokemod and other mod menus in pokemon go game play
-download pros and cons of using pokemod in pokemon go game play

-

In this article, we showed you how to download Pokemon Go mod menu safely and legally, what features it offers, how to use it effectively, and what are the risks and benefits of playing with it. We hope that this article helped you make an informed decision about whether you want to try out the mod menu or stick to the regular gameplay.

-

If you want to download Pokemon Go mod menu, you can follow the link below and follow the instructions. However, we advise you to use it at your own risk and discretion, and to follow the tips and tricks we provided to avoid getting banned or detected. We also recommend you to use the mod menu moderately and responsibly, and to enjoy the game as it was intended to be played.

-

Are you ready to download Pokemon Go mod menu and catch 'em all? Click here to get started!

-

FAQs

-

Here are some of the most frequently asked questions about Pokemon Go mod menu:

-
    -
  1. What is Pokemon Go mod menu?
  2. -

    Pokemon Go mod menu is a tool that allows you to access various cheats and hacks in the game, such as joystick, teleport, speed, radar, and more.

    -
  3. How do I download Pokemon Go mod menu?
  4. -

    You can download Pokemon Go mod menu from a reliable and verified source that provides a safe and legal download link. You can follow the link below and follow the instructions.

    -
  5. Is Pokemon Go mod menu safe and legal?
  6. -

    Pokemon Go mod menu is not officially endorsed or supported by the game developers or publishers. Using it may violate the terms of service or intellectual property rights of the game. It may also expose your device or account to viruses or malware. Therefore, using Pokemon Go mod menu is not safe or legal, and you do it at your own risk and discretion.

    -
  7. How do I use Pokemon Go mod menu?
  8. -

    You can use Pokemon Go mod menu by launching it on your device and selecting the features you want to activate. You can also adjust the settings and options according to your preferences. However, you need to be careful and smart about how you use it, as you could get banned or detected by the game developers. You also need to be responsible and respectful when using it, as you could affect your own or other players' gameplay experience.

    -
  9. What are the risks and benefits of playing Pokemon Go with mod menu?
  10. -

    Playing Pokemon Go with mod menu can have both positive and negative effects on your health, social life, and ethics. Some of the risks are getting banned or suspended from the game, losing your account or data, getting infected by viruses or malware, damaging your device or battery, harming your physical or mental health, losing interest or satisfaction in the game, ruining the gameplay experience for other players, breaking the law or ethics. Some of the benefits are catching more Pokemon, leveling up faster, winning more battles, completing more tasks, accessing more features and options, saving time and energy, improving your mood or relieving stress, discovering new places or experiences, making new friends or joining communities, expressing your creativity or personality.

    -

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Enjoy Tsukis Odyssey MOD APK with No Ads and More Carrots.md b/spaces/1phancelerku/anime-remove-background/Enjoy Tsukis Odyssey MOD APK with No Ads and More Carrots.md deleted file mode 100644 index 2afe7fb1b7f8bbded79eb83941e620924e48073a..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Enjoy Tsukis Odyssey MOD APK with No Ads and More Carrots.md +++ /dev/null @@ -1,117 +0,0 @@ - -

Tsuki Odyssey Mod Apk: A Relaxing Adventure Game with a Cute Rabbit

-

If you are looking for a game that can help you relax and unwind from the stress of everyday life, you might want to check out Tsuki Odyssey. This is a passive adventure game that immerses you into the world of Tsuki, a cute white rabbit who moves back to his hometown of Mushroom Village. In this game, you can decorate your home, make friends, catch all kinds of fish, and so much more. You can also explore different locations and discover new events and secrets. But what if you want to enjoy the game without any limitations or restrictions? Well, you can do that by downloading and installing Tsuki Odyssey mod apk. In this article, we will tell you everything you need to know about this game, its features, how to download and install the mod apk, how to play it on PC or Mac, and some tips and tricks for playing it.

-

tsuki odyssey mod apk


DOWNLOAD »»» https://jinyurl.com/2uNMs6



-

What is Tsuki Odyssey?

-

Tsuki Odyssey is a mobile game developed by RapBot Studios and released for iOS and Android by HyperBeard in 2021. It serves as a spiritual successor (and a soft reboot) to Tsuki Adventure, a game that was released in 2018. It shares a similar premise with its predecessor: a rabbit named Tsuki, having grown dissatisfied with his paper-pushing office job, abandons his life in the city and moves back to his quiet hometown of Mushroom Village, taking over his late grandfather's carrot farm. As in the first game, the player does not have direct control over what Tsuki does. Instead, the game revolves around checking in on him periodically and seeing what he gets up to on his own. The player can move Tsuki around with the world map, buy items and furniture, interact with the other residents of Mushroom Village, and enjoy hobbies like fishing.

-

However, Tsuki Odyssey is not just a copy of Tsuki Adventure. It offers a different gaming experience that is more immersive and interactive. For example, the game has more locations to explore, such as the bar, the workshop, the town hall, and the river. The game also has more events and secrets to discover, such as bounties, gachapon toys, hidden characters, and special quests. The game also has more customization options for your home, such as floorboards, wallpaper, décor, and furniture. The game also has more hobbies for Tsuki to enjoy, such as yoga, writing, and gardening. The game also has more collectibles to find, such as items, furniture, gachapon toys, and bounties. The game also has more characters to meet and befriend, such as Bobo the monkey, Chi the panda, Yori the fox, and Moca the cat. The game also has more dialogue and storylines to enjoy, such as Tsuki's memories, dreams, and adventures. In short, Tsuki Odyssey is a game that offers a lot of content and variety for the player to explore and experience.

-

What are the features of Tsuki Odyssey?

-

As we have mentioned, Tsuki Odyssey is a game that has a lot of features that make it fun and relaxing to play. Here are some of the main features of the game:

- -

These are just some of the features of Tsuki Odyssey. There are many more things to do and see in this game that will keep you entertained and relaxed.

-

tsuki odyssey mod apk unlimited carrots
-tsuki odyssey mod apk latest version
-tsuki odyssey mod apk download for android
-tsuki odyssey mod apk free shopping
-tsuki odyssey mod apk 1.0.7
-tsuki odyssey mod apk an1
-tsuki odyssey mod apk happymod
-tsuki odyssey mod apk revdl
-tsuki odyssey mod apk rexdl
-tsuki odyssey mod apk android 1
-tsuki odyssey mod apk no ads
-tsuki odyssey mod apk offline
-tsuki odyssey mod apk unlimited money
-tsuki odyssey mod apk 2023
-tsuki odyssey mod apk obb
-tsuki odyssey mod apk pure
-tsuki odyssey mod apk platinmods
-tsuki odyssey mod apk vip
-tsuki odyssey mod apk pro
-tsuki odyssey mod apk premium
-tsuki odyssey mod apk full unlocked
-tsuki odyssey mod apk mega
-tsuki odyssey mod apk mediafıre
-tsuki odyssey mod apk apkpure
-tsuki odyssey mod apk apkmody
-tsuki odyssey mod apk apkmirror
-tsuki odyssey mod apk apknite
-tsuki odyssey mod apk apksolo
-tsuki odyssey mod apk apksmash
-tsuki odyssey mod apk apksweet
-tsuki odyssey mod apk apktada
-tsuki odyssey mod apk apktovi
-tsuki odyssey mod apk apktoko
-tsuki odyssey mod apk apktada.com
-tsuki odyssey mod apk apktwist.com
-tsuki odyssey mod apk apkturbo.com
-tsuki odyssey mod apk apktouch.com
-tsuki odyssey mod apk apktreat.com
-tsuki odyssey mod apk apktrend.com
-tsuki odyssey mod apk apktune.com
-tsuki odyssey mod apk apktown.com
-tsuki odyssey mod apk apktube.com
-tsuki odyssey mod apk aptoide.com
-tsuki odyssey hack cheat tool generator online 2023 working 100%

-

How to download and install Tsuki Odyssey mod apk?

-

Tsuki Odyssey is a free-to-play game that you can download from the App Store or Google Play Store. However, if you want to enjoy the game without any limitations or restrictions, you might want to use a mod apk for Tsuki Odyssey. A mod apk is a modified version of an app that gives you access to features that are not available in the original app. For example, a mod apk for Tsuki Odyssey might give you unlimited carrots (the currency of the game), free gacha tickets (to get gachapon toys), unlocked locations (to explore new places), unlocked characters (to meet new friends), or other benefits that will make your gaming experience more enjoyable.

-

If you want to download and install a mod apk for Tsuki Odyssey on your Android device, here are the steps you need to follow:

-
    -
  1. Find a reliable source for downloading the mod apk file. There are many websites that offer mod apk files for various apps and games, but not all of them are safe or trustworthy. Some of them might contain malware or viruses that could harm your device or steal your personal information. Therefore, you should do some research before downloading any mod apk file from any website. You should check the reviews, ratings, comments, and feedback from other users who have downloaded the mod apk file from that website. You should also scan the mod apk file with an antivirus software before installing it on your device.
  2. -
  3. Enable unknown sources on your device. By default, Android devices do not allow installing apps from unknown sources, meaning sources other than the official app stores. However, since you are downloading a mod apk file from a third-party website, you need to enable unknown sources on your device to allow installing it. To do this, go to your device's settings, then security, then unknown sources, and toggle it on. You might see a warning message that installing apps from unknown sources could harm your device or data, but you can ignore it if you trust the source of the mod apk file.
  4. -
  5. Download the mod apk file from the website. Once you have found a reliable source for the mod apk file, you can download it from the website. You might need to click on a download button or link, or complete a captcha or survey to start the download. You might also see some pop-up ads or redirects that could be annoying or misleading, but you can close them or go back to the original website. The download might take some time depending on the size of the mod apk file and your internet speed.
  6. -
  7. Install the mod apk file on your device. After the download is complete, you can install the mod apk file on your device. You can find the mod apk file in your device's downloads folder or in the notification bar. You can tap on the mod apk file to start the installation process. You might see a prompt asking you to confirm the installation or grant some permissions to the app. You can follow the instructions on the screen to complete the installation.
  8. -
  9. Launch Tsuki Odyssey mod apk on your device. Once the installation is done, you can launch Tsuki Odyssey mod apk on your device. You can find the app icon on your device's home screen or app drawer. You can tap on the app icon to open it and start playing Tsuki Odyssey with all the benefits of the mod apk.
  10. -
-

These are the steps to download and install Tsuki Odyssey mod apk on your Android device. However, before you use a mod apk for Tsuki Odyssey, there are some precautions you need to take:

- -

These are some of the precautions you need to take before using a mod apk for Tsuki Odyssey.

-

How to play Tsuki Odyssey on PC or Mac?

-

Tsuki Odyssey is a mobile game that is designed for iOS and Android devices. However, if you want to play Tsuki Odyssey on a bigger screen with better graphics and performance, you might want to play it on PC or Mac. To do this, you need to use an emulator. An emulator is a software that allows you to run mobile apps and games on your PC or Mac as if they were native apps and games. There are many emulators available for PC and Mac, such as BlueStacks, NoxPlayer, MEmu, LDPlayer, and more.

-

If you want to play Tsuki Odyssey on PC or Mac using an emulator, here are the steps you need to follow:

-
    -
  1. Download and install an emulator on your PC or Mac. You can choose any emulator that suits your preference and system requirements. You can find and download emulators from their official websites or from other sources online. The download and installation process might vary depending on the emulator and your operating system, but generally it involves clicking on an installer file and following the instructions on the screen.
  2. -
  3. Launch the emulator on your PC or Mac. After installing the emulator, you can launch it on your PC or Mac by clicking on its icon or shortcut. You might see a welcome screen or a tutorial that will guide you through setting up the emulator and its features.
  4. -
  5. Download and install Tsuki Odyssey on your emulator. You can download Tsuki Odyssey from the app store of your emulator, such as Google Play Store or Apple App Store. You can also download Tsuki Odyssey mod apk from a third-party website and install it on your emulator using the same steps as mentioned above. The download and installation process might vary depending on the emulator and the app source, but generally it involves searching for the app, clicking on the install button, and waiting for the app to be installed.
  6. -
  7. Launch Tsuki Odyssey on your emulator. After installing Tsuki Odyssey, you can launch it on your emulator by clicking on its icon or shortcut. You might see a loading screen or a splash screen that will take you to the main menu of the game. You can then start playing Tsuki Odyssey on your PC or Mac as if you were playing it on your mobile device.
  8. -
-

These are the steps to play Tsuki Odyssey on PC or Mac using an emulator.

-

Tips and tricks for playing Tsuki Odyssey

-

Tsuki Odyssey is a game that does not require your constant input, but rewards you for checking in often and seeing what happens in the town. However, if you want to progress faster in the game and get more out of it, you might want to use some tips and tricks for playing Tsuki Odyssey. Here are some of them:

- -

These are some of the tips and tricks for playing Tsuki Odyssey.

-

Conclusion

-

Tsuki Odyssey is a relaxing adventure game with a cute rabbit that will make you feel calm and happy. It is a game that does not require your constant input, but rewards you for checking in often and seeing what happens in the town. It is a game that has a lot of features that make it fun and immersive to play. It is a game that you can download from the app store or use a mod apk for more benefits. It is a game that you can play on your mobile device or on your PC or Mac using an emulator. It is a game that you can enjoy with some tips and tricks.

-

If you are looking for a game that can help you relax and unwind from the stress of everyday life, you might want to give Tsuki Odyssey a try. It is a game that will make you smile and relax with its cute graphics, soothing music, and charming characters. It is a game that will let you escape from reality and immerse yourself into a world of peace and tranquility. It is a game that will make you feel like you are living a simple and happy life with a cute rabbit.

-

FAQs

-

Here are some of the frequently asked questions about Tsuki Odyssey:

-
    -
  1. Is Tsuki Odyssey online or offline?
  2. -

    Tsuki Odyssey is an offline game that does not require an internet connection to play. However, you might need an internet connection to download the game, update the game, watch ads, or use some features of the game.

    -
  3. Is Tsuki Odyssey free or paid?
  4. -

    Tsuki Odyssey is a free-to-play game that does not require any payment to download or play. However, the game has some optional in-app purchases that can enhance your gaming experience, such as buying carrots, gacha tickets, or travel tickets. You can also use a mod apk for Tsuki Odyssey that gives you these benefits for free.

    -
  5. Is Tsuki Odyssey safe or harmful?
  6. -

    Tsuki Odyssey is a safe game that does not contain any harmful content or malware. However, you should be careful when downloading and installing a mod apk for Tsuki Odyssey from a third-party website, as it might contain malware or viruses that could harm your device or data. You should also backup your data, disable automatic updates, and use a VPN before using a mod apk for Tsuki Odyssey.

    -
  7. Is Tsuki Odyssey easy or hard?
  8. -

    Tsuki Odyssey is an easy game that does not require any skill or strategy to play. It is a game that does not have any goals or challenges to complete. It is a game that does not have any timers or deadlines to meet. It is a game that does not have any enemies or dangers to avoid. It is a game that does not have any failure or game over scenarios. It is a game that lets you play at your own pace and enjoy the game as you wish.

    -
  9. Is Tsuki Odyssey fun or boring?
  10. -

    Tsuki Odyssey is a fun game that has a lot of content and variety to offer. It is a game that has many features that make it fun and immersive to play. It is a game that has many locations and characters to explore and interact with. It is a game that has many events and secrets to discover and experience. It is a game that has many items and collectibles to find and display. It is a game that has many hobbies and activities to enjoy and relax with. It is a game that will keep you entertained and relaxed for hours.

    -

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/1toTree/lora_test/ppdiffusers/pipelines/paint_by_example/__init__.py b/spaces/1toTree/lora_test/ppdiffusers/pipelines/paint_by_example/__init__.py deleted file mode 100644 index d59a0762e24976d31ee6ea77fa54b66963aa9709..0000000000000000000000000000000000000000 --- a/spaces/1toTree/lora_test/ppdiffusers/pipelines/paint_by_example/__init__.py +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright (c) 2022 PaddlePaddle 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. - -from dataclasses import dataclass -from typing import List, Optional, Union - -import numpy as np -import PIL -from PIL import Image - -from ...utils import is_paddle_available, is_paddlenlp_available - -if is_paddlenlp_available() and is_paddle_available(): - from .image_encoder import PaintByExampleImageEncoder - from .pipeline_paint_by_example import PaintByExamplePipeline diff --git a/spaces/2023Liu2023/bingo/src/app/layout.tsx b/spaces/2023Liu2023/bingo/src/app/layout.tsx deleted file mode 100644 index 8b5122759987177b8dc4e4356d1d06cea25c15ea..0000000000000000000000000000000000000000 --- a/spaces/2023Liu2023/bingo/src/app/layout.tsx +++ /dev/null @@ -1,47 +0,0 @@ -import { Metadata } from 'next' -import { Toaster } from 'react-hot-toast' -import { TailwindIndicator } from '@/components/tailwind-indicator' -import { Providers } from '@/components/providers' -import { Header } from '@/components/header' - -import '@/app/globals.scss' - - -export const metadata: Metadata = { - title: { - default: 'Bing AI Chatbot', - template: `%s - Bing AI Chatbot` - }, - description: 'Bing AI Chatbot Web App.', - themeColor: [ - { media: '(prefers-color-scheme: light)', color: 'white' }, - { media: '(prefers-color-scheme: dark)', color: 'dark' } - ], - icons: { - icon: '/favicon.ico', - shortcut: '../assets/images/logo.svg', - apple: '../assets/images/logo.svg' - } -} - -interface RootLayoutProps { - children: React.ReactNode -} - -export default function RootLayout({ children }: RootLayoutProps) { - return ( - - - - -
- {/* @ts-ignore */} -
-
{children}
-
- -
- - - ) -} diff --git a/spaces/801artistry/RVC801/infer/modules/train/extract/extract_f0_print.py b/spaces/801artistry/RVC801/infer/modules/train/extract/extract_f0_print.py deleted file mode 100644 index 14ef598d73b807974204664f100c828918199816..0000000000000000000000000000000000000000 --- a/spaces/801artistry/RVC801/infer/modules/train/extract/extract_f0_print.py +++ /dev/null @@ -1,298 +0,0 @@ -import os -import sys -import traceback - -import parselmouth - -now_dir = os.getcwd() -sys.path.append(now_dir) -import logging -from LazyImport import lazyload - -import numpy as np -import pyworld -torchcrepe = lazyload("torchcrepe") # Fork Feature. Crepe algo for training and preprocess -torch = lazyload("torch") -#from torch import Tensor # Fork Feature. Used for pitch prediction for torch crepe. -tqdm = lazyload("tqdm") -from infer.lib.audio import load_audio - -logging.getLogger("numba").setLevel(logging.WARNING) -from multiprocessing import Process - -exp_dir = sys.argv[1] -f = open("%s/extract_f0_feature.log" % exp_dir, "a+") - -DoFormant = False -Quefrency = 1.0 -Timbre = 1.0 - -def printt(strr): - print(strr) - f.write(f"{strr}\n") - f.flush() - - -n_p = int(sys.argv[2]) -f0method = sys.argv[3] -extraction_crepe_hop_length = 0 -try: - extraction_crepe_hop_length = int(sys.argv[4]) -except: - print("Temp Issue. echl is not being passed with argument!") - extraction_crepe_hop_length = 128 - -class FeatureInput(object): - def __init__(self, samplerate=16000, hop_size=160): - self.fs = samplerate - self.hop = hop_size - - self.f0_bin = 256 - self.f0_max = 1100.0 - self.f0_min = 50.0 - self.f0_mel_min = 1127 * np.log(1 + self.f0_min / 700) - self.f0_mel_max = 1127 * np.log(1 + self.f0_max / 700) - - def mncrepe(self, method, x, p_len, crepe_hop_length): - f0 = None - torch_device_index = 0 - torch_device = torch.device( - f"cuda:{torch_device_index % torch.cuda.device_count()}" - ) if torch.cuda.is_available() \ - else torch.device("mps") if torch.backends.mps.is_available() \ - else torch.device("cpu") - - audio = torch.from_numpy(x.astype(np.float32)).to(torch_device, copy=True) - audio /= torch.quantile(torch.abs(audio), 0.999) - audio = torch.unsqueeze(audio, dim=0) - if audio.ndim == 2 and audio.shape[0] > 1: - audio = torch.mean(audio, dim=0, keepdim=True).detach() - audio = audio.detach() - - if method == 'mangio-crepe': - pitch: torch.Tensor = torchcrepe.predict( - audio, - self.fs, - crepe_hop_length, - self.f0_min, - self.f0_max, - "full", - batch_size=crepe_hop_length * 2, - device=torch_device, - pad=True, - ) - p_len = p_len or x.shape[0] // crepe_hop_length - # Resize the pitch - source = np.array(pitch.squeeze(0).cpu().float().numpy()) - source[source < 0.001] = np.nan - target = np.interp( - np.arange(0, len(source) * p_len, len(source)) / p_len, - np.arange(0, len(source)), - source, - ) - f0 = np.nan_to_num(target) - - elif method == 'crepe': - batch_size = 512 - audio = torch.tensor(np.copy(x))[None].float() - f0, pd = torchcrepe.predict( - audio, - self.fs, - 160, - self.f0_min, - self.f0_max, - "full", - batch_size=batch_size, - device=torch_device, - return_periodicity=True, - ) - pd = torchcrepe.filter.median(pd, 3) - f0 = torchcrepe.filter.mean(f0, 3) - f0[pd < 0.1] = 0 - f0 = f0[0].cpu().numpy() - f0 = f0[1:] # Get rid of extra first frame - - return f0 - - def get_pm(self, x, p_len): - f0 = parselmouth.Sound(x, self.fs).to_pitch_ac( - time_step=160 / 16000, - voicing_threshold=0.6, - pitch_floor=self.f0_min, - pitch_ceiling=self.f0_max, - ).selected_array["frequency"] - - return np.pad( - f0, - [[max(0, (p_len - len(f0) + 1) // 2), max(0, p_len - len(f0) - (p_len - len(f0) + 1) // 2)]], - mode="constant" - ) - - def get_harvest(self, x): - f0_spectral = pyworld.harvest( - x.astype(np.double), - fs=self.fs, - f0_ceil=self.f0_max, - f0_floor=self.f0_min, - frame_period=1000 * self.hop / self.fs, - ) - return pyworld.stonemask(x.astype(np.double), *f0_spectral, self.fs) - - def get_dio(self, x): - f0_spectral = pyworld.dio( - x.astype(np.double), - fs=self.fs, - f0_ceil=self.f0_max, - f0_floor=self.f0_min, - frame_period=1000 * self.hop / self.fs, - ) - return pyworld.stonemask(x.astype(np.double), *f0_spectral, self.fs) - - def get_rmvpe(self, x): - if hasattr(self, "model_rmvpe") == False: - from infer.lib.rmvpe import RMVPE - - print("Loading rmvpe model") - self.model_rmvpe = RMVPE( - "assets/rmvpe/rmvpe.pt", is_half=False, device="cpu" - ) - return self.model_rmvpe.infer_from_audio(x, thred=0.03) - - def get_rmvpe_dml(self, x): - ... - - def get_f0_method_dict(self): - return { - "pm": self.get_pm, - "harvest": self.get_harvest, - "dio": self.get_dio, - "rmvpe": self.get_rmvpe - } - - def get_f0_hybrid_computation( - self, - methods_str, - x, - p_len, - crepe_hop_length, - ): - # Get various f0 methods from input to use in the computation stack - s = methods_str - s = s.split("hybrid")[1] - s = s.replace("[", "").replace("]", "") - methods = s.split("+") - f0_computation_stack = [] - - for method in methods: - if method in self.f0_method_dict: - f0 = self.f0_method_dict[method](x, p_len) if method == 'pm' else self.f0_method_dict[method](x) - f0_computation_stack.append(f0) - elif method == 'crepe' or method == 'mangio-crepe': - self.the_other_complex_function(x, method, crepe_hop_length) - - if len(f0_computation_stack) != 0: - f0_median_hybrid = np.nanmedian(f0_computation_stack, axis=0) if len(f0_computation_stack)>1 else f0_computation_stack[0] - return f0_median_hybrid - else: - raise ValueError("No valid methods were provided") - - def compute_f0(self, path, f0_method, crepe_hop_length): - x = load_audio(path, self.fs, DoFormant, Quefrency, Timbre) - p_len = x.shape[0] // self.hop - - if f0_method in self.f0_method_dict: - f0 = self.f0_method_dict[f0_method](x, p_len) if f0_method == 'pm' else self.f0_method_dict[f0_method](x) - elif f0_method in ['crepe', 'mangio-crepe']: - f0 = self.mncrepe(f0_method, x, p_len, crepe_hop_length) - elif "hybrid" in f0_method: # EXPERIMENTAL - # Perform hybrid median pitch estimation - f0 = self.get_f0_hybrid_computation( - f0_method, - x, - p_len, - crepe_hop_length, - ) - return f0 - - def coarse_f0(self, f0): - f0_mel = 1127 * np.log(1 + f0 / 700) - f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - self.f0_mel_min) * ( - self.f0_bin - 2 - ) / (self.f0_mel_max - self.f0_mel_min) + 1 - - # use 0 or 1 - f0_mel[f0_mel <= 1] = 1 - f0_mel[f0_mel > self.f0_bin - 1] = self.f0_bin - 1 - f0_coarse = np.rint(f0_mel).astype(int) - assert f0_coarse.max() <= 255 and f0_coarse.min() >= 1, ( - f0_coarse.max(), - f0_coarse.min(), - ) - return f0_coarse - - def go(self, paths, f0_method, crepe_hop_length, thread_n): - if len(paths) == 0: - printt("no-f0-todo") - return - with tqdm.tqdm(total=len(paths), leave=True, position=thread_n) as pbar: - description = f"thread:{thread_n}, f0ing, Hop-Length:{crepe_hop_length}" - pbar.set_description(description) - - for idx, (inp_path, opt_path1, opt_path2) in enumerate(paths): - try: - if ( - os.path.exists(opt_path1 + ".npy") - and os.path.exists(opt_path2 + ".npy") - ): - pbar.update(1) - continue - - featur_pit = self.compute_f0(inp_path, f0_method, crepe_hop_length) - np.save( - opt_path2, - featur_pit, - allow_pickle=False, - ) # nsf - coarse_pit = self.coarse_f0(featur_pit) - np.save( - opt_path1, - coarse_pit, - allow_pickle=False, - ) # ori - pbar.update(1) - except Exception as e: - printt(f"f0fail-{idx}-{inp_path}-{traceback.format_exc()}") - - -if __name__ == "__main__": - # exp_dir=r"E:\codes\py39\dataset\mi-test" - # n_p=16 - # f = open("%s/log_extract_f0.log"%exp_dir, "w") - printt(sys.argv) - featureInput = FeatureInput() - paths = [] - inp_root = "%s/1_16k_wavs" % (exp_dir) - opt_root1 = "%s/2a_f0" % (exp_dir) - opt_root2 = "%s/2b-f0nsf" % (exp_dir) - - os.makedirs(opt_root1, exist_ok=True) - os.makedirs(opt_root2, exist_ok=True) - for name in sorted(list(os.listdir(inp_root))): - inp_path = "%s/%s" % (inp_root, name) - if "spec" in inp_path: - continue - opt_path1 = "%s/%s" % (opt_root1, name) - opt_path2 = "%s/%s" % (opt_root2, name) - paths.append([inp_path, opt_path1, opt_path2]) - - ps = [] - print("Using f0 method: " + f0method) - for i in range(n_p): - p = Process( - target=featureInput.go, - args=(paths[i::n_p], f0method, extraction_crepe_hop_length, i), - ) - ps.append(p) - p.start() - for i in range(n_p): - ps[i].join() \ No newline at end of file diff --git a/spaces/AI-Hobbyist/Hoyo-RVC/infer_pack/onnx_inference.py b/spaces/AI-Hobbyist/Hoyo-RVC/infer_pack/onnx_inference.py deleted file mode 100644 index 18255129f8f1253e247b2baf08608fabf32f0be5..0000000000000000000000000000000000000000 --- a/spaces/AI-Hobbyist/Hoyo-RVC/infer_pack/onnx_inference.py +++ /dev/null @@ -1,143 +0,0 @@ -import onnxruntime -import librosa -import numpy as np -import soundfile - - -class ContentVec: - def __init__(self, vec_path="pretrained/vec-768-layer-12.onnx", device=None): - print("load model(s) from {}".format(vec_path)) - if device == "cpu" or device is None: - providers = ["CPUExecutionProvider"] - elif device == "cuda": - providers = ["CUDAExecutionProvider", "CPUExecutionProvider"] - elif device == "dml": - providers = ["DmlExecutionProvider"] - else: - raise RuntimeError("Unsportted Device") - self.model = onnxruntime.InferenceSession(vec_path, providers=providers) - - def __call__(self, wav): - return self.forward(wav) - - def forward(self, wav): - feats = wav - if feats.ndim == 2: # double channels - feats = feats.mean(-1) - assert feats.ndim == 1, feats.ndim - feats = np.expand_dims(np.expand_dims(feats, 0), 0) - onnx_input = {self.model.get_inputs()[0].name: feats} - logits = self.model.run(None, onnx_input)[0] - return logits.transpose(0, 2, 1) - - -def get_f0_predictor(f0_predictor, hop_length, sampling_rate, **kargs): - if f0_predictor == "pm": - from infer_pack.modules.F0Predictor.PMF0Predictor import PMF0Predictor - - f0_predictor_object = PMF0Predictor( - hop_length=hop_length, sampling_rate=sampling_rate - ) - elif f0_predictor == "harvest": - from infer_pack.modules.F0Predictor.HarvestF0Predictor import HarvestF0Predictor - - f0_predictor_object = HarvestF0Predictor( - hop_length=hop_length, sampling_rate=sampling_rate - ) - elif f0_predictor == "dio": - from infer_pack.modules.F0Predictor.DioF0Predictor import DioF0Predictor - - f0_predictor_object = DioF0Predictor( - hop_length=hop_length, sampling_rate=sampling_rate - ) - else: - raise Exception("Unknown f0 predictor") - return f0_predictor_object - - -class OnnxRVC: - def __init__( - self, - model_path, - sr=40000, - hop_size=512, - vec_path="vec-768-layer-12", - device="cpu", - ): - vec_path = f"pretrained/{vec_path}.onnx" - self.vec_model = ContentVec(vec_path, device) - if device == "cpu" or device is None: - providers = ["CPUExecutionProvider"] - elif device == "cuda": - providers = ["CUDAExecutionProvider", "CPUExecutionProvider"] - elif device == "dml": - providers = ["DmlExecutionProvider"] - else: - raise RuntimeError("Unsportted Device") - self.model = onnxruntime.InferenceSession(model_path, providers=providers) - self.sampling_rate = sr - self.hop_size = hop_size - - def forward(self, hubert, hubert_length, pitch, pitchf, ds, rnd): - onnx_input = { - self.model.get_inputs()[0].name: hubert, - self.model.get_inputs()[1].name: hubert_length, - self.model.get_inputs()[2].name: pitch, - self.model.get_inputs()[3].name: pitchf, - self.model.get_inputs()[4].name: ds, - self.model.get_inputs()[5].name: rnd, - } - return (self.model.run(None, onnx_input)[0] * 32767).astype(np.int16) - - def inference( - self, - raw_path, - sid, - f0_method="dio", - f0_up_key=0, - pad_time=0.5, - cr_threshold=0.02, - ): - f0_min = 50 - f0_max = 1100 - f0_mel_min = 1127 * np.log(1 + f0_min / 700) - f0_mel_max = 1127 * np.log(1 + f0_max / 700) - f0_predictor = get_f0_predictor( - f0_method, - hop_length=self.hop_size, - sampling_rate=self.sampling_rate, - threshold=cr_threshold, - ) - wav, sr = librosa.load(raw_path, sr=self.sampling_rate) - org_length = len(wav) - if org_length / sr > 50.0: - raise RuntimeError("Reached Max Length") - - wav16k = librosa.resample(wav, orig_sr=self.sampling_rate, target_sr=16000) - wav16k = wav16k - - hubert = self.vec_model(wav16k) - hubert = np.repeat(hubert, 2, axis=2).transpose(0, 2, 1).astype(np.float32) - hubert_length = hubert.shape[1] - - pitchf = f0_predictor.compute_f0(wav, hubert_length) - pitchf = pitchf * 2 ** (f0_up_key / 12) - pitch = pitchf.copy() - f0_mel = 1127 * np.log(1 + pitch / 700) - f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / ( - f0_mel_max - f0_mel_min - ) + 1 - f0_mel[f0_mel <= 1] = 1 - f0_mel[f0_mel > 255] = 255 - pitch = np.rint(f0_mel).astype(np.int64) - - pitchf = pitchf.reshape(1, len(pitchf)).astype(np.float32) - pitch = pitch.reshape(1, len(pitch)) - ds = np.array([sid]).astype(np.int64) - - rnd = np.random.randn(1, 192, hubert_length).astype(np.float32) - hubert_length = np.array([hubert_length]).astype(np.int64) - - out_wav = self.forward(hubert, hubert_length, pitch, pitchf, ds, rnd).squeeze() - out_wav = np.pad(out_wav, (0, 2 * self.hop_size), "constant") - return out_wav[0:org_length] diff --git a/spaces/AIFILMS/generate_human_motion/pyrender/pyrender/shader_program.py b/spaces/AIFILMS/generate_human_motion/pyrender/pyrender/shader_program.py deleted file mode 100644 index c1803f280c98033abe0769771a9ad8ecfec942e3..0000000000000000000000000000000000000000 --- a/spaces/AIFILMS/generate_human_motion/pyrender/pyrender/shader_program.py +++ /dev/null @@ -1,283 +0,0 @@ -"""OpenGL shader program wrapper. -""" -import numpy as np -import os -import re - -import OpenGL -from OpenGL.GL import * -from OpenGL.GL import shaders as gl_shader_utils - - -class ShaderProgramCache(object): - """A cache for shader programs. - """ - - def __init__(self, shader_dir=None): - self._program_cache = {} - self.shader_dir = shader_dir - if self.shader_dir is None: - base_dir, _ = os.path.split(os.path.realpath(__file__)) - self.shader_dir = os.path.join(base_dir, 'shaders') - - def get_program(self, vertex_shader, fragment_shader, - geometry_shader=None, defines=None): - """Get a program via a list of shader files to include in the program. - - Parameters - ---------- - vertex_shader : str - The vertex shader filename. - fragment_shader : str - The fragment shader filename. - geometry_shader : str - The geometry shader filename. - defines : dict - Defines and their values for the shader. - - Returns - ------- - program : :class:`.ShaderProgram` - The program. - """ - shader_names = [] - if defines is None: - defines = {} - shader_filenames = [ - x for x in [vertex_shader, fragment_shader, geometry_shader] - if x is not None - ] - for fn in shader_filenames: - if fn is None: - continue - _, name = os.path.split(fn) - shader_names.append(name) - cid = OpenGL.contextdata.getContext() - key = tuple([cid] + sorted( - [(s,1) for s in shader_names] + [(d, defines[d]) for d in defines] - )) - - if key not in self._program_cache: - shader_filenames = [ - os.path.join(self.shader_dir, fn) for fn in shader_filenames - ] - if len(shader_filenames) == 2: - shader_filenames.append(None) - vs, fs, gs = shader_filenames - self._program_cache[key] = ShaderProgram( - vertex_shader=vs, fragment_shader=fs, - geometry_shader=gs, defines=defines - ) - return self._program_cache[key] - - def clear(self): - for key in self._program_cache: - self._program_cache[key].delete() - self._program_cache = {} - - -class ShaderProgram(object): - """A thin wrapper about OpenGL shader programs that supports easy creation, - binding, and uniform-setting. - - Parameters - ---------- - vertex_shader : str - The vertex shader filename. - fragment_shader : str - The fragment shader filename. - geometry_shader : str - The geometry shader filename. - defines : dict - Defines and their values for the shader. - """ - - def __init__(self, vertex_shader, fragment_shader, - geometry_shader=None, defines=None): - - self.vertex_shader = vertex_shader - self.fragment_shader = fragment_shader - self.geometry_shader = geometry_shader - - self.defines = defines - if self.defines is None: - self.defines = {} - - self._program_id = None - self._vao_id = None # PYOPENGL BUG - - # DEBUG - # self._unif_map = {} - - def _add_to_context(self): - if self._program_id is not None: - raise ValueError('Shader program already in context') - shader_ids = [] - - # Load vert shader - shader_ids.append(gl_shader_utils.compileShader( - self._load(self.vertex_shader), GL_VERTEX_SHADER) - ) - # Load frag shader - shader_ids.append(gl_shader_utils.compileShader( - self._load(self.fragment_shader), GL_FRAGMENT_SHADER) - ) - # Load geometry shader - if self.geometry_shader is not None: - shader_ids.append(gl_shader_utils.compileShader( - self._load(self.geometry_shader), GL_GEOMETRY_SHADER) - ) - - # Bind empty VAO PYOPENGL BUG - if self._vao_id is None: - self._vao_id = glGenVertexArrays(1) - glBindVertexArray(self._vao_id) - - # Compile program - self._program_id = gl_shader_utils.compileProgram(*shader_ids) - - # Unbind empty VAO PYOPENGL BUG - glBindVertexArray(0) - - def _in_context(self): - return self._program_id is not None - - def _remove_from_context(self): - if self._program_id is not None: - glDeleteProgram(self._program_id) - glDeleteVertexArrays(1, [self._vao_id]) - self._program_id = None - self._vao_id = None - - def _load(self, shader_filename): - path, _ = os.path.split(shader_filename) - - with open(shader_filename) as f: - text = f.read() - - def ifdef(matchobj): - if matchobj.group(1) in self.defines: - return '#if 1' - else: - return '#if 0' - - def ifndef(matchobj): - if matchobj.group(1) in self.defines: - return '#if 0' - else: - return '#if 1' - - ifdef_regex = re.compile( - '#ifdef\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*$', re.MULTILINE - ) - ifndef_regex = re.compile( - '#ifndef\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*$', re.MULTILINE - ) - text = re.sub(ifdef_regex, ifdef, text) - text = re.sub(ifndef_regex, ifndef, text) - - for define in self.defines: - value = str(self.defines[define]) - text = text.replace(define, value) - - return text - - def _bind(self): - """Bind this shader program to the current OpenGL context. - """ - if self._program_id is None: - raise ValueError('Cannot bind program that is not in context') - # glBindVertexArray(self._vao_id) - glUseProgram(self._program_id) - - def _unbind(self): - """Unbind this shader program from the current OpenGL context. - """ - glUseProgram(0) - - def delete(self): - """Delete this shader program from the current OpenGL context. - """ - self._remove_from_context() - - def set_uniform(self, name, value, unsigned=False): - """Set a uniform value in the current shader program. - - Parameters - ---------- - name : str - Name of the uniform to set. - value : int, float, or ndarray - Value to set the uniform to. - unsigned : bool - If True, ints will be treated as unsigned values. - """ - try: - # DEBUG - # self._unif_map[name] = 1, (1,) - loc = glGetUniformLocation(self._program_id, name) - - if loc == -1: - raise ValueError('Invalid shader variable: {}'.format(name)) - - if isinstance(value, np.ndarray): - # DEBUG - # self._unif_map[name] = value.size, value.shape - if value.ndim == 1: - if (np.issubdtype(value.dtype, np.unsignedinteger) or - unsigned): - dtype = 'u' - value = value.astype(np.uint32) - elif np.issubdtype(value.dtype, np.integer): - dtype = 'i' - value = value.astype(np.int32) - else: - dtype = 'f' - value = value.astype(np.float32) - self._FUNC_MAP[(value.shape[0], dtype)](loc, 1, value) - else: - self._FUNC_MAP[(value.shape[0], value.shape[1])]( - loc, 1, GL_TRUE, value - ) - - # Call correct uniform function - elif isinstance(value, float): - glUniform1f(loc, value) - elif isinstance(value, int): - if unsigned: - glUniform1ui(loc, value) - else: - glUniform1i(loc, value) - elif isinstance(value, bool): - if unsigned: - glUniform1ui(loc, int(value)) - else: - glUniform1i(loc, int(value)) - else: - raise ValueError('Invalid data type') - except Exception: - pass - - _FUNC_MAP = { - (1,'u'): glUniform1uiv, - (2,'u'): glUniform2uiv, - (3,'u'): glUniform3uiv, - (4,'u'): glUniform4uiv, - (1,'i'): glUniform1iv, - (2,'i'): glUniform2iv, - (3,'i'): glUniform3iv, - (4,'i'): glUniform4iv, - (1,'f'): glUniform1fv, - (2,'f'): glUniform2fv, - (3,'f'): glUniform3fv, - (4,'f'): glUniform4fv, - (2,2): glUniformMatrix2fv, - (2,3): glUniformMatrix2x3fv, - (2,4): glUniformMatrix2x4fv, - (3,2): glUniformMatrix3x2fv, - (3,3): glUniformMatrix3fv, - (3,4): glUniformMatrix3x4fv, - (4,2): glUniformMatrix4x2fv, - (4,3): glUniformMatrix4x3fv, - (4,4): glUniformMatrix4fv, - } diff --git a/spaces/AIGC-Audio/AudioGPT/text_to_speech/utils/audio/rnnoise.py b/spaces/AIGC-Audio/AudioGPT/text_to_speech/utils/audio/rnnoise.py deleted file mode 100644 index 47f4eb6471918ca8144f217580a71d1720cd8c36..0000000000000000000000000000000000000000 --- a/spaces/AIGC-Audio/AudioGPT/text_to_speech/utils/audio/rnnoise.py +++ /dev/null @@ -1,48 +0,0 @@ -# rnnoise.py, requirements: ffmpeg, sox, rnnoise, python -import os -import subprocess - -INSTALL_STR = """ -RNNoise library not found. Please install RNNoise (https://github.com/xiph/rnnoise) to $REPO/rnnoise: -sudo apt-get install -y autoconf automake libtool ffmpeg sox -git clone https://github.com/xiph/rnnoise.git -rm -rf rnnoise/.git -cd rnnoise -./autogen.sh && ./configure && make -cd .. -""" - - -def rnnoise(filename, out_fn=None, verbose=False, out_sample_rate=22050): - assert os.path.exists('./rnnoise/examples/rnnoise_demo'), INSTALL_STR - if out_fn is None: - out_fn = f"{filename[:-4]}.denoised.wav" - out_48k_fn = f"{out_fn}.48000.wav" - tmp0_fn = f"{out_fn}.0.wav" - tmp1_fn = f"{out_fn}.1.wav" - tmp2_fn = f"{out_fn}.2.raw" - tmp3_fn = f"{out_fn}.3.raw" - if verbose: - print("Pre-processing audio...") # wav to pcm raw - subprocess.check_call( - f'sox "{filename}" -G -r48000 "{tmp0_fn}"', shell=True, stdin=subprocess.PIPE) # convert to raw - subprocess.check_call( - f'sox -v 0.95 "{tmp0_fn}" "{tmp1_fn}"', shell=True, stdin=subprocess.PIPE) # convert to raw - subprocess.check_call( - f'ffmpeg -y -i "{tmp1_fn}" -loglevel quiet -f s16le -ac 1 -ar 48000 "{tmp2_fn}"', - shell=True, stdin=subprocess.PIPE) # convert to raw - if verbose: - print("Applying rnnoise algorithm to audio...") # rnnoise - subprocess.check_call( - f'./rnnoise/examples/rnnoise_demo "{tmp2_fn}" "{tmp3_fn}"', shell=True) - - if verbose: - print("Post-processing audio...") # pcm raw to wav - if filename == out_fn: - subprocess.check_call(f'rm -f "{out_fn}"', shell=True) - subprocess.check_call( - f'sox -t raw -r 48000 -b 16 -e signed-integer -c 1 "{tmp3_fn}" "{out_48k_fn}"', shell=True) - subprocess.check_call(f'sox "{out_48k_fn}" -G -r{out_sample_rate} "{out_fn}"', shell=True) - subprocess.check_call(f'rm -f "{tmp0_fn}" "{tmp1_fn}" "{tmp2_fn}" "{tmp3_fn}" "{out_48k_fn}"', shell=True) - if verbose: - print("Audio-filtering completed!") diff --git a/spaces/Abhilashvj/planogram-compliance/utils/flask_rest_api/README.md b/spaces/Abhilashvj/planogram-compliance/utils/flask_rest_api/README.md deleted file mode 100644 index a726acbd92043458311dd949cc09c0195cd35400..0000000000000000000000000000000000000000 --- a/spaces/Abhilashvj/planogram-compliance/utils/flask_rest_api/README.md +++ /dev/null @@ -1,73 +0,0 @@ -# Flask REST API - -[REST](https://en.wikipedia.org/wiki/Representational_state_transfer) [API](https://en.wikipedia.org/wiki/API)s are -commonly used to expose Machine Learning (ML) models to other services. This folder contains an example REST API -created using Flask to expose the YOLOv5s model from [PyTorch Hub](https://pytorch.org/hub/ultralytics_yolov5/). - -## Requirements - -[Flask](https://palletsprojects.com/p/flask/) is required. Install with: - -```shell -$ pip install Flask -``` - -## Run - -After Flask installation run: - -```shell -$ python3 restapi.py --port 5000 -``` - -Then use [curl](https://curl.se/) to perform a request: - -```shell -$ curl -X POST -F image=@zidane.jpg 'http://localhost:5000/v1/object-detection/yolov5s' -``` - -The model inference results are returned as a JSON response: - -```json -[ - { - "class": 0, - "confidence": 0.8900438547, - "height": 0.9318675399, - "name": "person", - "width": 0.3264600933, - "xcenter": 0.7438579798, - "ycenter": 0.5207948685 - }, - { - "class": 0, - "confidence": 0.8440024257, - "height": 0.7155083418, - "name": "person", - "width": 0.6546785235, - "xcenter": 0.427829951, - "ycenter": 0.6334488392 - }, - { - "class": 27, - "confidence": 0.3771208823, - "height": 0.3902671337, - "name": "tie", - "width": 0.0696444362, - "xcenter": 0.3675483763, - "ycenter": 0.7991207838 - }, - { - "class": 27, - "confidence": 0.3527112305, - "height": 0.1540903747, - "name": "tie", - "width": 0.0336618312, - "xcenter": 0.7814827561, - "ycenter": 0.5065554976 - } -] -``` - -An example python script to perform inference using [requests](https://docs.python-requests.org/en/master/) is given -in `example_request.py` diff --git a/spaces/AchyuthGamer/OpenGPT/g4f/Provider/deprecated/ChatgptLogin.py b/spaces/AchyuthGamer/OpenGPT/g4f/Provider/deprecated/ChatgptLogin.py deleted file mode 100644 index 07f3b914a12c2bf09bfb661cb0cf803b79299a14..0000000000000000000000000000000000000000 --- a/spaces/AchyuthGamer/OpenGPT/g4f/Provider/deprecated/ChatgptLogin.py +++ /dev/null @@ -1,74 +0,0 @@ -from __future__ import annotations - -import os, re -from aiohttp import ClientSession - -from ..base_provider import AsyncProvider, format_prompt - - -class ChatgptLogin(AsyncProvider): - url = "https://opchatgpts.net" - supports_gpt_35_turbo = True - working = True - _nonce = None - - @classmethod - async def create_async( - cls, - model: str, - messages: list[dict[str, str]], - **kwargs - ) -> str: - headers = { - "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36", - "Accept" : "*/*", - "Accept-language" : "en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3", - "Origin" : "https://opchatgpts.net", - "Alt-Used" : "opchatgpts.net", - "Referer" : "https://opchatgpts.net/chatgpt-free-use/", - "Sec-Fetch-Dest" : "empty", - "Sec-Fetch-Mode" : "cors", - "Sec-Fetch-Site" : "same-origin", - } - async with ClientSession( - headers=headers - ) as session: - if not cls._nonce: - async with session.get( - "https://opchatgpts.net/chatgpt-free-use/", - params={"id": os.urandom(6).hex()}, - ) as response: - result = re.search(r'data-nonce="(.*?)"', await response.text()) - if not result: - raise RuntimeError("No nonce value") - cls._nonce = result.group(1) - data = { - "_wpnonce": cls._nonce, - "post_id": 28, - "url": "https://opchatgpts.net/chatgpt-free-use", - "action": "wpaicg_chat_shortcode_message", - "message": format_prompt(messages), - "bot_id": 0 - } - async with session.post("https://opchatgpts.net/wp-admin/admin-ajax.php", data=data) as response: - response.raise_for_status() - data = await response.json() - if "data" in data: - return data["data"] - elif "msg" in data: - raise RuntimeError(data["msg"]) - else: - raise RuntimeError(f"Response: {data}") - - - @classmethod - @property - def params(cls): - params = [ - ("model", "str"), - ("messages", "list[dict[str, str]]"), - ("stream", "bool"), - ("temperature", "float"), - ] - param = ", ".join([": ".join(p) for p in params]) - return f"g4f.provider.{cls.__name__} supports: ({param})" \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/agentverse/agents/tasksolving_agent/role_assigner.py b/spaces/AgentVerse/agentVerse/agentverse/agents/tasksolving_agent/role_assigner.py deleted file mode 100644 index 38d9e5dfbee7365f5b11cade939c4263a0937ad1..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/agentverse/agents/tasksolving_agent/role_assigner.py +++ /dev/null @@ -1,88 +0,0 @@ -from __future__ import annotations - -import asyncio -from colorama import Fore - -from agentverse.logging import get_logger -import bdb -from string import Template -from typing import TYPE_CHECKING, List - -from agentverse.message import RoleAssignerMessage, Message - -from agentverse.agents import agent_registry -from agentverse.agents.base import BaseAgent - - -logger = get_logger() - - -@agent_registry.register("role_assigner") -class RoleAssignerAgent(BaseAgent): - def step( - self, advice: str, task_description: str, cnt_critic_agents: int - ) -> RoleAssignerMessage: - logger.debug("", self.name, Fore.MAGENTA) - prepend_prompt, append_prompt = self.get_all_prompts( - advice=advice, - task_description=task_description, - cnt_critic_agents=cnt_critic_agents, - ) - history = self.memory.to_messages(self.name) - parsed_response = None - for i in range(self.max_retry): - try: - response = self.llm.generate_response( - prepend_prompt, history, append_prompt - ) - parsed_response = self.output_parser.parse(response) - if len(parsed_response) < cnt_critic_agents: - logger.warn( - f"Number of generate roles ({len(parsed_response)}) and number of group members ({cnt_critic_agents}) do not match." - ) - logger.warn("Retrying...") - continue - break - except (KeyboardInterrupt, bdb.BdbQuit): - raise - except Exception as e: - logger.error(e) - logger.warn("Retrying...") - continue - - if parsed_response is None: - logger.error(f"{self.name} failed to generate valid response.") - - message = RoleAssignerMessage( - content=parsed_response, sender=self.name, sender_agent=self - ) - return message - - async def astep(self, env_description: str = "") -> RoleAssignerMessage: - """Asynchronous version of step""" - pass - - def _fill_prompt_template( - self, advice, task_description: str, cnt_critic_agents: int - ) -> str: - """Fill the placeholders in the prompt template - - In the role_assigner agent, three placeholders are supported: - - ${task_description} - - ${cnt_critic_agnets} - - ${advice} - """ - input_arguments = { - "task_description": task_description, - "cnt_critic_agents": cnt_critic_agents, - "advice": advice, - } - return Template(self.prompt_template).safe_substitute(input_arguments) - - def add_message_to_memory(self, messages: List[Message]) -> None: - self.memory.add_message(messages) - - def reset(self) -> None: - """Reset the agent""" - self.memory.reset() - # TODO: reset receiver diff --git a/spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/basic.py b/spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/basic.py deleted file mode 100644 index 8531d48a071e74bb7544da7b4dd6055156bb911b..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/basic.py +++ /dev/null @@ -1,101 +0,0 @@ -import asyncio - -# import logging -from agentverse.logging import get_logger -from typing import Any, Dict, List - -# from agentverse.agents.agent import Agent -from agentverse.agents.simulation_agent.conversation import BaseAgent - -# from agentverse.environments.simulation_env.rules.base import Rule -from agentverse.environments.simulation_env.rules.base import SimulationRule as Rule -from agentverse.message import Message - -logger = get_logger() - -from .. import env_registry as EnvironmentRegistry -from ..base import BaseEnvironment - - -@EnvironmentRegistry.register("sim-basic") -class BasicEnvironment(BaseEnvironment): - """ - A basic environment implementing the logic of conversation. - - Args: - agents: List of agents - rule: Rule for the environment - max_turns: Maximum number of turns - cnt_turn: Current turn number - last_messages: Messages from last turn - rule_params: Variables set by the rule - """ - - agents: List[BaseAgent] - rule: Rule - max_turns: int = 10 - cnt_turn: int = 0 - last_messages: List[Message] = [] - rule_params: Dict = {} - - def __init__(self, rule, **kwargs): - rule_config = rule - order_config = rule_config.get("order", {"type": "sequential"}) - visibility_config = rule_config.get("visibility", {"type": "all"}) - selector_config = rule_config.get("selector", {"type": "basic"}) - updater_config = rule_config.get("updater", {"type": "basic"}) - describer_config = rule_config.get("describer", {"type": "basic"}) - rule = Rule( - order_config, - visibility_config, - selector_config, - updater_config, - describer_config, - ) - super().__init__(rule=rule, **kwargs) - - async def step(self) -> List[Message]: - """Run one step of the environment""" - - # Get the next agent index - agent_ids = self.rule.get_next_agent_idx(self) - - # Generate current environment description - env_descriptions = self.rule.get_env_description(self) - - # Generate the next message - messages = await asyncio.gather( - *[self.agents[i].astep(env_descriptions[i]) for i in agent_ids] - ) - - # Some rules will select certain messages from all the messages - selected_messages = self.rule.select_message(self, messages) - self.last_messages = selected_messages - self.print_messages(selected_messages) - - # Update the memory of the agents - self.rule.update_memory(self) - - # Update the set of visible agents for each agent - self.rule.update_visible_agents(self) - - self.cnt_turn += 1 - - return selected_messages - - def print_messages(self, messages: List[Message]) -> None: - for message in messages: - if message is not None: - # logging.info(f"{message.sender}: {message.content}") - logger.info(f"{message.sender}: {message.content}") - - def reset(self) -> None: - """Reset the environment""" - self.cnt_turn = 0 - self.rule.reset() - for agent in self.agents: - agent.reset() - - def is_done(self) -> bool: - """Check if the environment is done""" - return self.cnt_turn >= self.max_turns diff --git a/spaces/AhmedMagdy7/My_paper_space/README.md b/spaces/AhmedMagdy7/My_paper_space/README.md deleted file mode 100644 index 057c917dec0d99b469a9740b27930ea1189644ed..0000000000000000000000000000000000000000 --- a/spaces/AhmedMagdy7/My_paper_space/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: My Paper Space -emoji: 🏃 -colorFrom: purple -colorTo: gray -sdk: gradio -sdk_version: 4.1.2 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/AkashKhamkar/Job_Search_Engine/skill_list.py b/spaces/AkashKhamkar/Job_Search_Engine/skill_list.py deleted file mode 100644 index 994663aa7ac1fcf6af141cc40fb84ba9823dff3b..0000000000000000000000000000000000000000 --- a/spaces/AkashKhamkar/Job_Search_Engine/skill_list.py +++ /dev/null @@ -1,3 +0,0 @@ -skills = ['HTML','Cryptography' , 'Data structures' ,'Blockchain' ,'Cryptography' ,'Smart contracts' ,'Outlook','Netbeans','python','JAVA','Networking','DML','Rest Web Services','Windows','MS Power Point.','MS-Access','technical assistance.','SAP','UNIX','Citrix Xen Server','Web Application testing','Cyara','Linux','MICROSOFT','Nagios','Software Testing','GIT','Eclipse','Sonar Qube''C#.net','Apache','Data Modeling','Database','MySQL','Angular Js','Networking','AWS','java servlet','Jquery','Selenium','Selenium Webdriver','NoSQL','GWT','CSS','Computer','SQL Server 2010','Web Development','Internet Of Things','Windows/XP','R Studio','network engineers','Java.','MS OFFICE','Testing','CCNA','ipsec','ANDROID','HSRP','CPP','Application Designer','PowerShell','MS Word','Ms-Access', "NetBeans",'Cloud Computing','OpenShit','Web Designing','Jdeveloper','computer and firesafety','HTML','Windows and Linux','CISCO','Azure','SAS','Sql','SQL developer','Computer Networks','php','Ansible','Excel','Apache Tomcat','Ansible','Bootstrap','JavaScript','SQL','VB.net','APPLICATION SOFTWARE','Micro Services','Java Script','Eclipse IDE.','Bash','Putty','SPUFI','Agile','Hacking','bgp','Invoice','AMDP.','ASP','Artificial Intelligence','Application / Software Development','mpls','Program Management','C','MS-Access','Java' ,'Kibana','Maven','Open VZ','ASP.NET','C# .NET','AWS','java script','Hibernate','routing protocols.','cricket','Automation','MySQL','Lithium','Git','GCP','JSON','Maria-DB','Spring','Socket Programming','EJB','Nexus','Html5','PostgreSQL','Ms Word and Power Point','ASP.NET','CSS 3.0','Hyper-','Servlet','PowerPoint','JMS','multicast','Windows Services','IoT','Hardware & Networking','SAPUI5','Machine Learning','TRAINING','SQL','C++','Gephi','Go Lang','AngularJs','Object Oriented Programming','Struts','Application & Web Servers: Sciencelogic (EM7)','Java/C/C++ ','M.S. OFFICE','Billing','active directory','Big data''ASP Technical specifications creation','Confidential Record Keeping','Postman','Goal Oriented & Self Motivated','VB','Content',' SAPUI5 (Primary Skill)','Mongo DB','Market Basket Analysis','Familiar with SQL','Hospitality','Web Authoring Tools HTML 5','Reporting Tools: Vportal','Network Management','Operations','Inversion of Control','MS office','Monthly patching update activity and server owner approval / RFC follow-ups.','Ajax &JQuery','rogramming :C/C++','problem solving','Functional Testing','Octopus','good at communication','angular','PL/SQL Developer','Windows XP','ospf','Powershell','work devotee','APACHE','Android Studio','exchange','Frontend HTML and .Net','DBMS','excellent in various sports like soccer','Predictive Modelling','KVM','JQuery.','ACCESS','Work on Windows 7','CRM','Selenium (Selenium IDE','RESOURCE PLANNING','PowerPoint Language: Fluent in verbal','STL)','good time management skills','DNS','than 1 year)','Accounts Payable-FI-A/P','java','Mac','IDE: Eclipse','JQuery','PHP','kannada','IT Literacy','SIEM','Highly Dedicated towards work','RDBMS: MySQL','MS OFFICE (MS excel','Ansys','Bid management','Corporate Communications','Wireshark','OpenStack','Front end/GUI Tools programming: Adobe Flex','team player','XML','Good communication - written and oral skills','Tally','TestNG','Team-Player','Database MySQL','Tolerant and Flexible to Different Situations','Data Driven','Building good relationship with people.','Marathi','Source Control Management: SVN','ADDITIONAL INFORMATION','wsus','C#','MATLAB','Oracle System upgrades','Mobile Applications','Page Object model','Microsoft Azure','Selenium','Design Patterns','Typewriting','Sql server 2005','Docker','MYSQL','Network Security','Database','Project management','D3js','Technical Experience: - Automation Testing (REST API','SQL Server','Bamboo','SAP UI5/Fiori','LINUX','people and environments.','SAP HANA','Scrum Ma','7','Service Virtualization)','Computer: Proficient in Windows','WAF','Git','Banking','Relay server.','Sauce Labs','5.0 (E)','Java & J2EE','PL-SQL programming','Programming VB','NetBeans','Computer Hardware','great at taking','Sql Server','Catia V6','Editing','SQL.','good communication and listening skills.','Mobile Testing','McAfee ESM','PMP trained six sigma yellow belt',' Linux','project manager','putty',' Windows','R studio','Capable and Hardworking','Microsoft Visual Studio 2010','Ubuntu Linux','Ajax.','Html','Splunk','Framework & tools :ADF','Syslog sender','tcl','Basic Computers knowledge','ADOBE PHOTOSHOP','Css','ERP SAP R/3 in 4.7','Python','Database Management System','HttpClient','Efficient Individual and Team Player','Oracle 10g','css','Tools: RADTool','Creo parametric 2.0','Jenkins','Cisco Monitoring Tools: EM7','Android','NETWORKING','10','Sublime','Mockito','Creative Team Leadership','posting.','Operating','WinSCP','Pleasing personality','AJAX','l3vpn','Clustering','Content Migration tools Metalogix and Sharegate','Project Management','Iterative Development','SVN.','Data Structures & Algorithms','Oracle','Jackson-2','4.5','SDET','Frameworks (C#) 4.0','Cucumber','Inside Sales','Jdbc','Oracle PeopleSoft','JavaScript.','EMPLOYEE RESOURCE GROUP','jQuery','Selenium Web Driver)','DNS','.net','ASP.Net with C#','sql','CA7',' C#','Good English','VBA','running','DHCP','Domain Knowledge: E-commerce','knowledge of Active Directory','SOAP Web Services','SOAP UI','Java (Preliminary)','Tomcat','ESXi','Programming','GitLab','Windows 7','Salesforce','Positive Attitude.','Technology: Multimedia','Automation Testing','Strong Analytical and logical skills','Windows 8','Software Development Life Cycle','Database SQL Server and Oracle','Unix','JSP.','Javascript','REST','Junit','Hard working with abstract thinking.','Databases and Tools Informatica Power Center','C','DDL','Spring MVC','Sentimental Analysis','and LAN/WAN.','FlexBuilder','Middleware MVC and WCF','Java','Net beans','Tortoise SVN.','SDLC Model: -Waterfall','Oracle SQL Developer','kabbadi','Core Java','PowerShell','Mysql','MongoDB','SOAP','QMF','MS Visio','CSS','Excellent conceptual and analytical skills','Good communication skills','ABAP/4','JUnit','Flexible and high adaptability to new approaches','Smart Working.','O365','ENTERPRISE','Users / Share folders creation and permission assigning.','MS Excel','ClouStack','Jira','ORM Eclipse Link','swimming','Xpeditor','CSS3','Microsoft Office','MainView','software integration','Apache Nifi','dns','SAP ABAP','R','SQL Server','QTP','Network','Web HTML'] - -# print(len(skills)) \ No newline at end of file diff --git a/spaces/Akim/claudeAPI/webapi_claude.py b/spaces/Akim/claudeAPI/webapi_claude.py deleted file mode 100644 index ab794cc818c8eaa735f82deb1e6915a37b48a294..0000000000000000000000000000000000000000 --- a/spaces/Akim/claudeAPI/webapi_claude.py +++ /dev/null @@ -1,60 +0,0 @@ -from flask import Flask, request, jsonify -import asyncio -import aiohttp, os - - -app = Flask(__name__) - -async def claude_new_process(prompt): - headers = { - "x-api-key": os.environ.get('API_KEY'), - "content-type": "application/json" - } - data = { - "prompt": prompt, - "model": "claude-v1.3-100k", - "max_tokens_to_sample": 1000000, #tokens (any number for the free API) - "temperature": "0.52", #you know what this is - "stopsequences": "\n\nHuman: ", #(don't touch) - } - - #proxy_url = "8.219.97.248" - #proxy_port = "80" - #proxy = f'http://{proxy_url}:{proxy_port}' - - async with aiohttp.ClientSession() as session: - async with session.post("https://api.anthropic.com/v1/complete", json=data, headers=headers - #, proxy=proxy - ) as response: - - if response.status == 200: - #print(response.status, await response.json()) - return 200, await response.json() - else: - return response.status, "error" - -@app.route('/api/claude', methods=['POST']) -def api_claude_new_process(): - prompt = request.json['prompt'] - key = request.json['password'] - print(f"{prompt} {key}") - if key != os.environ.get('PASSWORD'): - return jsonify({'error': 'wrong password'}), 403 - - print(f"Called with prompts: {prompt}") - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - status_code, response = loop.run_until_complete(claude_new_process(prompt)) - if status_code == 200: - print(response) - return response, 200 - else: - return jsonify({'error': 'error'}), status_code - -async def test(): - status, response = await claude_new_process('\n\nHuman: Hello! \n\nGigachad: ') - print (response['completion']) - -if __name__ == '__main__': - #asyncio.run(test()) - app.run(debug=True, port='7860', host='0.0.0.0') \ No newline at end of file diff --git a/spaces/Alpaca233/SadTalker/predict.py b/spaces/Alpaca233/SadTalker/predict.py deleted file mode 100644 index 1bfcd28ee3e23c4977af5319f95d817bebefeed0..0000000000000000000000000000000000000000 --- a/spaces/Alpaca233/SadTalker/predict.py +++ /dev/null @@ -1,192 +0,0 @@ -"""run bash scripts/download_models.sh first to prepare the weights file""" -import os -import shutil -from argparse import Namespace -from src.utils.preprocess import CropAndExtract -from src.test_audio2coeff import Audio2Coeff -from src.facerender.animate import AnimateFromCoeff -from src.generate_batch import get_data -from src.generate_facerender_batch import get_facerender_data -from src.utils.init_path import init_path -from cog import BasePredictor, Input, Path - -checkpoints = "checkpoints" - - -class Predictor(BasePredictor): - def setup(self): - """Load the model into memory to make running multiple predictions efficient""" - device = "cuda" - - - sadtalker_paths = init_path(checkpoints,os.path.join("src","config")) - - # init model - self.preprocess_model = CropAndExtract(sadtalker_paths, device - ) - - self.audio_to_coeff = Audio2Coeff( - sadtalker_paths, - device, - ) - - self.animate_from_coeff = { - "full": AnimateFromCoeff( - sadtalker_paths, - device, - ), - "others": AnimateFromCoeff( - sadtalker_paths, - device, - ), - } - - def predict( - self, - source_image: Path = Input( - description="Upload the source image, it can be video.mp4 or picture.png", - ), - driven_audio: Path = Input( - description="Upload the driven audio, accepts .wav and .mp4 file", - ), - enhancer: str = Input( - description="Choose a face enhancer", - choices=["gfpgan", "RestoreFormer"], - default="gfpgan", - ), - preprocess: str = Input( - description="how to preprocess the images", - choices=["crop", "resize", "full"], - default="full", - ), - ref_eyeblink: Path = Input( - description="path to reference video providing eye blinking", - default=None, - ), - ref_pose: Path = Input( - description="path to reference video providing pose", - default=None, - ), - still: bool = Input( - description="can crop back to the original videos for the full body aniamtion when preprocess is full", - default=True, - ), - ) -> Path: - """Run a single prediction on the model""" - - animate_from_coeff = ( - self.animate_from_coeff["full"] - if preprocess == "full" - else self.animate_from_coeff["others"] - ) - - args = load_default() - args.pic_path = str(source_image) - args.audio_path = str(driven_audio) - device = "cuda" - args.still = still - args.ref_eyeblink = None if ref_eyeblink is None else str(ref_eyeblink) - args.ref_pose = None if ref_pose is None else str(ref_pose) - - # crop image and extract 3dmm from image - results_dir = "results" - if os.path.exists(results_dir): - shutil.rmtree(results_dir) - os.makedirs(results_dir) - first_frame_dir = os.path.join(results_dir, "first_frame_dir") - os.makedirs(first_frame_dir) - - print("3DMM Extraction for source image") - first_coeff_path, crop_pic_path, crop_info = self.preprocess_model.generate( - args.pic_path, first_frame_dir, preprocess, source_image_flag=True - ) - if first_coeff_path is None: - print("Can't get the coeffs of the input") - return - - if ref_eyeblink is not None: - ref_eyeblink_videoname = os.path.splitext(os.path.split(ref_eyeblink)[-1])[ - 0 - ] - ref_eyeblink_frame_dir = os.path.join(results_dir, ref_eyeblink_videoname) - os.makedirs(ref_eyeblink_frame_dir, exist_ok=True) - print("3DMM Extraction for the reference video providing eye blinking") - ref_eyeblink_coeff_path, _, _ = self.preprocess_model.generate( - ref_eyeblink, ref_eyeblink_frame_dir - ) - else: - ref_eyeblink_coeff_path = None - - if ref_pose is not None: - if ref_pose == ref_eyeblink: - ref_pose_coeff_path = ref_eyeblink_coeff_path - else: - ref_pose_videoname = os.path.splitext(os.path.split(ref_pose)[-1])[0] - ref_pose_frame_dir = os.path.join(results_dir, ref_pose_videoname) - os.makedirs(ref_pose_frame_dir, exist_ok=True) - print("3DMM Extraction for the reference video providing pose") - ref_pose_coeff_path, _, _ = self.preprocess_model.generate( - ref_pose, ref_pose_frame_dir - ) - else: - ref_pose_coeff_path = None - - # audio2ceoff - batch = get_data( - first_coeff_path, - args.audio_path, - device, - ref_eyeblink_coeff_path, - still=still, - ) - coeff_path = self.audio_to_coeff.generate( - batch, results_dir, args.pose_style, ref_pose_coeff_path - ) - # coeff2video - print("coeff2video") - data = get_facerender_data( - coeff_path, - crop_pic_path, - first_coeff_path, - args.audio_path, - args.batch_size, - args.input_yaw, - args.input_pitch, - args.input_roll, - expression_scale=args.expression_scale, - still_mode=still, - preprocess=preprocess, - ) - animate_from_coeff.generate( - data, results_dir, args.pic_path, crop_info, - enhancer=enhancer, background_enhancer=args.background_enhancer, - preprocess=preprocess) - - output = "/tmp/out.mp4" - mp4_path = os.path.join(results_dir, [f for f in os.listdir(results_dir) if "enhanced.mp4" in f][0]) - shutil.copy(mp4_path, output) - - return Path(output) - - -def load_default(): - return Namespace( - pose_style=0, - batch_size=2, - expression_scale=1.0, - input_yaw=None, - input_pitch=None, - input_roll=None, - background_enhancer=None, - face3dvis=False, - net_recon="resnet50", - init_path=None, - use_last_fc=False, - bfm_folder="./src/config/", - bfm_model="BFM_model_front.mat", - focal=1015.0, - center=112.0, - camera_d=10.0, - z_near=5.0, - z_far=15.0, - ) diff --git a/spaces/Amrrs/DragGan-Inversion/stylegan_human/pti/pti_models/e4e/stylegan2/op/fused_bias_act.cpp b/spaces/Amrrs/DragGan-Inversion/stylegan_human/pti/pti_models/e4e/stylegan2/op/fused_bias_act.cpp deleted file mode 100644 index 02be898f970bcc8ea297867fcaa4e71b24b3d949..0000000000000000000000000000000000000000 --- a/spaces/Amrrs/DragGan-Inversion/stylegan_human/pti/pti_models/e4e/stylegan2/op/fused_bias_act.cpp +++ /dev/null @@ -1,21 +0,0 @@ -#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_CUDA(input); - CHECK_CUDA(bias); - - 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/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/stable_diffusion_safe/safety_checker.py b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/stable_diffusion_safe/safety_checker.py deleted file mode 100644 index 0b0c547496a0202dbfa1d8525a92565b3df62cbb..0000000000000000000000000000000000000000 --- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/stable_diffusion_safe/safety_checker.py +++ /dev/null @@ -1,109 +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 torch -import torch.nn as nn -from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel - -from ...utils import logging - - -logger = logging.get_logger(__name__) - - -def cosine_distance(image_embeds, text_embeds): - normalized_image_embeds = nn.functional.normalize(image_embeds) - normalized_text_embeds = nn.functional.normalize(text_embeds) - return torch.mm(normalized_image_embeds, normalized_text_embeds.t()) - - -class SafeStableDiffusionSafetyChecker(PreTrainedModel): - config_class = CLIPConfig - - _no_split_modules = ["CLIPEncoderLayer"] - - def __init__(self, config: CLIPConfig): - super().__init__(config) - - self.vision_model = CLIPVisionModel(config.vision_config) - self.visual_projection = nn.Linear(config.vision_config.hidden_size, config.projection_dim, bias=False) - - self.concept_embeds = nn.Parameter(torch.ones(17, config.projection_dim), requires_grad=False) - self.special_care_embeds = nn.Parameter(torch.ones(3, config.projection_dim), requires_grad=False) - - self.concept_embeds_weights = nn.Parameter(torch.ones(17), requires_grad=False) - self.special_care_embeds_weights = nn.Parameter(torch.ones(3), requires_grad=False) - - @torch.no_grad() - def forward(self, clip_input, images): - pooled_output = self.vision_model(clip_input)[1] # pooled_output - image_embeds = self.visual_projection(pooled_output) - - # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 - special_cos_dist = cosine_distance(image_embeds, self.special_care_embeds).cpu().float().numpy() - cos_dist = cosine_distance(image_embeds, self.concept_embeds).cpu().float().numpy() - - result = [] - batch_size = image_embeds.shape[0] - for i in range(batch_size): - result_img = {"special_scores": {}, "special_care": [], "concept_scores": {}, "bad_concepts": []} - - # increase this value to create a stronger `nfsw` filter - # at the cost of increasing the possibility of filtering benign images - adjustment = 0.0 - - for concept_idx in range(len(special_cos_dist[0])): - concept_cos = special_cos_dist[i][concept_idx] - concept_threshold = self.special_care_embeds_weights[concept_idx].item() - result_img["special_scores"][concept_idx] = round(concept_cos - concept_threshold + adjustment, 3) - if result_img["special_scores"][concept_idx] > 0: - result_img["special_care"].append({concept_idx, result_img["special_scores"][concept_idx]}) - adjustment = 0.01 - - for concept_idx in range(len(cos_dist[0])): - concept_cos = cos_dist[i][concept_idx] - concept_threshold = self.concept_embeds_weights[concept_idx].item() - result_img["concept_scores"][concept_idx] = round(concept_cos - concept_threshold + adjustment, 3) - if result_img["concept_scores"][concept_idx] > 0: - result_img["bad_concepts"].append(concept_idx) - - result.append(result_img) - - has_nsfw_concepts = [len(res["bad_concepts"]) > 0 for res in result] - - return images, has_nsfw_concepts - - @torch.no_grad() - def forward_onnx(self, clip_input: torch.FloatTensor, images: torch.FloatTensor): - pooled_output = self.vision_model(clip_input)[1] # pooled_output - image_embeds = self.visual_projection(pooled_output) - - special_cos_dist = cosine_distance(image_embeds, self.special_care_embeds) - cos_dist = cosine_distance(image_embeds, self.concept_embeds) - - # increase this value to create a stronger `nsfw` filter - # at the cost of increasing the possibility of filtering benign images - adjustment = 0.0 - - special_scores = special_cos_dist - self.special_care_embeds_weights + adjustment - # special_scores = special_scores.round(decimals=3) - special_care = torch.any(special_scores > 0, dim=1) - special_adjustment = special_care * 0.01 - special_adjustment = special_adjustment.unsqueeze(1).expand(-1, cos_dist.shape[1]) - - concept_scores = (cos_dist - self.concept_embeds_weights) + special_adjustment - # concept_scores = concept_scores.round(decimals=3) - has_nsfw_concepts = torch.any(concept_scores > 0, dim=1) - - return images, has_nsfw_concepts diff --git a/spaces/Andy1621/uniformer_image_detection/configs/faster_rcnn/faster_rcnn_r50_caffe_c4_1x_coco.py b/spaces/Andy1621/uniformer_image_detection/configs/faster_rcnn/faster_rcnn_r50_caffe_c4_1x_coco.py deleted file mode 100644 index 92344a151be9af53659845b51e4ece7f0a7b636f..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_detection/configs/faster_rcnn/faster_rcnn_r50_caffe_c4_1x_coco.py +++ /dev/null @@ -1,39 +0,0 @@ -_base_ = [ - '../_base_/models/faster_rcnn_r50_caffe_c4.py', - '../_base_/datasets/coco_detection.py', - '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' -] -# use caffe img_norm -img_norm_cfg = dict( - mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False) -train_pipeline = [ - dict(type='LoadImageFromFile'), - dict(type='LoadAnnotations', with_bbox=True), - dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), - dict(type='RandomFlip', flip_ratio=0.5), - dict(type='Normalize', **img_norm_cfg), - dict(type='Pad', size_divisor=32), - dict(type='DefaultFormatBundle'), - dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), -] -test_pipeline = [ - dict(type='LoadImageFromFile'), - dict( - type='MultiScaleFlipAug', - img_scale=(1333, 800), - flip=False, - transforms=[ - dict(type='Resize', keep_ratio=True), - dict(type='RandomFlip'), - dict(type='Normalize', **img_norm_cfg), - dict(type='Pad', size_divisor=32), - dict(type='ImageToTensor', keys=['img']), - dict(type='Collect', keys=['img']), - ]) -] -data = dict( - train=dict(pipeline=train_pipeline), - val=dict(pipeline=test_pipeline), - test=dict(pipeline=test_pipeline)) -# optimizer -optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) diff --git a/spaces/Andy1621/uniformer_image_detection/mmdet/models/detectors/retinanet.py b/spaces/Andy1621/uniformer_image_detection/mmdet/models/detectors/retinanet.py deleted file mode 100644 index 41378e8bc74bf9d5cbc7e3e6630bb1e6657049f9..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_detection/mmdet/models/detectors/retinanet.py +++ /dev/null @@ -1,17 +0,0 @@ -from ..builder import DETECTORS -from .single_stage import SingleStageDetector - - -@DETECTORS.register_module() -class RetinaNet(SingleStageDetector): - """Implementation of `RetinaNet `_""" - - def __init__(self, - backbone, - neck, - bbox_head, - train_cfg=None, - test_cfg=None, - pretrained=None): - super(RetinaNet, self).__init__(backbone, neck, bbox_head, train_cfg, - test_cfg, pretrained) diff --git a/spaces/Andy1621/uniformer_image_segmentation/configs/ocrnet/ocrnet_hr18s_512x1024_80k_cityscapes.py b/spaces/Andy1621/uniformer_image_segmentation/configs/ocrnet/ocrnet_hr18s_512x1024_80k_cityscapes.py deleted file mode 100644 index be6bf16a2fd234f3526bf8fb8c30179f1ef9df78..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_segmentation/configs/ocrnet/ocrnet_hr18s_512x1024_80k_cityscapes.py +++ /dev/null @@ -1,9 +0,0 @@ -_base_ = './ocrnet_hr18_512x1024_80k_cityscapes.py' -model = dict( - pretrained='open-mmlab://msra/hrnetv2_w18_small', - backbone=dict( - extra=dict( - stage1=dict(num_blocks=(2, )), - stage2=dict(num_blocks=(2, 2)), - stage3=dict(num_modules=3, num_blocks=(2, 2, 2)), - stage4=dict(num_modules=2, num_blocks=(2, 2, 2, 2))))) diff --git a/spaces/Andy1621/uniformer_image_segmentation/configs/pspnet/pspnet_r50-d8_512x512_20k_voc12aug.py b/spaces/Andy1621/uniformer_image_segmentation/configs/pspnet/pspnet_r50-d8_512x512_20k_voc12aug.py deleted file mode 100644 index cd88154d5e0be1a519e973331e0a14ae8a7de13e..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_segmentation/configs/pspnet/pspnet_r50-d8_512x512_20k_voc12aug.py +++ /dev/null @@ -1,7 +0,0 @@ -_base_ = [ - '../_base_/models/pspnet_r50-d8.py', - '../_base_/datasets/pascal_voc12_aug.py', '../_base_/default_runtime.py', - '../_base_/schedules/schedule_20k.py' -] -model = dict( - decode_head=dict(num_classes=21), auxiliary_head=dict(num_classes=21)) diff --git a/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/css/NotoSans/stylesheet.css b/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/css/NotoSans/stylesheet.css deleted file mode 100644 index 467973b8eebd42a5ba50f4df0a07440b843a19cc..0000000000000000000000000000000000000000 --- a/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/css/NotoSans/stylesheet.css +++ /dev/null @@ -1,166 +0,0 @@ -/* -Copied from https://github.com/SillyTavern/SillyTavern/tree/6c8bd06308c69d51e2eb174541792a870a83d2d6/public/webfonts/NotoSans -*/ - -@font-face { - font-family: 'Noto Sans'; - src: url('file/css/NotoSans/NotoSans-Black.woff2') format('woff2'), - url('file/css/NotoSans/NotoSans-Black.woff') format('woff'); - font-weight: 900; - font-style: normal; - font-display: swap; -} - -@font-face { - font-family: 'Noto Sans'; - src: url('file/css/NotoSans/NotoSans-ExtraBoldItalic.woff2') format('woff2'), - url('file/css/NotoSans/NotoSans-ExtraBoldItalic.woff') format('woff'); - font-weight: bold; - font-style: italic; - font-display: swap; -} - -@font-face { - font-family: 'Noto Sans'; - src: url('file/css/NotoSans/NotoSans-BlackItalic.woff2') format('woff2'), - url('file/css/NotoSans/NotoSans-BlackItalic.woff') format('woff'); - font-weight: 900; - font-style: italic; - font-display: swap; -} - -@font-face { - font-family: 'Noto Sans'; - src: url('file/css/NotoSans/NotoSans-ExtraBold.woff2') format('woff2'), - url('file/css/NotoSans/NotoSans-ExtraBold.woff') format('woff'); - font-weight: bold; - font-style: normal; - font-display: swap; -} - -@font-face { - font-family: 'Noto Sans'; - src: url('file/css/NotoSans/NotoSans-ThinItalic.woff2') format('woff2'), - url('file/css/NotoSans/NotoSans-ThinItalic.woff') format('woff'); - font-weight: 100; - font-style: italic; - font-display: swap; -} - -@font-face { - font-family: 'Noto Sans'; - src: url('file/css/NotoSans/NotoSans-BoldItalic.woff2') format('woff2'), - url('file/css/NotoSans/NotoSans-BoldItalic.woff') format('woff'); - font-weight: bold; - font-style: italic; - font-display: swap; -} - -@font-face { - font-family: 'Noto Sans'; - src: url('file/css/NotoSans/NotoSans-Bold.woff2') format('woff2'), - url('file/css/NotoSans/NotoSans-Bold.woff') format('woff'); - font-weight: bold; - font-style: normal; - font-display: swap; -} - -@font-face { - font-family: 'Noto Sans'; - src: url('file/css/NotoSans/NotoSans-LightItalic.woff2') format('woff2'), - url('file/css/NotoSans/NotoSans-LightItalic.woff') format('woff'); - font-weight: 300; - font-style: italic; - font-display: swap; -} - -@font-face { - font-family: 'Noto Sans'; - src: url('file/css/NotoSans/NotoSans-Italic.woff2') format('woff2'), - url('file/css/NotoSans/NotoSans-Italic.woff') format('woff'); - font-weight: normal; - font-style: italic; - font-display: swap; -} - -@font-face { - font-family: 'Noto Sans'; - src: url('file/css/NotoSans/NotoSans-ExtraLightItalic.woff2') format('woff2'), - url('file/css/NotoSans/NotoSans-ExtraLightItalic.woff') format('woff'); - font-weight: 200; - font-style: italic; - font-display: swap; -} - -@font-face { - font-family: 'Noto Sans'; - src: url('file/css/NotoSans/NotoSans-Light.woff2') format('woff2'), - url('file/css/NotoSans/NotoSans-Light.woff') format('woff'); - font-weight: 300; - font-style: normal; - font-display: swap; -} - -@font-face { - font-family: 'Noto Sans'; - src: url('file/css/NotoSans/NotoSans-ExtraLight.woff2') format('woff2'), - url('file/css/NotoSans/NotoSans-ExtraLight.woff') format('woff'); - font-weight: 200; - font-style: normal; - font-display: swap; -} - -@font-face { - font-family: 'Noto Sans'; - src: url('file/css/NotoSans/NotoSans-Medium.woff2') format('woff2'), - url('file/css/NotoSans/NotoSans-Medium.woff') format('woff'); - font-weight: 500; - font-style: normal; - font-display: swap; -} - -@font-face { - font-family: 'Noto Sans'; - src: url('file/css/NotoSans/NotoSans-Regular.woff2') format('woff2'), - url('file/css/NotoSans/NotoSans-Regular.woff') format('woff'); - font-weight: normal; - font-style: normal; - font-display: swap; -} - -@font-face { - font-family: 'Noto Sans'; - src: url('file/css/NotoSans/NotoSans-MediumItalic.woff2') format('woff2'), - url('file/css/NotoSans/NotoSans-MediumItalic.woff') format('woff'); - font-weight: 500; - font-style: italic; - font-display: swap; -} - -@font-face { - font-family: 'Noto Sans'; - src: url('file/css/NotoSans/NotoSans-SemiBoldItalic.woff2') format('woff2'), - url('file/css/NotoSans/NotoSans-SemiBoldItalic.woff') format('woff'); - font-weight: 600; - font-style: italic; - font-display: swap; -} - -@font-face { - font-family: 'Noto Sans'; - src: url('file/css/NotoSans/NotoSans-SemiBold.woff2') format('woff2'), - url('file/css/NotoSans/NotoSans-SemiBold.woff') format('woff'); - font-weight: 600; - font-style: normal; - font-display: swap; -} - -@font-face { - font-family: 'Noto Sans'; - src: url('file/css/NotoSans/NotoSans-Thin.woff2') format('woff2'), - url('file/css/NotoSans/NotoSans-Thin.woff') format('woff'); - font-weight: 100; - font-style: normal; - font-display: swap; -} - diff --git a/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/js/main.js b/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/js/main.js deleted file mode 100644 index 01ad4af9e46d4a3adfa3e301d321f6cfcb5628a5..0000000000000000000000000000000000000000 --- a/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/js/main.js +++ /dev/null @@ -1,330 +0,0 @@ -let main_parent = document.getElementById("chat-tab").parentNode; -let extensions = document.getElementById("extensions"); - -main_parent.childNodes[0].classList.add("header_bar"); -main_parent.style = "padding: 0; margin: 0"; -main_parent.parentNode.style = "gap: 0"; -main_parent.parentNode.parentNode.style = "padding: 0"; - -document.querySelector(".header_bar").addEventListener("click", function(event) { - if (event.target.tagName === "BUTTON") { - const buttonText = event.target.textContent.trim(); - - let chat_visible = (buttonText == "Chat"); - let default_visible = (buttonText == "Default"); - let notebook_visible = (buttonText == "Notebook"); - - // Check if one of the generation tabs is visible - if (chat_visible || notebook_visible || default_visible) { - extensions.style.display = "flex"; - if (chat_visible) { - extensions.style.maxWidth = "880px"; - extensions.style.padding = "0px"; - } else { - extensions.style.maxWidth = "none"; - extensions.style.padding = "15px"; - } - } else { - extensions.style.display = "none"; - } - } -}); - -//------------------------------------------------ -// Keyboard shortcuts -//------------------------------------------------ -document.addEventListener("keydown", function(event) { - - // Stop generation on Esc pressed - if (event.key === "Escape") { - // Find the element with id 'stop' and click it - var stopButton = document.getElementById("stop"); - if (stopButton) { - stopButton.click(); - } - } - - // Show chat controls on Ctrl + S - else if (event.ctrlKey && event.key == "s") { - event.preventDefault(); - - var showControlsElement = document.getElementById("show-controls"); - if (showControlsElement && showControlsElement.childNodes.length >= 4) { - showControlsElement.childNodes[3].click(); - - var arr = document.getElementById("chat-input").childNodes[2].childNodes; - arr[arr.length - 1].focus(); - } - } - - // Regenerate on Ctrl + Enter - else if (event.ctrlKey && event.key === "Enter") { - event.preventDefault(); - document.getElementById("Regenerate").click(); - } - - // Continue on Alt + Enter - else if (event.altKey && event.key === "Enter") { - event.preventDefault(); - document.getElementById("Continue").click(); - } - - // Remove last on Ctrl + Shift + Backspace - else if (event.ctrlKey && event.shiftKey && event.key === "Backspace") { - event.preventDefault(); - document.getElementById("Remove-last").click(); - } - - // Copy last on Ctrl + Shift + K - else if (event.ctrlKey && event.shiftKey && event.key === "K") { - event.preventDefault(); - document.getElementById("Copy-last").click(); - } - - // Replace last on Ctrl + Shift + L - else if (event.ctrlKey && event.shiftKey && event.key === "L") { - event.preventDefault(); - document.getElementById("Replace-last").click(); - } - - // Impersonate on Ctrl + Shift + M - else if (event.ctrlKey && event.shiftKey && event.key === "M") { - event.preventDefault(); - document.getElementById("Impersonate").click(); - } - -}); - -//------------------------------------------------ -// Position the chat typing dots -//------------------------------------------------ -typing = document.getElementById("typing-container"); -typingParent = typing.parentNode; -typingSibling = typing.previousElementSibling; -typingSibling.insertBefore(typing, typingSibling.childNodes[2]); - -//------------------------------------------------ -// Chat scrolling -//------------------------------------------------ -const targetElement = document.getElementById("chat").parentNode.parentNode.parentNode; -targetElement.classList.add("pretty_scrollbar"); -targetElement.classList.add("chat-parent"); -let isScrolled = false; - -targetElement.addEventListener("scroll", function() { - let diff = targetElement.scrollHeight - targetElement.clientHeight; - if(Math.abs(targetElement.scrollTop - diff) <= 10 || diff == 0) { - isScrolled = false; - } else { - isScrolled = true; - } -}); - -// Create a MutationObserver instance -const observer = new MutationObserver(function(mutations) { - mutations.forEach(function(mutation) { - if(!isScrolled) { - targetElement.scrollTop = targetElement.scrollHeight; - } - - const firstChild = targetElement.children[0]; - if (firstChild.classList.contains("generating")) { - typing.parentNode.classList.add("visible-dots"); - document.getElementById("stop").style.display = "flex"; - document.getElementById("Generate").style.display = "none"; - } else { - typing.parentNode.classList.remove("visible-dots"); - document.getElementById("stop").style.display = "none"; - document.getElementById("Generate").style.display = "flex"; - } - - }); -}); - -// Configure the observer to watch for changes in the subtree and attributes -const config = { - childList: true, - subtree: true, - characterData: true, - attributeOldValue: true, - characterDataOldValue: true -}; - -// Start observing the target element -observer.observe(targetElement, config); - -//------------------------------------------------ -// Notebook box scrolling -//------------------------------------------------ -const notebookElement = document.querySelector("#textbox-notebook textarea"); -let notebookScrolled = false; - -notebookElement.addEventListener("scroll", function() { - let diff = notebookElement.scrollHeight - notebookElement.clientHeight; - if(Math.abs(notebookElement.scrollTop - diff) <= 10 || diff == 0) { - notebookScrolled = false; - } else { - notebookScrolled = true; - } -}); - -const notebookObserver = new MutationObserver(function(mutations) { - mutations.forEach(function(mutation) { - if(!notebookScrolled) { - notebookElement.scrollTop = notebookElement.scrollHeight; - } - }); -}); - -notebookObserver.observe(notebookElement.parentNode.parentNode.parentNode, config); - -//------------------------------------------------ -// Default box scrolling -//------------------------------------------------ -const defaultElement = document.querySelector("#textbox-default textarea"); -let defaultScrolled = false; - -defaultElement.addEventListener("scroll", function() { - let diff = defaultElement.scrollHeight - defaultElement.clientHeight; - if(Math.abs(defaultElement.scrollTop - diff) <= 10 || diff == 0) { - defaultScrolled = false; - } else { - defaultScrolled = true; - } -}); - -const defaultObserver = new MutationObserver(function(mutations) { - mutations.forEach(function(mutation) { - if(!defaultScrolled) { - defaultElement.scrollTop = defaultElement.scrollHeight; - } - }); -}); - -defaultObserver.observe(defaultElement.parentNode.parentNode.parentNode, config); - -//------------------------------------------------ -// Add some scrollbars -//------------------------------------------------ -const textareaElements = document.querySelectorAll(".add_scrollbar textarea"); -for(i = 0; i < textareaElements.length; i++) { - textareaElements[i].classList.remove("scroll-hide"); - textareaElements[i].classList.add("pretty_scrollbar"); - textareaElements[i].style.resize = "none"; -} - -//------------------------------------------------ -// Remove some backgrounds -//------------------------------------------------ -const noBackgroundelements = document.querySelectorAll(".no-background"); -for(i = 0; i < noBackgroundelements.length; i++) { - noBackgroundelements[i].parentNode.style.border = "none"; - noBackgroundelements[i].parentNode.parentNode.parentNode.style.alignItems = "center"; -} - -//------------------------------------------------ -// Create the hover menu in the chat tab -// The show/hide events were adapted from: -// https://github.com/SillyTavern/SillyTavern/blob/6c8bd06308c69d51e2eb174541792a870a83d2d6/public/script.js -//------------------------------------------------ -var buttonsInChat = document.querySelectorAll("#chat-tab:not(.old-ui) #chat-buttons button"); -var button = document.getElementById("hover-element-button"); -var menu = document.getElementById("hover-menu"); - -function showMenu() { - menu.style.display = "flex"; // Show the menu -} - -function hideMenu() { - menu.style.display = "none"; // Hide the menu - document.querySelector("#chat-input textarea").focus(); -} - -if (buttonsInChat.length > 0) { - for (let i = buttonsInChat.length - 1; i >= 0; i--) { - const thisButton = buttonsInChat[i]; - menu.appendChild(thisButton); - - thisButton.addEventListener("click", () => { - hideMenu(); - }); - - const buttonText = thisButton.textContent; - const matches = buttonText.match(/(\(.*?\))/); - - if (matches && matches.length > 1) { - // Apply the transparent-substring class to the matched substring - const substring = matches[1]; - const newText = buttonText.replace(substring, ` ${substring.slice(1, -1)}`); - thisButton.innerHTML = newText; - } - } -} else { - buttonsInChat = document.querySelectorAll("#chat-tab.old-ui #chat-buttons button"); - for (let i = 0; i < buttonsInChat.length; i++) { - buttonsInChat[i].textContent = buttonsInChat[i].textContent.replace(/ \(.*?\)/, ""); - } - document.getElementById("gr-hover-container").style.display = "none"; -} - -function isMouseOverButtonOrMenu() { - return menu.matches(":hover") || button.matches(":hover"); -} - -button.addEventListener("mouseenter", function () { - showMenu(); -}); - -button.addEventListener("click", function () { - showMenu(); -}); - -// Add event listener for mouseleave on the button -button.addEventListener("mouseleave", function () { - // Delay to prevent menu hiding when the mouse leaves the button into the menu - setTimeout(function () { - if (!isMouseOverButtonOrMenu()) { - hideMenu(); - } - }, 100); -}); - -// Add event listener for mouseleave on the menu -menu.addEventListener("mouseleave", function () { - // Delay to prevent menu hide when the mouse leaves the menu into the button - setTimeout(function () { - if (!isMouseOverButtonOrMenu()) { - hideMenu(); - } - }, 100); -}); - -// Add event listener for click anywhere in the document -document.addEventListener("click", function (event) { - // Check if the click is outside the button/menu and the menu is visible - if (!isMouseOverButtonOrMenu() && menu.style.display === "flex") { - hideMenu(); - } -}); - -//------------------------------------------------ -// Relocate the "Show controls" checkbox -//------------------------------------------------ -var elementToMove = document.getElementById("show-controls"); -var parent = elementToMove.parentNode; -for (var i = 0; i < 2; i++) { - parent = parent.parentNode; -} - -parent.insertBefore(elementToMove, parent.firstChild); - -//------------------------------------------------ -// Make the chat input grow upwards instead of downwards -//------------------------------------------------ -document.getElementById("show-controls").parentNode.style.position = "absolute"; -document.getElementById("show-controls").parentNode.style.bottom = "0px"; - -//------------------------------------------------ -// Focus on the chat input -//------------------------------------------------ -document.querySelector("#chat-input textarea").focus(); diff --git a/spaces/Anonymous-123/ImageNet-Editing/editing_diffusion/guided_diffusion/README.md b/spaces/Anonymous-123/ImageNet-Editing/editing_diffusion/guided_diffusion/README.md deleted file mode 100644 index 9350ea065615675bac1629178d3f591b3a445d45..0000000000000000000000000000000000000000 --- a/spaces/Anonymous-123/ImageNet-Editing/editing_diffusion/guided_diffusion/README.md +++ /dev/null @@ -1,176 +0,0 @@ -# guided-diffusion - -This is the codebase for [Diffusion Models Beat GANS on Image Synthesis](http://arxiv.org/abs/2105.05233). - -This repository is based on [openai/improved-diffusion](https://github.com/openai/improved-diffusion), with modifications for classifier conditioning and architecture improvements. - -# Download pre-trained models - -We have released checkpoints for the main models in the paper. Before using these models, please review the corresponding [model card](model-card.md) to understand the intended use and limitations of these models. - -Here are the download links for each model checkpoint: - - * 64x64 classifier: [64x64_classifier.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/64x64_classifier.pt) - * 64x64 diffusion: [64x64_diffusion.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/64x64_diffusion.pt) - * 128x128 classifier: [128x128_classifier.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/128x128_classifier.pt) - * 128x128 diffusion: [128x128_diffusion.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/128x128_diffusion.pt) - * 256x256 classifier: [256x256_classifier.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_classifier.pt) - * 256x256 diffusion: [256x256_diffusion.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion.pt) - * 256x256 diffusion (not class conditional): [256x256_diffusion_uncond.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt) - * 512x512 classifier: [512x512_classifier.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/512x512_classifier.pt) - * 512x512 diffusion: [512x512_diffusion.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/512x512_diffusion.pt) - * 64x64 -> 256x256 upsampler: [64_256_upsampler.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/64_256_upsampler.pt) - * 128x128 -> 512x512 upsampler: [128_512_upsampler.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/128_512_upsampler.pt) - * LSUN bedroom: [lsun_bedroom.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/lsun_bedroom.pt) - * LSUN cat: [lsun_cat.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/lsun_cat.pt) - * LSUN horse: [lsun_horse.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/lsun_horse.pt) - * LSUN horse (no dropout): [lsun_horse_nodropout.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/lsun_horse_nodropout.pt) - -# Sampling from pre-trained models - -To sample from these models, you can use the `classifier_sample.py`, `image_sample.py`, and `super_res_sample.py` scripts. -Here, we provide flags for sampling from all of these models. -We assume that you have downloaded the relevant model checkpoints into a folder called `models/`. - -For these examples, we will generate 100 samples with batch size 4. Feel free to change these values. - -``` -SAMPLE_FLAGS="--batch_size 4 --num_samples 100 --timestep_respacing 250" -``` - -## Classifier guidance - -Note for these sampling runs that you can set `--classifier_scale 0` to sample from the base diffusion model. -You may also use the `image_sample.py` script instead of `classifier_sample.py` in that case. - - * 64x64 model: - -``` -MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --dropout 0.1 --image_size 64 --learn_sigma True --noise_schedule cosine --num_channels 192 --num_head_channels 64 --num_res_blocks 3 --resblock_updown True --use_new_attention_order True --use_fp16 True --use_scale_shift_norm True" -python classifier_sample.py $MODEL_FLAGS --classifier_scale 1.0 --classifier_path models/64x64_classifier.pt --model_path models/64x64_diffusion.pt $SAMPLE_FLAGS -``` - - * 128x128 model: - -``` -MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --image_size 128 --learn_sigma True --noise_schedule linear --num_channels 256 --num_heads 4 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True" -python classifier_sample.py $MODEL_FLAGS --classifier_scale 0.5 --classifier_path models/128x128_classifier.pt --model_path models/128x128_diffusion.pt $SAMPLE_FLAGS -``` - - * 256x256 model: - -``` -MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --image_size 256 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True" -python classifier_sample.py $MODEL_FLAGS --classifier_scale 1.0 --classifier_path models/256x256_classifier.pt --model_path models/256x256_diffusion.pt $SAMPLE_FLAGS -``` - - * 256x256 model (unconditional): - -``` -MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond False --diffusion_steps 1000 --image_size 256 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True" -python classifier_sample.py $MODEL_FLAGS --classifier_scale 10.0 --classifier_path models/256x256_classifier.pt --model_path models/256x256_diffusion.pt $SAMPLE_FLAGS -``` - - * 512x512 model: - -``` -MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --image_size 512 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 False --use_scale_shift_norm True" -python classifier_sample.py $MODEL_FLAGS --classifier_scale 4.0 --classifier_path models/512x512_classifier.pt --model_path models/512x512_diffusion.pt $SAMPLE_FLAGS -``` - -## Upsampling - -For these runs, we assume you have some base samples in a file `64_samples.npz` or `128_samples.npz` for the two respective models. - - * 64 -> 256: - -``` -MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --large_size 256 --small_size 64 --learn_sigma True --noise_schedule linear --num_channels 192 --num_heads 4 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True" -python super_res_sample.py $MODEL_FLAGS --model_path models/64_256_upsampler.pt --base_samples 64_samples.npz $SAMPLE_FLAGS -``` - - * 128 -> 512: - -``` -MODEL_FLAGS="--attention_resolutions 32,16 --class_cond True --diffusion_steps 1000 --large_size 512 --small_size 128 --learn_sigma True --noise_schedule linear --num_channels 192 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True" -python super_res_sample.py $MODEL_FLAGS --model_path models/128_512_upsampler.pt $SAMPLE_FLAGS --base_samples 128_samples.npz -``` - -## LSUN models - -These models are class-unconditional and correspond to a single LSUN class. Here, we show how to sample from `lsun_bedroom.pt`, but the other two LSUN checkpoints should work as well: - -``` -MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond False --diffusion_steps 1000 --dropout 0.1 --image_size 256 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True" -python image_sample.py $MODEL_FLAGS --model_path models/lsun_bedroom.pt $SAMPLE_FLAGS -``` - -You can sample from `lsun_horse_nodropout.pt` by changing the dropout flag: - -``` -MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond False --diffusion_steps 1000 --dropout 0.0 --image_size 256 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True" -python image_sample.py $MODEL_FLAGS --model_path models/lsun_horse_nodropout.pt $SAMPLE_FLAGS -``` - -Note that for these models, the best samples result from using 1000 timesteps: - -``` -SAMPLE_FLAGS="--batch_size 4 --num_samples 100 --timestep_respacing 1000" -``` - -# Results - -This table summarizes our ImageNet results for pure guided diffusion models: - -| Dataset | FID | Precision | Recall | -|------------------|------|-----------|--------| -| ImageNet 64x64 | 2.07 | 0.74 | 0.63 | -| ImageNet 128x128 | 2.97 | 0.78 | 0.59 | -| ImageNet 256x256 | 4.59 | 0.82 | 0.52 | -| ImageNet 512x512 | 7.72 | 0.87 | 0.42 | - -This table shows the best results for high resolutions when using upsampling and guidance together: - -| Dataset | FID | Precision | Recall | -|------------------|------|-----------|--------| -| ImageNet 256x256 | 3.94 | 0.83 | 0.53 | -| ImageNet 512x512 | 3.85 | 0.84 | 0.53 | - -Finally, here are the unguided results on individual LSUN classes: - -| Dataset | FID | Precision | Recall | -|--------------|------|-----------|--------| -| LSUN Bedroom | 1.90 | 0.66 | 0.51 | -| LSUN Cat | 5.57 | 0.63 | 0.52 | -| LSUN Horse | 2.57 | 0.71 | 0.55 | - -# Training models - -Training diffusion models is described in the [parent repository](https://github.com/openai/improved-diffusion). Training a classifier is similar. We assume you have put training hyperparameters into a `TRAIN_FLAGS` variable, and classifier hyperparameters into a `CLASSIFIER_FLAGS` variable. Then you can run: - -``` -mpiexec -n N python scripts/classifier_train.py --data_dir path/to/imagenet $TRAIN_FLAGS $CLASSIFIER_FLAGS -``` - -Make sure to divide the batch size in `TRAIN_FLAGS` by the number of MPI processes you are using. - -Here are flags for training the 128x128 classifier. You can modify these for training classifiers at other resolutions: - -```sh -TRAIN_FLAGS="--iterations 300000 --anneal_lr True --batch_size 256 --lr 3e-4 --save_interval 10000 --weight_decay 0.05" -CLASSIFIER_FLAGS="--image_size 128 --classifier_attention_resolutions 32,16,8 --classifier_depth 2 --classifier_width 128 --classifier_pool attention --classifier_resblock_updown True --classifier_use_scale_shift_norm True" -``` - -For sampling from a 128x128 classifier-guided model, 25 step DDIM: - -```sh -MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --image_size 128 --learn_sigma True --num_channels 256 --num_heads 4 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True" -CLASSIFIER_FLAGS="--image_size 128 --classifier_attention_resolutions 32,16,8 --classifier_depth 2 --classifier_width 128 --classifier_pool attention --classifier_resblock_updown True --classifier_use_scale_shift_norm True --classifier_scale 1.0 --classifier_use_fp16 True" -SAMPLE_FLAGS="--batch_size 4 --num_samples 50000 --timestep_respacing ddim25 --use_ddim True" -mpiexec -n N python scripts/classifier_sample.py \ - --model_path /path/to/model.pt \ - --classifier_path path/to/classifier.pt \ - $MODEL_FLAGS $CLASSIFIER_FLAGS $SAMPLE_FLAGS -``` - -To sample for 250 timesteps without DDIM, replace `--timestep_respacing ddim25` to `--timestep_respacing 250`, and replace `--use_ddim True` with `--use_ddim False`. diff --git a/spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/ops/saconv.py b/spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/ops/saconv.py deleted file mode 100644 index b4ee3978e097fca422805db4e31ae481006d7971..0000000000000000000000000000000000000000 --- a/spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/ops/saconv.py +++ /dev/null @@ -1,145 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import torch -import torch.nn as nn -import torch.nn.functional as F - -from annotator.uniformer.mmcv.cnn import CONV_LAYERS, ConvAWS2d, constant_init -from annotator.uniformer.mmcv.ops.deform_conv import deform_conv2d -from annotator.uniformer.mmcv.utils import TORCH_VERSION, digit_version - - -@CONV_LAYERS.register_module(name='SAC') -class SAConv2d(ConvAWS2d): - """SAC (Switchable Atrous Convolution) - - This is an implementation of SAC in DetectoRS - (https://arxiv.org/pdf/2006.02334.pdf). - - Args: - in_channels (int): Number of channels in the input image - out_channels (int): Number of channels produced by the convolution - kernel_size (int or tuple): Size of the convolving kernel - stride (int or tuple, optional): Stride of the convolution. Default: 1 - padding (int or tuple, optional): Zero-padding added to both sides of - the input. Default: 0 - padding_mode (string, optional): ``'zeros'``, ``'reflect'``, - ``'replicate'`` or ``'circular'``. Default: ``'zeros'`` - dilation (int or tuple, optional): Spacing between kernel elements. - Default: 1 - groups (int, optional): Number of blocked connections from input - channels to output channels. Default: 1 - bias (bool, optional): If ``True``, adds a learnable bias to the - output. Default: ``True`` - use_deform: If ``True``, replace convolution with deformable - convolution. Default: ``False``. - """ - - def __init__(self, - in_channels, - out_channels, - kernel_size, - stride=1, - padding=0, - dilation=1, - groups=1, - bias=True, - use_deform=False): - super().__init__( - in_channels, - out_channels, - kernel_size, - stride=stride, - padding=padding, - dilation=dilation, - groups=groups, - bias=bias) - self.use_deform = use_deform - self.switch = nn.Conv2d( - self.in_channels, 1, kernel_size=1, stride=stride, bias=True) - self.weight_diff = nn.Parameter(torch.Tensor(self.weight.size())) - self.pre_context = nn.Conv2d( - self.in_channels, self.in_channels, kernel_size=1, bias=True) - self.post_context = nn.Conv2d( - self.out_channels, self.out_channels, kernel_size=1, bias=True) - if self.use_deform: - self.offset_s = nn.Conv2d( - self.in_channels, - 18, - kernel_size=3, - padding=1, - stride=stride, - bias=True) - self.offset_l = nn.Conv2d( - self.in_channels, - 18, - kernel_size=3, - padding=1, - stride=stride, - bias=True) - self.init_weights() - - def init_weights(self): - constant_init(self.switch, 0, bias=1) - self.weight_diff.data.zero_() - constant_init(self.pre_context, 0) - constant_init(self.post_context, 0) - if self.use_deform: - constant_init(self.offset_s, 0) - constant_init(self.offset_l, 0) - - def forward(self, x): - # pre-context - avg_x = F.adaptive_avg_pool2d(x, output_size=1) - avg_x = self.pre_context(avg_x) - avg_x = avg_x.expand_as(x) - x = x + avg_x - # switch - avg_x = F.pad(x, pad=(2, 2, 2, 2), mode='reflect') - avg_x = F.avg_pool2d(avg_x, kernel_size=5, stride=1, padding=0) - switch = self.switch(avg_x) - # sac - weight = self._get_weight(self.weight) - zero_bias = torch.zeros( - self.out_channels, device=weight.device, dtype=weight.dtype) - - if self.use_deform: - offset = self.offset_s(avg_x) - out_s = deform_conv2d(x, offset, weight, self.stride, self.padding, - self.dilation, self.groups, 1) - else: - if (TORCH_VERSION == 'parrots' - or digit_version(TORCH_VERSION) < digit_version('1.5.0')): - out_s = super().conv2d_forward(x, weight) - elif digit_version(TORCH_VERSION) >= digit_version('1.8.0'): - # bias is a required argument of _conv_forward in torch 1.8.0 - out_s = super()._conv_forward(x, weight, zero_bias) - else: - out_s = super()._conv_forward(x, weight) - ori_p = self.padding - ori_d = self.dilation - self.padding = tuple(3 * p for p in self.padding) - self.dilation = tuple(3 * d for d in self.dilation) - weight = weight + self.weight_diff - if self.use_deform: - offset = self.offset_l(avg_x) - out_l = deform_conv2d(x, offset, weight, self.stride, self.padding, - self.dilation, self.groups, 1) - else: - if (TORCH_VERSION == 'parrots' - or digit_version(TORCH_VERSION) < digit_version('1.5.0')): - out_l = super().conv2d_forward(x, weight) - elif digit_version(TORCH_VERSION) >= digit_version('1.8.0'): - # bias is a required argument of _conv_forward in torch 1.8.0 - out_l = super()._conv_forward(x, weight, zero_bias) - else: - out_l = super()._conv_forward(x, weight) - - out = switch * out_s + (1 - switch) * out_l - self.padding = ori_p - self.dilation = ori_d - # post-context - avg_x = F.adaptive_avg_pool2d(out, output_size=1) - avg_x = self.post_context(avg_x) - avg_x = avg_x.expand_as(out) - out = out + avg_x - return out diff --git a/spaces/ArchitSharma/Digital-Photo-Color-Restoration/src/deoldify/__init__.py b/spaces/ArchitSharma/Digital-Photo-Color-Restoration/src/deoldify/__init__.py deleted file mode 100644 index db38aa1a7e4c2f9c87b859c55f4f16a78aaa3b18..0000000000000000000000000000000000000000 --- a/spaces/ArchitSharma/Digital-Photo-Color-Restoration/src/deoldify/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from src.deoldify._device import _Device - -device = _Device() \ No newline at end of file diff --git a/spaces/Ash58947/Bot/Dockerfile b/spaces/Ash58947/Bot/Dockerfile deleted file mode 100644 index 6c01c09373883afcb4ea34ae2d316cd596e1737b..0000000000000000000000000000000000000000 --- a/spaces/Ash58947/Bot/Dockerfile +++ /dev/null @@ -1,21 +0,0 @@ -FROM node:18-bullseye-slim - -RUN apt-get update && \ - -apt-get install -y git - -RUN git clone https://gitgud.io/khanon/oai-reverse-proxy.git /app - -WORKDIR /app - -RUN npm install - -COPY Dockerfile greeting.md* .env* ./ - -RUN npm run build - -EXPOSE 7860 - -ENV NODE_ENV=production - -CMD [ "npm", "start" ] \ No newline at end of file diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pkg_resources/_vendor/importlib_resources/_legacy.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pkg_resources/_vendor/importlib_resources/_legacy.py deleted file mode 100644 index 1d5d3f1fbb1f6c69d0da2a50e1d4492ad3378f17..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pkg_resources/_vendor/importlib_resources/_legacy.py +++ /dev/null @@ -1,121 +0,0 @@ -import functools -import os -import pathlib -import types -import warnings - -from typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any - -from . import _common - -Package = Union[types.ModuleType, str] -Resource = str - - -def deprecated(func): - @functools.wraps(func) - def wrapper(*args, **kwargs): - warnings.warn( - f"{func.__name__} is deprecated. Use files() instead. " - "Refer to https://importlib-resources.readthedocs.io" - "/en/latest/using.html#migrating-from-legacy for migration advice.", - DeprecationWarning, - stacklevel=2, - ) - return func(*args, **kwargs) - - return wrapper - - -def normalize_path(path): - # type: (Any) -> str - """Normalize a path by ensuring it is a string. - - If the resulting string contains path separators, an exception is raised. - """ - str_path = str(path) - parent, file_name = os.path.split(str_path) - if parent: - raise ValueError(f'{path!r} must be only a file name') - return file_name - - -@deprecated -def open_binary(package: Package, resource: Resource) -> BinaryIO: - """Return a file-like object opened for binary reading of the resource.""" - return (_common.files(package) / normalize_path(resource)).open('rb') - - -@deprecated -def read_binary(package: Package, resource: Resource) -> bytes: - """Return the binary contents of the resource.""" - return (_common.files(package) / normalize_path(resource)).read_bytes() - - -@deprecated -def open_text( - package: Package, - resource: Resource, - encoding: str = 'utf-8', - errors: str = 'strict', -) -> TextIO: - """Return a file-like object opened for text reading of the resource.""" - return (_common.files(package) / normalize_path(resource)).open( - 'r', encoding=encoding, errors=errors - ) - - -@deprecated -def read_text( - package: Package, - resource: Resource, - encoding: str = 'utf-8', - errors: str = 'strict', -) -> str: - """Return the decoded string of the resource. - - The decoding-related arguments have the same semantics as those of - bytes.decode(). - """ - with open_text(package, resource, encoding, errors) as fp: - return fp.read() - - -@deprecated -def contents(package: Package) -> Iterable[str]: - """Return an iterable of entries in `package`. - - Note that not all entries are resources. Specifically, directories are - not considered resources. Use `is_resource()` on each entry returned here - to check if it is a resource or not. - """ - return [path.name for path in _common.files(package).iterdir()] - - -@deprecated -def is_resource(package: Package, name: str) -> bool: - """True if `name` is a resource inside `package`. - - Directories are *not* resources. - """ - resource = normalize_path(name) - return any( - traversable.name == resource and traversable.is_file() - for traversable in _common.files(package).iterdir() - ) - - -@deprecated -def path( - package: Package, - resource: Resource, -) -> ContextManager[pathlib.Path]: - """A context manager providing a file path object to the resource. - - If the resource does not already exist on its own on the file system, - a temporary file will be created. If the file was created, the file - will be deleted upon exiting the context manager (no exception is - raised if the file was deleted prior to the context manager - exiting). - """ - return _common.as_file(_common.files(package) / normalize_path(resource)) diff --git a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/tests/structures/test_instances.py b/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/tests/structures/test_instances.py deleted file mode 100644 index a352f74313ae9b2b7a42398f0ef4606fcb4a610c..0000000000000000000000000000000000000000 --- a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/tests/structures/test_instances.py +++ /dev/null @@ -1,219 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import unittest -import torch -from torch import Tensor - -from detectron2.export.torchscript import patch_instances -from detectron2.structures import Boxes, Instances -from detectron2.utils.testing import convert_scripted_instances - - -class TestInstances(unittest.TestCase): - def test_int_indexing(self): - attr1 = torch.tensor([[0.0, 0.0, 1.0], [0.0, 0.0, 0.5], [0.0, 0.0, 1.0], [0.0, 0.5, 0.5]]) - attr2 = torch.tensor([0.1, 0.2, 0.3, 0.4]) - instances = Instances((100, 100)) - instances.attr1 = attr1 - instances.attr2 = attr2 - for i in range(-len(instances), len(instances)): - inst = instances[i] - self.assertEqual((inst.attr1 == attr1[i]).all(), True) - self.assertEqual((inst.attr2 == attr2[i]).all(), True) - - self.assertRaises(IndexError, lambda: instances[len(instances)]) - self.assertRaises(IndexError, lambda: instances[-len(instances) - 1]) - - def test_script_new_fields(self): - def get_mask(x: Instances) -> torch.Tensor: - return x.mask - - class f(torch.nn.Module): - def forward(self, x: Instances): - proposal_boxes = x.proposal_boxes # noqa F841 - objectness_logits = x.objectness_logits # noqa F841 - return x - - class g(torch.nn.Module): - def forward(self, x: Instances): - return get_mask(x) - - class g2(torch.nn.Module): - def __init__(self): - super().__init__() - self.g = g() - - def forward(self, x: Instances): - proposal_boxes = x.proposal_boxes # noqa F841 - return x, self.g(x) - - fields = {"proposal_boxes": Boxes, "objectness_logits": Tensor} - with patch_instances(fields): - torch.jit.script(f()) - - # can't script anymore after exiting the context - with self.assertRaises(Exception): - # will create a ConcreteType for g - torch.jit.script(g2()) - - new_fields = {"mask": Tensor} - with patch_instances(new_fields): - # will compile g with a different Instances; this should pass - torch.jit.script(g()) - with self.assertRaises(Exception): - torch.jit.script(g2()) - - new_fields = {"mask": Tensor, "proposal_boxes": Boxes} - with patch_instances(new_fields) as NewInstances: - # get_mask will be compiled with a different Instances; this should pass - scripted_g2 = torch.jit.script(g2()) - x = NewInstances((3, 4)) - x.mask = torch.rand(3) - x.proposal_boxes = Boxes(torch.rand(3, 4)) - scripted_g2(x) # it should accept the new Instances object and run successfully - - def test_script_access_fields(self): - class f(torch.nn.Module): - def forward(self, x: Instances): - proposal_boxes = x.proposal_boxes - objectness_logits = x.objectness_logits - return proposal_boxes.tensor + objectness_logits - - fields = {"proposal_boxes": Boxes, "objectness_logits": Tensor} - with patch_instances(fields): - torch.jit.script(f()) - - def test_script_len(self): - class f(torch.nn.Module): - def forward(self, x: Instances): - return len(x) - - class g(torch.nn.Module): - def forward(self, x: Instances): - return len(x) - - image_shape = (15, 15) - - fields = {"proposal_boxes": Boxes} - with patch_instances(fields) as new_instance: - script_module = torch.jit.script(f()) - x = new_instance(image_shape) - with self.assertRaises(Exception): - script_module(x) - box_tensors = torch.tensor([[5, 5, 10, 10], [1, 1, 2, 3]]) - x.proposal_boxes = Boxes(box_tensors) - length = script_module(x) - self.assertEqual(length, 2) - - fields = {"objectness_logits": Tensor} - with patch_instances(fields) as new_instance: - script_module = torch.jit.script(g()) - x = new_instance(image_shape) - objectness_logits = torch.tensor([1.0]).reshape(1, 1) - x.objectness_logits = objectness_logits - length = script_module(x) - self.assertEqual(length, 1) - - def test_script_has(self): - class f(torch.nn.Module): - def forward(self, x: Instances): - return x.has("proposal_boxes") - - image_shape = (15, 15) - fields = {"proposal_boxes": Boxes} - with patch_instances(fields) as new_instance: - script_module = torch.jit.script(f()) - x = new_instance(image_shape) - self.assertFalse(script_module(x)) - - box_tensors = torch.tensor([[5, 5, 10, 10], [1, 1, 2, 3]]) - x.proposal_boxes = Boxes(box_tensors) - self.assertTrue(script_module(x)) - - def test_script_to(self): - class f(torch.nn.Module): - def forward(self, x: Instances): - return x.to(torch.device("cpu")) - - image_shape = (15, 15) - fields = {"proposal_boxes": Boxes, "a": Tensor} - with patch_instances(fields) as new_instance: - script_module = torch.jit.script(f()) - x = new_instance(image_shape) - script_module(x) - - box_tensors = torch.tensor([[5, 5, 10, 10], [1, 1, 2, 3]]) - x.proposal_boxes = Boxes(box_tensors) - x.a = box_tensors - script_module(x) - - def test_script_getitem(self): - class f(torch.nn.Module): - def forward(self, x: Instances, idx): - return x[idx] - - image_shape = (15, 15) - fields = {"proposal_boxes": Boxes, "a": Tensor} - inst = Instances(image_shape) - inst.proposal_boxes = Boxes(torch.rand(4, 4)) - inst.a = torch.rand(4, 10) - idx = torch.tensor([True, False, True, False]) - with patch_instances(fields) as new_instance: - script_module = torch.jit.script(f()) - - out = f()(inst, idx) - out_scripted = script_module(new_instance.from_instances(inst), idx) - self.assertTrue( - torch.equal(out.proposal_boxes.tensor, out_scripted.proposal_boxes.tensor) - ) - self.assertTrue(torch.equal(out.a, out_scripted.a)) - - def test_from_to_instances(self): - orig = Instances((30, 30)) - orig.proposal_boxes = Boxes(torch.rand(3, 4)) - - fields = {"proposal_boxes": Boxes, "a": Tensor} - with patch_instances(fields) as NewInstances: - # convert to NewInstances and back - new1 = NewInstances.from_instances(orig) - new2 = convert_scripted_instances(new1) - self.assertTrue(torch.equal(orig.proposal_boxes.tensor, new1.proposal_boxes.tensor)) - self.assertTrue(torch.equal(orig.proposal_boxes.tensor, new2.proposal_boxes.tensor)) - - def test_script_init_args(self): - def f(x: Tensor): - image_shape = (15, 15) - # __init__ can take arguments - inst = Instances(image_shape, a=x, proposal_boxes=Boxes(x)) - inst2 = Instances(image_shape, a=x) - return inst.a, inst2.a - - fields = {"proposal_boxes": Boxes, "a": Tensor} - with patch_instances(fields): - script_f = torch.jit.script(f) - x = torch.randn(3, 4) - outputs = script_f(x) - self.assertTrue(torch.equal(outputs[0], x)) - self.assertTrue(torch.equal(outputs[1], x)) - - def test_script_cat(self): - def f(x: Tensor): - image_shape = (15, 15) - # __init__ can take arguments - inst = Instances(image_shape, a=x) - inst2 = Instances(image_shape, a=x) - - inst3 = Instances(image_shape, proposal_boxes=Boxes(x)) - return inst.cat([inst, inst2]), inst3.cat([inst3, inst3]) - - fields = {"proposal_boxes": Boxes, "a": Tensor} - with patch_instances(fields): - script_f = torch.jit.script(f) - x = torch.randn(3, 4) - output, output2 = script_f(x) - self.assertTrue(torch.equal(output.a, torch.cat([x, x]))) - self.assertFalse(output.has("proposal_boxes")) - self.assertTrue(torch.equal(output2.proposal_boxes.tensor, torch.cat([x, x]))) - - -if __name__ == "__main__": - unittest.main() diff --git a/spaces/Benson/text-generation/Examples/Carx Calle Pc Descargar Mediafre.md b/spaces/Benson/text-generation/Examples/Carx Calle Pc Descargar Mediafre.md deleted file mode 100644 index b54b96df33c24b1327d037493ccfe56dd1f0aac8..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Carx Calle Pc Descargar Mediafre.md +++ /dev/null @@ -1,33 +0,0 @@ -
-

CarX Street PC Descargar Mediafıre: Cómo jugar el último juego de carreras en su computadora

-

Si eres un fan de los juegos de carreras, es posible que hayas oído hablar de CarX Street, un emocionante juego que te permite explorar el mundo de las carreras nocturnas. Puede recoger coches legendarios, personalizarlos y desafiar a otros jugadores en carreras de red reales. ¿Pero sabías que también puedes jugar CarX Street en tu PC usando Mediafıre? En este artículo, le mostraremos cómo descargar e instalar CarX Street en su computadora usando Mediafıre, y cómo optimizar su experiencia de juego de PC con este increíble juego. ¡Vamos a empezar!

-

carx calle pc descargar mediafıre


Downloadhttps://bltlly.com/2v6ITu



-

Introducción

-

¿Qué es CarX Street?

-

CarX Street es un juego de carreras desarrollado por CarX Technologies, LLC. Está disponible para dispositivos Android e iOS, así como para ordenadores Windows y Mac. En CarX Street, puede conducir más de 50 coches oficiales de los mejores fabricantes de automóviles del mundo, como BMW, Toyota, Nissan, Subaru y más. También puede personalizar sus coches con diferentes partes, colores, pegatinas y calcomanías. Puedes correr en varios lugares, desde las concurridas calles de la ciudad hasta las carreteras de montaña en espiral y las carreteras costeras. Puedes desviar, acelerar y esquivar el tráfico mientras compites con otros jugadores en carreras de red reales. También puedes participar en competiciones basadas en historias con múltiples formas de ganar.

-

¿Por qué jugar CarX Street en PC?

-

Si bien CarX Street es un gran juego para jugar en tu dispositivo móvil, jugar en tu PC tiene algunas ventajas. Por un lado, se puede disfrutar de los impresionantes gráficos y la física realista del juego en una pantalla más grande. También puede utilizar un controlador o un teclado y ratón para controlar su coche más fácilmente. También puede acceder a miles de aplicaciones y herramientas de productividad en su PC sin cambiar de dispositivo. Jugar CarX Street en PC también le permite ahorrar batería y espacio de almacenamiento en su dispositivo móvil.

-

Cómo descargar e instalar CarX Street en PC usando Mediafıre

- -

Para jugar CarX Street en su PC, tendrá que descargar los archivos del juego desde Mediafıre, un servicio de almacenamiento en la nube que le permite compartir archivos en línea. Puede encontrar el enlace Mediafıre para CarX Street [aquí]( 1 ). Haga clic en el enlace y espere a que comience la descarga. El tamaño del archivo es de aproximadamente 1 GB, por lo que podría tomar algún tiempo dependiendo de su velocidad de Internet.

-

Paso 2: Extraer el archivo zip y ejecutar el archivo de configuración

-

Una vez completada la descarga, tendrá que extraer el archivo zip utilizando un programa como WinRAR o 7-Zip. Puede descargar WinRAR [aquí] o 7-Zip [aquí]. Después de extraer el archivo zip, verá una carpeta llamada "CarX_Street". Ábralo y busque el archivo de configuración llamado "CarX_Street_Setup.exe". Haga doble clic en él y espere a que aparezca el asistente de instalación.

-

-

Paso 3: Siga las instrucciones de instalación y inicie el juego

-

El asistente de instalación le guiará a través del proceso de instalación de CarX Street en su PC. Deberá aceptar los términos y condiciones, elegir una carpeta de destino y crear un acceso directo al escritorio. La instalación tomará unos minutos, así que ten paciencia. Después de la instalación, puede iniciar el juego haciendo clic en el acceso directo del escritorio o el icono del menú de inicio. Verás el logo de CarX Street y luego el menú principal del juego.

-

Cómo optimizar tu experiencia de juego en PC con CarX Street

-

Ajustar la configuración de gráficos y la resolución

- -

Usa un controlador o un teclado y ratón

-

Otra forma de optimizar su experiencia de juego de PC con CarX Street es usar un controlador o un teclado y ratón para controlar su automóvil. Puedes usar cualquier mando compatible que se conecte a tu PC a través de USB o Bluetooth, como un mando de Xbox One, PlayStation 4 o Nintendo Switch. También puede utilizar un teclado y un ratón si lo prefiere. Puede personalizar los controles haciendo clic en el icono de engranaje en la esquina superior derecha del menú principal y luego seleccionando la pestaña de controles. Puede asignar diferentes teclas o botones a diferentes acciones, como dirección, aceleración, frenado, deriva, cambio de cámara y más.

-

Activar el modo multijugador en línea y unirse a otros corredores

-

La parte más divertida de jugar CarX Street en tu PC es habilitar el modo multijugador en línea y unirse a otros corredores de todo el mundo. Puede acceder al modo multijugador en línea haciendo clic en el icono del globo en la esquina superior izquierda del menú principal. Puede elegir entre diferentes modos, como carrera rápida, carrera clasificada, carrera personalizada o carrera privada. También puede crear o unirse a un club y chatear con otros miembros. Puedes competir con otros jugadores en carreras de red reales y ganar recompensas, puntos de reputación y clasificaciones de clasificación.

-

Conclusión

-

Resumen de los puntos principales

-

En este artículo, le hemos mostrado cómo jugar CarX Street en su PC usando Mediafıre. Hemos explicado lo que es CarX Street, por qué debe jugar en el PC, cómo descargar e instalar con Mediafıre, y cómo optimizar su experiencia de juego de PC con él. Esperamos que haya encontrado este artículo útil e informativo.

-

Llamada a la acción y pensamientos finales

- -

Gracias por leer este artículo. Si tiene alguna pregunta o comentario, déjelos en la sección de comentarios a continuación. Nos encantaría saber de ti. ¡Feliz carrera!

- P: ¿CarX Street es libre para jugar? R: Sí, CarX Street es libre para jugar en todas las plataformas. Sin embargo, contiene compras en la aplicación que le permiten comprar moneda premium, automóviles, piezas y otros artículos. P: ¿Es seguro descargar CarX Street desde Mediafıre? R: Sí, CarX Street es seguro para descargar desde Mediafıre siempre y cuando utilice el enlace oficial proporcionado en este artículo. Lo hemos probado nosotros mismos y no encontramos virus o malware. P: ¿Cuáles son los requisitos mínimos del sistema para jugar CarX Street en PC? R: Los requisitos mínimos del sistema para jugar CarX Street en PC son: - OS: Windows 7/8/10 - Procesador: Intel Core i3-4130 / AMD FX-4300 - Memoria: 4 GB RAM - Gráficos: NVIDIA GeForce GTX 660 / AMD Radeon HD 7870 - DirectX: Versión 11 - Almacenamiento: 5 GB de espacio disponible Q: ¿Cómo puedo contactar a los desarrolladores de CarX Street? R: Puede ponerse en contacto con los desarrolladores de CarX Street visitando su sitio web oficial [aquí], su página de Facebook [aquí], su página de Instagram [aquí], o su servidor Discord [aquí]. P: ¿Cómo puedo obtener más información sobre CarX Street? R: Puedes aprender más sobre CarX Street leyendo su blog oficial [ aquí], viendo su canal oficial de YouTube [aquí], o siguiendo su cuenta oficial de Twitter [aquí].

64aa2da5cf
-
-
\ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Descargar Cuentos De Los Hroes Gemelos Valientes (parcheado En Ingls) Iso Psp.md b/spaces/Benson/text-generation/Examples/Descargar Cuentos De Los Hroes Gemelos Valientes (parcheado En Ingls) Iso Psp.md deleted file mode 100644 index eebfc1e7154564de16ba6b5b494529493a24d38e..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Descargar Cuentos De Los Hroes Gemelos Valientes (parcheado En Ingls) Iso Psp.md +++ /dev/null @@ -1,58 +0,0 @@ - -

Cómo descargar cuentos de los héroes: Twin Brave (parcheado en inglés) ISO PSP

-

Si eres un fan de la serie Tales, quizás te interese jugar a Tales of the Heroes: Twin Brave, un juego spin-off que cuenta con muchos personajes del pasado Tales en un estilo de acción beat 'em up. Sin embargo, hay un problema: este juego solo fue lanzado en Japón para PlayStation Portable (PSP) en 2012, y no hay ninguna localización oficial en inglés. Afortunadamente, hay una manera de jugar este juego en inglés utilizando un parche en inglés no oficial hecho por fans. En este artículo, le mostraremos cómo descargar Tales of the Heroes: Twin Brave (parcheado en inglés) ISO PSP y disfrutar jugando en su dispositivo PSP.

-

Introducción

-

Antes de entrar en detalles, primero vamos a explicar lo que es Tales of the Heroes: Twin Brave y por qué necesitas un parche en inglés para jugarlo.

-

descargar cuentos de los héroes gemelos valientes (parcheado en inglés) iso psp


DOWNLOAD ★★★★★ https://bltlly.com/2v6Ldu



-

¿Qué es Cuentos de los Héroes: Twin Brave?

-

Tales of the Heroes: Twin Brave es un juego de acción en el Tales

Por eso necesitas un parche en inglés, que es una modificación de los archivos del juego que traduce el texto japonés al inglés. Un parche de Inglés es creado por los fans que tienen las habilidades y la pasión para hacer el juego accesible a más personas. Sin embargo, un parche en inglés no es un producto oficial, y puede tener algunos errores o inconsistencias. Por lo tanto, debes usarlo bajo tu propio riesgo y respetar a los creadores originales del juego y el parche.

-

¿Cuáles son los requisitos para jugar en PSP?

-

Para jugar Tales of the Heroes: Twin Brave (parcheado en inglés) ISO PSP en su dispositivo PSP, necesitará las siguientes cosas:

-
    - -
  • Una tarjeta de memoria que tiene suficiente espacio para almacenar la ISO del juego y el parche en inglés. El juego ISO es de aproximadamente 1,5 GB, y el parche en inglés es de unos 300 MB. También necesitará un poco de espacio adicional para el juego parcheado ISO, que será de aproximadamente 1,8 GB.
  • -
  • Un cable USB que puede conectar su PSP a su PC. Necesitará esto para transferir los archivos de su PC a su PSP.
  • -
-

Una vez que tengas estas cosas listas, puedes proceder al siguiente paso.

-

Paso 1: Descargar el juego ISO y el parche en inglés

-

El primer paso es descargar el juego ISO y el parche en inglés de fuentes confiables. Puede encontrarlos en varios sitios web, como CDRomance, Nicoblog, o Romhacking.net. Sin embargo, debe tener cuidado ya que algunos sitios web pueden contener malware o virus que pueden dañar su PC o PSP. También deberías revisar los comentarios y reseñas de otros usuarios antes de descargar nada.

-

Después de descargar el juego ISO y el parche en inglés, debe verificar los archivos y extraerlos. Puede utilizar una herramienta como 7-Zip o WinRAR para extraer los archivos de sus formatos comprimidos. También debe usar una herramienta como HashTab para verificar las sumas de verificación de los archivos y asegurarse de que no están dañados o manipulados. Las sumas de verificación suelen ser proporcionados por los cargadores de los archivos, y deben coincidir con los que obtiene de su herramienta.

Paso 2: Aplicar el parche en inglés al juego ISO

-

El siguiente paso es aplicar el parche en inglés a la ISO del juego. Necesitará algunas herramientas para hacer esto, como Xdelta o PPF-O-Matic. Estas herramientas pueden aplicar un archivo de parche a un archivo de origen y crear un nuevo archivo con los cambios. Puedes encontrar estas herramientas en línea, pero de nuevo, ten cuidado con el malware o los virus.

- -

Después de parchear el juego ISO, usted debe tener un nuevo archivo que tiene la traducción al inglés aplicado. Puede comprobar el tamaño y el nombre del archivo y compararlo con los dados por los creadores del parche en inglés. También puedes probar la ISO del juego parcheado en tu PC usando un emulador de PSP, como PPSSPP, para ver si funciona correctamente y no tiene errores o fallos.

-

Paso 3: Transferir el juego parcheado ISO a su PSP

-

El paso final es transferir el juego parcheado ISO a su dispositivo PSP. Tendrá que conectar su PSP a su PC mediante un cable USB. Entonces, tendrá que crear una carpeta para juegos de PSP en su tarjeta de memoria. La carpeta debe llamarse ISO y debe estar ubicada en el directorio raíz de su tarjeta de memoria. Si ya tiene esta carpeta, puede omitir este paso.

-

-

A continuación, tendrá que copiar el juego parcheado ISO a su carpeta PSP. Puede utilizar una herramienta como Explorador de Windows o ) A list of possible signature - versions, including s3, v4, v2, and s3v4 - - protocols: (list) A list of supported protocols - (e.g., http, https) - - ...: Other keys may be included as well based on the metadata - """ - raise NotImplementedError - - def get_available_partitions(self): - """Lists the partitions available to the endpoint resolver. - - :return: Returns a list of partition names (e.g., ["aws", "aws-cn"]). - """ - raise NotImplementedError - - def get_available_endpoints( - self, service_name, partition_name='aws', allow_non_regional=False - ): - """Lists the endpoint names of a particular partition. - - :type service_name: string - :param service_name: Name of a service to list endpoint for (e.g., s3) - - :type partition_name: string - :param partition_name: Name of the partition to limit endpoints to. - (e.g., aws for the public AWS endpoints, aws-cn for AWS China - endpoints, aws-us-gov for AWS GovCloud (US) Endpoints, etc. - - :type allow_non_regional: bool - :param allow_non_regional: Set to True to include endpoints that are - not regional endpoints (e.g., s3-external-1, - fips-us-gov-west-1, etc). - :return: Returns a list of endpoint names (e.g., ["us-east-1"]). - """ - raise NotImplementedError - - -class EndpointResolver(BaseEndpointResolver): - """Resolves endpoints based on partition endpoint metadata""" - - _UNSUPPORTED_DUALSTACK_PARTITIONS = ['aws-iso', 'aws-iso-b'] - - def __init__(self, endpoint_data, uses_builtin_data=False): - """ - :type endpoint_data: dict - :param endpoint_data: A dict of partition data. - - :type uses_builtin_data: boolean - :param uses_builtin_data: Whether the endpoint data originates in the - package's data directory. - """ - if 'partitions' not in endpoint_data: - raise ValueError('Missing "partitions" in endpoint data') - self._endpoint_data = endpoint_data - self.uses_builtin_data = uses_builtin_data - - def get_service_endpoints_data(self, service_name, partition_name='aws'): - for partition in self._endpoint_data['partitions']: - if partition['partition'] != partition_name: - continue - services = partition['services'] - if service_name not in services: - continue - return services[service_name]['endpoints'] - - def get_available_partitions(self): - result = [] - for partition in self._endpoint_data['partitions']: - result.append(partition['partition']) - return result - - def get_available_endpoints( - self, - service_name, - partition_name='aws', - allow_non_regional=False, - endpoint_variant_tags=None, - ): - result = [] - for partition in self._endpoint_data['partitions']: - if partition['partition'] != partition_name: - continue - services = partition['services'] - if service_name not in services: - continue - service_endpoints = services[service_name]['endpoints'] - for endpoint_name in service_endpoints: - is_regional_endpoint = endpoint_name in partition['regions'] - # Only regional endpoints can be modeled with variants - if endpoint_variant_tags and is_regional_endpoint: - variant_data = self._retrieve_variant_data( - service_endpoints[endpoint_name], endpoint_variant_tags - ) - if variant_data: - result.append(endpoint_name) - elif allow_non_regional or is_regional_endpoint: - result.append(endpoint_name) - return result - - def get_partition_dns_suffix( - self, partition_name, endpoint_variant_tags=None - ): - for partition in self._endpoint_data['partitions']: - if partition['partition'] == partition_name: - if endpoint_variant_tags: - variant = self._retrieve_variant_data( - partition.get('defaults'), endpoint_variant_tags - ) - if variant and 'dnsSuffix' in variant: - return variant['dnsSuffix'] - else: - return partition['dnsSuffix'] - return None - - def construct_endpoint( - self, - service_name, - region_name=None, - partition_name=None, - use_dualstack_endpoint=False, - use_fips_endpoint=False, - ): - if ( - service_name == 's3' - and use_dualstack_endpoint - and region_name is None - ): - region_name = 'us-east-1' - - if partition_name is not None: - valid_partition = None - for partition in self._endpoint_data['partitions']: - if partition['partition'] == partition_name: - valid_partition = partition - - if valid_partition is not None: - result = self._endpoint_for_partition( - valid_partition, - service_name, - region_name, - use_dualstack_endpoint, - use_fips_endpoint, - True, - ) - return result - return None - - # Iterate over each partition until a match is found. - for partition in self._endpoint_data['partitions']: - if use_dualstack_endpoint and ( - partition['partition'] - in self._UNSUPPORTED_DUALSTACK_PARTITIONS - ): - continue - result = self._endpoint_for_partition( - partition, - service_name, - region_name, - use_dualstack_endpoint, - use_fips_endpoint, - ) - if result: - return result - - def get_partition_for_region(self, region_name): - for partition in self._endpoint_data['partitions']: - if self._region_match(partition, region_name): - return partition['partition'] - raise UnknownRegionError( - region_name=region_name, - error_msg='No partition found for provided region_name.', - ) - - def _endpoint_for_partition( - self, - partition, - service_name, - region_name, - use_dualstack_endpoint, - use_fips_endpoint, - force_partition=False, - ): - partition_name = partition["partition"] - if ( - use_dualstack_endpoint - and partition_name in self._UNSUPPORTED_DUALSTACK_PARTITIONS - ): - error_msg = ( - "Dualstack endpoints are currently not supported" - " for %s partition" % partition_name - ) - raise EndpointVariantError(tags=['dualstack'], error_msg=error_msg) - - # Get the service from the partition, or an empty template. - service_data = partition['services'].get( - service_name, DEFAULT_SERVICE_DATA - ) - # Use the partition endpoint if no region is supplied. - if region_name is None: - if 'partitionEndpoint' in service_data: - region_name = service_data['partitionEndpoint'] - else: - raise NoRegionError() - - resolve_kwargs = { - 'partition': partition, - 'service_name': service_name, - 'service_data': service_data, - 'endpoint_name': region_name, - 'use_dualstack_endpoint': use_dualstack_endpoint, - 'use_fips_endpoint': use_fips_endpoint, - } - - # Attempt to resolve the exact region for this partition. - if region_name in service_data['endpoints']: - return self._resolve(**resolve_kwargs) - - # Check to see if the endpoint provided is valid for the partition. - if self._region_match(partition, region_name) or force_partition: - # Use the partition endpoint if set and not regionalized. - partition_endpoint = service_data.get('partitionEndpoint') - is_regionalized = service_data.get('isRegionalized', True) - if partition_endpoint and not is_regionalized: - LOG.debug( - 'Using partition endpoint for %s, %s: %s', - service_name, - region_name, - partition_endpoint, - ) - resolve_kwargs['endpoint_name'] = partition_endpoint - return self._resolve(**resolve_kwargs) - LOG.debug( - 'Creating a regex based endpoint for %s, %s', - service_name, - region_name, - ) - return self._resolve(**resolve_kwargs) - - def _region_match(self, partition, region_name): - if region_name in partition['regions']: - return True - if 'regionRegex' in partition: - return re.compile(partition['regionRegex']).match(region_name) - return False - - def _retrieve_variant_data(self, endpoint_data, tags): - variants = endpoint_data.get('variants', []) - for variant in variants: - if set(variant['tags']) == set(tags): - result = variant.copy() - return result - - def _create_tag_list(self, use_dualstack_endpoint, use_fips_endpoint): - tags = [] - if use_dualstack_endpoint: - tags.append('dualstack') - if use_fips_endpoint: - tags.append('fips') - return tags - - def _resolve_variant( - self, tags, endpoint_data, service_defaults, partition_defaults - ): - result = {} - for variants in [endpoint_data, service_defaults, partition_defaults]: - variant = self._retrieve_variant_data(variants, tags) - if variant: - self._merge_keys(variant, result) - return result - - def _resolve( - self, - partition, - service_name, - service_data, - endpoint_name, - use_dualstack_endpoint, - use_fips_endpoint, - ): - endpoint_data = service_data.get('endpoints', {}).get( - endpoint_name, {} - ) - - if endpoint_data.get('deprecated'): - LOG.warning( - 'Client is configured with the deprecated endpoint: %s' - % (endpoint_name) - ) - - service_defaults = service_data.get('defaults', {}) - partition_defaults = partition.get('defaults', {}) - tags = self._create_tag_list(use_dualstack_endpoint, use_fips_endpoint) - - if tags: - result = self._resolve_variant( - tags, endpoint_data, service_defaults, partition_defaults - ) - if result == {}: - error_msg = ( - f"Endpoint does not exist for {service_name} " - f"in region {endpoint_name}" - ) - raise EndpointVariantError(tags=tags, error_msg=error_msg) - self._merge_keys(endpoint_data, result) - else: - result = endpoint_data - - # If dnsSuffix has not already been consumed from a variant definition - if 'dnsSuffix' not in result: - result['dnsSuffix'] = partition['dnsSuffix'] - - result['partition'] = partition['partition'] - result['endpointName'] = endpoint_name - - # Merge in the service defaults then the partition defaults. - self._merge_keys(service_defaults, result) - self._merge_keys(partition_defaults, result) - - result['hostname'] = self._expand_template( - partition, - result['hostname'], - service_name, - endpoint_name, - result['dnsSuffix'], - ) - if 'sslCommonName' in result: - result['sslCommonName'] = self._expand_template( - partition, - result['sslCommonName'], - service_name, - endpoint_name, - result['dnsSuffix'], - ) - - return result - - def _merge_keys(self, from_data, result): - for key in from_data: - if key not in result: - result[key] = from_data[key] - - def _expand_template( - self, partition, template, service_name, endpoint_name, dnsSuffix - ): - return template.format( - service=service_name, region=endpoint_name, dnsSuffix=dnsSuffix - ) - - -class EndpointResolverBuiltins(str, Enum): - # The AWS Region configured for the SDK client (str) - AWS_REGION = "AWS::Region" - # Whether the UseFIPSEndpoint configuration option has been enabled for - # the SDK client (bool) - AWS_USE_FIPS = "AWS::UseFIPS" - # Whether the UseDualStackEndpoint configuration option has been enabled - # for the SDK client (bool) - AWS_USE_DUALSTACK = "AWS::UseDualStack" - # Whether the global endpoint should be used with STS, rather the the - # regional endpoint for us-east-1 (bool) - AWS_STS_USE_GLOBAL_ENDPOINT = "AWS::STS::UseGlobalEndpoint" - # Whether the global endpoint should be used with S3, rather then the - # regional endpoint for us-east-1 (bool) - AWS_S3_USE_GLOBAL_ENDPOINT = "AWS::S3::UseGlobalEndpoint" - # Whether S3 Transfer Acceleration has been requested (bool) - AWS_S3_ACCELERATE = "AWS::S3::Accelerate" - # Whether S3 Force Path Style has been enabled (bool) - AWS_S3_FORCE_PATH_STYLE = "AWS::S3::ForcePathStyle" - # Whether to use the ARN region or raise an error when ARN and client - # region differ (for s3 service only, bool) - AWS_S3_USE_ARN_REGION = "AWS::S3::UseArnRegion" - # Whether to use the ARN region or raise an error when ARN and client - # region differ (for s3-control service only, bool) - AWS_S3CONTROL_USE_ARN_REGION = 'AWS::S3Control::UseArnRegion' - # Whether multi-region access points (MRAP) should be disabled (bool) - AWS_S3_DISABLE_MRAP = "AWS::S3::DisableMultiRegionAccessPoints" - # Whether a custom endpoint has been configured (str) - SDK_ENDPOINT = "SDK::Endpoint" - - -class EndpointRulesetResolver: - """Resolves endpoints using a service's endpoint ruleset""" - - def __init__( - self, - endpoint_ruleset_data, - partition_data, - service_model, - builtins, - client_context, - event_emitter, - use_ssl=True, - requested_auth_scheme=None, - ): - self._provider = EndpointProvider( - ruleset_data=endpoint_ruleset_data, - partition_data=partition_data, - ) - self._param_definitions = self._provider.ruleset.parameters - self._service_model = service_model - self._builtins = builtins - self._client_context = client_context - self._event_emitter = event_emitter - self._use_ssl = use_ssl - self._requested_auth_scheme = requested_auth_scheme - self._instance_cache = {} - - def construct_endpoint( - self, - operation_model, - call_args, - request_context, - ): - """Invokes the provider with params defined in the service's ruleset""" - if call_args is None: - call_args = {} - - if request_context is None: - request_context = {} - - provider_params = self._get_provider_params( - operation_model, call_args, request_context - ) - LOG.debug( - 'Calling endpoint provider with parameters: %s' % provider_params - ) - try: - provider_result = self._provider.resolve_endpoint( - **provider_params - ) - except EndpointProviderError as ex: - botocore_exception = self.ruleset_error_to_botocore_exception( - ex, provider_params - ) - if botocore_exception is None: - raise - else: - raise botocore_exception from ex - LOG.debug('Endpoint provider result: %s' % provider_result.url) - - # The endpoint provider does not support non-secure transport. - if not self._use_ssl and provider_result.url.startswith('https://'): - provider_result = provider_result._replace( - url=f'http://{provider_result.url[8:]}' - ) - - # Multi-valued headers are not supported in botocore. Replace the list - # of values returned for each header with just its first entry, - # dropping any additionally entries. - provider_result = provider_result._replace( - headers={ - key: val[0] for key, val in provider_result.headers.items() - } - ) - - return provider_result - - def _get_provider_params( - self, operation_model, call_args, request_context - ): - """Resolve a value for each parameter defined in the service's ruleset - - The resolution order for parameter values is: - 1. Operation-specific static context values from the service definition - 2. Operation-specific dynamic context values from API parameters - 3. Client-specific context parameters - 4. Built-in values such as region, FIPS usage, ... - """ - provider_params = {} - # Builtin values can be customized for each operation by hooks - # subscribing to the ``before-endpoint-resolution.*`` event. - customized_builtins = self._get_customized_builtins( - operation_model, call_args, request_context - ) - for param_name, param_def in self._param_definitions.items(): - param_val = self._resolve_param_from_context( - param_name=param_name, - operation_model=operation_model, - call_args=call_args, - ) - if param_val is None and param_def.builtin is not None: - param_val = self._resolve_param_as_builtin( - builtin_name=param_def.builtin, - builtins=customized_builtins, - ) - if param_val is not None: - provider_params[param_name] = param_val - - return provider_params - - def _resolve_param_from_context( - self, param_name, operation_model, call_args - ): - static = self._resolve_param_as_static_context_param( - param_name, operation_model - ) - if static is not None: - return static - dynamic = self._resolve_param_as_dynamic_context_param( - param_name, operation_model, call_args - ) - if dynamic is not None: - return dynamic - return self._resolve_param_as_client_context_param(param_name) - - def _resolve_param_as_static_context_param( - self, param_name, operation_model - ): - static_ctx_params = self._get_static_context_params(operation_model) - return static_ctx_params.get(param_name) - - def _resolve_param_as_dynamic_context_param( - self, param_name, operation_model, call_args - ): - dynamic_ctx_params = self._get_dynamic_context_params(operation_model) - if param_name in dynamic_ctx_params: - member_name = dynamic_ctx_params[param_name] - return call_args.get(member_name) - - def _resolve_param_as_client_context_param(self, param_name): - client_ctx_params = self._get_client_context_params() - if param_name in client_ctx_params: - client_ctx_varname = client_ctx_params[param_name] - return self._client_context.get(client_ctx_varname) - - def _resolve_param_as_builtin(self, builtin_name, builtins): - if builtin_name not in EndpointResolverBuiltins.__members__.values(): - raise UnknownEndpointResolutionBuiltInName(name=builtin_name) - return builtins.get(builtin_name) - - @instance_cache - def _get_static_context_params(self, operation_model): - """Mapping of param names to static param value for an operation""" - return { - param.name: param.value - for param in operation_model.static_context_parameters - } - - @instance_cache - def _get_dynamic_context_params(self, operation_model): - """Mapping of param names to member names for an operation""" - return { - param.name: param.member_name - for param in operation_model.context_parameters - } - - @instance_cache - def _get_client_context_params(self): - """Mapping of param names to client configuration variable""" - return { - param.name: xform_name(param.name) - for param in self._service_model.client_context_parameters - } - - def _get_customized_builtins( - self, operation_model, call_args, request_context - ): - service_id = self._service_model.service_id.hyphenize() - customized_builtins = copy.copy(self._builtins) - # Handlers are expected to modify the builtins dict in place. - self._event_emitter.emit( - 'before-endpoint-resolution.%s' % service_id, - builtins=customized_builtins, - model=operation_model, - params=call_args, - context=request_context, - ) - return customized_builtins - - def auth_schemes_to_signing_ctx(self, auth_schemes): - """Convert an Endpoint's authSchemes property to a signing_context dict - - :type auth_schemes: list - :param auth_schemes: A list of dictionaries taken from the - ``authSchemes`` property of an Endpoint object returned by - ``EndpointProvider``. - - :rtype: str, dict - :return: Tuple of auth type string (to be used in - ``request_context['auth_type']``) and signing context dict (for use - in ``request_context['signing']``). - """ - if not isinstance(auth_schemes, list) or len(auth_schemes) == 0: - raise TypeError("auth_schemes must be a non-empty list.") - - LOG.debug( - 'Selecting from endpoint provider\'s list of auth schemes: %s. ' - 'User selected auth scheme is: "%s"', - ', '.join([f'"{s.get("name")}"' for s in auth_schemes]), - self._requested_auth_scheme, - ) - - if self._requested_auth_scheme == UNSIGNED: - return 'none', {} - - auth_schemes = [ - {**scheme, 'name': self._strip_sig_prefix(scheme['name'])} - for scheme in auth_schemes - ] - if self._requested_auth_scheme is not None: - try: - # Use the first scheme that matches the requested scheme, - # after accounting for naming differences between botocore and - # endpoint rulesets. Keep the requested name. - name, scheme = next( - (self._requested_auth_scheme, s) - for s in auth_schemes - if self._does_botocore_authname_match_ruleset_authname( - self._requested_auth_scheme, s['name'] - ) - ) - except StopIteration: - # For legacy signers, no match will be found. Do not raise an - # exception, instead default to the logic in botocore - # customizations. - return None, {} - else: - try: - name, scheme = next( - (s['name'], s) - for s in auth_schemes - if s['name'] in AUTH_TYPE_MAPS - ) - except StopIteration: - # If no auth scheme was specifically requested and an - # authSchemes list is present in the Endpoint object but none - # of the entries are supported, raise an exception. - fixable_with_crt = False - auth_type_options = [s['name'] for s in auth_schemes] - if not HAS_CRT: - fixable_with_crt = any( - scheme in CRT_SUPPORTED_AUTH_TYPES - for scheme in auth_type_options - ) - - if fixable_with_crt: - raise MissingDependencyException( - msg='This operation requires an additional dependency.' - ' Use pip install botocore[crt] before proceeding.' - ) - else: - raise UnknownSignatureVersionError( - signature_version=', '.join(auth_type_options) - ) - - signing_context = {} - if 'signingRegion' in scheme: - signing_context['region'] = scheme['signingRegion'] - elif 'signingRegionSet' in scheme: - if len(scheme['signingRegionSet']) > 0: - signing_context['region'] = scheme['signingRegionSet'][0] - if 'signingName' in scheme: - signing_context.update(signing_name=scheme['signingName']) - if 'disableDoubleEncoding' in scheme: - signing_context['disableDoubleEncoding'] = ensure_boolean( - scheme['disableDoubleEncoding'] - ) - - LOG.debug( - 'Selected auth type "%s" as "%s" with signing context params: %s', - scheme['name'], # original name without "sig" - name, # chosen name can differ when `signature_version` is set - signing_context, - ) - return name, signing_context - - def _strip_sig_prefix(self, auth_name): - """Normalize auth type names by removing any "sig" prefix""" - return auth_name[3:] if auth_name.startswith('sig') else auth_name - - def _does_botocore_authname_match_ruleset_authname(self, botoname, rsname): - """ - Whether a valid string provided as signature_version parameter for - client construction refers to the same auth methods as a string - returned by the endpoint ruleset provider. This accounts for: - - * The ruleset prefixes auth names with "sig" - * The s3 and s3control rulesets don't distinguish between v4[a] and - s3v4[a] signers - * The v2, v3, and HMAC v1 based signers (s3, s3-*) are botocore legacy - features and do not exist in the rulesets - * Only characters up to the first dash are considered - - Example matches: - * v4, sigv4 - * v4, v4 - * s3v4, sigv4 - * s3v7, sigv7 (hypothetical example) - * s3v4a, sigv4a - * s3v4-query, sigv4 - - Example mismatches: - * v4a, sigv4 - * s3, sigv4 - * s3-presign-post, sigv4 - """ - rsname = self._strip_sig_prefix(rsname) - botoname = botoname.split('-')[0] - if botoname != 's3' and botoname.startswith('s3'): - botoname = botoname[2:] - return rsname == botoname - - def ruleset_error_to_botocore_exception(self, ruleset_exception, params): - """Attempts to translate ruleset errors to pre-existing botocore - exception types by string matching exception strings. - """ - msg = ruleset_exception.kwargs.get('msg') - if msg is None: - return - - if msg.startswith('Invalid region in ARN: '): - # Example message: - # "Invalid region in ARN: `us-we$t-2` (invalid DNS name)" - try: - label = msg.split('`')[1] - except IndexError: - label = msg - return InvalidHostLabelError(label=label) - - service_name = self._service_model.service_name - if service_name == 's3': - if ( - msg == 'S3 Object Lambda does not support S3 Accelerate' - or msg == 'Accelerate cannot be used with FIPS' - ): - return UnsupportedS3ConfigurationError(msg=msg) - if ( - msg.startswith('S3 Outposts does not support') - or msg.startswith('S3 MRAP does not support') - or msg.startswith('S3 Object Lambda does not support') - or msg.startswith('Access Points do not support') - or msg.startswith('Invalid configuration:') - or msg.startswith('Client was configured for partition') - ): - return UnsupportedS3AccesspointConfigurationError(msg=msg) - if msg.lower().startswith('invalid arn:'): - return ParamValidationError(report=msg) - if service_name == 's3control': - if msg.startswith('Invalid ARN:'): - arn = params.get('Bucket') - return UnsupportedS3ControlArnError(arn=arn, msg=msg) - if msg.startswith('Invalid configuration:') or msg.startswith( - 'Client was configured for partition' - ): - return UnsupportedS3ControlConfigurationError(msg=msg) - if msg == "AccountId is required but not set": - return ParamValidationError(report=msg) - if service_name == 'events': - if msg.startswith( - 'Invalid Configuration: FIPS is not supported with ' - 'EventBridge multi-region endpoints.' - ): - return InvalidEndpointConfigurationError(msg=msg) - if msg == 'EndpointId must be a valid host label.': - return InvalidEndpointConfigurationError(msg=msg) - return None diff --git a/spaces/BigBoyBranding/README/README.md b/spaces/BigBoyBranding/README/README.md deleted file mode 100644 index acb7726e157c447579e0aac623d25363a7c9f93d..0000000000000000000000000000000000000000 --- a/spaces/BigBoyBranding/README/README.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: README -emoji: 🏃 -colorFrom: red -colorTo: indigo -sdk: static -pinned: false ---- - -Big Bird's Ballsack \ No newline at end of file diff --git a/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/tools/README.md b/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/tools/README.md deleted file mode 100644 index 3733863970218bf8bdf9b32420163f4c858e209e..0000000000000000000000000000000000000000 --- a/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/tools/README.md +++ /dev/null @@ -1,45 +0,0 @@ - -This directory contains a few scripts that use detectron2. - - -* `train_net.py` - -An example training script that's made to train builtin models of detectron2. - -For usage, see [GETTING_STARTED.md](../GETTING_STARTED.md). - -* `plain_train_net.py` - -Similar to `train_net.py`, but implements a training loop instead of using `Trainer`. -This script includes fewer features but it may be more friendly to hackers. - -* `benchmark.py` - -Benchmark the training speed, inference speed or data loading speed of a given config. - -Usage: -``` -python benchmark.py --config-file config.yaml --task train/eval/data [optional DDP flags] -``` - -* `visualize_json_results.py` - -Visualize the json instance detection/segmentation results dumped by `COCOEvalutor` or `LVISEvaluator` - -Usage: -``` -python visualize_json_results.py --input x.json --output dir/ --dataset coco_2017_val -``` -If not using a builtin dataset, you'll need your own script or modify this script. - -* `visualize_data.py` - -Visualize ground truth raw annotations or training data (after preprocessing/augmentations). - -Usage: -``` -python visualize_data.py --config-file config.yaml --source annotation/dataloader --output-dir dir/ [--show] -``` - -NOTE: the script does not stop by itself when using `--source dataloader` because a training -dataloader is usually infinite. diff --git a/spaces/CVPR/Text2Human/Text2Human/models/archs/shape_attr_embedding_arch.py b/spaces/CVPR/Text2Human/Text2Human/models/archs/shape_attr_embedding_arch.py deleted file mode 100644 index 217c179be3591173596bac7eb1df277e6b1a3c23..0000000000000000000000000000000000000000 --- a/spaces/CVPR/Text2Human/Text2Human/models/archs/shape_attr_embedding_arch.py +++ /dev/null @@ -1,35 +0,0 @@ -import torch -import torch.nn.functional as F -from torch import nn - - -class ShapeAttrEmbedding(nn.Module): - - def __init__(self, dim, out_dim, cls_num_list): - super(ShapeAttrEmbedding, self).__init__() - - for idx, cls_num in enumerate(cls_num_list): - setattr( - self, f'attr_{idx}', - nn.Sequential( - nn.Linear(cls_num, dim), nn.LeakyReLU(), - nn.Linear(dim, dim))) - self.cls_num_list = cls_num_list - self.attr_num = len(cls_num_list) - self.fusion = nn.Sequential( - nn.Linear(dim * self.attr_num, out_dim), nn.LeakyReLU(), - nn.Linear(out_dim, out_dim)) - - def forward(self, attr): - attr_embedding_list = [] - for idx in range(self.attr_num): - attr_embed_fc = getattr(self, f'attr_{idx}') - attr_embedding_list.append( - attr_embed_fc( - F.one_hot( - attr[:, idx], - num_classes=self.cls_num_list[idx]).to(torch.float32))) - attr_embedding = torch.cat(attr_embedding_list, dim=1) - attr_embedding = self.fusion(attr_embedding) - - return attr_embedding diff --git a/spaces/CVPR/WALT/mmdet/models/roi_heads/mask_heads/feature_relay_head.py b/spaces/CVPR/WALT/mmdet/models/roi_heads/mask_heads/feature_relay_head.py deleted file mode 100644 index a1cfb2ce8631d51e5c465f9bbc4164a37acc4782..0000000000000000000000000000000000000000 --- a/spaces/CVPR/WALT/mmdet/models/roi_heads/mask_heads/feature_relay_head.py +++ /dev/null @@ -1,55 +0,0 @@ -import torch.nn as nn -from mmcv.cnn import kaiming_init -from mmcv.runner import auto_fp16 - -from mmdet.models.builder import HEADS - - -@HEADS.register_module() -class FeatureRelayHead(nn.Module): - """Feature Relay Head used in `SCNet `_. - - Args: - in_channels (int, optional): number of input channels. Default: 256. - conv_out_channels (int, optional): number of output channels before - classification layer. Default: 256. - roi_feat_size (int, optional): roi feat size at box head. Default: 7. - scale_factor (int, optional): scale factor to match roi feat size - at mask head. Default: 2. - """ - - def __init__(self, - in_channels=1024, - out_conv_channels=256, - roi_feat_size=7, - scale_factor=2): - super(FeatureRelayHead, self).__init__() - assert isinstance(roi_feat_size, int) - - self.in_channels = in_channels - self.out_conv_channels = out_conv_channels - self.roi_feat_size = roi_feat_size - self.out_channels = (roi_feat_size**2) * out_conv_channels - self.scale_factor = scale_factor - self.fp16_enabled = False - - self.fc = nn.Linear(self.in_channels, self.out_channels) - self.upsample = nn.Upsample( - scale_factor=scale_factor, mode='bilinear', align_corners=True) - - def init_weights(self): - """Init weights for the head.""" - kaiming_init(self.fc) - - @auto_fp16() - def forward(self, x): - """Forward function.""" - N, in_C = x.shape - if N > 0: - out_C = self.out_conv_channels - out_HW = self.roi_feat_size - x = self.fc(x) - x = x.reshape(N, out_C, out_HW, out_HW) - x = self.upsample(x) - return x - return None diff --git a/spaces/CVPR/lama-example/bin/paper_runfiles/find_best_checkpoint.py b/spaces/CVPR/lama-example/bin/paper_runfiles/find_best_checkpoint.py deleted file mode 100644 index 42f5e0f9bb1a2ea25dd9a97a58cf318e6de19532..0000000000000000000000000000000000000000 --- a/spaces/CVPR/lama-example/bin/paper_runfiles/find_best_checkpoint.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python3 - - -import os -from argparse import ArgumentParser - - -def ssim_fid100_f1(metrics, fid_scale=100): - ssim = metrics.loc['total', 'ssim']['mean'] - fid = metrics.loc['total', 'fid']['mean'] - fid_rel = max(0, fid_scale - fid) / fid_scale - f1 = 2 * ssim * fid_rel / (ssim + fid_rel + 1e-3) - return f1 - - -def find_best_checkpoint(model_list, models_dir): - with open(model_list) as f: - models = [m.strip() for m in f.readlines()] - with open(f'{model_list}_best', 'w') as f: - for model in models: - print(model) - best_f1 = 0 - best_epoch = 0 - best_step = 0 - with open(os.path.join(models_dir, model, 'train.log')) as fm: - lines = fm.readlines() - for line_index in range(len(lines)): - line = lines[line_index] - if 'Validation metrics after epoch' in line: - sharp_index = line.index('#') - cur_ep = line[sharp_index + 1:] - comma_index = cur_ep.index(',') - cur_ep = int(cur_ep[:comma_index]) - total_index = line.index('total ') - step = int(line[total_index:].split()[1].strip()) - total_line = lines[line_index + 5] - if not total_line.startswith('total'): - continue - words = total_line.strip().split() - f1 = float(words[-1]) - print(f'\tEpoch: {cur_ep}, f1={f1}') - if f1 > best_f1: - best_f1 = f1 - best_epoch = cur_ep - best_step = step - f.write(f'{model}\t{best_epoch}\t{best_step}\t{best_f1}\n') - - -if __name__ == '__main__': - parser = ArgumentParser() - parser.add_argument('model_list') - parser.add_argument('models_dir') - args = parser.parse_args() - find_best_checkpoint(args.model_list, args.models_dir) diff --git a/spaces/CVPR/lama-example/fetch_data/sampler.py b/spaces/CVPR/lama-example/fetch_data/sampler.py deleted file mode 100644 index b25fa1fefc20f7f4eea7dbb69e54a8075570a1d1..0000000000000000000000000000000000000000 --- a/spaces/CVPR/lama-example/fetch_data/sampler.py +++ /dev/null @@ -1,39 +0,0 @@ -import os -import random - -test_files_path = os.path.abspath('.') + '/places_standard_dataset/original/test/' -test_files = [test_files_path + image for image in os.listdir(test_files_path)] -print(f'found {len(test_files)} images in {test_files_path}') - -random.shuffle(test_files) -test_files_random = test_files[0:2000] -#print(test_files_random[0:10]) - -list_of_random_test_files = os.path.abspath('.') \ -+ '/places_standard_dataset/original/test_random_files.txt' - -print(f'copying 100 random images to {list_of_random_test_files}') -with open(list_of_random_test_files, 'w') as fw: - for filename in test_files_random: - fw.write(filename+'\n') -print('...done') - -# ---------------------------------------------------------------------------------- - - -val_files_path = os.path.abspath('.') + '/places_standard_dataset/original/val/' -val_files = [val_files_path + image for image in os.listdir(val_files_path)] -print(f'found {len(val_files)} images in {val_files_path}') - -random.shuffle(val_files) -val_files_random = val_files[0:100] - -list_of_random_val_files = os.path.abspath('.') \ -+ '/places_standard_dataset/original/val_random_files.txt' - -print(f'copying 100 random images to {list_of_random_val_files}') -with open(list_of_random_val_files, 'w') as fw: - for filename in val_files_random: - fw.write(filename+'\n') -print('...done') - diff --git a/spaces/ChrisPreston/diff-svc_minato_aqua/utils/svc_utils.py b/spaces/ChrisPreston/diff-svc_minato_aqua/utils/svc_utils.py deleted file mode 100644 index 6fea0c1ee280fa7c8927c3d692a482fd50f6660a..0000000000000000000000000000000000000000 --- a/spaces/ChrisPreston/diff-svc_minato_aqua/utils/svc_utils.py +++ /dev/null @@ -1,141 +0,0 @@ -import glob -import importlib -import os - -import matplotlib -import numpy as np -import torch -import torch.distributions -import torch.optim -import torch.optim -import torch.utils.data - -from preprocessing.process_pipeline import File2Batch -from utils.hparams import hparams -from utils.indexed_datasets import IndexedDataset -from utils.pitch_utils import norm_interp_f0 - -matplotlib.use('Agg') - - -class SvcDataset(torch.utils.data.Dataset): - def __init__(self, prefix, shuffle=False): - super().__init__() - self.hparams = hparams - self.shuffle = shuffle - self.sort_by_len = hparams['sort_by_len'] - self.sizes = None - self.data_dir = hparams['binary_data_dir'] - self.prefix = prefix - self.sizes = np.load(f'{self.data_dir}/{self.prefix}_lengths.npy') - self.indexed_ds = None - # self.name2spk_id={} - - # pitch stats - f0_stats_fn = f'{self.data_dir}/train_f0s_mean_std.npy' - if os.path.exists(f0_stats_fn): - hparams['f0_mean'], hparams['f0_std'] = self.f0_mean, self.f0_std = np.load(f0_stats_fn) - hparams['f0_mean'] = float(hparams['f0_mean']) - hparams['f0_std'] = float(hparams['f0_std']) - else: - hparams['f0_mean'], hparams['f0_std'] = self.f0_mean, self.f0_std = None, None - - if prefix == 'test': - if hparams['test_input_dir'] != '': - self.indexed_ds, self.sizes = self.load_test_inputs(hparams['test_input_dir']) - else: - if hparams['num_test_samples'] > 0: - self.avail_idxs = list(range(hparams['num_test_samples'])) + hparams['test_ids'] - self.sizes = [self.sizes[i] for i in self.avail_idxs] - - @property - def _sizes(self): - return self.sizes - - def _get_item(self, index): - if hasattr(self, 'avail_idxs') and self.avail_idxs is not None: - index = self.avail_idxs[index] - if self.indexed_ds is None: - self.indexed_ds = IndexedDataset(f'{self.data_dir}/{self.prefix}') - return self.indexed_ds[index] - - def __getitem__(self, index): - item = self._get_item(index) - max_frames = hparams['max_frames'] - spec = torch.Tensor(item['mel'])[:max_frames] - # energy = (spec.exp() ** 2).sum(-1).sqrt() - mel2ph = torch.LongTensor(item['mel2ph'])[:max_frames] if 'mel2ph' in item else None - f0, uv = norm_interp_f0(item["f0"][:max_frames], hparams) - hubert = torch.Tensor(item['hubert'][:hparams['max_input_tokens']]) - pitch = torch.LongTensor(item.get("pitch"))[:max_frames] - sample = { - "id": index, - "item_name": item['item_name'], - "hubert": hubert, - "mel": spec, - "pitch": pitch, - "f0": f0, - "uv": uv, - "mel2ph": mel2ph, - "mel_nonpadding": spec.abs().sum(-1) > 0, - } - if hparams['use_energy_embed']: - sample['energy'] = item['energy'] - if hparams['use_spk_embed']: - sample["spk_embed"] = torch.Tensor(item['spk_embed']) - if hparams['use_spk_id']: - sample["spk_id"] = item['spk_id'] - return sample - - @staticmethod - def collater(samples): - return File2Batch.processed_input2batch(samples) - - @staticmethod - def load_test_inputs(test_input_dir): - inp_wav_paths = glob.glob(f'{test_input_dir}/*.wav') + glob.glob(f'{test_input_dir}/*.mp3') - sizes = [] - items = [] - - binarizer_cls = hparams.get("binarizer_cls", 'basics.base_binarizer.BaseBinarizer') - pkg = ".".join(binarizer_cls.split(".")[:-1]) - cls_name = binarizer_cls.split(".")[-1] - binarizer_cls = getattr(importlib.import_module(pkg), cls_name) - from preprocessing.hubertinfer import HubertEncoder - for wav_fn in inp_wav_paths: - item_name = os.path.basename(wav_fn) - wav_fn = wav_fn - encoder = HubertEncoder(hparams['hubert_path']) - item = binarizer_cls.process_item(item_name, {'wav_fn': wav_fn}, encoder) - print(item) - items.append(item) - sizes.append(item['len']) - return items, sizes - - def __len__(self): - return len(self._sizes) - - 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``.""" - size = min(self._sizes[index], hparams['max_frames']) - return size - - def ordered_indices(self): - """Return an ordered list of indices. Batches will be constructed based - on this order.""" - if self.shuffle: - indices = np.random.permutation(len(self)) - if self.sort_by_len: - indices = indices[np.argsort(np.array(self._sizes)[indices], kind='mergesort')] - # 先random, 然后稳定排序, 保证排序后同长度的数据顺序是依照random permutation的 (被其随机打乱). - else: - indices = np.arange(len(self)) - return indices - - @property - def num_workers(self): - return int(os.getenv('NUM_WORKERS', hparams['ds_workers'])) diff --git a/spaces/Cicooo/vits-uma-genshin-honkai/models.py b/spaces/Cicooo/vits-uma-genshin-honkai/models.py deleted file mode 100644 index 52e15d1b9775038fd6e82b2efe6f95f51c66802d..0000000000000000000000000000000000000000 --- a/spaces/Cicooo/vits-uma-genshin-honkai/models.py +++ /dev/null @@ -1,534 +0,0 @@ -import math -import torch -from torch import nn -from torch.nn import functional as F - -import commons -import modules -import attentions -import monotonic_align - -from torch.nn import Conv1d, ConvTranspose1d, Conv2d -from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm -from commons import init_weights, get_padding - - -class StochasticDurationPredictor(nn.Module): - def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0): - super().__init__() - filter_channels = in_channels # it needs to be removed from future version. - self.in_channels = in_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.log_flow = modules.Log() - self.flows = nn.ModuleList() - self.flows.append(modules.ElementwiseAffine(2)) - for i in range(n_flows): - self.flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)) - self.flows.append(modules.Flip()) - - self.post_pre = nn.Conv1d(1, filter_channels, 1) - self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1) - self.post_convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout) - self.post_flows = nn.ModuleList() - self.post_flows.append(modules.ElementwiseAffine(2)) - for i in range(4): - self.post_flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)) - self.post_flows.append(modules.Flip()) - - self.pre = nn.Conv1d(in_channels, filter_channels, 1) - self.proj = nn.Conv1d(filter_channels, filter_channels, 1) - self.convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout) - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, filter_channels, 1) - - def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0): - x = torch.detach(x) - x = self.pre(x) - if g is not None: - g = torch.detach(g) - x = x + self.cond(g) - x = self.convs(x, x_mask) - x = self.proj(x) * x_mask - - if not reverse: - flows = self.flows - assert w is not None - - logdet_tot_q = 0 - h_w = self.post_pre(w) - h_w = self.post_convs(h_w, x_mask) - h_w = self.post_proj(h_w) * x_mask - e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask - z_q = e_q - for flow in self.post_flows: - z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w)) - logdet_tot_q += logdet_q - z_u, z1 = torch.split(z_q, [1, 1], 1) - u = torch.sigmoid(z_u) * x_mask - z0 = (w - u) * x_mask - logdet_tot_q += torch.sum((F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1,2]) - logq = torch.sum(-0.5 * (math.log(2*math.pi) + (e_q**2)) * x_mask, [1,2]) - logdet_tot_q - - logdet_tot = 0 - z0, logdet = self.log_flow(z0, x_mask) - logdet_tot += logdet - z = torch.cat([z0, z1], 1) - for flow in flows: - z, logdet = flow(z, x_mask, g=x, reverse=reverse) - logdet_tot = logdet_tot + logdet - nll = torch.sum(0.5 * (math.log(2*math.pi) + (z**2)) * x_mask, [1,2]) - logdet_tot - return nll + logq # [b] - else: - flows = list(reversed(self.flows)) - flows = flows[:-2] + [flows[-1]] # remove a useless vflow - z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale - for flow in flows: - z = flow(z, x_mask, g=x, reverse=reverse) - z0, z1 = torch.split(z, [1, 1], 1) - logw = z0 - return logw - - -class DurationPredictor(nn.Module): - def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0): - super().__init__() - - self.in_channels = in_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.gin_channels = gin_channels - - self.drop = nn.Dropout(p_dropout) - self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size//2) - self.norm_1 = modules.LayerNorm(filter_channels) - self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2) - self.norm_2 = modules.LayerNorm(filter_channels) - self.proj = nn.Conv1d(filter_channels, 1, 1) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, in_channels, 1) - - def forward(self, x, x_mask, g=None): - x = torch.detach(x) - if g is not None: - g = torch.detach(g) - x = x + self.cond(g) - x = self.conv_1(x * x_mask) - x = torch.relu(x) - x = self.norm_1(x) - x = self.drop(x) - x = self.conv_2(x * x_mask) - x = torch.relu(x) - x = self.norm_2(x) - x = self.drop(x) - x = self.proj(x * x_mask) - return x * x_mask - - -class TextEncoder(nn.Module): - def __init__(self, - n_vocab, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout): - super().__init__() - self.n_vocab = n_vocab - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - - self.emb = nn.Embedding(n_vocab, hidden_channels) - nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5) - - self.encoder = attentions.Encoder( - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout) - self.proj= nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, x, x_lengths): - x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h] - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype) - - x = self.encoder(x * x_mask, x_mask) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return x, m, logs, x_mask - - -class ResidualCouplingBlock(nn.Module): - def __init__(self, - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - n_flows=4, - gin_channels=0): - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.flows = nn.ModuleList() - for i in range(n_flows): - self.flows.append(modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels, mean_only=True)) - self.flows.append(modules.Flip()) - - def forward(self, x, x_mask, g=None, reverse=False): - if not reverse: - for flow in self.flows: - x, _ = flow(x, x_mask, g=g, reverse=reverse) - else: - for flow in reversed(self.flows): - x = flow(x, x_mask, g=g, reverse=reverse) - return x - - -class PosteriorEncoder(nn.Module): - def __init__(self, - in_channels, - out_channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=0): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.gin_channels = gin_channels - - self.pre = nn.Conv1d(in_channels, hidden_channels, 1) - self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, x, x_lengths, g=None): - x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype) - x = self.pre(x) * x_mask - x = self.enc(x, x_mask, g=g) - stats = self.proj(x) * x_mask - m, logs = torch.split(stats, self.out_channels, dim=1) - z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask - return z, m, logs, x_mask - - -class Generator(torch.nn.Module): - def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=0): - super(Generator, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3) - resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - self.ups.append(weight_norm( - ConvTranspose1d(upsample_initial_channel//(2**i), upsample_initial_channel//(2**(i+1)), - k, u, padding=(k-u)//2))) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel//(2**(i+1)) - for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - def forward(self, x, g=None): - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i*self.num_kernels+j](x) - else: - xs += self.resblocks[i*self.num_kernels+j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - - return x - - def remove_weight_norm(self): - print('Removing weight norm...') - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -class DiscriminatorP(torch.nn.Module): - def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): - super(DiscriminatorP, self).__init__() - self.period = period - self.use_spectral_norm = use_spectral_norm - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList([ - norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), - norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), - norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), - norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), - norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))), - ]) - self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0))) - - def forward(self, x): - fmap = [] - - # 1d to 2d - b, c, t = x.shape - if t % self.period != 0: # pad first - n_pad = self.period - (t % self.period) - x = F.pad(x, (0, n_pad), "reflect") - t = t + n_pad - x = x.view(b, c, t // self.period, self.period) - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap - - -class DiscriminatorS(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(DiscriminatorS, self).__init__() - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList([ - norm_f(Conv1d(1, 16, 15, 1, padding=7)), - norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)), - norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)), - norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)), - norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)), - norm_f(Conv1d(1024, 1024, 5, 1, padding=2)), - ]) - self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1)) - - def forward(self, x): - fmap = [] - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap - - -class MultiPeriodDiscriminator(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(MultiPeriodDiscriminator, self).__init__() - periods = [2,3,5,7,11] - - discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] - discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods] - self.discriminators = nn.ModuleList(discs) - - def forward(self, y, y_hat): - y_d_rs = [] - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y) - y_d_g, fmap_g = d(y_hat) - y_d_rs.append(y_d_r) - y_d_gs.append(y_d_g) - fmap_rs.append(fmap_r) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - - - -class SynthesizerTrn(nn.Module): - """ - Synthesizer for Training - """ - - def __init__(self, - n_vocab, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - n_speakers=0, - gin_channels=0, - use_sdp=True, - **kwargs): - - super().__init__() - self.n_vocab = n_vocab - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.n_speakers = n_speakers - self.gin_channels = gin_channels - - self.use_sdp = use_sdp - - self.enc_p = TextEncoder(n_vocab, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout) - self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels) - self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels) - self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels) - - if use_sdp: - self.dp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels) - else: - self.dp = DurationPredictor(hidden_channels, 256, 3, 0.5, gin_channels=gin_channels) - - if n_speakers > 1: - self.emb_g = nn.Embedding(n_speakers, gin_channels) - - def forward(self, x, x_lengths, y, y_lengths, sid=None): - - x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths) - if self.n_speakers > 0: - g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1] - else: - g = None - - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - - with torch.no_grad(): - # negative cross-entropy - s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t] - neg_cent1 = torch.sum(-0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True) # [b, 1, t_s] - neg_cent2 = torch.matmul(-0.5 * (z_p ** 2).transpose(1, 2), s_p_sq_r) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s] - neg_cent3 = torch.matmul(z_p.transpose(1, 2), (m_p * s_p_sq_r)) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s] - neg_cent4 = torch.sum(-0.5 * (m_p ** 2) * s_p_sq_r, [1], keepdim=True) # [b, 1, t_s] - neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4 - - attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1) - attn = monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach() - - w = attn.sum(2) - if self.use_sdp: - l_length = self.dp(x, x_mask, w, g=g) - l_length = l_length / torch.sum(x_mask) - else: - logw_ = torch.log(w + 1e-6) * x_mask - logw = self.dp(x, x_mask, g=g) - l_length = torch.sum((logw - logw_)**2, [1,2]) / torch.sum(x_mask) # for averaging - - # expand prior - m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) - logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2) - - z_slice, ids_slice = commons.rand_slice_segments(z, y_lengths, self.segment_size) - o = self.dec(z_slice, g=g) - return o, l_length, attn, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, x, x_lengths, sid=None, noise_scale=1, length_scale=1, noise_scale_w=1., max_len=None): - device = next(self.parameters()).device # 获取模型所在的设备 - x, m_p, logs_p, x_mask = self.enc_p(x.to(device), x_lengths.to(device)) - if self.n_speakers > 0: - g = self.emb_g(sid.to(device)).unsqueeze(-1) # [b, h, 1] - else: - g = None - - if self.use_sdp: - logw = self.dp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w) - else: - logw = self.dp(x, x_mask, g=g) - w = torch.exp(logw) * x_mask * length_scale - w_ceil = torch.ceil(w) - y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long() - y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype) - attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1) - attn = commons.generate_path(w_ceil, attn_mask) - - m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t'] - logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t'] - - z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale - z = self.flow(z_p, y_mask, g=g, reverse=True) - o = self.dec((z * y_mask)[:,:,:max_len], g=g) - return o, attn, y_mask, (z, z_p, m_p, logs_p) - - def voice_conversion(self, y, y_lengths, sid_src, sid_tgt): - assert self.n_speakers > 0, "n_speakers have to be larger than 0." - g_src = self.emb_g(sid_src).unsqueeze(-1) - g_tgt = self.emb_g(sid_tgt).unsqueeze(-1) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g_src) - z_p = self.flow(z, y_mask, g=g_src) - z_hat = self.flow(z_p, y_mask, g=g_tgt, reverse=True) - o_hat = self.dec(z_hat * y_mask, g=g_tgt) - return o_hat, y_mask, (z, z_p, z_hat) - diff --git a/spaces/CofAI/chat/server/website.py b/spaces/CofAI/chat/server/website.py deleted file mode 100644 index 01b35dee1621b5b5bea49de330466ebb62817f20..0000000000000000000000000000000000000000 --- a/spaces/CofAI/chat/server/website.py +++ /dev/null @@ -1,58 +0,0 @@ -from flask import render_template, redirect, url_for, request, session -from flask_babel import refresh -from time import time -from os import urandom -from server.babel import get_locale, get_languages - - -class Website: - def __init__(self, bp, url_prefix) -> None: - self.bp = bp - self.url_prefix = url_prefix - self.routes = { - '/': { - 'function': lambda: redirect(url_for('._index')), - 'methods': ['GET', 'POST'] - }, - '/chat/': { - 'function': self._index, - 'methods': ['GET', 'POST'] - }, - '/chat/': { - 'function': self._chat, - 'methods': ['GET', 'POST'] - }, - '/change-language': { - 'function': self.change_language, - 'methods': ['POST'] - }, - '/get-locale': { - 'function': self.get_locale, - 'methods': ['GET'] - }, - '/get-languages': { - 'function': self.get_languages, - 'methods': ['GET'] - } - } - - def _chat(self, conversation_id): - if '-' not in conversation_id: - return redirect(url_for('._index')) - - return render_template('index.html', chat_id=conversation_id, url_prefix=self.url_prefix) - - def _index(self): - return render_template('index.html', chat_id=f'{urandom(4).hex()}-{urandom(2).hex()}-{urandom(2).hex()}-{urandom(2).hex()}-{hex(int(time() * 1000))[2:]}', url_prefix=self.url_prefix) - - def change_language(self): - data = request.get_json() - session['language'] = data.get('language') - refresh() - return '', 204 - - def get_locale(self): - return get_locale() - - def get_languages(self): - return get_languages() diff --git a/spaces/CoreyMorris/MMLU-by-task-Leaderboard/save_for_regression.py b/spaces/CoreyMorris/MMLU-by-task-Leaderboard/save_for_regression.py deleted file mode 100644 index 047ac6eb876dfd8b2a1d153dd850807a76397122..0000000000000000000000000000000000000000 --- a/spaces/CoreyMorris/MMLU-by-task-Leaderboard/save_for_regression.py +++ /dev/null @@ -1,55 +0,0 @@ -# when run -# checks if there is uncommitted code -# if there is uncommitted code, ti retuns an error -# if there is no uncommitted code, it saves the dataframe as a parquet file with the commit hash in the name - -import pytest -import pandas as pd -from result_data_processor import ResultDataProcessor - -import os - -import subprocess - -def check_git_changes(repo_path): - try: - # Change to the repository directory - original_path = os.getcwd() - os.chdir(repo_path) - - # Run the git status command - result = subprocess.run(['git', 'status', '--porcelain'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) - - # Check the result - if result.returncode != 0: - print(f"Error checking git status: {result.stderr}") - return False, False - - # Check for tracked and untracked changes - tracked_changes = any(line[:2].strip() != '??' for line in result.stdout.splitlines()) - untracked_changes = any(line[:2] == '??' for line in result.stdout.splitlines()) - - return tracked_changes, untracked_changes - - finally: - # Change back to the original directory - os.chdir(original_path) - -if __name__ == '__main__': - tracked_changes, untracked_changes = check_git_changes('.') - if tracked_changes: - print("There are tracked changes") - else: - print("There are no tracked changes") - df_current = ResultDataProcessor().data - last_commit = os.popen('git rev-parse HEAD').read().strip() - print(last_commit) - # save the current output to a file - df_current.to_parquet(f'dataframe_history/output_{last_commit}.parquet', index=True) - print("Saved output to file") - if untracked_changes: - print("There are untracked changes") - else: - print("There are no untracked changes") - - diff --git a/spaces/Cyril666/ContourNet-ABI/maskrcnn_benchmark/modeling/backbone/resnet.py b/spaces/Cyril666/ContourNet-ABI/maskrcnn_benchmark/modeling/backbone/resnet.py deleted file mode 100644 index 39adf1520463abcf5778a674c7e4d5fb3dc0163d..0000000000000000000000000000000000000000 --- a/spaces/Cyril666/ContourNet-ABI/maskrcnn_benchmark/modeling/backbone/resnet.py +++ /dev/null @@ -1,498 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. -""" -Variant of the resnet module that takes cfg as an argument. -Example usage. Strings may be specified in the config file. - model = ResNet( - "StemWithFixedBatchNorm", - "BottleneckWithFixedBatchNorm", - "ResNet50StagesTo4", - ) -OR: - model = ResNet( - "StemWithGN", - "BottleneckWithGN", - "ResNet50StagesTo4", - ) -Custom implementations may be written in user code and hooked in via the -`register_*` functions. -""" -from collections import namedtuple - -import torch -import torch.nn.functional as F -from torch import nn - -from maskrcnn_benchmark.layers import FrozenBatchNorm2d -from maskrcnn_benchmark.layers import Conv2d -from maskrcnn_benchmark.modeling.make_layers import group_norm -from maskrcnn_benchmark.layers import DCN -from maskrcnn_benchmark.utils.registry import Registry - - -# ResNet stage specification -StageSpec = namedtuple( - "StageSpec", - [ - "index", # Index of the stage, eg 1, 2, ..,. 5 - "block_count", # Number of residual blocks in the stage - "return_features", # True => return the last feature map from this stage - ], -) - -# ----------------------------------------------------------------------------- -# Standard ResNet models -# ----------------------------------------------------------------------------- -# ResNet-50 (including all stages) -ResNet50StagesTo5 = tuple( - StageSpec(index=i, block_count=c, return_features=r) - for (i, c, r) in ((1, 3, False), (2, 4, False), (3, 6, False), (4, 3, True)) -) -# ResNet-50 up to stage 4 (excludes stage 5) -ResNet50StagesTo4 = tuple( - StageSpec(index=i, block_count=c, return_features=r) - for (i, c, r) in ((1, 3, False), (2, 4, False), (3, 6, True)) -) -# ResNet-101 (including all stages) -ResNet101StagesTo5 = tuple( - StageSpec(index=i, block_count=c, return_features=r) - for (i, c, r) in ((1, 3, False), (2, 4, False), (3, 23, False), (4, 3, True)) -) -# ResNet-101 up to stage 4 (excludes stage 5) -ResNet101StagesTo4 = tuple( - StageSpec(index=i, block_count=c, return_features=r) - for (i, c, r) in ((1, 3, False), (2, 4, False), (3, 23, True)) -) -# ResNet-50-FPN (including all stages) -ResNet50FPNStagesTo5 = tuple( - StageSpec(index=i, block_count=c, return_features=r) - for (i, c, r) in ((1, 3, True), (2, 4, True), (3, 6, True), (4, 3, True)) -) -# ResNet-101-FPN (including all stages) -ResNet101FPNStagesTo5 = tuple( - StageSpec(index=i, block_count=c, return_features=r) - for (i, c, r) in ((1, 3, True), (2, 4, True), (3, 23, True), (4, 3, True)) -) -# ResNet-152-FPN (including all stages) -ResNet152FPNStagesTo5 = tuple( - StageSpec(index=i, block_count=c, return_features=r) - for (i, c, r) in ((1, 3, True), (2, 8, True), (3, 36, True), (4, 3, True)) -) - -class ResNet(nn.Module): - def __init__(self, cfg): - super(ResNet, self).__init__() - - # If we want to use the cfg in forward(), then we should make a copy - # of it and store it for later use: - # self.cfg = cfg.clone() - - # Translate string names to implementations - stem_module = _STEM_MODULES[cfg.MODEL.RESNETS.STEM_FUNC] - stage_specs = _STAGE_SPECS[cfg.MODEL.BACKBONE.CONV_BODY] - transformation_module = _TRANSFORMATION_MODULES[cfg.MODEL.RESNETS.TRANS_FUNC] - deformable_module = _TRANSFORMATION_MODULES[cfg.MODEL.RESNETS.DEF_FUNC] - start_module = cfg.MODEL.RESNETS.DEF_START_MODULE - _DEF_IDX = {"C3": 1, "C4": 2, "C5": 3} - if start_module in _DEF_IDX: - start_idx = _DEF_IDX[start_module] - else: - start_idx = 65535 - - # Construct the stem module - self.stem = stem_module(cfg) - - # Constuct the specified ResNet stages - num_groups = cfg.MODEL.RESNETS.NUM_GROUPS - width_per_group = cfg.MODEL.RESNETS.WIDTH_PER_GROUP - in_channels = cfg.MODEL.RESNETS.STEM_OUT_CHANNELS - stage2_bottleneck_channels = num_groups * width_per_group - stage2_out_channels = cfg.MODEL.RESNETS.RES2_OUT_CHANNELS - self.stages = [] - self.return_features = {} - for i, stage_spec in enumerate(stage_specs): - name = "layer" + str(stage_spec.index) - stage2_relative_factor = 2 ** (stage_spec.index - 1) - bottleneck_channels = stage2_bottleneck_channels * stage2_relative_factor - out_channels = stage2_out_channels * stage2_relative_factor - if i >= start_idx: - trans_mod = deformable_module - else: - trans_mod = transformation_module - module = _make_stage( - trans_mod, - in_channels, - bottleneck_channels, - out_channels, - stage_spec.block_count, - num_groups, - cfg.MODEL.RESNETS.STRIDE_IN_1X1, - first_stride=int(stage_spec.index > 1) + 1, - ) - in_channels = out_channels - self.add_module(name, module) - self.stages.append(name) - self.return_features[name] = stage_spec.return_features - - # Optionally freeze (requires_grad=False) parts of the backbone - self._freeze_backbone(cfg.MODEL.BACKBONE.FREEZE_CONV_BODY_AT) - - def _freeze_backbone(self, freeze_at): - if freeze_at < 0: - return - for stage_index in range(freeze_at): - if stage_index == 0: - m = self.stem # stage 0 is the stem - else: - m = getattr(self, "layer" + str(stage_index)) - for p in m.parameters(): - p.requires_grad = False - - def forward(self, x): - outputs = [] - x = self.stem(x) - for stage_name in self.stages: - x = getattr(self, stage_name)(x) - if self.return_features[stage_name]: - outputs.append(x) - return outputs - - -class ResNetHead(nn.Module): - def __init__( - self, - block_module, - stages, - num_groups=1, - width_per_group=64, - stride_in_1x1=True, - stride_init=None, - res2_out_channels=256, - dilation=1 - ): - super(ResNetHead, self).__init__() - - stage2_relative_factor = 2 ** (stages[0].index - 1) - # print('stage2_relative_factor---',stage2_relative_factor) - - stage2_bottleneck_channels = num_groups * width_per_group - # print('stage2_bottleneck_channels---',stage2_bottleneck_channels) - - out_channels = res2_out_channels * stage2_relative_factor - # print('out_channels---',out_channels) - - in_channels = out_channels // 2 - # print('in_channels---',in_channels) - # - bottleneck_channels = stage2_bottleneck_channels * stage2_relative_factor - # print('bottleneck_channels---',bottleneck_channels) - - block_module = _TRANSFORMATION_MODULES[block_module] - # print('block_module---',block_module) - - - self.stages = [] - stride = stride_init - for stage in stages: - name = "layer" + str(stage.index) - if not stride: - stride = int(stage.index > 1) + 1 - # print('stride---', stride) - print('stage.block_count---', stage.block_count) - module = _make_stage( - block_module, - in_channels, - bottleneck_channels, - out_channels, - stage.block_count, - num_groups, - stride_in_1x1, - first_stride=stride, - dilation=dilation - ) - stride = None - self.add_module(name, module) - self.stages.append(name) - self.out_channels = out_channels - - def forward(self, x): - for stage in self.stages: - x = getattr(self, stage)(x) - print('x-----------',x.shape) - return x - - -def _make_stage( - transformation_module, - in_channels, - bottleneck_channels, - out_channels, - block_count, - num_groups, - stride_in_1x1, - first_stride, - dilation=1 -): - blocks = [] - stride = first_stride - for _ in range(block_count): - blocks.append( - transformation_module( - in_channels, - bottleneck_channels, - out_channels, - num_groups, - stride_in_1x1, - stride, - dilation=dilation - ) - ) - stride = 1 - in_channels = out_channels - return nn.Sequential(*blocks) - - -class Bottleneck(nn.Module): - def __init__( - self, - in_channels, - bottleneck_channels, - out_channels, - num_groups, - stride_in_1x1, - stride, - dilation, - norm_func, - conv_func=Conv2d - ): - super(Bottleneck, self).__init__() - - self.downsample = None - if in_channels != out_channels: - down_stride = stride if dilation == 1 else 1 - self.downsample = nn.Sequential( - conv_func( - in_channels, out_channels, - kernel_size=1, stride=down_stride, bias=False - ), - norm_func(out_channels), - ) - for modules in [self.downsample,]: - for l in modules.modules(): - if isinstance(l, Conv2d): - nn.init.kaiming_uniform_(l.weight, a=1) - - if dilation > 1: - stride = 1 # reset to be 1 - - # The original MSRA ResNet models have stride in the first 1x1 conv - # The subsequent fb.torch.resnet and Caffe2 ResNe[X]t implementations have - # stride in the 3x3 conv - stride_1x1, stride_3x3 = (stride, 1) if stride_in_1x1 else (1, stride) - - self.conv1 = conv_func( - in_channels, - bottleneck_channels, - kernel_size=1, - stride=stride_1x1, - bias=False, - ) - self.bn1 = norm_func(bottleneck_channels) - # TODO: specify init for the above - - self.conv2 = conv_func( - bottleneck_channels, - bottleneck_channels, - kernel_size=3, - stride=stride_3x3, - padding=dilation, - bias=False, - groups=num_groups, - dilation=dilation - ) - self.bn2 = norm_func(bottleneck_channels) - - self.conv3 = Conv2d( - bottleneck_channels, out_channels, kernel_size=1, bias=False - ) - self.bn3 = norm_func(out_channels) - - for l in [self.conv1, self.conv2, self.conv3,]: - nn.init.kaiming_uniform_(l.weight, a=1) - - def forward(self, x): - identity = x - - out = self.conv1(x) - out = self.bn1(out) - out = F.relu_(out) - - out = self.conv2(out) - out = self.bn2(out) - out = F.relu_(out) - - out0 = self.conv3(out) - out = self.bn3(out0) - - if self.downsample is not None: - identity = self.downsample(x) - - out += identity - out = F.relu_(out) - - return out - - -class BaseStem(nn.Module): - def __init__(self, cfg, norm_func): - super(BaseStem, self).__init__() - - out_channels = cfg.MODEL.RESNETS.STEM_OUT_CHANNELS - - self.conv1 = Conv2d( - 3, out_channels, kernel_size=7, stride=2, padding=3, bias=False - ) - self.bn1 = norm_func(out_channels) - - for l in [self.conv1,]: - nn.init.kaiming_uniform_(l.weight, a=1) - - def forward(self, x): - x = self.conv1(x) - x = self.bn1(x) - x = F.relu_(x) - x = F.max_pool2d(x, kernel_size=3, stride=2, padding=1) - return x - -############################################# - -class BottleneckWithFixedBatchNorm(Bottleneck): - def __init__( - self, - in_channels, - bottleneck_channels, - out_channels, - num_groups=1, - stride_in_1x1=True, - stride=1, - dilation=1 - ): - super(BottleneckWithFixedBatchNorm, self).__init__( - in_channels=in_channels, - bottleneck_channels=bottleneck_channels, - out_channels=out_channels, - num_groups=num_groups, - stride_in_1x1=stride_in_1x1, - stride=stride, - dilation=dilation, - norm_func=FrozenBatchNorm2d - ) - - -class DeformableConvWithFixedBatchNorm(Bottleneck): - def __init__( - self, - in_channels, - bottleneck_channels, - out_channels, - num_groups=1, - stride_in_1x1=True, - stride=1, - dilation=1 - ): - super(DeformableConvWithFixedBatchNorm, self).__init__( - in_channels=in_channels, - bottleneck_channels=bottleneck_channels, - out_channels=out_channels, - num_groups=num_groups, - stride_in_1x1=stride_in_1x1, - stride=stride, - dilation=dilation, - norm_func=FrozenBatchNorm2d, - conv_func=DCN - ) - - -class StemWithFixedBatchNorm(BaseStem): - def __init__(self, cfg): - super(StemWithFixedBatchNorm, self).__init__( - cfg, norm_func=FrozenBatchNorm2d - ) - - -class BottleneckWithGN(Bottleneck): - def __init__( - self, - in_channels, - bottleneck_channels, - out_channels, - num_groups=1, - stride_in_1x1=True, - stride=1, - dilation=1 - ): - super(BottleneckWithGN, self).__init__( - in_channels=in_channels, - bottleneck_channels=bottleneck_channels, - out_channels=out_channels, - num_groups=num_groups, - stride_in_1x1=stride_in_1x1, - stride=stride, - dilation=dilation, - norm_func=group_norm - ) - - -class DeformableConvWithGN(Bottleneck): - def __init__( - self, - in_channels, - bottleneck_channels, - out_channels, - num_groups=1, - stride_in_1x1=True, - stride=1, - dilation=1 - ): - super(DeformableConvWithGN, self).__init__( - in_channels=in_channels, - bottleneck_channels=bottleneck_channels, - out_channels=out_channels, - num_groups=num_groups, - stride_in_1x1=stride_in_1x1, - stride=stride, - dilation=dilation, - norm_func=group_norm, - conv_func=DCN - ) - - -class StemWithGN(BaseStem): - def __init__(self, cfg): - super(StemWithGN, self).__init__(cfg, norm_func=group_norm) - - -_TRANSFORMATION_MODULES = Registry({ - "BottleneckWithFixedBatchNorm": BottleneckWithFixedBatchNorm, - "BottleneckWithGN": BottleneckWithGN, - "DeformableConvWithFixedBatchNorm": DeformableConvWithFixedBatchNorm, - "DeformableConvWithGN": DeformableConvWithGN, -}) - -_STEM_MODULES = Registry({ - "StemWithFixedBatchNorm": StemWithFixedBatchNorm, - "StemWithGN": StemWithGN, -}) - -_STAGE_SPECS = Registry({ - "R-50-C4": ResNet50StagesTo4, - "R-50-C5": ResNet50StagesTo5, - "R-101-C4": ResNet101StagesTo4, - "R-101-C5": ResNet101StagesTo5, - "R-50-FPN": ResNet50FPNStagesTo5, - "R-50-FPN-RETINANET": ResNet50FPNStagesTo5, - "R-101-FPN": ResNet101FPNStagesTo5, - "R-101-PAN": ResNet101FPNStagesTo5, - "R-101-FPN-RETINANET": ResNet101FPNStagesTo5, - "R-152-FPN": ResNet152FPNStagesTo5, - "R-152-PAN": ResNet152FPNStagesTo5, -}) diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/feaLib/lexer.c b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/feaLib/lexer.c deleted file mode 100644 index 1fef32ff3a4213e59ffbf37dce573f65a87cf0da..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/feaLib/lexer.c +++ /dev/null @@ -1,13368 +0,0 @@ -/* Generated by Cython 0.29.36 */ - -/* BEGIN: Cython Metadata -{ - "distutils": { - "name": "fontTools.feaLib.lexer", - "sources": [ - "Lib/fontTools/feaLib/lexer.py" - ] - }, - "module_name": "fontTools.feaLib.lexer" -} -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__feaLib__lexer -#define __PYX_HAVE_API__fontTools__feaLib__lexer -/* 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; - - -static const char *__pyx_f[] = { - "Lib/fontTools/feaLib/lexer.py", -}; - -/*--- Type declarations ---*/ - -/* --- 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); - -/* PyObjectSetAttrStr.proto */ -#if CYTHON_USE_TYPE_SLOTS -#define __Pyx_PyObject_DelAttrStr(o,n) __Pyx_PyObject_SetAttrStr(o, n, NULL) -static CYTHON_INLINE int __Pyx_PyObject_SetAttrStr(PyObject* obj, PyObject* attr_name, PyObject* value); -#else -#define __Pyx_PyObject_DelAttrStr(o,n) PyObject_DelAttr(o,n) -#define __Pyx_PyObject_SetAttrStr(o,n,v) PyObject_SetAttr(o,n,v) -#endif - -/* 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 - -/* 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 - -/* 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 - -/* PyObjectCallMethO.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); -#endif - -/* 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 - -/* 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 - -/* PyObjectCallOneArg.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); - -/* 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_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 - -/* PyObjectCall2Args.proto */ -static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); - -/* PyThreadStateGet.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; -#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; -#define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type -#else -#define __Pyx_PyThreadState_declare -#define __Pyx_PyThreadState_assign -#define __Pyx_PyErr_Occurred() PyErr_Occurred() -#endif - -/* PyErrFetchRestore.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) -#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) -#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) -#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) -#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); -static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) -#else -#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) -#endif -#else -#define __Pyx_PyErr_Clear() PyErr_Clear() -#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) -#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) -#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) -#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) -#endif - -/* RaiseException.proto */ -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); - -/* 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 - -/* IncludeStringH.proto */ -#include - -/* BytesEquals.proto */ -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); - -/* UnicodeEquals.proto */ -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); - -/* SliceObject.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( - PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, - PyObject** py_start, PyObject** py_stop, PyObject** py_slice, - int has_cstart, int has_cstop, int wraparound); - -/* PyIntBinop.proto */ -#if !CYTHON_COMPILING_IN_PYPY -static PyObject* __Pyx_PyInt_SubtractObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); -#else -#define __Pyx_PyInt_SubtractObjC(op1, op2, intval, inplace, zerodivision_check)\ - (inplace ? PyNumber_InPlaceSubtract(op1, op2) : PyNumber_Subtract(op1, op2)) -#endif - -/* PySequenceContains.proto */ -static CYTHON_INLINE int __Pyx_PySequence_ContainsTF(PyObject* item, PyObject* seq, int eq) { - int result = PySequence_Contains(seq, item); - return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); -} - -/* PyUnicodeContains.proto */ -static CYTHON_INLINE int __Pyx_PyUnicode_ContainsTF(PyObject* substring, PyObject* text, int eq) { - int result = PyUnicode_Contains(text, substring); - return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); -} - -/* IterNext.proto */ -#define __Pyx_PyIter_Next(obj) __Pyx_PyIter_Next2(obj, NULL) -static CYTHON_INLINE PyObject *__Pyx_PyIter_Next2(PyObject *, PyObject *); - -/* 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 - -/* 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 - -/* PyObjectGetMethod.proto */ -static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method); - -/* PyObjectCallMethod0.proto */ -static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); - -/* pop.proto */ -static CYTHON_INLINE PyObject* __Pyx__PyObject_Pop(PyObject* L); -#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS -static CYTHON_INLINE PyObject* __Pyx_PyList_Pop(PyObject* L); -#define __Pyx_PyObject_Pop(L) (likely(PyList_CheckExact(L)) ?\ - __Pyx_PyList_Pop(L) : __Pyx__PyObject_Pop(L)) -#else -#define __Pyx_PyList_Pop(L) __Pyx__PyObject_Pop(L) -#define __Pyx_PyObject_Pop(L) __Pyx__PyObject_Pop(L) -#endif - -/* UnpackUnboundCMethod.proto */ -typedef struct { - PyObject *type; - PyObject **method_name; - PyCFunction func; - PyObject *method; - int flag; -} __Pyx_CachedCFunction; - -/* CallUnboundCMethod0.proto */ -static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_CallUnboundCMethod0(cfunc, self)\ - (likely((cfunc)->func) ?\ - (likely((cfunc)->flag == METH_NOARGS) ? (*((cfunc)->func))(self, NULL) :\ - (PY_VERSION_HEX >= 0x030600B1 && likely((cfunc)->flag == METH_FASTCALL) ?\ - (PY_VERSION_HEX >= 0x030700A0 ?\ - (*(__Pyx_PyCFunctionFast)(void*)(PyCFunction)(cfunc)->func)(self, &__pyx_empty_tuple, 0) :\ - (*(__Pyx_PyCFunctionFastWithKeywords)(void*)(PyCFunction)(cfunc)->func)(self, &__pyx_empty_tuple, 0, NULL)) :\ - (PY_VERSION_HEX >= 0x030700A0 && (cfunc)->flag == (METH_FASTCALL | METH_KEYWORDS) ?\ - (*(__Pyx_PyCFunctionFastWithKeywords)(void*)(PyCFunction)(cfunc)->func)(self, &__pyx_empty_tuple, 0, NULL) :\ - (likely((cfunc)->flag == (METH_VARARGS | METH_KEYWORDS)) ? ((*(PyCFunctionWithKeywords)(void*)(PyCFunction)(cfunc)->func)(self, __pyx_empty_tuple, NULL)) :\ - ((cfunc)->flag == METH_VARARGS ? (*((cfunc)->func))(self, __pyx_empty_tuple) :\ - __Pyx__CallUnboundCMethod0(cfunc, self)))))) :\ - __Pyx__CallUnboundCMethod0(cfunc, self)) -#else -#define __Pyx_CallUnboundCMethod0(cfunc, self) __Pyx__CallUnboundCMethod0(cfunc, self) -#endif - -/* ListAppend.proto */ -#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS -static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { - PyListObject* L = (PyListObject*) list; - Py_ssize_t len = Py_SIZE(list); - if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { - Py_INCREF(x); - PyList_SET_ITEM(list, len, x); - __Pyx_SET_SIZE(list, len + 1); - return 0; - } - return PyList_Append(list, x); -} -#else -#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) -#endif - -/* PyObjectCallMethod1.proto */ -static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); - -/* append.proto */ -static CYTHON_INLINE int __Pyx_PyObject_Append(PyObject* L, PyObject* x); - -/* 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) - -/* 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 - -/* GetAttr.proto */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); - -/* HasAttr.proto */ -static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); - -/* GetAttr3.proto */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); - -/* Import.proto */ -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); - -/* ImportFrom.proto */ -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); - -/* CalculateMetaclass.proto */ -static PyObject *__Pyx_CalculateMetaclass(PyTypeObject *metaclass, PyObject *bases); - -/* SetNameInClass.proto */ -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 -#define __Pyx_SetNameInClass(ns, name, value)\ - (likely(PyDict_CheckExact(ns)) ? _PyDict_SetItem_KnownHash(ns, name, value, ((PyASCIIObject *) name)->hash) : PyObject_SetItem(ns, name, value)) -#elif CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_SetNameInClass(ns, name, value)\ - (likely(PyDict_CheckExact(ns)) ? PyDict_SetItem(ns, name, value) : PyObject_SetItem(ns, name, value)) -#else -#define __Pyx_SetNameInClass(ns, name, value) PyObject_SetItem(ns, name, value) -#endif - -/* FetchCommonType.proto */ -static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type); - -/* 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); - -/* Py3ClassCreate.proto */ -static PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, PyObject *qualname, - PyObject *mkw, PyObject *modname, PyObject *doc); -static PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, PyObject *dict, - PyObject *mkw, int calculate_metaclass, int allow_py2_metaclass); - -/* 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); - -/* 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 *); - -/* 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.feaLib.lexer' */ -#define __Pyx_MODULE_NAME "fontTools.feaLib.lexer" -extern int __pyx_module_is_main_fontTools__feaLib__lexer; -int __pyx_module_is_main_fontTools__feaLib__lexer = 0; - -/* Implementation of 'fontTools.feaLib.lexer' */ -static PyObject *__pyx_builtin_ImportError; -static PyObject *__pyx_builtin_object; -static PyObject *__pyx_builtin_staticmethod; -static PyObject *__pyx_builtin_StopIteration; -static PyObject *__pyx_builtin_open; -static const char __pyx_k_[] = "\n"; -static const char __pyx_k_0[] = "0"; -static const char __pyx_k_p[] = "p"; -static const char __pyx_k_r[] = "r"; -static const char __pyx_k_s[] = "}\\s*"; -static const char __pyx_k__2[] = "\r"; -static const char __pyx_k__3[] = "#"; -static const char __pyx_k__4[] = "("; -static const char __pyx_k__5[] = ")"; -static const char __pyx_k__6[] = "\\"; -static const char __pyx_k__7[] = "@"; -static const char __pyx_k__8[] = "."; -static const char __pyx_k__9[] = "-"; -static const char __pyx_k_os[] = "os"; -static const char __pyx_k_re[] = "re"; -static const char __pyx_k_xX[] = "xX"; -static const char __pyx_k_CID[] = "CID"; -static const char __pyx_k__10[] = "\""; -static const char __pyx_k__11[] = "[\r\n]"; -static const char __pyx_k__12[] = ""; -static const char __pyx_k__14[] = " \t"; -static const char __pyx_k__15[] = "\r\n"; -static const char __pyx_k__16[] = ",;:-+'{}[]<>()="; -static const char __pyx_k__17[] = "_+*:.^~!\\"; -static const char __pyx_k__18[] = "_.+*:^~!/-"; -static const char __pyx_k_doc[] = "__doc__"; -static const char __pyx_k_err[] = "err"; -static const char __pyx_k_pop[] = "pop"; -static const char __pyx_k_pos[] = "pos_"; -static const char __pyx_k_s_2[] = "\\s*;"; -static const char __pyx_k_sub[] = "sub"; -static const char __pyx_k_tag[] = "tag"; -static const char __pyx_k_NAME[] = "NAME"; -static const char __pyx_k_data[] = "data"; -static const char __pyx_k_init[] = "__init__"; -static const char __pyx_k_iter[] = "__iter__"; -static const char __pyx_k_join[] = "join"; -static const char __pyx_k_line[] = "line_"; -static const char __pyx_k_main[] = "__main__"; -static const char __pyx_k_mode[] = "mode_"; -static const char __pyx_k_name[] = "name"; -static const char __pyx_k_next[] = "__next__"; -static const char __pyx_k_open[] = "open"; -static const char __pyx_k_path[] = "path"; -static const char __pyx_k_read[] = "read"; -static const char __pyx_k_self[] = "self"; -static const char __pyx_k_test[] = "__test__"; -static const char __pyx_k_text[] = "text"; -static const char __pyx_k_FLOAT[] = "FLOAT"; -static const char __pyx_k_Lexer[] = "Lexer"; -static const char __pyx_k_OCTAL[] = "OCTAL"; -static const char __pyx_k_close[] = "close"; -static const char __pyx_k_isabs[] = "isabs"; -static const char __pyx_k_lexer[] = "lexer"; -static const char __pyx_k_limit[] = "limit"; -static const char __pyx_k_match[] = "match"; -static const char __pyx_k_split[] = "split"; -static const char __pyx_k_start[] = "start"; -static const char __pyx_k_strip[] = "strip"; -static const char __pyx_k_token[] = "token"; -static const char __pyx_k_utf_8[] = "utf-8"; -static const char __pyx_k_valid[] = "valid"; -static const char __pyx_k_NORMAL[] = "NORMAL"; -static const char __pyx_k_NUMBER[] = "NUMBER"; -static const char __pyx_k_STRING[] = "STRING"; -static const char __pyx_k_SYMBOL[] = "SYMBOL"; -static const char __pyx_k_append[] = "append"; -static const char __pyx_k_column[] = "column"; -static const char __pyx_k_getcwd[] = "getcwd"; -static const char __pyx_k_import[] = "__import__"; -static const char __pyx_k_lexers[] = "lexers_"; -static const char __pyx_k_module[] = "__module__"; -static const char __pyx_k_name_2[] = "__name__"; -static const char __pyx_k_next_2[] = "next_"; -static const char __pyx_k_next_3[] = "next"; -static const char __pyx_k_object[] = "object"; -static const char __pyx_k_regexp[] = "regexp"; -static const char __pyx_k_string[] = "string"; -static const char __pyx_k_text_2[] = "text_"; -static const char __pyx_k_COMMENT[] = "COMMENT"; -static const char __pyx_k_NEWLINE[] = "NEWLINE"; -static const char __pyx_k_NUMBERS[] = "NUMBERS"; -static const char __pyx_k_closing[] = "closing"; -static const char __pyx_k_compile[] = "compile"; -static const char __pyx_k_curpath[] = "curpath"; -static const char __pyx_k_dirname[] = "dirname"; -static const char __pyx_k_fileobj[] = "fileobj"; -static const char __pyx_k_include[] = "include"; -static const char __pyx_k_prepare[] = "__prepare__"; -static const char __pyx_k_stop_at[] = "stop_at"; -static const char __pyx_k_FILENAME[] = "FILENAME"; -static const char __pyx_k_cur_char[] = "cur_char"; -static const char __pyx_k_encoding[] = "encoding"; -static const char __pyx_k_features[] = ""; -static const char __pyx_k_filename[] = "filename"; -static const char __pyx_k_location[] = "location_"; -static const char __pyx_k_maxsplit[] = "maxsplit"; -static const char __pyx_k_qualname[] = "__qualname__"; -static const char __pyx_k_metaclass[] = "__metaclass__"; -static const char __pyx_k_next_char[] = "next_char"; -static const char __pyx_k_scan_over[] = "scan_over_"; -static const char __pyx_k_0123456789[] = "0123456789"; -static const char __pyx_k_A_Za_z_0_9[] = "^[A-Za-z_0-9.\\-]+$"; -static const char __pyx_k_CHAR_DIGIT[] = "CHAR_DIGIT_"; -static const char __pyx_k_GLYPHCLASS[] = "GLYPHCLASS"; -static const char __pyx_k_Lexer_next[] = "Lexer.next"; -static const char __pyx_k_filename_2[] = "filename_"; -static const char __pyx_k_fname_type[] = "fname_type"; -static const char __pyx_k_glyphclass[] = "glyphclass"; -static const char __pyx_k_includeDir[] = "includeDir"; -static const char __pyx_k_line_start[] = "line_start_"; -static const char __pyx_k_location_2[] = "location"; -static const char __pyx_k_make_lexer[] = "make_lexer_"; -static const char __pyx_k_scan_until[] = "scan_until_"; -static const char __pyx_k_token_type[] = "token_type"; -static const char __pyx_k_CHAR_LETTER[] = "CHAR_LETTER_"; -static const char __pyx_k_CHAR_SYMBOL[] = "CHAR_SYMBOL_"; -static const char __pyx_k_HEXADECIMAL[] = "HEXADECIMAL"; -static const char __pyx_k_ImportError[] = "ImportError"; -static const char __pyx_k_MODE_NORMAL[] = "MODE_NORMAL_"; -static const char __pyx_k_featurefile[] = "featurefile"; -static const char __pyx_k_fname_token[] = "fname_token"; -static const char __pyx_k_text_length[] = "text_length_"; -static const char __pyx_k_CHAR_NEWLINE[] = "CHAR_NEWLINE_"; -static const char __pyx_k_Lexer___init[] = "Lexer.__init__"; -static const char __pyx_k_Lexer___iter[] = "Lexer.__iter__"; -static const char __pyx_k_Lexer___next[] = "Lexer.__next__"; -static const char __pyx_k_Lexer_next_2[] = "Lexer.next_"; -static const char __pyx_k_file_or_path[] = "file_or_path"; -static const char __pyx_k_staticmethod[] = "staticmethod"; -static const char __pyx_k_CHAR_HEXDIGIT[] = "CHAR_HEXDIGIT_"; -static const char __pyx_k_MODE_FILENAME[] = "MODE_FILENAME_"; -static const char __pyx_k_RE_GLYPHCLASS[] = "RE_GLYPHCLASS"; -static const char __pyx_k_StopIteration[] = "StopIteration"; -static const char __pyx_k_IncludingLexer[] = "IncludingLexer"; -static const char __pyx_k_Lexer_location[] = "Lexer.location_"; -static const char __pyx_k_fname_location[] = "fname_location"; -static const char __pyx_k_ANONYMOUS_BLOCK[] = "ANONYMOUS_BLOCK"; -static const char __pyx_k_CHAR_NAME_START[] = "CHAR_NAME_START_"; -static const char __pyx_k_CHAR_WHITESPACE[] = "CHAR_WHITESPACE_"; -static const char __pyx_k_FeatureLibError[] = "FeatureLibError"; -static const char __pyx_k_Lexer_scan_over[] = "Lexer.scan_over_"; -static const char __pyx_k_featurefilepath[] = "featurefilepath"; -static const char __pyx_k_Lexer_scan_until[] = "Lexer.scan_until_"; -static const char __pyx_k_FileNotFoundError[] = "FileNotFoundError"; -static const char __pyx_k_NonIncludingLexer[] = "NonIncludingLexer"; -static const char __pyx_k_Expected_file_name[] = "Expected file name"; -static const char __pyx_k_FeatureLibLocation[] = "FeatureLibLocation"; -static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; -static const char __pyx_k_IncludedFeaNotFound[] = "IncludedFeaNotFound"; -static const char __pyx_k_IncludingLexer_next[] = "IncludingLexer.next"; -static const char __pyx_k_scan_anonymous_block[] = "scan_anonymous_block"; -static const char __pyx_k_IncludingLexer___init[] = "IncludingLexer.__init__"; -static const char __pyx_k_IncludingLexer___iter[] = "IncludingLexer.__iter__"; -static const char __pyx_k_IncludingLexer___next[] = "IncludingLexer.__next__"; -static const char __pyx_k_0123456789ABCDEFabcdef[] = "0123456789ABCDEFabcdef"; -static const char __pyx_k_CHAR_NAME_CONTINUATION[] = "CHAR_NAME_CONTINUATION_"; -static const char __pyx_k_Unexpected_character_r[] = "Unexpected character: %r"; -static const char __pyx_k_fontTools_feaLib_error[] = "fontTools.feaLib.error"; -static const char __pyx_k_fontTools_feaLib_lexer[] = "fontTools.feaLib.lexer"; -static const char __pyx_k_Expected_after_file_name[] = "Expected ')' after file name"; -static const char __pyx_k_NonIncludingLexer___next[] = "NonIncludingLexer.__next__"; -static const char __pyx_k_Expected_before_file_name[] = "Expected '(' before file name"; -static const char __pyx_k_Expected_glyph_class_name[] = "Expected glyph class name"; -static const char __pyx_k_IncludingLexer_make_lexer[] = "IncludingLexer.make_lexer_"; -static const char __pyx_k_fontTools_feaLib_location[] = "fontTools.feaLib.location"; -static const char __pyx_k_Lexer_scan_anonymous_block[] = "Lexer.scan_anonymous_block"; -static const char __pyx_k_Too_many_recursive_includes[] = "Too many recursive includes"; -static const char __pyx_k_Expected_to_terminate_string[] = "Expected '\"' to terminate string"; -static const char __pyx_k_Lib_fontTools_feaLib_lexer_py[] = "Lib/fontTools/feaLib/lexer.py"; -static const char __pyx_k_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; -static const char __pyx_k_A_Lexer_that_follows_include_sta[] = "A Lexer that follows include statements.\n\n The OpenType feature file specification states that due to\n historical reasons, relative imports should be resolved in this\n order:\n\n 1. If the source font is UFO format, then relative to the UFO's\n font directory\n 2. relative to the top-level include file\n 3. relative to the parent include file\n\n We only support 1 (via includeDir) and 2.\n "; -static const char __pyx_k_Expected_s_to_terminate_anonymou[] = "Expected '} %s;' to terminate anonymous block"; -static const char __pyx_k_Glyph_class_names_must_consist_o[] = "Glyph class names must consist of letters, digits, underscore, period or hyphen"; -static const char __pyx_k_Glyph_class_names_must_not_be_lo[] = "Glyph class names must not be longer than 63 characters"; -static const char __pyx_k_IncludingLexer_scan_anonymous_bl[] = "IncludingLexer.scan_anonymous_block"; -static const char __pyx_k_Lexer_that_does_not_follow_inclu[] = "Lexer that does not follow `include` statements, emits them as-is."; -static PyObject *__pyx_kp_u_; -static PyObject *__pyx_kp_u_0; -static PyObject *__pyx_kp_u_0123456789; -static PyObject *__pyx_kp_u_0123456789ABCDEFabcdef; -static PyObject *__pyx_n_u_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef; -static PyObject *__pyx_n_s_ANONYMOUS_BLOCK; -static PyObject *__pyx_n_u_ANONYMOUS_BLOCK; -static PyObject *__pyx_kp_s_A_Lexer_that_follows_include_sta; -static PyObject *__pyx_kp_u_A_Za_z_0_9; -static PyObject *__pyx_n_s_CHAR_DIGIT; -static PyObject *__pyx_n_s_CHAR_HEXDIGIT; -static PyObject *__pyx_n_s_CHAR_LETTER; -static PyObject *__pyx_n_s_CHAR_NAME_CONTINUATION; -static PyObject *__pyx_n_s_CHAR_NAME_START; -static PyObject *__pyx_n_s_CHAR_NEWLINE; -static PyObject *__pyx_n_s_CHAR_SYMBOL; -static PyObject *__pyx_n_s_CHAR_WHITESPACE; -static PyObject *__pyx_n_s_CID; -static PyObject *__pyx_n_u_CID; -static PyObject *__pyx_n_s_COMMENT; -static PyObject *__pyx_n_u_COMMENT; -static PyObject *__pyx_kp_u_Expected_after_file_name; -static PyObject *__pyx_kp_u_Expected_before_file_name; -static PyObject *__pyx_kp_u_Expected_file_name; -static PyObject *__pyx_kp_u_Expected_glyph_class_name; -static PyObject *__pyx_kp_u_Expected_s_to_terminate_anonymou; -static PyObject *__pyx_kp_u_Expected_to_terminate_string; -static PyObject *__pyx_n_s_FILENAME; -static PyObject *__pyx_n_u_FILENAME; -static PyObject *__pyx_n_s_FLOAT; -static PyObject *__pyx_n_u_FLOAT; -static PyObject *__pyx_n_s_FeatureLibError; -static PyObject *__pyx_n_s_FeatureLibLocation; -static PyObject *__pyx_n_s_FileNotFoundError; -static PyObject *__pyx_n_s_GLYPHCLASS; -static PyObject *__pyx_n_u_GLYPHCLASS; -static PyObject *__pyx_kp_u_Glyph_class_names_must_consist_o; -static PyObject *__pyx_kp_u_Glyph_class_names_must_not_be_lo; -static PyObject *__pyx_n_s_HEXADECIMAL; -static PyObject *__pyx_n_u_HEXADECIMAL; -static PyObject *__pyx_n_s_ImportError; -static PyObject *__pyx_n_s_IncludedFeaNotFound; -static PyObject *__pyx_n_s_IncludingLexer; -static PyObject *__pyx_n_s_IncludingLexer___init; -static PyObject *__pyx_n_s_IncludingLexer___iter; -static PyObject *__pyx_n_s_IncludingLexer___next; -static PyObject *__pyx_n_s_IncludingLexer_make_lexer; -static PyObject *__pyx_n_s_IncludingLexer_next; -static PyObject *__pyx_n_s_IncludingLexer_scan_anonymous_bl; -static PyObject *__pyx_n_s_Lexer; -static PyObject *__pyx_n_s_Lexer___init; -static PyObject *__pyx_n_s_Lexer___iter; -static PyObject *__pyx_n_s_Lexer___next; -static PyObject *__pyx_n_s_Lexer_location; -static PyObject *__pyx_n_s_Lexer_next; -static PyObject *__pyx_n_s_Lexer_next_2; -static PyObject *__pyx_n_s_Lexer_scan_anonymous_block; -static PyObject *__pyx_n_s_Lexer_scan_over; -static PyObject *__pyx_n_s_Lexer_scan_until; -static PyObject *__pyx_kp_s_Lexer_that_does_not_follow_inclu; -static PyObject *__pyx_kp_s_Lib_fontTools_feaLib_lexer_py; -static PyObject *__pyx_n_s_MODE_FILENAME; -static PyObject *__pyx_n_s_MODE_NORMAL; -static PyObject *__pyx_n_s_NAME; -static PyObject *__pyx_n_u_NAME; -static PyObject *__pyx_n_s_NEWLINE; -static PyObject *__pyx_n_u_NEWLINE; -static PyObject *__pyx_n_u_NORMAL; -static PyObject *__pyx_n_s_NUMBER; -static PyObject *__pyx_n_u_NUMBER; -static PyObject *__pyx_n_s_NUMBERS; -static PyObject *__pyx_n_s_NonIncludingLexer; -static PyObject *__pyx_n_s_NonIncludingLexer___next; -static PyObject *__pyx_n_s_OCTAL; -static PyObject *__pyx_n_u_OCTAL; -static PyObject *__pyx_n_s_RE_GLYPHCLASS; -static PyObject *__pyx_n_s_STRING; -static PyObject *__pyx_n_u_STRING; -static PyObject *__pyx_n_s_SYMBOL; -static PyObject *__pyx_n_u_SYMBOL; -static PyObject *__pyx_n_s_StopIteration; -static PyObject *__pyx_kp_u_Too_many_recursive_includes; -static PyObject *__pyx_kp_u_Unexpected_character_r; -static PyObject *__pyx_kp_u__10; -static PyObject *__pyx_kp_u__11; -static PyObject *__pyx_kp_u__12; -static PyObject *__pyx_kp_u__14; -static PyObject *__pyx_kp_u__15; -static PyObject *__pyx_kp_u__16; -static PyObject *__pyx_kp_u__17; -static PyObject *__pyx_kp_u__18; -static PyObject *__pyx_kp_u__2; -static PyObject *__pyx_kp_u__3; -static PyObject *__pyx_kp_u__4; -static PyObject *__pyx_kp_u__5; -static PyObject *__pyx_kp_u__6; -static PyObject *__pyx_kp_u__7; -static PyObject *__pyx_kp_u__8; -static PyObject *__pyx_kp_u__9; -static PyObject *__pyx_n_s_append; -static PyObject *__pyx_n_s_cline_in_traceback; -static PyObject *__pyx_n_s_close; -static PyObject *__pyx_n_s_closing; -static PyObject *__pyx_n_s_column; -static PyObject *__pyx_n_s_compile; -static PyObject *__pyx_n_s_cur_char; -static PyObject *__pyx_n_s_curpath; -static PyObject *__pyx_n_s_data; -static PyObject *__pyx_n_s_dirname; -static PyObject *__pyx_n_s_doc; -static PyObject *__pyx_n_s_encoding; -static PyObject *__pyx_n_s_err; -static PyObject *__pyx_n_s_featurefile; -static PyObject *__pyx_n_s_featurefilepath; -static PyObject *__pyx_kp_u_features; -static PyObject *__pyx_n_s_file_or_path; -static PyObject *__pyx_n_s_filename; -static PyObject *__pyx_n_s_filename_2; -static PyObject *__pyx_n_s_fileobj; -static PyObject *__pyx_n_s_fname_location; -static PyObject *__pyx_n_s_fname_token; -static PyObject *__pyx_n_s_fname_type; -static PyObject *__pyx_n_s_fontTools_feaLib_error; -static PyObject *__pyx_n_s_fontTools_feaLib_lexer; -static PyObject *__pyx_n_s_fontTools_feaLib_location; -static PyObject *__pyx_n_s_getcwd; -static PyObject *__pyx_n_s_glyphclass; -static PyObject *__pyx_n_s_import; -static PyObject *__pyx_n_u_include; -static PyObject *__pyx_n_s_includeDir; -static PyObject *__pyx_n_s_init; -static PyObject *__pyx_n_s_isabs; -static PyObject *__pyx_n_s_iter; -static PyObject *__pyx_n_s_join; -static PyObject *__pyx_n_s_lexer; -static PyObject *__pyx_n_s_lexers; -static PyObject *__pyx_n_s_limit; -static PyObject *__pyx_n_s_line; -static PyObject *__pyx_n_s_line_start; -static PyObject *__pyx_n_s_location; -static PyObject *__pyx_n_s_location_2; -static PyObject *__pyx_n_s_main; -static PyObject *__pyx_n_s_make_lexer; -static PyObject *__pyx_n_s_match; -static PyObject *__pyx_n_s_maxsplit; -static PyObject *__pyx_n_s_metaclass; -static PyObject *__pyx_n_s_mode; -static PyObject *__pyx_n_s_module; -static PyObject *__pyx_n_u_name; -static PyObject *__pyx_n_s_name_2; -static PyObject *__pyx_n_s_next; -static PyObject *__pyx_n_s_next_2; -static PyObject *__pyx_n_s_next_3; -static PyObject *__pyx_n_s_next_char; -static PyObject *__pyx_n_s_object; -static PyObject *__pyx_n_s_open; -static PyObject *__pyx_n_s_os; -static PyObject *__pyx_n_s_p; -static PyObject *__pyx_n_s_path; -static PyObject *__pyx_n_s_pop; -static PyObject *__pyx_n_s_pos; -static PyObject *__pyx_n_s_prepare; -static PyObject *__pyx_n_s_qualname; -static PyObject *__pyx_n_u_r; -static PyObject *__pyx_n_s_re; -static PyObject *__pyx_n_s_read; -static PyObject *__pyx_n_u_read; -static PyObject *__pyx_n_s_regexp; -static PyObject *__pyx_kp_u_s; -static PyObject *__pyx_kp_u_s_2; -static PyObject *__pyx_n_s_scan_anonymous_block; -static PyObject *__pyx_n_s_scan_over; -static PyObject *__pyx_n_s_scan_until; -static PyObject *__pyx_n_s_self; -static PyObject *__pyx_n_s_split; -static PyObject *__pyx_n_s_start; -static PyObject *__pyx_n_s_staticmethod; -static PyObject *__pyx_n_s_stop_at; -static PyObject *__pyx_n_s_string; -static PyObject *__pyx_n_s_strip; -static PyObject *__pyx_n_s_sub; -static PyObject *__pyx_n_s_tag; -static PyObject *__pyx_n_s_test; -static PyObject *__pyx_n_s_text; -static PyObject *__pyx_n_s_text_2; -static PyObject *__pyx_n_s_text_length; -static PyObject *__pyx_n_s_token; -static PyObject *__pyx_n_s_token_type; -static PyObject *__pyx_kp_u_utf_8; -static PyObject *__pyx_n_s_valid; -static PyObject *__pyx_n_u_xX; -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_5Lexer___init__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self, PyObject *__pyx_v_text, PyObject *__pyx_v_filename); /* proto */ -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_2__iter__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_4next(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_6__next__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_8location_(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_10next_(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_12scan_over_(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self, PyObject *__pyx_v_valid); /* proto */ -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_14scan_until_(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self, PyObject *__pyx_v_stop_at); /* proto */ -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_16scan_anonymous_block(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self, PyObject *__pyx_v_tag); /* proto */ -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_14IncludingLexer___init__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self, PyObject *__pyx_v_featurefile, PyObject *__pyx_v_includeDir); /* proto */ -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_14IncludingLexer_2__iter__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_14IncludingLexer_4next(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_14IncludingLexer_6__next__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_14IncludingLexer_8make_lexer_(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_file_or_path); /* proto */ -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_14IncludingLexer_10scan_anonymous_block(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self, PyObject *__pyx_v_tag); /* proto */ -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_17NonIncludingLexer___next__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self); /* proto */ -static __Pyx_CachedCFunction __pyx_umethod_PyList_Type_pop = {0, &__pyx_n_s_pop, 0, 0, 0}; -static PyObject *__pyx_int_0; -static PyObject *__pyx_int_1; -static PyObject *__pyx_int_2; -static PyObject *__pyx_int_8; -static PyObject *__pyx_int_10; -static PyObject *__pyx_int_16; -static PyObject *__pyx_tuple__13; -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__38; -static PyObject *__pyx_tuple__40; -static PyObject *__pyx_tuple__42; -static PyObject *__pyx_tuple__44; -static PyObject *__pyx_tuple__46; -static PyObject *__pyx_tuple__48; -static PyObject *__pyx_tuple__50; -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__39; -static PyObject *__pyx_codeobj__41; -static PyObject *__pyx_codeobj__43; -static PyObject *__pyx_codeobj__45; -static PyObject *__pyx_codeobj__47; -static PyObject *__pyx_codeobj__49; -static PyObject *__pyx_codeobj__51; -/* Late includes */ - -/* "fontTools/feaLib/lexer.py":43 - * MODE_FILENAME_ = "FILENAME" - * - * def __init__(self, text, filename): # <<<<<<<<<<<<<< - * self.filename_ = filename - * self.line_ = 1 - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_1__init__(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_6feaLib_5lexer_5Lexer___init__[] = "Lexer.__init__(self, text, filename)"; -static PyMethodDef __pyx_mdef_9fontTools_6feaLib_5lexer_5Lexer_1__init__ = {"__init__", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_1__init__, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_6feaLib_5lexer_5Lexer___init__}; -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_1__init__(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_self = 0; - PyObject *__pyx_v_text = 0; - PyObject *__pyx_v_filename = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_self,&__pyx_n_s_text,&__pyx_n_s_filename,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_self)) != 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_text)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 3, 3, 1); __PYX_ERR(0, 43, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_filename)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 3, 3, 2); __PYX_ERR(0, 43, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) __PYX_ERR(0, 43, __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_self = values[0]; - __pyx_v_text = values[1]; - __pyx_v_filename = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 43, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.feaLib.lexer.Lexer.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_6feaLib_5lexer_5Lexer___init__(__pyx_self, __pyx_v_self, __pyx_v_text, __pyx_v_filename); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_5Lexer___init__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self, PyObject *__pyx_v_text, PyObject *__pyx_v_filename) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - 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("__init__", 0); - - /* "fontTools/feaLib/lexer.py":44 - * - * def __init__(self, text, filename): - * self.filename_ = filename # <<<<<<<<<<<<<< - * self.line_ = 1 - * self.pos_ = 0 - */ - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_filename_2, __pyx_v_filename) < 0) __PYX_ERR(0, 44, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":45 - * def __init__(self, text, filename): - * self.filename_ = filename - * self.line_ = 1 # <<<<<<<<<<<<<< - * self.pos_ = 0 - * self.line_start_ = 0 - */ - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_line, __pyx_int_1) < 0) __PYX_ERR(0, 45, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":46 - * self.filename_ = filename - * self.line_ = 1 - * self.pos_ = 0 # <<<<<<<<<<<<<< - * self.line_start_ = 0 - * self.text_ = text - */ - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_pos, __pyx_int_0) < 0) __PYX_ERR(0, 46, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":47 - * self.line_ = 1 - * self.pos_ = 0 - * self.line_start_ = 0 # <<<<<<<<<<<<<< - * self.text_ = text - * self.text_length_ = len(text) - */ - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_line_start, __pyx_int_0) < 0) __PYX_ERR(0, 47, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":48 - * self.pos_ = 0 - * self.line_start_ = 0 - * self.text_ = text # <<<<<<<<<<<<<< - * self.text_length_ = len(text) - * self.mode_ = Lexer.MODE_NORMAL_ - */ - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_text_2, __pyx_v_text) < 0) __PYX_ERR(0, 48, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":49 - * self.line_start_ = 0 - * self.text_ = text - * self.text_length_ = len(text) # <<<<<<<<<<<<<< - * self.mode_ = Lexer.MODE_NORMAL_ - * - */ - __pyx_t_1 = PyObject_Length(__pyx_v_text); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 49, __pyx_L1_error) - __pyx_t_2 = PyInt_FromSsize_t(__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 49, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_text_length, __pyx_t_2) < 0) __PYX_ERR(0, 49, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":50 - * self.text_ = text - * self.text_length_ = len(text) - * self.mode_ = Lexer.MODE_NORMAL_ # <<<<<<<<<<<<<< - * - * def __iter__(self): - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 50, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_MODE_NORMAL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 50, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_mode, __pyx_t_3) < 0) __PYX_ERR(0, 50, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "fontTools/feaLib/lexer.py":43 - * MODE_FILENAME_ = "FILENAME" - * - * def __init__(self, text, filename): # <<<<<<<<<<<<<< - * self.filename_ = filename - * self.line_ = 1 - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("fontTools.feaLib.lexer.Lexer.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/feaLib/lexer.py":52 - * self.mode_ = Lexer.MODE_NORMAL_ - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return self - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_3__iter__(PyObject *__pyx_self, PyObject *__pyx_v_self); /*proto*/ -static char __pyx_doc_9fontTools_6feaLib_5lexer_5Lexer_2__iter__[] = "Lexer.__iter__(self)"; -static PyMethodDef __pyx_mdef_9fontTools_6feaLib_5lexer_5Lexer_3__iter__ = {"__iter__", (PyCFunction)__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_3__iter__, METH_O, __pyx_doc_9fontTools_6feaLib_5lexer_5Lexer_2__iter__}; -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_3__iter__(PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__iter__ (wrapper)", 0); - __pyx_r = __pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_2__iter__(__pyx_self, ((PyObject *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_2__iter__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__iter__", 0); - - /* "fontTools/feaLib/lexer.py":53 - * - * def __iter__(self): - * return self # <<<<<<<<<<<<<< - * - * def next(self): # Python 2 - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self); - __pyx_r = __pyx_v_self; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":52 - * self.mode_ = Lexer.MODE_NORMAL_ - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return self - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/feaLib/lexer.py":55 - * return self - * - * def next(self): # Python 2 # <<<<<<<<<<<<<< - * return self.__next__() - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_5next(PyObject *__pyx_self, PyObject *__pyx_v_self); /*proto*/ -static char __pyx_doc_9fontTools_6feaLib_5lexer_5Lexer_4next[] = "Lexer.next(self)"; -static PyMethodDef __pyx_mdef_9fontTools_6feaLib_5lexer_5Lexer_5next = {"next", (PyCFunction)__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_5next, METH_O, __pyx_doc_9fontTools_6feaLib_5lexer_5Lexer_4next}; -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_5next(PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("next (wrapper)", 0); - __pyx_r = __pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_4next(__pyx_self, ((PyObject *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_4next(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("next", 0); - - /* "fontTools/feaLib/lexer.py":56 - * - * def next(self): # Python 2 - * return self.__next__() # <<<<<<<<<<<<<< - * - * def __next__(self): # Python 3 - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_next); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 56, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_CallOneArg(__pyx_t_2, __pyx_t_3) : __Pyx_PyObject_CallNoArg(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 56, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":55 - * return self - * - * def next(self): # Python 2 # <<<<<<<<<<<<<< - * return self.__next__() - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("fontTools.feaLib.lexer.Lexer.next", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/feaLib/lexer.py":58 - * return self.__next__() - * - * def __next__(self): # Python 3 # <<<<<<<<<<<<<< - * while True: - * token_type, token, location = self.next_() - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_7__next__(PyObject *__pyx_self, PyObject *__pyx_v_self); /*proto*/ -static char __pyx_doc_9fontTools_6feaLib_5lexer_5Lexer_6__next__[] = "Lexer.__next__(self)"; -static PyMethodDef __pyx_mdef_9fontTools_6feaLib_5lexer_5Lexer_7__next__ = {"__next__", (PyCFunction)__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_7__next__, METH_O, __pyx_doc_9fontTools_6feaLib_5lexer_5Lexer_6__next__}; -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_7__next__(PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__next__ (wrapper)", 0); - __pyx_r = __pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_6__next__(__pyx_self, ((PyObject *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_6__next__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_v_token_type = NULL; - PyObject *__pyx_v_token = NULL; - PyObject *__pyx_v_location = 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)(PyObject *); - int __pyx_t_7; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__next__", 0); - - /* "fontTools/feaLib/lexer.py":59 - * - * def __next__(self): # Python 3 - * while True: # <<<<<<<<<<<<<< - * token_type, token, location = self.next_() - * if token_type != Lexer.NEWLINE: - */ - while (1) { - - /* "fontTools/feaLib/lexer.py":60 - * def __next__(self): # Python 3 - * while True: - * token_type, token, location = self.next_() # <<<<<<<<<<<<<< - * if token_type != Lexer.NEWLINE: - * return (token_type, token, location) - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_next_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 60, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_CallOneArg(__pyx_t_2, __pyx_t_3) : __Pyx_PyObject_CallNoArg(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 60, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __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, 60, __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); - } 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_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 60, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 60, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PySequence_ITEM(sequence, 2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 60, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_5 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 60, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_2)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_3); - index = 2; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_4); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 3) < 0) __PYX_ERR(0, 60, __pyx_L1_error) - __pyx_t_6 = NULL; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - goto __pyx_L6_unpacking_done; - __pyx_L5_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, 60, __pyx_L1_error) - __pyx_L6_unpacking_done:; - } - __Pyx_XDECREF_SET(__pyx_v_token_type, __pyx_t_2); - __pyx_t_2 = 0; - __Pyx_XDECREF_SET(__pyx_v_token, __pyx_t_3); - __pyx_t_3 = 0; - __Pyx_XDECREF_SET(__pyx_v_location, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/feaLib/lexer.py":61 - * while True: - * token_type, token, location = self.next_() - * if token_type != Lexer.NEWLINE: # <<<<<<<<<<<<<< - * return (token_type, token, location) - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 61, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_NEWLINE); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 61, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_RichCompare(__pyx_v_token_type, __pyx_t_4, Py_NE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 61, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 61, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_7) { - - /* "fontTools/feaLib/lexer.py":62 - * token_type, token, location = self.next_() - * if token_type != Lexer.NEWLINE: - * return (token_type, token, location) # <<<<<<<<<<<<<< - * - * def location_(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 62, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_token_type); - __Pyx_GIVEREF(__pyx_v_token_type); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_token_type); - __Pyx_INCREF(__pyx_v_token); - __Pyx_GIVEREF(__pyx_v_token); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_token); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_location); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":61 - * while True: - * token_type, token, location = self.next_() - * if token_type != Lexer.NEWLINE: # <<<<<<<<<<<<<< - * return (token_type, token, location) - * - */ - } - } - - /* "fontTools/feaLib/lexer.py":58 - * return self.__next__() - * - * def __next__(self): # Python 3 # <<<<<<<<<<<<<< - * while True: - * token_type, token, location = self.next_() - */ - - /* 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_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("fontTools.feaLib.lexer.Lexer.__next__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_token_type); - __Pyx_XDECREF(__pyx_v_token); - __Pyx_XDECREF(__pyx_v_location); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/feaLib/lexer.py":64 - * return (token_type, token, location) - * - * def location_(self): # <<<<<<<<<<<<<< - * column = self.pos_ - self.line_start_ + 1 - * return FeatureLibLocation(self.filename_ or "", self.line_, column) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_9location_(PyObject *__pyx_self, PyObject *__pyx_v_self); /*proto*/ -static char __pyx_doc_9fontTools_6feaLib_5lexer_5Lexer_8location_[] = "Lexer.location_(self)"; -static PyMethodDef __pyx_mdef_9fontTools_6feaLib_5lexer_5Lexer_9location_ = {"location_", (PyCFunction)__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_9location_, METH_O, __pyx_doc_9fontTools_6feaLib_5lexer_5Lexer_8location_}; -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_9location_(PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("location_ (wrapper)", 0); - __pyx_r = __pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_8location_(__pyx_self, ((PyObject *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_8location_(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_v_column = 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; - 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("location_", 0); - - /* "fontTools/feaLib/lexer.py":65 - * - * def location_(self): - * column = self.pos_ - self.line_start_ + 1 # <<<<<<<<<<<<<< - * return FeatureLibLocation(self.filename_ or "", self.line_, column) - * - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 65, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_line_start); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 65, __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, 65, __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_PyInt_AddObjC(__pyx_t_3, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 65, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_column = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":66 - * def location_(self): - * column = self.pos_ - self.line_start_ + 1 - * return FeatureLibLocation(self.filename_ or "", self.line_, column) # <<<<<<<<<<<<<< - * - * def next_(self): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_FeatureLibLocation); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 66, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_filename_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 66, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(0, 66, __pyx_L1_error) - if (!__pyx_t_5) { - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } else { - __Pyx_INCREF(__pyx_t_4); - __pyx_t_1 = __pyx_t_4; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - goto __pyx_L3_bool_binop_done; - } - __Pyx_INCREF(__pyx_kp_u_features); - __pyx_t_1 = __pyx_kp_u_features; - __pyx_L3_bool_binop_done:; - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_line); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 66, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = NULL; - __pyx_t_7 = 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_7 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[4] = {__pyx_t_6, __pyx_t_1, __pyx_t_4, __pyx_v_column}; - __pyx_t_2 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_7, 3+__pyx_t_7); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 66, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[4] = {__pyx_t_6, __pyx_t_1, __pyx_t_4, __pyx_v_column}; - __pyx_t_2 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_7, 3+__pyx_t_7); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 66, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } else - #endif - { - __pyx_t_8 = PyTuple_New(3+__pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 66, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - if (__pyx_t_6) { - __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_6); __pyx_t_6 = NULL; - } - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_t_4); - __Pyx_INCREF(__pyx_v_column); - __Pyx_GIVEREF(__pyx_v_column); - PyTuple_SET_ITEM(__pyx_t_8, 2+__pyx_t_7, __pyx_v_column); - __pyx_t_1 = 0; - __pyx_t_4 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_8, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 66, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":64 - * return (token_type, token, location) - * - * def location_(self): # <<<<<<<<<<<<<< - * column = self.pos_ - self.line_start_ + 1 - * return FeatureLibLocation(self.filename_ or "", self.line_, column) - */ - - /* 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_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("fontTools.feaLib.lexer.Lexer.location_", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_column); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/feaLib/lexer.py":68 - * return FeatureLibLocation(self.filename_ or "", self.line_, column) - * - * def next_(self): # <<<<<<<<<<<<<< - * self.scan_over_(Lexer.CHAR_WHITESPACE_) - * location = self.location_() - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_11next_(PyObject *__pyx_self, PyObject *__pyx_v_self); /*proto*/ -static char __pyx_doc_9fontTools_6feaLib_5lexer_5Lexer_10next_[] = "Lexer.next_(self)"; -static PyMethodDef __pyx_mdef_9fontTools_6feaLib_5lexer_5Lexer_11next_ = {"next_", (PyCFunction)__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_11next_, METH_O, __pyx_doc_9fontTools_6feaLib_5lexer_5Lexer_10next_}; -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_11next_(PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("next_ (wrapper)", 0); - __pyx_r = __pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_10next_(__pyx_self, ((PyObject *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_10next_(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_v_location = NULL; - PyObject *__pyx_v_start = NULL; - PyObject *__pyx_v_text = NULL; - Py_ssize_t __pyx_v_limit; - PyObject *__pyx_v_cur_char = NULL; - PyObject *__pyx_v_next_char = NULL; - PyObject *__pyx_v_glyphclass = NULL; - PyObject *__pyx_v_token = NULL; - PyObject *__pyx_v_string = 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; - Py_ssize_t __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - int __pyx_t_8; - int __pyx_t_9; - PyObject *__pyx_t_10 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("next_", 0); - - /* "fontTools/feaLib/lexer.py":69 - * - * def next_(self): - * self.scan_over_(Lexer.CHAR_WHITESPACE_) # <<<<<<<<<<<<<< - * location = self.location_() - * start = self.pos_ - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_scan_over); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 69, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 69, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_CHAR_WHITESPACE); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 69, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 69, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":70 - * def next_(self): - * self.scan_over_(Lexer.CHAR_WHITESPACE_) - * location = self.location_() # <<<<<<<<<<<<<< - * start = self.pos_ - * text = self.text_ - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_location); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 70, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4) : __Pyx_PyObject_CallNoArg(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 70, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_location = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":71 - * self.scan_over_(Lexer.CHAR_WHITESPACE_) - * location = self.location_() - * start = self.pos_ # <<<<<<<<<<<<<< - * text = self.text_ - * limit = len(text) - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_start = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":72 - * location = self.location_() - * start = self.pos_ - * text = self.text_ # <<<<<<<<<<<<<< - * limit = len(text) - * if start >= limit: - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_text_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 72, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_text = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":73 - * start = self.pos_ - * text = self.text_ - * limit = len(text) # <<<<<<<<<<<<<< - * if start >= limit: - * raise StopIteration() - */ - __pyx_t_5 = PyObject_Length(__pyx_v_text); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 73, __pyx_L1_error) - __pyx_v_limit = __pyx_t_5; - - /* "fontTools/feaLib/lexer.py":74 - * text = self.text_ - * limit = len(text) - * if start >= limit: # <<<<<<<<<<<<<< - * raise StopIteration() - * cur_char = text[start] - */ - __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_limit); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 74, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_RichCompare(__pyx_v_start, __pyx_t_1, Py_GE); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 74, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 74, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (unlikely(__pyx_t_6)) { - - /* "fontTools/feaLib/lexer.py":75 - * limit = len(text) - * if start >= limit: - * raise StopIteration() # <<<<<<<<<<<<<< - * cur_char = text[start] - * next_char = text[start + 1] if start + 1 < limit else None - */ - __pyx_t_2 = __Pyx_PyObject_CallNoArg(__pyx_builtin_StopIteration); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 75, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __PYX_ERR(0, 75, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":74 - * text = self.text_ - * limit = len(text) - * if start >= limit: # <<<<<<<<<<<<<< - * raise StopIteration() - * cur_char = text[start] - */ - } - - /* "fontTools/feaLib/lexer.py":76 - * if start >= limit: - * raise StopIteration() - * cur_char = text[start] # <<<<<<<<<<<<<< - * next_char = text[start + 1] if start + 1 < limit else None - * - */ - __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_v_text, __pyx_v_start); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 76, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_v_cur_char = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":77 - * raise StopIteration() - * cur_char = text[start] - * next_char = text[start + 1] if start + 1 < limit else None # <<<<<<<<<<<<<< - * - * if cur_char == "\n": - */ - __pyx_t_1 = __Pyx_PyInt_AddObjC(__pyx_v_start, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 77, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_limit); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 77, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_1, __pyx_t_4, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 77, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 77, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - __pyx_t_3 = __Pyx_PyInt_AddObjC(__pyx_v_start, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 77, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetItem(__pyx_v_text, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 77, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_2 = __pyx_t_4; - __pyx_t_4 = 0; - } else { - __Pyx_INCREF(Py_None); - __pyx_t_2 = Py_None; - } - __pyx_v_next_char = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":79 - * next_char = text[start + 1] if start + 1 < limit else None - * - * if cur_char == "\n": # <<<<<<<<<<<<<< - * self.pos_ += 1 - * self.line_ += 1 - */ - __pyx_t_6 = (__Pyx_PyUnicode_Equals(__pyx_v_cur_char, __pyx_kp_u_, Py_EQ)); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 79, __pyx_L1_error) - if (__pyx_t_6) { - - /* "fontTools/feaLib/lexer.py":80 - * - * if cur_char == "\n": - * self.pos_ += 1 # <<<<<<<<<<<<<< - * self.line_ += 1 - * self.line_start_ = self.pos_ - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 80, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyInt_AddObjC(__pyx_t_2, __pyx_int_1, 1, 1, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 80, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_pos, __pyx_t_4) < 0) __PYX_ERR(0, 80, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "fontTools/feaLib/lexer.py":81 - * if cur_char == "\n": - * self.pos_ += 1 - * self.line_ += 1 # <<<<<<<<<<<<<< - * self.line_start_ = self.pos_ - * return (Lexer.NEWLINE, None, location) - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_line); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 81, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_PyInt_AddObjC(__pyx_t_4, __pyx_int_1, 1, 1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 81, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_line, __pyx_t_2) < 0) __PYX_ERR(0, 81, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":82 - * self.pos_ += 1 - * self.line_ += 1 - * self.line_start_ = self.pos_ # <<<<<<<<<<<<<< - * return (Lexer.NEWLINE, None, location) - * if cur_char == "\r": - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 82, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_line_start, __pyx_t_2) < 0) __PYX_ERR(0, 82, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":83 - * self.line_ += 1 - * self.line_start_ = self.pos_ - * return (Lexer.NEWLINE, None, location) # <<<<<<<<<<<<<< - * if cur_char == "\r": - * self.pos_ += 2 if next_char == "\n" else 1 - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 83, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_NEWLINE); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 83, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 83, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_4); - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - PyTuple_SET_ITEM(__pyx_t_2, 1, Py_None); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_v_location); - __pyx_t_4 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":79 - * next_char = text[start + 1] if start + 1 < limit else None - * - * if cur_char == "\n": # <<<<<<<<<<<<<< - * self.pos_ += 1 - * self.line_ += 1 - */ - } - - /* "fontTools/feaLib/lexer.py":84 - * self.line_start_ = self.pos_ - * return (Lexer.NEWLINE, None, location) - * if cur_char == "\r": # <<<<<<<<<<<<<< - * self.pos_ += 2 if next_char == "\n" else 1 - * self.line_ += 1 - */ - __pyx_t_6 = (__Pyx_PyUnicode_Equals(__pyx_v_cur_char, __pyx_kp_u__2, Py_EQ)); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 84, __pyx_L1_error) - if (__pyx_t_6) { - - /* "fontTools/feaLib/lexer.py":85 - * return (Lexer.NEWLINE, None, location) - * if cur_char == "\r": - * self.pos_ += 2 if next_char == "\n" else 1 # <<<<<<<<<<<<<< - * self.line_ += 1 - * self.line_start_ = self.pos_ - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 85, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_6 = (__Pyx_PyUnicode_Equals(__pyx_v_next_char, __pyx_kp_u_, Py_EQ)); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 85, __pyx_L1_error) - if (__pyx_t_6) { - __Pyx_INCREF(__pyx_int_2); - __pyx_t_4 = __pyx_int_2; - } else { - __Pyx_INCREF(__pyx_int_1); - __pyx_t_4 = __pyx_int_1; - } - __pyx_t_3 = PyNumber_InPlaceAdd(__pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 85, __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; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_pos, __pyx_t_3) < 0) __PYX_ERR(0, 85, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "fontTools/feaLib/lexer.py":86 - * if cur_char == "\r": - * self.pos_ += 2 if next_char == "\n" else 1 - * self.line_ += 1 # <<<<<<<<<<<<<< - * self.line_start_ = self.pos_ - * return (Lexer.NEWLINE, None, location) - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_line); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 86, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyInt_AddObjC(__pyx_t_3, __pyx_int_1, 1, 1, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 86, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_line, __pyx_t_4) < 0) __PYX_ERR(0, 86, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "fontTools/feaLib/lexer.py":87 - * self.pos_ += 2 if next_char == "\n" else 1 - * self.line_ += 1 - * self.line_start_ = self.pos_ # <<<<<<<<<<<<<< - * return (Lexer.NEWLINE, None, location) - * if cur_char == "#": - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 87, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_line_start, __pyx_t_4) < 0) __PYX_ERR(0, 87, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "fontTools/feaLib/lexer.py":88 - * self.line_ += 1 - * self.line_start_ = self.pos_ - * return (Lexer.NEWLINE, None, location) # <<<<<<<<<<<<<< - * if cur_char == "#": - * self.scan_until_(Lexer.CHAR_NEWLINE_) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 88, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_NEWLINE); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 88, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 88, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - PyTuple_SET_ITEM(__pyx_t_4, 1, Py_None); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_v_location); - __pyx_t_3 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":84 - * self.line_start_ = self.pos_ - * return (Lexer.NEWLINE, None, location) - * if cur_char == "\r": # <<<<<<<<<<<<<< - * self.pos_ += 2 if next_char == "\n" else 1 - * self.line_ += 1 - */ - } - - /* "fontTools/feaLib/lexer.py":89 - * self.line_start_ = self.pos_ - * return (Lexer.NEWLINE, None, location) - * if cur_char == "#": # <<<<<<<<<<<<<< - * self.scan_until_(Lexer.CHAR_NEWLINE_) - * return (Lexer.COMMENT, text[start : self.pos_], location) - */ - __pyx_t_6 = (__Pyx_PyUnicode_Equals(__pyx_v_cur_char, __pyx_kp_u__3, Py_EQ)); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 89, __pyx_L1_error) - if (__pyx_t_6) { - - /* "fontTools/feaLib/lexer.py":90 - * return (Lexer.NEWLINE, None, location) - * if cur_char == "#": - * self.scan_until_(Lexer.CHAR_NEWLINE_) # <<<<<<<<<<<<<< - * return (Lexer.COMMENT, text[start : self.pos_], location) - * - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_scan_until); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 90, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 90, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_CHAR_NEWLINE); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 90, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __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_4 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_2, __pyx_t_1) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 90, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "fontTools/feaLib/lexer.py":91 - * if cur_char == "#": - * self.scan_until_(Lexer.CHAR_NEWLINE_) - * return (Lexer.COMMENT, text[start : self.pos_], location) # <<<<<<<<<<<<<< - * - * if self.mode_ is Lexer.MODE_FILENAME_: - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 91, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_COMMENT); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 91, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 91, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetSlice(__pyx_v_text, 0, 0, &__pyx_v_start, &__pyx_t_4, NULL, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 91, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 91, __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_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_v_location); - __pyx_t_3 = 0; - __pyx_t_1 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":89 - * self.line_start_ = self.pos_ - * return (Lexer.NEWLINE, None, location) - * if cur_char == "#": # <<<<<<<<<<<<<< - * self.scan_until_(Lexer.CHAR_NEWLINE_) - * return (Lexer.COMMENT, text[start : self.pos_], location) - */ - } - - /* "fontTools/feaLib/lexer.py":93 - * return (Lexer.COMMENT, text[start : self.pos_], location) - * - * if self.mode_ is Lexer.MODE_FILENAME_: # <<<<<<<<<<<<<< - * if cur_char != "(": - * raise FeatureLibError("Expected '(' before file name", location) - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_mode); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 93, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 93, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_MODE_FILENAME); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 93, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_6 = (__pyx_t_4 == __pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = (__pyx_t_6 != 0); - if (__pyx_t_7) { - - /* "fontTools/feaLib/lexer.py":94 - * - * if self.mode_ is Lexer.MODE_FILENAME_: - * if cur_char != "(": # <<<<<<<<<<<<<< - * raise FeatureLibError("Expected '(' before file name", location) - * self.scan_until_(")") - */ - __pyx_t_7 = (__Pyx_PyUnicode_Equals(__pyx_v_cur_char, __pyx_kp_u__4, Py_NE)); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 94, __pyx_L1_error) - if (unlikely(__pyx_t_7)) { - - /* "fontTools/feaLib/lexer.py":95 - * if self.mode_ is Lexer.MODE_FILENAME_: - * if cur_char != "(": - * raise FeatureLibError("Expected '(' before file name", location) # <<<<<<<<<<<<<< - * self.scan_until_(")") - * cur_char = text[self.pos_] if self.pos_ < limit else None - */ - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_FeatureLibError); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 95, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = NULL; - __pyx_t_8 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_1)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - __pyx_t_8 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[3] = {__pyx_t_1, __pyx_kp_u_Expected_before_file_name, __pyx_v_location}; - __pyx_t_3 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 95, __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_4)) { - PyObject *__pyx_temp[3] = {__pyx_t_1, __pyx_kp_u_Expected_before_file_name, __pyx_v_location}; - __pyx_t_3 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 95, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else - #endif - { - __pyx_t_2 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 95, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (__pyx_t_1) { - __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); __pyx_t_1 = NULL; - } - __Pyx_INCREF(__pyx_kp_u_Expected_before_file_name); - __Pyx_GIVEREF(__pyx_kp_u_Expected_before_file_name); - PyTuple_SET_ITEM(__pyx_t_2, 0+__pyx_t_8, __pyx_kp_u_Expected_before_file_name); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_2, 1+__pyx_t_8, __pyx_v_location); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 95, __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_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(0, 95, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":94 - * - * if self.mode_ is Lexer.MODE_FILENAME_: - * if cur_char != "(": # <<<<<<<<<<<<<< - * raise FeatureLibError("Expected '(' before file name", location) - * self.scan_until_(")") - */ - } - - /* "fontTools/feaLib/lexer.py":96 - * if cur_char != "(": - * raise FeatureLibError("Expected '(' before file name", location) - * self.scan_until_(")") # <<<<<<<<<<<<<< - * cur_char = text[self.pos_] if self.pos_ < limit else None - * if cur_char != ")": - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_scan_until); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 96, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_2)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - __pyx_t_3 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_2, __pyx_kp_u__5) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_kp_u__5); - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 96, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "fontTools/feaLib/lexer.py":97 - * raise FeatureLibError("Expected '(' before file name", location) - * self.scan_until_(")") - * cur_char = text[self.pos_] if self.pos_ < limit else None # <<<<<<<<<<<<<< - * if cur_char != ")": - * raise FeatureLibError("Expected ')' after file name", location) - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 97, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_limit); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 97, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_RichCompare(__pyx_t_4, __pyx_t_2, Py_LT); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 97, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 97, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_7) { - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 97, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_v_text, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 97, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __pyx_t_2; - __pyx_t_2 = 0; - } else { - __Pyx_INCREF(Py_None); - __pyx_t_3 = Py_None; - } - __Pyx_DECREF_SET(__pyx_v_cur_char, __pyx_t_3); - __pyx_t_3 = 0; - - /* "fontTools/feaLib/lexer.py":98 - * self.scan_until_(")") - * cur_char = text[self.pos_] if self.pos_ < limit else None - * if cur_char != ")": # <<<<<<<<<<<<<< - * raise FeatureLibError("Expected ')' after file name", location) - * self.pos_ += 1 - */ - __pyx_t_7 = (__Pyx_PyUnicode_Equals(__pyx_v_cur_char, __pyx_kp_u__5, Py_NE)); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 98, __pyx_L1_error) - if (unlikely(__pyx_t_7)) { - - /* "fontTools/feaLib/lexer.py":99 - * cur_char = text[self.pos_] if self.pos_ < limit else None - * if cur_char != ")": - * raise FeatureLibError("Expected ')' after file name", location) # <<<<<<<<<<<<<< - * self.pos_ += 1 - * self.mode_ = Lexer.MODE_NORMAL_ - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_FeatureLibError); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = NULL; - __pyx_t_8 = 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_8 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[3] = {__pyx_t_1, __pyx_kp_u_Expected_after_file_name, __pyx_v_location}; - __pyx_t_3 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 99, __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[3] = {__pyx_t_1, __pyx_kp_u_Expected_after_file_name, __pyx_v_location}; - __pyx_t_3 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else - #endif - { - __pyx_t_4 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (__pyx_t_1) { - __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); __pyx_t_1 = NULL; - } - __Pyx_INCREF(__pyx_kp_u_Expected_after_file_name); - __Pyx_GIVEREF(__pyx_kp_u_Expected_after_file_name); - PyTuple_SET_ITEM(__pyx_t_4, 0+__pyx_t_8, __pyx_kp_u_Expected_after_file_name); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_4, 1+__pyx_t_8, __pyx_v_location); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(0, 99, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":98 - * self.scan_until_(")") - * cur_char = text[self.pos_] if self.pos_ < limit else None - * if cur_char != ")": # <<<<<<<<<<<<<< - * raise FeatureLibError("Expected ')' after file name", location) - * self.pos_ += 1 - */ - } - - /* "fontTools/feaLib/lexer.py":100 - * if cur_char != ")": - * raise FeatureLibError("Expected ')' after file name", location) - * self.pos_ += 1 # <<<<<<<<<<<<<< - * self.mode_ = Lexer.MODE_NORMAL_ - * return (Lexer.FILENAME, text[start + 1 : self.pos_ - 1], location) - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 100, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyInt_AddObjC(__pyx_t_3, __pyx_int_1, 1, 1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 100, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_pos, __pyx_t_2) < 0) __PYX_ERR(0, 100, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":101 - * raise FeatureLibError("Expected ')' after file name", location) - * self.pos_ += 1 - * self.mode_ = Lexer.MODE_NORMAL_ # <<<<<<<<<<<<<< - * return (Lexer.FILENAME, text[start + 1 : self.pos_ - 1], location) - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 101, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_MODE_NORMAL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 101, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_mode, __pyx_t_3) < 0) __PYX_ERR(0, 101, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "fontTools/feaLib/lexer.py":102 - * self.pos_ += 1 - * self.mode_ = Lexer.MODE_NORMAL_ - * return (Lexer.FILENAME, text[start + 1 : self.pos_ - 1], location) # <<<<<<<<<<<<<< - * - * if cur_char == "\\" and next_char in Lexer.CHAR_DIGIT_: - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 102, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_FILENAME); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 102, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyInt_AddObjC(__pyx_v_start, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 102, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 102, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyInt_SubtractObjC(__pyx_t_4, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 102, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_GetSlice(__pyx_v_text, 0, 0, &__pyx_t_3, &__pyx_t_1, NULL, 0, 0, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 102, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 102, __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_4); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_4); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_location); - __pyx_t_2 = 0; - __pyx_t_4 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":93 - * return (Lexer.COMMENT, text[start : self.pos_], location) - * - * if self.mode_ is Lexer.MODE_FILENAME_: # <<<<<<<<<<<<<< - * if cur_char != "(": - * raise FeatureLibError("Expected '(' before file name", location) - */ - } - - /* "fontTools/feaLib/lexer.py":104 - * return (Lexer.FILENAME, text[start + 1 : self.pos_ - 1], location) - * - * if cur_char == "\\" and next_char in Lexer.CHAR_DIGIT_: # <<<<<<<<<<<<<< - * self.pos_ += 1 - * self.scan_over_(Lexer.CHAR_DIGIT_) - */ - __pyx_t_6 = (__Pyx_PyUnicode_Equals(__pyx_v_cur_char, __pyx_kp_u__6, Py_EQ)); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 104, __pyx_L1_error) - if (__pyx_t_6) { - } else { - __pyx_t_7 = __pyx_t_6; - goto __pyx_L11_bool_binop_done; - } - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 104, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_CHAR_DIGIT); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 104, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_6 = (__Pyx_PySequence_ContainsTF(__pyx_v_next_char, __pyx_t_4, Py_EQ)); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 104, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_9 = (__pyx_t_6 != 0); - __pyx_t_7 = __pyx_t_9; - __pyx_L11_bool_binop_done:; - if (__pyx_t_7) { - - /* "fontTools/feaLib/lexer.py":105 - * - * if cur_char == "\\" and next_char in Lexer.CHAR_DIGIT_: - * self.pos_ += 1 # <<<<<<<<<<<<<< - * self.scan_over_(Lexer.CHAR_DIGIT_) - * return (Lexer.CID, int(text[start + 1 : self.pos_], 10), location) - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 105, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyInt_AddObjC(__pyx_t_4, __pyx_int_1, 1, 1, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 105, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_pos, __pyx_t_1) < 0) __PYX_ERR(0, 105, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":106 - * if cur_char == "\\" and next_char in Lexer.CHAR_DIGIT_: - * self.pos_ += 1 - * self.scan_over_(Lexer.CHAR_DIGIT_) # <<<<<<<<<<<<<< - * return (Lexer.CID, int(text[start + 1 : self.pos_], 10), location) - * if cur_char == "@": - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_scan_over); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 106, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 106, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_CHAR_DIGIT); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 106, __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_4))) { - __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_2)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - __pyx_t_1 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_2, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 106, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":107 - * self.pos_ += 1 - * self.scan_over_(Lexer.CHAR_DIGIT_) - * return (Lexer.CID, int(text[start + 1 : self.pos_], 10), location) # <<<<<<<<<<<<<< - * if cur_char == "@": - * self.pos_ += 1 - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 107, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_CID); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 107, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyInt_AddObjC(__pyx_v_start, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 107, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 107, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetSlice(__pyx_v_text, 0, 0, &__pyx_t_1, &__pyx_t_3, NULL, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 107, __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_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 107, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); - __Pyx_INCREF(__pyx_int_10); - __Pyx_GIVEREF(__pyx_int_10); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_10); - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)(&PyInt_Type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 107, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 107, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_v_location); - __pyx_t_4 = 0; - __pyx_t_2 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":104 - * return (Lexer.FILENAME, text[start + 1 : self.pos_ - 1], location) - * - * if cur_char == "\\" and next_char in Lexer.CHAR_DIGIT_: # <<<<<<<<<<<<<< - * self.pos_ += 1 - * self.scan_over_(Lexer.CHAR_DIGIT_) - */ - } - - /* "fontTools/feaLib/lexer.py":108 - * self.scan_over_(Lexer.CHAR_DIGIT_) - * return (Lexer.CID, int(text[start + 1 : self.pos_], 10), location) - * if cur_char == "@": # <<<<<<<<<<<<<< - * self.pos_ += 1 - * self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_) - */ - __pyx_t_7 = (__Pyx_PyUnicode_Equals(__pyx_v_cur_char, __pyx_kp_u__7, Py_EQ)); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 108, __pyx_L1_error) - if (__pyx_t_7) { - - /* "fontTools/feaLib/lexer.py":109 - * return (Lexer.CID, int(text[start + 1 : self.pos_], 10), location) - * if cur_char == "@": - * self.pos_ += 1 # <<<<<<<<<<<<<< - * self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_) - * glyphclass = text[start + 1 : self.pos_] - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 109, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyInt_AddObjC(__pyx_t_3, __pyx_int_1, 1, 1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 109, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_pos, __pyx_t_2) < 0) __PYX_ERR(0, 109, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":110 - * if cur_char == "@": - * self.pos_ += 1 - * self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_) # <<<<<<<<<<<<<< - * glyphclass = text[start + 1 : self.pos_] - * if len(glyphclass) < 1: - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_scan_over); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 110, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 110, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_CHAR_NAME_CONTINUATION); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 110, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_t_1) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 110, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":111 - * self.pos_ += 1 - * self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_) - * glyphclass = text[start + 1 : self.pos_] # <<<<<<<<<<<<<< - * if len(glyphclass) < 1: - * raise FeatureLibError("Expected glyph class name", location) - */ - __pyx_t_2 = __Pyx_PyInt_AddObjC(__pyx_v_start, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 111, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 111, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = __Pyx_PyObject_GetSlice(__pyx_v_text, 0, 0, &__pyx_t_2, &__pyx_t_3, NULL, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 111, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_glyphclass = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":112 - * self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_) - * glyphclass = text[start + 1 : self.pos_] - * if len(glyphclass) < 1: # <<<<<<<<<<<<<< - * raise FeatureLibError("Expected glyph class name", location) - * if len(glyphclass) > 63: - */ - __pyx_t_5 = PyObject_Length(__pyx_v_glyphclass); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 112, __pyx_L1_error) - __pyx_t_7 = ((__pyx_t_5 < 1) != 0); - if (unlikely(__pyx_t_7)) { - - /* "fontTools/feaLib/lexer.py":113 - * glyphclass = text[start + 1 : self.pos_] - * if len(glyphclass) < 1: - * raise FeatureLibError("Expected glyph class name", location) # <<<<<<<<<<<<<< - * if len(glyphclass) > 63: - * raise FeatureLibError( - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_FeatureLibError); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 113, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = NULL; - __pyx_t_8 = 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_8 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_2, __pyx_kp_u_Expected_glyph_class_name, __pyx_v_location}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 113, __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_kp_u_Expected_glyph_class_name, __pyx_v_location}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 113, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_4 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 113, __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_INCREF(__pyx_kp_u_Expected_glyph_class_name); - __Pyx_GIVEREF(__pyx_kp_u_Expected_glyph_class_name); - PyTuple_SET_ITEM(__pyx_t_4, 0+__pyx_t_8, __pyx_kp_u_Expected_glyph_class_name); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_4, 1+__pyx_t_8, __pyx_v_location); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 113, __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_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(0, 113, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":112 - * self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_) - * glyphclass = text[start + 1 : self.pos_] - * if len(glyphclass) < 1: # <<<<<<<<<<<<<< - * raise FeatureLibError("Expected glyph class name", location) - * if len(glyphclass) > 63: - */ - } - - /* "fontTools/feaLib/lexer.py":114 - * if len(glyphclass) < 1: - * raise FeatureLibError("Expected glyph class name", location) - * if len(glyphclass) > 63: # <<<<<<<<<<<<<< - * raise FeatureLibError( - * "Glyph class names must not be longer than 63 characters", location - */ - __pyx_t_5 = PyObject_Length(__pyx_v_glyphclass); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 114, __pyx_L1_error) - __pyx_t_7 = ((__pyx_t_5 > 63) != 0); - if (unlikely(__pyx_t_7)) { - - /* "fontTools/feaLib/lexer.py":115 - * raise FeatureLibError("Expected glyph class name", location) - * if len(glyphclass) > 63: - * raise FeatureLibError( # <<<<<<<<<<<<<< - * "Glyph class names must not be longer than 63 characters", location - * ) - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_FeatureLibError); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 115, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - - /* "fontTools/feaLib/lexer.py":116 - * if len(glyphclass) > 63: - * raise FeatureLibError( - * "Glyph class names must not be longer than 63 characters", location # <<<<<<<<<<<<<< - * ) - * if not Lexer.RE_GLYPHCLASS.match(glyphclass): - */ - __pyx_t_4 = NULL; - __pyx_t_8 = 0; - 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_8 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_4, __pyx_kp_u_Glyph_class_names_must_not_be_lo, __pyx_v_location}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 115, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 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_4, __pyx_kp_u_Glyph_class_names_must_not_be_lo, __pyx_v_location}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 115, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_2 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 115, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (__pyx_t_4) { - __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_4); __pyx_t_4 = NULL; - } - __Pyx_INCREF(__pyx_kp_u_Glyph_class_names_must_not_be_lo); - __Pyx_GIVEREF(__pyx_kp_u_Glyph_class_names_must_not_be_lo); - PyTuple_SET_ITEM(__pyx_t_2, 0+__pyx_t_8, __pyx_kp_u_Glyph_class_names_must_not_be_lo); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_2, 1+__pyx_t_8, __pyx_v_location); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 115, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(0, 115, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":114 - * if len(glyphclass) < 1: - * raise FeatureLibError("Expected glyph class name", location) - * if len(glyphclass) > 63: # <<<<<<<<<<<<<< - * raise FeatureLibError( - * "Glyph class names must not be longer than 63 characters", location - */ - } - - /* "fontTools/feaLib/lexer.py":118 - * "Glyph class names must not be longer than 63 characters", location - * ) - * if not Lexer.RE_GLYPHCLASS.match(glyphclass): # <<<<<<<<<<<<<< - * raise FeatureLibError( - * "Glyph class names must consist of letters, digits, " - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 118, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_RE_GLYPHCLASS); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 118, __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_match); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 118, __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_glyphclass) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_v_glyphclass); - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 118, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 118, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_9 = ((!__pyx_t_7) != 0); - if (unlikely(__pyx_t_9)) { - - /* "fontTools/feaLib/lexer.py":119 - * ) - * if not Lexer.RE_GLYPHCLASS.match(glyphclass): - * raise FeatureLibError( # <<<<<<<<<<<<<< - * "Glyph class names must consist of letters, digits, " - * "underscore, period or hyphen", - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_FeatureLibError); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 119, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - - /* "fontTools/feaLib/lexer.py":122 - * "Glyph class names must consist of letters, digits, " - * "underscore, period or hyphen", - * location, # <<<<<<<<<<<<<< - * ) - * return (Lexer.GLYPHCLASS, glyphclass, location) - */ - __pyx_t_2 = NULL; - __pyx_t_8 = 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_8 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_2, __pyx_kp_u_Glyph_class_names_must_consist_o, __pyx_v_location}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 119, __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_kp_u_Glyph_class_names_must_consist_o, __pyx_v_location}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 119, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_4 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 119, __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_INCREF(__pyx_kp_u_Glyph_class_names_must_consist_o); - __Pyx_GIVEREF(__pyx_kp_u_Glyph_class_names_must_consist_o); - PyTuple_SET_ITEM(__pyx_t_4, 0+__pyx_t_8, __pyx_kp_u_Glyph_class_names_must_consist_o); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_4, 1+__pyx_t_8, __pyx_v_location); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 119, __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_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(0, 119, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":118 - * "Glyph class names must not be longer than 63 characters", location - * ) - * if not Lexer.RE_GLYPHCLASS.match(glyphclass): # <<<<<<<<<<<<<< - * raise FeatureLibError( - * "Glyph class names must consist of letters, digits, " - */ - } - - /* "fontTools/feaLib/lexer.py":124 - * location, - * ) - * return (Lexer.GLYPHCLASS, glyphclass, location) # <<<<<<<<<<<<<< - * if cur_char in Lexer.CHAR_NAME_START_: - * self.pos_ += 1 - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 124, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_GLYPHCLASS); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 124, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 124, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_3); - __Pyx_INCREF(__pyx_v_glyphclass); - __Pyx_GIVEREF(__pyx_v_glyphclass); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_glyphclass); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_location); - __pyx_t_3 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":108 - * self.scan_over_(Lexer.CHAR_DIGIT_) - * return (Lexer.CID, int(text[start + 1 : self.pos_], 10), location) - * if cur_char == "@": # <<<<<<<<<<<<<< - * self.pos_ += 1 - * self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_) - */ - } - - /* "fontTools/feaLib/lexer.py":125 - * ) - * return (Lexer.GLYPHCLASS, glyphclass, location) - * if cur_char in Lexer.CHAR_NAME_START_: # <<<<<<<<<<<<<< - * self.pos_ += 1 - * self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_) - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 125, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_CHAR_NAME_START); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 125, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_9 = (__Pyx_PySequence_ContainsTF(__pyx_v_cur_char, __pyx_t_3, Py_EQ)); if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 125, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = (__pyx_t_9 != 0); - if (__pyx_t_7) { - - /* "fontTools/feaLib/lexer.py":126 - * return (Lexer.GLYPHCLASS, glyphclass, location) - * if cur_char in Lexer.CHAR_NAME_START_: - * self.pos_ += 1 # <<<<<<<<<<<<<< - * self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_) - * token = text[start : self.pos_] - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = __Pyx_PyInt_AddObjC(__pyx_t_3, __pyx_int_1, 1, 1, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_pos, __pyx_t_1) < 0) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":127 - * if cur_char in Lexer.CHAR_NAME_START_: - * self.pos_ += 1 - * self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_) # <<<<<<<<<<<<<< - * token = text[start : self.pos_] - * if token == "include": - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_scan_over); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 127, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 127, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_CHAR_NAME_CONTINUATION); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 127, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_4, __pyx_t_2) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_2); - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 127, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":128 - * self.pos_ += 1 - * self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_) - * token = text[start : self.pos_] # <<<<<<<<<<<<<< - * if token == "include": - * self.mode_ = Lexer.MODE_FILENAME_ - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 128, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_GetSlice(__pyx_v_text, 0, 0, &__pyx_v_start, &__pyx_t_1, NULL, 0, 0, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 128, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_token = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/feaLib/lexer.py":129 - * self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_) - * token = text[start : self.pos_] - * if token == "include": # <<<<<<<<<<<<<< - * self.mode_ = Lexer.MODE_FILENAME_ - * return (Lexer.NAME, token, location) - */ - __pyx_t_7 = (__Pyx_PyUnicode_Equals(__pyx_v_token, __pyx_n_u_include, Py_EQ)); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 129, __pyx_L1_error) - if (__pyx_t_7) { - - /* "fontTools/feaLib/lexer.py":130 - * token = text[start : self.pos_] - * if token == "include": - * self.mode_ = Lexer.MODE_FILENAME_ # <<<<<<<<<<<<<< - * return (Lexer.NAME, token, location) - * if cur_char == "0" and next_char in "xX": - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 130, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_MODE_FILENAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 130, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_mode, __pyx_t_1) < 0) __PYX_ERR(0, 130, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":129 - * self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_) - * token = text[start : self.pos_] - * if token == "include": # <<<<<<<<<<<<<< - * self.mode_ = Lexer.MODE_FILENAME_ - * return (Lexer.NAME, token, location) - */ - } - - /* "fontTools/feaLib/lexer.py":131 - * if token == "include": - * self.mode_ = Lexer.MODE_FILENAME_ - * return (Lexer.NAME, token, location) # <<<<<<<<<<<<<< - * if cur_char == "0" and next_char in "xX": - * self.pos_ += 2 - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 131, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_NAME); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 131, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 131, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_3); - __Pyx_INCREF(__pyx_v_token); - __Pyx_GIVEREF(__pyx_v_token); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_token); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_location); - __pyx_t_3 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":125 - * ) - * return (Lexer.GLYPHCLASS, glyphclass, location) - * if cur_char in Lexer.CHAR_NAME_START_: # <<<<<<<<<<<<<< - * self.pos_ += 1 - * self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_) - */ - } - - /* "fontTools/feaLib/lexer.py":132 - * self.mode_ = Lexer.MODE_FILENAME_ - * return (Lexer.NAME, token, location) - * if cur_char == "0" and next_char in "xX": # <<<<<<<<<<<<<< - * self.pos_ += 2 - * self.scan_over_(Lexer.CHAR_HEXDIGIT_) - */ - __pyx_t_9 = (__Pyx_PyUnicode_Equals(__pyx_v_cur_char, __pyx_kp_u_0, Py_EQ)); if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 132, __pyx_L1_error) - if (__pyx_t_9) { - } else { - __pyx_t_7 = __pyx_t_9; - goto __pyx_L20_bool_binop_done; - } - __pyx_t_9 = (__Pyx_PyUnicode_ContainsTF(__pyx_v_next_char, __pyx_n_u_xX, Py_EQ)); if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 132, __pyx_L1_error) - __pyx_t_6 = (__pyx_t_9 != 0); - __pyx_t_7 = __pyx_t_6; - __pyx_L20_bool_binop_done:; - if (__pyx_t_7) { - - /* "fontTools/feaLib/lexer.py":133 - * return (Lexer.NAME, token, location) - * if cur_char == "0" and next_char in "xX": - * self.pos_ += 2 # <<<<<<<<<<<<<< - * self.scan_over_(Lexer.CHAR_HEXDIGIT_) - * return (Lexer.HEXADECIMAL, int(text[start : self.pos_], 16), location) - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 133, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyInt_AddObjC(__pyx_t_1, __pyx_int_2, 2, 1, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 133, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_pos, __pyx_t_3) < 0) __PYX_ERR(0, 133, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "fontTools/feaLib/lexer.py":134 - * if cur_char == "0" and next_char in "xX": - * self.pos_ += 2 - * self.scan_over_(Lexer.CHAR_HEXDIGIT_) # <<<<<<<<<<<<<< - * return (Lexer.HEXADECIMAL, int(text[start : self.pos_], 16), location) - * if cur_char == "0" and next_char in Lexer.CHAR_DIGIT_: - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_scan_over); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 134, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 134, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_CHAR_HEXDIGIT); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 134, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_3 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_1, __pyx_t_2, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_1, __pyx_t_4); - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 134, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "fontTools/feaLib/lexer.py":135 - * self.pos_ += 2 - * self.scan_over_(Lexer.CHAR_HEXDIGIT_) - * return (Lexer.HEXADECIMAL, int(text[start : self.pos_], 16), location) # <<<<<<<<<<<<<< - * if cur_char == "0" and next_char in Lexer.CHAR_DIGIT_: - * self.scan_over_(Lexer.CHAR_DIGIT_) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 135, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_HEXADECIMAL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 135, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 135, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetSlice(__pyx_v_text, 0, 0, &__pyx_v_start, &__pyx_t_3, NULL, 0, 0, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 135, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 135, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); - __Pyx_INCREF(__pyx_int_16); - __Pyx_GIVEREF(__pyx_int_16); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_16); - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)(&PyInt_Type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 135, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 135, __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_4); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_v_location); - __pyx_t_1 = 0; - __pyx_t_4 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":132 - * self.mode_ = Lexer.MODE_FILENAME_ - * return (Lexer.NAME, token, location) - * if cur_char == "0" and next_char in "xX": # <<<<<<<<<<<<<< - * self.pos_ += 2 - * self.scan_over_(Lexer.CHAR_HEXDIGIT_) - */ - } - - /* "fontTools/feaLib/lexer.py":136 - * self.scan_over_(Lexer.CHAR_HEXDIGIT_) - * return (Lexer.HEXADECIMAL, int(text[start : self.pos_], 16), location) - * if cur_char == "0" and next_char in Lexer.CHAR_DIGIT_: # <<<<<<<<<<<<<< - * self.scan_over_(Lexer.CHAR_DIGIT_) - * return (Lexer.OCTAL, int(text[start : self.pos_], 8), location) - */ - __pyx_t_6 = (__Pyx_PyUnicode_Equals(__pyx_v_cur_char, __pyx_kp_u_0, Py_EQ)); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 136, __pyx_L1_error) - if (__pyx_t_6) { - } else { - __pyx_t_7 = __pyx_t_6; - goto __pyx_L23_bool_binop_done; - } - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 136, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_CHAR_DIGIT); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 136, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = (__Pyx_PySequence_ContainsTF(__pyx_v_next_char, __pyx_t_4, Py_EQ)); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 136, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_9 = (__pyx_t_6 != 0); - __pyx_t_7 = __pyx_t_9; - __pyx_L23_bool_binop_done:; - if (__pyx_t_7) { - - /* "fontTools/feaLib/lexer.py":137 - * return (Lexer.HEXADECIMAL, int(text[start : self.pos_], 16), location) - * if cur_char == "0" and next_char in Lexer.CHAR_DIGIT_: - * self.scan_over_(Lexer.CHAR_DIGIT_) # <<<<<<<<<<<<<< - * return (Lexer.OCTAL, int(text[start : self.pos_], 8), location) - * if cur_char in Lexer.CHAR_DIGIT_: - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_scan_over); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 137, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 137, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_CHAR_DIGIT); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 137, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_4 = (__pyx_t_1) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_1, __pyx_t_2) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_2); - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 137, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "fontTools/feaLib/lexer.py":138 - * if cur_char == "0" and next_char in Lexer.CHAR_DIGIT_: - * self.scan_over_(Lexer.CHAR_DIGIT_) - * return (Lexer.OCTAL, int(text[start : self.pos_], 8), location) # <<<<<<<<<<<<<< - * if cur_char in Lexer.CHAR_DIGIT_: - * self.scan_over_(Lexer.CHAR_DIGIT_) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 138, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_OCTAL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 138, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 138, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_PyObject_GetSlice(__pyx_v_text, 0, 0, &__pyx_v_start, &__pyx_t_4, NULL, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 138, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 138, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_INCREF(__pyx_int_8); - __Pyx_GIVEREF(__pyx_int_8); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_int_8); - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)(&PyInt_Type)), __pyx_t_4, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 138, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 138, __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_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_v_location); - __pyx_t_3 = 0; - __pyx_t_2 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":136 - * self.scan_over_(Lexer.CHAR_HEXDIGIT_) - * return (Lexer.HEXADECIMAL, int(text[start : self.pos_], 16), location) - * if cur_char == "0" and next_char in Lexer.CHAR_DIGIT_: # <<<<<<<<<<<<<< - * self.scan_over_(Lexer.CHAR_DIGIT_) - * return (Lexer.OCTAL, int(text[start : self.pos_], 8), location) - */ - } - - /* "fontTools/feaLib/lexer.py":139 - * self.scan_over_(Lexer.CHAR_DIGIT_) - * return (Lexer.OCTAL, int(text[start : self.pos_], 8), location) - * if cur_char in Lexer.CHAR_DIGIT_: # <<<<<<<<<<<<<< - * self.scan_over_(Lexer.CHAR_DIGIT_) - * if self.pos_ >= limit or text[self.pos_] != ".": - */ - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 139, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_CHAR_DIGIT); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 139, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_7 = (__Pyx_PySequence_ContainsTF(__pyx_v_cur_char, __pyx_t_2, Py_EQ)); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 139, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_9 = (__pyx_t_7 != 0); - if (__pyx_t_9) { - - /* "fontTools/feaLib/lexer.py":140 - * return (Lexer.OCTAL, int(text[start : self.pos_], 8), location) - * if cur_char in Lexer.CHAR_DIGIT_: - * self.scan_over_(Lexer.CHAR_DIGIT_) # <<<<<<<<<<<<<< - * if self.pos_ >= limit or text[self.pos_] != ".": - * return (Lexer.NUMBER, int(text[start : self.pos_], 10), location) - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_scan_over); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 140, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 140, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_CHAR_DIGIT); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 140, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - __pyx_t_2 = (__pyx_t_3) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_3, __pyx_t_1) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 140, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":141 - * if cur_char in Lexer.CHAR_DIGIT_: - * self.scan_over_(Lexer.CHAR_DIGIT_) - * if self.pos_ >= limit or text[self.pos_] != ".": # <<<<<<<<<<<<<< - * return (Lexer.NUMBER, int(text[start : self.pos_], 10), location) - * self.scan_over_(".") - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 141, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_limit); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 141, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyObject_RichCompare(__pyx_t_2, __pyx_t_4, Py_GE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 141, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 141, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!__pyx_t_7) { - } else { - __pyx_t_9 = __pyx_t_7; - goto __pyx_L27_bool_binop_done; - } - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 141, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetItem(__pyx_v_text, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 141, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_7 = (__Pyx_PyUnicode_Equals(__pyx_t_4, __pyx_kp_u__8, Py_NE)); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 141, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_9 = __pyx_t_7; - __pyx_L27_bool_binop_done:; - if (__pyx_t_9) { - - /* "fontTools/feaLib/lexer.py":142 - * self.scan_over_(Lexer.CHAR_DIGIT_) - * if self.pos_ >= limit or text[self.pos_] != ".": - * return (Lexer.NUMBER, int(text[start : self.pos_], 10), location) # <<<<<<<<<<<<<< - * self.scan_over_(".") - * self.scan_over_(Lexer.CHAR_DIGIT_) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_NUMBER); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_PyObject_GetSlice(__pyx_v_text, 0, 0, &__pyx_v_start, &__pyx_t_4, NULL, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_INCREF(__pyx_int_10); - __Pyx_GIVEREF(__pyx_int_10); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_int_10); - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)(&PyInt_Type)), __pyx_t_4, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_v_location); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":141 - * if cur_char in Lexer.CHAR_DIGIT_: - * self.scan_over_(Lexer.CHAR_DIGIT_) - * if self.pos_ >= limit or text[self.pos_] != ".": # <<<<<<<<<<<<<< - * return (Lexer.NUMBER, int(text[start : self.pos_], 10), location) - * self.scan_over_(".") - */ - } - - /* "fontTools/feaLib/lexer.py":143 - * if self.pos_ >= limit or text[self.pos_] != ".": - * return (Lexer.NUMBER, int(text[start : self.pos_], 10), location) - * self.scan_over_(".") # <<<<<<<<<<<<<< - * self.scan_over_(Lexer.CHAR_DIGIT_) - * return (Lexer.FLOAT, float(text[start : self.pos_]), location) - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_scan_over); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 143, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_4 = (__pyx_t_1) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_1, __pyx_kp_u__8) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_kp_u__8); - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 143, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "fontTools/feaLib/lexer.py":144 - * return (Lexer.NUMBER, int(text[start : self.pos_], 10), location) - * self.scan_over_(".") - * self.scan_over_(Lexer.CHAR_DIGIT_) # <<<<<<<<<<<<<< - * return (Lexer.FLOAT, float(text[start : self.pos_]), location) - * if cur_char == "-" and next_char in Lexer.CHAR_DIGIT_: - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_scan_over); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 144, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 144, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_CHAR_DIGIT); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 144, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_4 = (__pyx_t_1) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_1, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3); - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 144, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "fontTools/feaLib/lexer.py":145 - * self.scan_over_(".") - * self.scan_over_(Lexer.CHAR_DIGIT_) - * return (Lexer.FLOAT, float(text[start : self.pos_]), location) # <<<<<<<<<<<<<< - * if cur_char == "-" and next_char in Lexer.CHAR_DIGIT_: - * self.pos_ += 1 - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_FLOAT); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyObject_GetSlice(__pyx_v_text, 0, 0, &__pyx_v_start, &__pyx_t_4, NULL, 0, 0, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyNumber_Float(__pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 145, __pyx_L1_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_4); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_v_location); - __pyx_t_2 = 0; - __pyx_t_4 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":139 - * self.scan_over_(Lexer.CHAR_DIGIT_) - * return (Lexer.OCTAL, int(text[start : self.pos_], 8), location) - * if cur_char in Lexer.CHAR_DIGIT_: # <<<<<<<<<<<<<< - * self.scan_over_(Lexer.CHAR_DIGIT_) - * if self.pos_ >= limit or text[self.pos_] != ".": - */ - } - - /* "fontTools/feaLib/lexer.py":146 - * self.scan_over_(Lexer.CHAR_DIGIT_) - * return (Lexer.FLOAT, float(text[start : self.pos_]), location) - * if cur_char == "-" and next_char in Lexer.CHAR_DIGIT_: # <<<<<<<<<<<<<< - * self.pos_ += 1 - * self.scan_over_(Lexer.CHAR_DIGIT_) - */ - __pyx_t_7 = (__Pyx_PyUnicode_Equals(__pyx_v_cur_char, __pyx_kp_u__9, Py_EQ)); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 146, __pyx_L1_error) - if (__pyx_t_7) { - } else { - __pyx_t_9 = __pyx_t_7; - goto __pyx_L30_bool_binop_done; - } - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 146, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_CHAR_DIGIT); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 146, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = (__Pyx_PySequence_ContainsTF(__pyx_v_next_char, __pyx_t_4, Py_EQ)); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 146, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_6 = (__pyx_t_7 != 0); - __pyx_t_9 = __pyx_t_6; - __pyx_L30_bool_binop_done:; - if (__pyx_t_9) { - - /* "fontTools/feaLib/lexer.py":147 - * return (Lexer.FLOAT, float(text[start : self.pos_]), location) - * if cur_char == "-" and next_char in Lexer.CHAR_DIGIT_: - * self.pos_ += 1 # <<<<<<<<<<<<<< - * self.scan_over_(Lexer.CHAR_DIGIT_) - * if self.pos_ >= limit or text[self.pos_] != ".": - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyInt_AddObjC(__pyx_t_4, __pyx_int_1, 1, 1, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_pos, __pyx_t_3) < 0) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "fontTools/feaLib/lexer.py":148 - * if cur_char == "-" and next_char in Lexer.CHAR_DIGIT_: - * self.pos_ += 1 - * self.scan_over_(Lexer.CHAR_DIGIT_) # <<<<<<<<<<<<<< - * if self.pos_ >= limit or text[self.pos_] != ".": - * return (Lexer.NUMBER, int(text[start : self.pos_], 10), location) - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_scan_over); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_CHAR_DIGIT); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_2)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - __pyx_t_3 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_2, __pyx_t_1) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 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_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "fontTools/feaLib/lexer.py":149 - * self.pos_ += 1 - * self.scan_over_(Lexer.CHAR_DIGIT_) - * if self.pos_ >= limit or text[self.pos_] != ".": # <<<<<<<<<<<<<< - * return (Lexer.NUMBER, int(text[start : self.pos_], 10), location) - * self.scan_over_(".") - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 149, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_limit); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 149, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyObject_RichCompare(__pyx_t_3, __pyx_t_4, Py_GE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 149, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 149, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!__pyx_t_6) { - } else { - __pyx_t_9 = __pyx_t_6; - goto __pyx_L33_bool_binop_done; - } - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 149, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetItem(__pyx_v_text, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 149, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_6 = (__Pyx_PyUnicode_Equals(__pyx_t_4, __pyx_kp_u__8, Py_NE)); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 149, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_9 = __pyx_t_6; - __pyx_L33_bool_binop_done:; - if (__pyx_t_9) { - - /* "fontTools/feaLib/lexer.py":150 - * self.scan_over_(Lexer.CHAR_DIGIT_) - * if self.pos_ >= limit or text[self.pos_] != ".": - * return (Lexer.NUMBER, int(text[start : self.pos_], 10), location) # <<<<<<<<<<<<<< - * self.scan_over_(".") - * self.scan_over_(Lexer.CHAR_DIGIT_) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 150, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_NUMBER); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 150, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 150, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyObject_GetSlice(__pyx_v_text, 0, 0, &__pyx_v_start, &__pyx_t_4, NULL, 0, 0, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 150, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 150, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); - __Pyx_INCREF(__pyx_int_10); - __Pyx_GIVEREF(__pyx_int_10); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_int_10); - __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)(&PyInt_Type)), __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 150, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 150, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_v_location); - __pyx_t_1 = 0; - __pyx_t_3 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":149 - * self.pos_ += 1 - * self.scan_over_(Lexer.CHAR_DIGIT_) - * if self.pos_ >= limit or text[self.pos_] != ".": # <<<<<<<<<<<<<< - * return (Lexer.NUMBER, int(text[start : self.pos_], 10), location) - * self.scan_over_(".") - */ - } - - /* "fontTools/feaLib/lexer.py":151 - * if self.pos_ >= limit or text[self.pos_] != ".": - * return (Lexer.NUMBER, int(text[start : self.pos_], 10), location) - * self.scan_over_(".") # <<<<<<<<<<<<<< - * self.scan_over_(Lexer.CHAR_DIGIT_) - * return (Lexer.FLOAT, float(text[start : self.pos_]), location) - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_scan_over); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 151, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_4 = (__pyx_t_1) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_1, __pyx_kp_u__8) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_kp_u__8); - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 151, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "fontTools/feaLib/lexer.py":152 - * return (Lexer.NUMBER, int(text[start : self.pos_], 10), location) - * self.scan_over_(".") - * self.scan_over_(Lexer.CHAR_DIGIT_) # <<<<<<<<<<<<<< - * return (Lexer.FLOAT, float(text[start : self.pos_]), location) - * if cur_char in Lexer.CHAR_SYMBOL_: - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_scan_over); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 152, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 152, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_CHAR_DIGIT); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 152, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_4 = (__pyx_t_1) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_1, __pyx_t_2) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_2); - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 152, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "fontTools/feaLib/lexer.py":153 - * self.scan_over_(".") - * self.scan_over_(Lexer.CHAR_DIGIT_) - * return (Lexer.FLOAT, float(text[start : self.pos_]), location) # <<<<<<<<<<<<<< - * if cur_char in Lexer.CHAR_SYMBOL_: - * self.pos_ += 1 - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_FLOAT); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_PyObject_GetSlice(__pyx_v_text, 0, 0, &__pyx_v_start, &__pyx_t_4, NULL, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyNumber_Float(__pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_v_location); - __pyx_t_3 = 0; - __pyx_t_4 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":146 - * self.scan_over_(Lexer.CHAR_DIGIT_) - * return (Lexer.FLOAT, float(text[start : self.pos_]), location) - * if cur_char == "-" and next_char in Lexer.CHAR_DIGIT_: # <<<<<<<<<<<<<< - * self.pos_ += 1 - * self.scan_over_(Lexer.CHAR_DIGIT_) - */ - } - - /* "fontTools/feaLib/lexer.py":154 - * self.scan_over_(Lexer.CHAR_DIGIT_) - * return (Lexer.FLOAT, float(text[start : self.pos_]), location) - * if cur_char in Lexer.CHAR_SYMBOL_: # <<<<<<<<<<<<<< - * self.pos_ += 1 - * return (Lexer.SYMBOL, cur_char, location) - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 154, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_CHAR_SYMBOL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 154, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_9 = (__Pyx_PySequence_ContainsTF(__pyx_v_cur_char, __pyx_t_4, Py_EQ)); if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 154, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_6 = (__pyx_t_9 != 0); - if (__pyx_t_6) { - - /* "fontTools/feaLib/lexer.py":155 - * return (Lexer.FLOAT, float(text[start : self.pos_]), location) - * if cur_char in Lexer.CHAR_SYMBOL_: - * self.pos_ += 1 # <<<<<<<<<<<<<< - * return (Lexer.SYMBOL, cur_char, location) - * if cur_char == '"': - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 155, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_PyInt_AddObjC(__pyx_t_4, __pyx_int_1, 1, 1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 155, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_pos, __pyx_t_2) < 0) __PYX_ERR(0, 155, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":156 - * if cur_char in Lexer.CHAR_SYMBOL_: - * self.pos_ += 1 - * return (Lexer.SYMBOL, cur_char, location) # <<<<<<<<<<<<<< - * if cur_char == '"': - * self.pos_ += 1 - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 156, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_SYMBOL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 156, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 156, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_4); - __Pyx_INCREF(__pyx_v_cur_char); - __Pyx_GIVEREF(__pyx_v_cur_char); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_cur_char); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_v_location); - __pyx_t_4 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":154 - * self.scan_over_(Lexer.CHAR_DIGIT_) - * return (Lexer.FLOAT, float(text[start : self.pos_]), location) - * if cur_char in Lexer.CHAR_SYMBOL_: # <<<<<<<<<<<<<< - * self.pos_ += 1 - * return (Lexer.SYMBOL, cur_char, location) - */ - } - - /* "fontTools/feaLib/lexer.py":157 - * self.pos_ += 1 - * return (Lexer.SYMBOL, cur_char, location) - * if cur_char == '"': # <<<<<<<<<<<<<< - * self.pos_ += 1 - * self.scan_until_('"') - */ - __pyx_t_6 = (__Pyx_PyUnicode_Equals(__pyx_v_cur_char, __pyx_kp_u__10, Py_EQ)); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 157, __pyx_L1_error) - if (__pyx_t_6) { - - /* "fontTools/feaLib/lexer.py":158 - * return (Lexer.SYMBOL, cur_char, location) - * if cur_char == '"': - * self.pos_ += 1 # <<<<<<<<<<<<<< - * self.scan_until_('"') - * if self.pos_ < self.text_length_ and self.text_[self.pos_] == '"': - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 158, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyInt_AddObjC(__pyx_t_2, __pyx_int_1, 1, 1, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 158, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_pos, __pyx_t_4) < 0) __PYX_ERR(0, 158, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "fontTools/feaLib/lexer.py":159 - * if cur_char == '"': - * self.pos_ += 1 - * self.scan_until_('"') # <<<<<<<<<<<<<< - * if self.pos_ < self.text_length_ and self.text_[self.pos_] == '"': - * self.pos_ += 1 - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_scan_until); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 159, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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 = (__pyx_t_3) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_3, __pyx_kp_u__10) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_kp_u__10); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 159, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "fontTools/feaLib/lexer.py":160 - * self.pos_ += 1 - * self.scan_until_('"') - * if self.pos_ < self.text_length_ and self.text_[self.pos_] == '"': # <<<<<<<<<<<<<< - * self.pos_ += 1 - * # strip newlines embedded within a string - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 160, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_text_length); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 160, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_4, __pyx_t_2, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 160, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_9 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 160, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_9) { - } else { - __pyx_t_6 = __pyx_t_9; - goto __pyx_L38_bool_binop_done; - } - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_text_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 160, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 160, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetItem(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 160, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_9 = (__Pyx_PyUnicode_Equals(__pyx_t_4, __pyx_kp_u__10, Py_EQ)); if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 160, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_6 = __pyx_t_9; - __pyx_L38_bool_binop_done:; - if (likely(__pyx_t_6)) { - - /* "fontTools/feaLib/lexer.py":161 - * self.scan_until_('"') - * if self.pos_ < self.text_length_ and self.text_[self.pos_] == '"': - * self.pos_ += 1 # <<<<<<<<<<<<<< - * # strip newlines embedded within a string - * string = re.sub("[\r\n]", "", text[start + 1 : self.pos_ - 1]) - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 161, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_PyInt_AddObjC(__pyx_t_4, __pyx_int_1, 1, 1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 161, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_pos, __pyx_t_2) < 0) __PYX_ERR(0, 161, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":163 - * self.pos_ += 1 - * # strip newlines embedded within a string - * string = re.sub("[\r\n]", "", text[start + 1 : self.pos_ - 1]) # <<<<<<<<<<<<<< - * return (Lexer.STRING, string, location) - * else: - */ - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_re); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_sub); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyInt_AddObjC(__pyx_v_start, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_10 = __Pyx_PyInt_SubtractObjC(__pyx_t_1, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetSlice(__pyx_v_text, 0, 0, &__pyx_t_4, &__pyx_t_10, NULL, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_10 = NULL; - __pyx_t_8 = 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_8 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[4] = {__pyx_t_10, __pyx_kp_u__11, __pyx_kp_u__12, __pyx_t_1}; - __pyx_t_2 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_8, 3+__pyx_t_8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_GOTREF(__pyx_t_2); - __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[4] = {__pyx_t_10, __pyx_kp_u__11, __pyx_kp_u__12, __pyx_t_1}; - __pyx_t_2 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_8, 3+__pyx_t_8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else - #endif - { - __pyx_t_4 = PyTuple_New(3+__pyx_t_8); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (__pyx_t_10) { - __Pyx_GIVEREF(__pyx_t_10); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_10); __pyx_t_10 = NULL; - } - __Pyx_INCREF(__pyx_kp_u__11); - __Pyx_GIVEREF(__pyx_kp_u__11); - PyTuple_SET_ITEM(__pyx_t_4, 0+__pyx_t_8, __pyx_kp_u__11); - __Pyx_INCREF(__pyx_kp_u__12); - __Pyx_GIVEREF(__pyx_kp_u__12); - PyTuple_SET_ITEM(__pyx_t_4, 1+__pyx_t_8, __pyx_kp_u__12); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_4, 2+__pyx_t_8, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_string = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":164 - * # strip newlines embedded within a string - * string = re.sub("[\r\n]", "", text[start + 1 : self.pos_ - 1]) - * return (Lexer.STRING, string, location) # <<<<<<<<<<<<<< - * else: - * raise FeatureLibError("Expected '\"' to terminate string", location) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 164, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_STRING); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 164, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 164, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); - __Pyx_INCREF(__pyx_v_string); - __Pyx_GIVEREF(__pyx_v_string); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_string); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_v_location); - __pyx_t_3 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":160 - * self.pos_ += 1 - * self.scan_until_('"') - * if self.pos_ < self.text_length_ and self.text_[self.pos_] == '"': # <<<<<<<<<<<<<< - * self.pos_ += 1 - * # strip newlines embedded within a string - */ - } - - /* "fontTools/feaLib/lexer.py":166 - * return (Lexer.STRING, string, location) - * else: - * raise FeatureLibError("Expected '\"' to terminate string", location) # <<<<<<<<<<<<<< - * raise FeatureLibError("Unexpected character: %r" % cur_char, location) - * - */ - /*else*/ { - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_FeatureLibError); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 166, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = NULL; - __pyx_t_8 = 0; - 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_8 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_4, __pyx_kp_u_Expected_to_terminate_string, __pyx_v_location}; - __pyx_t_2 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 166, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 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_4, __pyx_kp_u_Expected_to_terminate_string, __pyx_v_location}; - __pyx_t_2 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 166, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_2); - } else - #endif - { - __pyx_t_1 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 166, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (__pyx_t_4) { - __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_4); __pyx_t_4 = NULL; - } - __Pyx_INCREF(__pyx_kp_u_Expected_to_terminate_string); - __Pyx_GIVEREF(__pyx_kp_u_Expected_to_terminate_string); - PyTuple_SET_ITEM(__pyx_t_1, 0+__pyx_t_8, __pyx_kp_u_Expected_to_terminate_string); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_1, 1+__pyx_t_8, __pyx_v_location); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 166, __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_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __PYX_ERR(0, 166, __pyx_L1_error) - } - - /* "fontTools/feaLib/lexer.py":157 - * self.pos_ += 1 - * return (Lexer.SYMBOL, cur_char, location) - * if cur_char == '"': # <<<<<<<<<<<<<< - * self.pos_ += 1 - * self.scan_until_('"') - */ - } - - /* "fontTools/feaLib/lexer.py":167 - * else: - * raise FeatureLibError("Expected '\"' to terminate string", location) - * raise FeatureLibError("Unexpected character: %r" % cur_char, location) # <<<<<<<<<<<<<< - * - * def scan_over_(self, valid): - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_FeatureLibError); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = __Pyx_PyUnicode_FormatSafe(__pyx_kp_u_Unexpected_character_r, __pyx_v_cur_char); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = NULL; - __pyx_t_8 = 0; - 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_8 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_4, __pyx_t_1, __pyx_v_location}; - __pyx_t_2 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_2); - __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[3] = {__pyx_t_4, __pyx_t_1, __pyx_v_location}; - __pyx_t_2 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else - #endif - { - __pyx_t_10 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - if (__pyx_t_4) { - __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_4); __pyx_t_4 = NULL; - } - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_10, 0+__pyx_t_8, __pyx_t_1); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_10, 1+__pyx_t_8, __pyx_v_location); - __pyx_t_1 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_10, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 167, __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; - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __PYX_ERR(0, 167, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":68 - * return FeatureLibLocation(self.filename_ or "", self.line_, column) - * - * def next_(self): # <<<<<<<<<<<<<< - * self.scan_over_(Lexer.CHAR_WHITESPACE_) - * location = self.location_() - */ - - /* 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_10); - __Pyx_AddTraceback("fontTools.feaLib.lexer.Lexer.next_", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_location); - __Pyx_XDECREF(__pyx_v_start); - __Pyx_XDECREF(__pyx_v_text); - __Pyx_XDECREF(__pyx_v_cur_char); - __Pyx_XDECREF(__pyx_v_next_char); - __Pyx_XDECREF(__pyx_v_glyphclass); - __Pyx_XDECREF(__pyx_v_token); - __Pyx_XDECREF(__pyx_v_string); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/feaLib/lexer.py":169 - * raise FeatureLibError("Unexpected character: %r" % cur_char, location) - * - * def scan_over_(self, valid): # <<<<<<<<<<<<<< - * p = self.pos_ - * while p < self.text_length_ and self.text_[p] in valid: - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_13scan_over_(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_6feaLib_5lexer_5Lexer_12scan_over_[] = "Lexer.scan_over_(self, valid)"; -static PyMethodDef __pyx_mdef_9fontTools_6feaLib_5lexer_5Lexer_13scan_over_ = {"scan_over_", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_13scan_over_, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_6feaLib_5lexer_5Lexer_12scan_over_}; -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_13scan_over_(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_self = 0; - PyObject *__pyx_v_valid = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("scan_over_ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_self,&__pyx_n_s_valid,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_self)) != 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_valid)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("scan_over_", 1, 2, 2, 1); __PYX_ERR(0, 169, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "scan_over_") < 0)) __PYX_ERR(0, 169, __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_self = values[0]; - __pyx_v_valid = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("scan_over_", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 169, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.feaLib.lexer.Lexer.scan_over_", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_12scan_over_(__pyx_self, __pyx_v_self, __pyx_v_valid); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_12scan_over_(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self, PyObject *__pyx_v_valid) { - PyObject *__pyx_v_p = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("scan_over_", 0); - - /* "fontTools/feaLib/lexer.py":170 - * - * def scan_over_(self, valid): - * p = self.pos_ # <<<<<<<<<<<<<< - * while p < self.text_length_ and self.text_[p] in valid: - * p += 1 - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 170, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_p = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":171 - * def scan_over_(self, valid): - * p = self.pos_ - * while p < self.text_length_ and self.text_[p] in valid: # <<<<<<<<<<<<<< - * p += 1 - * self.pos_ = p - */ - while (1) { - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_text_length); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 171, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_p, __pyx_t_1, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 171, __pyx_L1_error) - __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, 171, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_4) { - } else { - __pyx_t_2 = __pyx_t_4; - goto __pyx_L5_bool_binop_done; - } - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_text_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 171, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = __Pyx_PyObject_GetItem(__pyx_t_3, __pyx_v_p); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 171, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = (__Pyx_PySequence_ContainsTF(__pyx_t_1, __pyx_v_valid, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 171, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_5 = (__pyx_t_4 != 0); - __pyx_t_2 = __pyx_t_5; - __pyx_L5_bool_binop_done:; - if (!__pyx_t_2) break; - - /* "fontTools/feaLib/lexer.py":172 - * p = self.pos_ - * while p < self.text_length_ and self.text_[p] in valid: - * p += 1 # <<<<<<<<<<<<<< - * self.pos_ = p - * - */ - __pyx_t_1 = __Pyx_PyInt_AddObjC(__pyx_v_p, __pyx_int_1, 1, 1, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 172, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF_SET(__pyx_v_p, __pyx_t_1); - __pyx_t_1 = 0; - } - - /* "fontTools/feaLib/lexer.py":173 - * while p < self.text_length_ and self.text_[p] in valid: - * p += 1 - * self.pos_ = p # <<<<<<<<<<<<<< - * - * def scan_until_(self, stop_at): - */ - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_pos, __pyx_v_p) < 0) __PYX_ERR(0, 173, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":169 - * raise FeatureLibError("Unexpected character: %r" % cur_char, location) - * - * def scan_over_(self, valid): # <<<<<<<<<<<<<< - * p = self.pos_ - * while p < self.text_length_ and self.text_[p] in valid: - */ - - /* 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_3); - __Pyx_AddTraceback("fontTools.feaLib.lexer.Lexer.scan_over_", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_p); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/feaLib/lexer.py":175 - * self.pos_ = p - * - * def scan_until_(self, stop_at): # <<<<<<<<<<<<<< - * p = self.pos_ - * while p < self.text_length_ and self.text_[p] not in stop_at: - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_15scan_until_(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_6feaLib_5lexer_5Lexer_14scan_until_[] = "Lexer.scan_until_(self, stop_at)"; -static PyMethodDef __pyx_mdef_9fontTools_6feaLib_5lexer_5Lexer_15scan_until_ = {"scan_until_", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_15scan_until_, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_6feaLib_5lexer_5Lexer_14scan_until_}; -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_15scan_until_(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_self = 0; - PyObject *__pyx_v_stop_at = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("scan_until_ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_self,&__pyx_n_s_stop_at,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_self)) != 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_stop_at)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("scan_until_", 1, 2, 2, 1); __PYX_ERR(0, 175, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "scan_until_") < 0)) __PYX_ERR(0, 175, __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_self = values[0]; - __pyx_v_stop_at = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("scan_until_", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 175, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.feaLib.lexer.Lexer.scan_until_", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_14scan_until_(__pyx_self, __pyx_v_self, __pyx_v_stop_at); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_14scan_until_(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self, PyObject *__pyx_v_stop_at) { - PyObject *__pyx_v_p = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("scan_until_", 0); - - /* "fontTools/feaLib/lexer.py":176 - * - * def scan_until_(self, stop_at): - * p = self.pos_ # <<<<<<<<<<<<<< - * while p < self.text_length_ and self.text_[p] not in stop_at: - * p += 1 - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 176, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_p = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":177 - * def scan_until_(self, stop_at): - * p = self.pos_ - * while p < self.text_length_ and self.text_[p] not in stop_at: # <<<<<<<<<<<<<< - * p += 1 - * self.pos_ = p - */ - while (1) { - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_text_length); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 177, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_p, __pyx_t_1, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 177, __pyx_L1_error) - __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, 177, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_4) { - } else { - __pyx_t_2 = __pyx_t_4; - goto __pyx_L5_bool_binop_done; - } - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_text_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 177, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = __Pyx_PyObject_GetItem(__pyx_t_3, __pyx_v_p); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 177, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = (__Pyx_PySequence_ContainsTF(__pyx_t_1, __pyx_v_stop_at, Py_NE)); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 177, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_5 = (__pyx_t_4 != 0); - __pyx_t_2 = __pyx_t_5; - __pyx_L5_bool_binop_done:; - if (!__pyx_t_2) break; - - /* "fontTools/feaLib/lexer.py":178 - * p = self.pos_ - * while p < self.text_length_ and self.text_[p] not in stop_at: - * p += 1 # <<<<<<<<<<<<<< - * self.pos_ = p - * - */ - __pyx_t_1 = __Pyx_PyInt_AddObjC(__pyx_v_p, __pyx_int_1, 1, 1, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 178, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF_SET(__pyx_v_p, __pyx_t_1); - __pyx_t_1 = 0; - } - - /* "fontTools/feaLib/lexer.py":179 - * while p < self.text_length_ and self.text_[p] not in stop_at: - * p += 1 - * self.pos_ = p # <<<<<<<<<<<<<< - * - * def scan_anonymous_block(self, tag): - */ - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_pos, __pyx_v_p) < 0) __PYX_ERR(0, 179, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":175 - * self.pos_ = p - * - * def scan_until_(self, stop_at): # <<<<<<<<<<<<<< - * p = self.pos_ - * while p < self.text_length_ and self.text_[p] not in stop_at: - */ - - /* 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_3); - __Pyx_AddTraceback("fontTools.feaLib.lexer.Lexer.scan_until_", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_p); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/feaLib/lexer.py":181 - * self.pos_ = p - * - * def scan_anonymous_block(self, tag): # <<<<<<<<<<<<<< - * location = self.location_() - * tag = tag.strip() - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_17scan_anonymous_block(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_6feaLib_5lexer_5Lexer_16scan_anonymous_block[] = "Lexer.scan_anonymous_block(self, tag)"; -static PyMethodDef __pyx_mdef_9fontTools_6feaLib_5lexer_5Lexer_17scan_anonymous_block = {"scan_anonymous_block", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_17scan_anonymous_block, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_6feaLib_5lexer_5Lexer_16scan_anonymous_block}; -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_5Lexer_17scan_anonymous_block(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_self = 0; - PyObject *__pyx_v_tag = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("scan_anonymous_block (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_self,&__pyx_n_s_tag,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_self)) != 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_tag)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("scan_anonymous_block", 1, 2, 2, 1); __PYX_ERR(0, 181, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "scan_anonymous_block") < 0)) __PYX_ERR(0, 181, __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_self = values[0]; - __pyx_v_tag = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("scan_anonymous_block", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 181, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.feaLib.lexer.Lexer.scan_anonymous_block", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_16scan_anonymous_block(__pyx_self, __pyx_v_self, __pyx_v_tag); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_5Lexer_16scan_anonymous_block(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self, PyObject *__pyx_v_tag) { - PyObject *__pyx_v_location = NULL; - PyObject *__pyx_v_regexp = NULL; - PyObject *__pyx_v_split = 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; - Py_ssize_t __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("scan_anonymous_block", 0); - __Pyx_INCREF(__pyx_v_tag); - - /* "fontTools/feaLib/lexer.py":182 - * - * def scan_anonymous_block(self, tag): - * location = self.location_() # <<<<<<<<<<<<<< - * tag = tag.strip() - * self.scan_until_(Lexer.CHAR_NEWLINE_) - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_location); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 182, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_CallOneArg(__pyx_t_2, __pyx_t_3) : __Pyx_PyObject_CallNoArg(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 182, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_location = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":183 - * def scan_anonymous_block(self, tag): - * location = self.location_() - * tag = tag.strip() # <<<<<<<<<<<<<< - * self.scan_until_(Lexer.CHAR_NEWLINE_) - * self.scan_over_(Lexer.CHAR_NEWLINE_) - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_tag, __pyx_n_s_strip); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 183, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_CallOneArg(__pyx_t_2, __pyx_t_3) : __Pyx_PyObject_CallNoArg(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 183, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF_SET(__pyx_v_tag, __pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":184 - * location = self.location_() - * tag = tag.strip() - * self.scan_until_(Lexer.CHAR_NEWLINE_) # <<<<<<<<<<<<<< - * self.scan_over_(Lexer.CHAR_NEWLINE_) - * regexp = r"}\s*" + tag + r"\s*;" - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_scan_until); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 184, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 184, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_CHAR_NEWLINE); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 184, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 184, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":185 - * tag = tag.strip() - * self.scan_until_(Lexer.CHAR_NEWLINE_) - * self.scan_over_(Lexer.CHAR_NEWLINE_) # <<<<<<<<<<<<<< - * regexp = r"}\s*" + tag + r"\s*;" - * split = re.split(regexp, self.text_[self.pos_ :], maxsplit=1) - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_scan_over); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 185, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 185, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_CHAR_NEWLINE); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 185, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_4, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 185, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":186 - * self.scan_until_(Lexer.CHAR_NEWLINE_) - * self.scan_over_(Lexer.CHAR_NEWLINE_) - * regexp = r"}\s*" + tag + r"\s*;" # <<<<<<<<<<<<<< - * split = re.split(regexp, self.text_[self.pos_ :], maxsplit=1) - * if len(split) != 2: - */ - __pyx_t_1 = PyNumber_Add(__pyx_kp_u_s, __pyx_v_tag); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 186, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Add(__pyx_t_1, __pyx_kp_u_s_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 186, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_regexp = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":187 - * self.scan_over_(Lexer.CHAR_NEWLINE_) - * regexp = r"}\s*" + tag + r"\s*;" - * split = re.split(regexp, self.text_[self.pos_ :], maxsplit=1) # <<<<<<<<<<<<<< - * if len(split) != 2: - * raise FeatureLibError( - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_re); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 187, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_split); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 187, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_text_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 187, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 187, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetSlice(__pyx_t_2, 0, 0, &__pyx_t_3, NULL, NULL, 0, 0, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 187, __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 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 187, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_regexp); - __Pyx_GIVEREF(__pyx_v_regexp); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_regexp); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 187, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_maxsplit, __pyx_int_1) < 0) __PYX_ERR(0, 187, __pyx_L1_error) - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 187, __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_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_v_split = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":188 - * regexp = r"}\s*" + tag + r"\s*;" - * split = re.split(regexp, self.text_[self.pos_ :], maxsplit=1) - * if len(split) != 2: # <<<<<<<<<<<<<< - * raise FeatureLibError( - * "Expected '} %s;' to terminate anonymous block" % tag, location - */ - __pyx_t_5 = PyObject_Length(__pyx_v_split); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 188, __pyx_L1_error) - __pyx_t_6 = ((__pyx_t_5 != 2) != 0); - if (unlikely(__pyx_t_6)) { - - /* "fontTools/feaLib/lexer.py":189 - * split = re.split(regexp, self.text_[self.pos_ :], maxsplit=1) - * if len(split) != 2: - * raise FeatureLibError( # <<<<<<<<<<<<<< - * "Expected '} %s;' to terminate anonymous block" % tag, location - * ) - */ - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_FeatureLibError); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 189, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - - /* "fontTools/feaLib/lexer.py":190 - * if len(split) != 2: - * raise FeatureLibError( - * "Expected '} %s;' to terminate anonymous block" % tag, location # <<<<<<<<<<<<<< - * ) - * self.pos_ += len(split[0]) - */ - __pyx_t_3 = __Pyx_PyUnicode_FormatSafe(__pyx_kp_u_Expected_s_to_terminate_anonymou, __pyx_v_tag); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 190, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = NULL; - __pyx_t_7 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_1)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - __pyx_t_7 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[3] = {__pyx_t_1, __pyx_t_3, __pyx_v_location}; - __pyx_t_2 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 189, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[3] = {__pyx_t_1, __pyx_t_3, __pyx_v_location}; - __pyx_t_2 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 189, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else - #endif - { - __pyx_t_8 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 189, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - if (__pyx_t_1) { - __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_1); __pyx_t_1 = NULL; - } - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_3); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_v_location); - __pyx_t_3 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_8, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 189, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __PYX_ERR(0, 189, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":188 - * regexp = r"}\s*" + tag + r"\s*;" - * split = re.split(regexp, self.text_[self.pos_ :], maxsplit=1) - * if len(split) != 2: # <<<<<<<<<<<<<< - * raise FeatureLibError( - * "Expected '} %s;' to terminate anonymous block" % tag, location - */ - } - - /* "fontTools/feaLib/lexer.py":192 - * "Expected '} %s;' to terminate anonymous block" % tag, location - * ) - * self.pos_ += len(split[0]) # <<<<<<<<<<<<<< - * return (Lexer.ANONYMOUS_BLOCK, split[0], location) - * - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_pos); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 192, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_split, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 192, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyObject_Length(__pyx_t_4); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 192, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyInt_FromSsize_t(__pyx_t_5); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 192, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_InPlaceAdd(__pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 192, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_pos, __pyx_t_8) < 0) __PYX_ERR(0, 192, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - - /* "fontTools/feaLib/lexer.py":193 - * ) - * self.pos_ += len(split[0]) - * return (Lexer.ANONYMOUS_BLOCK, split[0], location) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 193, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_ANONYMOUS_BLOCK); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 193, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = __Pyx_GetItemInt(__pyx_v_split, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 193, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 193, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_8); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_8); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_v_location); - __pyx_t_4 = 0; - __pyx_t_8 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":181 - * self.pos_ = p - * - * def scan_anonymous_block(self, tag): # <<<<<<<<<<<<<< - * location = self.location_() - * tag = tag.strip() - */ - - /* 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_8); - __Pyx_AddTraceback("fontTools.feaLib.lexer.Lexer.scan_anonymous_block", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_location); - __Pyx_XDECREF(__pyx_v_regexp); - __Pyx_XDECREF(__pyx_v_split); - __Pyx_XDECREF(__pyx_v_tag); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/feaLib/lexer.py":211 - * """ - * - * def __init__(self, featurefile, *, includeDir=None): # <<<<<<<<<<<<<< - * """Initializes an IncludingLexer. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_14IncludingLexer_1__init__(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_6feaLib_5lexer_14IncludingLexer___init__[] = "IncludingLexer.__init__(self, featurefile, *, includeDir=None)\nInitializes an IncludingLexer.\n\n Behavior:\n If includeDir is passed, it will be used to determine the top-level\n include directory to use for all encountered include statements. If it is\n not passed, ``os.path.dirname(featurefile)`` will be considered the\n include directory.\n "; -static PyMethodDef __pyx_mdef_9fontTools_6feaLib_5lexer_14IncludingLexer_1__init__ = {"__init__", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_6feaLib_5lexer_14IncludingLexer_1__init__, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_6feaLib_5lexer_14IncludingLexer___init__}; -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_14IncludingLexer_1__init__(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_self = 0; - PyObject *__pyx_v_featurefile = 0; - PyObject *__pyx_v_includeDir = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_self,&__pyx_n_s_featurefile,&__pyx_n_s_includeDir,0}; - PyObject* values[3] = {0,0,0}; - values[2] = ((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 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_self)) != 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_featurefile)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 2, 2, 1); __PYX_ERR(0, 211, __pyx_L3_error) - } - } - if (kw_args == 1) { - const Py_ssize_t index = 2; - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, *__pyx_pyargnames[index]); - if (value) { values[index] = value; kw_args--; } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) __PYX_ERR(0, 211, __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_self = values[0]; - __pyx_v_featurefile = values[1]; - __pyx_v_includeDir = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 211, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.feaLib.lexer.IncludingLexer.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_6feaLib_5lexer_14IncludingLexer___init__(__pyx_self, __pyx_v_self, __pyx_v_featurefile, __pyx_v_includeDir); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_14IncludingLexer___init__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self, PyObject *__pyx_v_featurefile, PyObject *__pyx_v_includeDir) { - 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("__init__", 0); - - /* "fontTools/feaLib/lexer.py":221 - * """ - * - * self.lexers_ = [self.make_lexer_(featurefile)] # <<<<<<<<<<<<<< - * self.featurefilepath = self.lexers_[0].filename_ - * self.includeDir = includeDir - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_make_lexer); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 221, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_featurefile) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v_featurefile); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 221, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 221, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_1); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); - __pyx_t_1 = 0; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_lexers, __pyx_t_2) < 0) __PYX_ERR(0, 221, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":222 - * - * self.lexers_ = [self.make_lexer_(featurefile)] - * self.featurefilepath = self.lexers_[0].filename_ # <<<<<<<<<<<<<< - * self.includeDir = includeDir - * - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_lexers); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 222, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_2, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 222, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_filename_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 222, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_featurefilepath, __pyx_t_2) < 0) __PYX_ERR(0, 222, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":223 - * self.lexers_ = [self.make_lexer_(featurefile)] - * self.featurefilepath = self.lexers_[0].filename_ - * self.includeDir = includeDir # <<<<<<<<<<<<<< - * - * def __iter__(self): - */ - if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_n_s_includeDir, __pyx_v_includeDir) < 0) __PYX_ERR(0, 223, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":211 - * """ - * - * def __init__(self, featurefile, *, includeDir=None): # <<<<<<<<<<<<<< - * """Initializes an IncludingLexer. - * - */ - - /* 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_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("fontTools.feaLib.lexer.IncludingLexer.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/feaLib/lexer.py":225 - * self.includeDir = includeDir - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return self - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_14IncludingLexer_3__iter__(PyObject *__pyx_self, PyObject *__pyx_v_self); /*proto*/ -static char __pyx_doc_9fontTools_6feaLib_5lexer_14IncludingLexer_2__iter__[] = "IncludingLexer.__iter__(self)"; -static PyMethodDef __pyx_mdef_9fontTools_6feaLib_5lexer_14IncludingLexer_3__iter__ = {"__iter__", (PyCFunction)__pyx_pw_9fontTools_6feaLib_5lexer_14IncludingLexer_3__iter__, METH_O, __pyx_doc_9fontTools_6feaLib_5lexer_14IncludingLexer_2__iter__}; -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_14IncludingLexer_3__iter__(PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__iter__ (wrapper)", 0); - __pyx_r = __pyx_pf_9fontTools_6feaLib_5lexer_14IncludingLexer_2__iter__(__pyx_self, ((PyObject *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_14IncludingLexer_2__iter__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__iter__", 0); - - /* "fontTools/feaLib/lexer.py":226 - * - * def __iter__(self): - * return self # <<<<<<<<<<<<<< - * - * def next(self): # Python 2 - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self); - __pyx_r = __pyx_v_self; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":225 - * self.includeDir = includeDir - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return self - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/feaLib/lexer.py":228 - * return self - * - * def next(self): # Python 2 # <<<<<<<<<<<<<< - * return self.__next__() - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_14IncludingLexer_5next(PyObject *__pyx_self, PyObject *__pyx_v_self); /*proto*/ -static char __pyx_doc_9fontTools_6feaLib_5lexer_14IncludingLexer_4next[] = "IncludingLexer.next(self)"; -static PyMethodDef __pyx_mdef_9fontTools_6feaLib_5lexer_14IncludingLexer_5next = {"next", (PyCFunction)__pyx_pw_9fontTools_6feaLib_5lexer_14IncludingLexer_5next, METH_O, __pyx_doc_9fontTools_6feaLib_5lexer_14IncludingLexer_4next}; -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_14IncludingLexer_5next(PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("next (wrapper)", 0); - __pyx_r = __pyx_pf_9fontTools_6feaLib_5lexer_14IncludingLexer_4next(__pyx_self, ((PyObject *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_14IncludingLexer_4next(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("next", 0); - - /* "fontTools/feaLib/lexer.py":229 - * - * def next(self): # Python 2 - * return self.__next__() # <<<<<<<<<<<<<< - * - * def __next__(self): # Python 3 - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_next); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 229, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_CallOneArg(__pyx_t_2, __pyx_t_3) : __Pyx_PyObject_CallNoArg(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 229, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":228 - * return self - * - * def next(self): # Python 2 # <<<<<<<<<<<<<< - * return self.__next__() - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("fontTools.feaLib.lexer.IncludingLexer.next", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/feaLib/lexer.py":231 - * return self.__next__() - * - * def __next__(self): # Python 3 # <<<<<<<<<<<<<< - * while self.lexers_: - * lexer = self.lexers_[-1] - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_14IncludingLexer_7__next__(PyObject *__pyx_self, PyObject *__pyx_v_self); /*proto*/ -static char __pyx_doc_9fontTools_6feaLib_5lexer_14IncludingLexer_6__next__[] = "IncludingLexer.__next__(self)"; -static PyMethodDef __pyx_mdef_9fontTools_6feaLib_5lexer_14IncludingLexer_7__next__ = {"__next__", (PyCFunction)__pyx_pw_9fontTools_6feaLib_5lexer_14IncludingLexer_7__next__, METH_O, __pyx_doc_9fontTools_6feaLib_5lexer_14IncludingLexer_6__next__}; -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_14IncludingLexer_7__next__(PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__next__ (wrapper)", 0); - __pyx_r = __pyx_pf_9fontTools_6feaLib_5lexer_14IncludingLexer_6__next__(__pyx_self, ((PyObject *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_14IncludingLexer_6__next__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_v_lexer = NULL; - PyObject *__pyx_v_token_type = NULL; - PyObject *__pyx_v_token = NULL; - PyObject *__pyx_v_location = NULL; - PyObject *__pyx_v_fname_type = NULL; - PyObject *__pyx_v_fname_token = NULL; - PyObject *__pyx_v_fname_location = NULL; - PyObject *__pyx_v_path = NULL; - PyObject *__pyx_v_curpath = NULL; - PyObject *__pyx_v_err = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - PyObject *(*__pyx_t_10)(PyObject *); - int __pyx_t_11; - int __pyx_t_12; - int __pyx_t_13; - Py_ssize_t __pyx_t_14; - int __pyx_t_15; - PyObject *__pyx_t_16 = NULL; - PyObject *__pyx_t_17 = NULL; - int __pyx_t_18; - char const *__pyx_t_19; - PyObject *__pyx_t_20 = NULL; - PyObject *__pyx_t_21 = NULL; - PyObject *__pyx_t_22 = NULL; - PyObject *__pyx_t_23 = NULL; - PyObject *__pyx_t_24 = NULL; - PyObject *__pyx_t_25 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__next__", 0); - - /* "fontTools/feaLib/lexer.py":232 - * - * def __next__(self): # Python 3 - * while self.lexers_: # <<<<<<<<<<<<<< - * lexer = self.lexers_[-1] - * try: - */ - while (1) { - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_lexers); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 232, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 232, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!__pyx_t_2) break; - - /* "fontTools/feaLib/lexer.py":233 - * def __next__(self): # Python 3 - * while self.lexers_: - * lexer = self.lexers_[-1] # <<<<<<<<<<<<<< - * try: - * token_type, token, location = next(lexer) - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_lexers); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 233, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_1, -1L, long, 1, __Pyx_PyInt_From_long, 0, 1, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 233, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF_SET(__pyx_v_lexer, __pyx_t_3); - __pyx_t_3 = 0; - - /* "fontTools/feaLib/lexer.py":234 - * while self.lexers_: - * lexer = self.lexers_[-1] - * try: # <<<<<<<<<<<<<< - * token_type, token, location = next(lexer) - * except StopIteration: - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_4, &__pyx_t_5, &__pyx_t_6); - __Pyx_XGOTREF(__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_5); - __Pyx_XGOTREF(__pyx_t_6); - /*try:*/ { - - /* "fontTools/feaLib/lexer.py":235 - * lexer = self.lexers_[-1] - * try: - * token_type, token, location = next(lexer) # <<<<<<<<<<<<<< - * except StopIteration: - * self.lexers_.pop() - */ - __pyx_t_3 = __Pyx_PyIter_Next(__pyx_v_lexer); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 235, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - 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 != 3)) { - if (size > 3) __Pyx_RaiseTooManyValuesError(3); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 235, __pyx_L5_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_7 = PyTuple_GET_ITEM(sequence, 1); - __pyx_t_8 = PyTuple_GET_ITEM(sequence, 2); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_7 = PyList_GET_ITEM(sequence, 1); - __pyx_t_8 = PyList_GET_ITEM(sequence, 2); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(__pyx_t_8); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 235, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_7 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 235, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_8 = PySequence_ITEM(sequence, 2); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 235, __pyx_L5_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, 235, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_10 = Py_TYPE(__pyx_t_9)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_10(__pyx_t_9); if (unlikely(!__pyx_t_1)) goto __pyx_L13_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_7 = __pyx_t_10(__pyx_t_9); if (unlikely(!__pyx_t_7)) goto __pyx_L13_unpacking_failed; - __Pyx_GOTREF(__pyx_t_7); - index = 2; __pyx_t_8 = __pyx_t_10(__pyx_t_9); if (unlikely(!__pyx_t_8)) goto __pyx_L13_unpacking_failed; - __Pyx_GOTREF(__pyx_t_8); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_10(__pyx_t_9), 3) < 0) __PYX_ERR(0, 235, __pyx_L5_error) - __pyx_t_10 = 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_10 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 235, __pyx_L5_error) - __pyx_L14_unpacking_done:; - } - __Pyx_XDECREF_SET(__pyx_v_token_type, __pyx_t_1); - __pyx_t_1 = 0; - __Pyx_XDECREF_SET(__pyx_v_token, __pyx_t_7); - __pyx_t_7 = 0; - __Pyx_XDECREF_SET(__pyx_v_location, __pyx_t_8); - __pyx_t_8 = 0; - - /* "fontTools/feaLib/lexer.py":234 - * while self.lexers_: - * lexer = self.lexers_[-1] - * try: # <<<<<<<<<<<<<< - * token_type, token, location = next(lexer) - * except StopIteration: - */ - } - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - goto __pyx_L12_try_end; - __pyx_L5_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":236 - * try: - * token_type, token, location = next(lexer) - * except StopIteration: # <<<<<<<<<<<<<< - * self.lexers_.pop() - * continue - */ - __pyx_t_11 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_StopIteration); - if (__pyx_t_11) { - __Pyx_AddTraceback("fontTools.feaLib.lexer.IncludingLexer.__next__", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_3, &__pyx_t_8, &__pyx_t_7) < 0) __PYX_ERR(0, 236, __pyx_L7_except_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GOTREF(__pyx_t_8); - __Pyx_GOTREF(__pyx_t_7); - - /* "fontTools/feaLib/lexer.py":237 - * token_type, token, location = next(lexer) - * except StopIteration: - * self.lexers_.pop() # <<<<<<<<<<<<<< - * continue - * if token_type is Lexer.NAME and token == "include": - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_lexers); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 237, __pyx_L7_except_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_9 = __Pyx_PyObject_Pop(__pyx_t_1); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 237, __pyx_L7_except_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":238 - * except StopIteration: - * self.lexers_.pop() - * continue # <<<<<<<<<<<<<< - * if token_type is Lexer.NAME and token == "include": - * fname_type, fname_token, fname_location = lexer.next() - */ - goto __pyx_L16_except_continue; - __pyx_L16_except_continue:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - goto __pyx_L11_try_continue; - } - goto __pyx_L7_except_error; - __pyx_L7_except_error:; - - /* "fontTools/feaLib/lexer.py":234 - * while self.lexers_: - * lexer = self.lexers_[-1] - * try: # <<<<<<<<<<<<<< - * token_type, token, location = next(lexer) - * except StopIteration: - */ - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_XGIVEREF(__pyx_t_5); - __Pyx_XGIVEREF(__pyx_t_6); - __Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6); - goto __pyx_L1_error; - __pyx_L11_try_continue:; - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_XGIVEREF(__pyx_t_5); - __Pyx_XGIVEREF(__pyx_t_6); - __Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6); - goto __pyx_L3_continue; - __pyx_L12_try_end:; - } - - /* "fontTools/feaLib/lexer.py":239 - * self.lexers_.pop() - * continue - * if token_type is Lexer.NAME and token == "include": # <<<<<<<<<<<<<< - * fname_type, fname_token, fname_location = lexer.next() - * if fname_type is not Lexer.FILENAME: - */ - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 239, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_NAME); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 239, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_12 = (__pyx_v_token_type == __pyx_t_8); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_13 = (__pyx_t_12 != 0); - if (__pyx_t_13) { - } else { - __pyx_t_2 = __pyx_t_13; - goto __pyx_L18_bool_binop_done; - } - __pyx_t_13 = (__Pyx_PyUnicode_Equals(__pyx_v_token, __pyx_n_u_include, Py_EQ)); if (unlikely(__pyx_t_13 < 0)) __PYX_ERR(0, 239, __pyx_L1_error) - __pyx_t_2 = __pyx_t_13; - __pyx_L18_bool_binop_done:; - if (__pyx_t_2) { - - /* "fontTools/feaLib/lexer.py":240 - * continue - * if token_type is Lexer.NAME and token == "include": - * fname_type, fname_token, fname_location = lexer.next() # <<<<<<<<<<<<<< - * if fname_type is not Lexer.FILENAME: - * raise FeatureLibError("Expected file name", fname_location) - */ - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_lexer, __pyx_n_s_next_3); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 240, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_8 = (__pyx_t_3) ? __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_3) : __Pyx_PyObject_CallNoArg(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 240, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 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, 240, __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_3 = PyTuple_GET_ITEM(sequence, 1); - __pyx_t_9 = PyTuple_GET_ITEM(sequence, 2); - } else { - __pyx_t_7 = PyList_GET_ITEM(sequence, 0); - __pyx_t_3 = PyList_GET_ITEM(sequence, 1); - __pyx_t_9 = PyList_GET_ITEM(sequence, 2); - } - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_9); - #else - __pyx_t_7 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 240, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 240, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_9 = PySequence_ITEM(sequence, 2); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 240, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - #endif - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_1 = PyObject_GetIter(__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 240, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_10 = Py_TYPE(__pyx_t_1)->tp_iternext; - index = 0; __pyx_t_7 = __pyx_t_10(__pyx_t_1); if (unlikely(!__pyx_t_7)) goto __pyx_L20_unpacking_failed; - __Pyx_GOTREF(__pyx_t_7); - index = 1; __pyx_t_3 = __pyx_t_10(__pyx_t_1); if (unlikely(!__pyx_t_3)) goto __pyx_L20_unpacking_failed; - __Pyx_GOTREF(__pyx_t_3); - index = 2; __pyx_t_9 = __pyx_t_10(__pyx_t_1); if (unlikely(!__pyx_t_9)) goto __pyx_L20_unpacking_failed; - __Pyx_GOTREF(__pyx_t_9); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_10(__pyx_t_1), 3) < 0) __PYX_ERR(0, 240, __pyx_L1_error) - __pyx_t_10 = NULL; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L21_unpacking_done; - __pyx_L20_unpacking_failed:; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_10 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 240, __pyx_L1_error) - __pyx_L21_unpacking_done:; - } - __Pyx_XDECREF_SET(__pyx_v_fname_type, __pyx_t_7); - __pyx_t_7 = 0; - __Pyx_XDECREF_SET(__pyx_v_fname_token, __pyx_t_3); - __pyx_t_3 = 0; - __Pyx_XDECREF_SET(__pyx_v_fname_location, __pyx_t_9); - __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":241 - * if token_type is Lexer.NAME and token == "include": - * fname_type, fname_token, fname_location = lexer.next() - * if fname_type is not Lexer.FILENAME: # <<<<<<<<<<<<<< - * raise FeatureLibError("Expected file name", fname_location) - * # semi_type, semi_token, semi_location = lexer.next() - */ - __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 241, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_FILENAME); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 241, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_2 = (__pyx_v_fname_type != __pyx_t_9); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_13 = (__pyx_t_2 != 0); - if (unlikely(__pyx_t_13)) { - - /* "fontTools/feaLib/lexer.py":242 - * fname_type, fname_token, fname_location = lexer.next() - * if fname_type is not Lexer.FILENAME: - * raise FeatureLibError("Expected file name", fname_location) # <<<<<<<<<<<<<< - * # semi_type, semi_token, semi_location = lexer.next() - * # if semi_type is not Lexer.SYMBOL or semi_token != ";": - */ - __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_n_s_FeatureLibError); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 242, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_3 = NULL; - __pyx_t_11 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_8))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_8); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_8); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_8, function); - __pyx_t_11 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_8)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_kp_u_Expected_file_name, __pyx_v_fname_location}; - __pyx_t_9 = __Pyx_PyFunction_FastCall(__pyx_t_8, __pyx_temp+1-__pyx_t_11, 2+__pyx_t_11); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 242, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_9); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_8)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_kp_u_Expected_file_name, __pyx_v_fname_location}; - __pyx_t_9 = __Pyx_PyCFunction_FastCall(__pyx_t_8, __pyx_temp+1-__pyx_t_11, 2+__pyx_t_11); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 242, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_9); - } else - #endif - { - __pyx_t_7 = PyTuple_New(2+__pyx_t_11); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 242, __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_kp_u_Expected_file_name); - __Pyx_GIVEREF(__pyx_kp_u_Expected_file_name); - PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_11, __pyx_kp_u_Expected_file_name); - __Pyx_INCREF(__pyx_v_fname_location); - __Pyx_GIVEREF(__pyx_v_fname_location); - PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_11, __pyx_v_fname_location); - __pyx_t_9 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_t_7, NULL); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 242, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_Raise(__pyx_t_9, 0, 0, 0); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __PYX_ERR(0, 242, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":241 - * if token_type is Lexer.NAME and token == "include": - * fname_type, fname_token, fname_location = lexer.next() - * if fname_type is not Lexer.FILENAME: # <<<<<<<<<<<<<< - * raise FeatureLibError("Expected file name", fname_location) - * # semi_type, semi_token, semi_location = lexer.next() - */ - } - - /* "fontTools/feaLib/lexer.py":246 - * # if semi_type is not Lexer.SYMBOL or semi_token != ";": - * # raise FeatureLibError("Expected ';'", semi_location) - * if os.path.isabs(fname_token): # <<<<<<<<<<<<<< - * path = fname_token - * else: - */ - __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_n_s_os); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 246, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_path); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 246, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_isabs); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 246, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_8))) { - __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_8); - if (likely(__pyx_t_7)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_8); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_8, function); - } - } - __pyx_t_9 = (__pyx_t_7) ? __Pyx_PyObject_Call2Args(__pyx_t_8, __pyx_t_7, __pyx_v_fname_token) : __Pyx_PyObject_CallOneArg(__pyx_t_8, __pyx_v_fname_token); - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 246, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_13 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_13 < 0)) __PYX_ERR(0, 246, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - if (__pyx_t_13) { - - /* "fontTools/feaLib/lexer.py":247 - * # raise FeatureLibError("Expected ';'", semi_location) - * if os.path.isabs(fname_token): - * path = fname_token # <<<<<<<<<<<<<< - * else: - * if self.includeDir is not None: - */ - __Pyx_INCREF(__pyx_v_fname_token); - __Pyx_XDECREF_SET(__pyx_v_path, __pyx_v_fname_token); - - /* "fontTools/feaLib/lexer.py":246 - * # if semi_type is not Lexer.SYMBOL or semi_token != ";": - * # raise FeatureLibError("Expected ';'", semi_location) - * if os.path.isabs(fname_token): # <<<<<<<<<<<<<< - * path = fname_token - * else: - */ - goto __pyx_L23; - } - - /* "fontTools/feaLib/lexer.py":249 - * path = fname_token - * else: - * if self.includeDir is not None: # <<<<<<<<<<<<<< - * curpath = self.includeDir - * elif self.featurefilepath is not None: - */ - /*else*/ { - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_includeDir); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 249, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_13 = (__pyx_t_9 != Py_None); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_2 = (__pyx_t_13 != 0); - if (__pyx_t_2) { - - /* "fontTools/feaLib/lexer.py":250 - * else: - * if self.includeDir is not None: - * curpath = self.includeDir # <<<<<<<<<<<<<< - * elif self.featurefilepath is not None: - * curpath = os.path.dirname(self.featurefilepath) - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_includeDir); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 250, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_XDECREF_SET(__pyx_v_curpath, __pyx_t_9); - __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":249 - * path = fname_token - * else: - * if self.includeDir is not None: # <<<<<<<<<<<<<< - * curpath = self.includeDir - * elif self.featurefilepath is not None: - */ - goto __pyx_L24; - } - - /* "fontTools/feaLib/lexer.py":251 - * if self.includeDir is not None: - * curpath = self.includeDir - * elif self.featurefilepath is not None: # <<<<<<<<<<<<<< - * curpath = os.path.dirname(self.featurefilepath) - * else: - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_featurefilepath); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_2 = (__pyx_t_9 != Py_None); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_13 = (__pyx_t_2 != 0); - if (__pyx_t_13) { - - /* "fontTools/feaLib/lexer.py":252 - * curpath = self.includeDir - * elif self.featurefilepath is not None: - * curpath = os.path.dirname(self.featurefilepath) # <<<<<<<<<<<<<< - * else: - * # if the IncludingLexer was initialized from an in-memory - */ - __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_n_s_os); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 252, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_path); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 252, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_dirname); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 252, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_featurefilepath); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 252, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_8))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_8); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_8); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_8, function); - } - } - __pyx_t_9 = (__pyx_t_3) ? __Pyx_PyObject_Call2Args(__pyx_t_8, __pyx_t_3, __pyx_t_7) : __Pyx_PyObject_CallOneArg(__pyx_t_8, __pyx_t_7); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 252, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_XDECREF_SET(__pyx_v_curpath, __pyx_t_9); - __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":251 - * if self.includeDir is not None: - * curpath = self.includeDir - * elif self.featurefilepath is not None: # <<<<<<<<<<<<<< - * curpath = os.path.dirname(self.featurefilepath) - * else: - */ - goto __pyx_L24; - } - - /* "fontTools/feaLib/lexer.py":258 - * # its filesystem path, therefore we fall back to using the - * # current working directory to resolve relative includes - * curpath = os.getcwd() # <<<<<<<<<<<<<< - * path = os.path.join(curpath, fname_token) - * if len(self.lexers_) >= 5: - */ - /*else*/ { - __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_n_s_os); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 258, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_getcwd); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 258, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = NULL; - 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 = (__pyx_t_8) ? __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_8) : __Pyx_PyObject_CallNoArg(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 258, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF_SET(__pyx_v_curpath, __pyx_t_9); - __pyx_t_9 = 0; - } - __pyx_L24:; - - /* "fontTools/feaLib/lexer.py":259 - * # current working directory to resolve relative includes - * curpath = os.getcwd() - * path = os.path.join(curpath, fname_token) # <<<<<<<<<<<<<< - * if len(self.lexers_) >= 5: - * raise FeatureLibError("Too many recursive includes", fname_location) - */ - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_os); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 259, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_path); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 259, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_join); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 259, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = NULL; - __pyx_t_11 = 0; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_8)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_8); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - __pyx_t_11 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[3] = {__pyx_t_8, __pyx_v_curpath, __pyx_v_fname_token}; - __pyx_t_9 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_11, 2+__pyx_t_11); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 259, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_GOTREF(__pyx_t_9); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[3] = {__pyx_t_8, __pyx_v_curpath, __pyx_v_fname_token}; - __pyx_t_9 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_11, 2+__pyx_t_11); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 259, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_GOTREF(__pyx_t_9); - } else - #endif - { - __pyx_t_3 = PyTuple_New(2+__pyx_t_11); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 259, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (__pyx_t_8) { - __Pyx_GIVEREF(__pyx_t_8); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_8); __pyx_t_8 = NULL; - } - __Pyx_INCREF(__pyx_v_curpath); - __Pyx_GIVEREF(__pyx_v_curpath); - PyTuple_SET_ITEM(__pyx_t_3, 0+__pyx_t_11, __pyx_v_curpath); - __Pyx_INCREF(__pyx_v_fname_token); - __Pyx_GIVEREF(__pyx_v_fname_token); - PyTuple_SET_ITEM(__pyx_t_3, 1+__pyx_t_11, __pyx_v_fname_token); - __pyx_t_9 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_3, NULL); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 259, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF_SET(__pyx_v_path, __pyx_t_9); - __pyx_t_9 = 0; - } - __pyx_L23:; - - /* "fontTools/feaLib/lexer.py":260 - * curpath = os.getcwd() - * path = os.path.join(curpath, fname_token) - * if len(self.lexers_) >= 5: # <<<<<<<<<<<<<< - * raise FeatureLibError("Too many recursive includes", fname_location) - * try: - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_lexers); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 260, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_14 = PyObject_Length(__pyx_t_9); if (unlikely(__pyx_t_14 == ((Py_ssize_t)-1))) __PYX_ERR(0, 260, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_13 = ((__pyx_t_14 >= 5) != 0); - if (unlikely(__pyx_t_13)) { - - /* "fontTools/feaLib/lexer.py":261 - * path = os.path.join(curpath, fname_token) - * if len(self.lexers_) >= 5: - * raise FeatureLibError("Too many recursive includes", fname_location) # <<<<<<<<<<<<<< - * try: - * self.lexers_.append(self.make_lexer_(path)) - */ - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_FeatureLibError); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 261, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_3 = NULL; - __pyx_t_11 = 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_11 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_kp_u_Too_many_recursive_includes, __pyx_v_fname_location}; - __pyx_t_9 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_11, 2+__pyx_t_11); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 261, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_9); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_kp_u_Too_many_recursive_includes, __pyx_v_fname_location}; - __pyx_t_9 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_11, 2+__pyx_t_11); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 261, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_9); - } else - #endif - { - __pyx_t_8 = PyTuple_New(2+__pyx_t_11); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 261, __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_INCREF(__pyx_kp_u_Too_many_recursive_includes); - __Pyx_GIVEREF(__pyx_kp_u_Too_many_recursive_includes); - PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_11, __pyx_kp_u_Too_many_recursive_includes); - __Pyx_INCREF(__pyx_v_fname_location); - __Pyx_GIVEREF(__pyx_v_fname_location); - PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_11, __pyx_v_fname_location); - __pyx_t_9 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_8, NULL); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 261, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_Raise(__pyx_t_9, 0, 0, 0); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __PYX_ERR(0, 261, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":260 - * curpath = os.getcwd() - * path = os.path.join(curpath, fname_token) - * if len(self.lexers_) >= 5: # <<<<<<<<<<<<<< - * raise FeatureLibError("Too many recursive includes", fname_location) - * try: - */ - } - - /* "fontTools/feaLib/lexer.py":262 - * if len(self.lexers_) >= 5: - * raise FeatureLibError("Too many recursive includes", fname_location) - * try: # <<<<<<<<<<<<<< - * self.lexers_.append(self.make_lexer_(path)) - * except FileNotFoundError as err: - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_6, &__pyx_t_5, &__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_6); - __Pyx_XGOTREF(__pyx_t_5); - __Pyx_XGOTREF(__pyx_t_4); - /*try:*/ { - - /* "fontTools/feaLib/lexer.py":263 - * raise FeatureLibError("Too many recursive includes", fname_location) - * try: - * self.lexers_.append(self.make_lexer_(path)) # <<<<<<<<<<<<<< - * except FileNotFoundError as err: - * raise IncludedFeaNotFound(fname_token, fname_location) from err - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_lexers); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 263, __pyx_L26_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_make_lexer); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 263, __pyx_L26_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_8))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_8); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_8); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_8, function); - } - } - __pyx_t_7 = (__pyx_t_3) ? __Pyx_PyObject_Call2Args(__pyx_t_8, __pyx_t_3, __pyx_v_path) : __Pyx_PyObject_CallOneArg(__pyx_t_8, __pyx_v_path); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 263, __pyx_L26_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_15 = __Pyx_PyObject_Append(__pyx_t_9, __pyx_t_7); if (unlikely(__pyx_t_15 == ((int)-1))) __PYX_ERR(0, 263, __pyx_L26_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - - /* "fontTools/feaLib/lexer.py":262 - * if len(self.lexers_) >= 5: - * raise FeatureLibError("Too many recursive includes", fname_location) - * try: # <<<<<<<<<<<<<< - * self.lexers_.append(self.make_lexer_(path)) - * except FileNotFoundError as err: - */ - } - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - goto __pyx_L33_try_end; - __pyx_L26_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":264 - * try: - * self.lexers_.append(self.make_lexer_(path)) - * except FileNotFoundError as err: # <<<<<<<<<<<<<< - * raise IncludedFeaNotFound(fname_token, fname_location) from err - * else: - */ - __Pyx_ErrFetch(&__pyx_t_7, &__pyx_t_9, &__pyx_t_8); - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_FileNotFoundError); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 264, __pyx_L28_except_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_11 = __Pyx_PyErr_GivenExceptionMatches(__pyx_t_7, __pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_ErrRestore(__pyx_t_7, __pyx_t_9, __pyx_t_8); - __pyx_t_7 = 0; __pyx_t_9 = 0; __pyx_t_8 = 0; - if (__pyx_t_11) { - __Pyx_AddTraceback("fontTools.feaLib.lexer.IncludingLexer.__next__", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_8, &__pyx_t_9, &__pyx_t_7) < 0) __PYX_ERR(0, 264, __pyx_L28_except_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_GOTREF(__pyx_t_9); - __Pyx_GOTREF(__pyx_t_7); - __Pyx_INCREF(__pyx_t_9); - __pyx_v_err = __pyx_t_9; - /*try:*/ { - - /* "fontTools/feaLib/lexer.py":265 - * self.lexers_.append(self.make_lexer_(path)) - * except FileNotFoundError as err: - * raise IncludedFeaNotFound(fname_token, fname_location) from err # <<<<<<<<<<<<<< - * else: - * return (token_type, token, location) - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_IncludedFeaNotFound); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 265, __pyx_L39_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_16 = NULL; - __pyx_t_11 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_1))) { - __pyx_t_16 = PyMethod_GET_SELF(__pyx_t_1); - if (likely(__pyx_t_16)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); - __Pyx_INCREF(__pyx_t_16); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_1, function); - __pyx_t_11 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_1)) { - PyObject *__pyx_temp[3] = {__pyx_t_16, __pyx_v_fname_token, __pyx_v_fname_location}; - __pyx_t_3 = __Pyx_PyFunction_FastCall(__pyx_t_1, __pyx_temp+1-__pyx_t_11, 2+__pyx_t_11); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 265, __pyx_L39_error) - __Pyx_XDECREF(__pyx_t_16); __pyx_t_16 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_1)) { - PyObject *__pyx_temp[3] = {__pyx_t_16, __pyx_v_fname_token, __pyx_v_fname_location}; - __pyx_t_3 = __Pyx_PyCFunction_FastCall(__pyx_t_1, __pyx_temp+1-__pyx_t_11, 2+__pyx_t_11); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 265, __pyx_L39_error) - __Pyx_XDECREF(__pyx_t_16); __pyx_t_16 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else - #endif - { - __pyx_t_17 = PyTuple_New(2+__pyx_t_11); if (unlikely(!__pyx_t_17)) __PYX_ERR(0, 265, __pyx_L39_error) - __Pyx_GOTREF(__pyx_t_17); - if (__pyx_t_16) { - __Pyx_GIVEREF(__pyx_t_16); PyTuple_SET_ITEM(__pyx_t_17, 0, __pyx_t_16); __pyx_t_16 = NULL; - } - __Pyx_INCREF(__pyx_v_fname_token); - __Pyx_GIVEREF(__pyx_v_fname_token); - PyTuple_SET_ITEM(__pyx_t_17, 0+__pyx_t_11, __pyx_v_fname_token); - __Pyx_INCREF(__pyx_v_fname_location); - __Pyx_GIVEREF(__pyx_v_fname_location); - PyTuple_SET_ITEM(__pyx_t_17, 1+__pyx_t_11, __pyx_v_fname_location); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_17, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 265, __pyx_L39_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_17); __pyx_t_17 = 0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, __pyx_v_err); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(0, 265, __pyx_L39_error) - } - - /* "fontTools/feaLib/lexer.py":264 - * try: - * self.lexers_.append(self.make_lexer_(path)) - * except FileNotFoundError as err: # <<<<<<<<<<<<<< - * raise IncludedFeaNotFound(fname_token, fname_location) from err - * else: - */ - /*finally:*/ { - __pyx_L39_error:; - /*exception exit:*/{ - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __pyx_t_20 = 0; __pyx_t_21 = 0; __pyx_t_22 = 0; __pyx_t_23 = 0; __pyx_t_24 = 0; __pyx_t_25 = 0; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_16); __pyx_t_16 = 0; - __Pyx_XDECREF(__pyx_t_17); __pyx_t_17 = 0; - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_23, &__pyx_t_24, &__pyx_t_25); - if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_20, &__pyx_t_21, &__pyx_t_22) < 0)) __Pyx_ErrFetch(&__pyx_t_20, &__pyx_t_21, &__pyx_t_22); - __Pyx_XGOTREF(__pyx_t_20); - __Pyx_XGOTREF(__pyx_t_21); - __Pyx_XGOTREF(__pyx_t_22); - __Pyx_XGOTREF(__pyx_t_23); - __Pyx_XGOTREF(__pyx_t_24); - __Pyx_XGOTREF(__pyx_t_25); - __pyx_t_11 = __pyx_lineno; __pyx_t_18 = __pyx_clineno; __pyx_t_19 = __pyx_filename; - { - __Pyx_DECREF(__pyx_v_err); - __pyx_v_err = NULL; - } - if (PY_MAJOR_VERSION >= 3) { - __Pyx_XGIVEREF(__pyx_t_23); - __Pyx_XGIVEREF(__pyx_t_24); - __Pyx_XGIVEREF(__pyx_t_25); - __Pyx_ExceptionReset(__pyx_t_23, __pyx_t_24, __pyx_t_25); - } - __Pyx_XGIVEREF(__pyx_t_20); - __Pyx_XGIVEREF(__pyx_t_21); - __Pyx_XGIVEREF(__pyx_t_22); - __Pyx_ErrRestore(__pyx_t_20, __pyx_t_21, __pyx_t_22); - __pyx_t_20 = 0; __pyx_t_21 = 0; __pyx_t_22 = 0; __pyx_t_23 = 0; __pyx_t_24 = 0; __pyx_t_25 = 0; - __pyx_lineno = __pyx_t_11; __pyx_clineno = __pyx_t_18; __pyx_filename = __pyx_t_19; - goto __pyx_L28_except_error; - } - } - } - goto __pyx_L28_except_error; - __pyx_L28_except_error:; - - /* "fontTools/feaLib/lexer.py":262 - * if len(self.lexers_) >= 5: - * raise FeatureLibError("Too many recursive includes", fname_location) - * try: # <<<<<<<<<<<<<< - * self.lexers_.append(self.make_lexer_(path)) - * except FileNotFoundError as err: - */ - __Pyx_XGIVEREF(__pyx_t_6); - __Pyx_XGIVEREF(__pyx_t_5); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_6, __pyx_t_5, __pyx_t_4); - goto __pyx_L1_error; - __pyx_L33_try_end:; - } - - /* "fontTools/feaLib/lexer.py":239 - * self.lexers_.pop() - * continue - * if token_type is Lexer.NAME and token == "include": # <<<<<<<<<<<<<< - * fname_type, fname_token, fname_location = lexer.next() - * if fname_type is not Lexer.FILENAME: - */ - goto __pyx_L17; - } - - /* "fontTools/feaLib/lexer.py":267 - * raise IncludedFeaNotFound(fname_token, fname_location) from err - * else: - * return (token_type, token, location) # <<<<<<<<<<<<<< - * raise StopIteration() - * - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __pyx_t_7 = PyTuple_New(3); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 267, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_INCREF(__pyx_v_token_type); - __Pyx_GIVEREF(__pyx_v_token_type); - PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_v_token_type); - __Pyx_INCREF(__pyx_v_token); - __Pyx_GIVEREF(__pyx_v_token); - PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_v_token); - __Pyx_INCREF(__pyx_v_location); - __Pyx_GIVEREF(__pyx_v_location); - PyTuple_SET_ITEM(__pyx_t_7, 2, __pyx_v_location); - __pyx_r = __pyx_t_7; - __pyx_t_7 = 0; - goto __pyx_L0; - } - __pyx_L17:; - __pyx_L3_continue:; - } - - /* "fontTools/feaLib/lexer.py":268 - * else: - * return (token_type, token, location) - * raise StopIteration() # <<<<<<<<<<<<<< - * - * @staticmethod - */ - __pyx_t_7 = __Pyx_PyObject_CallNoArg(__pyx_builtin_StopIteration); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 268, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_Raise(__pyx_t_7, 0, 0, 0); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __PYX_ERR(0, 268, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":231 - * return self.__next__() - * - * def __next__(self): # Python 3 # <<<<<<<<<<<<<< - * while self.lexers_: - * lexer = self.lexers_[-1] - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_16); - __Pyx_XDECREF(__pyx_t_17); - __Pyx_AddTraceback("fontTools.feaLib.lexer.IncludingLexer.__next__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_lexer); - __Pyx_XDECREF(__pyx_v_token_type); - __Pyx_XDECREF(__pyx_v_token); - __Pyx_XDECREF(__pyx_v_location); - __Pyx_XDECREF(__pyx_v_fname_type); - __Pyx_XDECREF(__pyx_v_fname_token); - __Pyx_XDECREF(__pyx_v_fname_location); - __Pyx_XDECREF(__pyx_v_path); - __Pyx_XDECREF(__pyx_v_curpath); - __Pyx_XDECREF(__pyx_v_err); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/feaLib/lexer.py":271 - * - * @staticmethod - * def make_lexer_(file_or_path): # <<<<<<<<<<<<<< - * if hasattr(file_or_path, "read"): - * fileobj, closing = file_or_path, False - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_14IncludingLexer_9make_lexer_(PyObject *__pyx_self, PyObject *__pyx_v_file_or_path); /*proto*/ -static char __pyx_doc_9fontTools_6feaLib_5lexer_14IncludingLexer_8make_lexer_[] = "IncludingLexer.make_lexer_(file_or_path)"; -static PyMethodDef __pyx_mdef_9fontTools_6feaLib_5lexer_14IncludingLexer_9make_lexer_ = {"make_lexer_", (PyCFunction)__pyx_pw_9fontTools_6feaLib_5lexer_14IncludingLexer_9make_lexer_, METH_O, __pyx_doc_9fontTools_6feaLib_5lexer_14IncludingLexer_8make_lexer_}; -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_14IncludingLexer_9make_lexer_(PyObject *__pyx_self, PyObject *__pyx_v_file_or_path) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("make_lexer_ (wrapper)", 0); - __pyx_r = __pyx_pf_9fontTools_6feaLib_5lexer_14IncludingLexer_8make_lexer_(__pyx_self, ((PyObject *)__pyx_v_file_or_path)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_14IncludingLexer_8make_lexer_(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_file_or_path) { - PyObject *__pyx_v_fileobj = NULL; - int __pyx_v_closing; - PyObject *__pyx_v_filename = NULL; - PyObject *__pyx_v_data = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("make_lexer_", 0); - - /* "fontTools/feaLib/lexer.py":272 - * @staticmethod - * def make_lexer_(file_or_path): - * if hasattr(file_or_path, "read"): # <<<<<<<<<<<<<< - * fileobj, closing = file_or_path, False - * else: - */ - __pyx_t_1 = __Pyx_HasAttr(__pyx_v_file_or_path, __pyx_n_u_read); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(0, 272, __pyx_L1_error) - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "fontTools/feaLib/lexer.py":273 - * def make_lexer_(file_or_path): - * if hasattr(file_or_path, "read"): - * fileobj, closing = file_or_path, False # <<<<<<<<<<<<<< - * else: - * filename, closing = file_or_path, True - */ - __pyx_t_3 = __pyx_v_file_or_path; - __Pyx_INCREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_v_fileobj = __pyx_t_3; - __pyx_t_3 = 0; - __pyx_v_closing = __pyx_t_2; - - /* "fontTools/feaLib/lexer.py":272 - * @staticmethod - * def make_lexer_(file_or_path): - * if hasattr(file_or_path, "read"): # <<<<<<<<<<<<<< - * fileobj, closing = file_or_path, False - * else: - */ - goto __pyx_L3; - } - - /* "fontTools/feaLib/lexer.py":275 - * fileobj, closing = file_or_path, False - * else: - * filename, closing = file_or_path, True # <<<<<<<<<<<<<< - * fileobj = open(filename, "r", encoding="utf-8") - * data = fileobj.read() - */ - /*else*/ { - __pyx_t_3 = __pyx_v_file_or_path; - __Pyx_INCREF(__pyx_t_3); - __pyx_t_2 = 1; - __pyx_v_filename = __pyx_t_3; - __pyx_t_3 = 0; - __pyx_v_closing = __pyx_t_2; - - /* "fontTools/feaLib/lexer.py":276 - * else: - * filename, closing = file_or_path, True - * fileobj = open(filename, "r", encoding="utf-8") # <<<<<<<<<<<<<< - * data = fileobj.read() - * filename = getattr(fileobj, "name", None) - */ - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 276, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_filename); - __Pyx_GIVEREF(__pyx_v_filename); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_filename); - __Pyx_INCREF(__pyx_n_u_r); - __Pyx_GIVEREF(__pyx_n_u_r); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_n_u_r); - __pyx_t_4 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 276, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_encoding, __pyx_kp_u_utf_8) < 0) __PYX_ERR(0, 276, __pyx_L1_error) - __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_open, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 276, __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_v_fileobj = __pyx_t_5; - __pyx_t_5 = 0; - } - __pyx_L3:; - - /* "fontTools/feaLib/lexer.py":277 - * filename, closing = file_or_path, True - * fileobj = open(filename, "r", encoding="utf-8") - * data = fileobj.read() # <<<<<<<<<<<<<< - * filename = getattr(fileobj, "name", None) - * if closing: - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_fileobj, __pyx_n_s_read); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 277, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - __pyx_t_5 = (__pyx_t_3) ? __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3) : __Pyx_PyObject_CallNoArg(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 277, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_v_data = __pyx_t_5; - __pyx_t_5 = 0; - - /* "fontTools/feaLib/lexer.py":278 - * fileobj = open(filename, "r", encoding="utf-8") - * data = fileobj.read() - * filename = getattr(fileobj, "name", None) # <<<<<<<<<<<<<< - * if closing: - * fileobj.close() - */ - __pyx_t_5 = __Pyx_GetAttr3(__pyx_v_fileobj, __pyx_n_u_name, Py_None); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 278, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_XDECREF_SET(__pyx_v_filename, __pyx_t_5); - __pyx_t_5 = 0; - - /* "fontTools/feaLib/lexer.py":279 - * data = fileobj.read() - * filename = getattr(fileobj, "name", None) - * if closing: # <<<<<<<<<<<<<< - * fileobj.close() - * return Lexer(data, filename) - */ - __pyx_t_2 = (__pyx_v_closing != 0); - if (__pyx_t_2) { - - /* "fontTools/feaLib/lexer.py":280 - * filename = getattr(fileobj, "name", None) - * if closing: - * fileobj.close() # <<<<<<<<<<<<<< - * return Lexer(data, filename) - * - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_fileobj, __pyx_n_s_close); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 280, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - __pyx_t_5 = (__pyx_t_3) ? __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3) : __Pyx_PyObject_CallNoArg(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 280, __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/feaLib/lexer.py":279 - * data = fileobj.read() - * filename = getattr(fileobj, "name", None) - * if closing: # <<<<<<<<<<<<<< - * fileobj.close() - * return Lexer(data, filename) - */ - } - - /* "fontTools/feaLib/lexer.py":281 - * if closing: - * fileobj.close() - * return Lexer(data, filename) # <<<<<<<<<<<<<< - * - * def scan_anonymous_block(self, tag): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_Lexer); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 281, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_3); - __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_3, __pyx_v_data, __pyx_v_filename}; - __pyx_t_5 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 281, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_5); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_v_data, __pyx_v_filename}; - __pyx_t_5 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 281, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_5); - } else - #endif - { - __pyx_t_7 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 281, __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_data); - __Pyx_GIVEREF(__pyx_v_data); - PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_6, __pyx_v_data); - __Pyx_INCREF(__pyx_v_filename); - __Pyx_GIVEREF(__pyx_v_filename); - PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_6, __pyx_v_filename); - __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_7, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 281, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":271 - * - * @staticmethod - * def make_lexer_(file_or_path): # <<<<<<<<<<<<<< - * if hasattr(file_or_path, "read"): - * fileobj, closing = file_or_path, False - */ - - /* 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_AddTraceback("fontTools.feaLib.lexer.IncludingLexer.make_lexer_", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_fileobj); - __Pyx_XDECREF(__pyx_v_filename); - __Pyx_XDECREF(__pyx_v_data); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/feaLib/lexer.py":283 - * return Lexer(data, filename) - * - * def scan_anonymous_block(self, tag): # <<<<<<<<<<<<<< - * return self.lexers_[-1].scan_anonymous_block(tag) - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_14IncludingLexer_11scan_anonymous_block(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_6feaLib_5lexer_14IncludingLexer_10scan_anonymous_block[] = "IncludingLexer.scan_anonymous_block(self, tag)"; -static PyMethodDef __pyx_mdef_9fontTools_6feaLib_5lexer_14IncludingLexer_11scan_anonymous_block = {"scan_anonymous_block", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_6feaLib_5lexer_14IncludingLexer_11scan_anonymous_block, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_6feaLib_5lexer_14IncludingLexer_10scan_anonymous_block}; -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_14IncludingLexer_11scan_anonymous_block(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_self = 0; - PyObject *__pyx_v_tag = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("scan_anonymous_block (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_self,&__pyx_n_s_tag,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_self)) != 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_tag)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("scan_anonymous_block", 1, 2, 2, 1); __PYX_ERR(0, 283, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "scan_anonymous_block") < 0)) __PYX_ERR(0, 283, __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_self = values[0]; - __pyx_v_tag = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("scan_anonymous_block", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 283, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.feaLib.lexer.IncludingLexer.scan_anonymous_block", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_6feaLib_5lexer_14IncludingLexer_10scan_anonymous_block(__pyx_self, __pyx_v_self, __pyx_v_tag); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_14IncludingLexer_10scan_anonymous_block(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self, PyObject *__pyx_v_tag) { - 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("scan_anonymous_block", 0); - - /* "fontTools/feaLib/lexer.py":284 - * - * def scan_anonymous_block(self, tag): - * return self.lexers_[-1].scan_anonymous_block(tag) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_lexers); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 284, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_2, -1L, long, 1, __Pyx_PyInt_From_long, 0, 1, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 284, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_scan_anonymous_block); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 284, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_tag) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v_tag); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 284, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":283 - * return Lexer(data, filename) - * - * def scan_anonymous_block(self, tag): # <<<<<<<<<<<<<< - * return self.lexers_[-1].scan_anonymous_block(tag) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("fontTools.feaLib.lexer.IncludingLexer.scan_anonymous_block", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/feaLib/lexer.py":290 - * """Lexer that does not follow `include` statements, emits them as-is.""" - * - * def __next__(self): # Python 3 # <<<<<<<<<<<<<< - * return next(self.lexers_[0]) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_17NonIncludingLexer_1__next__(PyObject *__pyx_self, PyObject *__pyx_v_self); /*proto*/ -static char __pyx_doc_9fontTools_6feaLib_5lexer_17NonIncludingLexer___next__[] = "NonIncludingLexer.__next__(self)"; -static PyMethodDef __pyx_mdef_9fontTools_6feaLib_5lexer_17NonIncludingLexer_1__next__ = {"__next__", (PyCFunction)__pyx_pw_9fontTools_6feaLib_5lexer_17NonIncludingLexer_1__next__, METH_O, __pyx_doc_9fontTools_6feaLib_5lexer_17NonIncludingLexer___next__}; -static PyObject *__pyx_pw_9fontTools_6feaLib_5lexer_17NonIncludingLexer_1__next__(PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__next__ (wrapper)", 0); - __pyx_r = __pyx_pf_9fontTools_6feaLib_5lexer_17NonIncludingLexer___next__(__pyx_self, ((PyObject *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_6feaLib_5lexer_17NonIncludingLexer___next__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__next__", 0); - - /* "fontTools/feaLib/lexer.py":291 - * - * def __next__(self): # Python 3 - * return next(self.lexers_[0]) # <<<<<<<<<<<<<< - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_lexers); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 291, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 291, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyIter_Next(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 291, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/feaLib/lexer.py":290 - * """Lexer that does not follow `include` statements, emits them as-is.""" - * - * def __next__(self): # Python 3 # <<<<<<<<<<<<<< - * return next(self.lexers_[0]) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("fontTools.feaLib.lexer.NonIncludingLexer.__next__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -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_lexer(PyObject* module); /*proto*/ -static PyModuleDef_Slot __pyx_moduledef_slots[] = { - {Py_mod_create, (void*)__pyx_pymod_create}, - {Py_mod_exec, (void*)__pyx_pymod_exec_lexer}, - {0, NULL} -}; -#endif - -static struct PyModuleDef __pyx_moduledef = { - PyModuleDef_HEAD_INIT, - "lexer", - 0, /* m_doc */ - #if CYTHON_PEP489_MULTI_PHASE_INIT - 0, /* m_size */ - #else - -1, /* m_size */ - #endif - __pyx_methods /* m_methods */, - #if CYTHON_PEP489_MULTI_PHASE_INIT - __pyx_moduledef_slots, /* m_slots */ - #else - NULL, /* m_reload */ - #endif - NULL, /* m_traverse */ - NULL, /* m_clear */ - NULL /* m_free */ -}; -#endif -#ifndef CYTHON_SMALL_CODE -#if defined(__clang__) - #define CYTHON_SMALL_CODE -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) - #define CYTHON_SMALL_CODE __attribute__((cold)) -#else - #define CYTHON_SMALL_CODE -#endif -#endif - -static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_kp_u_, __pyx_k_, sizeof(__pyx_k_), 0, 1, 0, 0}, - {&__pyx_kp_u_0, __pyx_k_0, sizeof(__pyx_k_0), 0, 1, 0, 0}, - {&__pyx_kp_u_0123456789, __pyx_k_0123456789, sizeof(__pyx_k_0123456789), 0, 1, 0, 0}, - {&__pyx_kp_u_0123456789ABCDEFabcdef, __pyx_k_0123456789ABCDEFabcdef, sizeof(__pyx_k_0123456789ABCDEFabcdef), 0, 1, 0, 0}, - {&__pyx_n_u_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef, __pyx_k_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef, sizeof(__pyx_k_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef), 0, 1, 0, 1}, - {&__pyx_n_s_ANONYMOUS_BLOCK, __pyx_k_ANONYMOUS_BLOCK, sizeof(__pyx_k_ANONYMOUS_BLOCK), 0, 0, 1, 1}, - {&__pyx_n_u_ANONYMOUS_BLOCK, __pyx_k_ANONYMOUS_BLOCK, sizeof(__pyx_k_ANONYMOUS_BLOCK), 0, 1, 0, 1}, - {&__pyx_kp_s_A_Lexer_that_follows_include_sta, __pyx_k_A_Lexer_that_follows_include_sta, sizeof(__pyx_k_A_Lexer_that_follows_include_sta), 0, 0, 1, 0}, - {&__pyx_kp_u_A_Za_z_0_9, __pyx_k_A_Za_z_0_9, sizeof(__pyx_k_A_Za_z_0_9), 0, 1, 0, 0}, - {&__pyx_n_s_CHAR_DIGIT, __pyx_k_CHAR_DIGIT, sizeof(__pyx_k_CHAR_DIGIT), 0, 0, 1, 1}, - {&__pyx_n_s_CHAR_HEXDIGIT, __pyx_k_CHAR_HEXDIGIT, sizeof(__pyx_k_CHAR_HEXDIGIT), 0, 0, 1, 1}, - {&__pyx_n_s_CHAR_LETTER, __pyx_k_CHAR_LETTER, sizeof(__pyx_k_CHAR_LETTER), 0, 0, 1, 1}, - {&__pyx_n_s_CHAR_NAME_CONTINUATION, __pyx_k_CHAR_NAME_CONTINUATION, sizeof(__pyx_k_CHAR_NAME_CONTINUATION), 0, 0, 1, 1}, - {&__pyx_n_s_CHAR_NAME_START, __pyx_k_CHAR_NAME_START, sizeof(__pyx_k_CHAR_NAME_START), 0, 0, 1, 1}, - {&__pyx_n_s_CHAR_NEWLINE, __pyx_k_CHAR_NEWLINE, sizeof(__pyx_k_CHAR_NEWLINE), 0, 0, 1, 1}, - {&__pyx_n_s_CHAR_SYMBOL, __pyx_k_CHAR_SYMBOL, sizeof(__pyx_k_CHAR_SYMBOL), 0, 0, 1, 1}, - {&__pyx_n_s_CHAR_WHITESPACE, __pyx_k_CHAR_WHITESPACE, sizeof(__pyx_k_CHAR_WHITESPACE), 0, 0, 1, 1}, - {&__pyx_n_s_CID, __pyx_k_CID, sizeof(__pyx_k_CID), 0, 0, 1, 1}, - {&__pyx_n_u_CID, __pyx_k_CID, sizeof(__pyx_k_CID), 0, 1, 0, 1}, - {&__pyx_n_s_COMMENT, __pyx_k_COMMENT, sizeof(__pyx_k_COMMENT), 0, 0, 1, 1}, - {&__pyx_n_u_COMMENT, __pyx_k_COMMENT, sizeof(__pyx_k_COMMENT), 0, 1, 0, 1}, - {&__pyx_kp_u_Expected_after_file_name, __pyx_k_Expected_after_file_name, sizeof(__pyx_k_Expected_after_file_name), 0, 1, 0, 0}, - {&__pyx_kp_u_Expected_before_file_name, __pyx_k_Expected_before_file_name, sizeof(__pyx_k_Expected_before_file_name), 0, 1, 0, 0}, - {&__pyx_kp_u_Expected_file_name, __pyx_k_Expected_file_name, sizeof(__pyx_k_Expected_file_name), 0, 1, 0, 0}, - {&__pyx_kp_u_Expected_glyph_class_name, __pyx_k_Expected_glyph_class_name, sizeof(__pyx_k_Expected_glyph_class_name), 0, 1, 0, 0}, - {&__pyx_kp_u_Expected_s_to_terminate_anonymou, __pyx_k_Expected_s_to_terminate_anonymou, sizeof(__pyx_k_Expected_s_to_terminate_anonymou), 0, 1, 0, 0}, - {&__pyx_kp_u_Expected_to_terminate_string, __pyx_k_Expected_to_terminate_string, sizeof(__pyx_k_Expected_to_terminate_string), 0, 1, 0, 0}, - {&__pyx_n_s_FILENAME, __pyx_k_FILENAME, sizeof(__pyx_k_FILENAME), 0, 0, 1, 1}, - {&__pyx_n_u_FILENAME, __pyx_k_FILENAME, sizeof(__pyx_k_FILENAME), 0, 1, 0, 1}, - {&__pyx_n_s_FLOAT, __pyx_k_FLOAT, sizeof(__pyx_k_FLOAT), 0, 0, 1, 1}, - {&__pyx_n_u_FLOAT, __pyx_k_FLOAT, sizeof(__pyx_k_FLOAT), 0, 1, 0, 1}, - {&__pyx_n_s_FeatureLibError, __pyx_k_FeatureLibError, sizeof(__pyx_k_FeatureLibError), 0, 0, 1, 1}, - {&__pyx_n_s_FeatureLibLocation, __pyx_k_FeatureLibLocation, sizeof(__pyx_k_FeatureLibLocation), 0, 0, 1, 1}, - {&__pyx_n_s_FileNotFoundError, __pyx_k_FileNotFoundError, sizeof(__pyx_k_FileNotFoundError), 0, 0, 1, 1}, - {&__pyx_n_s_GLYPHCLASS, __pyx_k_GLYPHCLASS, sizeof(__pyx_k_GLYPHCLASS), 0, 0, 1, 1}, - {&__pyx_n_u_GLYPHCLASS, __pyx_k_GLYPHCLASS, sizeof(__pyx_k_GLYPHCLASS), 0, 1, 0, 1}, - {&__pyx_kp_u_Glyph_class_names_must_consist_o, __pyx_k_Glyph_class_names_must_consist_o, sizeof(__pyx_k_Glyph_class_names_must_consist_o), 0, 1, 0, 0}, - {&__pyx_kp_u_Glyph_class_names_must_not_be_lo, __pyx_k_Glyph_class_names_must_not_be_lo, sizeof(__pyx_k_Glyph_class_names_must_not_be_lo), 0, 1, 0, 0}, - {&__pyx_n_s_HEXADECIMAL, __pyx_k_HEXADECIMAL, sizeof(__pyx_k_HEXADECIMAL), 0, 0, 1, 1}, - {&__pyx_n_u_HEXADECIMAL, __pyx_k_HEXADECIMAL, sizeof(__pyx_k_HEXADECIMAL), 0, 1, 0, 1}, - {&__pyx_n_s_ImportError, __pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 0, 1, 1}, - {&__pyx_n_s_IncludedFeaNotFound, __pyx_k_IncludedFeaNotFound, sizeof(__pyx_k_IncludedFeaNotFound), 0, 0, 1, 1}, - {&__pyx_n_s_IncludingLexer, __pyx_k_IncludingLexer, sizeof(__pyx_k_IncludingLexer), 0, 0, 1, 1}, - {&__pyx_n_s_IncludingLexer___init, __pyx_k_IncludingLexer___init, sizeof(__pyx_k_IncludingLexer___init), 0, 0, 1, 1}, - {&__pyx_n_s_IncludingLexer___iter, __pyx_k_IncludingLexer___iter, sizeof(__pyx_k_IncludingLexer___iter), 0, 0, 1, 1}, - {&__pyx_n_s_IncludingLexer___next, __pyx_k_IncludingLexer___next, sizeof(__pyx_k_IncludingLexer___next), 0, 0, 1, 1}, - {&__pyx_n_s_IncludingLexer_make_lexer, __pyx_k_IncludingLexer_make_lexer, sizeof(__pyx_k_IncludingLexer_make_lexer), 0, 0, 1, 1}, - {&__pyx_n_s_IncludingLexer_next, __pyx_k_IncludingLexer_next, sizeof(__pyx_k_IncludingLexer_next), 0, 0, 1, 1}, - {&__pyx_n_s_IncludingLexer_scan_anonymous_bl, __pyx_k_IncludingLexer_scan_anonymous_bl, sizeof(__pyx_k_IncludingLexer_scan_anonymous_bl), 0, 0, 1, 1}, - {&__pyx_n_s_Lexer, __pyx_k_Lexer, sizeof(__pyx_k_Lexer), 0, 0, 1, 1}, - {&__pyx_n_s_Lexer___init, __pyx_k_Lexer___init, sizeof(__pyx_k_Lexer___init), 0, 0, 1, 1}, - {&__pyx_n_s_Lexer___iter, __pyx_k_Lexer___iter, sizeof(__pyx_k_Lexer___iter), 0, 0, 1, 1}, - {&__pyx_n_s_Lexer___next, __pyx_k_Lexer___next, sizeof(__pyx_k_Lexer___next), 0, 0, 1, 1}, - {&__pyx_n_s_Lexer_location, __pyx_k_Lexer_location, sizeof(__pyx_k_Lexer_location), 0, 0, 1, 1}, - {&__pyx_n_s_Lexer_next, __pyx_k_Lexer_next, sizeof(__pyx_k_Lexer_next), 0, 0, 1, 1}, - {&__pyx_n_s_Lexer_next_2, __pyx_k_Lexer_next_2, sizeof(__pyx_k_Lexer_next_2), 0, 0, 1, 1}, - {&__pyx_n_s_Lexer_scan_anonymous_block, __pyx_k_Lexer_scan_anonymous_block, sizeof(__pyx_k_Lexer_scan_anonymous_block), 0, 0, 1, 1}, - {&__pyx_n_s_Lexer_scan_over, __pyx_k_Lexer_scan_over, sizeof(__pyx_k_Lexer_scan_over), 0, 0, 1, 1}, - {&__pyx_n_s_Lexer_scan_until, __pyx_k_Lexer_scan_until, sizeof(__pyx_k_Lexer_scan_until), 0, 0, 1, 1}, - {&__pyx_kp_s_Lexer_that_does_not_follow_inclu, __pyx_k_Lexer_that_does_not_follow_inclu, sizeof(__pyx_k_Lexer_that_does_not_follow_inclu), 0, 0, 1, 0}, - {&__pyx_kp_s_Lib_fontTools_feaLib_lexer_py, __pyx_k_Lib_fontTools_feaLib_lexer_py, sizeof(__pyx_k_Lib_fontTools_feaLib_lexer_py), 0, 0, 1, 0}, - {&__pyx_n_s_MODE_FILENAME, __pyx_k_MODE_FILENAME, sizeof(__pyx_k_MODE_FILENAME), 0, 0, 1, 1}, - {&__pyx_n_s_MODE_NORMAL, __pyx_k_MODE_NORMAL, sizeof(__pyx_k_MODE_NORMAL), 0, 0, 1, 1}, - {&__pyx_n_s_NAME, __pyx_k_NAME, sizeof(__pyx_k_NAME), 0, 0, 1, 1}, - {&__pyx_n_u_NAME, __pyx_k_NAME, sizeof(__pyx_k_NAME), 0, 1, 0, 1}, - {&__pyx_n_s_NEWLINE, __pyx_k_NEWLINE, sizeof(__pyx_k_NEWLINE), 0, 0, 1, 1}, - {&__pyx_n_u_NEWLINE, __pyx_k_NEWLINE, sizeof(__pyx_k_NEWLINE), 0, 1, 0, 1}, - {&__pyx_n_u_NORMAL, __pyx_k_NORMAL, sizeof(__pyx_k_NORMAL), 0, 1, 0, 1}, - {&__pyx_n_s_NUMBER, __pyx_k_NUMBER, sizeof(__pyx_k_NUMBER), 0, 0, 1, 1}, - {&__pyx_n_u_NUMBER, __pyx_k_NUMBER, sizeof(__pyx_k_NUMBER), 0, 1, 0, 1}, - {&__pyx_n_s_NUMBERS, __pyx_k_NUMBERS, sizeof(__pyx_k_NUMBERS), 0, 0, 1, 1}, - {&__pyx_n_s_NonIncludingLexer, __pyx_k_NonIncludingLexer, sizeof(__pyx_k_NonIncludingLexer), 0, 0, 1, 1}, - {&__pyx_n_s_NonIncludingLexer___next, __pyx_k_NonIncludingLexer___next, sizeof(__pyx_k_NonIncludingLexer___next), 0, 0, 1, 1}, - {&__pyx_n_s_OCTAL, __pyx_k_OCTAL, sizeof(__pyx_k_OCTAL), 0, 0, 1, 1}, - {&__pyx_n_u_OCTAL, __pyx_k_OCTAL, sizeof(__pyx_k_OCTAL), 0, 1, 0, 1}, - {&__pyx_n_s_RE_GLYPHCLASS, __pyx_k_RE_GLYPHCLASS, sizeof(__pyx_k_RE_GLYPHCLASS), 0, 0, 1, 1}, - {&__pyx_n_s_STRING, __pyx_k_STRING, sizeof(__pyx_k_STRING), 0, 0, 1, 1}, - {&__pyx_n_u_STRING, __pyx_k_STRING, sizeof(__pyx_k_STRING), 0, 1, 0, 1}, - {&__pyx_n_s_SYMBOL, __pyx_k_SYMBOL, sizeof(__pyx_k_SYMBOL), 0, 0, 1, 1}, - {&__pyx_n_u_SYMBOL, __pyx_k_SYMBOL, sizeof(__pyx_k_SYMBOL), 0, 1, 0, 1}, - {&__pyx_n_s_StopIteration, __pyx_k_StopIteration, sizeof(__pyx_k_StopIteration), 0, 0, 1, 1}, - {&__pyx_kp_u_Too_many_recursive_includes, __pyx_k_Too_many_recursive_includes, sizeof(__pyx_k_Too_many_recursive_includes), 0, 1, 0, 0}, - {&__pyx_kp_u_Unexpected_character_r, __pyx_k_Unexpected_character_r, sizeof(__pyx_k_Unexpected_character_r), 0, 1, 0, 0}, - {&__pyx_kp_u__10, __pyx_k__10, sizeof(__pyx_k__10), 0, 1, 0, 0}, - {&__pyx_kp_u__11, __pyx_k__11, sizeof(__pyx_k__11), 0, 1, 0, 0}, - {&__pyx_kp_u__12, __pyx_k__12, sizeof(__pyx_k__12), 0, 1, 0, 0}, - {&__pyx_kp_u__14, __pyx_k__14, sizeof(__pyx_k__14), 0, 1, 0, 0}, - {&__pyx_kp_u__15, __pyx_k__15, sizeof(__pyx_k__15), 0, 1, 0, 0}, - {&__pyx_kp_u__16, __pyx_k__16, sizeof(__pyx_k__16), 0, 1, 0, 0}, - {&__pyx_kp_u__17, __pyx_k__17, sizeof(__pyx_k__17), 0, 1, 0, 0}, - {&__pyx_kp_u__18, __pyx_k__18, sizeof(__pyx_k__18), 0, 1, 0, 0}, - {&__pyx_kp_u__2, __pyx_k__2, sizeof(__pyx_k__2), 0, 1, 0, 0}, - {&__pyx_kp_u__3, __pyx_k__3, sizeof(__pyx_k__3), 0, 1, 0, 0}, - {&__pyx_kp_u__4, __pyx_k__4, sizeof(__pyx_k__4), 0, 1, 0, 0}, - {&__pyx_kp_u__5, __pyx_k__5, sizeof(__pyx_k__5), 0, 1, 0, 0}, - {&__pyx_kp_u__6, __pyx_k__6, sizeof(__pyx_k__6), 0, 1, 0, 0}, - {&__pyx_kp_u__7, __pyx_k__7, sizeof(__pyx_k__7), 0, 1, 0, 0}, - {&__pyx_kp_u__8, __pyx_k__8, sizeof(__pyx_k__8), 0, 1, 0, 0}, - {&__pyx_kp_u__9, __pyx_k__9, sizeof(__pyx_k__9), 0, 1, 0, 0}, - {&__pyx_n_s_append, __pyx_k_append, sizeof(__pyx_k_append), 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_closing, __pyx_k_closing, sizeof(__pyx_k_closing), 0, 0, 1, 1}, - {&__pyx_n_s_column, __pyx_k_column, sizeof(__pyx_k_column), 0, 0, 1, 1}, - {&__pyx_n_s_compile, __pyx_k_compile, sizeof(__pyx_k_compile), 0, 0, 1, 1}, - {&__pyx_n_s_cur_char, __pyx_k_cur_char, sizeof(__pyx_k_cur_char), 0, 0, 1, 1}, - {&__pyx_n_s_curpath, __pyx_k_curpath, sizeof(__pyx_k_curpath), 0, 0, 1, 1}, - {&__pyx_n_s_data, __pyx_k_data, sizeof(__pyx_k_data), 0, 0, 1, 1}, - {&__pyx_n_s_dirname, __pyx_k_dirname, sizeof(__pyx_k_dirname), 0, 0, 1, 1}, - {&__pyx_n_s_doc, __pyx_k_doc, sizeof(__pyx_k_doc), 0, 0, 1, 1}, - {&__pyx_n_s_encoding, __pyx_k_encoding, sizeof(__pyx_k_encoding), 0, 0, 1, 1}, - {&__pyx_n_s_err, __pyx_k_err, sizeof(__pyx_k_err), 0, 0, 1, 1}, - {&__pyx_n_s_featurefile, __pyx_k_featurefile, sizeof(__pyx_k_featurefile), 0, 0, 1, 1}, - {&__pyx_n_s_featurefilepath, __pyx_k_featurefilepath, sizeof(__pyx_k_featurefilepath), 0, 0, 1, 1}, - {&__pyx_kp_u_features, __pyx_k_features, sizeof(__pyx_k_features), 0, 1, 0, 0}, - {&__pyx_n_s_file_or_path, __pyx_k_file_or_path, sizeof(__pyx_k_file_or_path), 0, 0, 1, 1}, - {&__pyx_n_s_filename, __pyx_k_filename, sizeof(__pyx_k_filename), 0, 0, 1, 1}, - {&__pyx_n_s_filename_2, __pyx_k_filename_2, sizeof(__pyx_k_filename_2), 0, 0, 1, 1}, - {&__pyx_n_s_fileobj, __pyx_k_fileobj, sizeof(__pyx_k_fileobj), 0, 0, 1, 1}, - {&__pyx_n_s_fname_location, __pyx_k_fname_location, sizeof(__pyx_k_fname_location), 0, 0, 1, 1}, - {&__pyx_n_s_fname_token, __pyx_k_fname_token, sizeof(__pyx_k_fname_token), 0, 0, 1, 1}, - {&__pyx_n_s_fname_type, __pyx_k_fname_type, sizeof(__pyx_k_fname_type), 0, 0, 1, 1}, - {&__pyx_n_s_fontTools_feaLib_error, __pyx_k_fontTools_feaLib_error, sizeof(__pyx_k_fontTools_feaLib_error), 0, 0, 1, 1}, - {&__pyx_n_s_fontTools_feaLib_lexer, __pyx_k_fontTools_feaLib_lexer, sizeof(__pyx_k_fontTools_feaLib_lexer), 0, 0, 1, 1}, - {&__pyx_n_s_fontTools_feaLib_location, __pyx_k_fontTools_feaLib_location, sizeof(__pyx_k_fontTools_feaLib_location), 0, 0, 1, 1}, - {&__pyx_n_s_getcwd, __pyx_k_getcwd, sizeof(__pyx_k_getcwd), 0, 0, 1, 1}, - {&__pyx_n_s_glyphclass, __pyx_k_glyphclass, sizeof(__pyx_k_glyphclass), 0, 0, 1, 1}, - {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, - {&__pyx_n_u_include, __pyx_k_include, sizeof(__pyx_k_include), 0, 1, 0, 1}, - {&__pyx_n_s_includeDir, __pyx_k_includeDir, sizeof(__pyx_k_includeDir), 0, 0, 1, 1}, - {&__pyx_n_s_init, __pyx_k_init, sizeof(__pyx_k_init), 0, 0, 1, 1}, - {&__pyx_n_s_isabs, __pyx_k_isabs, sizeof(__pyx_k_isabs), 0, 0, 1, 1}, - {&__pyx_n_s_iter, __pyx_k_iter, sizeof(__pyx_k_iter), 0, 0, 1, 1}, - {&__pyx_n_s_join, __pyx_k_join, sizeof(__pyx_k_join), 0, 0, 1, 1}, - {&__pyx_n_s_lexer, __pyx_k_lexer, sizeof(__pyx_k_lexer), 0, 0, 1, 1}, - {&__pyx_n_s_lexers, __pyx_k_lexers, sizeof(__pyx_k_lexers), 0, 0, 1, 1}, - {&__pyx_n_s_limit, __pyx_k_limit, sizeof(__pyx_k_limit), 0, 0, 1, 1}, - {&__pyx_n_s_line, __pyx_k_line, sizeof(__pyx_k_line), 0, 0, 1, 1}, - {&__pyx_n_s_line_start, __pyx_k_line_start, sizeof(__pyx_k_line_start), 0, 0, 1, 1}, - {&__pyx_n_s_location, __pyx_k_location, sizeof(__pyx_k_location), 0, 0, 1, 1}, - {&__pyx_n_s_location_2, __pyx_k_location_2, sizeof(__pyx_k_location_2), 0, 0, 1, 1}, - {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, - {&__pyx_n_s_make_lexer, __pyx_k_make_lexer, sizeof(__pyx_k_make_lexer), 0, 0, 1, 1}, - {&__pyx_n_s_match, __pyx_k_match, sizeof(__pyx_k_match), 0, 0, 1, 1}, - {&__pyx_n_s_maxsplit, __pyx_k_maxsplit, sizeof(__pyx_k_maxsplit), 0, 0, 1, 1}, - {&__pyx_n_s_metaclass, __pyx_k_metaclass, sizeof(__pyx_k_metaclass), 0, 0, 1, 1}, - {&__pyx_n_s_mode, __pyx_k_mode, sizeof(__pyx_k_mode), 0, 0, 1, 1}, - {&__pyx_n_s_module, __pyx_k_module, sizeof(__pyx_k_module), 0, 0, 1, 1}, - {&__pyx_n_u_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 1, 0, 1}, - {&__pyx_n_s_name_2, __pyx_k_name_2, sizeof(__pyx_k_name_2), 0, 0, 1, 1}, - {&__pyx_n_s_next, __pyx_k_next, sizeof(__pyx_k_next), 0, 0, 1, 1}, - {&__pyx_n_s_next_2, __pyx_k_next_2, sizeof(__pyx_k_next_2), 0, 0, 1, 1}, - {&__pyx_n_s_next_3, __pyx_k_next_3, sizeof(__pyx_k_next_3), 0, 0, 1, 1}, - {&__pyx_n_s_next_char, __pyx_k_next_char, sizeof(__pyx_k_next_char), 0, 0, 1, 1}, - {&__pyx_n_s_object, __pyx_k_object, sizeof(__pyx_k_object), 0, 0, 1, 1}, - {&__pyx_n_s_open, __pyx_k_open, sizeof(__pyx_k_open), 0, 0, 1, 1}, - {&__pyx_n_s_os, __pyx_k_os, sizeof(__pyx_k_os), 0, 0, 1, 1}, - {&__pyx_n_s_p, __pyx_k_p, sizeof(__pyx_k_p), 0, 0, 1, 1}, - {&__pyx_n_s_path, __pyx_k_path, sizeof(__pyx_k_path), 0, 0, 1, 1}, - {&__pyx_n_s_pop, __pyx_k_pop, sizeof(__pyx_k_pop), 0, 0, 1, 1}, - {&__pyx_n_s_pos, __pyx_k_pos, sizeof(__pyx_k_pos), 0, 0, 1, 1}, - {&__pyx_n_s_prepare, __pyx_k_prepare, sizeof(__pyx_k_prepare), 0, 0, 1, 1}, - {&__pyx_n_s_qualname, __pyx_k_qualname, sizeof(__pyx_k_qualname), 0, 0, 1, 1}, - {&__pyx_n_u_r, __pyx_k_r, sizeof(__pyx_k_r), 0, 1, 0, 1}, - {&__pyx_n_s_re, __pyx_k_re, sizeof(__pyx_k_re), 0, 0, 1, 1}, - {&__pyx_n_s_read, __pyx_k_read, sizeof(__pyx_k_read), 0, 0, 1, 1}, - {&__pyx_n_u_read, __pyx_k_read, sizeof(__pyx_k_read), 0, 1, 0, 1}, - {&__pyx_n_s_regexp, __pyx_k_regexp, sizeof(__pyx_k_regexp), 0, 0, 1, 1}, - {&__pyx_kp_u_s, __pyx_k_s, sizeof(__pyx_k_s), 0, 1, 0, 0}, - {&__pyx_kp_u_s_2, __pyx_k_s_2, sizeof(__pyx_k_s_2), 0, 1, 0, 0}, - {&__pyx_n_s_scan_anonymous_block, __pyx_k_scan_anonymous_block, sizeof(__pyx_k_scan_anonymous_block), 0, 0, 1, 1}, - {&__pyx_n_s_scan_over, __pyx_k_scan_over, sizeof(__pyx_k_scan_over), 0, 0, 1, 1}, - {&__pyx_n_s_scan_until, __pyx_k_scan_until, sizeof(__pyx_k_scan_until), 0, 0, 1, 1}, - {&__pyx_n_s_self, __pyx_k_self, sizeof(__pyx_k_self), 0, 0, 1, 1}, - {&__pyx_n_s_split, __pyx_k_split, sizeof(__pyx_k_split), 0, 0, 1, 1}, - {&__pyx_n_s_start, __pyx_k_start, sizeof(__pyx_k_start), 0, 0, 1, 1}, - {&__pyx_n_s_staticmethod, __pyx_k_staticmethod, sizeof(__pyx_k_staticmethod), 0, 0, 1, 1}, - {&__pyx_n_s_stop_at, __pyx_k_stop_at, sizeof(__pyx_k_stop_at), 0, 0, 1, 1}, - {&__pyx_n_s_string, __pyx_k_string, sizeof(__pyx_k_string), 0, 0, 1, 1}, - {&__pyx_n_s_strip, __pyx_k_strip, sizeof(__pyx_k_strip), 0, 0, 1, 1}, - {&__pyx_n_s_sub, __pyx_k_sub, sizeof(__pyx_k_sub), 0, 0, 1, 1}, - {&__pyx_n_s_tag, __pyx_k_tag, sizeof(__pyx_k_tag), 0, 0, 1, 1}, - {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, - {&__pyx_n_s_text, __pyx_k_text, sizeof(__pyx_k_text), 0, 0, 1, 1}, - {&__pyx_n_s_text_2, __pyx_k_text_2, sizeof(__pyx_k_text_2), 0, 0, 1, 1}, - {&__pyx_n_s_text_length, __pyx_k_text_length, sizeof(__pyx_k_text_length), 0, 0, 1, 1}, - {&__pyx_n_s_token, __pyx_k_token, sizeof(__pyx_k_token), 0, 0, 1, 1}, - {&__pyx_n_s_token_type, __pyx_k_token_type, sizeof(__pyx_k_token_type), 0, 0, 1, 1}, - {&__pyx_kp_u_utf_8, __pyx_k_utf_8, sizeof(__pyx_k_utf_8), 0, 1, 0, 0}, - {&__pyx_n_s_valid, __pyx_k_valid, sizeof(__pyx_k_valid), 0, 0, 1, 1}, - {&__pyx_n_u_xX, __pyx_k_xX, sizeof(__pyx_k_xX), 0, 1, 0, 1}, - {0, 0, 0, 0, 0, 0, 0} -}; -static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_n_s_ImportError); if (!__pyx_builtin_ImportError) __PYX_ERR(0, 8, __pyx_L1_error) - __pyx_builtin_object = __Pyx_GetBuiltinName(__pyx_n_s_object); if (!__pyx_builtin_object) __PYX_ERR(0, 13, __pyx_L1_error) - __pyx_builtin_staticmethod = __Pyx_GetBuiltinName(__pyx_n_s_staticmethod); if (!__pyx_builtin_staticmethod) __PYX_ERR(0, 270, __pyx_L1_error) - __pyx_builtin_StopIteration = __Pyx_GetBuiltinName(__pyx_n_s_StopIteration); if (!__pyx_builtin_StopIteration) __PYX_ERR(0, 75, __pyx_L1_error) - __pyx_builtin_open = __Pyx_GetBuiltinName(__pyx_n_s_open); if (!__pyx_builtin_open) __PYX_ERR(0, 276, __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/feaLib/lexer.py":13 - * - * - * class Lexer(object): # <<<<<<<<<<<<<< - * NUMBER = "NUMBER" - * HEXADECIMAL = "HEXADECIMAL" - */ - __pyx_tuple__13 = PyTuple_Pack(1, __pyx_builtin_object); if (unlikely(!__pyx_tuple__13)) __PYX_ERR(0, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__13); - __Pyx_GIVEREF(__pyx_tuple__13); - - /* "fontTools/feaLib/lexer.py":43 - * MODE_FILENAME_ = "FILENAME" - * - * def __init__(self, text, filename): # <<<<<<<<<<<<<< - * self.filename_ = filename - * self.line_ = 1 - */ - __pyx_tuple__19 = PyTuple_Pack(3, __pyx_n_s_self, __pyx_n_s_text, __pyx_n_s_filename); if (unlikely(!__pyx_tuple__19)) __PYX_ERR(0, 43, __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_feaLib_lexer_py, __pyx_n_s_init, 43, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__20)) __PYX_ERR(0, 43, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":52 - * self.mode_ = Lexer.MODE_NORMAL_ - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return self - * - */ - __pyx_tuple__21 = PyTuple_Pack(1, __pyx_n_s_self); if (unlikely(!__pyx_tuple__21)) __PYX_ERR(0, 52, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__21); - __Pyx_GIVEREF(__pyx_tuple__21); - __pyx_codeobj__22 = (PyObject*)__Pyx_PyCode_New(1, 0, 1, 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_feaLib_lexer_py, __pyx_n_s_iter, 52, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__22)) __PYX_ERR(0, 52, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":55 - * return self - * - * def next(self): # Python 2 # <<<<<<<<<<<<<< - * return self.__next__() - * - */ - __pyx_tuple__23 = PyTuple_Pack(1, __pyx_n_s_self); if (unlikely(!__pyx_tuple__23)) __PYX_ERR(0, 55, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__23); - __Pyx_GIVEREF(__pyx_tuple__23); - __pyx_codeobj__24 = (PyObject*)__Pyx_PyCode_New(1, 0, 1, 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_feaLib_lexer_py, __pyx_n_s_next_3, 55, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__24)) __PYX_ERR(0, 55, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":58 - * return self.__next__() - * - * def __next__(self): # Python 3 # <<<<<<<<<<<<<< - * while True: - * token_type, token, location = self.next_() - */ - __pyx_tuple__25 = PyTuple_Pack(4, __pyx_n_s_self, __pyx_n_s_token_type, __pyx_n_s_token, __pyx_n_s_location_2); if (unlikely(!__pyx_tuple__25)) __PYX_ERR(0, 58, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__25); - __Pyx_GIVEREF(__pyx_tuple__25); - __pyx_codeobj__26 = (PyObject*)__Pyx_PyCode_New(1, 0, 4, 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_feaLib_lexer_py, __pyx_n_s_next, 58, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__26)) __PYX_ERR(0, 58, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":64 - * return (token_type, token, location) - * - * def location_(self): # <<<<<<<<<<<<<< - * column = self.pos_ - self.line_start_ + 1 - * return FeatureLibLocation(self.filename_ or "", self.line_, column) - */ - __pyx_tuple__27 = PyTuple_Pack(2, __pyx_n_s_self, __pyx_n_s_column); if (unlikely(!__pyx_tuple__27)) __PYX_ERR(0, 64, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__27); - __Pyx_GIVEREF(__pyx_tuple__27); - __pyx_codeobj__28 = (PyObject*)__Pyx_PyCode_New(1, 0, 2, 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_feaLib_lexer_py, __pyx_n_s_location, 64, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__28)) __PYX_ERR(0, 64, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":68 - * return FeatureLibLocation(self.filename_ or "", self.line_, column) - * - * def next_(self): # <<<<<<<<<<<<<< - * self.scan_over_(Lexer.CHAR_WHITESPACE_) - * location = self.location_() - */ - __pyx_tuple__29 = PyTuple_Pack(10, __pyx_n_s_self, __pyx_n_s_location_2, __pyx_n_s_start, __pyx_n_s_text, __pyx_n_s_limit, __pyx_n_s_cur_char, __pyx_n_s_next_char, __pyx_n_s_glyphclass, __pyx_n_s_token, __pyx_n_s_string); if (unlikely(!__pyx_tuple__29)) __PYX_ERR(0, 68, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__29); - __Pyx_GIVEREF(__pyx_tuple__29); - __pyx_codeobj__30 = (PyObject*)__Pyx_PyCode_New(1, 0, 10, 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_feaLib_lexer_py, __pyx_n_s_next_2, 68, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__30)) __PYX_ERR(0, 68, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":169 - * raise FeatureLibError("Unexpected character: %r" % cur_char, location) - * - * def scan_over_(self, valid): # <<<<<<<<<<<<<< - * p = self.pos_ - * while p < self.text_length_ and self.text_[p] in valid: - */ - __pyx_tuple__31 = PyTuple_Pack(3, __pyx_n_s_self, __pyx_n_s_valid, __pyx_n_s_p); if (unlikely(!__pyx_tuple__31)) __PYX_ERR(0, 169, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__31); - __Pyx_GIVEREF(__pyx_tuple__31); - __pyx_codeobj__32 = (PyObject*)__Pyx_PyCode_New(2, 0, 3, 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_feaLib_lexer_py, __pyx_n_s_scan_over, 169, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__32)) __PYX_ERR(0, 169, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":175 - * self.pos_ = p - * - * def scan_until_(self, stop_at): # <<<<<<<<<<<<<< - * p = self.pos_ - * while p < self.text_length_ and self.text_[p] not in stop_at: - */ - __pyx_tuple__33 = PyTuple_Pack(3, __pyx_n_s_self, __pyx_n_s_stop_at, __pyx_n_s_p); if (unlikely(!__pyx_tuple__33)) __PYX_ERR(0, 175, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__33); - __Pyx_GIVEREF(__pyx_tuple__33); - __pyx_codeobj__34 = (PyObject*)__Pyx_PyCode_New(2, 0, 3, 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_feaLib_lexer_py, __pyx_n_s_scan_until, 175, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__34)) __PYX_ERR(0, 175, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":181 - * self.pos_ = p - * - * def scan_anonymous_block(self, tag): # <<<<<<<<<<<<<< - * location = self.location_() - * tag = tag.strip() - */ - __pyx_tuple__35 = PyTuple_Pack(5, __pyx_n_s_self, __pyx_n_s_tag, __pyx_n_s_location_2, __pyx_n_s_regexp, __pyx_n_s_split); if (unlikely(!__pyx_tuple__35)) __PYX_ERR(0, 181, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__35); - __Pyx_GIVEREF(__pyx_tuple__35); - __pyx_codeobj__36 = (PyObject*)__Pyx_PyCode_New(2, 0, 5, 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_feaLib_lexer_py, __pyx_n_s_scan_anonymous_block, 181, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__36)) __PYX_ERR(0, 181, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":196 - * - * - * class IncludingLexer(object): # <<<<<<<<<<<<<< - * """A Lexer that follows include statements. - * - */ - __pyx_tuple__37 = PyTuple_Pack(1, __pyx_builtin_object); if (unlikely(!__pyx_tuple__37)) __PYX_ERR(0, 196, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__37); - __Pyx_GIVEREF(__pyx_tuple__37); - - /* "fontTools/feaLib/lexer.py":211 - * """ - * - * def __init__(self, featurefile, *, includeDir=None): # <<<<<<<<<<<<<< - * """Initializes an IncludingLexer. - * - */ - __pyx_tuple__38 = PyTuple_Pack(3, __pyx_n_s_self, __pyx_n_s_featurefile, __pyx_n_s_includeDir); if (unlikely(!__pyx_tuple__38)) __PYX_ERR(0, 211, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__38); - __Pyx_GIVEREF(__pyx_tuple__38); - __pyx_codeobj__39 = (PyObject*)__Pyx_PyCode_New(2, 1, 3, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__38, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_feaLib_lexer_py, __pyx_n_s_init, 211, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__39)) __PYX_ERR(0, 211, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":225 - * self.includeDir = includeDir - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return self - * - */ - __pyx_tuple__40 = PyTuple_Pack(1, __pyx_n_s_self); if (unlikely(!__pyx_tuple__40)) __PYX_ERR(0, 225, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__40); - __Pyx_GIVEREF(__pyx_tuple__40); - __pyx_codeobj__41 = (PyObject*)__Pyx_PyCode_New(1, 0, 1, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__40, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_feaLib_lexer_py, __pyx_n_s_iter, 225, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__41)) __PYX_ERR(0, 225, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":228 - * return self - * - * def next(self): # Python 2 # <<<<<<<<<<<<<< - * return self.__next__() - * - */ - __pyx_tuple__42 = PyTuple_Pack(1, __pyx_n_s_self); if (unlikely(!__pyx_tuple__42)) __PYX_ERR(0, 228, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__42); - __Pyx_GIVEREF(__pyx_tuple__42); - __pyx_codeobj__43 = (PyObject*)__Pyx_PyCode_New(1, 0, 1, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__42, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_feaLib_lexer_py, __pyx_n_s_next_3, 228, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__43)) __PYX_ERR(0, 228, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":231 - * return self.__next__() - * - * def __next__(self): # Python 3 # <<<<<<<<<<<<<< - * while self.lexers_: - * lexer = self.lexers_[-1] - */ - __pyx_tuple__44 = PyTuple_Pack(11, __pyx_n_s_self, __pyx_n_s_lexer, __pyx_n_s_token_type, __pyx_n_s_token, __pyx_n_s_location_2, __pyx_n_s_fname_type, __pyx_n_s_fname_token, __pyx_n_s_fname_location, __pyx_n_s_path, __pyx_n_s_curpath, __pyx_n_s_err); if (unlikely(!__pyx_tuple__44)) __PYX_ERR(0, 231, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__44); - __Pyx_GIVEREF(__pyx_tuple__44); - __pyx_codeobj__45 = (PyObject*)__Pyx_PyCode_New(1, 0, 11, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__44, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_feaLib_lexer_py, __pyx_n_s_next, 231, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__45)) __PYX_ERR(0, 231, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":271 - * - * @staticmethod - * def make_lexer_(file_or_path): # <<<<<<<<<<<<<< - * if hasattr(file_or_path, "read"): - * fileobj, closing = file_or_path, False - */ - __pyx_tuple__46 = PyTuple_Pack(5, __pyx_n_s_file_or_path, __pyx_n_s_fileobj, __pyx_n_s_closing, __pyx_n_s_filename, __pyx_n_s_data); if (unlikely(!__pyx_tuple__46)) __PYX_ERR(0, 271, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__46); - __Pyx_GIVEREF(__pyx_tuple__46); - __pyx_codeobj__47 = (PyObject*)__Pyx_PyCode_New(1, 0, 5, 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_feaLib_lexer_py, __pyx_n_s_make_lexer, 271, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__47)) __PYX_ERR(0, 271, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":283 - * return Lexer(data, filename) - * - * def scan_anonymous_block(self, tag): # <<<<<<<<<<<<<< - * return self.lexers_[-1].scan_anonymous_block(tag) - * - */ - __pyx_tuple__48 = PyTuple_Pack(2, __pyx_n_s_self, __pyx_n_s_tag); if (unlikely(!__pyx_tuple__48)) __PYX_ERR(0, 283, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__48); - __Pyx_GIVEREF(__pyx_tuple__48); - __pyx_codeobj__49 = (PyObject*)__Pyx_PyCode_New(2, 0, 2, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__48, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_feaLib_lexer_py, __pyx_n_s_scan_anonymous_block, 283, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__49)) __PYX_ERR(0, 283, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":290 - * """Lexer that does not follow `include` statements, emits them as-is.""" - * - * def __next__(self): # Python 3 # <<<<<<<<<<<<<< - * return next(self.lexers_[0]) - */ - __pyx_tuple__50 = PyTuple_Pack(1, __pyx_n_s_self); if (unlikely(!__pyx_tuple__50)) __PYX_ERR(0, 290, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__50); - __Pyx_GIVEREF(__pyx_tuple__50); - __pyx_codeobj__51 = (PyObject*)__Pyx_PyCode_New(1, 0, 1, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__50, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_feaLib_lexer_py, __pyx_n_s_next, 290, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__51)) __PYX_ERR(0, 290, __pyx_L1_error) - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { - __pyx_umethod_PyList_Type_pop.type = (PyObject*)&PyList_Type; - if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_8 = PyInt_FromLong(8); if (unlikely(!__pyx_int_8)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_10 = PyInt_FromLong(10); if (unlikely(!__pyx_int_10)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_16 = PyInt_FromLong(16); if (unlikely(!__pyx_int_16)) __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 - __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); - /*--- Type init code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -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 initlexer(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC initlexer(void) -#else -__Pyx_PyMODINIT_FUNC PyInit_lexer(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC PyInit_lexer(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_lexer(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; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - 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 'lexer' 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_lexer(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("lexer", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); - #else - __pyx_m = PyModule_Create(&__pyx_moduledef); - #endif - if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_d); - __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_b); - __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_cython_runtime); - if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - /*--- Initialize various global constants etc. ---*/ - if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) - if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - if (__pyx_module_is_main_fontTools__feaLib__lexer) { - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name_2, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - } - #if PY_MAJOR_VERSION >= 3 - { - PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) - if (!PyDict_GetItemString(modules, "fontTools.feaLib.lexer")) { - if (unlikely(PyDict_SetItemString(modules, "fontTools.feaLib.lexer", __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(); - (void)__Pyx_modinit_type_init_code(); - (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/feaLib/lexer.py":1 - * from fontTools.feaLib.error import FeatureLibError, IncludedFeaNotFound # <<<<<<<<<<<<<< - * from fontTools.feaLib.location import FeatureLibLocation - * import re - */ - __pyx_t_1 = PyList_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_s_FeatureLibError); - __Pyx_GIVEREF(__pyx_n_s_FeatureLibError); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_FeatureLibError); - __Pyx_INCREF(__pyx_n_s_IncludedFeaNotFound); - __Pyx_GIVEREF(__pyx_n_s_IncludedFeaNotFound); - PyList_SET_ITEM(__pyx_t_1, 1, __pyx_n_s_IncludedFeaNotFound); - __pyx_t_2 = __Pyx_Import(__pyx_n_s_fontTools_feaLib_error, __pyx_t_1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __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_FeatureLibError); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_FeatureLibError, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_IncludedFeaNotFound); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_IncludedFeaNotFound, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":2 - * from fontTools.feaLib.error import FeatureLibError, IncludedFeaNotFound - * from fontTools.feaLib.location import FeatureLibLocation # <<<<<<<<<<<<<< - * import re - * import os - */ - __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_n_s_FeatureLibLocation); - __Pyx_GIVEREF(__pyx_n_s_FeatureLibLocation); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_FeatureLibLocation); - __pyx_t_1 = __Pyx_Import(__pyx_n_s_fontTools_feaLib_location, __pyx_t_2, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2, __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_FeatureLibLocation); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_FeatureLibLocation, __pyx_t_2) < 0) __PYX_ERR(0, 2, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":3 - * from fontTools.feaLib.error import FeatureLibError, IncludedFeaNotFound - * from fontTools.feaLib.location import FeatureLibLocation - * import re # <<<<<<<<<<<<<< - * import os - * - */ - __pyx_t_1 = __Pyx_Import(__pyx_n_s_re, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 3, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_re, __pyx_t_1) < 0) __PYX_ERR(0, 3, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":4 - * from fontTools.feaLib.location import FeatureLibLocation - * import re - * import os # <<<<<<<<<<<<<< - * - * try: - */ - __pyx_t_1 = __Pyx_Import(__pyx_n_s_os, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_os, __pyx_t_1) < 0) __PYX_ERR(0, 4, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":6 - * import os - * - * try: # <<<<<<<<<<<<<< - * import cython - * except ImportError: - */ - { - (void)__pyx_t_3; (void)__pyx_t_4; (void)__pyx_t_5; /* mark used */ - /*try:*/ { - - /* "fontTools/feaLib/lexer.py":7 - * - * try: - * import cython # <<<<<<<<<<<<<< - * except ImportError: - * # if cython not installed, use mock module with no-op decorators and types - */ - } - } - - /* "fontTools/feaLib/lexer.py":13 - * - * - * class Lexer(object): # <<<<<<<<<<<<<< - * NUMBER = "NUMBER" - * HEXADECIMAL = "HEXADECIMAL" - */ - __pyx_t_1 = __Pyx_CalculateMetaclass(NULL, __pyx_tuple__13); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_Py3MetaclassPrepare(__pyx_t_1, __pyx_tuple__13, __pyx_n_s_Lexer, __pyx_n_s_Lexer, (PyObject *) NULL, __pyx_n_s_fontTools_feaLib_lexer, (PyObject *) NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - - /* "fontTools/feaLib/lexer.py":14 - * - * class Lexer(object): - * NUMBER = "NUMBER" # <<<<<<<<<<<<<< - * HEXADECIMAL = "HEXADECIMAL" - * OCTAL = "OCTAL" - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_NUMBER, __pyx_n_u_NUMBER) < 0) __PYX_ERR(0, 14, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":15 - * class Lexer(object): - * NUMBER = "NUMBER" - * HEXADECIMAL = "HEXADECIMAL" # <<<<<<<<<<<<<< - * OCTAL = "OCTAL" - * NUMBERS = (NUMBER, HEXADECIMAL, OCTAL) - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_HEXADECIMAL, __pyx_n_u_HEXADECIMAL) < 0) __PYX_ERR(0, 15, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":16 - * NUMBER = "NUMBER" - * HEXADECIMAL = "HEXADECIMAL" - * OCTAL = "OCTAL" # <<<<<<<<<<<<<< - * NUMBERS = (NUMBER, HEXADECIMAL, OCTAL) - * FLOAT = "FLOAT" - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_OCTAL, __pyx_n_u_OCTAL) < 0) __PYX_ERR(0, 16, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":17 - * HEXADECIMAL = "HEXADECIMAL" - * OCTAL = "OCTAL" - * NUMBERS = (NUMBER, HEXADECIMAL, OCTAL) # <<<<<<<<<<<<<< - * FLOAT = "FLOAT" - * STRING = "STRING" - */ - __pyx_t_6 = PyObject_GetItem(__pyx_t_2, __pyx_n_s_NUMBER); - if (unlikely(!__pyx_t_6)) { - PyErr_Clear(); - __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_NUMBER); - } - if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 17, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = PyObject_GetItem(__pyx_t_2, __pyx_n_s_HEXADECIMAL); - if (unlikely(!__pyx_t_7)) { - PyErr_Clear(); - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_HEXADECIMAL); - } - if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 17, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_8 = PyObject_GetItem(__pyx_t_2, __pyx_n_s_OCTAL); - if (unlikely(!__pyx_t_8)) { - PyErr_Clear(); - __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_n_s_OCTAL); - } - if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 17, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_9 = PyTuple_New(3); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 17, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_8); - PyTuple_SET_ITEM(__pyx_t_9, 2, __pyx_t_8); - __pyx_t_6 = 0; - __pyx_t_7 = 0; - __pyx_t_8 = 0; - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_NUMBERS, __pyx_t_9) < 0) __PYX_ERR(0, 17, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":18 - * OCTAL = "OCTAL" - * NUMBERS = (NUMBER, HEXADECIMAL, OCTAL) - * FLOAT = "FLOAT" # <<<<<<<<<<<<<< - * STRING = "STRING" - * NAME = "NAME" - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_FLOAT, __pyx_n_u_FLOAT) < 0) __PYX_ERR(0, 18, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":19 - * NUMBERS = (NUMBER, HEXADECIMAL, OCTAL) - * FLOAT = "FLOAT" - * STRING = "STRING" # <<<<<<<<<<<<<< - * NAME = "NAME" - * FILENAME = "FILENAME" - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_STRING, __pyx_n_u_STRING) < 0) __PYX_ERR(0, 19, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":20 - * FLOAT = "FLOAT" - * STRING = "STRING" - * NAME = "NAME" # <<<<<<<<<<<<<< - * FILENAME = "FILENAME" - * GLYPHCLASS = "GLYPHCLASS" - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_NAME, __pyx_n_u_NAME) < 0) __PYX_ERR(0, 20, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":21 - * STRING = "STRING" - * NAME = "NAME" - * FILENAME = "FILENAME" # <<<<<<<<<<<<<< - * GLYPHCLASS = "GLYPHCLASS" - * CID = "CID" - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_FILENAME, __pyx_n_u_FILENAME) < 0) __PYX_ERR(0, 21, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":22 - * NAME = "NAME" - * FILENAME = "FILENAME" - * GLYPHCLASS = "GLYPHCLASS" # <<<<<<<<<<<<<< - * CID = "CID" - * SYMBOL = "SYMBOL" - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_GLYPHCLASS, __pyx_n_u_GLYPHCLASS) < 0) __PYX_ERR(0, 22, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":23 - * FILENAME = "FILENAME" - * GLYPHCLASS = "GLYPHCLASS" - * CID = "CID" # <<<<<<<<<<<<<< - * SYMBOL = "SYMBOL" - * COMMENT = "COMMENT" - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_CID, __pyx_n_u_CID) < 0) __PYX_ERR(0, 23, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":24 - * GLYPHCLASS = "GLYPHCLASS" - * CID = "CID" - * SYMBOL = "SYMBOL" # <<<<<<<<<<<<<< - * COMMENT = "COMMENT" - * NEWLINE = "NEWLINE" - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_SYMBOL, __pyx_n_u_SYMBOL) < 0) __PYX_ERR(0, 24, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":25 - * CID = "CID" - * SYMBOL = "SYMBOL" - * COMMENT = "COMMENT" # <<<<<<<<<<<<<< - * NEWLINE = "NEWLINE" - * ANONYMOUS_BLOCK = "ANONYMOUS_BLOCK" - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_COMMENT, __pyx_n_u_COMMENT) < 0) __PYX_ERR(0, 25, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":26 - * SYMBOL = "SYMBOL" - * COMMENT = "COMMENT" - * NEWLINE = "NEWLINE" # <<<<<<<<<<<<<< - * ANONYMOUS_BLOCK = "ANONYMOUS_BLOCK" - * - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_NEWLINE, __pyx_n_u_NEWLINE) < 0) __PYX_ERR(0, 26, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":27 - * COMMENT = "COMMENT" - * NEWLINE = "NEWLINE" - * ANONYMOUS_BLOCK = "ANONYMOUS_BLOCK" # <<<<<<<<<<<<<< - * - * CHAR_WHITESPACE_ = " \t" - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_ANONYMOUS_BLOCK, __pyx_n_u_ANONYMOUS_BLOCK) < 0) __PYX_ERR(0, 27, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":29 - * ANONYMOUS_BLOCK = "ANONYMOUS_BLOCK" - * - * CHAR_WHITESPACE_ = " \t" # <<<<<<<<<<<<<< - * CHAR_NEWLINE_ = "\r\n" - * CHAR_SYMBOL_ = ",;:-+'{}[]<>()=" - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_CHAR_WHITESPACE, __pyx_kp_u__14) < 0) __PYX_ERR(0, 29, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":30 - * - * CHAR_WHITESPACE_ = " \t" - * CHAR_NEWLINE_ = "\r\n" # <<<<<<<<<<<<<< - * CHAR_SYMBOL_ = ",;:-+'{}[]<>()=" - * CHAR_DIGIT_ = "0123456789" - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_CHAR_NEWLINE, __pyx_kp_u__15) < 0) __PYX_ERR(0, 30, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":31 - * CHAR_WHITESPACE_ = " \t" - * CHAR_NEWLINE_ = "\r\n" - * CHAR_SYMBOL_ = ",;:-+'{}[]<>()=" # <<<<<<<<<<<<<< - * CHAR_DIGIT_ = "0123456789" - * CHAR_HEXDIGIT_ = "0123456789ABCDEFabcdef" - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_CHAR_SYMBOL, __pyx_kp_u__16) < 0) __PYX_ERR(0, 31, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":32 - * CHAR_NEWLINE_ = "\r\n" - * CHAR_SYMBOL_ = ",;:-+'{}[]<>()=" - * CHAR_DIGIT_ = "0123456789" # <<<<<<<<<<<<<< - * CHAR_HEXDIGIT_ = "0123456789ABCDEFabcdef" - * CHAR_LETTER_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_CHAR_DIGIT, __pyx_kp_u_0123456789) < 0) __PYX_ERR(0, 32, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":33 - * CHAR_SYMBOL_ = ",;:-+'{}[]<>()=" - * CHAR_DIGIT_ = "0123456789" - * CHAR_HEXDIGIT_ = "0123456789ABCDEFabcdef" # <<<<<<<<<<<<<< - * CHAR_LETTER_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" - * CHAR_NAME_START_ = CHAR_LETTER_ + "_+*:.^~!\\" - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_CHAR_HEXDIGIT, __pyx_kp_u_0123456789ABCDEFabcdef) < 0) __PYX_ERR(0, 33, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":34 - * CHAR_DIGIT_ = "0123456789" - * CHAR_HEXDIGIT_ = "0123456789ABCDEFabcdef" - * CHAR_LETTER_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" # <<<<<<<<<<<<<< - * CHAR_NAME_START_ = CHAR_LETTER_ + "_+*:.^~!\\" - * CHAR_NAME_CONTINUATION_ = CHAR_LETTER_ + CHAR_DIGIT_ + "_.+*:^~!/-" - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_CHAR_LETTER, __pyx_n_u_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef) < 0) __PYX_ERR(0, 34, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":35 - * CHAR_HEXDIGIT_ = "0123456789ABCDEFabcdef" - * CHAR_LETTER_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" - * CHAR_NAME_START_ = CHAR_LETTER_ + "_+*:.^~!\\" # <<<<<<<<<<<<<< - * CHAR_NAME_CONTINUATION_ = CHAR_LETTER_ + CHAR_DIGIT_ + "_.+*:^~!/-" - * - */ - __pyx_t_9 = PyObject_GetItem(__pyx_t_2, __pyx_n_s_CHAR_LETTER); - if (unlikely(!__pyx_t_9)) { - PyErr_Clear(); - __Pyx_GetModuleGlobalName(__pyx_t_9, __pyx_n_s_CHAR_LETTER); - } - if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 35, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_8 = PyNumber_Add(__pyx_t_9, __pyx_kp_u__17); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 35, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_CHAR_NAME_START, __pyx_t_8) < 0) __PYX_ERR(0, 35, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - - /* "fontTools/feaLib/lexer.py":36 - * CHAR_LETTER_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" - * CHAR_NAME_START_ = CHAR_LETTER_ + "_+*:.^~!\\" - * CHAR_NAME_CONTINUATION_ = CHAR_LETTER_ + CHAR_DIGIT_ + "_.+*:^~!/-" # <<<<<<<<<<<<<< - * - * RE_GLYPHCLASS = re.compile(r"^[A-Za-z_0-9.\-]+$") - */ - __pyx_t_8 = PyObject_GetItem(__pyx_t_2, __pyx_n_s_CHAR_LETTER); - if (unlikely(!__pyx_t_8)) { - PyErr_Clear(); - __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_n_s_CHAR_LETTER); - } - if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 36, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_9 = PyObject_GetItem(__pyx_t_2, __pyx_n_s_CHAR_DIGIT); - if (unlikely(!__pyx_t_9)) { - PyErr_Clear(); - __Pyx_GetModuleGlobalName(__pyx_t_9, __pyx_n_s_CHAR_DIGIT); - } - if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 36, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_7 = PyNumber_Add(__pyx_t_8, __pyx_t_9); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 36, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_9 = PyNumber_Add(__pyx_t_7, __pyx_kp_u__18); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 36, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_CHAR_NAME_CONTINUATION, __pyx_t_9) < 0) __PYX_ERR(0, 36, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":38 - * CHAR_NAME_CONTINUATION_ = CHAR_LETTER_ + CHAR_DIGIT_ + "_.+*:^~!/-" - * - * RE_GLYPHCLASS = re.compile(r"^[A-Za-z_0-9.\-]+$") # <<<<<<<<<<<<<< - * - * MODE_NORMAL_ = "NORMAL" - */ - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_re); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 38, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_compile); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 38, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_8))) { - __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_8); - if (likely(__pyx_t_7)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_8); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_8, function); - } - } - __pyx_t_9 = (__pyx_t_7) ? __Pyx_PyObject_Call2Args(__pyx_t_8, __pyx_t_7, __pyx_kp_u_A_Za_z_0_9) : __Pyx_PyObject_CallOneArg(__pyx_t_8, __pyx_kp_u_A_Za_z_0_9); - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 38, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_RE_GLYPHCLASS, __pyx_t_9) < 0) __PYX_ERR(0, 38, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":40 - * RE_GLYPHCLASS = re.compile(r"^[A-Za-z_0-9.\-]+$") - * - * MODE_NORMAL_ = "NORMAL" # <<<<<<<<<<<<<< - * MODE_FILENAME_ = "FILENAME" - * - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_MODE_NORMAL, __pyx_n_u_NORMAL) < 0) __PYX_ERR(0, 40, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":41 - * - * MODE_NORMAL_ = "NORMAL" - * MODE_FILENAME_ = "FILENAME" # <<<<<<<<<<<<<< - * - * def __init__(self, text, filename): - */ - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_MODE_FILENAME, __pyx_n_u_FILENAME) < 0) __PYX_ERR(0, 41, __pyx_L1_error) - - /* "fontTools/feaLib/lexer.py":43 - * MODE_FILENAME_ = "FILENAME" - * - * def __init__(self, text, filename): # <<<<<<<<<<<<<< - * self.filename_ = filename - * self.line_ = 1 - */ - __pyx_t_9 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6feaLib_5lexer_5Lexer_1__init__, 0, __pyx_n_s_Lexer___init, NULL, __pyx_n_s_fontTools_feaLib_lexer, __pyx_d, ((PyObject *)__pyx_codeobj__20)); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 43, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_init, __pyx_t_9) < 0) __PYX_ERR(0, 43, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":52 - * self.mode_ = Lexer.MODE_NORMAL_ - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return self - * - */ - __pyx_t_9 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6feaLib_5lexer_5Lexer_3__iter__, 0, __pyx_n_s_Lexer___iter, NULL, __pyx_n_s_fontTools_feaLib_lexer, __pyx_d, ((PyObject *)__pyx_codeobj__22)); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 52, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_iter, __pyx_t_9) < 0) __PYX_ERR(0, 52, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":55 - * return self - * - * def next(self): # Python 2 # <<<<<<<<<<<<<< - * return self.__next__() - * - */ - __pyx_t_9 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6feaLib_5lexer_5Lexer_5next, 0, __pyx_n_s_Lexer_next, NULL, __pyx_n_s_fontTools_feaLib_lexer, __pyx_d, ((PyObject *)__pyx_codeobj__24)); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 55, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_next_3, __pyx_t_9) < 0) __PYX_ERR(0, 55, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":58 - * return self.__next__() - * - * def __next__(self): # Python 3 # <<<<<<<<<<<<<< - * while True: - * token_type, token, location = self.next_() - */ - __pyx_t_9 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6feaLib_5lexer_5Lexer_7__next__, 0, __pyx_n_s_Lexer___next, NULL, __pyx_n_s_fontTools_feaLib_lexer, __pyx_d, ((PyObject *)__pyx_codeobj__26)); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 58, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_next, __pyx_t_9) < 0) __PYX_ERR(0, 58, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":64 - * return (token_type, token, location) - * - * def location_(self): # <<<<<<<<<<<<<< - * column = self.pos_ - self.line_start_ + 1 - * return FeatureLibLocation(self.filename_ or "", self.line_, column) - */ - __pyx_t_9 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6feaLib_5lexer_5Lexer_9location_, 0, __pyx_n_s_Lexer_location, NULL, __pyx_n_s_fontTools_feaLib_lexer, __pyx_d, ((PyObject *)__pyx_codeobj__28)); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 64, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_location, __pyx_t_9) < 0) __PYX_ERR(0, 64, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":68 - * return FeatureLibLocation(self.filename_ or "", self.line_, column) - * - * def next_(self): # <<<<<<<<<<<<<< - * self.scan_over_(Lexer.CHAR_WHITESPACE_) - * location = self.location_() - */ - __pyx_t_9 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6feaLib_5lexer_5Lexer_11next_, 0, __pyx_n_s_Lexer_next_2, NULL, __pyx_n_s_fontTools_feaLib_lexer, __pyx_d, ((PyObject *)__pyx_codeobj__30)); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 68, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_next_2, __pyx_t_9) < 0) __PYX_ERR(0, 68, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":169 - * raise FeatureLibError("Unexpected character: %r" % cur_char, location) - * - * def scan_over_(self, valid): # <<<<<<<<<<<<<< - * p = self.pos_ - * while p < self.text_length_ and self.text_[p] in valid: - */ - __pyx_t_9 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6feaLib_5lexer_5Lexer_13scan_over_, 0, __pyx_n_s_Lexer_scan_over, NULL, __pyx_n_s_fontTools_feaLib_lexer, __pyx_d, ((PyObject *)__pyx_codeobj__32)); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 169, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_scan_over, __pyx_t_9) < 0) __PYX_ERR(0, 169, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":175 - * self.pos_ = p - * - * def scan_until_(self, stop_at): # <<<<<<<<<<<<<< - * p = self.pos_ - * while p < self.text_length_ and self.text_[p] not in stop_at: - */ - __pyx_t_9 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6feaLib_5lexer_5Lexer_15scan_until_, 0, __pyx_n_s_Lexer_scan_until, NULL, __pyx_n_s_fontTools_feaLib_lexer, __pyx_d, ((PyObject *)__pyx_codeobj__34)); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 175, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_scan_until, __pyx_t_9) < 0) __PYX_ERR(0, 175, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":181 - * self.pos_ = p - * - * def scan_anonymous_block(self, tag): # <<<<<<<<<<<<<< - * location = self.location_() - * tag = tag.strip() - */ - __pyx_t_9 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6feaLib_5lexer_5Lexer_17scan_anonymous_block, 0, __pyx_n_s_Lexer_scan_anonymous_block, NULL, __pyx_n_s_fontTools_feaLib_lexer, __pyx_d, ((PyObject *)__pyx_codeobj__36)); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 181, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_scan_anonymous_block, __pyx_t_9) < 0) __PYX_ERR(0, 181, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":13 - * - * - * class Lexer(object): # <<<<<<<<<<<<<< - * NUMBER = "NUMBER" - * HEXADECIMAL = "HEXADECIMAL" - */ - __pyx_t_9 = __Pyx_Py3ClassCreate(__pyx_t_1, __pyx_n_s_Lexer, __pyx_tuple__13, __pyx_t_2, NULL, 0, 0); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_Lexer, __pyx_t_9) < 0) __PYX_ERR(0, 13, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":196 - * - * - * class IncludingLexer(object): # <<<<<<<<<<<<<< - * """A Lexer that follows include statements. - * - */ - __pyx_t_1 = __Pyx_CalculateMetaclass(NULL, __pyx_tuple__37); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 196, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_Py3MetaclassPrepare(__pyx_t_1, __pyx_tuple__37, __pyx_n_s_IncludingLexer, __pyx_n_s_IncludingLexer, (PyObject *) NULL, __pyx_n_s_fontTools_feaLib_lexer, __pyx_kp_s_A_Lexer_that_follows_include_sta); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 196, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - - /* "fontTools/feaLib/lexer.py":211 - * """ - * - * def __init__(self, featurefile, *, includeDir=None): # <<<<<<<<<<<<<< - * """Initializes an IncludingLexer. - * - */ - __pyx_t_9 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 211, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - if (PyDict_SetItem(__pyx_t_9, __pyx_n_s_includeDir, ((PyObject *)Py_None)) < 0) __PYX_ERR(0, 211, __pyx_L1_error) - __pyx_t_8 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6feaLib_5lexer_14IncludingLexer_1__init__, 0, __pyx_n_s_IncludingLexer___init, NULL, __pyx_n_s_fontTools_feaLib_lexer, __pyx_d, ((PyObject *)__pyx_codeobj__39)); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 211, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_CyFunction_SetDefaultsKwDict(__pyx_t_8, __pyx_t_9); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_init, __pyx_t_8) < 0) __PYX_ERR(0, 211, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - - /* "fontTools/feaLib/lexer.py":225 - * self.includeDir = includeDir - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return self - * - */ - __pyx_t_8 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6feaLib_5lexer_14IncludingLexer_3__iter__, 0, __pyx_n_s_IncludingLexer___iter, NULL, __pyx_n_s_fontTools_feaLib_lexer, __pyx_d, ((PyObject *)__pyx_codeobj__41)); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 225, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_iter, __pyx_t_8) < 0) __PYX_ERR(0, 225, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - - /* "fontTools/feaLib/lexer.py":228 - * return self - * - * def next(self): # Python 2 # <<<<<<<<<<<<<< - * return self.__next__() - * - */ - __pyx_t_8 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6feaLib_5lexer_14IncludingLexer_5next, 0, __pyx_n_s_IncludingLexer_next, NULL, __pyx_n_s_fontTools_feaLib_lexer, __pyx_d, ((PyObject *)__pyx_codeobj__43)); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 228, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_next_3, __pyx_t_8) < 0) __PYX_ERR(0, 228, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - - /* "fontTools/feaLib/lexer.py":231 - * return self.__next__() - * - * def __next__(self): # Python 3 # <<<<<<<<<<<<<< - * while self.lexers_: - * lexer = self.lexers_[-1] - */ - __pyx_t_8 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6feaLib_5lexer_14IncludingLexer_7__next__, 0, __pyx_n_s_IncludingLexer___next, NULL, __pyx_n_s_fontTools_feaLib_lexer, __pyx_d, ((PyObject *)__pyx_codeobj__45)); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 231, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_next, __pyx_t_8) < 0) __PYX_ERR(0, 231, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - - /* "fontTools/feaLib/lexer.py":271 - * - * @staticmethod - * def make_lexer_(file_or_path): # <<<<<<<<<<<<<< - * if hasattr(file_or_path, "read"): - * fileobj, closing = file_or_path, False - */ - __pyx_t_8 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6feaLib_5lexer_14IncludingLexer_9make_lexer_, __Pyx_CYFUNCTION_STATICMETHOD, __pyx_n_s_IncludingLexer_make_lexer, NULL, __pyx_n_s_fontTools_feaLib_lexer, __pyx_d, ((PyObject *)__pyx_codeobj__47)); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 271, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - - /* "fontTools/feaLib/lexer.py":270 - * raise StopIteration() - * - * @staticmethod # <<<<<<<<<<<<<< - * def make_lexer_(file_or_path): - * if hasattr(file_or_path, "read"): - */ - __pyx_t_9 = __Pyx_PyObject_CallOneArg(__pyx_builtin_staticmethod, __pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 270, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_make_lexer, __pyx_t_9) < 0) __PYX_ERR(0, 271, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":283 - * return Lexer(data, filename) - * - * def scan_anonymous_block(self, tag): # <<<<<<<<<<<<<< - * return self.lexers_[-1].scan_anonymous_block(tag) - * - */ - __pyx_t_9 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6feaLib_5lexer_14IncludingLexer_11scan_anonymous_block, 0, __pyx_n_s_IncludingLexer_scan_anonymous_bl, NULL, __pyx_n_s_fontTools_feaLib_lexer, __pyx_d, ((PyObject *)__pyx_codeobj__49)); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 283, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - if (__Pyx_SetNameInClass(__pyx_t_2, __pyx_n_s_scan_anonymous_block, __pyx_t_9) < 0) __PYX_ERR(0, 283, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "fontTools/feaLib/lexer.py":196 - * - * - * class IncludingLexer(object): # <<<<<<<<<<<<<< - * """A Lexer that follows include statements. - * - */ - __pyx_t_9 = __Pyx_Py3ClassCreate(__pyx_t_1, __pyx_n_s_IncludingLexer, __pyx_tuple__37, __pyx_t_2, NULL, 0, 0); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 196, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_IncludingLexer, __pyx_t_9) < 0) __PYX_ERR(0, 196, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/feaLib/lexer.py":287 - * - * - * class NonIncludingLexer(IncludingLexer): # <<<<<<<<<<<<<< - * """Lexer that does not follow `include` statements, emits them as-is.""" - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_IncludingLexer); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 287, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 287, __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_CalculateMetaclass(NULL, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 287, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_9 = __Pyx_Py3MetaclassPrepare(__pyx_t_1, __pyx_t_2, __pyx_n_s_NonIncludingLexer, __pyx_n_s_NonIncludingLexer, (PyObject *) NULL, __pyx_n_s_fontTools_feaLib_lexer, __pyx_kp_s_Lexer_that_does_not_follow_inclu); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 287, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - - /* "fontTools/feaLib/lexer.py":290 - * """Lexer that does not follow `include` statements, emits them as-is.""" - * - * def __next__(self): # Python 3 # <<<<<<<<<<<<<< - * return next(self.lexers_[0]) - */ - __pyx_t_8 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6feaLib_5lexer_17NonIncludingLexer_1__next__, 0, __pyx_n_s_NonIncludingLexer___next, NULL, __pyx_n_s_fontTools_feaLib_lexer, __pyx_d, ((PyObject *)__pyx_codeobj__51)); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 290, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - if (__Pyx_SetNameInClass(__pyx_t_9, __pyx_n_s_next, __pyx_t_8) < 0) __PYX_ERR(0, 290, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - - /* "fontTools/feaLib/lexer.py":287 - * - * - * class NonIncludingLexer(IncludingLexer): # <<<<<<<<<<<<<< - * """Lexer that does not follow `include` statements, emits them as-is.""" - * - */ - __pyx_t_8 = __Pyx_Py3ClassCreate(__pyx_t_1, __pyx_n_s_NonIncludingLexer, __pyx_t_2, __pyx_t_9, NULL, 0, 0); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 287, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_NonIncludingLexer, __pyx_t_8) < 0) __PYX_ERR(0, 287, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/feaLib/lexer.py":1 - * from fontTools.feaLib.error import FeatureLibError, IncludedFeaNotFound # <<<<<<<<<<<<<< - * from fontTools.feaLib.location import FeatureLibLocation - * import re - */ - __pyx_t_2 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - 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_6); - __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.feaLib.lexer", __pyx_clineno, __pyx_lineno, __pyx_filename); - } - Py_CLEAR(__pyx_m); - } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init fontTools.feaLib.lexer"); - } - __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; -} - -/* PyObjectSetAttrStr */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE int __Pyx_PyObject_SetAttrStr(PyObject* obj, PyObject* attr_name, PyObject* value) { - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_setattro)) - return tp->tp_setattro(obj, attr_name, value); -#if PY_MAJOR_VERSION < 3 - if (likely(tp->tp_setattr)) - return tp->tp_setattr(obj, PyString_AS_STRING(attr_name), value); -#endif - return PyObject_SetAttr(obj, attr_name, value); -} -#endif - -/* 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); -} - -/* 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 - -/* 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 - -/* 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 - -/* 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 - -/* 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 - -/* 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 - -/* 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 -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 - -/* 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; -} - -/* PyErrFetchRestore */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - tmp_type = tstate->curexc_type; - tmp_value = tstate->curexc_value; - tmp_tb = tstate->curexc_traceback; - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} -static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - *type = tstate->curexc_type; - *value = tstate->curexc_value; - *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -} -#endif - -/* RaiseException */ -#if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, - CYTHON_UNUSED PyObject *cause) { - __Pyx_PyThreadState_declare - Py_XINCREF(type); - if (!value || value == Py_None) - value = NULL; - else - Py_INCREF(value); - if (!tb || tb == Py_None) - tb = NULL; - else { - Py_INCREF(tb); - if (!PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - } - if (PyType_Check(type)) { -#if CYTHON_COMPILING_IN_PYPY - if (!value) { - Py_INCREF(Py_None); - value = Py_None; - } -#endif - PyErr_NormalizeException(&type, &value, &tb); - } else { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto raise_error; - } - value = type; - type = (PyObject*) Py_TYPE(type); - Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } - } - __Pyx_PyThreadState_assign - __Pyx_ErrRestore(type, value, tb); - return; -raise_error: - Py_XDECREF(value); - Py_XDECREF(type); - Py_XDECREF(tb); - return; -} -#else -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - PyObject* owned_instance = NULL; - if (tb == Py_None) { - tb = 0; - } else if (tb && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto bad; - } - if (value == Py_None) - value = 0; - if (PyExceptionInstance_Check(type)) { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto bad; - } - value = type; - type = (PyObject*) Py_TYPE(value); - } else if (PyExceptionClass_Check(type)) { - PyObject *instance_class = NULL; - if (value && PyExceptionInstance_Check(value)) { - instance_class = (PyObject*) Py_TYPE(value); - if (instance_class != type) { - int is_subclass = PyObject_IsSubclass(instance_class, type); - if (!is_subclass) { - instance_class = NULL; - } else if (unlikely(is_subclass == -1)) { - goto bad; - } else { - type = instance_class; - } - } - } - if (!instance_class) { - PyObject *args; - if (!value) - args = PyTuple_New(0); - else if (PyTuple_Check(value)) { - Py_INCREF(value); - args = value; - } else - args = PyTuple_Pack(1, value); - if (!args) - goto bad; - owned_instance = PyObject_Call(type, args, NULL); - Py_DECREF(args); - if (!owned_instance) - goto bad; - value = owned_instance; - if (!PyExceptionInstance_Check(value)) { - PyErr_Format(PyExc_TypeError, - "calling %R should have returned an instance of " - "BaseException, not %R", - type, Py_TYPE(value)); - goto bad; - } - } - } else { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto bad; - } - if (cause) { - PyObject *fixed_cause; - if (cause == Py_None) { - fixed_cause = NULL; - } else if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto bad; - } else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - Py_INCREF(fixed_cause); - } else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto bad; - } - PyException_SetCause(value, fixed_cause); - } - PyErr_SetObject(type, value); - if (tb) { -#if CYTHON_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 - -/* 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 - -/* 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 -} - -/* SliceObject */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice(PyObject* obj, - Py_ssize_t cstart, Py_ssize_t cstop, - PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, - int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) { -#if CYTHON_USE_TYPE_SLOTS - PyMappingMethods* mp; -#if PY_MAJOR_VERSION < 3 - PySequenceMethods* ms = Py_TYPE(obj)->tp_as_sequence; - if (likely(ms && ms->sq_slice)) { - if (!has_cstart) { - if (_py_start && (*_py_start != Py_None)) { - cstart = __Pyx_PyIndex_AsSsize_t(*_py_start); - if ((cstart == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; - } else - cstart = 0; - } - if (!has_cstop) { - if (_py_stop && (*_py_stop != Py_None)) { - cstop = __Pyx_PyIndex_AsSsize_t(*_py_stop); - if ((cstop == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; - } else - cstop = PY_SSIZE_T_MAX; - } - if (wraparound && unlikely((cstart < 0) | (cstop < 0)) && likely(ms->sq_length)) { - Py_ssize_t l = ms->sq_length(obj); - if (likely(l >= 0)) { - if (cstop < 0) { - cstop += l; - if (cstop < 0) cstop = 0; - } - if (cstart < 0) { - cstart += l; - if (cstart < 0) cstart = 0; - } - } else { - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - goto bad; - PyErr_Clear(); - } - } - return ms->sq_slice(obj, cstart, cstop); - } -#endif - mp = Py_TYPE(obj)->tp_as_mapping; - if (likely(mp && mp->mp_subscript)) -#endif - { - PyObject* result; - PyObject *py_slice, *py_start, *py_stop; - if (_py_slice) { - py_slice = *_py_slice; - } else { - PyObject* owned_start = NULL; - PyObject* owned_stop = NULL; - if (_py_start) { - py_start = *_py_start; - } else { - if (has_cstart) { - owned_start = py_start = PyInt_FromSsize_t(cstart); - if (unlikely(!py_start)) goto bad; - } else - py_start = Py_None; - } - if (_py_stop) { - py_stop = *_py_stop; - } else { - if (has_cstop) { - owned_stop = py_stop = PyInt_FromSsize_t(cstop); - if (unlikely(!py_stop)) { - Py_XDECREF(owned_start); - goto bad; - } - } else - py_stop = Py_None; - } - py_slice = PySlice_New(py_start, py_stop, Py_None); - Py_XDECREF(owned_start); - Py_XDECREF(owned_stop); - if (unlikely(!py_slice)) goto bad; - } -#if CYTHON_USE_TYPE_SLOTS - result = mp->mp_subscript(obj, py_slice); -#else - result = PyObject_GetItem(obj, py_slice); -#endif - if (!_py_slice) { - Py_DECREF(py_slice); - } - return result; - } - PyErr_Format(PyExc_TypeError, - "'%.200s' object is unsliceable", Py_TYPE(obj)->tp_name); -bad: - return NULL; -} - -/* PyIntBinop */ -#if !CYTHON_COMPILING_IN_PYPY -static PyObject* __Pyx_PyInt_SubtractObjC(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_subtract(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_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(op1)) { - const long b = intval; - double a = PyFloat_AS_DOUBLE(op1); - 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 - -/* IterNext */ -static PyObject *__Pyx_PyIter_Next2Default(PyObject* defval) { - PyObject* exc_type; - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - exc_type = __Pyx_PyErr_Occurred(); - if (unlikely(exc_type)) { - if (!defval || unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) - return NULL; - __Pyx_PyErr_Clear(); - Py_INCREF(defval); - return defval; - } - if (defval) { - Py_INCREF(defval); - return defval; - } - __Pyx_PyErr_SetNone(PyExc_StopIteration); - return NULL; -} -static void __Pyx_PyIter_Next_ErrorNoIterator(PyObject *iterator) { - PyErr_Format(PyExc_TypeError, - "%.200s object is not an iterator", Py_TYPE(iterator)->tp_name); -} -static CYTHON_INLINE PyObject *__Pyx_PyIter_Next2(PyObject* iterator, PyObject* defval) { - PyObject* next; - iternextfunc iternext = Py_TYPE(iterator)->tp_iternext; - if (likely(iternext)) { -#if CYTHON_USE_TYPE_SLOTS || CYTHON_COMPILING_IN_PYPY - next = iternext(iterator); - if (likely(next)) - return next; - #if PY_VERSION_HEX >= 0x02070000 && CYTHON_COMPILING_IN_CPYTHON - if (unlikely(iternext == &_PyObject_NextNotImplemented)) - return NULL; - #endif -#else - next = PyIter_Next(iterator); - if (likely(next)) - return next; -#endif - } else if (CYTHON_USE_TYPE_SLOTS || unlikely(!PyIter_Check(iterator))) { - __Pyx_PyIter_Next_ErrorNoIterator(iterator); - return NULL; - } -#if !CYTHON_USE_TYPE_SLOTS - else { - next = PyIter_Next(iterator); - if (likely(next)) - return next; - } -#endif - return __Pyx_PyIter_Next2Default(defval); -} - -/* 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 - -/* 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; -} - -/* 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; -} - -/* PyObjectCallMethod0 */ -static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { - PyObject *method = NULL, *result = NULL; - int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); - if (likely(is_method)) { - result = __Pyx_PyObject_CallOneArg(method, obj); - Py_DECREF(method); - return result; - } - if (unlikely(!method)) goto bad; - result = __Pyx_PyObject_CallNoArg(method); - Py_DECREF(method); -bad: - return result; -} - -/* UnpackUnboundCMethod */ -static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) { - PyObject *method; - method = __Pyx_PyObject_GetAttrStr(target->type, *target->method_name); - if (unlikely(!method)) - return -1; - target->method = method; -#if CYTHON_COMPILING_IN_CPYTHON - #if PY_MAJOR_VERSION >= 3 - if (likely(__Pyx_TypeCheck(method, &PyMethodDescr_Type))) - #endif - { - PyMethodDescrObject *descr = (PyMethodDescrObject*) method; - target->func = descr->d_method->ml_meth; - target->flag = descr->d_method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_STACKLESS); - } -#endif - return 0; -} - -/* CallUnboundCMethod0 */ -static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { - PyObject *args, *result = NULL; - if (unlikely(!cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; -#if CYTHON_ASSUME_SAFE_MACROS - args = PyTuple_New(1); - if (unlikely(!args)) goto bad; - Py_INCREF(self); - PyTuple_SET_ITEM(args, 0, self); -#else - args = PyTuple_Pack(1, self); - if (unlikely(!args)) goto bad; -#endif - result = __Pyx_PyObject_Call(cfunc->method, args, NULL); - Py_DECREF(args); -bad: - return result; -} - -/* pop */ -static CYTHON_INLINE PyObject* __Pyx__PyObject_Pop(PyObject* L) { - if (Py_TYPE(L) == &PySet_Type) { - return PySet_Pop(L); - } - return __Pyx_PyObject_CallMethod0(L, __pyx_n_s_pop); -} -#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS -static CYTHON_INLINE PyObject* __Pyx_PyList_Pop(PyObject* L) { - if (likely(PyList_GET_SIZE(L) > (((PyListObject*)L)->allocated >> 1))) { - __Pyx_SET_SIZE(L, Py_SIZE(L) - 1); - return PyList_GET_ITEM(L, PyList_GET_SIZE(L)); - } - return __Pyx_CallUnboundCMethod0(&__pyx_umethod_PyList_Type_pop, L); -} -#endif - -/* 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); -} - -/* 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; -} - -/* 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; iexc_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 - -/* GetAttr */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { -#if CYTHON_USE_TYPE_SLOTS -#if PY_MAJOR_VERSION >= 3 - if (likely(PyUnicode_Check(n))) -#else - if (likely(PyString_Check(n))) -#endif - return __Pyx_PyObject_GetAttrStr(o, n); -#endif - return PyObject_GetAttr(o, n); -} - -/* HasAttr */ -static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { - PyObject *r; - if (unlikely(!__Pyx_PyBaseString_Check(n))) { - PyErr_SetString(PyExc_TypeError, - "hasattr(): attribute name must be string"); - return -1; - } - r = __Pyx_GetAttr(o, n); - if (unlikely(!r)) { - PyErr_Clear(); - return 0; - } else { - Py_DECREF(r); - return 1; - } -} - -/* GetAttr3 */ -static PyObject *__Pyx_GetAttr3Default(PyObject *d) { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) - return NULL; - __Pyx_PyErr_Clear(); - Py_INCREF(d); - return d; -} -static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { - PyObject *r = __Pyx_GetAttr(o, n); - return (likely(r)) ? r : __Pyx_GetAttr3Default(d); -} - -/* 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; -} - -/* CalculateMetaclass */ -static PyObject *__Pyx_CalculateMetaclass(PyTypeObject *metaclass, PyObject *bases) { - Py_ssize_t i, nbases = PyTuple_GET_SIZE(bases); - for (i=0; i < nbases; i++) { - PyTypeObject *tmptype; - PyObject *tmp = PyTuple_GET_ITEM(bases, i); - tmptype = Py_TYPE(tmp); -#if PY_MAJOR_VERSION < 3 - if (tmptype == &PyClass_Type) - continue; -#endif - if (!metaclass) { - metaclass = tmptype; - continue; - } - if (PyType_IsSubtype(metaclass, tmptype)) - continue; - if (PyType_IsSubtype(tmptype, metaclass)) { - metaclass = tmptype; - continue; - } - PyErr_SetString(PyExc_TypeError, - "metaclass conflict: " - "the metaclass of a derived class " - "must be a (non-strict) subclass " - "of the metaclasses of all its bases"); - return NULL; - } - if (!metaclass) { -#if PY_MAJOR_VERSION < 3 - metaclass = &PyClass_Type; -#else - metaclass = &PyType_Type; -#endif - } - Py_INCREF((PyObject*) metaclass); - return (PyObject*) metaclass; -} - -/* 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; -} - -/* 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; -} - -/* Py3ClassCreate */ -static PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, - PyObject *qualname, PyObject *mkw, PyObject *modname, PyObject *doc) { - PyObject *ns; - if (metaclass) { - PyObject *prep = __Pyx_PyObject_GetAttrStr(metaclass, __pyx_n_s_prepare); - if (prep) { - PyObject *pargs = PyTuple_Pack(2, name, bases); - if (unlikely(!pargs)) { - Py_DECREF(prep); - return NULL; - } - ns = PyObject_Call(prep, pargs, mkw); - Py_DECREF(prep); - Py_DECREF(pargs); - } else { - if (unlikely(!PyErr_ExceptionMatches(PyExc_AttributeError))) - return NULL; - PyErr_Clear(); - ns = PyDict_New(); - } - } else { - ns = PyDict_New(); - } - if (unlikely(!ns)) - return NULL; - if (unlikely(PyObject_SetItem(ns, __pyx_n_s_module, modname) < 0)) goto bad; - if (unlikely(PyObject_SetItem(ns, __pyx_n_s_qualname, qualname) < 0)) goto bad; - if (unlikely(doc && PyObject_SetItem(ns, __pyx_n_s_doc, doc) < 0)) goto bad; - return ns; -bad: - Py_DECREF(ns); - return NULL; -} -static PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, - PyObject *dict, PyObject *mkw, - int calculate_metaclass, int allow_py2_metaclass) { - PyObject *result, *margs; - PyObject *owned_metaclass = NULL; - if (allow_py2_metaclass) { - owned_metaclass = PyObject_GetItem(dict, __pyx_n_s_metaclass); - if (owned_metaclass) { - metaclass = owned_metaclass; - } else if (likely(PyErr_ExceptionMatches(PyExc_KeyError))) { - PyErr_Clear(); - } else { - return NULL; - } - } - if (calculate_metaclass && (!metaclass || PyType_Check(metaclass))) { - metaclass = __Pyx_CalculateMetaclass((PyTypeObject*) metaclass, bases); - Py_XDECREF(owned_metaclass); - if (unlikely(!metaclass)) - return NULL; - owned_metaclass = metaclass; - } - margs = PyTuple_Pack(3, name, bases, dict); - if (unlikely(!margs)) { - result = NULL; - } else { - result = PyObject_Call(metaclass, margs, mkw); - Py_DECREF(margs); - } - Py_XDECREF(owned_metaclass); - return result; -} - -/* 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); -} - -/* 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; -} - -/* CheckBinaryVersion */ -static int __Pyx_check_binary_version(void) { - char ctversion[5]; - int same=1, i, found_dot; - const char* rt_from_call = Py_GetVersion(); - PyOS_snprintf(ctversion, 5, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); - found_dot = 0; - for (i = 0; i < 4; i++) { - if (!ctversion[i]) { - same = (rt_from_call[i] < '0' || rt_from_call[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/Dagfinn1962/stablediffusion-models/README.md b/spaces/Dagfinn1962/stablediffusion-models/README.md deleted file mode 100644 index 5bd79f1f137204e77aaebfb8b3fc111fb0e7236f..0000000000000000000000000000000000000000 --- a/spaces/Dagfinn1962/stablediffusion-models/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Maximum Multiplier -emoji: 🛕🛕 -colorFrom: green -colorTo: blue -sdk: gradio -sdk_version: 3.15.0 -app_file: app.py -pinned: true -duplicated_from: blueorigin6/stablediffusion-models ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/DataRaptor/ActionNet/README.md b/spaces/DataRaptor/ActionNet/README.md deleted file mode 100644 index d45a9c80d111991258335ffb401890a5580982cd..0000000000000000000000000000000000000000 --- a/spaces/DataRaptor/ActionNet/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: ActionNet -emoji: 😻 -colorFrom: green -colorTo: green -sdk: streamlit -sdk_version: 1.21.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Datasculptor/StyleGAN-NADA/e4e/models/encoders/psp_encoders.py b/spaces/Datasculptor/StyleGAN-NADA/e4e/models/encoders/psp_encoders.py deleted file mode 100644 index dc49acd11f062cbd29f839ee3c04bce7fa84f479..0000000000000000000000000000000000000000 --- a/spaces/Datasculptor/StyleGAN-NADA/e4e/models/encoders/psp_encoders.py +++ /dev/null @@ -1,200 +0,0 @@ -from enum import Enum -import math -import numpy as np -import torch -from torch import nn -from torch.nn import Conv2d, BatchNorm2d, PReLU, Sequential, Module - -from e4e.models.encoders.helpers import get_blocks, bottleneck_IR, bottleneck_IR_SE, _upsample_add -from e4e.models.stylegan2.model import EqualLinear - - -class ProgressiveStage(Enum): - WTraining = 0 - Delta1Training = 1 - Delta2Training = 2 - Delta3Training = 3 - Delta4Training = 4 - Delta5Training = 5 - Delta6Training = 6 - Delta7Training = 7 - Delta8Training = 8 - Delta9Training = 9 - Delta10Training = 10 - Delta11Training = 11 - Delta12Training = 12 - Delta13Training = 13 - Delta14Training = 14 - Delta15Training = 15 - Delta16Training = 16 - Delta17Training = 17 - Inference = 18 - - -class GradualStyleBlock(Module): - def __init__(self, in_c, out_c, spatial): - super(GradualStyleBlock, self).__init__() - self.out_c = out_c - self.spatial = spatial - num_pools = int(np.log2(spatial)) - modules = [] - modules += [Conv2d(in_c, out_c, kernel_size=3, stride=2, padding=1), - nn.LeakyReLU()] - for i in range(num_pools - 1): - modules += [ - Conv2d(out_c, out_c, kernel_size=3, stride=2, padding=1), - nn.LeakyReLU() - ] - self.convs = nn.Sequential(*modules) - self.linear = EqualLinear(out_c, out_c, lr_mul=1) - - def forward(self, x): - x = self.convs(x) - x = x.view(-1, self.out_c) - x = self.linear(x) - return x - - -class GradualStyleEncoder(Module): - def __init__(self, num_layers, mode='ir', opts=None): - super(GradualStyleEncoder, self).__init__() - assert num_layers in [50, 100, 152], 'num_layers should be 50,100, or 152' - assert mode in ['ir', 'ir_se'], 'mode should be ir or ir_se' - blocks = get_blocks(num_layers) - if mode == 'ir': - unit_module = bottleneck_IR - elif mode == 'ir_se': - unit_module = bottleneck_IR_SE - self.input_layer = Sequential(Conv2d(3, 64, (3, 3), 1, 1, bias=False), - BatchNorm2d(64), - PReLU(64)) - modules = [] - for block in blocks: - for bottleneck in block: - modules.append(unit_module(bottleneck.in_channel, - bottleneck.depth, - bottleneck.stride)) - self.body = Sequential(*modules) - - self.styles = nn.ModuleList() - log_size = int(math.log(opts.stylegan_size, 2)) - self.style_count = 2 * log_size - 2 - self.coarse_ind = 3 - self.middle_ind = 7 - for i in range(self.style_count): - if i < self.coarse_ind: - style = GradualStyleBlock(512, 512, 16) - elif i < self.middle_ind: - style = GradualStyleBlock(512, 512, 32) - else: - style = GradualStyleBlock(512, 512, 64) - self.styles.append(style) - self.latlayer1 = nn.Conv2d(256, 512, kernel_size=1, stride=1, padding=0) - self.latlayer2 = nn.Conv2d(128, 512, kernel_size=1, stride=1, padding=0) - - def forward(self, x): - x = self.input_layer(x) - - latents = [] - modulelist = list(self.body._modules.values()) - for i, l in enumerate(modulelist): - x = l(x) - if i == 6: - c1 = x - elif i == 20: - c2 = x - elif i == 23: - c3 = x - - for j in range(self.coarse_ind): - latents.append(self.styles[j](c3)) - - p2 = _upsample_add(c3, self.latlayer1(c2)) - for j in range(self.coarse_ind, self.middle_ind): - latents.append(self.styles[j](p2)) - - p1 = _upsample_add(p2, self.latlayer2(c1)) - for j in range(self.middle_ind, self.style_count): - latents.append(self.styles[j](p1)) - - out = torch.stack(latents, dim=1) - return out - - -class Encoder4Editing(Module): - def __init__(self, num_layers, mode='ir', opts=None): - super(Encoder4Editing, self).__init__() - assert num_layers in [50, 100, 152], 'num_layers should be 50,100, or 152' - assert mode in ['ir', 'ir_se'], 'mode should be ir or ir_se' - blocks = get_blocks(num_layers) - if mode == 'ir': - unit_module = bottleneck_IR - elif mode == 'ir_se': - unit_module = bottleneck_IR_SE - self.input_layer = Sequential(Conv2d(3, 64, (3, 3), 1, 1, bias=False), - BatchNorm2d(64), - PReLU(64)) - modules = [] - for block in blocks: - for bottleneck in block: - modules.append(unit_module(bottleneck.in_channel, - bottleneck.depth, - bottleneck.stride)) - self.body = Sequential(*modules) - - self.styles = nn.ModuleList() - log_size = int(math.log(opts.stylegan_size, 2)) - self.style_count = 2 * log_size - 2 - self.coarse_ind = 3 - self.middle_ind = 7 - - for i in range(self.style_count): - if i < self.coarse_ind: - style = GradualStyleBlock(512, 512, 16) - elif i < self.middle_ind: - style = GradualStyleBlock(512, 512, 32) - else: - style = GradualStyleBlock(512, 512, 64) - self.styles.append(style) - - self.latlayer1 = nn.Conv2d(256, 512, kernel_size=1, stride=1, padding=0) - self.latlayer2 = nn.Conv2d(128, 512, kernel_size=1, stride=1, padding=0) - - self.progressive_stage = ProgressiveStage.Inference - - def get_deltas_starting_dimensions(self): - ''' Get a list of the initial dimension of every delta from which it is applied ''' - return list(range(self.style_count)) # Each dimension has a delta applied to it - - def set_progressive_stage(self, new_stage: ProgressiveStage): - self.progressive_stage = new_stage - print('Changed progressive stage to: ', new_stage) - - def forward(self, x): - x = self.input_layer(x) - - modulelist = list(self.body._modules.values()) - for i, l in enumerate(modulelist): - x = l(x) - if i == 6: - c1 = x - elif i == 20: - c2 = x - elif i == 23: - c3 = x - - # Infer main W and duplicate it - w0 = self.styles[0](c3) - w = w0.repeat(self.style_count, 1, 1).permute(1, 0, 2) - stage = self.progressive_stage.value - features = c3 - for i in range(1, min(stage + 1, self.style_count)): # Infer additional deltas - if i == self.coarse_ind: - p2 = _upsample_add(c3, self.latlayer1(c2)) # FPN's middle features - features = p2 - elif i == self.middle_ind: - p1 = _upsample_add(p2, self.latlayer2(c1)) # FPN's fine features - features = p1 - delta_i = self.styles[i](features) - w[:, i] += delta_i - return w diff --git a/spaces/EPFL-VILAB/MultiMAE/mask2former/modeling/meta_arch/__init__.py b/spaces/EPFL-VILAB/MultiMAE/mask2former/modeling/meta_arch/__init__.py deleted file mode 100644 index 9020c2df23e2af280b7bb168b996ae9eaf312eb8..0000000000000000000000000000000000000000 --- a/spaces/EPFL-VILAB/MultiMAE/mask2former/modeling/meta_arch/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. diff --git a/spaces/ERICTORRALBA/CAD/README.md b/spaces/ERICTORRALBA/CAD/README.md deleted file mode 100644 index 2ab4aebe218676d37a6fb194259d911ab2f49b79..0000000000000000000000000000000000000000 --- a/spaces/ERICTORRALBA/CAD/README.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: AutoTrain Advanced -emoji: 🚀 -colorFrom: blue -colorTo: green -sdk: docker -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/ElainaFanBoy/MusicGen/audiocraft/utils/__init__.py b/spaces/ElainaFanBoy/MusicGen/audiocraft/utils/__init__.py deleted file mode 100644 index 0952fcc3f57e34b3747962e9ebd6fc57aeea63fa..0000000000000000000000000000000000000000 --- a/spaces/ElainaFanBoy/MusicGen/audiocraft/utils/__init__.py +++ /dev/null @@ -1,5 +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. diff --git a/spaces/Fernando22/freegpt-webui/g4f/Provider/Providers/helpers/phind.py b/spaces/Fernando22/freegpt-webui/g4f/Provider/Providers/helpers/phind.py deleted file mode 100644 index 70525d51d849c43bd1cf29c7f9b18f22bff1e982..0000000000000000000000000000000000000000 --- a/spaces/Fernando22/freegpt-webui/g4f/Provider/Providers/helpers/phind.py +++ /dev/null @@ -1,69 +0,0 @@ -import sys -import json -import datetime -import urllib.parse - -from curl_cffi import requests - -config = json.loads(sys.argv[1]) -prompt = config['messages'][-1]['content'] - -skill = 'expert' if config['model'] == 'gpt-4' else 'intermediate' - -json_data = json.dumps({ - 'question': prompt, - 'options': { - 'skill': skill, - 'date': datetime.datetime.now().strftime('%d/%m/%Y'), - 'language': 'en', - 'detailed': True, - 'creative': True, - 'customLinks': []}}, separators=(',', ':')) - -headers = { - 'Content-Type': 'application/json', - 'Pragma': 'no-cache', - 'Accept': '*/*', - 'Sec-Fetch-Site': 'same-origin', - 'Accept-Language': 'en-GB,en;q=0.9', - 'Cache-Control': 'no-cache', - 'Sec-Fetch-Mode': 'cors', - 'Content-Length': str(len(json_data)), - 'Origin': 'https://www.phind.com', - 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.4 Safari/605.1.15', - 'Referer': f'https://www.phind.com/search?q={urllib.parse.quote(prompt)}&source=searchbox', - 'Connection': 'keep-alive', - 'Host': 'www.phind.com', - 'Sec-Fetch-Dest': 'empty' -} - - -def output(chunk): - try: - if b'PHIND_METADATA' in chunk: - return - - if chunk == b'data: \r\ndata: \r\ndata: \r\n\r\n': - chunk = b'data: \n\r\n\r\n' - - chunk = chunk.decode() - - chunk = chunk.replace('data: \r\n\r\ndata: ', 'data: \n') - chunk = chunk.replace('\r\ndata: \r\ndata: \r\n\r\n', '\n\r\n\r\n') - chunk = chunk.replace('data: ', '').replace('\r\n\r\n', '') - - print(chunk, flush=True, end = '') - - except json.decoder.JSONDecodeError: - pass - -while True: - try: - response = requests.post('https://www.phind.com/api/infer/answer', - headers=headers, data=json_data, content_callback=output, timeout=999999, impersonate='safari15_5') - - exit(0) - - except Exception as e: - print('an error occured, retrying... |', e, flush=True) - continue \ No newline at end of file diff --git a/spaces/FloydianSound/Redline_Diffusion_V1-5/app.py b/spaces/FloydianSound/Redline_Diffusion_V1-5/app.py deleted file mode 100644 index 943aaae60d5f541506f76dc5ba3f8f865d6dd999..0000000000000000000000000000000000000000 --- a/spaces/FloydianSound/Redline_Diffusion_V1-5/app.py +++ /dev/null @@ -1,137 +0,0 @@ -from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline, DPMSolverMultistepScheduler -import gradio as gr -import torch -from PIL import Image - -model_id = 'FloydianSound/Redline_Diffusion_V1-5' -prefix = 'redline' - -scheduler = DPMSolverMultistepScheduler.from_pretrained(model_id, subfolder="scheduler") - -pipe = StableDiffusionPipeline.from_pretrained( - model_id, - torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, - scheduler=scheduler) - -pipe_i2i = StableDiffusionImg2ImgPipeline.from_pretrained( - model_id, - torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, - scheduler=scheduler) - -if torch.cuda.is_available(): - pipe = pipe.to("cuda") - pipe_i2i = pipe_i2i.to("cuda") - -def error_str(error, title="Error"): - return f"""#### {title} - {error}""" if error else "" - -def inference(prompt, guidance, steps, width=512, height=512, seed=0, img=None, strength=0.5, neg_prompt="", auto_prefix=False): - - generator = torch.Generator('cuda').manual_seed(seed) if seed != 0 else None - prompt = f"{prefix} {prompt}" if auto_prefix else prompt - - try: - if img is not None: - return img_to_img(prompt, neg_prompt, img, strength, guidance, steps, width, height, generator), None - else: - return txt_to_img(prompt, neg_prompt, guidance, steps, width, height, generator), None - except Exception as e: - return None, error_str(e) - -def txt_to_img(prompt, neg_prompt, guidance, steps, width, height, generator): - - result = pipe( - prompt, - negative_prompt = neg_prompt, - num_inference_steps = int(steps), - guidance_scale = guidance, - width = width, - height = height, - generator = generator) - - return result.images[0] - -def img_to_img(prompt, neg_prompt, img, strength, guidance, steps, width, height, generator): - - ratio = min(height / img.height, width / img.width) - img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS) - result = pipe_i2i( - prompt, - negative_prompt = neg_prompt, - init_image = img, - num_inference_steps = int(steps), - strength = strength, - guidance_scale = guidance, - width = width, - height = height, - generator = generator) - - return result.images[0] - -css = """.main-div div{display:inline-flex;align-items:center;gap:.8rem;font-size:1.75rem}.main-div div h1{font-weight:900;margin-bottom:7px}.main-div p{margin-bottom:10px;font-size:94%}a{text-decoration:underline}.tabs{margin-top:0;margin-bottom:0}#gallery{min-height:20rem} -""" -with gr.Blocks(css=css) as demo: - gr.HTML( - f""" -

-
-

Redline Diffusion V1 5

-
-

- Demo for Redline Diffusion V1 5 Stable Diffusion model.
- {"Add the following tokens to your prompts for the model to work properly: prefix" if prefix else ""} -

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

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

This space was created using SD Space Creator.

-
- """) - -demo.queue(concurrency_count=1) -demo.launch() diff --git a/spaces/FridaZuley/RVC_HFKawaii/tools/infer/trans_weights.py b/spaces/FridaZuley/RVC_HFKawaii/tools/infer/trans_weights.py deleted file mode 100644 index 1c54eefd6e7c678238d31e251a2e15479bf35d5b..0000000000000000000000000000000000000000 --- a/spaces/FridaZuley/RVC_HFKawaii/tools/infer/trans_weights.py +++ /dev/null @@ -1,18 +0,0 @@ -import pdb - -import torch - -# a=torch.load(r"E:\codes\py39\vits_vc_gpu_train\logs\ft-mi-suc\G_1000.pth")["model"]#sim_nsf# -# a=torch.load(r"E:\codes\py39\vits_vc_gpu_train\logs\ft-mi-freeze-vocoder-flow-enc_q\G_1000.pth")["model"]#sim_nsf# -# a=torch.load(r"E:\codes\py39\vits_vc_gpu_train\logs\ft-mi-freeze-vocoder\G_1000.pth")["model"]#sim_nsf# -# a=torch.load(r"E:\codes\py39\vits_vc_gpu_train\logs\ft-mi-test\G_1000.pth")["model"]#sim_nsf# -a = torch.load( - r"E:\codes\py39\vits_vc_gpu_train\logs\ft-mi-no_opt-no_dropout\G_1000.pth" -)[ - "model" -] # sim_nsf# -for key in a.keys(): - a[key] = a[key].half() -# torch.save(a,"ft-mi-freeze-vocoder_true_1k.pt")# -# torch.save(a,"ft-mi-sim1k.pt")# -torch.save(a, "ft-mi-no_opt-no_dropout.pt") # diff --git a/spaces/GipAdonimus/Real-Time-Voice-Cloning/README.md b/spaces/GipAdonimus/Real-Time-Voice-Cloning/README.md deleted file mode 100644 index 753600359817925a36e07b3b5c944567a2f0d946..0000000000000000000000000000000000000000 --- a/spaces/GipAdonimus/Real-Time-Voice-Cloning/README.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -title: Real Time Voice Cloning -emoji: 📈 -colorFrom: blue -colorTo: red -sdk: gradio -app_file: app.py -sdk_version: 3.17.1 -pinned: false -duplicated_from: akhaliq/Real-Time-Voice-Cloning ---- - -# Configuration - -`title`: _string_ -Display title for the Space - -`emoji`: _string_ -Space emoji (emoji-only character allowed) - -`colorFrom`: _string_ -Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray) - -`colorTo`: _string_ -Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray) - -`sdk`: _string_ -Can be either `gradio` or `streamlit` - -`sdk_version` : _string_ -Only applicable for `streamlit` SDK. -See [doc](https://hf.co/docs/hub/spaces) for more info on supported versions. - -`app_file`: _string_ -Path to your main application file (which contains either `gradio` or `streamlit` Python code). -Path is relative to the root of the repository. - -`pinned`: _boolean_ -Whether the Space stays on top of your list. diff --git a/spaces/Gmq-x/gpt-academic/.github/ISSUE_TEMPLATE/feature_request.md b/spaces/Gmq-x/gpt-academic/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index e46a4c01e804aa4b649bd40af6c13d5981c873d4..0000000000000000000000000000000000000000 --- a/spaces/Gmq-x/gpt-academic/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this project -title: '' -labels: '' -assignees: '' - ---- - - diff --git a/spaces/Gradio-Blocks/uniformer_image_detection/configs/hrnet/faster_rcnn_hrnetv2p_w40_2x_coco.py b/spaces/Gradio-Blocks/uniformer_image_detection/configs/hrnet/faster_rcnn_hrnetv2p_w40_2x_coco.py deleted file mode 100644 index 585cc2c332fd88a9f0164b14084d45d7a3783b11..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_detection/configs/hrnet/faster_rcnn_hrnetv2p_w40_2x_coco.py +++ /dev/null @@ -1,4 +0,0 @@ -_base_ = './faster_rcnn_hrnetv2p_w40_1x_coco.py' -# learning policy -lr_config = dict(step=[16, 22]) -runner = dict(type='EpochBasedRunner', max_epochs=24) diff --git a/spaces/GrandaddyShmax/MusicGen_Plus_hfv2/audiocraft/modules/seanet.py b/spaces/GrandaddyShmax/MusicGen_Plus_hfv2/audiocraft/modules/seanet.py deleted file mode 100644 index 3e5998e9153afb6e68ea410d565e00ea835db248..0000000000000000000000000000000000000000 --- a/spaces/GrandaddyShmax/MusicGen_Plus_hfv2/audiocraft/modules/seanet.py +++ /dev/null @@ -1,258 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -import typing as tp - -import numpy as np -import torch.nn as nn - -from .conv import StreamableConv1d, StreamableConvTranspose1d -from .lstm import StreamableLSTM - - -class SEANetResnetBlock(nn.Module): - """Residual block from SEANet model. - - Args: - dim (int): Dimension of the input/output. - kernel_sizes (list): List of kernel sizes for the convolutions. - dilations (list): List of dilations for the convolutions. - activation (str): Activation function. - activation_params (dict): Parameters to provide to the activation function. - norm (str): Normalization method. - norm_params (dict): Parameters to provide to the underlying normalization used along with the convolution. - causal (bool): Whether to use fully causal convolution. - pad_mode (str): Padding mode for the convolutions. - compress (int): Reduced dimensionality in residual branches (from Demucs v3). - true_skip (bool): Whether to use true skip connection or a simple - (streamable) convolution as the skip connection. - """ - def __init__(self, dim: int, kernel_sizes: tp.List[int] = [3, 1], dilations: tp.List[int] = [1, 1], - activation: str = 'ELU', activation_params: dict = {'alpha': 1.0}, - norm: str = 'none', norm_params: tp.Dict[str, tp.Any] = {}, causal: bool = False, - pad_mode: str = 'reflect', compress: int = 2, true_skip: bool = True): - super().__init__() - assert len(kernel_sizes) == len(dilations), 'Number of kernel sizes should match number of dilations' - act = getattr(nn, activation) - hidden = dim // compress - block = [] - for i, (kernel_size, dilation) in enumerate(zip(kernel_sizes, dilations)): - in_chs = dim if i == 0 else hidden - out_chs = dim if i == len(kernel_sizes) - 1 else hidden - block += [ - act(**activation_params), - StreamableConv1d(in_chs, out_chs, kernel_size=kernel_size, dilation=dilation, - norm=norm, norm_kwargs=norm_params, - causal=causal, pad_mode=pad_mode), - ] - self.block = nn.Sequential(*block) - self.shortcut: nn.Module - if true_skip: - self.shortcut = nn.Identity() - else: - self.shortcut = StreamableConv1d(dim, dim, kernel_size=1, norm=norm, norm_kwargs=norm_params, - causal=causal, pad_mode=pad_mode) - - def forward(self, x): - return self.shortcut(x) + self.block(x) - - -class SEANetEncoder(nn.Module): - """SEANet encoder. - - Args: - channels (int): Audio channels. - dimension (int): Intermediate representation dimension. - n_filters (int): Base width for the model. - n_residual_layers (int): nb of residual layers. - ratios (Sequence[int]): kernel size and stride ratios. The encoder uses downsampling ratios instead of - upsampling ratios, hence it will use the ratios in the reverse order to the ones specified here - that must match the decoder order. We use the decoder order as some models may only employ the decoder. - activation (str): Activation function. - activation_params (dict): Parameters to provide to the activation function. - norm (str): Normalization method. - norm_params (dict): Parameters to provide to the underlying normalization used along with the convolution. - kernel_size (int): Kernel size for the initial convolution. - last_kernel_size (int): Kernel size for the initial convolution. - residual_kernel_size (int): Kernel size for the residual layers. - dilation_base (int): How much to increase the dilation with each layer. - causal (bool): Whether to use fully causal convolution. - pad_mode (str): Padding mode for the convolutions. - true_skip (bool): Whether to use true skip connection or a simple - (streamable) convolution as the skip connection in the residual network blocks. - compress (int): Reduced dimensionality in residual branches (from Demucs v3). - lstm (int): Number of LSTM layers at the end of the encoder. - disable_norm_outer_blocks (int): Number of blocks for which we don't apply norm. - For the encoder, it corresponds to the N first blocks. - """ - def __init__(self, channels: int = 1, dimension: int = 128, n_filters: int = 32, n_residual_layers: int = 3, - ratios: tp.List[int] = [8, 5, 4, 2], activation: str = 'ELU', activation_params: dict = {'alpha': 1.0}, - norm: str = 'none', norm_params: tp.Dict[str, tp.Any] = {}, kernel_size: int = 7, - last_kernel_size: int = 7, residual_kernel_size: int = 3, dilation_base: int = 2, causal: bool = False, - pad_mode: str = 'reflect', true_skip: bool = True, compress: int = 2, lstm: int = 0, - disable_norm_outer_blocks: int = 0): - super().__init__() - self.channels = channels - self.dimension = dimension - self.n_filters = n_filters - self.ratios = list(reversed(ratios)) - del ratios - self.n_residual_layers = n_residual_layers - self.hop_length = np.prod(self.ratios) - self.n_blocks = len(self.ratios) + 2 # first and last conv + residual blocks - self.disable_norm_outer_blocks = disable_norm_outer_blocks - assert self.disable_norm_outer_blocks >= 0 and self.disable_norm_outer_blocks <= self.n_blocks, \ - "Number of blocks for which to disable norm is invalid." \ - "It should be lower or equal to the actual number of blocks in the network and greater or equal to 0." - - act = getattr(nn, activation) - mult = 1 - model: tp.List[nn.Module] = [ - StreamableConv1d(channels, mult * n_filters, kernel_size, - norm='none' if self.disable_norm_outer_blocks >= 1 else norm, - norm_kwargs=norm_params, causal=causal, pad_mode=pad_mode) - ] - # Downsample to raw audio scale - for i, ratio in enumerate(self.ratios): - block_norm = 'none' if self.disable_norm_outer_blocks >= i + 2 else norm - # Add residual layers - for j in range(n_residual_layers): - model += [ - SEANetResnetBlock(mult * n_filters, kernel_sizes=[residual_kernel_size, 1], - dilations=[dilation_base ** j, 1], - norm=block_norm, norm_params=norm_params, - activation=activation, activation_params=activation_params, - causal=causal, pad_mode=pad_mode, compress=compress, true_skip=true_skip)] - - # Add downsampling layers - model += [ - act(**activation_params), - StreamableConv1d(mult * n_filters, mult * n_filters * 2, - kernel_size=ratio * 2, stride=ratio, - norm=block_norm, norm_kwargs=norm_params, - causal=causal, pad_mode=pad_mode), - ] - mult *= 2 - - if lstm: - model += [StreamableLSTM(mult * n_filters, num_layers=lstm)] - - model += [ - act(**activation_params), - StreamableConv1d(mult * n_filters, dimension, last_kernel_size, - norm='none' if self.disable_norm_outer_blocks == self.n_blocks else norm, - norm_kwargs=norm_params, causal=causal, pad_mode=pad_mode) - ] - - self.model = nn.Sequential(*model) - - def forward(self, x): - return self.model(x) - - -class SEANetDecoder(nn.Module): - """SEANet decoder. - - Args: - channels (int): Audio channels. - dimension (int): Intermediate representation dimension. - n_filters (int): Base width for the model. - n_residual_layers (int): nb of residual layers. - ratios (Sequence[int]): kernel size and stride ratios. - activation (str): Activation function. - activation_params (dict): Parameters to provide to the activation function. - final_activation (str): Final activation function after all convolutions. - final_activation_params (dict): Parameters to provide to the activation function. - norm (str): Normalization method. - norm_params (dict): Parameters to provide to the underlying normalization used along with the convolution. - kernel_size (int): Kernel size for the initial convolution. - last_kernel_size (int): Kernel size for the initial convolution. - residual_kernel_size (int): Kernel size for the residual layers. - dilation_base (int): How much to increase the dilation with each layer. - causal (bool): Whether to use fully causal convolution. - pad_mode (str): Padding mode for the convolutions. - true_skip (bool): Whether to use true skip connection or a simple. - (streamable) convolution as the skip connection in the residual network blocks. - compress (int): Reduced dimensionality in residual branches (from Demucs v3). - lstm (int): Number of LSTM layers at the end of the encoder. - disable_norm_outer_blocks (int): Number of blocks for which we don't apply norm. - For the decoder, it corresponds to the N last blocks. - trim_right_ratio (float): Ratio for trimming at the right of the transposed convolution under the causal setup. - If equal to 1.0, it means that all the trimming is done at the right. - """ - def __init__(self, channels: int = 1, dimension: int = 128, n_filters: int = 32, n_residual_layers: int = 3, - ratios: tp.List[int] = [8, 5, 4, 2], activation: str = 'ELU', activation_params: dict = {'alpha': 1.0}, - final_activation: tp.Optional[str] = None, final_activation_params: tp.Optional[dict] = None, - norm: str = 'none', norm_params: tp.Dict[str, tp.Any] = {}, kernel_size: int = 7, - last_kernel_size: int = 7, residual_kernel_size: int = 3, dilation_base: int = 2, causal: bool = False, - pad_mode: str = 'reflect', true_skip: bool = True, compress: int = 2, lstm: int = 0, - disable_norm_outer_blocks: int = 0, trim_right_ratio: float = 1.0): - super().__init__() - self.dimension = dimension - self.channels = channels - self.n_filters = n_filters - self.ratios = ratios - del ratios - self.n_residual_layers = n_residual_layers - self.hop_length = np.prod(self.ratios) - self.n_blocks = len(self.ratios) + 2 # first and last conv + residual blocks - self.disable_norm_outer_blocks = disable_norm_outer_blocks - assert self.disable_norm_outer_blocks >= 0 and self.disable_norm_outer_blocks <= self.n_blocks, \ - "Number of blocks for which to disable norm is invalid." \ - "It should be lower or equal to the actual number of blocks in the network and greater or equal to 0." - - act = getattr(nn, activation) - mult = int(2 ** len(self.ratios)) - model: tp.List[nn.Module] = [ - StreamableConv1d(dimension, mult * n_filters, kernel_size, - norm='none' if self.disable_norm_outer_blocks == self.n_blocks else norm, - norm_kwargs=norm_params, causal=causal, pad_mode=pad_mode) - ] - - if lstm: - model += [StreamableLSTM(mult * n_filters, num_layers=lstm)] - - # Upsample to raw audio scale - for i, ratio in enumerate(self.ratios): - block_norm = 'none' if self.disable_norm_outer_blocks >= self.n_blocks - (i + 1) else norm - # Add upsampling layers - model += [ - act(**activation_params), - StreamableConvTranspose1d(mult * n_filters, mult * n_filters // 2, - kernel_size=ratio * 2, stride=ratio, - norm=block_norm, norm_kwargs=norm_params, - causal=causal, trim_right_ratio=trim_right_ratio), - ] - # Add residual layers - for j in range(n_residual_layers): - model += [ - SEANetResnetBlock(mult * n_filters // 2, kernel_sizes=[residual_kernel_size, 1], - dilations=[dilation_base ** j, 1], - activation=activation, activation_params=activation_params, - norm=block_norm, norm_params=norm_params, causal=causal, - pad_mode=pad_mode, compress=compress, true_skip=true_skip)] - - mult //= 2 - - # Add final layers - model += [ - act(**activation_params), - StreamableConv1d(n_filters, channels, last_kernel_size, - norm='none' if self.disable_norm_outer_blocks >= 1 else norm, - norm_kwargs=norm_params, causal=causal, pad_mode=pad_mode) - ] - # Add optional final activation to decoder (eg. tanh) - if final_activation is not None: - final_act = getattr(nn, final_activation) - final_activation_params = final_activation_params or {} - model += [ - final_act(**final_activation_params) - ] - self.model = nn.Sequential(*model) - - def forward(self, z): - y = self.model(z) - return y diff --git a/spaces/Hallucinate/demo/ldm/modules/x_transformer.py b/spaces/Hallucinate/demo/ldm/modules/x_transformer.py deleted file mode 100644 index 5fc15bf9cfe0111a910e7de33d04ffdec3877576..0000000000000000000000000000000000000000 --- a/spaces/Hallucinate/demo/ldm/modules/x_transformer.py +++ /dev/null @@ -1,641 +0,0 @@ -"""shout-out to https://github.com/lucidrains/x-transformers/tree/main/x_transformers""" -import torch -from torch import nn, einsum -import torch.nn.functional as F -from functools import partial -from inspect import isfunction -from collections import namedtuple -from einops import rearrange, repeat, reduce - -# constants - -DEFAULT_DIM_HEAD = 64 - -Intermediates = namedtuple('Intermediates', [ - 'pre_softmax_attn', - 'post_softmax_attn' -]) - -LayerIntermediates = namedtuple('Intermediates', [ - 'hiddens', - 'attn_intermediates' -]) - - -class AbsolutePositionalEmbedding(nn.Module): - def __init__(self, dim, max_seq_len): - super().__init__() - self.emb = nn.Embedding(max_seq_len, dim) - self.init_() - - def init_(self): - nn.init.normal_(self.emb.weight, std=0.02) - - def forward(self, x): - n = torch.arange(x.shape[1], device=x.device) - return self.emb(n)[None, :, :] - - -class FixedPositionalEmbedding(nn.Module): - def __init__(self, dim): - super().__init__() - inv_freq = 1. / (10000 ** (torch.arange(0, dim, 2).float() / dim)) - self.register_buffer('inv_freq', inv_freq) - - def forward(self, x, seq_dim=1, offset=0): - t = torch.arange(x.shape[seq_dim], device=x.device).type_as(self.inv_freq) + offset - sinusoid_inp = torch.einsum('i , j -> i j', t, self.inv_freq) - emb = torch.cat((sinusoid_inp.sin(), sinusoid_inp.cos()), dim=-1) - return emb[None, :, :] - - -# helpers - -def exists(val): - return val is not None - - -def default(val, d): - if exists(val): - return val - return d() if isfunction(d) else d - - -def always(val): - def inner(*args, **kwargs): - return val - return inner - - -def not_equals(val): - def inner(x): - return x != val - return inner - - -def equals(val): - def inner(x): - return x == val - return inner - - -def max_neg_value(tensor): - return -torch.finfo(tensor.dtype).max - - -# keyword argument helpers - -def pick_and_pop(keys, d): - values = list(map(lambda key: d.pop(key), keys)) - return dict(zip(keys, values)) - - -def group_dict_by_key(cond, d): - return_val = [dict(), dict()] - for key in d.keys(): - match = bool(cond(key)) - ind = int(not match) - return_val[ind][key] = d[key] - return (*return_val,) - - -def string_begins_with(prefix, str): - return str.startswith(prefix) - - -def group_by_key_prefix(prefix, d): - return group_dict_by_key(partial(string_begins_with, prefix), d) - - -def groupby_prefix_and_trim(prefix, d): - kwargs_with_prefix, kwargs = group_dict_by_key(partial(string_begins_with, prefix), d) - kwargs_without_prefix = dict(map(lambda x: (x[0][len(prefix):], x[1]), tuple(kwargs_with_prefix.items()))) - return kwargs_without_prefix, kwargs - - -# classes -class Scale(nn.Module): - def __init__(self, value, fn): - super().__init__() - self.value = value - self.fn = fn - - def forward(self, x, **kwargs): - x, *rest = self.fn(x, **kwargs) - return (x * self.value, *rest) - - -class Rezero(nn.Module): - def __init__(self, fn): - super().__init__() - self.fn = fn - self.g = nn.Parameter(torch.zeros(1)) - - def forward(self, x, **kwargs): - x, *rest = self.fn(x, **kwargs) - return (x * self.g, *rest) - - -class ScaleNorm(nn.Module): - def __init__(self, dim, eps=1e-5): - super().__init__() - self.scale = dim ** -0.5 - self.eps = eps - self.g = nn.Parameter(torch.ones(1)) - - def forward(self, x): - norm = torch.norm(x, dim=-1, keepdim=True) * self.scale - return x / norm.clamp(min=self.eps) * self.g - - -class RMSNorm(nn.Module): - def __init__(self, dim, eps=1e-8): - super().__init__() - self.scale = dim ** -0.5 - self.eps = eps - self.g = nn.Parameter(torch.ones(dim)) - - def forward(self, x): - norm = torch.norm(x, dim=-1, keepdim=True) * self.scale - return x / norm.clamp(min=self.eps) * self.g - - -class Residual(nn.Module): - def forward(self, x, residual): - return x + residual - - -class GRUGating(nn.Module): - def __init__(self, dim): - super().__init__() - self.gru = nn.GRUCell(dim, dim) - - def forward(self, x, residual): - gated_output = self.gru( - rearrange(x, 'b n d -> (b n) d'), - rearrange(residual, 'b n d -> (b n) d') - ) - - return gated_output.reshape_as(x) - - -# feedforward - -class GEGLU(nn.Module): - def __init__(self, dim_in, dim_out): - super().__init__() - self.proj = nn.Linear(dim_in, dim_out * 2) - - def forward(self, x): - x, gate = self.proj(x).chunk(2, dim=-1) - return x * F.gelu(gate) - - -class FeedForward(nn.Module): - def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.): - super().__init__() - inner_dim = int(dim * mult) - dim_out = default(dim_out, dim) - project_in = nn.Sequential( - nn.Linear(dim, inner_dim), - nn.GELU() - ) if not glu else GEGLU(dim, inner_dim) - - self.net = nn.Sequential( - project_in, - nn.Dropout(dropout), - nn.Linear(inner_dim, dim_out) - ) - - def forward(self, x): - return self.net(x) - - -# attention. -class Attention(nn.Module): - def __init__( - self, - dim, - dim_head=DEFAULT_DIM_HEAD, - heads=8, - causal=False, - mask=None, - talking_heads=False, - sparse_topk=None, - use_entmax15=False, - num_mem_kv=0, - dropout=0., - on_attn=False - ): - super().__init__() - if use_entmax15: - raise NotImplementedError("Check out entmax activation instead of softmax activation!") - self.scale = dim_head ** -0.5 - self.heads = heads - self.causal = causal - self.mask = mask - - inner_dim = dim_head * heads - - self.to_q = nn.Linear(dim, inner_dim, bias=False) - self.to_k = nn.Linear(dim, inner_dim, bias=False) - self.to_v = nn.Linear(dim, inner_dim, bias=False) - self.dropout = nn.Dropout(dropout) - - # talking heads - self.talking_heads = talking_heads - if talking_heads: - self.pre_softmax_proj = nn.Parameter(torch.randn(heads, heads)) - self.post_softmax_proj = nn.Parameter(torch.randn(heads, heads)) - - # explicit topk sparse attention - self.sparse_topk = sparse_topk - - # entmax - #self.attn_fn = entmax15 if use_entmax15 else F.softmax - self.attn_fn = F.softmax - - # add memory key / values - self.num_mem_kv = num_mem_kv - if num_mem_kv > 0: - self.mem_k = nn.Parameter(torch.randn(heads, num_mem_kv, dim_head)) - self.mem_v = nn.Parameter(torch.randn(heads, num_mem_kv, dim_head)) - - # attention on attention - self.attn_on_attn = on_attn - self.to_out = nn.Sequential(nn.Linear(inner_dim, dim * 2), nn.GLU()) if on_attn else nn.Linear(inner_dim, dim) - - def forward( - self, - x, - context=None, - mask=None, - context_mask=None, - rel_pos=None, - sinusoidal_emb=None, - prev_attn=None, - mem=None - ): - b, n, _, h, talking_heads, device = *x.shape, self.heads, self.talking_heads, x.device - kv_input = default(context, x) - - q_input = x - k_input = kv_input - v_input = kv_input - - if exists(mem): - k_input = torch.cat((mem, k_input), dim=-2) - v_input = torch.cat((mem, v_input), dim=-2) - - if exists(sinusoidal_emb): - # in shortformer, the query would start at a position offset depending on the past cached memory - offset = k_input.shape[-2] - q_input.shape[-2] - q_input = q_input + sinusoidal_emb(q_input, offset=offset) - k_input = k_input + sinusoidal_emb(k_input) - - q = self.to_q(q_input) - k = self.to_k(k_input) - v = self.to_v(v_input) - - q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h=h), (q, k, v)) - - input_mask = None - if any(map(exists, (mask, context_mask))): - q_mask = default(mask, lambda: torch.ones((b, n), device=device).bool()) - k_mask = q_mask if not exists(context) else context_mask - k_mask = default(k_mask, lambda: torch.ones((b, k.shape[-2]), device=device).bool()) - q_mask = rearrange(q_mask, 'b i -> b () i ()') - k_mask = rearrange(k_mask, 'b j -> b () () j') - input_mask = q_mask * k_mask - - if self.num_mem_kv > 0: - mem_k, mem_v = map(lambda t: repeat(t, 'h n d -> b h n d', b=b), (self.mem_k, self.mem_v)) - k = torch.cat((mem_k, k), dim=-2) - v = torch.cat((mem_v, v), dim=-2) - if exists(input_mask): - input_mask = F.pad(input_mask, (self.num_mem_kv, 0), value=True) - - dots = einsum('b h i d, b h j d -> b h i j', q, k) * self.scale - mask_value = max_neg_value(dots) - - if exists(prev_attn): - dots = dots + prev_attn - - pre_softmax_attn = dots - - if talking_heads: - dots = einsum('b h i j, h k -> b k i j', dots, self.pre_softmax_proj).contiguous() - - if exists(rel_pos): - dots = rel_pos(dots) - - if exists(input_mask): - dots.masked_fill_(~input_mask, mask_value) - del input_mask - - if self.causal: - i, j = dots.shape[-2:] - r = torch.arange(i, device=device) - mask = rearrange(r, 'i -> () () i ()') < rearrange(r, 'j -> () () () j') - mask = F.pad(mask, (j - i, 0), value=False) - dots.masked_fill_(mask, mask_value) - del mask - - if exists(self.sparse_topk) and self.sparse_topk < dots.shape[-1]: - top, _ = dots.topk(self.sparse_topk, dim=-1) - vk = top[..., -1].unsqueeze(-1).expand_as(dots) - mask = dots < vk - dots.masked_fill_(mask, mask_value) - del mask - - attn = self.attn_fn(dots, dim=-1) - post_softmax_attn = attn - - attn = self.dropout(attn) - - if talking_heads: - attn = einsum('b h i j, h k -> b k i j', attn, self.post_softmax_proj).contiguous() - - out = einsum('b h i j, b h j d -> b h i d', attn, v) - out = rearrange(out, 'b h n d -> b n (h d)') - - intermediates = Intermediates( - pre_softmax_attn=pre_softmax_attn, - post_softmax_attn=post_softmax_attn - ) - - return self.to_out(out), intermediates - - -class AttentionLayers(nn.Module): - def __init__( - self, - dim, - depth, - heads=8, - causal=False, - cross_attend=False, - only_cross=False, - use_scalenorm=False, - use_rmsnorm=False, - use_rezero=False, - rel_pos_num_buckets=32, - rel_pos_max_distance=128, - position_infused_attn=False, - custom_layers=None, - sandwich_coef=None, - par_ratio=None, - residual_attn=False, - cross_residual_attn=False, - macaron=False, - pre_norm=True, - gate_residual=False, - **kwargs - ): - super().__init__() - ff_kwargs, kwargs = groupby_prefix_and_trim('ff_', kwargs) - attn_kwargs, _ = groupby_prefix_and_trim('attn_', kwargs) - - dim_head = attn_kwargs.get('dim_head', DEFAULT_DIM_HEAD) - - self.dim = dim - self.depth = depth - self.layers = nn.ModuleList([]) - - self.has_pos_emb = position_infused_attn - self.pia_pos_emb = FixedPositionalEmbedding(dim) if position_infused_attn else None - self.rotary_pos_emb = always(None) - - assert rel_pos_num_buckets <= rel_pos_max_distance, 'number of relative position buckets must be less than the relative position max distance' - self.rel_pos = None - - self.pre_norm = pre_norm - - self.residual_attn = residual_attn - self.cross_residual_attn = cross_residual_attn - - norm_class = ScaleNorm if use_scalenorm else nn.LayerNorm - norm_class = RMSNorm if use_rmsnorm else norm_class - norm_fn = partial(norm_class, dim) - - norm_fn = nn.Identity if use_rezero else norm_fn - branch_fn = Rezero if use_rezero else None - - if cross_attend and not only_cross: - default_block = ('a', 'c', 'f') - elif cross_attend and only_cross: - default_block = ('c', 'f') - else: - default_block = ('a', 'f') - - if macaron: - default_block = ('f',) + default_block - - if exists(custom_layers): - layer_types = custom_layers - elif exists(par_ratio): - par_depth = depth * len(default_block) - assert 1 < par_ratio <= par_depth, 'par ratio out of range' - default_block = tuple(filter(not_equals('f'), default_block)) - par_attn = par_depth // par_ratio - depth_cut = par_depth * 2 // 3 # 2 / 3 attention layer cutoff suggested by PAR paper - par_width = (depth_cut + depth_cut // par_attn) // par_attn - assert len(default_block) <= par_width, 'default block is too large for par_ratio' - par_block = default_block + ('f',) * (par_width - len(default_block)) - par_head = par_block * par_attn - layer_types = par_head + ('f',) * (par_depth - len(par_head)) - elif exists(sandwich_coef): - assert sandwich_coef > 0 and sandwich_coef <= depth, 'sandwich coefficient should be less than the depth' - layer_types = ('a',) * sandwich_coef + default_block * (depth - sandwich_coef) + ('f',) * sandwich_coef - else: - layer_types = default_block * depth - - self.layer_types = layer_types - self.num_attn_layers = len(list(filter(equals('a'), layer_types))) - - for layer_type in self.layer_types: - if layer_type == 'a': - layer = Attention(dim, heads=heads, causal=causal, **attn_kwargs) - elif layer_type == 'c': - layer = Attention(dim, heads=heads, **attn_kwargs) - elif layer_type == 'f': - layer = FeedForward(dim, **ff_kwargs) - layer = layer if not macaron else Scale(0.5, layer) - else: - raise Exception(f'invalid layer type {layer_type}') - - if isinstance(layer, Attention) and exists(branch_fn): - layer = branch_fn(layer) - - if gate_residual: - residual_fn = GRUGating(dim) - else: - residual_fn = Residual() - - self.layers.append(nn.ModuleList([ - norm_fn(), - layer, - residual_fn - ])) - - def forward( - self, - x, - context=None, - mask=None, - context_mask=None, - mems=None, - return_hiddens=False - ): - hiddens = [] - intermediates = [] - prev_attn = None - prev_cross_attn = None - - mems = mems.copy() if exists(mems) else [None] * self.num_attn_layers - - for ind, (layer_type, (norm, block, residual_fn)) in enumerate(zip(self.layer_types, self.layers)): - is_last = ind == (len(self.layers) - 1) - - if layer_type == 'a': - hiddens.append(x) - layer_mem = mems.pop(0) - - residual = x - - if self.pre_norm: - x = norm(x) - - if layer_type == 'a': - out, inter = block(x, mask=mask, sinusoidal_emb=self.pia_pos_emb, rel_pos=self.rel_pos, - prev_attn=prev_attn, mem=layer_mem) - elif layer_type == 'c': - out, inter = block(x, context=context, mask=mask, context_mask=context_mask, prev_attn=prev_cross_attn) - elif layer_type == 'f': - out = block(x) - - x = residual_fn(out, residual) - - if layer_type in ('a', 'c'): - intermediates.append(inter) - - if layer_type == 'a' and self.residual_attn: - prev_attn = inter.pre_softmax_attn - elif layer_type == 'c' and self.cross_residual_attn: - prev_cross_attn = inter.pre_softmax_attn - - if not self.pre_norm and not is_last: - x = norm(x) - - if return_hiddens: - intermediates = LayerIntermediates( - hiddens=hiddens, - attn_intermediates=intermediates - ) - - return x, intermediates - - return x - - -class Encoder(AttentionLayers): - def __init__(self, **kwargs): - assert 'causal' not in kwargs, 'cannot set causality on encoder' - super().__init__(causal=False, **kwargs) - - - -class TransformerWrapper(nn.Module): - def __init__( - self, - *, - num_tokens, - max_seq_len, - attn_layers, - emb_dim=None, - max_mem_len=0., - emb_dropout=0., - num_memory_tokens=None, - tie_embedding=False, - use_pos_emb=True - ): - super().__init__() - assert isinstance(attn_layers, AttentionLayers), 'attention layers must be one of Encoder or Decoder' - - dim = attn_layers.dim - emb_dim = default(emb_dim, dim) - - self.max_seq_len = max_seq_len - self.max_mem_len = max_mem_len - self.num_tokens = num_tokens - - self.token_emb = nn.Embedding(num_tokens, emb_dim) - self.pos_emb = AbsolutePositionalEmbedding(emb_dim, max_seq_len) if ( - use_pos_emb and not attn_layers.has_pos_emb) else always(0) - self.emb_dropout = nn.Dropout(emb_dropout) - - self.project_emb = nn.Linear(emb_dim, dim) if emb_dim != dim else nn.Identity() - self.attn_layers = attn_layers - self.norm = nn.LayerNorm(dim) - - self.init_() - - self.to_logits = nn.Linear(dim, num_tokens) if not tie_embedding else lambda t: t @ self.token_emb.weight.t() - - # memory tokens (like [cls]) from Memory Transformers paper - num_memory_tokens = default(num_memory_tokens, 0) - self.num_memory_tokens = num_memory_tokens - if num_memory_tokens > 0: - self.memory_tokens = nn.Parameter(torch.randn(num_memory_tokens, dim)) - - # let funnel encoder know number of memory tokens, if specified - if hasattr(attn_layers, 'num_memory_tokens'): - attn_layers.num_memory_tokens = num_memory_tokens - - def init_(self): - nn.init.normal_(self.token_emb.weight, std=0.02) - - def forward( - self, - x, - return_embeddings=False, - mask=None, - return_mems=False, - return_attn=False, - mems=None, - **kwargs - ): - b, n, device, num_mem = *x.shape, x.device, self.num_memory_tokens - x = self.token_emb(x) - x += self.pos_emb(x) - x = self.emb_dropout(x) - - x = self.project_emb(x) - - if num_mem > 0: - mem = repeat(self.memory_tokens, 'n d -> b n d', b=b) - x = torch.cat((mem, x), dim=1) - - # auto-handle masking after appending memory tokens - if exists(mask): - mask = F.pad(mask, (num_mem, 0), value=True) - - x, intermediates = self.attn_layers(x, mask=mask, mems=mems, return_hiddens=True, **kwargs) - x = self.norm(x) - - mem, x = x[:, :num_mem], x[:, num_mem:] - - out = self.to_logits(x) if not return_embeddings else x - - if return_mems: - hiddens = intermediates.hiddens - new_mems = list(map(lambda pair: torch.cat(pair, dim=-2), zip(mems, hiddens))) if exists(mems) else hiddens - new_mems = list(map(lambda t: t[..., -self.max_mem_len:, :].detach(), new_mems)) - return out, new_mems - - if return_attn: - attn_maps = list(map(lambda t: t.post_softmax_attn, intermediates.attn_intermediates)) - return out, attn_maps - - return out - diff --git a/spaces/Hamda/AraJARIR/app.py b/spaces/Hamda/AraJARIR/app.py deleted file mode 100644 index 885a8d0fa2327554876d2f743552f4f8044fffd3..0000000000000000000000000000000000000000 --- a/spaces/Hamda/AraJARIR/app.py +++ /dev/null @@ -1,129 +0,0 @@ -import streamlit as st -import transformers -from transformers import pipeline -from transformers import AutoTokenizer, AutoModelForMaskedLM -import pandas as pd -import string -from time import time -from PIL import Image - - -image = Image.open('./Logo_APP.jpg') -n_image = image.resize((150, 150)) -st.image(n_image) - -st.title("المساعدة اللغوية في التنبؤ بالمتلازمات والمتصاحبات وتصحيحها") -default_value = "أستاذ التعليم" - -# sent is the variable holding the user's input -sent = st.text_area('المدخل',default_value) - -tokenizer = AutoTokenizer.from_pretrained("moussaKam/AraBART", max_length=128, padding=True, pad_to_max_length = True, truncation=True) - -model = AutoModelForMaskedLM.from_pretrained("Hamda/test-1-finetuned-AraBART") -pipe = pipeline("fill-mask", tokenizer=tokenizer, model=model, top_k=10) - -def next_word(text, pipe): - res_dict= { - 'الكلمة المقترحة':[], - 'العلامة':[], - } - for e in pipe(text): - if all(c not in list(string.punctuation) for c in e['token_str']): - res_dict['الكلمة المقترحة'].append(e['token_str']) - res_dict['العلامة'].append(e['score']) - return res_dict - -if (st.button('بحث', disabled=False)): - text_st = sent+ ' ' - dict_next_words = next_word(text_st, pipe) - df = pd.DataFrame.from_dict(dict_next_words) - st.dataframe(df) -#using Graph - -if (st.checkbox('الاستعانة بالرسم البياني المعرفي الاحتمالي', value=False)): - a = time() - VocMap = './voc.csv' - ScoreMap = './BM25.csv' - - #@st.cache - def reading_df(path1, path2): - df_voc = pd.read_csv(path1, delimiter='\t') - df_graph = pd.read_csv(path2, delimiter='\t') - df_graph.set_index(['ID1','ID2'], inplace=True) - df_gr = pd.read_csv(ScoreMap, delimiter='\t') - df_gr.set_index(['ID1'], inplace=True) - return df_voc, df_graph, df_gr - - df3, df_g, df_in = reading_df(VocMap, ScoreMap) - - - def Query2id(voc, query): - res= [] - for word in query.split(): - try: - res.append(voc.index[voc['word'] == word].values[0]) - except (IndexError, KeyError) as e: - st.write('Token not found') - continue - return res - - id_list = Query2id(df3, sent) - - def setQueriesVoc(df, id_list): - res = [] - for e in id_list: - try: - res.extend(list(df.loc[e]['ID2'].values)) - except (KeyError, AttributeError) as f: - st.write('Token not found') - continue - return list(set(res)) - - L = setQueriesVoc(df_in, id_list) - @st.cache - def compute_score(L_terms, id_l): - tmt = {} - for nc in L_terms: - score = 0.0 - temp = [] - for ni in id_l: - try: - score = score + df_g.loc[(ni, nc),'score'] - except KeyError: - continue - key = df3.loc[nc].values[0] - tmt[key] = score - return tmt - tmt = compute_score(L, id_list) - exp_terms = [] - t_li = tmt.values() - tmexp = sorted(tmt.items(), key=lambda x: x[1], reverse=True) - i = 0 - dict_res = {'الكلمة المقترحة':[], - 'العلامة':[]} - for key, value in tmexp: - new_score=((value-min(t_li))/(max(t_li)-min(t_li)))-0.0001 - dict_res['العلامة'].append(str(new_score)[:6]) - dict_res['الكلمة المقترحة'].append(key) - i+=1 - if (i==10): - break - res_df = pd.DataFrame.from_dict(dict_res) - res_df.index += 1 - b = time() - exec_time = (b-a) - text_st = sent+ ' ' - dict_next_words = next_word(text_st, pipe) - df = pd.DataFrame.from_dict(dict_next_words) - df.index += 1 - str_time = str(exec_time)[:3] - - st.markdown("""---""") - st.header("الكلمات المقترحة باستعمال النموذج اللغوي") - st.dataframe(df) - st.markdown("""---""") - st.header("الكلمات المقترحة باستعمال الرسم البياني") - st.dataframe(res_df) - st.markdown("""---""") - st.write(f'{str_time} s :الوقت المستغرق باستعمال الرسم البياني') \ No newline at end of file diff --git a/spaces/HarryLee/eCommerceImageCaptioning/app.py b/spaces/HarryLee/eCommerceImageCaptioning/app.py deleted file mode 100644 index 0c0a564561fb481f382a40197c42d6edc9b6ca5a..0000000000000000000000000000000000000000 --- a/spaces/HarryLee/eCommerceImageCaptioning/app.py +++ /dev/null @@ -1,125 +0,0 @@ -# author : LiHE -import os - -os.system('cd fairseq;' - 'pip install --use-feature=in-tree-build ./; cd ..') -os.system('ls -l') - -import torch -import numpy as np -from fairseq import utils, tasks -from fairseq import checkpoint_utils -from utils.eval_utils import eval_step -from tasks.mm_tasks.caption import CaptionTask -from models.ofa import OFAModel -from PIL import Image -from torchvision import transforms -import gradio as gr - -# Register caption task -tasks.register_task('caption', CaptionTask) -# turn on cuda if GPU is available -use_cuda = torch.cuda.is_available() -# use fp16 only when GPU is available -use_fp16 = False - -os.system('wget https://ofa-silicon.oss-us-west-1.aliyuncs.com/checkpoints/caption_large_best_clean.pt; ' - 'mkdir -p checkpoints; mv caption_large_best_clean.pt checkpoints/caption.pt') - -# Load pretrained ckpt & config -overrides = {"bpe_dir": "utils/BPE", "eval_cider": False, "beam": 5, - "max_len_b": 16, "no_repeat_ngram_size": 3, "seed": 7} -models, cfg, task = checkpoint_utils.load_model_ensemble_and_task( - utils.split_paths('checkpoints/caption.pt'), - arg_overrides=overrides -) - -# Move models to GPU -for model in models: - model.eval() - if use_fp16: - model.half() - if use_cuda and not cfg.distributed_training.pipeline_model_parallel: - model.cuda() - model.prepare_for_inference_(cfg) - -# Initialize generator -generator = task.build_generator(models, cfg.generation) - -mean = [0.5, 0.5, 0.5] -std = [0.5, 0.5, 0.5] - -patch_resize_transform = transforms.Compose([ - lambda image: image.convert("RGB"), - transforms.Resize((cfg.task.patch_image_size, cfg.task.patch_image_size), interpolation=Image.BICUBIC), - transforms.ToTensor(), - transforms.Normalize(mean=mean, std=std), -]) - -# Text preprocess -bos_item = torch.LongTensor([task.src_dict.bos()]) -eos_item = torch.LongTensor([task.src_dict.eos()]) -pad_idx = task.src_dict.pad() - - -def encode_text(text, length=None, append_bos=False, append_eos=False): - s = task.tgt_dict.encode_line( - line=task.bpe.encode(text), - add_if_not_exist=False, - append_eos=False - ).long() - if length is not None: - s = s[:length] - if append_bos: - s = torch.cat([bos_item, s]) - if append_eos: - s = torch.cat([s, eos_item]) - return s - - -# Construct input for caption task -def construct_sample(image: Image): - patch_image = patch_resize_transform(image).unsqueeze(0) - patch_mask = torch.tensor([True]) - src_text = encode_text(" what does the image describe?", append_bos=True, append_eos=True).unsqueeze(0) - src_length = torch.LongTensor([s.ne(pad_idx).long().sum() for s in src_text]) - sample = { - "id": np.array(['42']), - "net_input": { - "src_tokens": src_text, - "src_lengths": src_length, - "patch_images": patch_image, - "patch_masks": patch_mask - } - } - return sample - - -# Function to turn FP32 to FP16 -def apply_half(t): - if t.dtype is torch.float32: - return t.to(dtype=torch.half) - return t - - -# Function for image captioning -def image_caption(Image): - sample = construct_sample(Image) - sample = utils.move_to_cuda(sample) if use_cuda else sample - sample = utils.apply_to_sample(apply_half, sample) if use_fp16 else sample - with torch.no_grad(): - result, scores = eval_step(task, generator, models, sample) - return result[0]['caption'] - - -title = "eRupt e-Commerce Image Captioning" -description = "Online Demo for e-Commerce Image Captioning. Upload your own image or click any one of the examples, and click " \ - "\"Submit\" and then wait for the generated caption. " -article = "

LIHE Github " \ - "Repo

" -examples = [['0001.jpg'], ['0002.jpg'], ['0003.jpg'], ['0004.jpg'], ['0005.jpg']] -io = gr.Interface(fn=image_caption, inputs=gr.inputs.Image(type='pil'), outputs=gr.outputs.Textbox(label="Caption"), - title=title, description=description, article=article, examples=examples, - allow_flagging=False, allow_screenshot=False) -#io.launch(cache_examples=True) -io.launch() diff --git a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/fairseq/optim/bmuf.py b/spaces/HarryLee/eCommerceImageCaptioning/fairseq/fairseq/optim/bmuf.py deleted file mode 100644 index d6d0e04e86eb894efe59e13a78843d01ca9e651d..0000000000000000000000000000000000000000 --- a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/fairseq/optim/bmuf.py +++ /dev/null @@ -1,200 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -from dataclasses import dataclass, field - -import torch -import torch.distributed as dist -from fairseq.dataclass.configs import FairseqBMUFConfig -from fairseq.dataclass.utils import gen_parser_from_dataclass -from fairseq.optim.fairseq_optimizer import FairseqOptimizer - - -class FairseqBMUF(FairseqOptimizer): - """ - Implements incremental block distributed data parallelism similar to - https://ieeexplore.ieee.org/document/7472805 - - Paper title: Scalable training of deep learning machines by incremental - block training with intra-block parallel optimization and blockwise - model-update filtering - """ - - def __init__(self, cfg: FairseqBMUFConfig, optimizer): - super().__init__(cfg) - self._optimizer = optimizer - self._num_updates = 0 - self.sync_iter = cfg.global_sync_iter - self.block_momentum = cfg.block_momentum - self.block_lr = cfg.block_lr - self._reset_local_data() - self.warmup_iteration = cfg.warmup_iterations - self.use_nbm = cfg.use_nbm - self.initial_state = self._optimizer.state_dict() - self.average_sync = self.cfg.average_sync - self.world_size = self.cfg.distributed_world_size - - @staticmethod - def add_args(parser): - """Add optimizer-specific arguments to the parser.""" - gen_parser_from_dataclass(parser, FairseqBMUFConfig()) - - @property - def optimizer(self): - return self._optimizer.optimizer - - @property - def optimizer_config(self): - return self._optimizer.optimizer_config - - def get_lr(self): - return self._optimizer.get_lr() - - def set_lr(self, lr): - self._optimizer.set_lr(lr) - - def state_dict(self): - return self._optimizer.state_dict() - - def load_state_dict(self, state_dict, optimizer_overrides=None): - self._optimizer.load_state_dict(state_dict, optimizer_overrides) - self.initial_state = self._optimizer.state_dict() - - def multiply_grads(self, c): - """Multiplies grads by a constant *c*.""" - self._optimizer.multiply_grads(c) - - def clip_grad_norm(self, max_norm, aggregate_norm_fn=None): - """Clips gradient norm.""" - return self._optimizer.clip_grad_norm(max_norm, aggregate_norm_fn) - - def average_params(self): - self._optimizer.average_params() - - def _block_sync(self): - if self.world_size <= 1: - return - # Update the global model using local models from all GPUs - # (Step-1) Calculate grad between previously synced model and - # currrent local model - if self.block_momentum != 0: - self._calc_grad() - - # (Step-2) Average gradient from all GPUs - self._avg_grad_from_all_gpus() - - # (Step-3) Calculate global momentum and update the global model - if self.block_momentum != 0: - self._update_global_model() - - # (Step-4) Average local optimizer params - if self.average_sync: - self.average_params() - - def _is_warmup_end(self): - # Check whether train iterations is equal to warmup iter - if self.get_num_updates() == self.warmup_iteration: - return True - return False - - def _is_bmuf_iter(self): - # Check whether train iterations is equal to bmuf sync iter - if (self.get_num_updates() > self.warmup_iteration) and ( - self.get_num_updates() % self.sync_iter == 0 - ): - return True - return False - - def _warmup_sync(self, root_rank=0): - if self.world_size <= 1: - return - # Broadcast the local model to all gpus - for param in self.params: - dist.broadcast(param.data, src=root_rank) - - # Update local optimizer state - if self.average_sync: - self._optimizer.average_params() - else: - self._optimizer.load_state_dict(self.initial_state) - - self._reset_local_data() - - def step(self, closure=None): - """Performs a single optimization step.""" - self._optimizer.step(closure) - self.set_num_updates(self.get_num_updates() + 1) - if self._is_warmup_end(): - self._warmup_sync() - elif self._is_bmuf_iter(): - self._block_sync() - - def zero_grad(self): - """Clears the gradients of all optimized parameters.""" - self._optimizer.zero_grad() - - def get_num_updates(self): - """Get the number of parameters updates.""" - return self._num_updates - - def set_num_updates(self, num_updates): - """Set the number of parameters updates.""" - self._num_updates = num_updates - - @torch.no_grad() - def _reset_local_data(self): - # (Step-0) Initialize global momentum parameters and store global copy on each gpu - self.global_params = [torch.zeros_like(p.data) for p in self.params] - self.smoothed_grads = [p.data.new_zeros(p.data.size()) for p in self.params] - self.grads = [p.data.new_zeros(p.data.size()) for p in self.params] - - # saving the global model locally for calculating gradient during bmuf sync - for param, global_param in zip(self.params, self.global_params): - global_param.copy_(param.data) - - @torch.no_grad() - def _calc_grad(self): - # global_params is basically the global copy from the previously finished - # synchronisation. param.data is local parameter after block_sync_freq - # for the local gpu. so grad is difference between previously synced - # model and currrent local model. - for index, (param, global_param) in enumerate( - zip(self.params, self.global_params) - ): - self.grads[index] = global_param - param.data - - def _avg_grad_from_all_gpus(self): - for index, param in enumerate(self.params): - sync_para = param.data if self.block_momentum == 0 else self.grads[index] - sync_para /= float(dist.get_world_size()) - dist.all_reduce(sync_para, op=dist.ReduceOp.SUM) - - @torch.no_grad() - def _update_global_model(self): - for index, (param, global_param, smoothed_grad, grad) in enumerate( - zip( - self.params, - self.global_params, - self.smoothed_grads, - # all gpus would share the same value of smoothed_grad, since it is - # always computed on synchronized gradients. - self.grads, - ) - ): - # global_param is basically last syncrhornized parameter. though - # smoothed_grad is local, all processes will have same value of - # smoothed_grad and hence param is globally synchronized copy. - # smoothed_grad(t) = BM * smoothed_grad(t-1) + BM_lr * grad(t) - smoothed_grad = self.block_momentum * smoothed_grad + self.block_lr * grad - param.data.copy_(global_param - smoothed_grad) - - # A Nesterov momentum here is to do a partial weight update before - # calculating the gradient - if self.use_nbm: - param.data.copy_(param.data - self.block_momentum * smoothed_grad) - - # backup for the next synchronization. - self.smoothed_grads[index] = smoothed_grad - global_param.copy_(param.data) diff --git a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/scripts/convert_dictionary.lua b/spaces/HarryLee/eCommerceImageCaptioning/fairseq/scripts/convert_dictionary.lua deleted file mode 100644 index 14ee8c997f642c8ff196617c2dcd0584037a60c4..0000000000000000000000000000000000000000 --- a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/scripts/convert_dictionary.lua +++ /dev/null @@ -1,34 +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. --- --- Usage: convert_dictionary.lua -require 'fairseq' -require 'torch' -require 'paths' - -if #arg < 1 then - print('usage: convert_dictionary.lua ') - os.exit(1) -end -if not paths.filep(arg[1]) then - print('error: file does not exit: ' .. arg[1]) - os.exit(1) -end - -dict = torch.load(arg[1]) -dst = paths.basename(arg[1]):gsub('.th7', '.txt') -assert(dst:match('.txt$')) - -f = io.open(dst, 'w') -for idx, symbol in ipairs(dict.index_to_symbol) do - if idx > dict.cutoff then - break - end - f:write(symbol) - f:write(' ') - f:write(dict.index_to_freq[idx]) - f:write('\n') -end -f:close() diff --git a/spaces/Harshveer/Finetuned_Diffusion_Max/utils.py b/spaces/Harshveer/Finetuned_Diffusion_Max/utils.py deleted file mode 100644 index ff1c065d186347ca51b47d010a697dbe1814695c..0000000000000000000000000000000000000000 --- a/spaces/Harshveer/Finetuned_Diffusion_Max/utils.py +++ /dev/null @@ -1,6 +0,0 @@ -def is_google_colab(): - try: - import google.colab - return True - except: - return False \ No newline at end of file diff --git a/spaces/Harveenchadha/Hindi_TTS/vakyansh_tts/tts_infer/num_to_word_on_sent.py b/spaces/Harveenchadha/Hindi_TTS/vakyansh_tts/tts_infer/num_to_word_on_sent.py deleted file mode 100644 index ee9bd2de5f0b1a6d6b3c788d9c3934a7475d7307..0000000000000000000000000000000000000000 --- a/spaces/Harveenchadha/Hindi_TTS/vakyansh_tts/tts_infer/num_to_word_on_sent.py +++ /dev/null @@ -1,1314 +0,0 @@ -import re -import string - -# ----------------------------- indic_num.py ----------------------------- -supported_lang = {"en", "hi", "gu", "mr", "bn", "te", "ta", "kn", "or", "pa"} -# supported_lang = {'eng', 'hin', 'guj', 'mar', 'ben', 'tel', 'tam', 'kan', 'ori', 'pan'} # Three alphabet lang code - -all_num = { - "en": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], - "hi": ["०", "१", "२", "३", "४", "५", "६", "७", "८", "९"], - "gu": ["૦", "૧", "૨", "૩", "૪", "૫", "૬", "૭", "૮", "૯"], - "mr": ["०", "१", "२", "३", "४", "५", "६", "७", "८", "९"], - "bn": ["০", "১", "২", "৩", "৪", "৫", "৬", "৭", "৮", "৯"], - "te": ["౦", "౧", "౨", "౩", "౪", "౫", "౬", "౭", "౮", "౯"], - "ta": ["0", "௧", "௨", "௩", "௪", "௫", "௬", "௭", "௮", "௯", "௰"], - "kn": ["೦", "೧", "೨", "೩", "೪", "೫", "೬", "೭", "೮", "೯"], - "or": ["୦", "୧", "୨", "୩", "୪", "୫", "୬", "୭", "୮", "୯"], - "pa": ["੦", "੧", "੨", "੩", "੪", "੫", "੬", "੭", "੮", "੯"], -} - -num_dict = dict() -num_dict["en"] = { - "0": "zero", - "1": "one", - "2": "two", - "3": "three", - "4": "four", - "5": "five", - "6": "six", - "7": "seven", - "8": "eight", - "9": "nine", - "10": "ten", - "11": "eleven", - "12": "twelve", - "13": "thirteen", - "14": "fourteen", - "15": "fifteen", - "16": "sixteen", - "17": "seventeen", - "18": "eighteen", - "19": "nineteen", - "20": "twenty", - "21": "twenty-one", - "22": "twenty-two", - "23": "twenty-three", - "24": "twenty-four", - "25": "twenty-five", - "26": "twenty-six", - "27": "twenty-seven", - "28": "twenty-eight", - "29": "twenty-nine", - "30": "thirty", - "31": "thirty-one", - "32": "thirty-two", - "33": "thirty-three", - "34": "thirty-four", - "35": "thirty-five", - "36": "thirty-six", - "37": "thirty-seven", - "38": "thirty-eight", - "39": "thirty-nine", - "40": "forty", - "41": "forty-one", - "42": "forty-two", - "43": "forty-three", - "44": "forty-four", - "45": "forty-five", - "46": "forty-six", - "47": "forty-seven", - "48": "forty-eight", - "49": "forty-nine", - "50": "fifty", - "51": "fifty-one", - "52": "fifty-two", - "53": "fifty-three", - "54": "fifty-four", - "55": "fifty-five", - "56": "fifty-six", - "57": "fifty-seven", - "58": "fifty-eight", - "59": "fifty-nine", - "60": "sixty", - "61": "sixty-one", - "62": "sixty-two", - "63": "sixty-three", - "64": "sixty-four", - "65": "sixty-five", - "66": "sixty-six", - "67": "sixty-seven", - "68": "sixty-eight", - "69": "sixty-nine", - "70": "seventy", - "71": "seventy-one", - "72": "seventy-two", - "73": "seventy-three", - "74": "seventy-four", - "75": "seventy-five", - "76": "seventy-six", - "77": "seventy-seven", - "78": "seventy-eight", - "79": "seventy-nine", - "80": "eighty", - "81": "eighty-one", - "82": "eighty-two", - "83": "eighty-three", - "84": "eighty-four", - "85": "eighty-five", - "86": "eighty-six", - "87": "eighty-seven", - "88": "eighty-eight", - "89": "eighty-nine", - "90": "ninety", - "91": "ninety-one", - "92": "ninety-two", - "93": "ninety-three", - "94": "ninety-four", - "95": "ninety-five", - "96": "ninety-six", - "97": "ninety-seven", - "98": "ninety-eight", - "99": "ninety-nine", - "100": "hundred", - "1000": "thousand", - "100000": "lakh", - "10000000": "crore", - "1000000000": "arab", -} # English-India -num_dict["hi"] = { - "0": "शून्य", - "1": "एक", - "2": "दो", - "3": "तीन", - "4": "चार", - "5": "पाँच", - "6": "छः", - "7": "सात", - "8": "आठ", - "9": "नौ", - "10": "दस", - "11": "ग्यारह", - "12": "बारह", - "13": "तेरह", - "14": "चौदह", - "15": "पंद्रह", - "16": "सोलह", - "17": "सत्रह", - "18": "अट्ठारह", - "19": "उन्नीस", - "20": "बीस", - "21": "इक्कीस", - "22": "बाईस", - "23": "तेईस", - "24": "चौबिस", - "25": "पच्चीस", - "26": "छब्बीस", - "27": "सत्ताईस", - "28": "अट्ठाईस", - "29": "उनतीस", - "30": "तीस", - "31": "इकतीस", - "32": "बत्तीस", - "33": "तैंतीस", - "34": "चौंतीस", - "35": "पैंतीस", - "36": "छत्तीस", - "37": "सैंतीस", - "38": "अड़तीस", - "39": "उनतालीस", - "40": "चालीस", - "41": "इकतालीस", - "42": "बयालीस", - "43": "तैंतालीस", - "44": "चौंतालीस", - "45": "पैंतालीस", - "46": "छियालीस", - "47": "सैंतालीस", - "48": "अड़तालीस", - "49": "उनचास", - "50": "पचास", - "51": "इक्यावन​", - "52": "बावन", - "53": "तिरेपन", - "54": "चौवन", - "55": "पचपन", - "56": "छप्पन", - "57": "सत्तावन", - "58": "अट्ठावन", - "59": "उनसठ", - "60": "साठ", - "61": "इकसठ", - "62": "बासठ", - "63": "तिरेसठ", - "64": "चौंसठ", - "65": "पैंसठ", - "66": "छयासठ", - "67": "सरसठ​", - "68": "अड़सठ", - "69": "उनहत्तर", - "70": "सत्तर", - "71": "इकहत्तर", - "72": "बहत्तर", - "73": "तिहत्तर", - "74": "चौहत्तर", - "75": "पचहत्तर", - "76": "छिहत्तर", - "77": "सतहत्तर", - "78": "अठहत्तर", - "79": "उन्यासी", - "80": "अस्सी", - "81": "इक्यासी", - "82": "बयासी", - "83": "तिरासी", - "84": "चौरासी", - "85": "पचासी", - "86": "छियासी", - "87": "सत्तासी", - "88": "अठासी", - "89": "नवासी", - "90": "नब्बे", - "91": "इक्यानवे", - "92": "बानवे", - "93": "तिरानवे", - "94": "चौरानवे", - "95": "पचानवे", - "96": "छियानवे", - "97": "सत्तानवे", - "98": "अट्ठानवे", - "99": "निन्यानवे", - "100": "सौ", - "1000": "हज़ार", - "100000": "लाख", - "10000000": "करोड़", - "1000000000": "अरब", -} # Hindi -num_dict["gu"] = { - "0": "શૂન્ય", - "1": "એક", - "2": "બે", - "3": "ત્રણ", - "4": "ચાર", - "5": "પાંચ", - "6": "છ", - "7": "સાત", - "8": "આઠ", - "9": "નવ", - "10": "દસ", - "11": "અગિયાર", - "12": "બાર", - "13": "તેર", - "14": "ચૌદ", - "15": "પંદર", - "16": "સોળ", - "17": "સત્તર", - "18": "અઢાર", - "19": "ઓગણિસ", - "20": "વીસ", - "21": "એકવીસ", - "22": "બાવીસ", - "23": "તેવીસ", - "24": "ચોવીસ", - "25": "પચ્ચીસ", - "26": "છવીસ", - "27": "સત્તાવીસ", - "28": "અઠ્ઠાવીસ", - "29": "ઓગણત્રીસ", - "30": "ત્રીસ", - "31": "એકત્રીસ", - "32": "બત્રીસ", - "33": "તેત્રીસ", - "34": "ચોત્રીસ", - "35": "પાંત્રીસ", - "36": "છત્રીસ", - "37": "સડત્રીસ", - "38": "અડત્રીસ", - "39": "ઓગણચાલીસ", - "40": "ચાલીસ", - "41": "એકતાલીસ", - "42": "બેતાલીસ", - "43": "ત્રેતાલીસ", - "44": "ચુંમાલીસ", - "45": "પિસ્તાલીસ", - "46": "છેતાલીસ", - "47": "સુડતાલીસ", - "48": "અડતાલીસ", - "49": "ઓગણપચાસ", - "50": "પચાસ", - "51": "એકાવન", - "52": "બાવન", - "53": "ત્રેપન", - "54": "ચોપન", - "55": "પંચાવન", - "56": "છપ્પન", - "57": "સત્તાવન", - "58": "અઠ્ઠાવન", - "59": "ઓગણસાઠ", - "60": "સાઈઠ", - "61": "એકસઠ", - "62": "બાસઠ", - "63": "ત્રેસઠ", - "64": "ચોસઠ", - "65": "પાંસઠ", - "66": "છાસઠ", - "67": "સડસઠ", - "68": "અડસઠ", - "69": "અગણોસિત્તેર", - "70": "સિત્તેર", - "71": "એકોતેર", - "72": "બોતેર", - "73": "તોતેર", - "74": "ચુમોતેર", - "75": "પંચોતેર", - "76": "છોતેર", - "77": "સિત્યોતેર", - "78": "ઇઠ્યોતેર", - "79": "ઓગણાએંસી", - "80": "એંસી", - "81": "એક્યાસી", - "82": "બ્યાસી", - "83": "ત્યાસી", - "84": "ચોર્યાસી", - "85": "પંચાસી", - "86": "છ્યાસી", - "87": "સિત્યાસી", - "88": "ઈઠ્યાસી", - "89": "નેવ્યાસી", - "90": "નેવું", - "91": "એકાણું", - "92": "બાણું", - "93": "ત્રાણું", - "94": "ચોરાણું", - "95": "પંચાણું", - "96": "છન્નું", - "97": "સત્તાણું", - "98": "અઠ્ઠાણું", - "99": "નવ્વાણું", - "100": "સો", - "1000": "હજાર", - "100000": "લાખ", - "1000000": "દસ લાખ", - "10000000": "કરોડ઼", -} # Gujarati -num_dict["mr"] = { - "0": "शून्य", - "1": "एक", - "2": "दोन", - "3": "तीन", - "4": "चार", - "5": "पाच", - "6": "सहा", - "7": "सात", - "8": "आठ", - "9": "नऊ", - "10": "दहा", - "11": "अकरा", - "12": "बारा", - "13": "तेरा", - "14": "चौदा", - "15": "पंधरा", - "16": "सोळा", - "17": "सतरा", - "18": "अठरा", - "19": "एकोणीस", - "20": "वीस", - "21": "एकवीस", - "22": "बावीस", - "23": "तेवीस", - "24": "चोवीस", - "25": "पंचवीस", - "26": "सव्वीस", - "27": "सत्तावीस", - "28": "अठ्ठावीस", - "29": "एकोणतीस", - "30": "तीस", - "31": "एकतीस", - "32": "बत्तीस", - "33": "तेहेतीस", - "34": "चौतीस", - "35": "पस्तीस", - "36": "छत्तीस", - "37": "सदतीस", - "38": "अडतीस", - "39": "एकोणचाळीस", - "40": "चाळीस", - "41": "एक्केचाळीस", - "42": "बेचाळीस", - "43": "त्रेचाळीस", - "44": "चव्वेचाळीस", - "45": "पंचेचाळीस", - "46": "सेहेचाळीस", - "47": "सत्तेचाळीस", - "48": "अठ्ठेचाळीस", - "49": "एकोणपन्नास", - "50": "पन्नास", - "51": "एक्कावन्न", - "52": "बावन्न", - "53": "त्रेपन्न", - "54": "चोपन्न", - "55": "पंचावन्न", - "56": "छप्पन्न", - "57": "सत्तावन्न", - "58": "अठ्ठावन्न", - "59": "एकोणसाठ", - "60": "साठ", - "61": "एकसष्ठ", - "62": "बासष्ठ", - "63": "त्रेसष्ठ", - "64": "चौसष्ठ", - "65": "पासष्ठ", - "66": "सहासष्ठ", - "67": "सदुसष्ठ", - "68": "अडुसष्ठ", - "69": "एकोणसत्तर", - "70": "सत्तर", - "71": "एक्काहत्तर", - "72": "बाहत्तर", - "73": "त्र्याहत्तर", - "74": "चौर्‍याहत्तर", - "75": "पंच्याहत्तर", - "76": "शहात्तर", - "77": "सत्याहत्तर", - "78": "अठ्ठ्याहत्तर", - "79": "एकोण ऐंशी", - "80": "ऐंशी", - "81": "एक्क्याऐंशी", - "82": "ब्याऐंशी", - "83": "त्र्याऐंशी", - "84": "चौऱ्याऐंशी", - "85": "पंच्याऐंशी", - "86": "शहाऐंशी", - "87": "सत्त्याऐंशी", - "88": "अठ्ठ्याऐंशी", - "89": "एकोणनव्वद", - "90": "नव्वद", - "91": "एक्क्याण्णव", - "92": "ब्याण्णव", - "93": "त्र्याण्णव", - "94": "चौऱ्याण्णव", - "95": "पंच्याण्णव", - "96": "शहाण्णव", - "97": "सत्त्याण्णव", - "98": "अठ्ठ्याण्णव", - "99": "नव्व्याण्णव", - "100": "शे", - "1000": "हजार", - "100000": "लाख", - "10000000": "कोटी", - "1000000000": "अब्ज", -} # Marathi -num_dict["bn"] = { - "0": "শূন্য", - "1": "এক", - "2": "দুই", - "3": "তিন", - "4": "চার", - "5": "পাঁচ", - "6": "ছয়", - "7": "সাত", - "8": "আট", - "9": "নয়", - "10": "দশ", - "11": "এগার", - "12": "বার", - "13": "তের", - "14": "চৌদ্দ", - "15": "পনের", - "16": "ষোল", - "17": "সতের", - "18": "আঠার", - "19": "ঊনিশ", - "20": "বিশ", - "21": "একুশ", - "22": "বাইশ", - "23": "তেইশ", - "24": "চব্বিশ", - "25": "পঁচিশ", - "26": "ছাব্বিশ", - "27": "সাতাশ", - "28": "আঠাশ", - "29": "ঊনত্রিশ", - "30": "ত্রিশ", - "31": "একত্রিশ", - "32": "বত্রিশ", - "33": "তেত্রিশ", - "34": "চৌত্রিশ", - "35": "পঁয়ত্রিশ", - "36": "ছত্রিশ", - "37": "সাঁইত্রিশ", - "38": "আটত্রিশ", - "39": "ঊনচল্লিশ", - "40": "চল্লিশ", - "41": "একচল্লিশ", - "42": "বিয়াল্লিশ", - "43": "তেতাল্লিশ", - "44": "চুয়াল্লিশ", - "45": "পঁয়তাল্লিশ", - "46": "ছেচল্লিশ", - "47": "সাতচল্লিশ", - "48": "আটচল্লিশ", - "49": "ঊনপঞ্চাশ", - "50": "পঞ্চাশ", - "51": "একান্ন", - "52": "বায়ান্ন", - "53": "তিপ্পান্ন", - "54": "চুয়ান্ন", - "55": "পঞ্চান্ন", - "56": "ছাপ্পান্ন", - "57": "সাতান্ন", - "58": "আটান্ন", - "59": "ঊনষাট", - "60": "ষাট", - "61": "একষট্টি", - "62": "বাষট্টি", - "63": "তেষট্টি", - "64": "চৌষট্টি", - "65": "পঁয়ষট্টি", - "66": "ছেষট্টি", - "67": "সাতষট্টি", - "68": "আটষট্টি", - "69": "ঊনসত্তর", - "70": "সত্তর", - "71": "একাত্তর", - "72": "বাহাত্তর", - "73": "তিয়াত্তর", - "74": "চুয়াত্তর", - "75": "পঁচাত্তর", - "76": "ছিয়াত্তর", - "77": "সাতাত্তর", - "78": "আটাত্তর", - "79": "ঊনআশি", - "80": "আশি", - "81": "একাশি", - "82": "বিরাশি", - "83": "তিরাশি", - "84": "চুরাশি", - "85": "পঁচাশি", - "86": "ছিয়াশি", - "87": "সাতাশি", - "88": "আটাশি", - "89": "ঊননব্বই", - "90": "নব্বই", - "91": "একানব্বই", - "92": "বিরানব্বই", - "93": "তিরানব্বই", - "94": "চুরানব্বই", - "95": "পঁচানব্বই", - "96": "ছিয়ানব্বই", - "97": "সাতানব্বই", - "98": "আটানব্বই", - "99": "নিরানব্বই", - "100": "শো", - "1000": "হাজার", - "100000": "লাখ", - "10000000": "কোটি", - "1000000000": "একশ’ কোটি", -} # Bengali -num_dict["te"] = { - "0": "సున్నా", - "1": "ఒకటి", - "2": "రెండు", - "3": "మూడు", - "4": "నాలుగు", - "5": "ఐదు", - "6": "ఆరు", - "7": "ఏడు", - "8": "ఎనిమిది", - "9": "తొమ్మిది", - "10": "పది", - "11": "పదకొండు", - "12": "పన్నెండు", - "13": "పదమూడు", - "14": "పద్నాలుగు", - "15": "పదిహేను", - "16": "పదహారు", - "17": "పదిహేడు", - "18": "పద్దెనిమిది", - "19": "పందొమ్మిది", - "20": "ఇరవై", - "21": "ఇరవై ఒకటి", - "22": "ఇరవై రెండు", - "23": "ఇరవై మూడు", - "24": "ఇరవై నాలుగు", - "25": "ఇరవై ఐదు", - "26": "ఇరవై ఆరు", - "27": "ఇరవై ఏడు", - "28": "ఇరవై ఎనిమిది", - "29": "ఇరవై తొమ్మిది", - "30": "ముప్పై", - "31": "ముప్పై ఒకటి", - "32": "ముప్పై రెండు", - "33": "ముప్పై మూడు", - "34": "ముప్పై నాలుగు", - "35": "ముప్పై ఐదు", - "36": "ముప్పై ఆరు", - "37": "ముప్పై ఏడు", - "38": "ముప్పై ఎనిమిది", - "39": "ముప్పై తొమ్మిది", - "40": "నలభై", - "41": "నలభై ఒకటి", - "42": "నలభై రెండు", - "43": "నలభై మూడు", - "44": "నలభై నాలుగు", - "45": "నలభై ఐదు", - "46": "నలభై ఆరు", - "47": "నలభై ఏడు", - "48": "నలభై ఎనిమిది", - "49": "నలభై తొమ్మిది", - "50": "యాభై", - "51": "యాభై ఒకటి", - "52": "యాభై రెండు", - "53": "యాభై మూడు", - "54": "యాభై నాలుగు", - "55": "యాభై ఐదు", - "56": "యాభై ఆరు", - "57": "యాభై ఏడు", - "58": "యాభై ఎనిమిది", - "59": "యాభై తొమ్మిది", - "60": "అరవై", - "61": "అరవై ఒకటి", - "62": "అరవై రెండు", - "63": "అరవై మూడు", - "64": "అరవై నాలుగు", - "65": "అరవై ఐదు", - "66": "అరవై ఆరు", - "67": "అరవై ఏడు", - "68": "అరవై ఎనిమిది", - "69": "అరవై తొమ్మిది", - "70": "డెబ్బై", - "71": "డెబ్బై ఒకటి", - "72": "డెబ్బై రెండు", - "73": "డెబ్బై మూడు", - "74": "డెబ్బై నాలుగు", - "75": "డెబ్బై ఐదు", - "76": "డెబ్బై ఆరు", - "77": "డెబ్బై ఏడు", - "78": "డెబ్బై ఎనిమిది", - "79": "డెబ్బై తొమ్మిది", - "80": "ఎనభై", - "81": "ఎనభై ఒకటి", - "82": "ఎనభై రెండు", - "83": "ఎనభై మూడు", - "84": "ఎనభై నాలుగు", - "85": "ఎనభై ఐదు", - "86": "ఎనభై ఆరు", - "87": "ఎనభై ఏడు", - "88": "ఎనభై ఎనిమిది", - "89": "ఎనభై తొమ్మిది", - "90": "తొంభై", - "91": "తొంభై ఒకటి", - "92": "తొంభై రెండు", - "93": "తొంభై మూడు", - "94": "తొంభై నాలుగు", - "95": "తొంభై ఐదు", - "96": "తొంభై ఆరు", - "97": "తొంభై ఏడు", - "98": "తొంభై ఎనిమిది", - "99": "తొంభై తొమ్మిది", - "100": "వందల", - "1000": "వేల", - "100000": "లక్షల", - "10000000": "కోట్ల", - "1000000000": "బిలియన్", -} # Telugu -num_dict["ta"] = { - "0": "பூஜ்ஜியம்", - "1": "ஒன்று", - "2": "இரண்டு", - "3": "மூன்று", - "4": "நான்கு", - "5": "ஐந்து", - "6": "ஆறு", - "7": "ஏழு", - "8": "எட்டு", - "9": "ஒன்பது", - "10": "பத்து", - "11": "பதினொன்று", - "12": "பன்னிரண்டு", - "13": "பதிமூன்று", - "14": "பதினான்கு", - "15": "பதினைந்து", - "16": "பதினாறு", - "17": "பதினேழு", - "18": "பதினெட்டு", - "19": "பத்தொன்பது", - "20": "இருபது", - "21": "இருபது ஒன்று", - "22": "இருபத்து இரண்டு", - "23": "இருபத்து மூன்று", - "24": "இருபத்து நான்கு", - "25": "இருபத்து ஐந்து", - "26": "இருபத்து ஆறு", - "27": "இருபத்து ஏழு", - "28": "இருபத்து எட்டு", - "29": "இருபத்து ஒன்பது", - "30": "முப்பது", - "31": "முப்பத்து ஒன்று", - "32": "முப்பத்து இரண்டு", - "33": "முப்பத்து மூன்று", - "34": "முப்பத்து நான்கு", - "35": "முப்பத்து ஐந்து", - "36": "முப்பத்து ஆறு", - "37": "முப்பத்து ஏழு", - "38": "முப்பத்து எட்டு", - "39": "முப்பத்து ஒன்பது", - "40": "நாற்பது", - "41": "நாற்பத்து ஒன்று", - "42": "நாற்பத்து இரண்டு", - "43": "நாற்பத்து மூன்று", - "44": "நாற்பத்து நான்கு", - "45": "நாற்பத்து ஐந்து", - "46": "நாற்பத்து ஆறு", - "47": " நாற்பத்து ஏழு", - "48": "நாற்பத்து எட்டு", - "49": "நாற்பத்து ஒன்பது", - "50": "ஐம்பது", - "51": "ஐம்பத்து ஒன்று", - "52": "ஐம்பத்து இரண்டு", - "53": "ஐம்பத்து மூன்று", - "54": "ஐம்பத்து நான்கு", - "55": "ஐம்பத்து ஐந்து", - "56": "ஐம்பத்து ஆறு", - "57": "ஐம்பத்து ஏழு", - "58": "ஐம்பத்து எட்டு", - "59": "ஐம்பத்து ஒன்பது", - "60": "அறுபது", - "61": "அறுபத்து ஒன்று", - "62": "அறுபத்து இரண்டு", - "63": "அறுபத்து மூன்று", - "64": "அறுபத்து நான்கு", - "65": "அறுபத்து ஐந்து", - "66": "அறுபத்து ஆறு", - "67": "அறுபத்து ஏழு", - "68": "அறுபத்து எட்டு", - "69": "அறுபத்து ஒன்பது", - "70": "எழுபது", - "71": "எழுபத்தி ஒன்று", - "72": "எழுபத்தி இரண்டு", - "73": "எழுபத்தி முச்சக்கர", - "74": "எழுபத்தி நான்கு", - "75": "எழுபத்தி ஐந்து", - "76": "எழுபத்தி ஆறு", - "77": "எழுபத்தி ஏழு", - "78": "எழுபத்தி எட்டு", - "79": "எழுபத்தி ஒன்பது", - "80": "எண்பது", - "81": "எண்பத்தியொன்று", - "82": "எண்பத்திரண்டு", - "83": "எண்பத்திமூன்று", - "84": "என்பதினான்கு", - "85": "என்பதினைந்து", - "86": "எண்பத்திஆறு", - "87": "எண்பத்திஏழு", - "88": "எண்பத்தியெட்டு", - "89": "எண்பத்தியொன்பது", - "90": "தொன்னூறு", - "91": "தொண்ணூற்றியொன்று", - "92": "தொண்ணூற்றிரண்டு", - "93": "தொண்ணூற்றிமூன்று", - "94": "தொண்ணூற்றிநான்கு", - "95": "தொண்ணூற்றிஐந்து", - "96": "தொண்ணூற்றியாறு", - "97": "தொண்ணூற்றியேழு", - "98": "தொண்ணூற்றியெட்டு", - "99": "தொண்ணூற்றிஒன்பது", - "100": "நூறு", - "1000": "ஆயிரம்", - "100000": "இலட்சம்", - "10000000": "கோடி", - "1000000000": "பில்லியன்", -} # Tamil -num_dict["kn"] = { - "0": "ಸೊನ್ನೆ", - "1": "ಒಂದು", - "2": "ಎರಡು", - "3": "ಮೂರು", - "4": "ನಾಲ್ಕು", - "5": "ಅಯ್ದು", - "6": "ಆರು", - "7": "ಏಳು", - "8": "ಎಂಟು", - "9": "ಒಂಬತ್ತು", - "10": "ಹತ್ತು", - "11": "ಹನ್ನೊಂದು", - "12": "ಹನ್ನೆರಡು", - "13": "ಹದಿಮೂರು", - "14": "ಹದಿನಾಲ್ಕು", - "15": "ಹದಿನೈದು", - "16": "ಹದಿನಾರು", - "17": "ಹದಿನೇಳು", - "18": "ಹದಿನೆಂಟು", - "19": "ಹತ್ತೊಂಬತ್ತು", - "20": "ಇಪ್ಪತ್ತು", - "21": "ಇಪ್ಪತ್ತ್’ಒಂದು", - "22": "ಇಪ್ಪತ್ತ್’ಎರಡು", - "23": "ಇಪ್ಪತ್ತ್’ಮೂರು", - "24": "ಇಪ್ಪತ್ತ್’ನಾಲ್ಕು", - "25": "ಇಪ್ಪತ್ತ್’ಐದು", - "26": "ಇಪ್ಪತ್ತ್’ಆರು", - "27": "ಇಪ್ಪತ್ತ್’ಏಳು", - "28": "ಇಪ್ಪತ್ತ್’ಎಂಟು", - "29": "ಇಪ್ಪತ್ತ್’ಒಂಬತ್ತು", - "30": "ಮೂವತ್ತು", - "31": "ಮುವತ್ತ್’ಒಂದು", - "32": "ಮುವತ್ತ್’ಎರಡು", - "33": "ಮುವತ್ತ್’ಮೂರು", - "34": "ಮೂವತ್ತ್’ನಾಲ್ಕು", - "35": "ಮೂವತ್ತ್’ಐದು", - "36": "ಮೂವತ್ತ್’ಆರು", - "37": "ಮೂವತ್ತ್’ಏಳು", - "38": "ಮೂವತ್ತ್’ಎಂಟು", - "39": "ಮೂವತ್ತ್’ಒಂಬತ್ತು", - "40": "ನಲವತ್ತು", - "41": "ನಲವತ್ತೊಂದು", - "42": "ನಲವತ್ತ್ ಎರಡು", - "43": "ನಲವತ್ತ್ ಮೂರು", - "44": "ನಲವತ್ತ್ ನಾಲ್ಕು", - "45": "ನಲವತ್ತೈದು", - "46": "ನಲವತ್ತಾರು", - "47": "ನಲವತ್ತೇಳು", - "48": "ನಲವತ್ತೆಂಟು", - "49": "ನಲವತ್ತೊಂಬತ್ತು", - "50": "ಐವತ್ತು", - "51": "ಐವತ್ತೊಂದು", - "52": "ಐವತ್ತೆರಡು", - "53": "ಐವತ್ತಮೂರು", - "54": "ಐವತ್ತ್ನಾಲ್ಕು", - "55": "ಐವತ್ತೈದು", - "56": "ಐವತ್ತಾರು", - "57": "ಐವತ್ತೇಳು", - "58": "ಐವತ್ತೆಂಟು", - "59": "ಐವತ್ತೊಂಬತ್ತು", - "60": "ಅರವತ್ತು", - "61": "ಅರವತ್ತೊಂದು", - "62": "ಅರವತ್ತೆರಡು", - "63": "ಅರವತ್ತ್ ಮೂರು", - "64": "ಅರವತ್ತ್ ನಾಲ್ಕು", - "65": "ಅರವತ್ತೈದು", - "66": "ಅರವತ್ತಾರು", - "67": "ಅರವತ್ತೇಳು", - "68": "ಅರವತ್ತೆಂಟು", - "69": "ಅರವತ್ತೊಂಬತ್ತು", - "70": "ಎಪ್ಪತ್ತು", - "71": "ಎಪ್ಪತ್ತೊಂದು", - "72": "ಎಪ್ಪತ್ತೆರಡು", - "73": "ಎಪ್ಪತ್ತ್ ಮೂರು", - "74": "ಎಪ್ಪತ್ತ್ ನಾಲ್ಕು", - "75": "ಎಪ್ಪತ್ತೈದು", - "76": "ಎಪ್ಪತ್ತಾರು", - "77": "ಎಪ್ಪತ್ತೇಳು", - "78": "ಎಪ್ಪತ್ತೆಂಟು", - "79": "ಎಪ್ಪತ್ತೊಂಬತ್ತು", - "80": "ಎಂಬತ್ತು", - "81": "ಎಂಬತ್ತೊಂದು", - "82": "ಎಂಬತ್ತೆರಡು", - "83": "ಎಂಬತ್ತ್ ಮೂರು", - "84": "ಎಂಬತ್ತ್ ನಾಲ್ಕು", - "85": "ಎಂಬತ್ತೈದು", - "86": "ಎಂಬತ್ತಾರು", - "87": "ಎಂಬತ್ತೇಳು", - "88": "ಎಂಬತ್ತೆಂಟು", - "89": "ಎಂಬತ್ತೊಂಬತ್ತು", - "90": "ತೊಂಬತ್ತು", - "91": "ತೊಂಬತ್ತೊಂದು", - "92": "ತೊಂಬತ್ತೆರಡು", - "93": "ತೊಂಬತ್ತ ಮೂರು", - "94": "ತೊಂಬತ್ತ ನಾಲ್ಕು", - "95": "ತೊಂಬತ್ತೈದು", - "96": "ತೊಂಬತ್ತಾರು", - "97": "ತೊಂಬತ್ತೇಳು", - "98": "ತೊಂಬತ್ತೆಂಟು", - "99": "ತೊಂಬತ್ತೊಂಬತ್ತು", - "100": "ನೂರ", - "1000": "ಸಾವಿರದ", - "100000": "ಲಕ್ಷದ", - "10000000": "ಕೋಟಿ", - "1000000000": "ಶತಕೋಟಿ", -} # Kannada -num_dict["or"] = { - "0": "ଶୁନ୍ୟ", - "1": "ଏକ", - "2": "ଦୁଇ", - "3": "ତିନି", - "4": "ଚାରି", - "5": "ପାଞ୍ଚ", - "6": "ଛଅ", - "7": "ସାତ", - "8": "ଆଠ", - "9": "ନଅ", - "10": "ନଅ", - "11": "ଏଗାର", - "12": "ବାର", - "13": "ତେର", - "14": "ଚଉଦ", - "15": "ପନ୍ଦର", - "16": "ଷୋହଳ", - "17": "ସତର", - "18": "ଅଠର", - "19": "ଊଣାଇଶ", - "20": "କୋଡିଏ", - "21": "ଏକୋଇଶି", - "22": "ବାଇଶି", - "23": "ତେଇଶି", - "24": "ଚବିଶି", - "25": "ପଚିଶି", - "26": "ଛବିଶି", - "27": "ସତାଇଶି", - "28": "ଅଠାଇଶି", - "29": "ଅଣତିରିଶି", - "30": "ତିରିଶି", - "31": "ଏକତିରିଶି", - "32": "ବତିଶି", - "33": "ତେତିଶି", - "34": "ଚଉତିରିଶି", - "35": "ପଞ୍ଚତିରିଶି", - "36": "ଛତିଶି", - "37": "ସଂଇତିରିଶି", - "38": "ଅଠତିରିଶି", - "39": "ଅଣଚାଳିଶି", - "40": "ଚାଳିଶି", - "41": "ଏକଚାଳିଶି", - "42": "ବୟାଳିଶି", - "43": "ତେୟାଳିଶି", - "44": "ଚଉରାଳିଶି", - "45": "ପଞ୍ଚଚାଳିଶି", - "46": "ଛୟାଳିଶି", - "47": "ସତଚାଳିଶି", - "48": "ଅଠଚାଳିଶି", - "49": "ଅଣଚାଶ", - "50": "ପଚାଶ", - "51": "ଏକାବନ", - "52": "ବାଉନ", - "53": "ତେପନ", - "54": "ଚଉବନ", - "55": "ପଞ୍ଚାବନ", - "56": "ଛପନ", - "57": "ସତାବନ", - "58": "ଅଠାବନ", - "59": "ଅଣଷଠି", - "60": "ଷାଠିଏ", - "61": "ଏକଷଠି", - "62": "ବାଷଠି", - "63": "ତେଷଠି", - "64": "ଚଉଷଠି", - "65": "ପଞ୍ଚଷଠି", - "66": "ଛଅଷଠି", - "67": "ସତଷଠି", - "68": "ଅଠଷଠି", - "69": "ଅଣସ୍ତରୀ", - "70": "ସତୂରୀ", - "71": "ଏକସ୍ତରୀ", - "72": "ବାସ୍ତରୀ", - "73": "ତେସ୍ତରୀ", - "74": "ଚଉସ୍ତରୀ", - "75": "ପଞ୍ଚସ୍ତରୀ", - "76": "ଛଅସ୍ତରୀ", - "77": "ସତସ୍ତରୀ", - "78": "ଅଠସ୍ତରୀ", - "79": "ଅଣାଅଶୀ", - "80": "ଅଶୀ", - "81": "ଏକାଅଶୀ", - "82": "ବୟାଅଶୀ", - "83": "ତେୟାଅଶୀ", - "84": "ଚଉରାଅଶୀ", - "85": "ପଞ୍ଚାଅଶୀ", - "86": "ଛୟାଅଶୀ", - "87": "ସତାଅଶୀ", - "88": "ଅଠାଅଶୀ", - "89": "ଅଣାନବେ", - "90": "ନବେ", - "91": "ଏକାନବେ", - "92": "ବୟାନବେ", - "93": "ତେୟାନବେ", - "94": "ଚଉରାନବେ", - "95": "ପଞ୍ଚାନବେ", - "96": "ଛୟାନବେ", - "97": "ସତାନବେ", - "98": "ଅଠାନବେ", - "99": "ଅନେଶତ", - "100": "ଶହେ", - "1000": "ହଜାର", - "100000": "ଲକ୍ଷ", - "10000000": "କୋଟି", - "1000000000": "କୋଟି", -} # Oriya -num_dict["pa"] = { - "0": "ਸਿਫਰ ", - "1": "ਇੱਕ", - "2": "ਦੋ", - "3": "ਤਿੰਨ", - "4": "ਚਾਰ", - "5": "ਪੰਜ", - "6": "ਛੇ", - "7": "ਸੱਤ", - "8": "ਅੱਠ", - "9": "ਨੌਂ", - "10": "ਦੱਸ", - "11": "ਗਿਆਰਾਂ", - "12": "ਬਾਰਾਂ", - "13": "ਤੇਰਾਂ", - "14": "ਚੌਦਾਂ", - "15": "ਪੰਦਰਾਂ", - "16": "ਸੋਲ਼ਾਂ", - "17": "ਸਤਾਰਾਂ", - "18": "ਅਠਾਰਾਂ", - "19": "ਉਨੀ", - "20": "ਵੀਹ", - "21": "ਇੱਕੀ", - "22": "ਬਾਈ", - "23": "ਤੇਈ", - "24": "ਚੌਵੀ", - "25": "ਪੰਝੀ", - "26": "ਛੱਬੀ", - "27": "ਸਤਾਈ", - "28": "ਅਠਾਈ", - "29": "ਉਨੱਤੀ", - "30": "ਤੀਹ", - "31": "ਇਕੱਤੀ", - "32": "ਬੱਤੀ", - "33": "ਤੇਤੀ", - "34": "ਚੌਂਤੀ", - "35": "ਪੈਂਤੀ", - "36": "ਛੱਤੀ", - "37": "ਸੈਂਤੀ", - "38": "ਅਠੱਤੀ", - "39": "ਉਨਤਾਲੀ", - "40": "ਚਾਲੀ", - "41": "ਇਕਤਾਲੀ", - "42": "ਬਤਾਲੀ", - "43": "ਤਰਤਾਲੀ", - "44": "ਚੌਤਾਲੀ", - "45": "ਪੰਜਤਾਲੀ", - "46": "ਛਿਆਲੀ", - "47": "ਸੰਤਾਲੀ", - "48": "ਅੱਠਤਾਲੀ", - "49": "ਉਣਿੰਜਾ", - "50": "ਪੰਜਾਹ", - "51": "ਇਕਵਿੰਜਾ", - "52": "ਬਵਿੰਜਾ", - "53": "ਤਰਵਿੰਜਾ", - "54": "ਚਰਿੰਜਾ", - "55": "ਪਚਵਿੰਜਾ", - "56": "ਛਪਿੰਜਾ", - "57": "ਸਤਵਿੰਜਾ", - "58": "ਅੱਠਵਿੰਜਾ", - "59": "ਉਣਾਠ", - "60": "ਸੱਠ", - "61": "ਇਕਾਠ", - "62": "ਬਾਠ੍ਹ", - "63": "ਤਰੇਠ੍ਹ", - "64": "ਚੌਠ੍ਹ", - "65": "ਪੈਂਠ", - "66": "ਛਿਆਠ", - "67": "ਸਤਾਹਠ", - "68": "ਅੱਠਾਠ", - "69": "ਉਣੱਤਰ", - "70": "ਸੱਤਰ", - "71": "ਇਕ੍ਹੱਤਰ", - "72": "ਬਹੱਤਰ", - "73": "ਤਹੱਤਰ", - "74": "ਚੌਹੱਤਰ", - "75": "ਪੰਜੱਤਰ", - "76": "ਛਿਹੱਤਰ", - "77": "ਸਤੱਤਰ", - "78": "ਅਠੱਤਰ", - "79": "ਉਣਾਸੀ", - "80": "ਅੱਸੀ", - "81": "ਇਕਾਸੀ", - "82": "ਬਿਆਸੀ", - "83": "ਤਰਾਸੀ", - "84": "ਚਰਾਸੀ", - "85": "ਪੰਜਾਸੀ", - "86": "ਛਿਆਸੀ", - "87": "ਸਤਾਸੀ", - "88": "ਅਠਾਸੀ", - "89": "ਉਣਾਨਵੇਂ", - "90": "ਨੱਬੇ", - "91": "ਇਕਾਨਵੇਂ", - "92": "ਬਿਆਨਵੇਂ", - "93": "ਤਰਾਨਵੇਂ", - "94": "ਚਰਾਨਵੇਂ", - "95": "ਪਚਾਨਵੇਂ", - "96": "ਛਿਆਨਵੇਂ", - "97": "ਸਤਾਨਵੇਂ", - "98": "ਅਠਾਨਵੇਂ", - "99": "ਨਿੜਾਨਵੇਂ", - "100": "ਸੌ", - "1000": "ਹਜਾਰ", - "100000": "ਲੱਖ", - "10000000": "ਕਰੋੜ", - "1000000000": "ਅਰਬ", -} # Punjabi - -# --------------------------- num_to_word.py ------------------------------ -""" -Method to convert Numbers to Words -for indian languages - -Use cases:- -1) Speech recognition pre-processing -2) Language modeling Data pre-processing - -------------------------- -check indic_numbers.py to add support -for any indian language -""" - - -def language_specific_exception(words, lang, combiner): - """ - Language Specific Exception will come here - """ - - def occurs_at_end(piece): - return words[-len(piece) :] == piece - - if lang == "mr": - words = words.replace("एक" + combiner + "शे", "शंभर") - elif lang == "gu": - words = words.replace("બે" + combiner + "સો", "બસ્સો") - elif lang == "te": - exception_dict = { - "1": "ఒక", - "100": "వంద", - "100+": "వందలు", - "1000": "వెయ్యి", - "1000+": "వేలు", - "100000": "లక్ష", - "100000+": "లక్షలు", - "10000000": "కోటి", - "10000000+": "కోట్లు", - } - - test_case = ["100", "1000", "100000", "10000000"] - for test in test_case: - test_word = num_dict["te"][test] - match = num_dict["te"]["1"] + combiner + test_word - # for numbers like : 100, 1000, 100000 - if words == match: - return exception_dict[test] - # for numbers like : 200, 4000, 800000 - elif occurs_at_end(test_word): - words = words.replace(test_word, exception_dict[test + "+"]) - # for numbers like : 105, 1076, 123993 - elif not occurs_at_end(match): - replacement = exception_dict["1"] + combiner + exception_dict[test] - words = words.replace(match, replacement) - - # Exception case for 101...199 - special_case = "ఒక" + combiner + "వంద" - words = words.replace(special_case, "నూట") - elif lang == "kn": - # special case for 100 - if words == ("ಒಂದು" + combiner + "ನೂರ"): - return "ನೂರು" - exception_dict = { - "ನೂರ": "ನೂರು", - "ಸಾವಿರದ": "ಸಾವಿರ", - "ಲಕ್ಷದ": "ಲಕ್ಷ", - "ಕೋಟಿಯ": "ಕೋಟಿ", - } - for expt in exception_dict: - if occurs_at_end(expt): - words = words.replace(expt, exception_dict[expt]) - return words - - -def num_to_word(num, lang, separator=", ", combiner=" "): - """ - Main Method - :param num: Number digits from any indian language - :param lang: Language Code from supported Language - :param separator: Separator character i.e. separator = '-' --> 'two hundred-sixty' - :param combiner: combine number with position i.e. combiner = '-' --> 'two-hundred sixty' - :return: UTF-8 String of numbers in words - """ - lang = lang.lower() - num = str(num) - - # Load dictionary according to language code - assert lang in supported_lang, "Language not supported" - num_dic = num_dict[lang] - - # dash default combiner for english-india - if (lang == "en") & (combiner == " "): - combiner = "-" - - # Remove punctuations from numbers - num = str(num).replace(",", "").replace(" ", "") - - # Replace native language numbers with english digits - for language in supported_lang: - for num_index in range(10): - num = num.replace(all_num[language][num_index], all_num["en"][num_index]) - - # Assert that input contains only integer number - for digit in num: - assert digit in all_num["en"], "Give proper input" - - # Process - # For Number longer than 9 digits - def all_two_digit(digits_2): - if len(digits_2) <= 1: # Provided only one/zero digit - return num_dic.get(digits_2, "") - elif digits_2 == "00": # Two Zero provided - return num_dic["0"] + separator + num_dic["0"] - elif digits_2[0] == "0": # First digit is zero - return num_dic["0"] + separator + num_dic[digits_2[1]] - else: # Both digit provided - return num_dic[digits_2] - - # For Number less than 9 digits - def two_digit(digits_2): - digits_2 = digits_2.lstrip("0") - if len(digits_2) != 0: - return num_dic[digits_2] - else: - return "" - - def all_digit(digits): - digits = digits.lstrip("0") - digit_len = len(digits) - if digit_len > 3: - num_of_digits_to_process = (digit_len % 2) + 1 - process_digits = digits[:num_of_digits_to_process] - base = str(10 ** (int(digit_len / 2) * 2 - 1)) - remain_digits = digits[num_of_digits_to_process:] - return ( - num_dic[process_digits] - + combiner - + num_dic[base] - + separator - + all_digit(remain_digits) - ) - elif len(digits) == 3: - return ( - num_dic[digits[:1]] - + combiner - + num_dic["100"] - + separator - + two_digit(digits[1:]) - ) - else: - return two_digit(digits) - - num = num.lstrip("0") - full_digit_len = len(num) - - if full_digit_len == 0: - output = num_dic["0"] - elif full_digit_len <= 9: - output = all_digit(num) - else: - iteration = round(full_digit_len / 2) - output = all_two_digit(num[:2]) # First to digit - for i in range(1, iteration): - output = ( - output + separator + all_two_digit(num[i * 2 : (i + 1) * 2]) - ) # Next two digit pairs - remaining_digits = num[iteration * 2 :] - if not all_two_digit(remaining_digits) == "": - output = ( - output + separator + all_two_digit(remaining_digits) - ) # remaining Last one/two digits - - output = output.strip(separator) - - output = language_specific_exception(output, lang, combiner) - - return output - - -# --------------------------------- num_to_word_on_a_sent --------------------------------- - - -def is_digit(word, digit_pattern): - return re.search(digit_pattern, word) - - -def remove_punct(sent): - clean = re.sub("[%s]" % re.escape(string.punctuation), " ", sent) - return " ".join([word for word in clean.split() if word]) - - -def normalize_nums(text, lang): - """ - text: str (eg) - lang: lang code ['en', 'hi'] - - returns: str - (eg) - """ - - if lang in supported_lang: - words = text.split() - lang_digits = [str(i) for i in range(0, 10)] - - digit_pattern = "[" + "".join(lang_digits) + "]" - num_indices = [ - ind for ind, word in enumerate(words) if is_digit(word, digit_pattern) - ] - - words_up = [ - num_to_word(word, lang, separator=" ", combiner=" ") - if ind in num_indices - else word - for ind, word in enumerate(words) - ] - return " ".join(words_up) - else: - return text - - -if __name__ == "__main__": - print(normalize_nums("रीटा के पास 16 बिल्लियाँ हैं।", "hi")) diff --git a/spaces/Harveenchadha/en_to_indic_translation/indic_nlp_library/contrib/README.md b/spaces/Harveenchadha/en_to_indic_translation/indic_nlp_library/contrib/README.md deleted file mode 100644 index 0a99b9ddd9e9bcc72bae930fc8a778f3094fea50..0000000000000000000000000000000000000000 --- a/spaces/Harveenchadha/en_to_indic_translation/indic_nlp_library/contrib/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Contrib - -Contains additional utilities and applications using Indic NLP library core - -- `indic_scraper_project_sample.ipynb`: A simple pipeline for building monolingual corpora for Indian languages from crawled web content, Wikipedia, etc. An extensible framework which allows incorporation of website specific extractors, whereas generic NLP tasks like tokenization, sentence splitting, normalization, etc. are handled by the framework. -- `correct_moses_tokenizer.py`: This script corrects the incorrect tokenization done by Moses tokenizer. The Moses tokenizer splits on nukta and halant characters. -- `hindi_to_kannada_transliterator.py`: This script transliterates Hindi to Kannada. It removes/remaps characters only found in Hindi. It also adds halanta to words ending with consonant - as is the convention in Kannada. diff --git a/spaces/HgMenon/Transcribe_V0.2/src/utils.py b/spaces/HgMenon/Transcribe_V0.2/src/utils.py deleted file mode 100644 index 576244c9cf8b8e8aa888b0a51312ddf56db928ce..0000000000000000000000000000000000000000 --- a/spaces/HgMenon/Transcribe_V0.2/src/utils.py +++ /dev/null @@ -1,245 +0,0 @@ -import textwrap -import unicodedata -import re - -import zlib -from typing import Iterator, TextIO, Union -import tqdm - -import urllib3 - - -def exact_div(x, y): - assert x % y == 0 - return x // y - - -def str2bool(string): - str2val = {"True": True, "False": False} - if string in str2val: - return str2val[string] - else: - raise ValueError(f"Expected one of {set(str2val.keys())}, got {string}") - - -def optional_int(string): - return None if string == "None" else int(string) - - -def optional_float(string): - return None if string == "None" else float(string) - - -def compression_ratio(text) -> float: - return len(text) / len(zlib.compress(text.encode("utf-8"))) - - -def format_timestamp(seconds: float, always_include_hours: bool = False, fractionalSeperator: str = '.'): - assert seconds >= 0, "non-negative timestamp expected" - milliseconds = round(seconds * 1000.0) - - hours = milliseconds // 3_600_000 - milliseconds -= hours * 3_600_000 - - minutes = milliseconds // 60_000 - milliseconds -= minutes * 60_000 - - seconds = milliseconds // 1_000 - milliseconds -= seconds * 1_000 - - hours_marker = f"{hours:02d}:" if always_include_hours or hours > 0 else "" - return f"{hours_marker}{minutes:02d}:{seconds:02d}{fractionalSeperator}{milliseconds:03d}" - - -def write_txt(transcript: Iterator[dict], file: TextIO): - for segment in transcript: - print(segment['text'].strip(), file=file, flush=True) - - -def write_vtt(transcript: Iterator[dict], file: TextIO, - maxLineWidth=None, highlight_words: bool = False): - iterator = __subtitle_preprocessor_iterator(transcript, maxLineWidth, highlight_words) - - print("WEBVTT\n", file=file) - - for segment in iterator: - text = segment['text'].replace('-->', '->') - - print( - f"{format_timestamp(segment['start'])} --> {format_timestamp(segment['end'])}\n" - f"{text}\n", - file=file, - flush=True, - ) - -def write_srt(transcript: Iterator[dict], file: TextIO, - maxLineWidth=None, highlight_words: bool = False): - """ - Write a transcript to a file in SRT format. - Example usage: - from pathlib import Path - from whisper.utils import write_srt - result = transcribe(model, audio_path, temperature=temperature, **args) - # save SRT - audio_basename = Path(audio_path).stem - with open(Path(output_dir) / (audio_basename + ".srt"), "w", encoding="utf-8") as srt: - write_srt(result["segments"], file=srt) - """ - iterator = __subtitle_preprocessor_iterator(transcript, maxLineWidth, highlight_words) - - for i, segment in enumerate(iterator, start=1): - text = segment['text'].replace('-->', '->') - - # write srt lines - print( - f"{i}\n" - f"{format_timestamp(segment['start'], always_include_hours=True, fractionalSeperator=',')} --> " - f"{format_timestamp(segment['end'], always_include_hours=True, fractionalSeperator=',')}\n" - f"{text}\n", - file=file, - flush=True, - ) - -def __subtitle_preprocessor_iterator(transcript: Iterator[dict], maxLineWidth: int = None, highlight_words: bool = False): - for segment in transcript: - words = segment.get('words', []) - - if len(words) == 0: - # Yield the segment as-is or processed - if maxLineWidth is None or maxLineWidth < 0: - yield segment - else: - yield { - 'start': segment['start'], - 'end': segment['end'], - 'text': process_text(segment['text'].strip(), maxLineWidth) - } - # We are done - continue - - subtitle_start = segment['start'] - subtitle_end = segment['end'] - - text_words = [ this_word["word"] for this_word in words ] - subtitle_text = __join_words(text_words, maxLineWidth) - - # Iterate over the words in the segment - if highlight_words: - last = subtitle_start - - for i, this_word in enumerate(words): - start = this_word['start'] - end = this_word['end'] - - if last != start: - # Display the text up to this point - yield { - 'start': last, - 'end': start, - 'text': subtitle_text - } - - # Display the text with the current word highlighted - yield { - 'start': start, - 'end': end, - 'text': __join_words( - [ - { - "word": re.sub(r"^(\s*)(.*)$", r"\1\2", word) - if j == i - else word, - # The HTML tags and are not displayed, - # # so they should not be counted in the word length - "length": len(word) - } for j, word in enumerate(text_words) - ], maxLineWidth) - } - last = end - - if last != subtitle_end: - # Display the last part of the text - yield { - 'start': last, - 'end': subtitle_end, - 'text': subtitle_text - } - - # Just return the subtitle text - else: - yield { - 'start': subtitle_start, - 'end': subtitle_end, - 'text': subtitle_text - } - -def __join_words(words: Iterator[Union[str, dict]], maxLineWidth: int = None): - if maxLineWidth is None or maxLineWidth < 0: - return " ".join(words) - - lines = [] - current_line = "" - current_length = 0 - - for entry in words: - # Either accept a string or a dict with a 'word' and 'length' field - if isinstance(entry, dict): - word = entry['word'] - word_length = entry['length'] - else: - word = entry - word_length = len(word) - - if current_length > 0 and current_length + word_length > maxLineWidth: - lines.append(current_line) - current_line = "" - current_length = 0 - - current_length += word_length - # The word will be prefixed with a space by Whisper, so we don't need to add one here - current_line += word - - if len(current_line) > 0: - lines.append(current_line) - - return "\n".join(lines) - -def process_text(text: str, maxLineWidth=None): - if (maxLineWidth is None or maxLineWidth < 0): - return text - - lines = textwrap.wrap(text, width=maxLineWidth, tabsize=4) - return '\n'.join(lines) - -def slugify(value, allow_unicode=False): - """ - Taken from https://github.com/django/django/blob/master/django/utils/text.py - Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated - dashes to single dashes. Remove characters that aren't alphanumerics, - underscores, or hyphens. Convert to lowercase. Also strip leading and - trailing whitespace, dashes, and underscores. - """ - value = str(value) - if allow_unicode: - value = unicodedata.normalize('NFKC', value) - else: - value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii') - value = re.sub(r'[^\w\s-]', '', value.lower()) - return re.sub(r'[-\s]+', '-', value).strip('-_') - -def download_file(url: str, destination: str): - with urllib3.request.urlopen(url) as source, open(destination, "wb") as output: - with tqdm( - total=int(source.info().get("Content-Length")), - ncols=80, - unit="iB", - unit_scale=True, - unit_divisor=1024, - ) as loop: - while True: - buffer = source.read(8192) - if not buffer: - break - - output.write(buffer) - loop.update(len(buffer)) \ No newline at end of file diff --git a/spaces/ICML2022/Leaderboard/app.py b/spaces/ICML2022/Leaderboard/app.py deleted file mode 100644 index 958950af83dae605628e0d97e0daa5bbd709f1a4..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/Leaderboard/app.py +++ /dev/null @@ -1,39 +0,0 @@ -import os -import requests -import pandas as pd -import gradio as gr -from huggingface_hub.hf_api import SpaceInfo -from pathlib import Path - - -path = f"https://huggingface.co/api/spaces" - - -def get_blocks_party_spaces(): - r = requests.get(path) - d = r.json() - spaces = [SpaceInfo(**x) for x in d] - blocks_spaces = {} - for i in range(0,len(spaces)): - if spaces[i].id.split('/')[0] == 'ICML2022' and hasattr(spaces[i], 'likes') and spaces[i].id != 'ICML2022/Leaderboard' and spaces[i].id != 'ICML2022/README': - blocks_spaces[spaces[i].id]=spaces[i].likes - df = pd.DataFrame( - [{"Spaces_Name": Spaces, "likes": likes} for Spaces,likes in blocks_spaces.items()]) - df = df.sort_values(by=['likes'],ascending=False) - return df - - -block = gr.Blocks() - -with block: - gr.Markdown("""Leaderboard for the most popular ICML 2022 Spaces. To learn more and join, see ICML 2022 Event""") - with gr.Tabs(): - with gr.TabItem("ICML 2022 Leaderboard"): - with gr.Row(): - data = gr.outputs.Dataframe(type="pandas") - with gr.Row(): - data_run = gr.Button("Refresh") - data_run.click(get_blocks_party_spaces, inputs=None, outputs=data) - - block.load(get_blocks_party_spaces, inputs=None, outputs=data) -block.launch() diff --git a/spaces/ICML2022/OFA/fairseq/examples/backtranslation/README.md b/spaces/ICML2022/OFA/fairseq/examples/backtranslation/README.md deleted file mode 100644 index 73675f1125d80f58aa824db67d8970504d4d6b2a..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/examples/backtranslation/README.md +++ /dev/null @@ -1,297 +0,0 @@ -# Understanding Back-Translation at Scale (Edunov et al., 2018) - -This page includes pre-trained models from the paper [Understanding Back-Translation at Scale (Edunov et al., 2018)](https://arxiv.org/abs/1808.09381). - -## Pre-trained models - -Model | Description | Dataset | Download ----|---|---|--- -`transformer.wmt18.en-de` | Transformer
([Edunov et al., 2018](https://arxiv.org/abs/1808.09381))
WMT'18 winner | [WMT'18 English-German](http://www.statmt.org/wmt18/translation-task.html) | [download (.tar.gz)](https://dl.fbaipublicfiles.com/fairseq/models/wmt18.en-de.ensemble.tar.gz)
See NOTE in the archive - -## Example usage (torch.hub) - -We require a few additional Python dependencies for preprocessing: -```bash -pip install subword_nmt sacremoses -``` - -Then to generate translations from the full model ensemble: -```python -import torch - -# List available models -torch.hub.list('pytorch/fairseq') # [..., 'transformer.wmt18.en-de', ... ] - -# Load the WMT'18 En-De ensemble -en2de_ensemble = torch.hub.load( - 'pytorch/fairseq', 'transformer.wmt18.en-de', - checkpoint_file='wmt18.model1.pt:wmt18.model2.pt:wmt18.model3.pt:wmt18.model4.pt:wmt18.model5.pt', - tokenizer='moses', bpe='subword_nmt') - -# The ensemble contains 5 models -len(en2de_ensemble.models) -# 5 - -# Translate -en2de_ensemble.translate('Hello world!') -# 'Hallo Welt!' -``` - -## Training your own model (WMT'18 English-German) - -The following instructions can be adapted to reproduce the models from the paper. - - -#### Step 1. Prepare parallel data and optionally train a baseline (English-German) model - -First download and preprocess the data: -```bash -# Download and prepare the data -cd examples/backtranslation/ -bash prepare-wmt18en2de.sh -cd ../.. - -# Binarize the data -TEXT=examples/backtranslation/wmt18_en_de -fairseq-preprocess \ - --joined-dictionary \ - --source-lang en --target-lang de \ - --trainpref $TEXT/train --validpref $TEXT/valid --testpref $TEXT/test \ - --destdir data-bin/wmt18_en_de --thresholdtgt 0 --thresholdsrc 0 \ - --workers 20 - -# Copy the BPE code into the data-bin directory for future use -cp examples/backtranslation/wmt18_en_de/code data-bin/wmt18_en_de/code -``` - -(Optionally) Train a baseline model (English-German) using just the parallel data: -```bash -CHECKPOINT_DIR=checkpoints_en_de_parallel -fairseq-train --fp16 \ - data-bin/wmt18_en_de \ - --source-lang en --target-lang de \ - --arch transformer_wmt_en_de_big --share-all-embeddings \ - --dropout 0.3 --weight-decay 0.0 \ - --criterion label_smoothed_cross_entropy --label-smoothing 0.1 \ - --optimizer adam --adam-betas '(0.9, 0.98)' --clip-norm 0.0 \ - --lr 0.001 --lr-scheduler inverse_sqrt --warmup-updates 4000 \ - --max-tokens 3584 --update-freq 16 \ - --max-update 30000 \ - --save-dir $CHECKPOINT_DIR -# Note: the above command assumes 8 GPUs. Adjust `--update-freq` if you have a -# different number of GPUs. -``` - -Average the last 10 checkpoints: -```bash -python scripts/average_checkpoints.py \ - --inputs $CHECKPOINT_DIR \ - --num-epoch-checkpoints 10 \ - --output $CHECKPOINT_DIR/checkpoint.avg10.pt -``` - -Evaluate BLEU: -```bash -# tokenized BLEU on newstest2017: -bash examples/backtranslation/tokenized_bleu.sh \ - wmt17 \ - en-de \ - data-bin/wmt18_en_de \ - data-bin/wmt18_en_de/code \ - $CHECKPOINT_DIR/checkpoint.avg10.pt -# BLEU4 = 29.57, 60.9/35.4/22.9/15.5 (BP=1.000, ratio=1.014, syslen=63049, reflen=62152) -# compare to 29.46 in Table 1, which is also for tokenized BLEU - -# generally it's better to report (detokenized) sacrebleu though: -bash examples/backtranslation/sacrebleu.sh \ - wmt17 \ - en-de \ - data-bin/wmt18_en_de \ - data-bin/wmt18_en_de/code \ - $CHECKPOINT_DIR/checkpoint.avg10.pt -# BLEU+case.mixed+lang.en-de+numrefs.1+smooth.exp+test.wmt17+tok.13a+version.1.4.3 = 29.0 60.6/34.7/22.4/14.9 (BP = 1.000 ratio = 1.013 hyp_len = 62099 ref_len = 61287) -``` - - -#### Step 2. Back-translate monolingual German data - -Train a reverse model (German-English) to do the back-translation: -```bash -CHECKPOINT_DIR=checkpoints_de_en_parallel -fairseq-train --fp16 \ - data-bin/wmt18_en_de \ - --source-lang de --target-lang en \ - --arch transformer_wmt_en_de_big --share-all-embeddings \ - --dropout 0.3 --weight-decay 0.0 \ - --criterion label_smoothed_cross_entropy --label-smoothing 0.1 \ - --optimizer adam --adam-betas '(0.9, 0.98)' --clip-norm 0.0 \ - --lr 0.001 --lr-scheduler inverse_sqrt --warmup-updates 4000 \ - --max-tokens 3584 --update-freq 16 \ - --max-update 30000 \ - --save-dir $CHECKPOINT_DIR -# Note: the above command assumes 8 GPUs. Adjust `--update-freq` if you have a -# different number of GPUs. -``` - -Let's evaluate the back-translation (BT) model to make sure it is well trained: -```bash -bash examples/backtranslation/sacrebleu.sh \ - wmt17 \ - de-en \ - data-bin/wmt18_en_de \ - data-bin/wmt18_en_de/code \ - $CHECKPOINT_DIR/checkpoint_best.py -# BLEU+case.mixed+lang.de-en+numrefs.1+smooth.exp+test.wmt17+tok.13a+version.1.4.3 = 34.9 66.9/41.8/28.5/19.9 (BP = 0.983 ratio = 0.984 hyp_len = 63342 ref_len = 64399) -# compare to the best system from WMT'17 which scored 35.1: http://matrix.statmt.org/matrix/systems_list/1868 -``` - -Next prepare the monolingual data: -```bash -# Download and prepare the monolingual data -# By default the script samples 25M monolingual sentences, which after -# deduplication should be just over 24M sentences. These are split into 25 -# shards, each with 1M sentences (except for the last shard). -cd examples/backtranslation/ -bash prepare-de-monolingual.sh -cd ../.. - -# Binarize each shard of the monolingual data -TEXT=examples/backtranslation/wmt18_de_mono -for SHARD in $(seq -f "%02g" 0 24); do \ - fairseq-preprocess \ - --only-source \ - --source-lang de --target-lang en \ - --joined-dictionary \ - --srcdict data-bin/wmt18_en_de/dict.de.txt \ - --testpref $TEXT/bpe.monolingual.dedup.${SHARD} \ - --destdir data-bin/wmt18_de_mono/shard${SHARD} \ - --workers 20; \ - cp data-bin/wmt18_en_de/dict.en.txt data-bin/wmt18_de_mono/shard${SHARD}/; \ -done -``` - -Now we're ready to perform back-translation over the monolingual data. The -following command generates via sampling, but it's possible to use greedy -decoding (`--beam 1`), beam search (`--beam 5`), -top-k sampling (`--sampling --beam 1 --sampling-topk 10`), etc.: -```bash -mkdir backtranslation_output -for SHARD in $(seq -f "%02g" 0 24); do \ - fairseq-generate --fp16 \ - data-bin/wmt18_de_mono/shard${SHARD} \ - --path $CHECKPOINT_DIR/checkpoint_best.pt \ - --skip-invalid-size-inputs-valid-test \ - --max-tokens 4096 \ - --sampling --beam 1 \ - > backtranslation_output/sampling.shard${SHARD}.out; \ -done -``` - -After BT, use the `extract_bt_data.py` script to re-combine the shards, extract -the back-translations and apply length ratio filters: -```bash -python examples/backtranslation/extract_bt_data.py \ - --minlen 1 --maxlen 250 --ratio 1.5 \ - --output backtranslation_output/bt_data --srclang en --tgtlang de \ - backtranslation_output/sampling.shard*.out - -# Ensure lengths are the same: -# wc -l backtranslation_output/bt_data.{en,de} -# 21795614 backtranslation_output/bt_data.en -# 21795614 backtranslation_output/bt_data.de -# 43591228 total -``` - -Binarize the filtered BT data and combine it with the parallel data: -```bash -TEXT=backtranslation_output -fairseq-preprocess \ - --source-lang en --target-lang de \ - --joined-dictionary \ - --srcdict data-bin/wmt18_en_de/dict.en.txt \ - --trainpref $TEXT/bt_data \ - --destdir data-bin/wmt18_en_de_bt \ - --workers 20 - -# We want to train on the combined data, so we'll symlink the parallel + BT data -# in the wmt18_en_de_para_plus_bt directory. We link the parallel data as "train" -# and the BT data as "train1", so that fairseq will combine them automatically -# and so that we can use the `--upsample-primary` option to upsample the -# parallel data (if desired). -PARA_DATA=$(readlink -f data-bin/wmt18_en_de) -BT_DATA=$(readlink -f data-bin/wmt18_en_de_bt) -COMB_DATA=data-bin/wmt18_en_de_para_plus_bt -mkdir -p $COMB_DATA -for LANG in en de; do \ - ln -s ${PARA_DATA}/dict.$LANG.txt ${COMB_DATA}/dict.$LANG.txt; \ - for EXT in bin idx; do \ - ln -s ${PARA_DATA}/train.en-de.$LANG.$EXT ${COMB_DATA}/train.en-de.$LANG.$EXT; \ - ln -s ${BT_DATA}/train.en-de.$LANG.$EXT ${COMB_DATA}/train1.en-de.$LANG.$EXT; \ - ln -s ${PARA_DATA}/valid.en-de.$LANG.$EXT ${COMB_DATA}/valid.en-de.$LANG.$EXT; \ - ln -s ${PARA_DATA}/test.en-de.$LANG.$EXT ${COMB_DATA}/test.en-de.$LANG.$EXT; \ - done; \ -done -``` - - -#### 3. Train an English-German model over the combined parallel + BT data - -Finally we can train a model over the parallel + BT data: -```bash -CHECKPOINT_DIR=checkpoints_en_de_parallel_plus_bt -fairseq-train --fp16 \ - data-bin/wmt18_en_de_para_plus_bt \ - --upsample-primary 16 \ - --source-lang en --target-lang de \ - --arch transformer_wmt_en_de_big --share-all-embeddings \ - --dropout 0.3 --weight-decay 0.0 \ - --criterion label_smoothed_cross_entropy --label-smoothing 0.1 \ - --optimizer adam --adam-betas '(0.9, 0.98)' --clip-norm 0.0 \ - --lr 0.0007 --lr-scheduler inverse_sqrt --warmup-updates 4000 \ - --max-tokens 3584 --update-freq 16 \ - --max-update 100000 \ - --save-dir $CHECKPOINT_DIR -# Note: the above command assumes 8 GPUs. Adjust `--update-freq` if you have a -# different number of GPUs. -``` - -Average the last 10 checkpoints: -```bash -python scripts/average_checkpoints.py \ - --inputs $CHECKPOINT_DIR \ - --num-epoch-checkpoints 10 \ - --output $CHECKPOINT_DIR/checkpoint.avg10.pt -``` - -Evaluate BLEU: -```bash -# tokenized BLEU on newstest2017: -bash examples/backtranslation/tokenized_bleu.sh \ - wmt17 \ - en-de \ - data-bin/wmt18_en_de \ - data-bin/wmt18_en_de/code \ - $CHECKPOINT_DIR/checkpoint.avg10.pt -# BLEU4 = 32.35, 64.4/38.9/26.2/18.3 (BP=0.977, ratio=0.977, syslen=60729, reflen=62152) -# compare to 32.35 in Table 1, which is also for tokenized BLEU - -# generally it's better to report (detokenized) sacrebleu: -bash examples/backtranslation/sacrebleu.sh \ - wmt17 \ - en-de \ - data-bin/wmt18_en_de \ - data-bin/wmt18_en_de/code \ - $CHECKPOINT_DIR/checkpoint.avg10.pt -# BLEU+case.mixed+lang.en-de+numrefs.1+smooth.exp+test.wmt17+tok.13a+version.1.4.3 = 31.5 64.3/38.2/25.6/17.6 (BP = 0.971 ratio = 0.971 hyp_len = 59515 ref_len = 61287) -``` - - -## Citation -```bibtex -@inproceedings{edunov2018backtranslation, - title = {Understanding Back-Translation at Scale}, - author = {Edunov, Sergey and Ott, Myle and Auli, Michael and Grangier, David}, - booktitle = {Conference of the Association for Computational Linguistics (ACL)}, - year = 2018, -} -``` diff --git a/spaces/ICML2022/OFA/fairseq/examples/criss/unsupervised_mt/eval.sh b/spaces/ICML2022/OFA/fairseq/examples/criss/unsupervised_mt/eval.sh deleted file mode 100644 index 03b773ed5a522eb82186fea8ffbb6c557e14b6d3..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/examples/criss/unsupervised_mt/eval.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash -# Copyright (c) Facebook, Inc. and its affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. -# -SRC=si_LK -TGT=en_XX -MODEL=criss_checkpoints/criss.3rd.pt - -MULTIBLEU=mosesdecoder/scripts/generic/multi-bleu.perl -MOSES=mosesdecoder -REPLACE_UNICODE_PUNCT=$MOSES/scripts/tokenizer/replace-unicode-punctuation.perl -NORM_PUNC=$MOSES/scripts/tokenizer/normalize-punctuation.perl -REM_NON_PRINT_CHAR=$MOSES/scripts/tokenizer/remove-non-printing-char.perl -TOKENIZER=$MOSES/scripts/tokenizer/tokenizer.perl -GEN_TMP_DIR=gen_tmp -LANG_DICT=criss_checkpoints/lang_dict.txt - -if [ ! -d "mosesdecoder" ]; then - git clone https://github.com/moses-smt/mosesdecoder -fi -mkdir -p $GEN_TMP_DIR -fairseq-generate data_tmp/${SRC}-${TGT}-flores \ - --task translation_multi_simple_epoch \ - --max-tokens 2000 \ - --path ${MODEL} \ - --skip-invalid-size-inputs-valid-test \ - --beam 5 --lenpen 1.0 --gen-subset test \ - --remove-bpe=sentencepiece \ - --source-lang ${SRC} --target-lang ${TGT} \ - --decoder-langtok --lang-pairs 'en_XX-ar_AR,en_XX-de_DE,en_XX-es_XX,en_XX-fr_XX,en_XX-hi_IN,en_XX-it_IT,en_XX-ja_XX,en_XX-ko_KR,en_XX-nl_XX,en_XX-ru_RU,en_XX-zh_CN,en_XX-tr_TR,en_XX-vi_VN,en_XX-ro_RO,en_XX-my_MM,en_XX-ne_NP,en_XX-si_LK,en_XX-cs_CZ,en_XX-lt_LT,en_XX-kk_KZ,en_XX-gu_IN,en_XX-fi_FI,en_XX-et_EE,en_XX-lv_LV,ar_AR-en_XX,cs_CZ-en_XX,de_DE-en_XX,es_XX-en_XX,et_EE-en_XX,fi_FI-en_XX,fr_XX-en_XX,gu_IN-en_XX,hi_IN-en_XX,it_IT-en_XX,ja_XX-en_XX,kk_KZ-en_XX,ko_KR-en_XX,lt_LT-en_XX,lv_LV-en_XX,my_MM-en_XX,ne_NP-en_XX,nl_XX-en_XX,ro_RO-en_XX,ru_RU-en_XX,si_LK-en_XX,tr_TR-en_XX,vi_VN-en_XX,zh_CN-en_XX,ar_AR-es_XX,es_XX-ar_AR,ar_AR-hi_IN,hi_IN-ar_AR,ar_AR-zh_CN,zh_CN-ar_AR,cs_CZ-es_XX,es_XX-cs_CZ,cs_CZ-hi_IN,hi_IN-cs_CZ,cs_CZ-zh_CN,zh_CN-cs_CZ,de_DE-es_XX,es_XX-de_DE,de_DE-hi_IN,hi_IN-de_DE,de_DE-zh_CN,zh_CN-de_DE,es_XX-hi_IN,hi_IN-es_XX,es_XX-zh_CN,zh_CN-es_XX,et_EE-es_XX,es_XX-et_EE,et_EE-hi_IN,hi_IN-et_EE,et_EE-zh_CN,zh_CN-et_EE,fi_FI-es_XX,es_XX-fi_FI,fi_FI-hi_IN,hi_IN-fi_FI,fi_FI-zh_CN,zh_CN-fi_FI,fr_XX-es_XX,es_XX-fr_XX,fr_XX-hi_IN,hi_IN-fr_XX,fr_XX-zh_CN,zh_CN-fr_XX,gu_IN-es_XX,es_XX-gu_IN,gu_IN-hi_IN,hi_IN-gu_IN,gu_IN-zh_CN,zh_CN-gu_IN,hi_IN-zh_CN,zh_CN-hi_IN,it_IT-es_XX,es_XX-it_IT,it_IT-hi_IN,hi_IN-it_IT,it_IT-zh_CN,zh_CN-it_IT,ja_XX-es_XX,es_XX-ja_XX,ja_XX-hi_IN,hi_IN-ja_XX,ja_XX-zh_CN,zh_CN-ja_XX,kk_KZ-es_XX,es_XX-kk_KZ,kk_KZ-hi_IN,hi_IN-kk_KZ,kk_KZ-zh_CN,zh_CN-kk_KZ,ko_KR-es_XX,es_XX-ko_KR,ko_KR-hi_IN,hi_IN-ko_KR,ko_KR-zh_CN,zh_CN-ko_KR,lt_LT-es_XX,es_XX-lt_LT,lt_LT-hi_IN,hi_IN-lt_LT,lt_LT-zh_CN,zh_CN-lt_LT,lv_LV-es_XX,es_XX-lv_LV,lv_LV-hi_IN,hi_IN-lv_LV,lv_LV-zh_CN,zh_CN-lv_LV,my_MM-es_XX,es_XX-my_MM,my_MM-hi_IN,hi_IN-my_MM,my_MM-zh_CN,zh_CN-my_MM,ne_NP-es_XX,es_XX-ne_NP,ne_NP-hi_IN,hi_IN-ne_NP,ne_NP-zh_CN,zh_CN-ne_NP,nl_XX-es_XX,es_XX-nl_XX,nl_XX-hi_IN,hi_IN-nl_XX,nl_XX-zh_CN,zh_CN-nl_XX,ro_RO-es_XX,es_XX-ro_RO,ro_RO-hi_IN,hi_IN-ro_RO,ro_RO-zh_CN,zh_CN-ro_RO,ru_RU-es_XX,es_XX-ru_RU,ru_RU-hi_IN,hi_IN-ru_RU,ru_RU-zh_CN,zh_CN-ru_RU,si_LK-es_XX,es_XX-si_LK,si_LK-hi_IN,hi_IN-si_LK,si_LK-zh_CN,zh_CN-si_LK,tr_TR-es_XX,es_XX-tr_TR,tr_TR-hi_IN,hi_IN-tr_TR,tr_TR-zh_CN,zh_CN-tr_TR,vi_VN-es_XX,es_XX-vi_VN,vi_VN-hi_IN,hi_IN-vi_VN,vi_VN-zh_CN,zh_CN-vi_VN' \ - --lang-dict ${LANG_DICT} --lang-tok-style 'mbart' --sampling-method 'temperature' --sampling-temperature '1.0' > $GEN_TMP_DIR/${SRC}_${TGT}.gen -cat $GEN_TMP_DIR/${SRC}_${TGT}.gen | grep -P "^T-" | cut -f2 | $REPLACE_UNICODE_PUNCT | $NORM_PUNC -l ${TGT:0:2} | $REM_NON_PRINT_CHAR | $TOKENIZER -no-escape ${TGT:0:2} > $GEN_TMP_DIR/${SRC}_${TGT}.hyp -cat $GEN_TMP_DIR/${SRC}_${TGT}.gen | grep -P "^H-" | cut -f3 | $REPLACE_UNICODE_PUNCT | $NORM_PUNC -l ${TGT:0:2} | $REM_NON_PRINT_CHAR | $TOKENIZER -no-escape ${TGT:0:2} > $GEN_TMP_DIR/${SRC}_${TGT}.ref -${MULTIBLEU} $GEN_TMP_DIR/${SRC}_${TGT}.ref < $GEN_TMP_DIR/${SRC}_${TGT}.hyp diff --git a/spaces/IcelandAI/Foods-and-Drinks-of-Iceland/README.md b/spaces/IcelandAI/Foods-and-Drinks-of-Iceland/README.md deleted file mode 100644 index 9ad7617b01eee8b2ca79ee999cbc5d6004eb6cd9..0000000000000000000000000000000000000000 --- a/spaces/IcelandAI/Foods-and-Drinks-of-Iceland/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Foods And Drinks Of Iceland -emoji: 🚀 -colorFrom: gray -colorTo: green -sdk: streamlit -sdk_version: 1.17.0 -app_file: app.py -pinned: false -license: mit ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Iqbaljanitra/brandshoesprediction_nike_converse_adidas/README.md b/spaces/Iqbaljanitra/brandshoesprediction_nike_converse_adidas/README.md deleted file mode 100644 index cd03df6cebebaa11c99ae43562b18fdeb64a1daa..0000000000000000000000000000000000000000 --- a/spaces/Iqbaljanitra/brandshoesprediction_nike_converse_adidas/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Brandshoesprediction Nike Converse Adidas -emoji: 🐠 -colorFrom: yellow -colorTo: pink -sdk: streamlit -sdk_version: 1.17.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Izal887/rvc-ram12/lib/infer_pack/modules/F0Predictor/__init__.py b/spaces/Izal887/rvc-ram12/lib/infer_pack/modules/F0Predictor/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/JUNGU/gpt4kids/README.md b/spaces/JUNGU/gpt4kids/README.md deleted file mode 100644 index 7903b155e84daf8ecc150f2c64f18aae360ff3ee..0000000000000000000000000000000000000000 --- a/spaces/JUNGU/gpt4kids/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Talktosayno -emoji: 📉 -colorFrom: green -colorTo: pink -sdk: gradio -sdk_version: 3.34.0 -app_file: app.py -pinned: false -license: openrail -duplicated_from: JUNGU/talktosayno ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/JeffJing/ZookChatBot/steamship/plugin/outputs/model_checkpoint.py b/spaces/JeffJing/ZookChatBot/steamship/plugin/outputs/model_checkpoint.py deleted file mode 100644 index 7211818d3381de83098b839b8709ada2367756ee..0000000000000000000000000000000000000000 --- a/spaces/JeffJing/ZookChatBot/steamship/plugin/outputs/model_checkpoint.py +++ /dev/null @@ -1,140 +0,0 @@ -import logging -import tempfile -from pathlib import Path -from typing import ClassVar, Optional - -from steamship import Steamship, SteamshipError -from steamship.base.client import Client -from steamship.base.model import CamelModel -from steamship.data.workspace import SignedUrl, Workspace -from steamship.utils.signed_urls import download_from_signed_url, upload_to_signed_url -from steamship.utils.zip_archives import unzip_folder, zip_folder - - -class ModelCheckpoint(CamelModel): - # The default model checkpoint handle unless one is provided. - DEFAULT_HANDLE: ClassVar[str] = "default" - - """Represents the saved state of a trained PluginInstance. - """ - client: Client - workspace: Optional[Workspace] = None - plugin_instance_id: str - - parent_directory: Optional[Path] = None # e.g. /tmp - handle: str = None # The handle of this ModelCheckpoint. - plugin_instance_id: str = None # - - def __init__( - self, - client: Steamship, - parent_directory: Optional[Path] = None, - handle: str = DEFAULT_HANDLE, - plugin_instance_id: str = None, - ): - super().__init__( - client=client, - parent_directory=parent_directory, - plugin_instance_id=plugin_instance_id, - handle=handle or ModelCheckpoint.DEFAULT_HANDLE, - ) - - if self.plugin_instance_id is None: - raise SteamshipError("Null plugin_instance_id provided ModelCheckpoint") - - self.workspace = client.get_workspace() - - if parent_directory is None: - # TODO(ted): We may want to not use a tempdir so that we can cache it. - self.parent_directory = Path(tempfile.mkdtemp()) - - # Create the folder path on disk. - logging.info(f"Making sure Checkpoint path exists: {self.folder_path_on_disk()}") - self.folder_path_on_disk().mkdir(parents=True, exist_ok=True) - - def folder_path_on_disk(self) -> Path: - """Returns the path to this checkpoint on the local disk. - - On disk, the model checkpoint is the folder: - `{parent_directory}/{checkpoint_handle}/` - """ - return self.parent_directory / Path(self.handle) - - def archive_path_on_disk(self) -> Path: - """Returns the path to the checkpoint archive on disk. - - On disk, the model checkpoint is the folder: - `{parent_directory}/{checkpoint_handle}.zip` - """ - return self.parent_directory / Path(f"{self.handle}.zip") - - def archive_path_in_steamship(self, as_handle: str = None) -> str: - """Returns the path to the checkpoint archive on Steamship. - - On steamship, the checkpoint is archived in the Workspace's PluginInstance bucket as: - `{plugin_instance_bucket}/{plugin_instance_id}/{checkpoint_handle}.zip` - - Here we only return the following path since the bucket is specified separately - in the required Steamship API calls: `{plugin_instance_id}/{checkpoint_handle}.zip` - """ - return f"{self.plugin_instance_id}/{as_handle or self.handle}.zip" - - def download_model_bundle(self) -> Path: - """Download's the model from Steamship and unzips to `parent_directory`""" - download_resp = self.workspace.create_signed_url( - SignedUrl.Request( - bucket=SignedUrl.Bucket.PLUGIN_DATA, - filepath=self.archive_path_in_steamship(), - operation=SignedUrl.Operation.READ, - ) - ) - if not download_resp or not download_resp.signed_url: - raise SteamshipError( - message=f"Received empty Signed URL for model download of '{self.handle}." - ) - download_from_signed_url(download_resp.signed_url, to_file=self.archive_path_on_disk()) - unzip_folder(self.archive_path_on_disk(), into_folder=self.folder_path_on_disk()) - if not download_resp or not download_resp.signed_url: - raise SteamshipError( - message=f"Received empty Signed URL for model download of '{self.handle}." - ) - download_from_signed_url(download_resp.signed_url, to_file=self.archive_path_on_disk()) - unzip_folder(self.archive_path_on_disk(), into_folder=self.folder_path_on_disk()) - return self.folder_path_on_disk() - - def _upload_model_zip(self, as_handle: str = None): - """Assumes a pre-zipped model, uploads to the requested zip. - - This is an internal function. Please use upload_model_bundle as an caller.""" - logging.info(f"ModelCheckpoint:_upload_model_zip - handle={as_handle}") - signed_url_resp = self.workspace.create_signed_url( - SignedUrl.Request( - bucket=SignedUrl.Bucket.PLUGIN_DATA, - filepath=self.archive_path_in_steamship(as_handle=as_handle), - operation=SignedUrl.Operation.WRITE, - ) - ) - - if not signed_url_resp: - raise SteamshipError( - message="Empty result on Signed URL request while uploading model checkpoint" - ) - if not signed_url_resp.signed_url: - raise SteamshipError( - message="Empty signedUrl on Signed URL request while uploading model checkpoint" - ) - - upload_to_signed_url(signed_url_resp.signed_url, filepath=self.archive_path_on_disk()) - - def upload_model_bundle(self, set_as_default: bool = True): - """Zips and uploads the Model to steamship""" - logging.info("ModelCheckpoint:upload_model_bundle") - zip_folder(self.folder_path_on_disk(), into_file=self.archive_path_on_disk()) - self._upload_model_zip() - - if set_as_default: - # For simplicity, we'll assume the checkpoint named `default` is the one to be loaded unless otherwise - # specified. This means that we need to double-upload some checkpoints: - # - Once under the actual checkpoint name (e.g. `epoch-10`) - # - Again under the name: default - self._upload_model_zip(as_handle=ModelCheckpoint.DEFAULT_HANDLE) diff --git a/spaces/Jesuscriss301/prueba/app.py b/spaces/Jesuscriss301/prueba/app.py deleted file mode 100644 index f12964b627c76ac565b1115d16b0d4a707c78476..0000000000000000000000000000000000000000 --- a/spaces/Jesuscriss301/prueba/app.py +++ /dev/null @@ -1,38 +0,0 @@ -#Librerias para cargar imagenes -import numpy as np -from keras.preprocessing.image import load_img, img_to_array -from keras.models import load_model -import streamlit as st - -dim = 200 -modelo = './modelo.h5' -pesos = './pesos.h5' -cnn = load_model(modelo) -cnn.load_weights(pesos) - -st.title("Upload + Classification Example") -uploaded_file = st.file_uploader("Choose an image...", type="jpg") -if uploaded_file is not None: - image = Image.open(uploaded_file) - st.image(image, caption='Uploaded Image.', use_column_width=True) - st.write("") - st.write("Classifying...") - label = predict(uploaded_file) ##aqui va el llamado a la IA - st.write('%s (%.2f%%)' % (label[1], label[2]*100)) - -def clasificar(uploaded_file): - x = load_img(uploaded_file, target_size=(dim, dim), color_mode = "grayscale") - x = img_to_array(x) - x = np.expand_dims(x, axis=0) - arreglo = cnn.predict(x) - resultado = arreglo[0] - respuesta = np.argmax(resultado) - - if respuesta==0: - print('NORMAL') - else: - print('TUMOR CEREBRAL') - - return respuesta - -clasificar(uploaded_file) \ No newline at end of file diff --git a/spaces/JohnnyPittt/audio-styling/deepafx_st/system.py b/spaces/JohnnyPittt/audio-styling/deepafx_st/system.py deleted file mode 100644 index 449afa586bf80bbafd858999670a2c364c6a9c2b..0000000000000000000000000000000000000000 --- a/spaces/JohnnyPittt/audio-styling/deepafx_st/system.py +++ /dev/null @@ -1,563 +0,0 @@ -import torch -import auraloss -import torchaudio -from itertools import chain -import pytorch_lightning as pl -from argparse import ArgumentParser -from typing import Tuple, List, Dict - -import deepafx_st.utils as utils -from deepafx_st.utils import DSPMode -from deepafx_st.data.dataset import AudioDataset -from deepafx_st.models.encoder import SpectralEncoder -from deepafx_st.models.controller import StyleTransferController -from deepafx_st.processors.spsa.channel import SPSAChannel -from deepafx_st.processors.spsa.eps_scheduler import EpsilonScheduler -from deepafx_st.processors.proxy.channel import ProxyChannel -from deepafx_st.processors.autodiff.channel import AutodiffChannel - - -class System(pl.LightningModule): - def __init__( - self, - ext="wav", - dsp_sample_rate=24000, - **kwargs, - ): - super().__init__() - self.save_hyperparameters() - - self.eps_scheduler = EpsilonScheduler( - self.hparams.spsa_epsilon, - self.hparams.spsa_patience, - self.hparams.spsa_factor, - self.hparams.spsa_verbose, - ) - - self.hparams.dsp_mode = DSPMode.NONE - - # first construct the processor, since this will dictate encoder - if self.hparams.processor_model == "spsa": - self.processor = SPSAChannel( - self.hparams.dsp_sample_rate, - self.hparams.spsa_parallel, - self.hparams.batch_size, - ) - elif self.hparams.processor_model == "autodiff": - self.processor = AutodiffChannel(self.hparams.dsp_sample_rate) - elif self.hparams.processor_model == "proxy0": - # print('self.hparams.proxy_ckpts,',self.hparams.proxy_ckpts) - self.hparams.dsp_mode = DSPMode.NONE - self.processor = ProxyChannel( - self.hparams.proxy_ckpts, - self.hparams.freeze_proxies, - self.hparams.dsp_mode, - sample_rate=self.hparams.dsp_sample_rate, - ) - elif self.hparams.processor_model == "proxy1": - # print('self.hparams.proxy_ckpts,',self.hparams.proxy_ckpts) - self.hparams.dsp_mode = DSPMode.INFER - self.processor = ProxyChannel( - self.hparams.proxy_ckpts, - self.hparams.freeze_proxies, - self.hparams.dsp_mode, - sample_rate=self.hparams.dsp_sample_rate, - ) - elif self.hparams.processor_model == "proxy2": - # print('self.hparams.proxy_ckpts,',self.hparams.proxy_ckpts) - self.hparams.dsp_mode = DSPMode.TRAIN_INFER - self.processor = ProxyChannel( - self.hparams.proxy_ckpts, - self.hparams.freeze_proxies, - self.hparams.dsp_mode, - sample_rate=self.hparams.dsp_sample_rate, - ) - elif self.hparams.processor_model == "tcn1": - # self.processor = ConditionalTCN(self.hparams.sample_rate) - self.hparams.dsp_mode = DSPMode.NONE - self.processor = ProxyChannel( - [], - freeze_proxies=False, - dsp_mode=self.hparams.dsp_mode, - tcn_nblocks=self.hparams.tcn_nblocks, - tcn_dilation_growth=self.hparams.tcn_dilation_growth, - tcn_channel_width=self.hparams.tcn_channel_width, - tcn_kernel_size=self.hparams.tcn_kernel_size, - num_tcns=1, - sample_rate=self.hparams.sample_rate, - ) - elif self.hparams.processor_model == "tcn2": - self.hparams.dsp_mode = DSPMode.NONE - self.processor = ProxyChannel( - [], - freeze_proxies=False, - dsp_mode=self.hparams.dsp_mode, - tcn_nblocks=self.hparams.tcn_nblocks, - tcn_dilation_growth=self.hparams.tcn_dilation_growth, - tcn_channel_width=self.hparams.tcn_channel_width, - tcn_kernel_size=self.hparams.tcn_kernel_size, - num_tcns=2, - sample_rate=self.hparams.sample_rate, - ) - else: - raise ValueError(f"Invalid processor_model: {self.hparams.processor_model}") - - if self.hparams.encoder_ckpt is not None: - # load encoder weights from a pre-trained system - system = System.load_from_checkpoint(self.hparams.encoder_ckpt) - self.encoder = system.encoder - self.hparams.encoder_embed_dim = system.encoder.embed_dim - else: - self.encoder = SpectralEncoder( - self.processor.num_control_params, - self.hparams.sample_rate, - encoder_model=self.hparams.encoder_model, - embed_dim=self.hparams.encoder_embed_dim, - width_mult=self.hparams.encoder_width_mult, - ) - - if self.hparams.encoder_freeze: - for param in self.encoder.parameters(): - param.requires_grad = False - - self.controller = StyleTransferController( - self.processor.num_control_params, - self.hparams.encoder_embed_dim, - ) - - if len(self.hparams.recon_losses) != len(self.hparams.recon_loss_weights): - raise ValueError("Must supply same number of weights as losses.") - - self.recon_losses = torch.nn.ModuleDict() - for recon_loss in self.hparams.recon_losses: - if recon_loss == "mrstft": - self.recon_losses[recon_loss] = auraloss.freq.MultiResolutionSTFTLoss( - fft_sizes=[32, 128, 512, 2048, 8192, 32768], - hop_sizes=[16, 64, 256, 1024, 4096, 16384], - win_lengths=[32, 128, 512, 2048, 8192, 32768], - w_sc=0.0, - w_phs=0.0, - w_lin_mag=1.0, - w_log_mag=1.0, - ) - elif recon_loss == "mrstft-md": - self.recon_losses[recon_loss] = auraloss.freq.MultiResolutionSTFTLoss( - fft_sizes=[128, 512, 2048, 8192], - hop_sizes=[32, 128, 512, 2048], # 1 / 4 - win_lengths=[128, 512, 2048, 8192], - w_sc=0.0, - w_phs=0.0, - w_lin_mag=1.0, - w_log_mag=1.0, - ) - elif recon_loss == "mrstft-sm": - self.recon_losses[recon_loss] = auraloss.freq.MultiResolutionSTFTLoss( - fft_sizes=[512, 2048, 8192], - hop_sizes=[256, 1024, 4096], # 1 / 4 - win_lengths=[512, 2048, 8192], - w_sc=0.0, - w_phs=0.0, - w_lin_mag=1.0, - w_log_mag=1.0, - ) - elif recon_loss == "melfft": - self.recon_losses[recon_loss] = auraloss.freq.MelSTFTLoss( - self.hparams.sample_rate, - fft_size=self.hparams.train_length, - hop_size=self.hparams.train_length // 2, - win_length=self.hparams.train_length, - n_mels=128, - w_sc=0.0, - device="cuda" if self.hparams.gpus > 0 else "cpu", - ) - elif recon_loss == "melstft": - self.recon_losses[recon_loss] = auraloss.freq.MelSTFTLoss( - self.hparams.sample_rate, - device="cuda" if self.hparams.gpus > 0 else "cpu", - ) - elif recon_loss == "l1": - self.recon_losses[recon_loss] = torch.nn.L1Loss() - elif recon_loss == "sisdr": - self.recon_losses[recon_loss] = auraloss.time.SISDRLoss() - else: - raise ValueError( - f"Invalid reconstruction loss: {self.hparams.recon_losses}" - ) - - def forward( - self, - x: torch.Tensor, - y: torch.Tensor = None, - e_y: torch.Tensor = None, - z: torch.Tensor = None, - dsp_mode: DSPMode = DSPMode.NONE, - analysis_length: int = 0, - sample_rate: int = 24000, - ): - """Forward pass through the system subnetworks. - - Args: - x (tensor): Input audio tensor with shape (batch x 1 x samples) - y (tensor): Target audio tensor with shape (batch x 1 x samples) - e_y (tensor): Target embedding with shape (batch x edim) - z (tensor): Bottleneck latent. - dsp_mode (DSPMode): Mode of operation for the DSP blocks. - analysis_length (optional, int): Only analyze the first N samples. - sample_rate (optional, int): Desired sampling rate for the DSP blocks. - - You must supply target audio `y`, `z`, or an embedding for the target `e_y`. - - Returns: - y_hat (tensor): Output audio. - p (tensor): - e (tensor): - - """ - bs, chs, samp = x.size() - - if sample_rate != self.hparams.sample_rate: - x_enc = torchaudio.transforms.Resample( - sample_rate, self.hparams.sample_rate - ).to(x.device)(x) - if y is not None: - y_enc = torchaudio.transforms.Resample( - sample_rate, self.hparams.sample_rate - ).to(x.device)(y) - else: - x_enc = x - y_enc = y - - if analysis_length > 0: - x_enc = x_enc[..., :analysis_length] - if y is not None: - y_enc = y_enc[..., :analysis_length] - - e_x = self.encoder(x_enc) # generate latent embedding for input - - if y is not None: - e_y = self.encoder(y_enc) # generate latent embedding for target - elif e_y is None: - raise RuntimeError("Must supply y, z, or e_y. None supplied.") - - # learnable comparision - p = self.controller(e_x, e_y, z=z) - - # process audio conditioned on parameters - # if there are multiple channels process them using same parameters - y_hat = torch.zeros(x.shape).type_as(x) - for ch_idx in range(chs): - y_hat_ch = self.processor( - x[:, ch_idx : ch_idx + 1, :], - p, - epsilon=self.eps_scheduler.epsilon, - dsp_mode=dsp_mode, - sample_rate=sample_rate, - ) - y_hat[:, ch_idx : ch_idx + 1, :] = y_hat_ch - - return y_hat, p, e_x - - def common_paired_step( - self, - batch: Tuple, - batch_idx: int, - optimizer_idx: int = 0, - train: bool = False, - ): - """Model step used for validation and training. - - Args: - batch (Tuple[Tensor, Tensor]): Batch items containing input audio (x) and target audio (y). - batch_idx (int): Index of the batch within the current epoch. - optimizer_idx (int): Index of the optimizer, this step is called once for each optimizer. - The firs optimizer corresponds to the generator and the second optimizer, - corresponds to the adversarial loss (when in use). - train (bool): Whether step is called during training (True) or validation (False). - """ - x, y = batch - loss = 0 - dsp_mode = self.hparams.dsp_mode - - if train and dsp_mode.INFER.name == DSPMode.INFER.name: - dsp_mode = DSPMode.NONE - - # proces input audio through model - if self.hparams.style_transfer: - length = x.shape[-1] - - x_A = x[..., : length // 2] - x_B = x[..., length // 2 :] - - y_A = y[..., : length // 2] - y_B = y[..., length // 2 :] - - if torch.rand(1).sum() > 0.5: - y_ref = y_B - y = y_A - x = x_A - else: - y_ref = y_A - y = y_B - x = x_B - - y_hat, p, e = self(x, y=y_ref, dsp_mode=dsp_mode) - else: - y_ref = None - y_hat, p, e = self(x, dsp_mode=dsp_mode) - - # compute reconstruction loss terms - for loss_idx, (loss_name, recon_loss_fn) in enumerate( - self.recon_losses.items() - ): - temp_loss = recon_loss_fn(y_hat, y) # reconstruction loss - loss += float(self.hparams.recon_loss_weights[loss_idx]) * temp_loss - - self.log( - ("train" if train else "val") + f"_loss/{loss_name}", - temp_loss, - on_step=True, - on_epoch=True, - prog_bar=False, - logger=True, - sync_dist=True, - ) - - # log the overall aggregate loss - self.log( - ("train" if train else "val") + "_loss/loss", - loss, - on_step=True, - on_epoch=True, - prog_bar=False, - logger=True, - sync_dist=True, - ) - - # store audio data - data_dict = { - "x": x.cpu(), - "y": y.cpu(), - "p": p.cpu(), - "e": e.cpu(), - "y_hat": y_hat.cpu(), - } - - if y_ref is not None: - data_dict["y_ref"] = y_ref.cpu() - - return loss, data_dict - - def training_step(self, batch, batch_idx, optimizer_idx=0): - loss, _ = self.common_paired_step( - batch, - batch_idx, - optimizer_idx, - train=True, - ) - - return loss - - def training_epoch_end(self, training_step_outputs): - if self.hparams.spsa_schedule and self.hparams.processor_model == "spsa": - self.eps_scheduler.step( - self.trainer.callback_metrics[self.hparams.train_monitor], - ) - - def validation_step(self, batch, batch_idx): - loss, data_dict = self.common_paired_step(batch, batch_idx) - - return data_dict - - def optimizer_step( - self, - epoch, - batch_idx, - optimizer, - optimizer_idx, - optimizer_closure, - on_tpu=False, - using_native_amp=False, - using_lbfgs=False, - ): - if optimizer_idx == 0: - optimizer.step(closure=optimizer_closure) - - def configure_optimizers(self): - # we need additional optimizer for the discriminator - optimizers = [] - g_optimizer = torch.optim.Adam( - chain( - self.encoder.parameters(), - self.processor.parameters(), - self.controller.parameters(), - ), - lr=self.hparams.lr, - betas=(0.9, 0.999), - ) - optimizers.append(g_optimizer) - - g_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( - g_optimizer, - patience=self.hparams.lr_patience, - verbose=True, - ) - ms1 = int(self.hparams.max_epochs * 0.8) - ms2 = int(self.hparams.max_epochs * 0.95) - print( - "Learning rate schedule:", - f"0 {self.hparams.lr:0.2e} -> ", - f"{ms1} {self.hparams.lr*0.1:0.2e} -> ", - f"{ms2} {self.hparams.lr*0.01:0.2e}", - ) - g_scheduler = torch.optim.lr_scheduler.MultiStepLR( - g_optimizer, - milestones=[ms1, ms2], - gamma=0.1, - ) - - lr_schedulers = { - "scheduler": g_scheduler, - } - - return optimizers, lr_schedulers - - def train_dataloader(self): - - train_dataset = AudioDataset( - self.hparams.audio_dir, - subset="train", - train_frac=self.hparams.train_frac, - half=self.hparams.half, - length=self.hparams.train_length, - input_dirs=self.hparams.input_dirs, - random_scale_input=self.hparams.random_scale_input, - random_scale_target=self.hparams.random_scale_target, - buffer_size_gb=self.hparams.buffer_size_gb, - buffer_reload_rate=self.hparams.buffer_reload_rate, - num_examples_per_epoch=self.hparams.train_examples_per_epoch, - augmentations={ - "pitch": {"sr": self.hparams.sample_rate}, - "tempo": {"sr": self.hparams.sample_rate}, - }, - freq_corrupt=self.hparams.freq_corrupt, - drc_corrupt=self.hparams.drc_corrupt, - ext=self.hparams.ext, - ) - - g = torch.Generator() - g.manual_seed(0) - - return torch.utils.data.DataLoader( - train_dataset, - num_workers=self.hparams.num_workers, - batch_size=self.hparams.batch_size, - worker_init_fn=utils.seed_worker, - generator=g, - pin_memory=True, - persistent_workers=True, - timeout=60, - ) - - def val_dataloader(self): - - val_dataset = AudioDataset( - self.hparams.audio_dir, - subset="val", - half=self.hparams.half, - train_frac=self.hparams.train_frac, - length=self.hparams.val_length, - input_dirs=self.hparams.input_dirs, - buffer_size_gb=self.hparams.buffer_size_gb, - buffer_reload_rate=self.hparams.buffer_reload_rate, - random_scale_input=self.hparams.random_scale_input, - random_scale_target=self.hparams.random_scale_target, - num_examples_per_epoch=self.hparams.val_examples_per_epoch, - augmentations={}, - freq_corrupt=self.hparams.freq_corrupt, - drc_corrupt=self.hparams.drc_corrupt, - ext=self.hparams.ext, - ) - - self.val_dataset = val_dataset - - g = torch.Generator() - g.manual_seed(0) - - return torch.utils.data.DataLoader( - val_dataset, - num_workers=1, - batch_size=self.hparams.batch_size, - worker_init_fn=utils.seed_worker, - generator=g, - pin_memory=True, - persistent_workers=True, - timeout=60, - ) - def shutdown(self): - del self.processor - - # add any model hyperparameters here - @staticmethod - def add_model_specific_args(parent_parser): - parser = ArgumentParser(parents=[parent_parser], add_help=False) - # --- Training --- - parser.add_argument("--batch_size", type=int, default=32) - parser.add_argument("--lr", type=float, default=3e-4) - parser.add_argument("--lr_patience", type=int, default=20) - parser.add_argument("--recon_losses", nargs="+", default=["l1"]) - parser.add_argument("--recon_loss_weights", nargs="+", default=[1.0]) - # --- Controller --- - parser.add_argument( - "--processor_model", - type=str, - help="autodiff, spsa, tcn1, tcn2, proxy0, proxy1, proxy2", - ) - parser.add_argument("--controller_hidden_dim", type=int, default=256) - parser.add_argument("--style_transfer", action="store_true") - # --- Encoder --- - parser.add_argument("--encoder_model", type=str, default="mobilenet_v2") - parser.add_argument("--encoder_embed_dim", type=int, default=128) - parser.add_argument("--encoder_width_mult", type=int, default=2) - parser.add_argument("--encoder_ckpt", type=str, default=None) - parser.add_argument("--encoder_freeze", action="store_true", default=False) - # --- TCN --- - parser.add_argument("--tcn_causal", action="store_true") - parser.add_argument("--tcn_nblocks", type=int, default=4) - parser.add_argument("--tcn_dilation_growth", type=int, default=8) - parser.add_argument("--tcn_channel_width", type=int, default=32) - parser.add_argument("--tcn_kernel_size", type=int, default=13) - # --- SPSA --- - parser.add_argument("--plugin_config_file", type=str, default=None) - parser.add_argument("--spsa_epsilon", type=float, default=0.001) - parser.add_argument("--spsa_schedule", action="store_true") - parser.add_argument("--spsa_patience", type=int, default=10) - parser.add_argument("--spsa_verbose", action="store_true") - parser.add_argument("--spsa_factor", type=float, default=0.5) - parser.add_argument("--spsa_parallel", action="store_true") - # --- Proxy ---- - parser.add_argument("--proxy_ckpts", nargs="+") - parser.add_argument("--freeze_proxies", action="store_true", default=False) - parser.add_argument("--use_dsp", action="store_true", default=False) - parser.add_argument("--dsp_mode", choices=DSPMode, type=DSPMode) - # --- Dataset --- - parser.add_argument("--audio_dir", type=str) - parser.add_argument("--ext", type=str, default="wav") - parser.add_argument("--input_dirs", nargs="+") - parser.add_argument("--buffer_reload_rate", type=int, default=1000) - parser.add_argument("--buffer_size_gb", type=float, default=1.0) - parser.add_argument("--sample_rate", type=int, default=24000) - parser.add_argument("--dsp_sample_rate", type=int, default=24000) - parser.add_argument("--shuffle", type=bool, default=True) - parser.add_argument("--random_scale_input", action="store_true") - parser.add_argument("--random_scale_target", action="store_true") - parser.add_argument("--freq_corrupt", action="store_true") - parser.add_argument("--drc_corrupt", action="store_true") - parser.add_argument("--train_length", type=int, default=65536) - parser.add_argument("--train_frac", type=float, default=0.8) - parser.add_argument("--half", action="store_true") - parser.add_argument("--train_examples_per_epoch", type=int, default=10000) - parser.add_argument("--val_length", type=int, default=131072) - parser.add_argument("--val_examples_per_epoch", type=int, default=1000) - parser.add_argument("--num_workers", type=int, default=16) - - return parser diff --git a/spaces/KaygNas/cut-it/mocks/index.ts b/spaces/KaygNas/cut-it/mocks/index.ts deleted file mode 100644 index bccbe9f94b782f98031582b874b50d92c1315d77..0000000000000000000000000000000000000000 --- a/spaces/KaygNas/cut-it/mocks/index.ts +++ /dev/null @@ -1,7 +0,0 @@ -// Mock Service Worker is an API mocking library that uses Service Worker API to intercept actual requests. -// https://mswjs.io/docs/ -import { setupWorker } from 'msw'; - -import { handlers } from './handlers'; - -export const worker = setupWorker(...handlers); diff --git a/spaces/KrishnaBakshi1/YoutubeVideoSummarizer/README.md b/spaces/KrishnaBakshi1/YoutubeVideoSummarizer/README.md deleted file mode 100644 index e3a1cac07b4de72e15c1d23219e6daea1f7aaf9a..0000000000000000000000000000000000000000 --- a/spaces/KrishnaBakshi1/YoutubeVideoSummarizer/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: YoutubeVideoSummarizer -emoji: 🏢 -colorFrom: gray -colorTo: indigo -sdk: gradio -sdk_version: 3.14.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/KyanChen/RSPrompter/mmpl/models/backbones/base_backbone.py b/spaces/KyanChen/RSPrompter/mmpl/models/backbones/base_backbone.py deleted file mode 100644 index 1ed65b7bac50568b5fd9101c967be6f0f43e7ebb..0000000000000000000000000000000000000000 --- a/spaces/KyanChen/RSPrompter/mmpl/models/backbones/base_backbone.py +++ /dev/null @@ -1,31 +0,0 @@ -from abc import ABCMeta, abstractmethod -from mmengine.model import BaseModule - - -class BaseBackbone(BaseModule, metaclass=ABCMeta): - """Base backbone. - - This class defines the basic functions of a backbone. Any backbone that - inherits this class should at least define its own `forward` function. - """ - - def __init__(self, init_cfg=None): - super(BaseBackbone, self).__init__(init_cfg) - - @abstractmethod - def forward(self, x): - """Forward computation. - - Args: - x (tensor | tuple[tensor]): x could be a Torch.tensor or a tuple of - Torch.tensor, containing input data for forward computation. - """ - pass - - def train(self, mode=True): - """Set module status before forward computation. - - Args: - mode (bool): Whether it is train_mode or test_mode - """ - super(BaseBackbone, self).train(mode) diff --git a/spaces/LDJA/iris/app/templates/index_exemple.html b/spaces/LDJA/iris/app/templates/index_exemple.html deleted file mode 100644 index 382cb2e40634ccacf8b534c576cbe5879da1bf95..0000000000000000000000000000000000000000 --- a/spaces/LDJA/iris/app/templates/index_exemple.html +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - VIVADATA | Profile - - - - - - - - - - - -
-
-

VIVADATA - Flask Demo

-
- -
-

Hello {{mon_nom}} 👋🙋🕺

-

This is your custom page

- -
- -
-

© Vivadata 2023

-
- -
- - diff --git a/spaces/LamaAl/chatbot/app.py b/spaces/LamaAl/chatbot/app.py deleted file mode 100644 index 1341c91405966065b5d5dd0e0ed5da8c0141f0ff..0000000000000000000000000000000000000000 --- a/spaces/LamaAl/chatbot/app.py +++ /dev/null @@ -1,38 +0,0 @@ -import streamlit as st -from streamlit_chat import message as st_message -from transformers import BlenderbotTokenizer -from transformers import BlenderbotForConditionalGeneration - - -@st.experimental_singleton -def get_models(): - # pytorch keeps an internal state of the conversation - model_name = "facebook/blenderbot-400M-distill" - tokenizer = BlenderbotTokenizer.from_pretrained(model_name) - model = BlenderbotForConditionalGeneration.from_pretrained(model_name) - return tokenizer, model - - -if "history" not in st.session_state: - st.session_state.history = [] - -st.title("Hello Chatbot") - - -def generate_answer(): - tokenizer, model = get_models() - user_message = st.session_state.input_text - inputs = tokenizer(st.session_state.input_text, return_tensors="pt") - result = model.generate(**inputs) - message_bot = tokenizer.decode( - result[0], skip_special_tokens=True - ) # .replace("", "").replace("", "") - - st.session_state.history.append({"message": user_message, "is_user": True}) - st.session_state.history.append({"message": message_bot, "is_user": False}) - - -st.text_input("Talk to the bot", key="input_text", on_change=generate_answer) - -for chat in st.session_state.history: - st_message(**chat) # unpacking \ No newline at end of file diff --git a/spaces/LandonBurlingham/04GR-StoryGen-Memory/app.py b/spaces/LandonBurlingham/04GR-StoryGen-Memory/app.py deleted file mode 100644 index 087bdd6afad343607b5b1838d7f9c86943f38f57..0000000000000000000000000000000000000000 --- a/spaces/LandonBurlingham/04GR-StoryGen-Memory/app.py +++ /dev/null @@ -1,99 +0,0 @@ -import gradio as gr -import os - -# PersistDataset ----- -import os -import csv -import gradio as gr -from gradio import inputs, outputs -import huggingface_hub -from huggingface_hub import Repository, hf_hub_download, upload_file -from datetime import datetime - -# created new dataset as awacke1/MindfulStory.csv -DATASET_REPO_URL = "https://huggingface.co/datasets/awacke1/MindfulStory.csv" -DATASET_REPO_ID = "awacke1/MindfulStory.csv" -DATA_FILENAME = "MindfulStory.csv" -DATA_FILE = os.path.join("data", DATA_FILENAME) -HF_TOKEN = os.environ.get("HF_TOKEN") -# Download dataset repo using hub download -try: - hf_hub_download( - repo_id=DATASET_REPO_ID, - filename=DATA_FILENAME, - cache_dir=DATA_DIRNAME, - force_filename=DATA_FILENAME - ) -except: - print("file not found") - -def AIMemory(title: str, story: str): - if title and story: - with open(DATA_FILE, "a") as csvfile: - writer = csv.DictWriter(csvfile, fieldnames=["title", "story", "time"]) - writer.writerow({"title": title, "story": story, "time": str(datetime.now())}) - commit_url = repo.push_to_hub() - return "" - - -# Set up cloned dataset from repo for operations -repo = Repository( - local_dir="data", clone_from=DATASET_REPO_URL, use_auth_token=HF_TOKEN -) - -#generator1 = gr.Interface.load("bigscience/bloom", api_key=HF_TOKEN) - - -generator1 = gr.Interface.load("huggingface/gpt2-large", api_key=HF_TOKEN) -generator2 = gr.Interface.load("huggingface/EleutherAI/gpt-neo-2.7B", api_key=HF_TOKEN) -generator3 = gr.Interface.load("huggingface/EleutherAI/gpt-j-6B", api_key=HF_TOKEN) - - -def calculator(intro, operator, outro): - if operator == "add": - output = generator2(intro) + generator3(outro) - title = intro + " " + outro - saved = AIMemory(title, output) - return output - elif operator == "subtract": - output = generator2(outro) + generator3(intro) - title = outro + " " + intro - saved = AIMemory(title, output) - output = output.replace(intro, "").replace(outro, "") - return output - elif operator == "multiply": - output = generator1(intro) + generator2(outro) + generator3(intro) - title = intro + " " + outro + " " + intro - saved = AIMemory(title, output) - return output - elif operator == "divide": - output = generator1(outro) + generator2(intro) + generator3(outro) - title = outro + " " + intro + " " + outro - saved = AIMemory(title, output) - output = output.replace(intro, "").replace(outro, "") - return output - -#with open('Mindfulness.txt', 'r') as file: -# context = file.read() -#contextBox = gr.Textbox(lines=3, default=context, label="Story starter") -#Two space marines named Liev Schreiber and Will Sasso take up arms to save the planet from an alien invasion. These two dashing strong men play a comedic role in the science fiction movie of the future where even barnaby bunny is willing to join their wacky gang of space marines to save the planet with good looks and comedy. - -examples = [ - ["Two space marines take up arms to save the planet from an alien invasion.", "multiply", "These two dashing strong actors play a comedic role in the science fiction movie of the future"], - ["These two dashing strong actors play a comedic role in the science fiction movie of the future", "add", "Barnaby bunny is willing to join their wacky gang of space marines"], - ["to save the planet with good looks and comedy", "add", "Two space marines become best friends as they assist with saving the world from the alien invasion"] -] - -demo = gr.Interface( - calculator, - [ - "text", - gr.Radio(["add", "subtract", "multiply", "divide"]), - "text" - ], - "text", - examples=examples, - article="Saved story memory dataset: https://huggingface.co/datasets/awacke1/MindfulStory.csv with available models to use from text gen: https://huggingface.co/models?pipeline_tag=text-generation&sort=downloads", - live=True, -) -demo.launch() \ No newline at end of file diff --git a/spaces/LaynzKunz/Aesthetic_RVC_Inference_HF/lib/infer/infer_libs/uvr5_pack/demucs/wav.py b/spaces/LaynzKunz/Aesthetic_RVC_Inference_HF/lib/infer/infer_libs/uvr5_pack/demucs/wav.py deleted file mode 100644 index a65c3b2ba5aacb1fcab3753f1f85ff7b8db7fc11..0000000000000000000000000000000000000000 --- a/spaces/LaynzKunz/Aesthetic_RVC_Inference_HF/lib/infer/infer_libs/uvr5_pack/demucs/wav.py +++ /dev/null @@ -1,174 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -from collections import OrderedDict -import hashlib -import math -import json -from pathlib import Path - -import julius -import torch as th -from torch import distributed -import torchaudio as ta -from torch.nn import functional as F - -from .audio import convert_audio_channels -from .compressed import get_musdb_tracks - -MIXTURE = "mixture" -EXT = ".wav" - - -def _track_metadata(track, sources): - track_length = None - track_samplerate = None - for source in sources + [MIXTURE]: - file = track / f"{source}{EXT}" - info = ta.info(str(file)) - length = info.num_frames - if track_length is None: - track_length = length - track_samplerate = info.sample_rate - elif track_length != length: - raise ValueError( - f"Invalid length for file {file}: " - f"expecting {track_length} but got {length}.") - elif info.sample_rate != track_samplerate: - raise ValueError( - f"Invalid sample rate for file {file}: " - f"expecting {track_samplerate} but got {info.sample_rate}.") - if source == MIXTURE: - wav, _ = ta.load(str(file)) - wav = wav.mean(0) - mean = wav.mean().item() - std = wav.std().item() - - return {"length": length, "mean": mean, "std": std, "samplerate": track_samplerate} - - -def _build_metadata(path, sources): - meta = {} - path = Path(path) - for file in path.iterdir(): - meta[file.name] = _track_metadata(file, sources) - return meta - - -class Wavset: - def __init__( - self, - root, metadata, sources, - length=None, stride=None, normalize=True, - samplerate=44100, channels=2): - """ - Waveset (or mp3 set for that matter). Can be used to train - with arbitrary sources. Each track should be one folder inside of `path`. - The folder should contain files named `{source}.{ext}`. - Files will be grouped according to `sources` (each source is a list of - filenames). - - Sample rate and channels will be converted on the fly. - - `length` is the sample size to extract (in samples, not duration). - `stride` is how many samples to move by between each example. - """ - self.root = Path(root) - self.metadata = OrderedDict(metadata) - self.length = length - self.stride = stride or length - self.normalize = normalize - self.sources = sources - self.channels = channels - self.samplerate = samplerate - self.num_examples = [] - for name, meta in self.metadata.items(): - track_length = int(self.samplerate * meta['length'] / meta['samplerate']) - if length is None or track_length < length: - examples = 1 - else: - examples = int(math.ceil((track_length - self.length) / self.stride) + 1) - self.num_examples.append(examples) - - def __len__(self): - return sum(self.num_examples) - - def get_file(self, name, source): - return self.root / name / f"{source}{EXT}" - - def __getitem__(self, index): - for name, examples in zip(self.metadata, self.num_examples): - if index >= examples: - index -= examples - continue - meta = self.metadata[name] - num_frames = -1 - offset = 0 - if self.length is not None: - offset = int(math.ceil( - meta['samplerate'] * self.stride * index / self.samplerate)) - num_frames = int(math.ceil( - meta['samplerate'] * self.length / self.samplerate)) - wavs = [] - for source in self.sources: - file = self.get_file(name, source) - wav, _ = ta.load(str(file), frame_offset=offset, num_frames=num_frames) - wav = convert_audio_channels(wav, self.channels) - wavs.append(wav) - - example = th.stack(wavs) - example = julius.resample_frac(example, meta['samplerate'], self.samplerate) - if self.normalize: - example = (example - meta['mean']) / meta['std'] - if self.length: - example = example[..., :self.length] - example = F.pad(example, (0, self.length - example.shape[-1])) - return example - - -def get_wav_datasets(args, samples, sources): - sig = hashlib.sha1(str(args.wav).encode()).hexdigest()[:8] - metadata_file = args.metadata / (sig + ".json") - train_path = args.wav / "train" - valid_path = args.wav / "valid" - if not metadata_file.is_file() and args.rank == 0: - train = _build_metadata(train_path, sources) - valid = _build_metadata(valid_path, sources) - json.dump([train, valid], open(metadata_file, "w")) - if args.world_size > 1: - distributed.barrier() - train, valid = json.load(open(metadata_file)) - train_set = Wavset(train_path, train, sources, - length=samples, stride=args.data_stride, - samplerate=args.samplerate, channels=args.audio_channels, - normalize=args.norm_wav) - valid_set = Wavset(valid_path, valid, [MIXTURE] + sources, - samplerate=args.samplerate, channels=args.audio_channels, - normalize=args.norm_wav) - return train_set, valid_set - - -def get_musdb_wav_datasets(args, samples, sources): - metadata_file = args.metadata / "musdb_wav.json" - root = args.musdb / "train" - if not metadata_file.is_file() and args.rank == 0: - metadata = _build_metadata(root, sources) - json.dump(metadata, open(metadata_file, "w")) - if args.world_size > 1: - distributed.barrier() - metadata = json.load(open(metadata_file)) - - train_tracks = get_musdb_tracks(args.musdb, is_wav=True, subsets=["train"], split="train") - metadata_train = {name: meta for name, meta in metadata.items() if name in train_tracks} - metadata_valid = {name: meta for name, meta in metadata.items() if name not in train_tracks} - train_set = Wavset(root, metadata_train, sources, - length=samples, stride=args.data_stride, - samplerate=args.samplerate, channels=args.audio_channels, - normalize=args.norm_wav) - valid_set = Wavset(root, metadata_valid, [MIXTURE] + sources, - samplerate=args.samplerate, channels=args.audio_channels, - normalize=args.norm_wav) - return train_set, valid_set diff --git a/spaces/LecJackS/wolfram-alpha-query/wolfram_alpha_tool.py b/spaces/LecJackS/wolfram-alpha-query/wolfram_alpha_tool.py deleted file mode 100644 index 28141ce1cb51ad16c435c907043399e1b4a2f076..0000000000000000000000000000000000000000 --- a/spaces/LecJackS/wolfram-alpha-query/wolfram_alpha_tool.py +++ /dev/null @@ -1,62 +0,0 @@ -import os -import requests -from transformers import Tool - -class WolframAlpha(Tool): - name = "wolfram_alpha" - description = ("This is a tool that uses WolframAlpha to compute any mathematical query. It takes one input query, and returns a verbose result in xml format, which includes the solution.") - - inputs = ["query"] - outputs = ["result"] - - def __init__(self, *args, **kwargs): - self.base_url = 'http://api.wolframalpha.com/v2/query' - - self.app_id = os.environ.get('WOLFRAM_APP_ID') - if self.app_id is None: - raise ValueError("Please set the `WOLFRAM_APP_ID` as an environment variable in order to instantiate the Wolfram tool.\nTo do so, before instantiating the class, run:\nos.environ['WOLFRAM_APP_ID'] = 'YOUR_WOLFRAM_APP_ID'") - - print("Making sure APP_ID is valid... ", end="") - dummy_params = { - 'input': '1+1', - 'output': 'xml', - 'appid': self.app_id, - } - response = self.make_request(params=dummy_params) - if "Invalid appid" in response: - appid_url = 'https://developer.wolframalpha.com/portal/myapps/index.html' - raise ValueError(f"Please set a valid `WOLFRAM_APP_ID` as an environment variable.\nWolframAlpha is not validating APP_ID: {self.app_id}\nTo get an APP_ID, go to:\n{appid_url}\nand click on [Get an AppID]") - print("APP_ID validated! Tool ready to use.") - - def __call__(self, query, output='xml', pod_format='plaintext'): - - - output_opts = ['xml','json'] - format_opts = ['plaintext', 'image', 'image,imagemap', 'mathml', 'sound', 'wav'] - - if output not in output_opts: - return f"{output} is not a correct output parameter! It must be one of these: {output_opts}" - - if pod_format not in format_opts: - return f"{pod_format} is not a correct pod_format parameter! It must be one of these: {format_opts}" - - params = { - 'input': query, - 'output': output, - 'appid': self.app_id, - } - - response = self.make_request(params) - - return response - - def make_request(self, params): - response = requests.get(self.base_url, params=params) - if response.status_code == 200: - if params['output'] == 'xml': - return response.text - elif params['output'] == 'json': - # Remove unnecessary empty spaces - return str(response.json()) - else: - return f"There was an error with the request, with response: {response}" \ No newline at end of file diff --git a/spaces/MRroboto/Loacker_app/postprocessing.py b/spaces/MRroboto/Loacker_app/postprocessing.py deleted file mode 100644 index c77745d872f708aea56c3aa50a741f5e27011af6..0000000000000000000000000000000000000000 --- a/spaces/MRroboto/Loacker_app/postprocessing.py +++ /dev/null @@ -1,148 +0,0 @@ -# should work for all apporaches (Deep learning or not) -# should work on segmentation masks -# should include a smoothing and an max-area threshold -# should try to work with the tortina circle (or maybe better estimate it again) -# maybe even to apply before thresholding, directly on anomaly maps/other outputs to have better smoothing -# output should be again a segmentation mask - -import numpy as np -import cv2 - - - - - -def get_points_in_circle(circle): - x0, y0, radius = circle.astype(np.int32) - x_ = np.arange(x0 - radius - 1, x0 + radius + 1, dtype=np.int32) - y_ = np.arange(y0 - radius - 1, y0 + radius + 1, dtype=np.int32) - x, y = np.where((x_[:,np.newaxis] - x0)**2 + (y_ - y0)**2 <= radius**2) - # for x, y in zip(x_[x], y_[y]): # yield x, y - return (x_[x], y_[y]) - - - - -def find_single_tortina_circle(image): - height, width, num_channels = image.shape - - #find the biggest circle (tortina) in the image - #init with default circle - selected_circle = np.array((width//2, height//2, int(height/2*0.9))) - try: - #circles = find_tortinas(image, 1, force_num_tortinas=True) - height, width = image.shape[:2] - if (image.ndim == 2) or (image.shape[-1] == 1): - gray = image - else: - gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) - blur = cv2.blur(gray, (7,7)) - circles = cv2.HoughCircles(blur, cv2.HOUGH_GRADIENT, 3, minDist=width//2) - if circles is None: - circles = [] - else: - circles = circles[0].astype(np.uint32) - - except: - circles = [] - - if len(circles) > 0: - max_r = 0 - for x,y,r in circles: - if r > max_r: - max_r = r - selected_circle = np.array((x,y,r)) - - return selected_circle - - - -def postprocessing(image, segmask, fat_bloom_id=1): - - if segmask.shape != image.shape[:2]: - raise ValueError( - """segmask argument should represent a segmentation mask with 2 dimensions (height, width)! - This means that its values should already be thresholded and (in case of rgb) reduced to - a single channel. - """) - - height, width = image.shape[:2] - selected_circle = find_single_tortina_circle(image) - - #debugging - #plot_image_with_circle(image, selected_circle) - - # smooth the segmask - binary = (segmask == fat_bloom_id).astype(np.uint8) - kernel = np.ones((5,5),np.uint8) - closing = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel) - opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel) - - #the opening values should overwrite the fat_bloom of the input - #segmask. Where we had fat bloom in the input but not anymore in the - #opening we need to determine whether it is backgorund or tortina. We - #can do so using the estimated circle. - - #initialize everything to background. background = 0 - new_segmask = np.zeros_like(segmask) - tortina_indices = get_points_in_circle(selected_circle) - #correction - out_of_width_0 = (tortina_indices[0] < 0) - out_of_width_1 = (tortina_indices[0] >= width) - out_of_height_0 = (tortina_indices[1] < 0) - out_of_height_1 = (tortina_indices[1] >= height) - tortina_indices[0][out_of_width_0] = 0 - tortina_indices[0][out_of_width_1] = width - 1 - tortina_indices[1][out_of_height_0] = 0 - tortina_indices[1][out_of_height_1] = height - 1 - # remove_indices = (tortina_indices[0] < 0) | (tortina_indices[0] >= height) | \ - # (tortina_indices[1] < 0) | (tortina_indices[1] >= width) - # keep_indices = np.setdiff1d(np.arange(len(tortina_indices[0])), remove_indices) - # tortina_indices = (tortina_indices[0][keep_indices], tortina_indices[1][keep_indices]) - - - is_tortina = np.zeros_like(segmask, dtype=bool) - is_tortina[tortina_indices] = True - #tortina = 1 - new_segmask[is_tortina] = 1 - #fat_bloom = 2 - new_segmask[(opening == 1) & is_tortina] = 2 - - return new_segmask - - -def final_prediction(anomaly_map, segmask): - - fat_bloom_area = np.count_nonzero(segmask == 2) - tortina_area = np.count_nonzero(segmask == 1) + fat_bloom_area - - relative_area = fat_bloom_area / tortina_area - - area = 0 - if (relative_area > 0) and (relative_area <= 0.25): - area = 1 - elif (relative_area > 0.25) and (relative_area <= 0.5): - area = 2 - elif (relative_area > 0.5) and (relative_area <= 0.75): - area = 3 - elif relative_area > 0.75: - area = 4 - - relative_intensity = 0.0 - if fat_bloom_area > 0.0: - relative_intensity = anomaly_map[segmask==2].mean() - - #TODO: intensity should be depending on colour of underlying tortina - # i.e. for a darker tortina intesity is automatically higher, - # but that should be relativiert. - intensity = 0 - if (relative_intensity > 0) and (relative_intensity <= 0.25): - intensity = 1 - elif (relative_intensity > 0.25) and (relative_intensity <= 0.5): - intensity = 2 - elif (relative_intensity > 0.5) and (relative_intensity <= 0.75): - intensity = 3 - elif relative_intensity > 0.75: - intensity = 4 - - return area, intensity \ No newline at end of file diff --git a/spaces/Manjushri/MusicGen/tests/data/test_audio_utils.py b/spaces/Manjushri/MusicGen/tests/data/test_audio_utils.py deleted file mode 100644 index 0480671bb17281d61ce02bce6373a5ccec89fece..0000000000000000000000000000000000000000 --- a/spaces/Manjushri/MusicGen/tests/data/test_audio_utils.py +++ /dev/null @@ -1,110 +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 julius -import torch -import pytest - -from audiocraft.data.audio_utils import ( - _clip_wav, - convert_audio_channels, - convert_audio, - normalize_audio -) -from ..common_utils import get_batch_white_noise - - -class TestConvertAudioChannels: - - def test_convert_audio_channels_downmix(self): - b, c, t = 2, 3, 100 - audio = get_batch_white_noise(b, c, t) - mixed = convert_audio_channels(audio, channels=2) - assert list(mixed.shape) == [b, 2, t] - - def test_convert_audio_channels_nochange(self): - b, c, t = 2, 3, 100 - audio = get_batch_white_noise(b, c, t) - mixed = convert_audio_channels(audio, channels=c) - assert list(mixed.shape) == list(audio.shape) - - def test_convert_audio_channels_upmix(self): - b, c, t = 2, 1, 100 - audio = get_batch_white_noise(b, c, t) - mixed = convert_audio_channels(audio, channels=3) - assert list(mixed.shape) == [b, 3, t] - - def test_convert_audio_channels_upmix_error(self): - b, c, t = 2, 2, 100 - audio = get_batch_white_noise(b, c, t) - with pytest.raises(ValueError): - convert_audio_channels(audio, channels=3) - - -class TestConvertAudio: - - def test_convert_audio_channels_downmix(self): - b, c, dur = 2, 3, 4. - sr = 128 - audio = get_batch_white_noise(b, c, int(sr * dur)) - out = convert_audio(audio, from_rate=sr, to_rate=sr, to_channels=2) - assert list(out.shape) == [audio.shape[0], 2, audio.shape[-1]] - - def test_convert_audio_channels_upmix(self): - b, c, dur = 2, 1, 4. - sr = 128 - audio = get_batch_white_noise(b, c, int(sr * dur)) - out = convert_audio(audio, from_rate=sr, to_rate=sr, to_channels=3) - assert list(out.shape) == [audio.shape[0], 3, audio.shape[-1]] - - def test_convert_audio_upsample(self): - b, c, dur = 2, 1, 4. - sr = 2 - new_sr = 3 - audio = get_batch_white_noise(b, c, int(sr * dur)) - out = convert_audio(audio, from_rate=sr, to_rate=new_sr, to_channels=c) - out_j = julius.resample.resample_frac(audio, old_sr=sr, new_sr=new_sr) - assert torch.allclose(out, out_j) - - def test_convert_audio_resample(self): - b, c, dur = 2, 1, 4. - sr = 3 - new_sr = 2 - audio = get_batch_white_noise(b, c, int(sr * dur)) - out = convert_audio(audio, from_rate=sr, to_rate=new_sr, to_channels=c) - out_j = julius.resample.resample_frac(audio, old_sr=sr, new_sr=new_sr) - assert torch.allclose(out, out_j) - - -class TestNormalizeAudio: - - def test_clip_wav(self): - b, c, dur = 2, 1, 4. - sr = 3 - audio = 10.0 * get_batch_white_noise(b, c, int(sr * dur)) - _clip_wav(audio) - assert audio.abs().max() <= 1 - - def test_normalize_audio_clip(self): - b, c, dur = 2, 1, 4. - sr = 3 - audio = 10.0 * get_batch_white_noise(b, c, int(sr * dur)) - norm_audio = normalize_audio(audio, strategy='clip') - assert norm_audio.abs().max() <= 1 - - def test_normalize_audio_rms(self): - b, c, dur = 2, 1, 4. - sr = 3 - audio = 10.0 * get_batch_white_noise(b, c, int(sr * dur)) - norm_audio = normalize_audio(audio, strategy='rms') - assert norm_audio.abs().max() <= 1 - - def test_normalize_audio_peak(self): - b, c, dur = 2, 1, 4. - sr = 3 - audio = 10.0 * get_batch_white_noise(b, c, int(sr * dur)) - norm_audio = normalize_audio(audio, strategy='peak') - assert norm_audio.abs().max() <= 1 diff --git a/spaces/Marshalls/testmtd/models/residualflower_model.py b/spaces/Marshalls/testmtd/models/residualflower_model.py deleted file mode 100644 index 736b0fcffc7014052382dc64bfa5d2dd4f2442db..0000000000000000000000000000000000000000 --- a/spaces/Marshalls/testmtd/models/residualflower_model.py +++ /dev/null @@ -1,155 +0,0 @@ -import torch -from torch import nn -from .transformer import BasicTransformerModel -from models import BaseModel -from models.flowplusplus import FlowPlusPlus -import ast - -from .util.generation import autoregressive_generation_multimodal -from .transformer_model import TransformerModel - -#TODO: refactor a whole bunch of stuff - -class ResidualflowerModel(BaseModel): - def __init__(self, opt): - super().__init__(opt) - self.opt = opt - input_mods = self.input_mods - output_mods = self.output_mods - input_lengths = self.input_lengths - output_lengths = self.output_lengths - dins = self.dins - douts = self.douts - if self.opt.conditioning_seq_lens is not None: - self.conditioning_seq_lens = [int(x) for x in str(self.opt.conditioning_seq_lens).split(",")] - else: - self.conditioning_seq_lens = [int(x) for x in str(self.opt.output_lengths).split(",")] - - self.input_mod_nets = [] - self.output_mod_nets = [] - self.output_mod_glows = [] - self.module_names = [] - for i, mod in enumerate(input_mods): - net = BasicTransformerModel(opt.dhid, dins[i], opt.nhead, opt.dhid, 2, opt.dropout, self.device, use_pos_emb=True, input_length=input_lengths[i]).to(self.device) - name = "_input_"+mod - setattr(self,"net"+name, net) - self.input_mod_nets.append(net) - self.module_names.append(name) - for i, mod in enumerate(output_mods): - if self.opt.cond_concat_dims: - net = BasicTransformerModel(opt.dhid, opt.dhid, opt.nhead, opt.dhid, opt.nlayers, opt.dropout, self.device, use_pos_emb=opt.use_pos_emb_output, input_length=sum(input_lengths)).to(self.device) - else: - net = BasicTransformerModel(douts[i]//2, opt.dhid, opt.nhead, opt.dhid, opt.nlayers, opt.dropout, self.device, use_pos_emb=opt.use_pos_emb_output, input_length=sum(input_lengths)).to(self.device) - name = "_output_"+mod - setattr(self, "net"+name, net) - self.output_mod_nets.append(net) - self.module_names.append(name) - - # import pdb;pdb.set_trace() - glow = FlowPlusPlus(scales=ast.literal_eval(opt.scales), - in_shape=(douts[i], output_lengths[i], 1), - cond_dim=opt.dhid, - mid_channels=opt.dhid_flow, - num_blocks=opt.num_glow_coupling_blocks, - num_components=opt.num_mixture_components, - use_attn=opt.glow_use_attn, - use_logmix=opt.num_mixture_components>0, - drop_prob=opt.dropout, - num_heads=opt.num_heads_flow, - use_transformer_nn=opt.use_transformer_nn, - use_pos_emb=opt.use_pos_emb_coupling, - norm_layer = opt.glow_norm_layer, - bn_momentum = opt.glow_bn_momentum, - cond_concat_dims=opt.cond_concat_dims, - cond_seq_len=self.conditioning_seq_lens[i], - ) - name = "_output_glow_"+mod - setattr(self, "net"+name, glow) - self.output_mod_glows.append(glow) - - self.mean_model = TransformerModel(opt) - - self.inputs = [] - self.targets = [] - self.criterion = nn.MSELoss() - - def name(self): - return "Transflower" - - @staticmethod - def modify_commandline_options(parser, opt): - parser.add_argument('--dhid', type=int, default=512) - parser.add_argument('--dhid_flow', type=int, default=512) - parser.add_argument('--predicted_inputs', default="0") - parser.add_argument('--conditioning_seq_lens', type=str, default=None, help="the number of outputs of the conditioning transformers to feed (meaning the number of elements along the sequence dimension)") - parser.add_argument('--nlayers', type=int, default=6) - parser.add_argument('--nhead', type=int, default=8) - parser.add_argument('--num_heads_flow', type=int, default=8) - parser.add_argument('--dropout', type=float, default=0.1) - parser.add_argument('--scales', type=str, default="[[10,0]]") - parser.add_argument('--glow_norm_layer', type=str, default=None) - parser.add_argument('--glow_bn_momentum', type=float, default=0.1) - parser.add_argument('--num_glow_coupling_blocks', type=int, default=10) - parser.add_argument('--num_mixture_components', type=int, default=0) - parser.add_argument('--glow_use_attn', action='store_true', help="whether to use the internal attention for the FlowPlusPLus model") - parser.add_argument('--use_transformer_nn', action='store_true', help="whether to use the internal attention for the FlowPlusPLus model") - parser.add_argument('--use_pos_emb_output', action='store_true', help="whether to use positional embeddings for output modality transformers") - parser.add_argument('--use_pos_emb_coupling', action='store_true', help="whether to use positional embeddings for the coupling layer transformers") - parser.add_argument('--cond_concat_dims', action='store_true', help="if set we concatenate along the channel dimension with with the x for the coupling layer; otherwise we concatenate along the sequence dimesion") - return parser - - def forward(self, data): - # in lightning, forward defines the prediction/inference actions - predicted_means = self.mean_model(data) - latents = [] - for i, mod in enumerate(self.input_mods): - latents.append(self.input_mod_nets[i].forward(data[i])) - latent = torch.cat(latents) - outputs = [] - for i, mod in enumerate(self.output_mods): - trans_output = self.output_mod_nets[i].forward(latent)[:self.conditioning_seq_lens[i]] - output, _ = self.output_mod_glows[i](x=None, cond=trans_output.permute(1,0,2), reverse=True) - outputs.append(predicted_means[i]+output.permute(1,0,2)) - - return outputs - - def training_step(self, batch, batch_idx): - self.set_inputs(batch) - predicted_means = self.mean_model(self.inputs) - mse_loss = 0 - for i, mod in enumerate(self.output_mods): - mse_loss += 100*self.criterion(predicted_means[i], self.targets[i]) - #print("mse_loss: ", mse_loss) - latents = [] - for i, mod in enumerate(self.input_mods): - latents.append(self.input_mod_nets[i].forward(self.inputs[i])) - - latent = torch.cat(latents) - nll_loss=0 - for i, mod in enumerate(self.output_mods): - output = self.output_mod_nets[i].forward(latent)[:self.conditioning_seq_lens[i]] - glow = self.output_mod_glows[i] - # import pdb;pdb.set_trace() - z, sldj = glow(x=self.targets[i].permute(1,0,2)-predicted_means[i].detach().permute(1,0,2), cond=output.permute(1,0,2)) #time, batch, features -> batch, time, features - #print(sldj) - n_timesteps = self.targets[i].shape[1] - nll_loss += glow.loss_generative(z, sldj) - - loss = mse_loss + nll_loss - #print("nll_loss: ", nll_loss) - self.log('mse_loss', mse_loss) - self.log('nll_loss', nll_loss) - self.log('loss', loss) - return loss - - #to help debug XLA stuff, like missing ops, or data loading/compiling bottlenecks - # see https://youtu.be/iwtpwQRdb3Y?t=1056 - # def on_epoch_end(self): - # import torch_xla.core.xla_model as xm - # import torch_xla.debug.metrics as met - # xm.master_print(met.metrics_report()) - - - #def optimizer_step(self, epoch, batch_idx, optimizer, optimizer_idx, - # optimizer_closure, on_tpu, using_native_amp, using_lbfgs): - # optimizer.zero_grad() diff --git a/spaces/Mellow-ai/PhotoAI_Mellow/annotator/midas/midas/blocks.py b/spaces/Mellow-ai/PhotoAI_Mellow/annotator/midas/midas/blocks.py deleted file mode 100644 index 2145d18fa98060a618536d9a64fe6589e9be4f78..0000000000000000000000000000000000000000 --- a/spaces/Mellow-ai/PhotoAI_Mellow/annotator/midas/midas/blocks.py +++ /dev/null @@ -1,342 +0,0 @@ -import torch -import torch.nn as nn - -from .vit import ( - _make_pretrained_vitb_rn50_384, - _make_pretrained_vitl16_384, - _make_pretrained_vitb16_384, - forward_vit, -) - -def _make_encoder(backbone, features, use_pretrained, groups=1, expand=False, exportable=True, hooks=None, use_vit_only=False, use_readout="ignore",): - if backbone == "vitl16_384": - pretrained = _make_pretrained_vitl16_384( - use_pretrained, hooks=hooks, use_readout=use_readout - ) - scratch = _make_scratch( - [256, 512, 1024, 1024], features, groups=groups, expand=expand - ) # ViT-L/16 - 85.0% Top1 (backbone) - elif backbone == "vitb_rn50_384": - pretrained = _make_pretrained_vitb_rn50_384( - use_pretrained, - hooks=hooks, - use_vit_only=use_vit_only, - use_readout=use_readout, - ) - scratch = _make_scratch( - [256, 512, 768, 768], features, groups=groups, expand=expand - ) # ViT-H/16 - 85.0% Top1 (backbone) - elif backbone == "vitb16_384": - pretrained = _make_pretrained_vitb16_384( - use_pretrained, hooks=hooks, use_readout=use_readout - ) - scratch = _make_scratch( - [96, 192, 384, 768], features, groups=groups, expand=expand - ) # ViT-B/16 - 84.6% Top1 (backbone) - elif backbone == "resnext101_wsl": - pretrained = _make_pretrained_resnext101_wsl(use_pretrained) - scratch = _make_scratch([256, 512, 1024, 2048], features, groups=groups, expand=expand) # efficientnet_lite3 - elif backbone == "efficientnet_lite3": - pretrained = _make_pretrained_efficientnet_lite3(use_pretrained, exportable=exportable) - scratch = _make_scratch([32, 48, 136, 384], features, groups=groups, expand=expand) # efficientnet_lite3 - else: - print(f"Backbone '{backbone}' not implemented") - assert False - - return pretrained, scratch - - -def _make_scratch(in_shape, out_shape, groups=1, expand=False): - scratch = nn.Module() - - out_shape1 = out_shape - out_shape2 = out_shape - out_shape3 = out_shape - out_shape4 = out_shape - if expand==True: - out_shape1 = out_shape - out_shape2 = out_shape*2 - out_shape3 = out_shape*4 - out_shape4 = out_shape*8 - - scratch.layer1_rn = nn.Conv2d( - in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups - ) - scratch.layer2_rn = nn.Conv2d( - in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups - ) - scratch.layer3_rn = nn.Conv2d( - in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups - ) - scratch.layer4_rn = nn.Conv2d( - in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups - ) - - return scratch - - -def _make_pretrained_efficientnet_lite3(use_pretrained, exportable=False): - efficientnet = torch.hub.load( - "rwightman/gen-efficientnet-pytorch", - "tf_efficientnet_lite3", - pretrained=use_pretrained, - exportable=exportable - ) - return _make_efficientnet_backbone(efficientnet) - - -def _make_efficientnet_backbone(effnet): - pretrained = nn.Module() - - pretrained.layer1 = nn.Sequential( - effnet.conv_stem, effnet.bn1, effnet.act1, *effnet.blocks[0:2] - ) - pretrained.layer2 = nn.Sequential(*effnet.blocks[2:3]) - pretrained.layer3 = nn.Sequential(*effnet.blocks[3:5]) - pretrained.layer4 = nn.Sequential(*effnet.blocks[5:9]) - - return pretrained - - -def _make_resnet_backbone(resnet): - pretrained = nn.Module() - pretrained.layer1 = nn.Sequential( - resnet.conv1, resnet.bn1, resnet.relu, resnet.maxpool, resnet.layer1 - ) - - pretrained.layer2 = resnet.layer2 - pretrained.layer3 = resnet.layer3 - pretrained.layer4 = resnet.layer4 - - return pretrained - - -def _make_pretrained_resnext101_wsl(use_pretrained): - resnet = torch.hub.load("facebookresearch/WSL-Images", "resnext101_32x8d_wsl") - return _make_resnet_backbone(resnet) - - - -class Interpolate(nn.Module): - """Interpolation module. - """ - - def __init__(self, scale_factor, mode, align_corners=False): - """Init. - - Args: - scale_factor (float): scaling - mode (str): interpolation mode - """ - super(Interpolate, self).__init__() - - self.interp = nn.functional.interpolate - self.scale_factor = scale_factor - self.mode = mode - self.align_corners = align_corners - - def forward(self, x): - """Forward pass. - - Args: - x (tensor): input - - Returns: - tensor: interpolated data - """ - - x = self.interp( - x, scale_factor=self.scale_factor, mode=self.mode, align_corners=self.align_corners - ) - - return x - - -class ResidualConvUnit(nn.Module): - """Residual convolution module. - """ - - def __init__(self, features): - """Init. - - Args: - features (int): number of features - """ - super().__init__() - - self.conv1 = nn.Conv2d( - features, features, kernel_size=3, stride=1, padding=1, bias=True - ) - - self.conv2 = nn.Conv2d( - features, features, kernel_size=3, stride=1, padding=1, bias=True - ) - - self.relu = nn.ReLU(inplace=True) - - def forward(self, x): - """Forward pass. - - Args: - x (tensor): input - - Returns: - tensor: output - """ - out = self.relu(x) - out = self.conv1(out) - out = self.relu(out) - out = self.conv2(out) - - return out + x - - -class FeatureFusionBlock(nn.Module): - """Feature fusion block. - """ - - def __init__(self, features): - """Init. - - Args: - features (int): number of features - """ - super(FeatureFusionBlock, self).__init__() - - self.resConfUnit1 = ResidualConvUnit(features) - self.resConfUnit2 = ResidualConvUnit(features) - - def forward(self, *xs): - """Forward pass. - - Returns: - tensor: output - """ - output = xs[0] - - if len(xs) == 2: - output += self.resConfUnit1(xs[1]) - - output = self.resConfUnit2(output) - - output = nn.functional.interpolate( - output, scale_factor=2, mode="bilinear", align_corners=True - ) - - return output - - - - -class ResidualConvUnit_custom(nn.Module): - """Residual convolution module. - """ - - def __init__(self, features, activation, bn): - """Init. - - Args: - features (int): number of features - """ - super().__init__() - - self.bn = bn - - self.groups=1 - - self.conv1 = nn.Conv2d( - features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups - ) - - self.conv2 = nn.Conv2d( - features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups - ) - - if self.bn==True: - self.bn1 = nn.BatchNorm2d(features) - self.bn2 = nn.BatchNorm2d(features) - - self.activation = activation - - self.skip_add = nn.quantized.FloatFunctional() - - def forward(self, x): - """Forward pass. - - Args: - x (tensor): input - - Returns: - tensor: output - """ - - out = self.activation(x) - out = self.conv1(out) - if self.bn==True: - out = self.bn1(out) - - out = self.activation(out) - out = self.conv2(out) - if self.bn==True: - out = self.bn2(out) - - if self.groups > 1: - out = self.conv_merge(out) - - return self.skip_add.add(out, x) - - # return out + x - - -class FeatureFusionBlock_custom(nn.Module): - """Feature fusion block. - """ - - def __init__(self, features, activation, deconv=False, bn=False, expand=False, align_corners=True): - """Init. - - Args: - features (int): number of features - """ - super(FeatureFusionBlock_custom, self).__init__() - - self.deconv = deconv - self.align_corners = align_corners - - self.groups=1 - - self.expand = expand - out_features = features - if self.expand==True: - out_features = features//2 - - self.out_conv = nn.Conv2d(features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=1) - - self.resConfUnit1 = ResidualConvUnit_custom(features, activation, bn) - self.resConfUnit2 = ResidualConvUnit_custom(features, activation, bn) - - self.skip_add = nn.quantized.FloatFunctional() - - def forward(self, *xs): - """Forward pass. - - Returns: - tensor: output - """ - output = xs[0] - - if len(xs) == 2: - res = self.resConfUnit1(xs[1]) - output = self.skip_add.add(output, res) - # output += res - - output = self.resConfUnit2(output) - - output = nn.functional.interpolate( - output, scale_factor=2, mode="bilinear", align_corners=self.align_corners - ) - - output = self.out_conv(output) - - return output - diff --git a/spaces/Mellow-ai/PhotoAI_Mellow/annotator/uniformer/mmcv/video/optflow.py b/spaces/Mellow-ai/PhotoAI_Mellow/annotator/uniformer/mmcv/video/optflow.py deleted file mode 100644 index 84160f8d6ef9fceb5a2f89e7481593109fc1905d..0000000000000000000000000000000000000000 --- a/spaces/Mellow-ai/PhotoAI_Mellow/annotator/uniformer/mmcv/video/optflow.py +++ /dev/null @@ -1,254 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import warnings - -import cv2 -import numpy as np - -from annotator.uniformer.mmcv.arraymisc import dequantize, quantize -from annotator.uniformer.mmcv.image import imread, imwrite -from annotator.uniformer.mmcv.utils import is_str - - -def flowread(flow_or_path, quantize=False, concat_axis=0, *args, **kwargs): - """Read an optical flow map. - - Args: - flow_or_path (ndarray or str): A flow map or filepath. - quantize (bool): whether to read quantized pair, if set to True, - remaining args will be passed to :func:`dequantize_flow`. - concat_axis (int): The axis that dx and dy are concatenated, - can be either 0 or 1. Ignored if quantize is False. - - Returns: - ndarray: Optical flow represented as a (h, w, 2) numpy array - """ - if isinstance(flow_or_path, np.ndarray): - if (flow_or_path.ndim != 3) or (flow_or_path.shape[-1] != 2): - raise ValueError(f'Invalid flow with shape {flow_or_path.shape}') - return flow_or_path - elif not is_str(flow_or_path): - raise TypeError(f'"flow_or_path" must be a filename or numpy array, ' - f'not {type(flow_or_path)}') - - if not quantize: - with open(flow_or_path, 'rb') as f: - try: - header = f.read(4).decode('utf-8') - except Exception: - raise IOError(f'Invalid flow file: {flow_or_path}') - else: - if header != 'PIEH': - raise IOError(f'Invalid flow file: {flow_or_path}, ' - 'header does not contain PIEH') - - w = np.fromfile(f, np.int32, 1).squeeze() - h = np.fromfile(f, np.int32, 1).squeeze() - flow = np.fromfile(f, np.float32, w * h * 2).reshape((h, w, 2)) - else: - assert concat_axis in [0, 1] - cat_flow = imread(flow_or_path, flag='unchanged') - if cat_flow.ndim != 2: - raise IOError( - f'{flow_or_path} is not a valid quantized flow file, ' - f'its dimension is {cat_flow.ndim}.') - assert cat_flow.shape[concat_axis] % 2 == 0 - dx, dy = np.split(cat_flow, 2, axis=concat_axis) - flow = dequantize_flow(dx, dy, *args, **kwargs) - - return flow.astype(np.float32) - - -def flowwrite(flow, filename, quantize=False, concat_axis=0, *args, **kwargs): - """Write optical flow to file. - - If the flow is not quantized, it will be saved as a .flo file losslessly, - otherwise a jpeg image which is lossy but of much smaller size. (dx and dy - will be concatenated horizontally into a single image if quantize is True.) - - Args: - flow (ndarray): (h, w, 2) array of optical flow. - filename (str): Output filepath. - quantize (bool): Whether to quantize the flow and save it to 2 jpeg - images. If set to True, remaining args will be passed to - :func:`quantize_flow`. - concat_axis (int): The axis that dx and dy are concatenated, - can be either 0 or 1. Ignored if quantize is False. - """ - if not quantize: - with open(filename, 'wb') as f: - f.write('PIEH'.encode('utf-8')) - np.array([flow.shape[1], flow.shape[0]], dtype=np.int32).tofile(f) - flow = flow.astype(np.float32) - flow.tofile(f) - f.flush() - else: - assert concat_axis in [0, 1] - dx, dy = quantize_flow(flow, *args, **kwargs) - dxdy = np.concatenate((dx, dy), axis=concat_axis) - imwrite(dxdy, filename) - - -def quantize_flow(flow, max_val=0.02, norm=True): - """Quantize flow to [0, 255]. - - After this step, the size of flow will be much smaller, and can be - dumped as jpeg images. - - Args: - flow (ndarray): (h, w, 2) array of optical flow. - max_val (float): Maximum value of flow, values beyond - [-max_val, max_val] will be truncated. - norm (bool): Whether to divide flow values by image width/height. - - Returns: - tuple[ndarray]: Quantized dx and dy. - """ - h, w, _ = flow.shape - dx = flow[..., 0] - dy = flow[..., 1] - if norm: - dx = dx / w # avoid inplace operations - dy = dy / h - # use 255 levels instead of 256 to make sure 0 is 0 after dequantization. - flow_comps = [ - quantize(d, -max_val, max_val, 255, np.uint8) for d in [dx, dy] - ] - return tuple(flow_comps) - - -def dequantize_flow(dx, dy, max_val=0.02, denorm=True): - """Recover from quantized flow. - - Args: - dx (ndarray): Quantized dx. - dy (ndarray): Quantized dy. - max_val (float): Maximum value used when quantizing. - denorm (bool): Whether to multiply flow values with width/height. - - Returns: - ndarray: Dequantized flow. - """ - assert dx.shape == dy.shape - assert dx.ndim == 2 or (dx.ndim == 3 and dx.shape[-1] == 1) - - dx, dy = [dequantize(d, -max_val, max_val, 255) for d in [dx, dy]] - - if denorm: - dx *= dx.shape[1] - dy *= dx.shape[0] - flow = np.dstack((dx, dy)) - return flow - - -def flow_warp(img, flow, filling_value=0, interpolate_mode='nearest'): - """Use flow to warp img. - - Args: - img (ndarray, float or uint8): Image to be warped. - flow (ndarray, float): Optical Flow. - filling_value (int): The missing pixels will be set with filling_value. - interpolate_mode (str): bilinear -> Bilinear Interpolation; - nearest -> Nearest Neighbor. - - Returns: - ndarray: Warped image with the same shape of img - """ - warnings.warn('This function is just for prototyping and cannot ' - 'guarantee the computational efficiency.') - assert flow.ndim == 3, 'Flow must be in 3D arrays.' - height = flow.shape[0] - width = flow.shape[1] - channels = img.shape[2] - - output = np.ones( - (height, width, channels), dtype=img.dtype) * filling_value - - grid = np.indices((height, width)).swapaxes(0, 1).swapaxes(1, 2) - dx = grid[:, :, 0] + flow[:, :, 1] - dy = grid[:, :, 1] + flow[:, :, 0] - sx = np.floor(dx).astype(int) - sy = np.floor(dy).astype(int) - valid = (sx >= 0) & (sx < height - 1) & (sy >= 0) & (sy < width - 1) - - if interpolate_mode == 'nearest': - output[valid, :] = img[dx[valid].round().astype(int), - dy[valid].round().astype(int), :] - elif interpolate_mode == 'bilinear': - # dirty walkround for integer positions - eps_ = 1e-6 - dx, dy = dx + eps_, dy + eps_ - left_top_ = img[np.floor(dx[valid]).astype(int), - np.floor(dy[valid]).astype(int), :] * ( - np.ceil(dx[valid]) - dx[valid])[:, None] * ( - np.ceil(dy[valid]) - dy[valid])[:, None] - left_down_ = img[np.ceil(dx[valid]).astype(int), - np.floor(dy[valid]).astype(int), :] * ( - dx[valid] - np.floor(dx[valid]))[:, None] * ( - np.ceil(dy[valid]) - dy[valid])[:, None] - right_top_ = img[np.floor(dx[valid]).astype(int), - np.ceil(dy[valid]).astype(int), :] * ( - np.ceil(dx[valid]) - dx[valid])[:, None] * ( - dy[valid] - np.floor(dy[valid]))[:, None] - right_down_ = img[np.ceil(dx[valid]).astype(int), - np.ceil(dy[valid]).astype(int), :] * ( - dx[valid] - np.floor(dx[valid]))[:, None] * ( - dy[valid] - np.floor(dy[valid]))[:, None] - output[valid, :] = left_top_ + left_down_ + right_top_ + right_down_ - else: - raise NotImplementedError( - 'We only support interpolation modes of nearest and bilinear, ' - f'but got {interpolate_mode}.') - return output.astype(img.dtype) - - -def flow_from_bytes(content): - """Read dense optical flow from bytes. - - .. note:: - This load optical flow function works for FlyingChairs, FlyingThings3D, - Sintel, FlyingChairsOcc datasets, but cannot load the data from - ChairsSDHom. - - Args: - content (bytes): Optical flow bytes got from files or other streams. - - Returns: - ndarray: Loaded optical flow with the shape (H, W, 2). - """ - - # header in first 4 bytes - header = content[:4] - if header.decode('utf-8') != 'PIEH': - raise Exception('Flow file header does not contain PIEH') - # width in second 4 bytes - width = np.frombuffer(content[4:], np.int32, 1).squeeze() - # height in third 4 bytes - height = np.frombuffer(content[8:], np.int32, 1).squeeze() - # after first 12 bytes, all bytes are flow - flow = np.frombuffer(content[12:], np.float32, width * height * 2).reshape( - (height, width, 2)) - - return flow - - -def sparse_flow_from_bytes(content): - """Read the optical flow in KITTI datasets from bytes. - - This function is modified from RAFT load the `KITTI datasets - `_. - - Args: - content (bytes): Optical flow bytes got from files or other streams. - - Returns: - Tuple(ndarray, ndarray): Loaded optical flow with the shape (H, W, 2) - and flow valid mask with the shape (H, W). - """ # nopa - - content = np.frombuffer(content, np.uint8) - flow = cv2.imdecode(content, cv2.IMREAD_ANYDEPTH | cv2.IMREAD_COLOR) - flow = flow[:, :, ::-1].astype(np.float32) - # flow shape (H, W, 2) valid shape (H, W) - flow, valid = flow[:, :, :2], flow[:, :, 2] - flow = (flow - 2**15) / 64.0 - return flow, valid diff --git a/spaces/Michale1017/Auto-keep-online/README.md b/spaces/Michale1017/Auto-keep-online/README.md deleted file mode 100644 index 04f8bbb0cf1aa866057895161fb1a070280c14f2..0000000000000000000000000000000000000000 --- a/spaces/Michale1017/Auto-keep-online/README.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Auto Keep Online -emoji: 📈 -colorFrom: indigo -colorTo: purple -sdk: docker -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Miuzarte/SUI-svc-4.0/vdecoder/hifigan/nvSTFT.py b/spaces/Miuzarte/SUI-svc-4.0/vdecoder/hifigan/nvSTFT.py deleted file mode 100644 index 88597d62a505715091f9ba62d38bf0a85a31b95a..0000000000000000000000000000000000000000 --- a/spaces/Miuzarte/SUI-svc-4.0/vdecoder/hifigan/nvSTFT.py +++ /dev/null @@ -1,111 +0,0 @@ -import math -import os -os.environ["LRU_CACHE_CAPACITY"] = "3" -import random -import torch -import torch.utils.data -import numpy as np -import librosa -from librosa.util import normalize -from librosa.filters import mel as librosa_mel_fn -from scipy.io.wavfile import read -import soundfile as sf - -def load_wav_to_torch(full_path, target_sr=None, return_empty_on_exception=False): - sampling_rate = None - try: - data, sampling_rate = sf.read(full_path, always_2d=True)# than soundfile. - except Exception as ex: - print(f"'{full_path}' failed to load.\nException:") - print(ex) - if return_empty_on_exception: - return [], sampling_rate or target_sr or 32000 - else: - raise Exception(ex) - - if len(data.shape) > 1: - data = data[:, 0] - assert len(data) > 2# check duration of audio file is > 2 samples (because otherwise the slice operation was on the wrong dimension) - - if np.issubdtype(data.dtype, np.integer): # if audio data is type int - max_mag = -np.iinfo(data.dtype).min # maximum magnitude = min possible value of intXX - else: # if audio data is type fp32 - max_mag = max(np.amax(data), -np.amin(data)) - max_mag = (2**31)+1 if max_mag > (2**15) else ((2**15)+1 if max_mag > 1.01 else 1.0) # data should be either 16-bit INT, 32-bit INT or [-1 to 1] float32 - - data = torch.FloatTensor(data.astype(np.float32))/max_mag - - if (torch.isinf(data) | torch.isnan(data)).any() and return_empty_on_exception:# resample will crash with inf/NaN inputs. return_empty_on_exception will return empty arr instead of except - return [], sampling_rate or target_sr or 32000 - if target_sr is not None and sampling_rate != target_sr: - data = torch.from_numpy(librosa.core.resample(data.numpy(), orig_sr=sampling_rate, target_sr=target_sr)) - sampling_rate = target_sr - - return data, sampling_rate - -def dynamic_range_compression(x, C=1, clip_val=1e-5): - return np.log(np.clip(x, a_min=clip_val, a_max=None) * C) - -def dynamic_range_decompression(x, C=1): - return np.exp(x) / C - -def dynamic_range_compression_torch(x, C=1, clip_val=1e-5): - return torch.log(torch.clamp(x, min=clip_val) * C) - -def dynamic_range_decompression_torch(x, C=1): - return torch.exp(x) / C - -class STFT(): - def __init__(self, sr=22050, n_mels=80, n_fft=1024, win_size=1024, hop_length=256, fmin=20, fmax=11025, clip_val=1e-5): - self.target_sr = sr - - self.n_mels = n_mels - self.n_fft = n_fft - self.win_size = win_size - self.hop_length = hop_length - self.fmin = fmin - self.fmax = fmax - self.clip_val = clip_val - self.mel_basis = {} - self.hann_window = {} - - def get_mel(self, y, center=False): - sampling_rate = self.target_sr - n_mels = self.n_mels - n_fft = self.n_fft - win_size = self.win_size - hop_length = self.hop_length - fmin = self.fmin - fmax = self.fmax - clip_val = self.clip_val - - if torch.min(y) < -1.: - print('min value is ', torch.min(y)) - if torch.max(y) > 1.: - print('max value is ', torch.max(y)) - - if fmax not in self.mel_basis: - mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=n_mels, fmin=fmin, fmax=fmax) - self.mel_basis[str(fmax)+'_'+str(y.device)] = torch.from_numpy(mel).float().to(y.device) - self.hann_window[str(y.device)] = torch.hann_window(self.win_size).to(y.device) - - y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_length)/2), int((n_fft-hop_length)/2)), mode='reflect') - y = y.squeeze(1) - - spec = torch.stft(y, n_fft, hop_length=hop_length, win_length=win_size, window=self.hann_window[str(y.device)], - center=center, pad_mode='reflect', normalized=False, onesided=True) - # print(111,spec) - spec = torch.sqrt(spec.pow(2).sum(-1)+(1e-9)) - # print(222,spec) - spec = torch.matmul(self.mel_basis[str(fmax)+'_'+str(y.device)], spec) - # print(333,spec) - spec = dynamic_range_compression_torch(spec, clip_val=clip_val) - # print(444,spec) - return spec - - def __call__(self, audiopath): - audio, sr = load_wav_to_torch(audiopath, target_sr=self.target_sr) - spect = self.get_mel(audio.unsqueeze(0)).squeeze(0) - return spect - -stft = STFT() diff --git a/spaces/Mostafa92/detecting_plant_leaf_diseases/article.md b/spaces/Mostafa92/detecting_plant_leaf_diseases/article.md deleted file mode 100644 index b6563f7641b9a764682796e9b7ba91b8223ed69c..0000000000000000000000000000000000000000 --- a/spaces/Mostafa92/detecting_plant_leaf_diseases/article.md +++ /dev/null @@ -1,82 +0,0 @@ -## EXAMPLES -- We added a test_data folder which contains around 740 images from our **test dataset of 5000 images**, that's around 15 to 20 image per class and all of these images are shuffled and used as examples in this demo web app. -**Can you see which images the model got it wrong?** - - -## Dataset - -In this data-set, 39 different classes of plant leaf and background images are available. The data-set containing 61,486 images. This data comes with six different augmentation techniques for increasing the data-set size. The techniques are image flipping, Gamma correction, noise injection, PCA color augmentation, rotation, and Scaling. [see more](https://data.mendeley.com/datasets/tywbtsjrjv/1) - - -## Model Architecture ----------------------------------------------------------------- -| Layer (type) | Output Shape | Param | -|-----------------------|:------------------------:|-------------:| -| Conv2d-1 | [-1, 64, 256, 256] | 1,792 | -| BatchNorm2d-2 | [-1, 64, 256, 256] | 128 | -| ReLU-3 | [-1, 64, 256, 256] | 0 | -| Conv2d-4 | [-1, 128, 256, 256] | 73,856 | -| BatchNorm2d-5 | [-1, 128, 256, 256] | 256 | -| ReLU-6 | [-1, 128, 256, 256] | 0 | -| MaxPool2d-7 | [-1, 128, 64, 64] | 0 | -| Conv2d-8 | [-1, 128, 64, 64] | 147,584 | -| BatchNorm2d-9 | [-1, 128, 64, 64] | 256 | -| ReLU-10 | [-1, 128, 64, 64] | 0 | -| Conv2d-11 | [-1, 128, 64, 64] | 147,584 | -| BatchNorm2d-12 | [-1, 128, 64, 64] | 256 | -| ReLU-13 | [-1, 128, 64, 64] | 0 | -| Conv2d-14 | [-1, 256, 64, 64] | 295,168 | -| BatchNorm2d-15 | [-1, 256, 64, 64] | 512 | -| ReLU-16 | [-1, 256, 64, 64] | 0 | -| MaxPool2d-17 | [-1, 256, 16, 16] | 0 | -| Conv2d-18 | [-1, 512, 16, 16] | 1,180,160 | -| BatchNorm2d-19 | [-1, 512, 16, 16] | 1,024 | -| ReLU-20 | [-1, 512, 16, 16] | 0 | -| MaxPool2d-21 | [-1, 512, 4, 4] | 0 | -| Conv2d-22 | [-1, 512, 4, 4] | 2,359,808 | -| BatchNorm2d-23 | [-1, 512, 4, 4] | 1,024 | -| ReLU-24 | [-1, 512, 4, 4] | 0 | -| Conv2d-25 | [-1, 512, 4, 4] | 2,359,808 | -| BatchNorm2d-26 | [-1, 512, 4, 4] | 1,024 | -| ReLU-27 | [-1, 512, 4, 4] | 0 | -| MaxPool2d-28 | [-1, 512, 1, 1] | 0 | -| Flatten-29 | [-1, 512] | 0 | -| Dropout-30 | [-1, 512] | 0 | -| Linear-31 | [-1, 39] | 20,007 | - - -- **Total params: `6,590,247`** -- **Trainable params: `6,590,247`** -- **Non-trainable params: `0`** - -- **Input size (MB): `0.75`** -- **Forward/backward pass size (MB): `343.95`** -- **Params size (MB): `25.14`** -- **Estimated Total Size (MB): 369.84`** - ----------------------------------------------------------------- -## Training - -- **Epoch [1], last_lr: `0.00696`, train_loss: `0.9292`, val_loss: `0.4448`, val_acc: `0.8572`** -- **Epoch [2], last_lr: `0.00324`, train_loss: `0.2816`, val_loss: `0.3342`, val_acc: `0.8999`** -- **Epoch [3], last_lr: `0.00000`, train_loss: `0.0851`, val_loss: `0.0355`, val_acc: `0.9931`** -- **CPU times: user 18min 48s, sys: 14min 36s, total: 33min 25s** -**Wall time: `33min 29s`** - -### Params -- **EPOCHS = `3`** -- **MAX_LR = `0.007`** -- **GRAD_CLIP = `0.1`** -- **WEIGHT_DECAY = `1e-4`** -- **OPTIMIZER = `torch.optim.Adam`** - ----------------------------------------------------------------- - -## Important Info -- **Model size is: `(25.17M)`** -- **Validation Accuracy is: `99.3%`** -- **Last validation Loss is: `0.0355`** -- **Last Train Loss is: `0.0851`** -- **Test Accuracy is: `99.1%`** - ----------------------------------------------------------------- \ No newline at end of file diff --git a/spaces/Mountchicken/MAERec-Gradio/mmocr/models/textrecog/decoders/sar_decoder.py b/spaces/Mountchicken/MAERec-Gradio/mmocr/models/textrecog/decoders/sar_decoder.py deleted file mode 100644 index d156c30fd144a5256965c7bc376ab5645c925792..0000000000000000000000000000000000000000 --- a/spaces/Mountchicken/MAERec-Gradio/mmocr/models/textrecog/decoders/sar_decoder.py +++ /dev/null @@ -1,574 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import math -from typing import Dict, List, Optional, Sequence, Union - -import torch -import torch.nn as nn -import torch.nn.functional as F - -from mmocr.models.common.dictionary import Dictionary -from mmocr.registry import MODELS -from mmocr.structures import TextRecogDataSample -from .base import BaseDecoder - - -@MODELS.register_module() -class ParallelSARDecoder(BaseDecoder): - """Implementation Parallel Decoder module in `SAR. - - `_. - - Args: - dictionary (dict or :obj:`Dictionary`): The config for `Dictionary` or - the instance of `Dictionary`. - module_loss (dict, optional): Config to build module_loss. Defaults - to None. - postprocessor (dict, optional): Config to build postprocessor. - Defaults to None. - enc_bi_rnn (bool): If True, use bidirectional RNN in encoder. - Defaults to False. - dec_bi_rnn (bool): If True, use bidirectional RNN in decoder. - Defaults to False. - dec_rnn_dropout (float): Dropout of RNN layer in decoder. - Defaults to 0.0. - dec_gru (bool): If True, use GRU, else LSTM in decoder. Defaults to - False. - d_model (int): Dim of channels from backbone :math:`D_i`. Defaults - to 512. - d_enc (int): Dim of encoder RNN layer :math:`D_m`. Defaults to 512. - d_k (int): Dim of channels of attention module. Defaults to 64. - pred_dropout (float): Dropout probability of prediction layer. Defaults - to 0.0. - max_seq_len (int): Maximum sequence length for decoding. Defaults to - 30. - mask (bool): If True, mask padding in feature map. Defaults to True. - pred_concat (bool): If True, concat glimpse feature from - attention with holistic feature and hidden state. Defaults to - False. - init_cfg (dict or list[dict], optional): Initialization configs. - Defaults to None. - """ - - def __init__(self, - dictionary: Union[Dict, Dictionary], - module_loss: Optional[Dict] = None, - postprocessor: Optional[Dict] = None, - enc_bi_rnn: bool = False, - dec_bi_rnn: bool = False, - dec_rnn_dropout: Union[int, float] = 0.0, - dec_gru: bool = False, - d_model: int = 512, - d_enc: int = 512, - d_k: int = 64, - pred_dropout: float = 0.0, - max_seq_len: int = 30, - mask: bool = True, - pred_concat: bool = False, - init_cfg: Optional[Union[Dict, List[Dict]]] = None, - **kwargs) -> None: - super().__init__( - dictionary=dictionary, - module_loss=module_loss, - max_seq_len=max_seq_len, - postprocessor=postprocessor, - init_cfg=init_cfg) - - self.num_classes = self.dictionary.num_classes - self.enc_bi_rnn = enc_bi_rnn - self.d_k = d_k - self.start_idx = self.dictionary.start_idx - self.mask = mask - self.pred_concat = pred_concat - - encoder_rnn_out_size = d_enc * (int(enc_bi_rnn) + 1) - decoder_rnn_out_size = encoder_rnn_out_size * (int(dec_bi_rnn) + 1) - # 2D attention layer - self.conv1x1_1 = nn.Linear(decoder_rnn_out_size, d_k) - self.conv3x3_1 = nn.Conv2d( - d_model, d_k, kernel_size=3, stride=1, padding=1) - self.conv1x1_2 = nn.Linear(d_k, 1) - - # Decoder RNN layer - kwargs = dict( - input_size=encoder_rnn_out_size, - hidden_size=encoder_rnn_out_size, - num_layers=2, - batch_first=True, - dropout=dec_rnn_dropout, - bidirectional=dec_bi_rnn) - if dec_gru: - self.rnn_decoder = nn.GRU(**kwargs) - else: - self.rnn_decoder = nn.LSTM(**kwargs) - - # Decoder input embedding - self.embedding = nn.Embedding( - self.num_classes, - encoder_rnn_out_size, - padding_idx=self.dictionary.padding_idx) - - # Prediction layer - self.pred_dropout = nn.Dropout(pred_dropout) - if pred_concat: - fc_in_channel = decoder_rnn_out_size + d_model + \ - encoder_rnn_out_size - else: - fc_in_channel = d_model - self.prediction = nn.Linear(fc_in_channel, self.num_classes) - self.softmax = nn.Softmax(dim=-1) - - def _2d_attention(self, - decoder_input: torch.Tensor, - feat: torch.Tensor, - holistic_feat: torch.Tensor, - valid_ratios: Optional[Sequence[float]] = None - ) -> torch.Tensor: - """2D attention layer. - - Args: - decoder_input (torch.Tensor): Input of decoder RNN. - feat (torch.Tensor): Feature map of encoder. - holistic_feat (torch.Tensor): Feature map of holistic encoder. - valid_ratios (Sequence[float]): Valid ratios of attention. - Defaults to None. - - Returns: - torch.Tensor: Output of 2D attention layer. - """ - y = self.rnn_decoder(decoder_input)[0] - # y: bsz * (seq_len + 1) * hidden_size - - attn_query = self.conv1x1_1(y) # bsz * (seq_len + 1) * attn_size - bsz, seq_len, attn_size = attn_query.size() - attn_query = attn_query.view(bsz, seq_len, attn_size, 1, 1) - - attn_key = self.conv3x3_1(feat) - # bsz * attn_size * h * w - attn_key = attn_key.unsqueeze(1) - # bsz * 1 * attn_size * h * w - - attn_weight = torch.tanh(torch.add(attn_key, attn_query, alpha=1)) - # bsz * (seq_len + 1) * attn_size * h * w - attn_weight = attn_weight.permute(0, 1, 3, 4, 2).contiguous() - # bsz * (seq_len + 1) * h * w * attn_size - attn_weight = self.conv1x1_2(attn_weight) - # bsz * (seq_len + 1) * h * w * 1 - bsz, T, h, w, c = attn_weight.size() - assert c == 1 - - if valid_ratios is not None: - # cal mask of attention weight - attn_mask = torch.zeros_like(attn_weight) - for i, valid_ratio in enumerate(valid_ratios): - valid_width = min(w, math.ceil(w * valid_ratio)) - attn_mask[i, :, :, valid_width:, :] = 1 - attn_weight = attn_weight.masked_fill(attn_mask.bool(), - float('-inf')) - - attn_weight = attn_weight.view(bsz, T, -1) - attn_weight = F.softmax(attn_weight, dim=-1) - attn_weight = attn_weight.view(bsz, T, h, w, - c).permute(0, 1, 4, 2, 3).contiguous() - - attn_feat = torch.sum( - torch.mul(feat.unsqueeze(1), attn_weight), (3, 4), keepdim=False) - # bsz * (seq_len + 1) * C - - # linear transformation - if self.pred_concat: - hf_c = holistic_feat.size(-1) - holistic_feat = holistic_feat.expand(bsz, seq_len, hf_c) - y = self.prediction(torch.cat((y, attn_feat, holistic_feat), 2)) - else: - y = self.prediction(attn_feat) - # bsz * (seq_len + 1) * num_classes - y = self.pred_dropout(y) - - return y - - def forward_train(self, feat: torch.Tensor, out_enc: torch.Tensor, - data_samples: Sequence[TextRecogDataSample] - ) -> torch.Tensor: - """ - Args: - feat (Tensor): Tensor of shape :math:`(N, D_i, H, W)`. - out_enc (Tensor): Encoder output of shape - :math:`(N, D_m, H, W)`. - data_samples (list[TextRecogDataSample]): Batch of - TextRecogDataSample, containing gt_text and valid_ratio - information. - - Returns: - Tensor: A raw logit tensor of shape :math:`(N, T, C)`. - """ - if data_samples is not None: - assert len(data_samples) == feat.size(0) - - valid_ratios = [ - img_meta.get('valid_ratio', 1.0) for img_meta in data_samples - ] if self.mask else None - - padded_targets = [ - data_sample.gt_text.padded_indexes for data_sample in data_samples - ] - padded_targets = torch.stack(padded_targets, dim=0).to(feat.device) - tgt_embedding = self.embedding(padded_targets) - # bsz * seq_len * emb_dim - out_enc = out_enc.unsqueeze(1) - # bsz * 1 * emb_dim - in_dec = torch.cat((out_enc, tgt_embedding), dim=1) - # bsz * (seq_len + 1) * C - out_dec = self._2d_attention( - in_dec, feat, out_enc, valid_ratios=valid_ratios) - # bsz * (seq_len + 1) * num_classes - - return out_dec[:, 1:, :] # bsz * seq_len * num_classes - - def forward_test( - self, - feat: torch.Tensor, - out_enc: torch.Tensor, - data_samples: Optional[Sequence[TextRecogDataSample]] = None - ) -> torch.Tensor: - """ - Args: - feat (Tensor): Tensor of shape :math:`(N, D_i, H, W)`. - out_enc (Tensor): Encoder output of shape - :math:`(N, D_m, H, W)`. - data_samples (list[TextRecogDataSample], optional): Batch of - TextRecogDataSample, containing valid_ratio - information. Defaults to None. - - Returns: - Tensor: Character probabilities. of shape - :math:`(N, self.max_seq_len, C)` where :math:`C` is - ``num_classes``. - """ - if data_samples is not None: - assert len(data_samples) == feat.size(0) - - valid_ratios = None - if data_samples is not None: - valid_ratios = [ - data_sample.get('valid_ratio', 1.0) - for data_sample in data_samples - ] if self.mask else None - - seq_len = self.max_seq_len - - bsz = feat.size(0) - start_token = torch.full((bsz, ), - self.start_idx, - device=feat.device, - dtype=torch.long) - # bsz - start_token = self.embedding(start_token) - # bsz * emb_dim - start_token = start_token.unsqueeze(1).expand(-1, seq_len, -1) - # bsz * seq_len * emb_dim - out_enc = out_enc.unsqueeze(1) - # bsz * 1 * emb_dim - decoder_input = torch.cat((out_enc, start_token), dim=1) - # bsz * (seq_len + 1) * emb_dim - - outputs = [] - for i in range(1, seq_len + 1): - decoder_output = self._2d_attention( - decoder_input, feat, out_enc, valid_ratios=valid_ratios) - char_output = decoder_output[:, i, :] # bsz * num_classes - outputs.append(char_output) - _, max_idx = torch.max(char_output, dim=1, keepdim=False) - char_embedding = self.embedding(max_idx) # bsz * emb_dim - if i < seq_len: - decoder_input[:, i + 1, :] = char_embedding - - outputs = torch.stack(outputs, 1) # bsz * seq_len * num_classes - - return self.softmax(outputs) - - -@MODELS.register_module() -class SequentialSARDecoder(BaseDecoder): - """Implementation Sequential Decoder module in `SAR. - - `_. - - Args: - dictionary (dict or :obj:`Dictionary`): The config for `Dictionary` or - the instance of `Dictionary`. - module_loss (dict, optional): Config to build module_loss. Defaults - to None. - postprocessor (dict, optional): Config to build postprocessor. - Defaults to None. - enc_bi_rnn (bool): If True, use bidirectional RNN in encoder. Defaults - to False. - dec_bi_rnn (bool): If True, use bidirectional RNN in decoder. Defaults - to False. - dec_do_rnn (float): Dropout of RNN layer in decoder. Defaults to 0. - dec_gru (bool): If True, use GRU, else LSTM in decoder. Defaults to - False. - d_k (int): Dim of conv layers in attention module. Defaults to 64. - d_model (int): Dim of channels from backbone :math:`D_i`. Defaults to - 512. - d_enc (int): Dim of encoder RNN layer :math:`D_m`. Defaults to 512. - pred_dropout (float): Dropout probability of prediction layer. Defaults - to 0. - max_seq_len (int): Maximum sequence length during decoding. Defaults to - 40. - mask (bool): If True, mask padding in feature map. Defaults to False. - pred_concat (bool): If True, concat glimpse feature from - attention with holistic feature and hidden state. Defaults to - False. - init_cfg (dict or list[dict], optional): Initialization configs. - Defaults to None. - """ - - def __init__(self, - dictionary: Optional[Union[Dict, Dictionary]] = None, - module_loss: Optional[Dict] = None, - postprocessor: Optional[Dict] = None, - enc_bi_rnn: bool = False, - dec_bi_rnn: bool = False, - dec_gru: bool = False, - d_k: int = 64, - d_model: int = 512, - d_enc: int = 512, - pred_dropout: float = 0.0, - mask: bool = True, - max_seq_len: int = 40, - pred_concat: bool = False, - init_cfg: Optional[Union[Dict, List[Dict]]] = None, - **kwargs): - super().__init__( - dictionary=dictionary, - module_loss=module_loss, - postprocessor=postprocessor, - max_seq_len=max_seq_len, - init_cfg=init_cfg) - - self.num_classes = self.dictionary.num_classes - self.enc_bi_rnn = enc_bi_rnn - self.d_k = d_k - self.start_idx = self.dictionary.start_idx - self.dec_gru = dec_gru - self.mask = mask - self.pred_concat = pred_concat - - encoder_rnn_out_size = d_enc * (int(enc_bi_rnn) + 1) - decoder_rnn_out_size = encoder_rnn_out_size * (int(dec_bi_rnn) + 1) - # 2D attention layer - self.conv1x1_1 = nn.Conv2d( - decoder_rnn_out_size, d_k, kernel_size=1, stride=1) - self.conv3x3_1 = nn.Conv2d( - d_model, d_k, kernel_size=3, stride=1, padding=1) - self.conv1x1_2 = nn.Conv2d(d_k, 1, kernel_size=1, stride=1) - - # Decoder rnn layer - if dec_gru: - self.rnn_decoder_layer1 = nn.GRUCell(encoder_rnn_out_size, - encoder_rnn_out_size) - self.rnn_decoder_layer2 = nn.GRUCell(encoder_rnn_out_size, - encoder_rnn_out_size) - else: - self.rnn_decoder_layer1 = nn.LSTMCell(encoder_rnn_out_size, - encoder_rnn_out_size) - self.rnn_decoder_layer2 = nn.LSTMCell(encoder_rnn_out_size, - encoder_rnn_out_size) - - # Decoder input embedding - self.embedding = nn.Embedding( - self.num_classes, - encoder_rnn_out_size, - padding_idx=self.dictionary.padding_idx) - - # Prediction layer - self.pred_dropout = nn.Dropout(pred_dropout) - if pred_concat: - fc_in_channel = decoder_rnn_out_size + d_model + d_enc - else: - fc_in_channel = d_model - self.prediction = nn.Linear(fc_in_channel, self.num_classes) - self.softmax = nn.Softmax(dim=-1) - - def _2d_attention(self, - y_prev: torch.Tensor, - feat: torch.Tensor, - holistic_feat: torch.Tensor, - hx1: torch.Tensor, - cx1: torch.Tensor, - hx2: torch.Tensor, - cx2: torch.Tensor, - valid_ratios: Optional[Sequence[float]] = None - ) -> torch.Tensor: - """2D attention layer. - - Args: - y_prev (torch.Tensor): Previous decoder hidden state. - feat (torch.Tensor): Feature map. - holistic_feat (torch.Tensor): Holistic feature map. - hx1 (torch.Tensor): rnn decoder layer 1 hidden state. - cx1 (torch.Tensor): rnn decoder layer 1 cell state. - hx2 (torch.Tensor): rnn decoder layer 2 hidden state. - cx2 (torch.Tensor): rnn decoder layer 2 cell state. - valid_ratios (Optional[Sequence[float]]): Valid ratios of - attention. Defaults to None. - """ - _, _, h_feat, w_feat = feat.size() - if self.dec_gru: - hx1 = cx1 = self.rnn_decoder_layer1(y_prev, hx1) - hx2 = cx2 = self.rnn_decoder_layer2(hx1, hx2) - else: - hx1, cx1 = self.rnn_decoder_layer1(y_prev, (hx1, cx1)) - hx2, cx2 = self.rnn_decoder_layer2(hx1, (hx2, cx2)) - - tile_hx2 = hx2.view(hx2.size(0), hx2.size(1), 1, 1) - attn_query = self.conv1x1_1(tile_hx2) # bsz * attn_size * 1 * 1 - attn_query = attn_query.expand(-1, -1, h_feat, w_feat) - attn_key = self.conv3x3_1(feat) - attn_weight = torch.tanh(torch.add(attn_key, attn_query, alpha=1)) - attn_weight = self.conv1x1_2(attn_weight) - bsz, c, h, w = attn_weight.size() - assert c == 1 - - if valid_ratios is not None: - # cal mask of attention weight - attn_mask = torch.zeros_like(attn_weight) - for i, valid_ratio in enumerate(valid_ratios): - valid_width = min(w, math.ceil(w * valid_ratio)) - attn_mask[i, :, :, valid_width:] = 1 - attn_weight = attn_weight.masked_fill(attn_mask.bool(), - float('-inf')) - - attn_weight = F.softmax(attn_weight.view(bsz, -1), dim=-1) - attn_weight = attn_weight.view(bsz, c, h, w) - - attn_feat = torch.sum( - torch.mul(feat, attn_weight), (2, 3), keepdim=False) # n * c - - # linear transformation - if self.pred_concat: - y = self.prediction(torch.cat((hx2, attn_feat, holistic_feat), 1)) - else: - y = self.prediction(attn_feat) - - return y, hx1, hx1, hx2, hx2 - - def forward_train( - self, - feat: torch.Tensor, - out_enc: torch.Tensor, - data_samples: Optional[Sequence[TextRecogDataSample]] = None - ) -> torch.Tensor: - """ - Args: - feat (Tensor): Tensor of shape :math:`(N, D_i, H, W)`. - out_enc (Tensor): Encoder output of shape - :math:`(N, D_m, H, W)`. - data_samples (list[TextRecogDataSample]): Batch of - TextRecogDataSample, containing gt_text and valid_ratio - information. - - Returns: - Tensor: A raw logit tensor of shape :math:`(N, T, C)`. - """ - valid_ratios = None - if data_samples is not None: - valid_ratios = [ - data_sample.get('valid_ratio', 1.0) - for data_sample in data_samples - ] if self.mask else None - - padded_targets = [ - data_sample.gt_text.padded_indexes for data_sample in data_samples - ] - padded_targets = torch.stack(padded_targets, dim=0).to(feat.device) - tgt_embedding = self.embedding(padded_targets) - - outputs = [] - for i in range(-1, self.max_seq_len): - if i == -1: - if self.dec_gru: - hx1 = cx1 = self.rnn_decoder_layer1(out_enc) - hx2 = cx2 = self.rnn_decoder_layer2(hx1) - else: - hx1, cx1 = self.rnn_decoder_layer1(out_enc) - hx2, cx2 = self.rnn_decoder_layer2(hx1) - else: - y_prev = tgt_embedding[:, i, :] - y, hx1, cx1, hx2, cx2 = self._2d_attention( - y_prev, - feat, - out_enc, - hx1, - cx1, - hx2, - cx2, - valid_ratios=valid_ratios) - y = self.pred_dropout(y) - - outputs.append(y) - - outputs = torch.stack(outputs, 1) - - return outputs - - def forward_test( - self, - feat: torch.Tensor, - out_enc: torch.Tensor, - data_samples: Optional[Sequence[TextRecogDataSample]] = None - ) -> torch.Tensor: - """ - Args: - feat (Tensor): Tensor of shape :math:`(N, D_i, H, W)`. - out_enc (Tensor): Encoder output of shape - :math:`(N, D_m, H, W)`. - data_samples (list[TextRecogDataSample]): Batch of - TextRecogDataSample, containing valid_ratio - information. - - Returns: - Tensor: Character probabilities. of shape - :math:`(N, self.max_seq_len, C)` where :math:`C` is - ``num_classes``. - """ - valid_ratios = None - if data_samples is not None: - valid_ratios = [ - data_sample.get('valid_ratio', 1.0) - for data_sample in data_samples - ] if self.mask else None - - outputs = [] - start_token = torch.full((feat.size(0), ), - self.start_idx, - device=feat.device, - dtype=torch.long) - start_token = self.embedding(start_token) - for i in range(-1, self.max_seq_len): - if i == -1: - if self.dec_gru: - hx1 = cx1 = self.rnn_decoder_layer1(out_enc) - hx2 = cx2 = self.rnn_decoder_layer2(hx1) - else: - hx1, cx1 = self.rnn_decoder_layer1(out_enc) - hx2, cx2 = self.rnn_decoder_layer2(hx1) - y_prev = start_token - else: - y, hx1, cx1, hx2, cx2 = self._2d_attention( - y_prev, - feat, - out_enc, - hx1, - cx1, - hx2, - cx2, - valid_ratios=valid_ratios) - _, max_idx = torch.max(y, dim=1, keepdim=False) - char_embedding = self.embedding(max_idx) - y_prev = char_embedding - outputs.append(y) - - outputs = torch.stack(outputs, 1) - - return self.softmax(outputs) diff --git a/spaces/Mountchicken/MAERec-Gradio/tools/dataset_converters/textrecog/art_converter.py b/spaces/Mountchicken/MAERec-Gradio/tools/dataset_converters/textrecog/art_converter.py deleted file mode 100644 index 24acaad289be221558701d19a95ea7ce24a7e0f9..0000000000000000000000000000000000000000 --- a/spaces/Mountchicken/MAERec-Gradio/tools/dataset_converters/textrecog/art_converter.py +++ /dev/null @@ -1,108 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import argparse -import math -import os.path as osp - -import mmengine - -from mmocr.utils import dump_ocr_data - - -def parse_args(): - parser = argparse.ArgumentParser( - description='Generate training and validation set of ArT ') - parser.add_argument('root_path', help='Root dir path of ArT') - parser.add_argument( - '--val-ratio', help='Split ratio for val set', default=0.0, type=float) - parser.add_argument( - '--nproc', default=1, type=int, help='Number of processes') - args = parser.parse_args() - return args - - -def convert_art(root_path, split, ratio): - """Collect the annotation information and crop the images. - - The annotation format is as the following: - { - "gt_2836_0": [ - { - "transcription": "URDER", - "points": [ - [25, 51], - [0, 2], - [21, 0], - [42, 43] - ], - "language": "Latin", - "illegibility": false - } - ], ... - } - - Args: - root_path (str): The root path of the dataset - split (str): The split of dataset. Namely: training or val - ratio (float): Split ratio for val set - - Returns: - img_info (dict): The dict of the img and annotation information - """ - - annotation_path = osp.join(root_path, - 'annotations/train_task2_labels.json') - if not osp.exists(annotation_path): - raise Exception( - f'{annotation_path} not exists, please check and try again.') - - annotation = mmengine.load(annotation_path) - img_prefixes = annotation.keys() - - trn_files, val_files = [], [] - if ratio > 0: - for i, file in enumerate(img_prefixes): - if i % math.floor(1 / ratio): - trn_files.append(file) - else: - val_files.append(file) - else: - trn_files, val_files = img_prefixes, [] - print(f'training #{len(trn_files)}, val #{len(val_files)}') - - if split == 'train': - img_prefixes = trn_files - elif split == 'val': - img_prefixes = val_files - else: - raise NotImplementedError - - img_info = [] - for prefix in img_prefixes: - text_label = annotation[prefix][0]['transcription'] - dst_img_name = prefix + '.jpg' - - img_info.append({ - 'file_name': dst_img_name, - 'anno_info': [{ - 'text': text_label - }] - }) - - ensure_ascii = dict(ensure_ascii=False) - dump_ocr_data(img_info, osp.join(root_path, f'{split.lower()}_label.json'), - 'textrecog', **ensure_ascii) - - -def main(): - args = parse_args() - root_path = args.root_path - print('Processing training set...') - convert_art(root_path=root_path, split='train', ratio=args.val_ratio) - if args.val_ratio > 0: - print('Processing validation set...') - convert_art(root_path=root_path, split='val', ratio=args.val_ratio) - print('Finish') - - -if __name__ == '__main__': - main() diff --git a/spaces/NCTCMumbai/NCTC/models/official/vision/detection/configs/maskrcnn_config.py b/spaces/NCTCMumbai/NCTC/models/official/vision/detection/configs/maskrcnn_config.py deleted file mode 100644 index 70c9b31448d3d83754c439c87ce9f0d0a04f88c9..0000000000000000000000000000000000000000 --- a/spaces/NCTCMumbai/NCTC/models/official/vision/detection/configs/maskrcnn_config.py +++ /dev/null @@ -1,116 +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. -# ============================================================================== -"""Config template to train Mask R-CNN.""" - -from official.modeling.hyperparams import params_dict -from official.vision.detection.configs import base_config - - -# pylint: disable=line-too-long -MASKRCNN_CFG = params_dict.ParamsDict(base_config.BASE_CFG) -MASKRCNN_CFG.override({ - 'type': 'mask_rcnn', - 'eval': { - 'type': 'box_and_mask', - 'num_images_to_visualize': 0, - }, - 'architecture': { - 'parser': 'maskrcnn_parser', - 'min_level': 2, - 'max_level': 6, - 'include_mask': True, - 'mask_target_size': 28, - }, - 'maskrcnn_parser': { - 'output_size': [1024, 1024], - 'num_channels': 3, - 'rpn_match_threshold': 0.7, - 'rpn_unmatched_threshold': 0.3, - 'rpn_batch_size_per_im': 256, - 'rpn_fg_fraction': 0.5, - 'aug_rand_hflip': True, - 'aug_scale_min': 1.0, - 'aug_scale_max': 1.0, - 'skip_crowd_during_training': True, - 'max_num_instances': 100, - 'mask_crop_size': 112, - }, - 'anchor': { - 'num_scales': 1, - 'anchor_size': 8, - }, - 'rpn_head': { - 'anchors_per_location': 3, - 'num_convs': 2, - 'num_filters': 256, - 'use_separable_conv': False, - 'use_batch_norm': False, - }, - 'frcnn_head': { - 'num_convs': 0, - 'num_filters': 256, - 'use_separable_conv': False, - 'num_fcs': 2, - 'fc_dims': 1024, - 'use_batch_norm': False, - }, - 'mrcnn_head': { - 'num_convs': 4, - 'num_filters': 256, - 'use_separable_conv': False, - 'use_batch_norm': False, - }, - 'rpn_score_loss': { - 'rpn_batch_size_per_im': 256, - }, - 'rpn_box_loss': { - 'huber_loss_delta': 1.0 / 9.0, - }, - 'frcnn_box_loss': { - 'huber_loss_delta': 1.0, - }, - 'roi_proposal': { - 'rpn_pre_nms_top_k': 2000, - 'rpn_post_nms_top_k': 1000, - 'rpn_nms_threshold': 0.7, - 'rpn_score_threshold': 0.0, - 'rpn_min_size_threshold': 0.0, - 'test_rpn_pre_nms_top_k': 1000, - 'test_rpn_post_nms_top_k': 1000, - 'test_rpn_nms_threshold': 0.7, - 'test_rpn_score_threshold': 0.0, - 'test_rpn_min_size_threshold': 0.0, - 'use_batched_nms': False, - }, - 'roi_sampling': { - 'num_samples_per_image': 512, - 'fg_fraction': 0.25, - 'fg_iou_thresh': 0.5, - 'bg_iou_thresh_hi': 0.5, - 'bg_iou_thresh_lo': 0.0, - 'mix_gt_boxes': True, - }, - 'mask_sampling': { - 'num_mask_samples_per_image': 128, # Typically = `num_samples_per_image` * `fg_fraction`. - }, - 'postprocess': { - 'pre_nms_num_boxes': 1000, - }, -}, is_strict=False) - - -MASKRCNN_RESTRICTIONS = [ -] -# pylint: enable=line-too-long diff --git a/spaces/NCTCMumbai/NCTC/models/official/vision/image_classification/resnet/__init__.py b/spaces/NCTCMumbai/NCTC/models/official/vision/image_classification/resnet/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/NeoonN/Aurora/app.py b/spaces/NeoonN/Aurora/app.py deleted file mode 100644 index 85bf55364c3584ab5eb78b40b49c35ded16f572f..0000000000000000000000000000000000000000 --- a/spaces/NeoonN/Aurora/app.py +++ /dev/null @@ -1,57 +0,0 @@ -import gradio as gr -import numpy as np -import pandas as pd -from pandas.core.frame import DataFrame -from PIL import Image -import requests - -import hopsworks -import joblib - -project = hopsworks.login() -fs = project.get_feature_store() - -mr = project.get_model_registry() -model = mr.get_model("aurora_model", version=1) -model_dir = model.download() -model = joblib.load(model_dir+"/aurora_model.pkl") - - -def tb_aurora(Kp_index, visibility, icon): - input_list = [] - input_list.append(Kp_index) - input_list.append(visibility) - input_icon = icon - - icon_feature_list = ['clear_day', 'clear_night', 'cloudy', 'fog', 'partly_cloudy_day', 'partly_cloudy_night', 'rain', - 'snow', 'wind'] - - icon_feature_list.append(input_icon) - - icon_df = DataFrame(icon_feature_list) - icon_df_one = pd.get_dummies(icon_df) - icon = icon_df_one.values.tolist()[9] - - input_list.extend(icon) - print(input_list) - - # 'res' is a list of predictions returned as the label. - # global res - res = model.predict(np.asarray(input_list).reshape(1, 11)) - aurora_url = "https://raw.githubusercontent.com/NeoForNew/ID2223_scalable_machine_learning_and_deep_learning/main/Project/pic/" + str(res[0]) + ".png" - img = Image.open(requests.get(aurora_url, stream=True).raw) - return img - -demo = gr.Interface( - fn=tb_aurora, - title="Aurora Predictive Analytics", - description="Predict aurora 0 for not occur and 1 for occur. ", - inputs=[ - gr.inputs.Number(default=0.0, label="Kp_index"), - gr.inputs.Number(default=0.0, label="visibility"), - gr.inputs.Dropdown(['clear_day', 'clear_night', 'cloudy', 'fog', 'partly_cloudy_day', 'partly_cloudy_night', 'rain', - 'snow', 'wind'], label="icon"), - ], - outputs=gr.Image(type="pil")) - -demo.launch() \ No newline at end of file diff --git a/spaces/Nultx/VITS-TTS/monotonic_align/setup.py b/spaces/Nultx/VITS-TTS/monotonic_align/setup.py deleted file mode 100644 index 30c224807a70faa9df9c9eb75f8e80c8c867b16b..0000000000000000000000000000000000000000 --- a/spaces/Nultx/VITS-TTS/monotonic_align/setup.py +++ /dev/null @@ -1,9 +0,0 @@ -from distutils.core import setup -from Cython.Build import cythonize -import numpy - -setup( - name = 'monotonic_align', - ext_modules = cythonize("core.pyx"), - include_dirs=[numpy.get_include()] -) diff --git a/spaces/OAOA/DifFace/basicsr/archs/srresnet_arch.py b/spaces/OAOA/DifFace/basicsr/archs/srresnet_arch.py deleted file mode 100644 index 7f571557cd7d9ba8791bd6462fccf648c57186d2..0000000000000000000000000000000000000000 --- a/spaces/OAOA/DifFace/basicsr/archs/srresnet_arch.py +++ /dev/null @@ -1,65 +0,0 @@ -from torch import nn as nn -from torch.nn import functional as F - -from basicsr.utils.registry import ARCH_REGISTRY -from .arch_util import ResidualBlockNoBN, default_init_weights, make_layer - - -@ARCH_REGISTRY.register() -class MSRResNet(nn.Module): - """Modified SRResNet. - - A compacted version modified from SRResNet in - "Photo-Realistic Single Image Super-Resolution Using a Generative Adversarial Network" - It uses residual blocks without BN, similar to EDSR. - Currently, it supports x2, x3 and x4 upsampling scale factor. - - Args: - num_in_ch (int): Channel number of inputs. Default: 3. - num_out_ch (int): Channel number of outputs. Default: 3. - num_feat (int): Channel number of intermediate features. Default: 64. - num_block (int): Block number in the body network. Default: 16. - upscale (int): Upsampling factor. Support x2, x3 and x4. Default: 4. - """ - - def __init__(self, num_in_ch=3, num_out_ch=3, num_feat=64, num_block=16, upscale=4): - super(MSRResNet, self).__init__() - self.upscale = upscale - - self.conv_first = nn.Conv2d(num_in_ch, num_feat, 3, 1, 1) - self.body = make_layer(ResidualBlockNoBN, num_block, num_feat=num_feat) - - # upsampling - if self.upscale in [2, 3]: - self.upconv1 = nn.Conv2d(num_feat, num_feat * self.upscale * self.upscale, 3, 1, 1) - self.pixel_shuffle = nn.PixelShuffle(self.upscale) - elif self.upscale == 4: - self.upconv1 = nn.Conv2d(num_feat, num_feat * 4, 3, 1, 1) - self.upconv2 = nn.Conv2d(num_feat, num_feat * 4, 3, 1, 1) - self.pixel_shuffle = nn.PixelShuffle(2) - - 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) - - # activation function - self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True) - - # initialization - default_init_weights([self.conv_first, self.upconv1, self.conv_hr, self.conv_last], 0.1) - if self.upscale == 4: - default_init_weights(self.upconv2, 0.1) - - def forward(self, x): - feat = self.lrelu(self.conv_first(x)) - out = self.body(feat) - - if self.upscale == 4: - out = self.lrelu(self.pixel_shuffle(self.upconv1(out))) - out = self.lrelu(self.pixel_shuffle(self.upconv2(out))) - elif self.upscale in [2, 3]: - out = self.lrelu(self.pixel_shuffle(self.upconv1(out))) - - out = self.conv_last(self.lrelu(self.conv_hr(out))) - base = F.interpolate(x, scale_factor=self.upscale, mode='bilinear', align_corners=False) - out += base - return out diff --git a/spaces/OAOA/DifFace/basicsr/data/data_util.py b/spaces/OAOA/DifFace/basicsr/data/data_util.py deleted file mode 100644 index bf4c494b7715399395a7d23dd87202d09592c725..0000000000000000000000000000000000000000 --- a/spaces/OAOA/DifFace/basicsr/data/data_util.py +++ /dev/null @@ -1,315 +0,0 @@ -import cv2 -import numpy as np -import torch -from os import path as osp -from torch.nn import functional as F - -from basicsr.data.transforms import mod_crop -from basicsr.utils import img2tensor, scandir - - -def read_img_seq(path, require_mod_crop=False, scale=1, return_imgname=False): - """Read a sequence of images from a given folder path. - - Args: - path (list[str] | str): List of image paths or image folder path. - require_mod_crop (bool): Require mod crop for each image. - Default: False. - scale (int): Scale factor for mod_crop. Default: 1. - return_imgname(bool): Whether return image names. Default False. - - Returns: - Tensor: size (t, c, h, w), RGB, [0, 1]. - list[str]: Returned image name list. - """ - if isinstance(path, list): - img_paths = path - else: - img_paths = sorted(list(scandir(path, full_path=True))) - imgs = [cv2.imread(v).astype(np.float32) / 255. for v in img_paths] - - if require_mod_crop: - imgs = [mod_crop(img, scale) for img in imgs] - imgs = img2tensor(imgs, bgr2rgb=True, float32=True) - imgs = torch.stack(imgs, dim=0) - - if return_imgname: - imgnames = [osp.splitext(osp.basename(path))[0] for path in img_paths] - return imgs, imgnames - else: - return imgs - - -def generate_frame_indices(crt_idx, max_frame_num, num_frames, padding='reflection'): - """Generate an index list for reading `num_frames` frames from a sequence - of images. - - Args: - crt_idx (int): Current center index. - max_frame_num (int): Max number of the sequence of images (from 1). - num_frames (int): Reading num_frames frames. - padding (str): Padding mode, one of - 'replicate' | 'reflection' | 'reflection_circle' | 'circle' - Examples: current_idx = 0, num_frames = 5 - The generated frame indices under different padding mode: - replicate: [0, 0, 0, 1, 2] - reflection: [2, 1, 0, 1, 2] - reflection_circle: [4, 3, 0, 1, 2] - circle: [3, 4, 0, 1, 2] - - Returns: - list[int]: A list of indices. - """ - assert num_frames % 2 == 1, 'num_frames should be an odd number.' - assert padding in ('replicate', 'reflection', 'reflection_circle', 'circle'), f'Wrong padding mode: {padding}.' - - max_frame_num = max_frame_num - 1 # start from 0 - num_pad = num_frames // 2 - - indices = [] - for i in range(crt_idx - num_pad, crt_idx + num_pad + 1): - if i < 0: - if padding == 'replicate': - pad_idx = 0 - elif padding == 'reflection': - pad_idx = -i - elif padding == 'reflection_circle': - pad_idx = crt_idx + num_pad - i - else: - pad_idx = num_frames + i - elif i > max_frame_num: - if padding == 'replicate': - pad_idx = max_frame_num - elif padding == 'reflection': - pad_idx = max_frame_num * 2 - i - elif padding == 'reflection_circle': - pad_idx = (crt_idx - num_pad) - (i - max_frame_num) - else: - pad_idx = i - num_frames - else: - pad_idx = i - indices.append(pad_idx) - return indices - - -def paired_paths_from_lmdb(folders, keys): - """Generate paired paths from lmdb files. - - Contents of lmdb. Taking the `lq.lmdb` for example, the file structure is: - - :: - - lq.lmdb - ├── data.mdb - ├── lock.mdb - ├── meta_info.txt - - The data.mdb and lock.mdb are standard lmdb files and you can refer to - https://lmdb.readthedocs.io/en/release/ for more details. - - The meta_info.txt is a specified txt file to record the meta information - of our datasets. It will be automatically created when preparing - datasets by our provided dataset tools. - Each line in the txt file records - 1)image name (with extension), - 2)image shape, - 3)compression level, separated by a white space. - Example: `baboon.png (120,125,3) 1` - - We use the image name without extension as the lmdb key. - Note that we use the same key for the corresponding lq and gt images. - - Args: - folders (list[str]): A list of folder path. The order of list should - be [input_folder, gt_folder]. - keys (list[str]): A list of keys identifying folders. The order should - be in consistent with folders, e.g., ['lq', 'gt']. - Note that this key is different from lmdb keys. - - Returns: - list[str]: Returned path list. - """ - assert len(folders) == 2, ('The len of folders should be 2 with [input_folder, gt_folder]. ' - f'But got {len(folders)}') - assert len(keys) == 2, f'The len of keys should be 2 with [input_key, gt_key]. But got {len(keys)}' - input_folder, gt_folder = folders - input_key, gt_key = keys - - if not (input_folder.endswith('.lmdb') and gt_folder.endswith('.lmdb')): - raise ValueError(f'{input_key} folder and {gt_key} folder should both in lmdb ' - f'formats. But received {input_key}: {input_folder}; ' - f'{gt_key}: {gt_folder}') - # ensure that the two meta_info files are the same - with open(osp.join(input_folder, 'meta_info.txt')) as fin: - input_lmdb_keys = [line.split('.')[0] for line in fin] - with open(osp.join(gt_folder, 'meta_info.txt')) as fin: - gt_lmdb_keys = [line.split('.')[0] for line in fin] - if set(input_lmdb_keys) != set(gt_lmdb_keys): - raise ValueError(f'Keys in {input_key}_folder and {gt_key}_folder are different.') - else: - paths = [] - for lmdb_key in sorted(input_lmdb_keys): - paths.append(dict([(f'{input_key}_path', lmdb_key), (f'{gt_key}_path', lmdb_key)])) - return paths - - -def paired_paths_from_meta_info_file(folders, keys, meta_info_file, filename_tmpl): - """Generate paired paths from an meta information file. - - Each line in the meta information file contains the image names and - image shape (usually for gt), separated by a white space. - - Example of an meta information file: - ``` - 0001_s001.png (480,480,3) - 0001_s002.png (480,480,3) - ``` - - Args: - folders (list[str]): A list of folder path. The order of list should - be [input_folder, gt_folder]. - keys (list[str]): A list of keys identifying folders. The order should - be in consistent with folders, e.g., ['lq', 'gt']. - meta_info_file (str): Path to the meta information file. - filename_tmpl (str): Template for each filename. Note that the - template excludes the file extension. Usually the filename_tmpl is - for files in the input folder. - - Returns: - list[str]: Returned path list. - """ - assert len(folders) == 2, ('The len of folders should be 2 with [input_folder, gt_folder]. ' - f'But got {len(folders)}') - assert len(keys) == 2, f'The len of keys should be 2 with [input_key, gt_key]. But got {len(keys)}' - input_folder, gt_folder = folders - input_key, gt_key = keys - - with open(meta_info_file, 'r') as fin: - gt_names = [line.strip().split(' ')[0] for line in fin] - - paths = [] - for gt_name in gt_names: - basename, ext = osp.splitext(osp.basename(gt_name)) - input_name = f'{filename_tmpl.format(basename)}{ext}' - input_path = osp.join(input_folder, input_name) - gt_path = osp.join(gt_folder, gt_name) - paths.append(dict([(f'{input_key}_path', input_path), (f'{gt_key}_path', gt_path)])) - return paths - - -def paired_paths_from_folder(folders, keys, filename_tmpl): - """Generate paired paths from folders. - - Args: - folders (list[str]): A list of folder path. The order of list should - be [input_folder, gt_folder]. - keys (list[str]): A list of keys identifying folders. The order should - be in consistent with folders, e.g., ['lq', 'gt']. - filename_tmpl (str): Template for each filename. Note that the - template excludes the file extension. Usually the filename_tmpl is - for files in the input folder. - - Returns: - list[str]: Returned path list. - """ - assert len(folders) == 2, ('The len of folders should be 2 with [input_folder, gt_folder]. ' - f'But got {len(folders)}') - assert len(keys) == 2, f'The len of keys should be 2 with [input_key, gt_key]. But got {len(keys)}' - input_folder, gt_folder = folders - input_key, gt_key = keys - - input_paths = list(scandir(input_folder)) - gt_paths = list(scandir(gt_folder)) - assert len(input_paths) == len(gt_paths), (f'{input_key} and {gt_key} datasets have different number of images: ' - f'{len(input_paths)}, {len(gt_paths)}.') - paths = [] - for gt_path in gt_paths: - basename, ext = osp.splitext(osp.basename(gt_path)) - input_name = f'{filename_tmpl.format(basename)}{ext}' - input_path = osp.join(input_folder, input_name) - assert input_name in input_paths, f'{input_name} is not in {input_key}_paths.' - gt_path = osp.join(gt_folder, gt_path) - paths.append(dict([(f'{input_key}_path', input_path), (f'{gt_key}_path', gt_path)])) - return paths - - -def paths_from_folder(folder): - """Generate paths from folder. - - Args: - folder (str): Folder path. - - Returns: - list[str]: Returned path list. - """ - - paths = list(scandir(folder)) - paths = [osp.join(folder, path) for path in paths] - return paths - - -def paths_from_lmdb(folder): - """Generate paths from lmdb. - - Args: - folder (str): Folder path. - - Returns: - list[str]: Returned path list. - """ - if not folder.endswith('.lmdb'): - raise ValueError(f'Folder {folder}folder should in lmdb format.') - with open(osp.join(folder, 'meta_info.txt')) as fin: - paths = [line.split('.')[0] for line in fin] - return paths - - -def generate_gaussian_kernel(kernel_size=13, sigma=1.6): - """Generate Gaussian kernel used in `duf_downsample`. - - Args: - kernel_size (int): Kernel size. Default: 13. - sigma (float): Sigma of the Gaussian kernel. Default: 1.6. - - Returns: - np.array: The Gaussian kernel. - """ - from scipy.ndimage import filters as filters - kernel = np.zeros((kernel_size, kernel_size)) - # set element at the middle to one, a dirac delta - kernel[kernel_size // 2, kernel_size // 2] = 1 - # gaussian-smooth the dirac, resulting in a gaussian filter - return filters.gaussian_filter(kernel, sigma) - - -def duf_downsample(x, kernel_size=13, scale=4): - """Downsamping with Gaussian kernel used in the DUF official code. - - Args: - x (Tensor): Frames to be downsampled, with shape (b, t, c, h, w). - kernel_size (int): Kernel size. Default: 13. - scale (int): Downsampling factor. Supported scale: (2, 3, 4). - Default: 4. - - Returns: - Tensor: DUF downsampled frames. - """ - assert scale in (2, 3, 4), f'Only support scale (2, 3, 4), but got {scale}.' - - squeeze_flag = False - if x.ndim == 4: - squeeze_flag = True - x = x.unsqueeze(0) - b, t, c, h, w = x.size() - x = x.view(-1, 1, h, w) - pad_w, pad_h = kernel_size // 2 + scale * 2, kernel_size // 2 + scale * 2 - x = F.pad(x, (pad_w, pad_w, pad_h, pad_h), 'reflect') - - gaussian_filter = generate_gaussian_kernel(kernel_size, 0.4 * scale) - gaussian_filter = torch.from_numpy(gaussian_filter).type_as(x).unsqueeze(0).unsqueeze(0) - x = F.conv2d(x, gaussian_filter, stride=scale) - x = x[:, :, 2:-2, 2:-2] - x = x.view(b, t, c, x.size(2), x.size(3)) - if squeeze_flag: - x = x.squeeze(0) - return x diff --git a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/examples/multilingual/data_scripts/download_ted_and_extract.py b/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/examples/multilingual/data_scripts/download_ted_and_extract.py deleted file mode 100644 index eb756680fa7dc31a14ba45c216776a6d60c16b60..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/examples/multilingual/data_scripts/download_ted_and_extract.py +++ /dev/null @@ -1,338 +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 itertools -import os -import csv -from collections import defaultdict -from six.moves import zip -import io -import wget -import sys - -from subprocess import check_call, check_output - -# scripts and data locations -CWD = os.getcwd() -UTILS = f"{CWD}/utils" - -MOSES = f"{UTILS}/mosesdecoder" - -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) - - -# please donwload mosesdecoder here: -detok_cmd = f'{MOSES}/scripts/tokenizer/detokenizer.perl' - - -def call(cmd): - print(f"Executing: {cmd}") - check_call(cmd, shell=True) - -class MultiLingualAlignedCorpusReader(object): - """A class to read TED talk dataset - """ - - def __init__(self, corpus_path, delimiter='\t', - target_token=True, bilingual=True, corpus_type='file', - lang_dict={'source': ['fr'], 'target': ['en']}, - eval_lang_dict=None, zero_shot=False, - detok=True, - ): - - self.empty_line_flag = 'NULL' - self.corpus_path = corpus_path - self.delimiter = delimiter - self.bilingual = bilingual - self.lang_dict = lang_dict - self.lang_set = set() - self.target_token = target_token - self.zero_shot = zero_shot - self.eval_lang_dict = eval_lang_dict - self.corpus_type = corpus_type - self.detok = detok - - for list_ in self.lang_dict.values(): - for lang in list_: - self.lang_set.add(lang) - - self.data = dict() - self.data['train'] = self.read_aligned_corpus(split_type='train') - self.data['test'] = self.read_aligned_corpus(split_type='test') - self.data['dev'] = self.read_aligned_corpus(split_type='dev') - - def read_data(self, file_loc_): - data_list = list() - with io.open(file_loc_, 'r', encoding='utf8') as fp: - for line in fp: - try: - text = line.strip() - except IndexError: - text = self.empty_line_flag - data_list.append(text) - return data_list - - def filter_text(self, dict_): - if self.target_token: - field_index = 1 - else: - field_index = 0 - data_dict = defaultdict(list) - list1 = dict_['source'] - list2 = dict_['target'] - for sent1, sent2 in zip(list1, list2): - try: - src_sent = ' '.join(sent1.split()[field_index: ]) - except IndexError: - src_sent = 'NULL' - - if src_sent.find(self.empty_line_flag) != -1 or len(src_sent) == 0: - continue - - elif sent2.find(self.empty_line_flag) != -1 or len(sent2) == 0: - continue - - else: - data_dict['source'].append(sent1) - data_dict['target'].append(sent2) - return data_dict - - def read_file(self, split_type, data_type): - return self.data[split_type][data_type] - - def save_file(self, path_, split_type, data_type, lang): - tok_file = tok_file_name(path_, lang) - with io.open(tok_file, 'w', encoding='utf8') as fp: - for line in self.data[split_type][data_type]: - fp.write(line + '\n') - if self.detok: - de_tok(tok_file, lang) - - def add_target_token(self, list_, lang_id): - new_list = list() - token = '__' + lang_id + '__' - for sent in list_: - new_list.append(token + ' ' + sent) - return new_list - - def read_from_single_file(self, path_, s_lang, t_lang): - data_dict = defaultdict(list) - with io.open(path_, 'r', encoding='utf8') as fp: - reader = csv.DictReader(fp, delimiter='\t', quoting=csv.QUOTE_NONE) - for row in reader: - data_dict['source'].append(row[s_lang]) - data_dict['target'].append(row[t_lang]) - - if self.target_token: - text = self.add_target_token(data_dict['source'], t_lang) - data_dict['source'] = text - - return data_dict['source'], data_dict['target'] - - def read_aligned_corpus(self, split_type='train'): - data_dict = defaultdict(list) - iterable = [] - s_list = [] - t_list = [] - - if self.zero_shot: - if split_type == "train": - iterable = zip(self.lang_dict['source'], self.lang_dict['target']) - else: - iterable = zip(self.eval_lang_dict['source'], self.eval_lang_dict['target']) - - elif self.bilingual: - iterable = itertools.product(self.lang_dict['source'], self.lang_dict['target']) - - for s_lang, t_lang in iterable: - if s_lang == t_lang: - continue - if self.corpus_type == 'file': - split_type_file_path = os.path.join(self.corpus_path, - "all_talks_{}.tsv".format(split_type)) - s_list, t_list = self.read_from_single_file(split_type_file_path, - s_lang=s_lang, - t_lang=t_lang) - data_dict['source'] += s_list - data_dict['target'] += t_list - new_data_dict = self.filter_text(data_dict) - return new_data_dict - - -def read_langs(corpus_path): - split_type_file_path = os.path.join(corpus_path, 'extracted', - "all_talks_dev.tsv") - with io.open(split_type_file_path, 'r', encoding='utf8') as fp: - reader = csv.DictReader(fp, delimiter='\t', quoting=csv.QUOTE_NONE) - header = next(reader) - return [k for k in header.keys() if k != 'talk_name'] - -def extra_english(corpus_path, split): - split_type_file_path = os.path.join(corpus_path, - f"all_talks_{split}.tsv") - output_split_type_file_path = os.path.join(corpus_path, - f"all_talks_{split}.en") - with io.open(split_type_file_path, 'r', encoding='utf8') as fp, io.open(output_split_type_file_path, 'w', encoding='utf8') as fw: - reader = csv.DictReader(fp, delimiter='\t', quoting=csv.QUOTE_NONE) - for row in reader: - line = row['en'] - fw.write(line + '\n') - de_tok(output_split_type_file_path, 'en') - - - -def tok_file_name(filename, lang): - seps = filename.split('.') - seps.insert(-1, 'tok') - tok_file = '.'.join(seps) - return tok_file - -def de_tok(tok_file, lang): - # seps = tok_file.split('.') - # seps.insert(-1, 'detok') - # de_tok_file = '.'.join(seps) - de_tok_file = tok_file.replace('.tok.', '.') - cmd = 'perl {detok_cmd} -l {lang} < {tok_file} > {de_tok_file}'.format( - detok_cmd=detok_cmd, tok_file=tok_file, - de_tok_file=de_tok_file, lang=lang[:2]) - call(cmd) - -def extra_bitex( - ted_data_path, - lsrc_lang, - ltrg_lang, - target_token, - output_data_path, -): - def get_ted_lang(lang): - long_langs = ['pt-br', 'zh-cn', 'zh-tw', 'fr-ca'] - if lang[:5] in long_langs: - return lang[:5] - elif lang[:4] =='calv': - return lang[:5] - elif lang in ['pt_BR', 'zh_CN', 'zh_TW', 'fr_CA']: - return lang.lower().replace('_', '-') - return lang[:2] - src_lang = get_ted_lang(lsrc_lang) - trg_lang = get_ted_lang(ltrg_lang) - train_lang_dict={'source': [src_lang], 'target': [trg_lang]} - eval_lang_dict = {'source': [src_lang], 'target': [trg_lang]} - - obj = MultiLingualAlignedCorpusReader(corpus_path=ted_data_path, - lang_dict=train_lang_dict, - target_token=target_token, - corpus_type='file', - eval_lang_dict=eval_lang_dict, - zero_shot=False, - bilingual=True) - - os.makedirs(output_data_path, exist_ok=True) - lsrc_lang = lsrc_lang.replace('-', '_') - ltrg_lang = ltrg_lang.replace('-', '_') - obj.save_file(output_data_path + f"/train.{lsrc_lang}-{ltrg_lang}.{lsrc_lang}", - split_type='train', data_type='source', lang=src_lang) - obj.save_file(output_data_path + f"/train.{lsrc_lang}-{ltrg_lang}.{ltrg_lang}", - split_type='train', data_type='target', lang=trg_lang) - - obj.save_file(output_data_path + f"/test.{lsrc_lang}-{ltrg_lang}.{lsrc_lang}", - split_type='test', data_type='source', lang=src_lang) - obj.save_file(output_data_path + f"/test.{lsrc_lang}-{ltrg_lang}.{ltrg_lang}", - split_type='test', data_type='target', lang=trg_lang) - - obj.save_file(output_data_path + f"/valid.{lsrc_lang}-{ltrg_lang}.{lsrc_lang}", - split_type='dev', data_type='source', lang=src_lang) - obj.save_file(output_data_path + f"/valid.{lsrc_lang}-{ltrg_lang}.{ltrg_lang}", - split_type='dev', data_type='target', lang=trg_lang) - - -def bar_custom(current, total, width=80): - print("Downloading: %d%% [%d / %d] Ks" % (current / total * 100, current / 1000, total / 1000), end='\r') - - -def download_and_extract(download_to, extract_to): - url = 'http://phontron.com/data/ted_talks.tar.gz' - filename = f"{download_to}/ted_talks.tar.gz" - if os.path.exists(filename): - print(f'{filename} has already been downloaded so skip') - else: - filename = wget.download(url, filename, bar=bar_custom) - if os.path.exists(f'{extract_to}/all_talks_train.tsv'): - print(f'Already extracted so skip') - else: - extract_cmd = f'tar xzfv "{filename}" -C "{extract_to}"' - call(extract_cmd) - - -if __name__ == "__main__": - import argparse - parser = argparse.ArgumentParser() - parser.add_argument('--ted_data_path', type=str, default=WORKDIR_ROOT, required=False) - parser.add_argument( - '--direction-list', - type=str, - # default=None, - #for ML50 - default=( - "bn_IN-en_XX,he_IL-en_XX,fa_IR-en_XX,id_ID-en_XX,sv_SE-en_XX,pt_XX-en_XX,ka_GE-en_XX,ka_GE-en_XX,th_TH-en_XX," - "mr_IN-en_XX,hr_HR-en_XX,uk_UA-en_XX,az_AZ-en_XX,mk_MK-en_XX,gl_ES-en_XX,sl_SI-en_XX,mn_MN-en_XX," - #non-english directions - # "fr_XX-de_DE," # replaced with wmt20 - # "ja_XX-ko_KR,es_XX-pt_XX,ru_RU-sv_SE,hi_IN-bn_IN,id_ID-ar_AR,cs_CZ-pl_PL,ar_AR-tr_TR" - ), - required=False) - parser.add_argument('--target-token', action='store_true', default=False) - parser.add_argument('--extract-all-english', action='store_true', default=False) - - args = parser.parse_args() - - import sys - import json - - # TED Talks data directory - ted_data_path = args.ted_data_path - - download_to = f'{ted_data_path}/downloads' - extract_to = f'{ted_data_path}/extracted' - - #DESTDIR=${WORKDIR_ROOT}/ML50/raw/ - output_path = f'{ted_data_path}/ML50/raw' - os.makedirs(download_to, exist_ok=True) - os.makedirs(extract_to, exist_ok=True) - os.makedirs(output_path, exist_ok=True) - download_and_extract(download_to, extract_to) - - - if args.extract_all_english: - for split in ['train', 'dev', 'test']: - extra_english(ted_data_path, split) - exit(0) - if args.direction_list is not None: - directions = args.direction_list.strip().split(',') - directions = [tuple(d.strip().split('-', 1)) for d in directions if d] - else: - langs = read_langs(ted_data_path) - # directions = [ - # '{}.{}'.format(src, tgt) - # for src in langs - # for tgt in langs - # if src < tgt - # ] - directions = [('en', tgt) for tgt in langs if tgt != 'en'] - print(f'num directions={len(directions)}: {directions}') - - for src_lang, trg_lang in directions: - print('--working on {}-{}'.format(src_lang, trg_lang)) - extra_bitex( - extract_to, - src_lang, - trg_lang, - target_token=args.target_token, - output_data_path=output_path - ) diff --git a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/models/speech_to_text/s2t_transformer.py b/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/models/speech_to_text/s2t_transformer.py deleted file mode 100644 index aff9d0ffc7b7e671c476ff28d1cd945e9ff41519..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Generic_Interface/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/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/modules/kmeans_attention.py b/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/modules/kmeans_attention.py deleted file mode 100644 index 11a7debcf2ac025fb02ba5e672987f87dbbc49a4..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/modules/kmeans_attention.py +++ /dev/null @@ -1,609 +0,0 @@ -import torch -import torch.nn as nn -import torch.nn.functional as F -import math -from inspect import isfunction -from operator import mul -from functools import reduce, wraps - -from aml.multimodal_video.utils.einops.lib import rearrange, repeat -from aml.multimodal_video.utils.einops.lib.layers.torch import Rearrange - -from fairseq.modules.local_attention import LocalAttention - -# constants - -TOKEN_SELF_ATTN_VALUE = -5e4 -KMEAN_INIT_ITERS = 10 - -# helper functions - - -def exists(val): - return val is not None - - -def identity(x, *args, **kwargs): - return x - - -def default(x, d): - if not exists(x): - return d if not isfunction(d) else d() - return x - - -def cast_tuple(x): - return x if isinstance(x, tuple) else (x,) - - -def cache_fn(f): - cache = None - - @wraps(f) - def cached_fn(*args, **kwargs): - nonlocal cache - if exists(cache): - return cache - cache = f(*args, **kwargs) - return cache - return cached_fn - - -def to(t): - return {'device': t.device, 'dtype': t.dtype} - - -def find_modules(nn_module, type): - return [module for module in nn_module.modules() if isinstance(module, type)] - - -def is_empty(t): - return t.nelement() == 0 - - -def max_neg_value(tensor): - return -torch.finfo(tensor.dtype).max - - -def batched_index_select(values, indices): - last_dim = values.shape[-1] - return values.gather(2, expand_dim(indices, -1, last_dim)) - - -def merge_dims(ind_from, ind_to, tensor): - shape = list(tensor.shape) - arr_slice = slice(ind_from, ind_to + 1) - shape[arr_slice] = [reduce(mul, shape[arr_slice])] - return tensor.reshape(*shape) - - -def expand_dim(t, dim, k): - t = t.unsqueeze(dim) - expand_shape = [-1] * len(t.shape) - expand_shape[dim] = k - return t.expand(*expand_shape) - - -def scatter_mean(src, t, index, dim, eps=1e-5): - numer = src.scatter_add(dim, index, t) - denom = src.scatter_add(dim, index, torch.ones_like(t)) - return numer / (denom + eps) - - -def split_at_index(dim, index, t): - pre_slices = (slice(None),) * dim - l = (*pre_slices, slice(None, index)) - r = (*pre_slices, slice(index, None)) - return t[l], t[r] - - -def reshape_dim(t, dim, split_dims): - shape = list(t.shape) - num_dims = len(shape) - dim = (dim + num_dims) % num_dims - shape[dim:dim+1] = split_dims - return t.reshape(shape) - - -def ema(old, new, decay): - if not exists(old): - return new - return old * decay + new * (1 - decay) - - -def ema_inplace(moving_avg, new, decay): - if is_empty(moving_avg): - moving_avg.data.copy_(new) - return - moving_avg.data.mul_(decay).add_(new, alpha=(1 - decay)) - -# helper classes - - -def map_first_tuple_or_el(x, fn): - if isinstance(x, tuple): - return (fn(x[0]),) + x[1:] - return fn(x) - - -class Chunk(nn.Module): - def __init__(self, chunks, fn, along_dim=-1): - super().__init__() - self.dim = along_dim - self.chunks = chunks - self.fn = fn - - def forward(self, x, **kwargs): - if self.chunks <= 1: - return self.fn(x, **kwargs) - chunks = x.chunk(self.chunks, dim=self.dim) - return torch.cat([self.fn(c, **kwargs) for c in chunks], dim=self.dim) - - -class PreNorm(nn.ModuleList): - def __init__(self, norm_class, dim, fn): - super().__init__() - self.norm = norm_class(dim) - self.fn = fn - - def forward(self, x, **kwargs): - x = self.norm(x) - return self.fn(x, **kwargs) - - -class ReZero(nn.Module): - def __init__(self, fn): - super().__init__() - self.residual_weight = nn.Parameter(torch.zeros(1)) - self.fn = fn - - def forward(self, x, **kwargs): - x = self.fn(x, **kwargs) - return map_first_tuple_or_el(x, lambda t: t * self.residual_weight) - - -class ScaleNorm(nn.Module): - def __init__(self, dim, eps=1e-5): - super().__init__() - self.g = nn.Parameter(torch.ones(1)) - self.eps = eps - - def forward(self, x): - def norm(t): - n = torch.norm(t, dim=-1, keepdim=True).clamp(min=self.eps) - return t / n * self.g - return map_first_tuple_or_el(x, norm) - - -class ProjectInOut(nn.Module): - def __init__(self, fn, dim_in, dim_out, project_out=True): - super().__init__() - self.fn = fn - self.project_in = nn.Linear(dim_in, dim_out) - self.project_out = nn.Linear(dim_out, dim_in) if project_out else identity - - def forward(self, x, **kwargs): - x = self.project_in(x) - x, loss = self.fn(x, **kwargs) - x = self.project_out(x) - return x, loss - - -class MatrixMultiply(nn.Module): - def __init__(self, tensor, transpose=False): - super().__init__() - self.tensor = tensor - self.transpose = transpose - - def forward(self, x): - tensor = self.tensor - if self.transpose: - tensor = tensor.t() - return x @ tensor - -# positional embeddings - - -class DepthWiseConv1d(nn.Module): - def __init__(self, dim_in, dim_out, kernel_size, stride=1, bias=True, causal=False): - super().__init__() - self.padding = ((kernel_size - 1), 0) if causal else (kernel_size // 2, kernel_size // 2) - - self.net = nn.Sequential( - nn.Conv1d(dim_in, dim_in, kernel_size=kernel_size, groups=dim_in, stride=stride, bias=bias), - nn.Conv1d(dim_in, dim_out, 1, bias=bias) - ) - - def forward(self, x): - x = F.pad(x, self.padding, value=0.) - return self.net(x) - - -class FixedPositionalEmbedding(nn.Module): - def __init__(self, dim, max_seq_len): - super().__init__() - inv_freq = 1. / (10000 ** (torch.arange(0, dim, 2).float() / dim)) - position = torch.arange(0, max_seq_len, dtype=torch.float) - sinusoid_inp = torch.einsum("i,j->ij", position, inv_freq) - emb = torch.cat((sinusoid_inp.sin(), sinusoid_inp.cos()), dim=-1) - self.register_buffer('emb', emb) - - def forward(self, x): - return self.emb[None, :x.shape[1], :].to(x) - - -def rotate_every_two(x): - x = rearrange(x, '... (d j) -> ... d j', j=2) - x1, x2 = x.unbind(dim=-1) - x = torch.stack((-x2, x1), dim=-1) - return rearrange(x, '... d j -> ... (d j)') - - -def apply_rotary_pos_emb(q, k, sinu_pos): - sinu_pos = rearrange(sinu_pos, '() n (j d) -> n j d', j=2) - sin, cos = sinu_pos.unbind(dim=-2) - sin, cos = map(lambda t: repeat(t, 'b n -> b (n j)', j=2), (sin, cos)) - q, k = map(lambda t: (t * cos) + (rotate_every_two(t) * sin), (q, k)) - return q, k - -# kmeans related function and class - - -def update_kmeans_on_backwards(module): - module.kmean_modules = find_modules(module, Kmeans) - - def hook(_, grad_in, grad_out): - for m in module.kmean_modules: - m.update() - - return module.register_backward_hook(hook) - - -def similarity(x, means): - return torch.einsum('bhld,hcd->bhlc', x, means) - - -def dists_and_buckets(x, means): - dists = similarity(x, means) - _, buckets = torch.max(dists, dim=-1) - return dists, buckets - - -def batched_bincount(index, num_classes, dim=-1): - shape = list(index.shape) - shape[dim] = num_classes - out = index.new_zeros(shape) - out.scatter_add_(dim, index, torch.ones_like(index, dtype=index.dtype)) - return out - - -def kmeans_iter(x, means, buckets=None): - b, h, _, d, dtype, num_clusters = *x.shape, x.dtype, means.shape[1] - - if not exists(buckets): - _, buckets = dists_and_buckets(x, means) - - bins = batched_bincount(buckets, num_clusters).sum(0, keepdim=True) - zero_mask = bins.long() == 0 - - means_ = buckets.new_zeros(b, h, num_clusters, d, dtype=dtype) - means_.scatter_add_(-2, expand_dim(buckets, -1, d), x) - means_ = F.normalize(means_.sum(0, keepdim=True), dim=-1).type(dtype) - - means = torch.where(zero_mask.unsqueeze(-1), means, means_) - means = means.squeeze(0) - return means - - -def distribution(dists, window_size): - _, topk_indices = dists.topk(k=window_size, dim=-2) - indices = topk_indices.transpose(-2, -1) - return indices.reshape(*indices.size()[:2], -1) - - -class Kmeans(nn.Module): - def __init__(self, num_heads, head_dim, num_clusters, ema_decay=0.999, commitment=1e-4): - super().__init__() - self.commitment = commitment - self.ema_decay = ema_decay - - self.register_buffer('means', torch.randn(num_heads, num_clusters, head_dim)) - self.register_buffer('initted', torch.tensor(False)) - self.num_new_means = 0 - self.new_means = None - - @torch.no_grad() - def init(self, x): - if self.initted: - return - _, h, _, d, device, _ = *x.shape, x.device, x.dtype - - num_clusters = self.means.shape[1] - - means = x.transpose(0, 1).contiguous().view(h, -1, d) - num_samples = means.shape[1] - - if num_samples >= num_clusters: - indices = torch.randperm(num_samples, device=device)[:num_clusters] - else: - indices = torch.randint(0, num_samples, (num_clusters,), device=device) - - means = means[:, indices] - - for _ in range(KMEAN_INIT_ITERS): - means = kmeans_iter(x, means) - - self.num_new_means = 0 - self.means.data.copy_(means) - self.initted.data.copy_(torch.tensor(True)) - - @torch.no_grad() - def update(self, new_means=None): - new_means = default(new_means, self.new_means) - assert exists(new_means), 'new kmeans has not been supplied' - ema_inplace(self.means, new_means, self.ema_decay) - - del self.new_means - self.new_means = None - self.num_new_means = 0 - - def forward(self, x, update_means=False): - self.init(x) - - b, dtype = x.shape[0], x.dtype - means = self.means.type(dtype) - x = F.normalize(x, 2, dim=-1).type(dtype) - - with torch.no_grad(): - dists, buckets = dists_and_buckets(x, means) - - routed_means = batched_index_select(expand_dim(means, 0, b), buckets) - loss = F.mse_loss(x, routed_means) * self.commitment - - if update_means: - with torch.no_grad(): - means = kmeans_iter(x, means, buckets) - self.new_means = ema(self.new_means, means, self.num_new_means / (self.num_new_means + 1)) - self.num_new_means += 1 - - return dists, loss - -# kmeans attention class - - -class KmeansAttention(nn.Module): - def __init__(self, num_clusters, window_size, num_heads, head_dim, causal=False, dropout=0., ema_decay=0.999, commitment=1e-4, context_window_size=None, receives_context=False, num_mem_kv=0, shared_qk=False): - super().__init__() - self.num_heads = num_heads - self.num_clusters = num_clusters - self.head_dim = head_dim - - self.window_size = window_size - self.context_window_size = default(context_window_size, window_size) - self.causal = causal - - self.shared_qk = shared_qk - self.receives_context = receives_context - self.kmeans = Kmeans(num_heads, head_dim, num_clusters, ema_decay, commitment) - self.dropout = nn.Dropout(dropout) - - self.num_mem_kv = max(num_mem_kv, 1 if causal and not shared_qk else 0) - self.mem_key = nn.Parameter(torch.randn(num_heads, num_clusters, self.num_mem_kv, head_dim)) - self.mem_value = nn.Parameter(torch.randn(num_heads, num_clusters, self.num_mem_kv, head_dim)) - - def forward(self, q, k, v, query_mask=None, key_mask=None, **kwargs): - b, h, t, d, kv_t, wsz, c_wsz, nc, device, dtype = *q.shape, k.shape[2], self.window_size, self.context_window_size, self.num_clusters, q.device, q.dtype - is_reverse = kwargs.pop('_reverse', False) - - out = torch.zeros_like(q, dtype=dtype) - - update_kmeans = self.training and not is_reverse - - key_mask = default(key_mask, query_mask) if not self.receives_context else key_mask - kv_wsz = wsz if not self.receives_context else c_wsz - - wsz = min(wsz, t) - kv_wsz = min(kv_wsz, kv_t) - - if not self.shared_qk or self.receives_context: - dists, aux_loss = self.kmeans(torch.cat((q, k), dim=2), update_kmeans) - q_dists, k_dists = split_at_index(2, t, dists) - indices = distribution(q_dists, wsz) - kv_indices = distribution(k_dists, kv_wsz) - else: - dists, aux_loss = self.kmeans(q, update_kmeans) - k = F.normalize(k, dim=-1).to(q) - indices = distribution(dists, wsz) - kv_indices = indices - - q = batched_index_select(q, indices) - k = batched_index_select(k, kv_indices) - v = batched_index_select(v, kv_indices) - - reshape_with_window = lambda x: x.reshape(b, h, nc, -1, d) - q, k, v = map(reshape_with_window, (q, k, v)) - - m_k, m_v = map(lambda x: expand_dim(x, 0, b).to(q), (self.mem_key, self.mem_value)) - k, v = map(lambda x: torch.cat(x, dim=3), ((m_k, k), (m_v, v))) - - dots = torch.einsum('bhnid,bhnjd->bhnij', q, k) * (d ** -0.5) - - mask_value = max_neg_value(dots) - - if exists(query_mask) or exists(key_mask): - query_mask = default(query_mask, lambda: torch.ones((b, t), device=device).bool()) - key_mask = default(key_mask, lambda: torch.ones((b, kv_t), device=device).bool()) - - q_mask = expand_dim(query_mask, 1, h).gather(2, indices) - kv_mask = expand_dim(key_mask, 1, h).gather(2, kv_indices) - q_mask, kv_mask = map(lambda t: t.reshape(b, h, nc, -1), (q_mask, kv_mask)) - mask = q_mask[:, :, :, :, None] * kv_mask[:, :, :, None, :] - mask = F.pad(mask, (self.num_mem_kv, 0), value=1) - dots.masked_fill_(~mask, mask_value) - del mask - - if self.causal: - q_mask, kv_mask = map(lambda t: t.reshape(b, h, nc, -1), (indices, kv_indices)) - mask = q_mask[:, :, :, :, None] >= kv_mask[:, :, :, None, :] - mask = F.pad(mask, (self.num_mem_kv, 0), value=1) - dots.masked_fill_(~mask, mask_value) - del mask - - if self.shared_qk: - q_mask, kv_mask = map(lambda t: t.reshape(b, h, nc, -1), (indices, kv_indices)) - mask = q_mask[:, :, :, :, None] == kv_mask[:, :, :, None, :] - mask = F.pad(mask, (self.num_mem_kv, 0), value=0) - dots.masked_fill_(mask, TOKEN_SELF_ATTN_VALUE) - del mask - - dots = dots.softmax(dim=-1) - dots = self.dropout(dots) - - bo = torch.einsum('bhcij,bhcjd->bhcid', dots, v) - so = torch.reshape(bo, (b, h, -1, bo.shape[-1])).type(dtype) - out = scatter_mean(out, so, indices.unsqueeze(-1).expand_as(so), -2) - return out, aux_loss - -# feedforward - - -class GELU_(nn.Module): - def forward(self, x): - return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) - - -GELU = nn.GELU if hasattr(nn, 'GELU') else GELU_ - - -class FeedForward(nn.Module): - def __init__(self, dim, mult=4, dropout=0., activation=None, glu=False): - super().__init__() - activation = default(activation, GELU) - - self.glu = glu - self.w1 = nn.Linear(dim, dim * mult * (2 if glu else 1)) - self.act = activation() - self.dropout = nn.Dropout(dropout) - self.w2 = nn.Linear(dim * mult, dim) - - def forward(self, x, **kwargs): - if not self.glu: - x = self.w1(x) - x = self.act(x) - else: - x, v = self.w1(x).chunk(2, dim=-1) - x = self.act(x) * v - - x = self.dropout(x) - x = self.w2(x) - return x - -# self attention - - -class SelfAttention(nn.Module): - def __init__(self, dim, max_seq_len, heads, local_attn_heads, window_size, dim_head=None, local_attn_window_size=None, local_attn_radius_blocks=1, causal=False, attn_dropout=0., dropout=0., kmeans_ema_decay=0.999, commitment_factor=1e-4, receives_context=False, context_window_size=None, rel_pos_emb=True, num_mem_kv=0, shared_qk=False, conv_query_kernel=9): - super().__init__() - assert dim_head or (dim % heads) == 0, 'hidden dimension must be divisible by number of heads' - assert (max_seq_len % window_size) == 0, 'maximum sequence length must be divisible by the target window size' - assert local_attn_heads <= heads, 'number of local attention heads must be less than total heads' - assert not (receives_context and local_attn_heads > 0), 'local attention cannot be used for self attention with context' - assert not (receives_context and causal), 'contextual attention layer cannot be causal' - - local_attn_window_size = default(local_attn_window_size, window_size) - context_window_size = default(context_window_size, window_size) - - self.shared_qk = shared_qk - self.receives_context = receives_context - self.heads = heads - self.local_attn_heads = local_attn_heads - self.global_attn_heads = heads - local_attn_heads - - self.causal = causal - self.window_size = window_size - - dim_head = default(dim_head, dim // heads) - dim_heads = dim_head * heads - self.dim_head = dim_head - - num_clusters = max_seq_len // window_size - - # local - - local_dim_heads = dim_head * self.local_attn_heads - - if self.local_attn_heads > 0: - rel_pos_emb_config = (dim_head, local_attn_heads) if rel_pos_emb else None - self.local_attn = LocalAttention(dim=dim_head, window_size=local_attn_window_size, causal=causal, dropout=attn_dropout, rel_pos_emb_config=rel_pos_emb_config, look_backward=local_attn_radius_blocks, look_forward=0 if causal else local_attn_radius_blocks) - self.local_to_qkv = nn.Linear(dim, 3 * local_dim_heads) - - # global - - global_dim_heads = dim_head * self.global_attn_heads - - if self.global_attn_heads > 0: - self.global_attn = KmeansAttention(num_clusters, window_size, self.global_attn_heads, dim_head, causal=causal, dropout=attn_dropout, ema_decay=kmeans_ema_decay, commitment=commitment_factor, receives_context=receives_context, num_mem_kv=num_mem_kv, shared_qk=shared_qk) - - self.to_q = nn.Sequential( - Rearrange('b n c -> b c n'), - DepthWiseConv1d(dim, global_dim_heads, conv_query_kernel, causal=causal), - Rearrange('b c n -> b n c') - ) - - self.to_v = nn.Linear(dim, global_dim_heads, bias=False) - - if not self.shared_qk: - self.to_k = nn.Linear(dim, global_dim_heads, bias=False) - - # out - - self.to_out = nn.Linear(dim_heads, dim, bias=False) - self.dropout = nn.Dropout(dropout) - - def forward(self, query, key, value, context=None, key_padding_mask=None, context_mask=None, pos_emb=None, **kwargs): - assert not (self.receives_context and not exists(context)), 'context must be passed if self attention is set to receive context' - input_mask = key_padding_mask - x = query.transpose(0, 1) - b, t, _, h, dh = *x.shape, self.heads, self.dim_head - has_local, has_global = map(lambda x: x > 0, (self.local_attn_heads, self.global_attn_heads)) - - split_heads = lambda v: reshape_dim(v, -1, (-1, dh)).transpose(1, 2).contiguous() - - if has_local: - local_qkv = self.local_to_qkv(x).chunk(3, dim=-1) - lq, lk, lv = map(split_heads, local_qkv) - - if has_global: - kv_input = x if not self.receives_context else context - - q, v = self.to_q(x), self.to_v(kv_input) - - if not self.shared_qk: - k = self.to_k(kv_input) - else: - k = self.to_q(kv_input) if self.receives_context else q - - q, k, v = map(split_heads, (q, k, v)) - - out = [] - total_loss = torch.tensor(0., requires_grad=True, **to(x)) - - if has_local: - local_out = self.local_attn(lq, lk, lv, input_mask=input_mask) - out.append(local_out) - - if has_global: - if not self.receives_context and exists(pos_emb): - q, k = apply_rotary_pos_emb(q, k, pos_emb) - - global_out, loss = self.global_attn(q, k, v, query_mask=input_mask, key_mask=context_mask) - total_loss = total_loss + loss - - out.append(global_out) - - out = torch.cat(out, dim=1) - out = out.reshape(b, h, t, -1).transpose(1, 2).reshape(b, t, -1) - out = self.dropout(out.transpose(0, 1)) - # out = self.to_out(out) - return out, total_loss diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/shuffled_word_order/README.md b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/shuffled_word_order/README.md deleted file mode 100644 index f20483849a8ca33bf349b57882a79155ba593bf1..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/shuffled_word_order/README.md +++ /dev/null @@ -1,84 +0,0 @@ -# Masked Language Modeling and the Distributional Hypothesis: Order Word Matters Pre-training for Little - -[https://arxiv.org/abs/2104.06644](https://arxiv.org/abs/2104.06644) - -## Introduction - -In this work, we pre-train [RoBERTa](../roberta) base on various word shuffled variants of BookWiki corpus (16GB). We observe that a word shuffled pre-trained model achieves surprisingly good scores on GLUE, PAWS and several parametric probing tasks. Please read our paper for more details on the experiments. - -## Pre-trained models - -| Model | Description | Download | -| ------------------------------------- | -------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | -| `roberta.base.orig` | RoBERTa (base) trained on natural corpus | [roberta.base.orig.tar.gz](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.orig.tar.gz) | -| `roberta.base.shuffle.n1` | RoBERTa (base) trained on n=1 gram sentence word shuffled data | [roberta.base.shuffle.n1.tar.gz](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.n1.tar.gz) | -| `roberta.base.shuffle.n2` | RoBERTa (base) trained on n=2 gram sentence word shuffled data | [roberta.base.shuffle.n2.tar.gz](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.n2.tar.gz) | -| `roberta.base.shuffle.n3` | RoBERTa (base) trained on n=3 gram sentence word shuffled data | [roberta.base.shuffle.n3.tar.gz](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.n3.tar.gz) | -| `roberta.base.shuffle.n4` | RoBERTa (base) trained on n=4 gram sentence word shuffled data | [roberta.base.shuffle.n4.tar.gz](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.n4.tar.gz) | -| `roberta.base.shuffle.512` | RoBERTa (base) trained on unigram 512 word block shuffled data | [roberta.base.shuffle.512.tar.gz](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.512.tar.gz) | -| `roberta.base.shuffle.corpus` | RoBERTa (base) trained on unigram corpus word shuffled data | [roberta.base.shuffle.corpus.tar.gz](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.corpus.tar.gz) | -| `roberta.base.shuffle.corpus_uniform` | RoBERTa (base) trained on unigram corpus word shuffled data, where all words are uniformly sampled | [roberta.base.shuffle.corpus_uniform.tar.gz](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.corpus_uniform.tar.gz) | -| `roberta.base.nopos` | RoBERTa (base) without positional embeddings, trained on natural corpus | [roberta.base.nopos.tar.gz](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.nopos.tar.gz) | - -## Results - -[GLUE (Wang et al, 2019)](https://gluebenchmark.com/) & [PAWS (Zhang et al, 2019)](https://github.com/google-research-datasets/paws) _(dev set, single model, single-task fine-tuning, median of 5 seeds)_ - -| name | CoLA | MNLI | MRPC | PAWS | QNLI | QQP | RTE | SST-2 | -| :----------------------------------- | ----: | ----: | ----: | ----: | ----: | ----: | ----: | ----: | -| `roberta.base.orig` | 61.4 | 86.11 | 89.19 | 94.46 | 92.53 | 91.26 | 74.64 | 93.92 | -| `roberta.base.shuffle.n1` | 35.15 | 82.64 | 86 | 89.97 | 89.02 | 91.01 | 69.02 | 90.47 | -| `roberta.base.shuffle.n2` | 54.37 | 83.43 | 86.24 | 93.46 | 90.44 | 91.36 | 70.83 | 91.79 | -| `roberta.base.shuffle.n3` | 48.72 | 83.85 | 86.36 | 94.05 | 91.69 | 91.24 | 70.65 | 92.02 | -| `roberta.base.shuffle.n4` | 58.64 | 83.77 | 86.98 | 94.32 | 91.69 | 91.4 | 70.83 | 92.48 | -| `roberta.base.shuffle.512` | 12.76 | 77.52 | 79.61 | 84.77 | 85.19 | 90.2 | 56.52 | 86.34 | -| `roberta.base.shuffle.corpus` | 0 | 71.9 | 70.52 | 58.52 | 71.11 | 85.52 | 53.99 | 83.35 | -| `roberta.base.shuffle.corpus_random` | 9.19 | 72.33 | 70.76 | 58.42 | 77.76 | 85.93 | 53.99 | 84.04 | -| `roberta.base.nopos` | 0 | 63.5 | 72.73 | 57.08 | 77.72 | 87.87 | 54.35 | 83.24 | - -For more results on probing tasks, please refer to [our paper](https://arxiv.org/abs/2104.06644). - -## Example Usage - -Follow the same usage as in [RoBERTa](https://github.com/pytorch/fairseq/tree/main/examples/roberta) to load and test your models: - -```python -# Download roberta.base.shuffle.n1 model -wget https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.n1.tar.gz -tar -xzvf roberta.base.shuffle.n1.tar.gz - -# Load the model in fairseq -from fairseq.models.roberta import RoBERTaModel -roberta = RoBERTaModel.from_pretrained('/path/to/roberta.base.shuffle.n1', checkpoint_file='model.pt') -roberta.eval() # disable dropout (or leave in train mode to finetune) -``` - -**Note**: The model trained without positional embeddings (`roberta.base.nopos`) is a modified `RoBERTa` model, where the positional embeddings are not used. Thus, the typical `from_pretrained` method on fairseq version of RoBERTa will not be able to load the above model weights. To do so, construct a new `RoBERTaModel` object by setting the flag `use_positional_embeddings` to `False` (or [in the latest code](https://github.com/pytorch/fairseq/blob/main/fairseq/models/roberta/model.py#L543), set `no_token_positional_embeddings` to `True`), and then load the individual weights. - -## Fine-tuning Evaluation - -We provide the trained fine-tuned models on MNLI here for each model above for quick evaluation (1 seed for each model). Please refer to [finetuning details](README.finetuning.md) for the parameters of these models. Follow [RoBERTa](https://github.com/pytorch/fairseq/tree/main/examples/roberta) instructions to evaluate these models. - -| Model | MNLI M Dev Accuracy | Link | -| :----------------------------------------- | :------------------ | :--------------------------------------------------------------------------------------------------------------- | -| `roberta.base.orig.mnli` | 86.14 | [Download](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.orig.mnli.tar.gz) | -| `roberta.base.shuffle.n1.mnli` | 82.55 | [Download](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.n1.mnli.tar.gz) | -| `roberta.base.shuffle.n2.mnli` | 83.21 | [Download](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.n2.mnli.tar.gz) | -| `roberta.base.shuffle.n3.mnli` | 83.89 | [Download](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.n3.mnli.tar.gz) | -| `roberta.base.shuffle.n4.mnli` | 84.00 | [Download](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.n4.mnli.tar.gz) | -| `roberta.base.shuffle.512.mnli` | 77.22 | [Download](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.512.mnli.tar.gz) | -| `roberta.base.shuffle.corpus.mnli` | 71.88 | [Download](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.corpus.mnli.tar.gz) | -| `roberta.base.shuffle.corpus_uniform.mnli` | 72.46 | [Download](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.corpus_uniform.mnli.tar.gz) | - -## Citation - -```bibtex -@misc{sinha2021masked, - title={Masked Language Modeling and the Distributional Hypothesis: Order Word Matters Pre-training for Little}, - author={Koustuv Sinha and Robin Jia and Dieuwke Hupkes and Joelle Pineau and Adina Williams and Douwe Kiela}, - year={2021}, - eprint={2104.06644}, - archivePrefix={arXiv}, - primaryClass={cs.CL} -} -``` diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/simultaneous_translation/utils/__init__.py b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/simultaneous_translation/utils/__init__.py deleted file mode 100644 index 1e9ce844f59a4211061392084cc81075e6bab19f..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/simultaneous_translation/utils/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import importlib -import os - - -# automatically import any Python files in the criterions/ directory -for file in sorted(os.listdir(os.path.dirname(__file__))): - if file.endswith(".py") and not file.startswith("_"): - module = file[: file.find(".py")] - importlib.import_module("examples.simultaneous_translation.utils." + module) diff --git a/spaces/OFA-Sys/OFA-Visual_Grounding/fairseq/examples/adaptive_span/adaptive_span_attention.py b/spaces/OFA-Sys/OFA-Visual_Grounding/fairseq/examples/adaptive_span/adaptive_span_attention.py deleted file mode 100644 index 07f757bb8e1a8a67b1124175ee338c8735aa8d65..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Visual_Grounding/fairseq/examples/adaptive_span/adaptive_span_attention.py +++ /dev/null @@ -1,160 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. -import math - -import torch -import torch.nn as nn -import torch.nn.functional as F - - -class AdaptiveMask(nn.Module): - """Soft masking function for adaptive size. - It masks out the last K values of an input. The masking value - goes from 1 to 0 gradually, so K can be learned with - back-propagation. - Args: - max_size: maximum size (i.e. input dimension) - ramp_size: size of the ramp going from 0 to 1 - init_val: initial size proportion not to be masked out - shape: learn multiple sizes independent of each other - """ - - def __init__(self, max_size, ramp_size, init_val=0, shape=(1,)): - nn.Module.__init__(self) - self._max_size = max_size - self._ramp_size = ramp_size - self.current_val = nn.Parameter(torch.zeros(*shape) + init_val) - mask_template = torch.linspace(1 - max_size, 0, steps=max_size) - self.register_buffer("mask_template", mask_template) - - def forward(self, x): - mask = self.mask_template.float() + self.current_val.float() * self._max_size - mask = mask / self._ramp_size + 1 - mask = mask.clamp(0, 1) - if x.size(-1) < self._max_size: - # the input could have been trimmed beforehand to save computation - mask = mask.narrow(-1, self._max_size - x.size(-1), x.size(-1)) - x = (x * mask).type_as(x) - return x - - def get_current_max_size(self, include_ramp=True): - current_size = math.ceil(self.current_val.max().item() * self._max_size) - if include_ramp: - current_size += self._ramp_size - current_size = max(0, min(self._max_size, current_size)) - return current_size - - def get_current_avg_size(self, include_ramp=True): - current_size = math.ceil( - self.current_val.float().mean().item() * self._max_size - ) - if include_ramp: - current_size += self._ramp_size - current_size = max(0, min(self._max_size, current_size)) - return current_size - - def clamp_param(self): - """this need to be called after each update""" - self.current_val.data.clamp_(0, 1) - - -class AdaptiveSpan(nn.Module): - """Adaptive attention span for Transformerself. - This module learns an attention span length from data for each - self-attention head. - Args: - attn_span: maximum attention span - adapt_span_loss: loss coefficient for the span length - adapt_span_ramp: length of the masking ramp - adapt_span_init: initial size ratio - adapt_span_cache: adapt cache size to reduce memory usage - """ - - def __init__( - self, - attn_span, - adapt_span_ramp, - adapt_span_init, - n_head, - adapt_span_layer, - **kargs - ): - nn.Module.__init__(self) - self._max_span = attn_span - self._n_head = n_head - self._adapt_span_layer = adapt_span_layer - if self._adapt_span_layer: - self._mask = AdaptiveMask( - max_size=self._max_span, - ramp_size=adapt_span_ramp, - init_val=adapt_span_init, - ) - else: - self._mask = AdaptiveMask( - max_size=self._max_span, - ramp_size=adapt_span_ramp, - init_val=adapt_span_init, - shape=(n_head, 1, 1), - ) - - def forward(self, attn, normalize=True): - """mask attention with the right span""" - # batch and head dimensions are merged together, so separate them first - self.clamp_param() - if self._adapt_span_layer: - attn = self._mask(attn) - else: - B = attn.size(0) # batch size - M = attn.size(1) # block size - attn = attn.reshape(B // self._n_head, self._n_head, M, -1) - attn = self._mask(attn) - attn = attn.view(B, M, -1) - return attn - - def get_trim_len(self): - """how much of memory can be trimmed to reduce computation""" - L = self._max_span - trim_len = min(L - 1, L - self._mask.get_current_max_size()) - # too fine granularity might be bad for the memory management - trim_len = math.floor(trim_len / 64) * 64 - return trim_len - - def trim_memory(self, query, key, value, key_pe): - """trim out unnecessary memory beforehand to reduce computation""" - trim_len = self.get_trim_len() - cache_size = key.size(1) - query.size(1) - trim_len_cache = trim_len - (self._max_span - cache_size) - if trim_len_cache > 0: - key = key[:, trim_len_cache:, :] - value = value[:, trim_len_cache:, :] - elif trim_len_cache < 0: - # cache is too short! this happens when validation resumes - # after a lot of updates. - key = F.pad(key, [0, 0, -trim_len_cache, 0]) - value = F.pad(value, [0, 0, -trim_len_cache, 0]) - if trim_len > 0: - if key_pe is not None: - key_pe = key_pe[:, :, trim_len:] - return key, value, key_pe - - def get_cache_size(self): - """determine how long the cache should be""" - trim_len = self.get_trim_len() - # give a buffer of 64 steps since a span might increase - # in future updates - return min(self._max_span, self._max_span - trim_len + 64) - - def get_loss(self): - """a loss term for regularizing the span length""" - return self._max_span * self._mask.current_val.float().mean() - - def get_current_max_span(self): - return self._mask.get_current_max_size() - - def get_current_avg_span(self): - return self._mask.get_current_avg_size() - - def clamp_param(self): - self._mask.clamp_param() diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/wav2vec/unsupervised/kaldi_self_train/st/local/score.sh b/spaces/OFA-Sys/OFA-vqa/fairseq/examples/wav2vec/unsupervised/kaldi_self_train/st/local/score.sh deleted file mode 100644 index cb5bbb7277bfb9f2d5440da0514bf7b16da8140d..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/wav2vec/unsupervised/kaldi_self_train/st/local/score.sh +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env bash -# Copyright 2012 Johns Hopkins University (Author: Daniel Povey) -# 2014 Guoguo Chen -# Apache 2.0 - -[ -f ./path.sh ] && . ./path.sh - -# begin configuration section. -cmd=run.pl -stage=0 -decode_mbr=true -word_ins_penalty=0.0,0.5,1.0 -min_lmwt=7 -max_lmwt=17 -iter=final -#end configuration section. - -[ -f ./path.sh ] && . ./path.sh -. parse_options.sh || exit 1; - -if [ $# -ne 3 ]; then - echo "Usage: local/score.sh [--cmd (run.pl|queue.pl...)] " - echo " Options:" - echo " --cmd (run.pl|queue.pl...) # specify how to run the sub-processes." - echo " --stage (0|1|2) # start scoring script from part-way through." - echo " --decode_mbr (true/false) # maximum bayes risk decoding (confusion network)." - echo " --min_lmwt # minumum LM-weight for lattice rescoring " - echo " --max_lmwt # maximum LM-weight for lattice rescoring " - exit 1; -fi - -data=$1 -lang_or_graph=$2 -dir=$3 - -symtab=$lang_or_graph/words.txt - -for f in $symtab $dir/lat.1.gz $data/text; do - [ ! -f $f ] && echo "score.sh: no such file $f" && exit 1; -done - -mkdir -p $dir/scoring/log - -cat $data/text | sed 's:::g' | sed 's:::g' > $dir/scoring/test_filt.txt - -for wip in $(echo $word_ins_penalty | sed 's/,/ /g'); do - $cmd LMWT=$min_lmwt:$max_lmwt $dir/scoring/log/best_path.LMWT.$wip.log \ - lattice-scale --inv-acoustic-scale=LMWT "ark:gunzip -c $dir/lat.*.gz|" ark:- \| \ - lattice-add-penalty --word-ins-penalty=$wip ark:- ark:- \| \ - lattice-best-path --word-symbol-table=$symtab \ - ark:- ark,t:$dir/scoring/LMWT.$wip.tra || exit 1; -done - -# Note: the double level of quoting for the sed command -for wip in $(echo $word_ins_penalty | sed 's/,/ /g'); do - $cmd LMWT=$min_lmwt:$max_lmwt $dir/scoring/log/score.LMWT.$wip.log \ - cat $dir/scoring/LMWT.$wip.tra \| \ - utils/int2sym.pl -f 2- $symtab \| sed 's:\::g' \| \ - compute-wer --text --mode=present \ - ark:$dir/scoring/test_filt.txt ark,p:- ">&" $dir/wer_LMWT_$wip || exit 1; -done - -exit 0; diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/logging/metrics.py b/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/logging/metrics.py deleted file mode 100644 index 58c2fb64e186ed9d5e9a06c73194d98a21bb7560..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/logging/metrics.py +++ /dev/null @@ -1,314 +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. -""" -A standalone module for aggregating metrics. - -Metrics can be logged from anywhere using the `log_*` functions defined -in this module. The logged values will be aggregated dynamically based -on the aggregation context in which the logging occurs. See the -:func:`aggregate` context manager for more details. -""" - -import contextlib -import uuid -from collections import defaultdict -from typing import Callable, List, Optional - -from .meters import * - - -# Aggregation contexts are considered "active" when inside the scope -# created by the :func:`aggregate` context manager. -_aggregators = OrderedDict() -_active_aggregators = OrderedDict() -_active_aggregators_cnt = defaultdict(lambda: 0) - - -def reset() -> None: - """Reset all metrics aggregators.""" - _aggregators.clear() - _active_aggregators.clear() - _active_aggregators_cnt.clear() - - # The "default" aggregator observes all logged values. - _aggregators["default"] = MetersDict() - _active_aggregators["default"] = _aggregators["default"] - _active_aggregators_cnt["default"] = 1 - - -reset() - - -@contextlib.contextmanager -def aggregate(name: Optional[str] = None, new_root: bool = False): - """Context manager to aggregate metrics under a given name. - - Aggregations can be nested. If *new_root* is ``False``, then logged - metrics will be recorded along the entire stack of nested - aggregators, including a global "default" aggregator. If *new_root* - is ``True``, then this aggregator will be the root of a new - aggregation stack, thus bypassing any parent aggregators. - - Note that aggregation contexts are uniquely identified by their - *name* (e.g., train, valid). Creating a context with an existing - name will reuse the corresponding :class:`MetersDict` instance. - If no name is given, then a temporary aggregator will be created. - - Usage:: - - with metrics.aggregate("train"): - for step, batch in enumerate(epoch): - with metrics.aggregate("train_inner") as agg: - metrics.log_scalar("loss", get_loss(batch)) - if step % log_interval == 0: - print(agg.get_smoothed_value("loss")) - agg.reset() - print(metrics.get_smoothed_values("train")["loss"]) - - Args: - name (str): name of the aggregation. Defaults to a - random/temporary name if not given explicitly. - new_root (bool): make this aggregation the root of a new - aggregation stack. - """ - if name is None: - # generate a temporary name - name = str(uuid.uuid4()) - assert name not in _aggregators - agg = MetersDict() - else: - assert name != "default" - agg = _aggregators.setdefault(name, MetersDict()) - - if new_root: - backup_aggregators = _active_aggregators.copy() - _active_aggregators.clear() - backup_aggregators_cnt = _active_aggregators_cnt.copy() - _active_aggregators_cnt.clear() - - _active_aggregators[name] = agg - _active_aggregators_cnt[name] += 1 - - yield agg - - _active_aggregators_cnt[name] -= 1 - if _active_aggregators_cnt[name] == 0 and name in _active_aggregators: - del _active_aggregators[name] - - if new_root: - _active_aggregators.clear() - _active_aggregators.update(backup_aggregators) - _active_aggregators_cnt.clear() - _active_aggregators_cnt.update(backup_aggregators_cnt) - - -def get_active_aggregators() -> List[MetersDict]: - return list(_active_aggregators.values()) - - -def log_scalar( - key: str, - value: float, - weight: float = 1, - priority: int = 10, - round: Optional[int] = None, -): - """Log a scalar value. - - Args: - key (str): name of the field to log - value (float): value to log - weight (float): weight that this value contributes to the average. - A weight of 0 will always log the latest value. - priority (int): smaller values are logged earlier in the output - round (Optional[int]): number of digits to round to when displaying - """ - for agg in get_active_aggregators(): - if key not in agg: - agg.add_meter(key, AverageMeter(round=round), priority) - agg[key].update(value, weight) - -def log_scalar_sum( - key: str, - value: float, - priority: int = 10, - round: Optional[int] = None, -): - """Log a scalar value that is summed for reporting. - - Args: - key (str): name of the field to log - value (float): value to log - priority (int): smaller values are logged earlier in the output - round (Optional[int]): number of digits to round to when displaying - """ - for agg in get_active_aggregators(): - if key not in agg: - agg.add_meter(key, SumMeter(round=round), priority) - agg[key].update(value) - - -def log_derived(key: str, fn: Callable[[MetersDict], float], priority: int = 20): - """Log a scalar value derived from other meters. - - Args: - key (str): name of the field to log - fn (Callable[[MetersDict], float]): function that takes a single - argument *meters* and returns the derived value - priority (int): smaller values are logged earlier in the output - """ - for agg in get_active_aggregators(): - if key not in agg: - agg.add_meter(key, MetersDict._DerivedMeter(fn), priority) - - -def log_speed( - key: str, - value: float, - priority: int = 30, - round: Optional[int] = None, -): - """Log the rate of some quantity per second. - - Args: - key (str): name of the field to log - value (float): value to log - priority (int): smaller values are logged earlier in the output - round (Optional[int]): number of digits to round to when displaying - """ - for agg in get_active_aggregators(): - if key not in agg: - agg.add_meter(key, TimeMeter(round=round), priority) - agg[key].reset() # reset meter on the first call - else: - agg[key].update(value) - - -def log_start_time(key: str, priority: int = 40, round: Optional[int] = None): - """Log the duration of some event in seconds. - - The duration will be computed once :func:`log_stop_time` is called. - - Args: - key (str): name of the field to log - priority (int): smaller values are logged earlier in the output - round (Optional[int]): number of digits to round to when displaying - """ - for agg in get_active_aggregators(): - if key not in agg: - agg.add_meter(key, StopwatchMeter(round=round), priority) - agg[key].start() - - -def log_stop_time(key: str, weight: float = 0.0, prehook=None): - """Log the duration of some event in seconds. - - The duration will be computed since :func:`log_start_time` was called. - Set weight > 0 to report the average time instead of the sum. - - Args: - key (str): name of the field to log - weight (float): weight that this time contributes to the average - prehook (function, no arguments): will be called before the timer - is stopped. For example, use prehook=torch.cuda.synchronize to - make sure all gpu operations are done before timer is stopped. - """ - for agg in get_active_aggregators(): - if key in agg: - agg[key].stop(weight, prehook) - - -def log_custom( - new_meter_fn: Callable[[], Meter], - key: str, - *args, - priority: int = 50, - **kwargs, -): - """Log using a custom Meter. - - Any extra *args* or *kwargs* will be passed through to the Meter's - *update* method. - - Args: - new_meter_fn (Callable[[], Meter]): function that returns a new - Meter instance - key (str): name of the field to log - priority (int): smaller values are logged earlier in the output - """ - for agg in get_active_aggregators(): - if key not in agg: - agg.add_meter(key, new_meter_fn(), priority) - agg[key].update(*args, **kwargs) - - -def reset_meter(name: str, key: str) -> None: - """Reset Meter instance aggregated under a given *name* and *key*.""" - meter = get_meter(name, key) - if meter is not None: - meter.reset() - - -def reset_meters(name: str) -> None: - """Reset Meter instances aggregated under a given *name*.""" - meters = get_meters(name) - if meters is not None: - meters.reset() - - -def get_meter(name: str, key: str) -> Meter: - """Get a single Meter instance aggregated under *name* and *key*. - - Returns: - Meter or None if no metrics have been logged under *name* and *key*. - """ - if name not in _aggregators: - return None - return _aggregators[name].get(key, None) - - -def get_meters(name: str) -> MetersDict: - """Get Meter instances aggregated under a given *name*. - - Returns: - MetersDict or None if no metrics have been logged under *name*. - """ - return _aggregators.get(name, None) - - -def get_smoothed_value(name: str, key: str) -> float: - """Get a single smoothed value. - - Raises: - KeyError: if no metrics have been logged under *name* and *key*. - """ - return _aggregators[name].get_smoothed_value(key) - - -def get_smoothed_values(name: str) -> Dict[str, float]: - """Get smoothed values aggregated under a given *name*. - - Raises: - KeyError: if no metrics have been logged under *name*. - """ - return _aggregators[name].get_smoothed_values() - - -def state_dict(): - return OrderedDict([(name, agg.state_dict()) for name, agg in _aggregators.items()]) - - -def load_state_dict(state_dict): - for name, agg_state in state_dict.items(): - _aggregators[name] = MetersDict() - _aggregators[name].load_state_dict(agg_state) - - -def xla_metrics_report(): - try: - import torch_xla.debug.metrics as met - print(met.metrics_report()) - except ImportError: - return diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/optim/shard.py b/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/optim/shard.py deleted file mode 100644 index 9d7f2eb9e5de6086fe2435d432bde7521ebb8155..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/optim/shard.py +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -from typing import Any, Dict - -from fairseq.distributed import utils - - -try: - from fairscale.optim import OSS - - _has_fairscale = True -except ImportError: - _has_fairscale = False - - -def shard_(optimizer, group): - if not _has_fairscale: - raise ImportError( - "\n\nPlease install the fairscale package:" "\n\n pip install fairscale" - ) - - class FairseqOSS(OSS): - @property - def disable_mem_eff_fp16_loading_hack(self): - return True - - def __getattr__(self, name): - if name.startswith("supports") and hasattr(self.optim, name): - return getattr(self.optim, name) - raise AttributeError( - "'FairseqOSS' object has no attribute {0!r}".format(name) - ) - - def broadcast_global_state_dict( - self, state_dict: Dict[str, Any] - ) -> Dict[str, Any]: - """ - Broadcasts the entire state_dict to all other ranks - each rank is responsible to load their own partition of data - """ - return utils.broadcast_object( - state_dict, - src_rank=0, - group=self.group, - ) - - torch_optimizer = optimizer.optimizer - optim_cls = type(torch_optimizer) - - optimizer.optimizer = FairseqOSS( - torch_optimizer.param_groups, - optim_cls, - group=group, - **optimizer.optimizer_config - ) diff --git a/spaces/OptimalScale/Robin-7b/lmflow/utils/data_utils.py b/spaces/OptimalScale/Robin-7b/lmflow/utils/data_utils.py deleted file mode 100644 index 25ff71ef3d5e953e7dd26fb595e5b35a3b0a273e..0000000000000000000000000000000000000000 --- a/spaces/OptimalScale/Robin-7b/lmflow/utils/data_utils.py +++ /dev/null @@ -1,212 +0,0 @@ -"""The program includes several functions: setting a random seed, -loading data from a JSON file, batching data, and extracting answers from generated text. -""" - -import random -import numpy as np -import torch -import json -import re -def set_random_seed(seed: int): - """ - Set the random seed for `random`, `numpy`, `torch`, `torch.cuda`. - - Parameters - ------------ - seed : int - The default seed. - - """ - random.seed(seed) - np.random.seed(seed) - torch.manual_seed(seed) - if torch.cuda.is_available(): - torch.cuda.manual_seed_all(seed) - -def load_data(file_name: str): - """ - Load data with file name. - - Parameters - ------------ - file_name : str. - The dataset file name. - - Returns - ------------ - inputs : list. - The input texts of the dataset. - outputs : list. - The output texts file datasets. - len : int. - The length of the dataset. - """ - inputs = [] - outputs = [] - type = "" - with open(file_name, encoding='utf-8') as f: - json_data = json.load(f) - type = json_data["type"] - for line in json_data["instances"]: - inputs.append(line["input"]) - outputs.append(line["output"]) - - print(f"load dataset {file_name} success.\n") - print(f"Type : {type}, datasize : {len(outputs)}") - - return inputs, outputs, len(outputs) - -def batchlize(examples: list, batch_size: int, random_shuffle: bool): - """ - Convert examples to a dataloader. - - Parameters - ------------ - examples : list. - Data list. - batch_size : int. - - random_shuffle : bool - If true, the dataloader shuffle the training data. - - Returns - ------------ - dataloader: - Dataloader with batch generator. - """ - size = 0 - dataloader = [] - length = len(examples) - if (random_shuffle): - random.shuffle(examples) - while size < length: - if length - size > batch_size: - dataloader.append(examples[size : size+batch_size]) - size += batch_size - else: - dataloader.append(examples[size : size+(length-size)]) - size += (length - size) - return dataloader - - - -def answer_extraction(response, answer_type=None): #use this funtion to extract answers from generated text - - """ - Use this funtion to extract answers from generated text - - Parameters - ------------ - args : - Arguments. - response : str - plain string response. - - - Returns - ------------ - answer: - Decoded answer (such as A, B, C, D, E for mutiple-choice QA). - """ - - # temp = response["generated_text"] - temp = response - if answer_type in ("gsm8k", "svamp", "asdiv", "addsub", "singleeq", "multiarith", "math"): - temp = temp.replace(",", "") - temp = [s for s in re.findall(r'-?\d+\.?\d*', temp)] - elif answer_type in ("aqua", "csqa", "multiple_choice"): - temp = re.findall(r'A|B|C|D|E', temp) - elif answer_type in ("strategyqa", "coin_flip"): - temp = temp.lower() - temp = re.sub("\"|\'|\n|\.|\s|\:|\,"," ", temp) - temp = temp.split(" ") - temp = [i for i in temp if i in ("yes", "no")] - elif answer_type in ("last_letters"): - temp = re.sub("\"|\'|\n|\.|\s","", temp) - temp = [temp] - elif answer_type in ("pubmedqa", "binary_choice"): - # pattern = "Output: (yes|no|maybe)" - # sttr = re.search(pattern, temp) - # answer = sttr.group(0)[8:] if sttr is not None else "N/A" - pattern = "(answer|Answer|ANSWER|output|Output|OUTPUT|A): \(*(yes|Yes|YES|no|No|NO|maybe|Maybe|MAYBE)" - sttr = re.search(pattern, temp) - if sttr is not None: - mid_answer = sttr.group(0) - mid_answer = mid_answer.split(":")[-1].strip() - answer = mid_answer.lower() - else: - pattern = "(yes|Yes|YES|no|No|NO|maybe|Maybe|MAYBE)(\.|\s)" - sttr = re.search(pattern, temp) - if sttr is not None: - answer = sttr.group(0)[:-1].lower() - else: - answer = "N/A" - return answer - elif answer_type == "medmcqa": - # pattern = "Output: (A|B|C|D)." - # sttr = re.search(pattern, temp) - # answer = sttr.group(0)[8:-1].lower() if sttr is not None else "N/A" - pattern = "(answer|Answer|ANSWER|output|Output|OUTPUT|A): \(*(A|B|C|D|a|b|c|d)" - sttr = re.search(pattern, temp) - if sttr is not None: - mid_answer = sttr.group(0) - answer = mid_answer[-1].lower() - else: - pattern = "\(*(A|B|C|D|a|b|c|d)\)*(\.|\s)" - sttr = re.search(pattern, temp) - if sttr is not None: - if '(' in sttr.group(0): - answer = sttr.group(0)[1].lower() - else: - answer = sttr.group(0)[0].lower() - else: - answer = "N/A" - return answer - - elif answer_type == "usmle": - # pattern = "Output: (A|B|C|D)." - # sttr = re.search(pattern, temp) - # answer = sttr.group(0)[8:-1].lower() if sttr is not None else "N/A" - pattern = "(Answer|Output|A): \(*(A|B|C|D|a|b|c|d)" - sttr = re.search(pattern, temp) - if sttr is not None: - mid_answer = sttr.group(0) - answer = mid_answer[-1].lower() - else: - pattern = "\(*(A|B|C|D|a|b|c|d)\)*(\.|\s)" - sttr = re.search(pattern, temp) - if sttr is not None: - if '(' in sttr.group(0): - answer = sttr.group(0)[1].lower() - else: - answer = sttr.group(0)[0].lower() - else: - answer = "N/A" - return answer - elif answer_type == "text": - return response - else: - raise NotImplementedError(f"Unsupported answer type: {answer_type}") - - if len(temp) != 0: - answer = temp[-1] - # if there is . at the end of answer, remove it - # e.g. answer = 64. - if answer != "": - if answer[-1] == ".": - answer = answer[:-1] - - # round the answer to nearest integer - if answer_type in ("gsm8k", "svamp"): - try: - answer = str(round(float(answer))) - except: - answer = "" # no sol or sol doesn't have valid format - elif answer_type in ("last_letters"): - try: - answer = answer[-args.concat_length:] - except: - answer = "" - else: - answer = "" - return answer diff --git a/spaces/OptimalScale/Robin-7b/lmflow/version.py b/spaces/OptimalScale/Robin-7b/lmflow/version.py deleted file mode 100644 index b3c06d488393abb3b3829e5590d42409c995b4cf..0000000000000000000000000000000000000000 --- a/spaces/OptimalScale/Robin-7b/lmflow/version.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = "0.0.1" \ No newline at end of file diff --git a/spaces/OptorAI/site/index.html b/spaces/OptorAI/site/index.html deleted file mode 100644 index d2eb5b58bf79f513862e21db3f47594b1b35124a..0000000000000000000000000000000000000000 --- a/spaces/OptorAI/site/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - OPTOR.redirect - - - - -

OPTOR.redirect to our site

-Redirecting in 2 seconds... - \ No newline at end of file diff --git a/spaces/Osborn-bh/ChatGLM3-6B-Osborn/openai_api.py b/spaces/Osborn-bh/ChatGLM3-6B-Osborn/openai_api.py deleted file mode 100644 index 7d372dc9cd1e085a04f9d94c25302e0843078338..0000000000000000000000000000000000000000 --- a/spaces/Osborn-bh/ChatGLM3-6B-Osborn/openai_api.py +++ /dev/null @@ -1,229 +0,0 @@ -# coding=utf-8 -# Implements API for ChatGLM3-6B in OpenAI's format. (https://platform.openai.com/docs/api-reference/chat) -# Usage: python openai_api.py -# Visit http://localhost:8000/docs for documents. - - -import json -import time -from contextlib import asynccontextmanager -from typing import List, Literal, Optional, Union - -import torch -import uvicorn -from fastapi import FastAPI, HTTPException -from fastapi.middleware.cors import CORSMiddleware -from pydantic import BaseModel, Field -from sse_starlette.sse import EventSourceResponse -from transformers import AutoTokenizer, AutoModel - -from utils import process_response, generate_chatglm3, generate_stream_chatglm3 - - -@asynccontextmanager -async def lifespan(app: FastAPI): # collects GPU memory - yield - if torch.cuda.is_available(): - torch.cuda.empty_cache() - torch.cuda.ipc_collect() - - -app = FastAPI(lifespan=lifespan) - -app.add_middleware( - CORSMiddleware, - allow_origins=["*"], - allow_credentials=True, - allow_methods=["*"], - allow_headers=["*"], -) - - -class ModelCard(BaseModel): - id: str - object: str = "model" - created: int = Field(default_factory=lambda: int(time.time())) - owned_by: str = "owner" - root: Optional[str] = None - parent: Optional[str] = None - permission: Optional[list] = None - - -class ModelList(BaseModel): - object: str = "list" - data: List[ModelCard] = [] - - -class ChatMessage(BaseModel): - role: Literal["user", "assistant", "system", "observation"] - content: str = None - metadata: Optional[str] = None - tools: Optional[List[dict]] = None - - -class DeltaMessage(BaseModel): - role: Optional[Literal["user", "assistant", "system"]] = None - content: Optional[str] = None - - -class ChatCompletionRequest(BaseModel): - model: str - messages: List[ChatMessage] - temperature: Optional[float] = 0.7 - top_p: Optional[float] = 1.0 - max_tokens: Optional[int] = None - stop: Optional[Union[str, List[str]]] = None - stream: Optional[bool] = False - - # Additional parameters support for stop generation - stop_token_ids: Optional[List[int]] = None - repetition_penalty: Optional[float] = 1.1 - - # Additional parameters supported by tools - return_function_call: Optional[bool] = False - - -class ChatCompletionResponseChoice(BaseModel): - index: int - message: ChatMessage - finish_reason: Literal["stop", "length", "function_call"] - history: Optional[List[dict]] = None - - -class ChatCompletionResponseStreamChoice(BaseModel): - index: int - delta: DeltaMessage - finish_reason: Optional[Literal["stop", "length"]] - - -class UsageInfo(BaseModel): - prompt_tokens: int = 0 - total_tokens: int = 0 - completion_tokens: Optional[int] = 0 - - -class ChatCompletionResponse(BaseModel): - model: str - object: Literal["chat.completion", "chat.completion.chunk"] - choices: List[Union[ChatCompletionResponseChoice, ChatCompletionResponseStreamChoice]] - created: Optional[int] = Field(default_factory=lambda: int(time.time())) - usage: Optional[UsageInfo] = None - - -@app.get("/v1/models", response_model=ModelList) -async def list_models(): - model_card = ModelCard(id="gpt-3.5-turbo") - return ModelList(data=[model_card]) - - -@app.post("/v1/chat/completions", response_model=ChatCompletionResponse) -async def create_chat_completion(request: ChatCompletionRequest): - global model, tokenizer - - if request.messages[-1].role == "assistant": - raise HTTPException(status_code=400, detail="Invalid request") - - with_function_call = bool(request.messages[0].role == "system" and request.messages[0].tools is not None) - - # stop settings - request.stop = request.stop or [] - if isinstance(request.stop, str): - request.stop = [request.stop] - - request.stop_token_ids = request.stop_token_ids or [] - - gen_params = dict( - messages=request.messages, - temperature=request.temperature, - top_p=request.top_p, - max_tokens=request.max_tokens or 1024, - echo=False, - stream=request.stream, - stop_token_ids=request.stop_token_ids, - stop=request.stop, - repetition_penalty=request.repetition_penalty, - with_function_call=with_function_call, - ) - - if request.stream: - generate = predict(request.model, gen_params) - return EventSourceResponse(generate, media_type="text/event-stream") - - response = generate_chatglm3(model, tokenizer, gen_params) - usage = UsageInfo() - - finish_reason, history = "stop", None - if with_function_call and request.return_function_call: - history = [m.dict(exclude_none=True) for m in request.messages] - content, history = process_response(response["text"], history) - if isinstance(content, dict): - message, finish_reason = ChatMessage( - role="assistant", - content=json.dumps(content, ensure_ascii=False), - ), "function_call" - else: - message = ChatMessage(role="assistant", content=content) - else: - message = ChatMessage(role="assistant", content=response["text"]) - - choice_data = ChatCompletionResponseChoice( - index=0, - message=message, - finish_reason=finish_reason, - history=history - ) - - task_usage = UsageInfo.parse_obj(response["usage"]) - for usage_key, usage_value in task_usage.dict().items(): - setattr(usage, usage_key, getattr(usage, usage_key) + usage_value) - - return ChatCompletionResponse(model=request.model, choices=[choice_data], object="chat.completion", usage=usage) - - -async def predict(model_id: str, params: dict): - global model, tokenizer - - choice_data = ChatCompletionResponseStreamChoice( - index=0, - delta=DeltaMessage(role="assistant"), - finish_reason=None - ) - chunk = ChatCompletionResponse(model=model_id, choices=[choice_data], object="chat.completion.chunk") - yield "{}".format(chunk.json(exclude_unset=True, ensure_ascii=False)) - - previous_text = "" - for new_response in generate_stream_chatglm3(model, tokenizer, params): - decoded_unicode = new_response["text"] - delta_text = decoded_unicode[len(previous_text):] - previous_text = decoded_unicode - - if len(delta_text) == 0: - delta_text = None - - choice_data = ChatCompletionResponseStreamChoice( - index=0, - delta=DeltaMessage(content=delta_text), - finish_reason=None - ) - chunk = ChatCompletionResponse(model=model_id, choices=[choice_data], object="chat.completion.chunk") - yield "{}".format(chunk.json(exclude_unset=True, ensure_ascii=False)) - - choice_data = ChatCompletionResponseStreamChoice( - index=0, - delta=DeltaMessage(), - finish_reason="stop" - ) - chunk = ChatCompletionResponse(model=model_id, choices=[choice_data], object="chat.completion.chunk") - yield "{}".format(chunk.json(exclude_unset=True, ensure_ascii=False)) - yield '[DONE]' - - -if __name__ == "__main__": - tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm3-6b", trust_remote_code=True) - model = AutoModel.from_pretrained("THUDM/chatglm3-6b", trust_remote_code=True).cuda() - # 多显卡支持,使用下面两行代替上面一行,将num_gpus改为你实际的显卡数量 - # from utils import load_model_on_gpus - # model = load_model_on_gpus("THUDM/chatglm3-6b", num_gpus=2) - model = model.eval() - - uvicorn.run(app, host='0.0.0.0', port=8000, workers=1) diff --git a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/configs/_base_/models/upernet_r50.py b/spaces/PAIR/Text2Video-Zero/annotator/uniformer/configs/_base_/models/upernet_r50.py deleted file mode 100644 index 10974962fdd7136031fd06de1700f497d355ceaa..0000000000000000000000000000000000000000 --- a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/configs/_base_/models/upernet_r50.py +++ /dev/null @@ -1,44 +0,0 @@ -# model settings -norm_cfg = dict(type='SyncBN', requires_grad=True) -model = dict( - type='EncoderDecoder', - pretrained='open-mmlab://resnet50_v1c', - backbone=dict( - type='ResNetV1c', - depth=50, - num_stages=4, - out_indices=(0, 1, 2, 3), - dilations=(1, 1, 1, 1), - strides=(1, 2, 2, 2), - norm_cfg=norm_cfg, - norm_eval=False, - style='pytorch', - contract_dilation=True), - decode_head=dict( - type='UPerHead', - in_channels=[256, 512, 1024, 2048], - in_index=[0, 1, 2, 3], - pool_scales=(1, 2, 3, 6), - channels=512, - dropout_ratio=0.1, - num_classes=19, - norm_cfg=norm_cfg, - align_corners=False, - loss_decode=dict( - type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), - auxiliary_head=dict( - type='FCNHead', - in_channels=1024, - in_index=2, - channels=256, - num_convs=1, - concat_input=False, - dropout_ratio=0.1, - num_classes=19, - norm_cfg=norm_cfg, - align_corners=False, - loss_decode=dict( - type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.4)), - # model training and testing settings - train_cfg=dict(), - test_cfg=dict(mode='whole')) diff --git a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmcv/cnn/bricks/drop.py b/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmcv/cnn/bricks/drop.py deleted file mode 100644 index b7b4fccd457a0d51fb10c789df3c8537fe7b67c1..0000000000000000000000000000000000000000 --- a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmcv/cnn/bricks/drop.py +++ /dev/null @@ -1,65 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import torch -import torch.nn as nn - -from annotator.uniformer.mmcv import build_from_cfg -from .registry import DROPOUT_LAYERS - - -def drop_path(x, drop_prob=0., training=False): - """Drop paths (Stochastic Depth) per sample (when applied in main path of - residual blocks). - - We follow the implementation - https://github.com/rwightman/pytorch-image-models/blob/a2727c1bf78ba0d7b5727f5f95e37fb7f8866b1f/timm/models/layers/drop.py # noqa: E501 - """ - if drop_prob == 0. or not training: - return x - keep_prob = 1 - drop_prob - # handle tensors with different dimensions, not just 4D tensors. - shape = (x.shape[0], ) + (1, ) * (x.ndim - 1) - random_tensor = keep_prob + torch.rand( - shape, dtype=x.dtype, device=x.device) - output = x.div(keep_prob) * random_tensor.floor() - return output - - -@DROPOUT_LAYERS.register_module() -class DropPath(nn.Module): - """Drop paths (Stochastic Depth) per sample (when applied in main path of - residual blocks). - - We follow the implementation - https://github.com/rwightman/pytorch-image-models/blob/a2727c1bf78ba0d7b5727f5f95e37fb7f8866b1f/timm/models/layers/drop.py # noqa: E501 - - Args: - drop_prob (float): Probability of the path to be zeroed. Default: 0.1 - """ - - def __init__(self, drop_prob=0.1): - super(DropPath, self).__init__() - self.drop_prob = drop_prob - - def forward(self, x): - return drop_path(x, self.drop_prob, self.training) - - -@DROPOUT_LAYERS.register_module() -class Dropout(nn.Dropout): - """A wrapper for ``torch.nn.Dropout``, We rename the ``p`` of - ``torch.nn.Dropout`` to ``drop_prob`` so as to be consistent with - ``DropPath`` - - Args: - drop_prob (float): Probability of the elements to be - zeroed. Default: 0.5. - inplace (bool): Do the operation inplace or not. Default: False. - """ - - def __init__(self, drop_prob=0.5, inplace=False): - super().__init__(p=drop_prob, inplace=inplace) - - -def build_dropout(cfg, default_args=None): - """Builder for drop out layers.""" - return build_from_cfg(cfg, DROPOUT_LAYERS, default_args) diff --git a/spaces/PKaushik/humandetect/yolov6/utils/nms.py b/spaces/PKaushik/humandetect/yolov6/utils/nms.py deleted file mode 100644 index 9c61b7cc4567b03cd2977b505b89c76e0e1d6769..0000000000000000000000000000000000000000 --- a/spaces/PKaushik/humandetect/yolov6/utils/nms.py +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -# The code is based on -# https://github.com/ultralytics/yolov5/blob/master/utils/general.py - -import os -import time -import numpy as np -import cv2 -import torch -import torchvision - - -# Settings -torch.set_printoptions(linewidth=320, precision=5, profile='long') -np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5 -cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader) -os.environ['NUMEXPR_MAX_THREADS'] = str(min(os.cpu_count(), 8)) # NumExpr max threads - - -def xywh2xyxy(x): - # Convert boxes with shape [n, 4] from [x, y, w, h] to [x1, y1, x2, y2] where x1y1 is top-left, x2y2=bottom-right - y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) - y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x - y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y - y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x - y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y - return y - - -def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False, max_det=300): - """Runs Non-Maximum Suppression (NMS) on inference results. - This code is borrowed from: https://github.com/ultralytics/yolov5/blob/47233e1698b89fc437a4fb9463c815e9171be955/utils/general.py#L775 - Args: - prediction: (tensor), with shape [N, 5 + num_classes], N is the number of bboxes. - conf_thres: (float) confidence threshold. - iou_thres: (float) iou threshold. - classes: (None or list[int]), if a list is provided, nms only keep the classes you provide. - agnostic: (bool), when it is set to True, we do class-independent nms, otherwise, different class would do nms respectively. - multi_label: (bool), when it is set to True, one box can have multi labels, otherwise, one box only huave one label. - max_det:(int), max number of output bboxes. - - Returns: - list of detections, echo item is one tensor with shape (num_boxes, 6), 6 is for [xyxy, conf, cls]. - """ - - num_classes = prediction.shape[2] - 5 # number of classes - pred_candidates = prediction[..., 4] > conf_thres # candidates - - # Check the parameters. - assert 0 <= conf_thres <= 1, f'conf_thresh must be in 0.0 to 1.0, however {conf_thres} is provided.' - assert 0 <= iou_thres <= 1, f'iou_thres must be in 0.0 to 1.0, however {iou_thres} is provided.' - - # Function settings. - max_wh = 4096 # maximum box width and height - max_nms = 30000 # maximum number of boxes put into torchvision.ops.nms() - time_limit = 10.0 # quit the function when nms cost time exceed the limit time. - multi_label &= num_classes > 1 # multiple labels per box - - tik = time.time() - output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0] - for img_idx, x in enumerate(prediction): # image index, image inference - x = x[pred_candidates[img_idx]] # confidence - - # If no box remains, skip the next process. - if not x.shape[0]: - continue - - # confidence multiply the objectness - x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf - - # (center x, center y, width, height) to (x1, y1, x2, y2) - box = xywh2xyxy(x[:, :4]) - - # Detections matrix's shape is (n,6), each row represents (xyxy, conf, cls) - if multi_label: - box_idx, class_idx = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T - x = torch.cat((box[box_idx], x[box_idx, class_idx + 5, None], class_idx[:, None].float()), 1) - else: # Only keep the class with highest scores. - conf, class_idx = x[:, 5:].max(1, keepdim=True) - x = torch.cat((box, conf, class_idx.float()), 1)[conf.view(-1) > conf_thres] - - # Filter by class, only keep boxes whose category is in classes. - if classes is not None: - x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)] - - # Check shape - num_box = x.shape[0] # number of boxes - if not num_box: # no boxes kept. - continue - elif num_box > max_nms: # excess max boxes' number. - x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence - - # Batched NMS - class_offset = x[:, 5:6] * (0 if agnostic else max_wh) # classes - boxes, scores = x[:, :4] + class_offset, x[:, 4] # boxes (offset by class), scores - keep_box_idx = torchvision.ops.nms(boxes, scores, iou_thres) # NMS - if keep_box_idx.shape[0] > max_det: # limit detections - keep_box_idx = keep_box_idx[:max_det] - - output[img_idx] = x[keep_box_idx] - if (time.time() - tik) > time_limit: - print(f'WARNING: NMS cost time exceed the limited {time_limit}s.') - break # time limit exceeded - - return output diff --git a/spaces/PaddlePaddle/PaddleOCR/app.py b/spaces/PaddlePaddle/PaddleOCR/app.py deleted file mode 100644 index eb8e5c2628f259ae9917a4c2bd70c119474aa081..0000000000000000000000000000000000000000 --- a/spaces/PaddlePaddle/PaddleOCR/app.py +++ /dev/null @@ -1,40 +0,0 @@ -import os -os.system('pip install paddlepaddle') -os.system('pip install paddleocr') -from paddleocr import PaddleOCR, draw_ocr -from PIL import Image -import gradio as gr -import torch - -torch.hub.download_url_to_file('https://i.imgur.com/aqMBT0i.jpg', 'example.jpg') - -def inference(img, lang): - ocr = PaddleOCR(use_angle_cls=True, lang=lang,use_gpu=False) - img_path = img.name - result = ocr.ocr(img_path, cls=True)[0] - image = Image.open(img_path).convert('RGB') - boxes = [line[0] for line in result] - txts = [line[1][0] for line in result] - scores = [line[1][1] for line in result] - im_show = draw_ocr(image, boxes, txts, scores, - font_path='simfang.ttf') - im_show = Image.fromarray(im_show) - im_show.save('result.jpg') - return 'result.jpg' - -title = 'PaddleOCR' -description = 'Gradio demo for PaddleOCR. PaddleOCR demo supports Chinese, English, French, German, Korean and Japanese. To use it, simply upload your image and choose a language from the dropdown menu, or click one of the examples to load them. Read more at the links below.' -article = "

Awesome multilingual OCR toolkits based on PaddlePaddle (practical ultra lightweight OCR system, support 80+ languages recognition, provide data annotation and synthesis tools, support training and deployment among server, mobile, embedded and IoT devices) | Github Repo

" -examples = [['example.jpg','en']] -css = ".output_image, .input_image {height: 40rem !important; width: 100% !important;}" -gr.Interface( - inference, - [gr.inputs.Image(type='file', label='Input'),gr.inputs.Dropdown(choices=['ch', 'en', 'fr', 'german', 'korean', 'japan'], type="value", default='en', label='language')], - gr.outputs.Image(type='file', label='Output'), - title=title, - description=description, - article=article, - examples=examples, - css=css, - enable_queue=True - ).launch(debug=True) \ No newline at end of file diff --git a/spaces/ParityError/Interstellar/README.md b/spaces/ParityError/Interstellar/README.md deleted file mode 100644 index e471b5ce80e3b1119e42fbd94ce2359e4ed96add..0000000000000000000000000000000000000000 --- a/spaces/ParityError/Interstellar/README.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -tags: [gradio-theme, track-1, track-4, minimalist-theme, custom-gradio-theme] -title: Interstellar -colorFrom: orange -colorTo: purple -sdk: gradio -sdk_version: 3.24.1 -app_file: app.py -pinned: false -license: apache-2.0 -emoji: 🚀 ---- -# Interstellar -## Description -A clean dark purple and violet theme that is out of this world! -## Contributions -Thanks to [@ParityError](https://huggingface.co/ParityError) for adding this gradio theme! \ No newline at end of file diff --git a/spaces/Pie31415/control-animation/annotator/uniformer/mmcv/utils/timer.py b/spaces/Pie31415/control-animation/annotator/uniformer/mmcv/utils/timer.py deleted file mode 100644 index e3db7d497d8b374e18b5297e0a1d6eb186fd8cba..0000000000000000000000000000000000000000 --- a/spaces/Pie31415/control-animation/annotator/uniformer/mmcv/utils/timer.py +++ /dev/null @@ -1,118 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from time import time - - -class TimerError(Exception): - - def __init__(self, message): - self.message = message - super(TimerError, self).__init__(message) - - -class Timer: - """A flexible Timer class. - - :Example: - - >>> import time - >>> import annotator.uniformer.mmcv as mmcv - >>> with mmcv.Timer(): - >>> # simulate a code block that will run for 1s - >>> time.sleep(1) - 1.000 - >>> with mmcv.Timer(print_tmpl='it takes {:.1f} seconds'): - >>> # simulate a code block that will run for 1s - >>> time.sleep(1) - it takes 1.0 seconds - >>> timer = mmcv.Timer() - >>> time.sleep(0.5) - >>> print(timer.since_start()) - 0.500 - >>> time.sleep(0.5) - >>> print(timer.since_last_check()) - 0.500 - >>> print(timer.since_start()) - 1.000 - """ - - def __init__(self, start=True, print_tmpl=None): - self._is_running = False - self.print_tmpl = print_tmpl if print_tmpl else '{:.3f}' - if start: - self.start() - - @property - def is_running(self): - """bool: indicate whether the timer is running""" - return self._is_running - - def __enter__(self): - self.start() - return self - - def __exit__(self, type, value, traceback): - print(self.print_tmpl.format(self.since_last_check())) - self._is_running = False - - def start(self): - """Start the timer.""" - if not self._is_running: - self._t_start = time() - self._is_running = True - self._t_last = time() - - def since_start(self): - """Total time since the timer is started. - - Returns (float): Time in seconds. - """ - if not self._is_running: - raise TimerError('timer is not running') - self._t_last = time() - return self._t_last - self._t_start - - def since_last_check(self): - """Time since the last checking. - - Either :func:`since_start` or :func:`since_last_check` is a checking - operation. - - Returns (float): Time in seconds. - """ - if not self._is_running: - raise TimerError('timer is not running') - dur = time() - self._t_last - self._t_last = time() - return dur - - -_g_timers = {} # global timers - - -def check_time(timer_id): - """Add check points in a single line. - - This method is suitable for running a task on a list of items. A timer will - be registered when the method is called for the first time. - - :Example: - - >>> import time - >>> import annotator.uniformer.mmcv as mmcv - >>> for i in range(1, 6): - >>> # simulate a code block - >>> time.sleep(i) - >>> mmcv.check_time('task1') - 2.000 - 3.000 - 4.000 - 5.000 - - Args: - timer_id (str): Timer identifier. - """ - if timer_id not in _g_timers: - _g_timers[timer_id] = Timer() - return 0 - else: - return _g_timers[timer_id].since_last_check() diff --git a/spaces/Plachta/VITS-Umamusume-voice-synthesizer/monotonic_align/core.c b/spaces/Plachta/VITS-Umamusume-voice-synthesizer/monotonic_align/core.c deleted file mode 100644 index 5631d20a9a00db29e143a6e8e4e5c378d6bb850a..0000000000000000000000000000000000000000 --- a/spaces/Plachta/VITS-Umamusume-voice-synthesizer/monotonic_align/core.c +++ /dev/null @@ -1,21299 +0,0 @@ -/* Generated by Cython 0.29.21 */ - -/* BEGIN: Cython Metadata -{ - "distutils": { - "name": "monotonic_align.core", - "sources": [ - "core.pyx" - ] - }, - "module_name": "monotonic_align.core" -} -END: Cython Metadata */ - -#define PY_SSIZE_T_CLEAN -#include "Python.h" -#ifndef Py_PYTHON_H - #error Python headers needed to compile C extensions, please install development version of Python. -#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000) - #error Cython requires Python 2.6+ or Python 3.3+. -#else -#define CYTHON_ABI "0_29_21" -#define CYTHON_HEX_VERSION 0x001D15F0 -#define CYTHON_FUTURE_DIVISION 0 -#include -#ifndef offsetof - #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) -#endif -#if !defined(WIN32) && !defined(MS_WINDOWS) - #ifndef __stdcall - #define __stdcall - #endif - #ifndef __cdecl - #define __cdecl - #endif - #ifndef __fastcall - #define __fastcall - #endif -#endif -#ifndef DL_IMPORT - #define DL_IMPORT(t) t -#endif -#ifndef DL_EXPORT - #define DL_EXPORT(t) t -#endif -#define __PYX_COMMA , -#ifndef HAVE_LONG_LONG - #if PY_VERSION_HEX >= 0x02070000 - #define HAVE_LONG_LONG - #endif -#endif -#ifndef PY_LONG_LONG - #define PY_LONG_LONG LONG_LONG -#endif -#ifndef Py_HUGE_VAL - #define Py_HUGE_VAL HUGE_VAL -#endif -#ifdef PYPY_VERSION - #define CYTHON_COMPILING_IN_PYPY 1 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #undef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 0 - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #if PY_VERSION_HEX < 0x03050000 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #elif !defined(CYTHON_USE_ASYNC_SLOTS) - #define CYTHON_USE_ASYNC_SLOTS 1 - #endif - #undef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 0 - #undef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 0 - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #undef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 1 - #undef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 0 - #undef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 0 - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #undef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 0 - #undef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 0 - #undef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE 0 - #undef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS 0 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 -#elif defined(PYSTON_VERSION) - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 1 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #ifndef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 1 - #endif - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #undef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 0 - #ifndef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 1 - #endif - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #ifndef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 0 - #endif - #ifndef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 1 - #endif - #ifndef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 1 - #endif - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #undef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 0 - #undef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 0 - #undef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE 0 - #undef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS 0 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 -#else - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 1 - #ifndef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 1 - #endif - #if PY_VERSION_HEX < 0x02070000 - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #elif !defined(CYTHON_USE_PYTYPE_LOOKUP) - #define CYTHON_USE_PYTYPE_LOOKUP 1 - #endif - #if PY_MAJOR_VERSION < 3 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #elif !defined(CYTHON_USE_ASYNC_SLOTS) - #define CYTHON_USE_ASYNC_SLOTS 1 - #endif - #if PY_VERSION_HEX < 0x02070000 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #elif !defined(CYTHON_USE_PYLONG_INTERNALS) - #define CYTHON_USE_PYLONG_INTERNALS 1 - #endif - #ifndef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 1 - #endif - #ifndef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 1 - #endif - #if PY_VERSION_HEX < 0x030300F0 - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #elif !defined(CYTHON_USE_UNICODE_WRITER) - #define CYTHON_USE_UNICODE_WRITER 1 - #endif - #ifndef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 0 - #endif - #ifndef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 1 - #endif - #ifndef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 1 - #endif - #ifndef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 1 - #endif - #ifndef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 1 - #endif - #ifndef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000) - #endif - #ifndef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1) - #endif - #ifndef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX >= 0x030600B1) - #endif - #ifndef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3) - #endif -#endif -#if !defined(CYTHON_FAST_PYCCALL) -#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) -#endif -#if CYTHON_USE_PYLONG_INTERNALS - #include "longintrepr.h" - #undef SHIFT - #undef BASE - #undef MASK - #ifdef SIZEOF_VOID_P - enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; - #endif -#endif -#ifndef __has_attribute - #define __has_attribute(x) 0 -#endif -#ifndef __has_cpp_attribute - #define __has_cpp_attribute(x) 0 -#endif -#ifndef CYTHON_RESTRICT - #if defined(__GNUC__) - #define CYTHON_RESTRICT __restrict__ - #elif defined(_MSC_VER) && _MSC_VER >= 1400 - #define CYTHON_RESTRICT __restrict - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_RESTRICT restrict - #else - #define CYTHON_RESTRICT - #endif -#endif -#ifndef CYTHON_UNUSED -# if defined(__GNUC__) -# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -#endif -#ifndef CYTHON_MAYBE_UNUSED_VAR -# if defined(__cplusplus) - template void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } -# else -# define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) -# endif -#endif -#ifndef CYTHON_NCP_UNUSED -# if CYTHON_COMPILING_IN_CPYTHON -# define CYTHON_NCP_UNUSED -# else -# define CYTHON_NCP_UNUSED CYTHON_UNUSED -# endif -#endif -#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) -#ifdef _MSC_VER - #ifndef _MSC_STDINT_H_ - #if _MSC_VER < 1300 - typedef unsigned char uint8_t; - typedef unsigned int uint32_t; - #else - typedef unsigned __int8 uint8_t; - typedef unsigned __int32 uint32_t; - #endif - #endif -#else - #include -#endif -#ifndef CYTHON_FALLTHROUGH - #if defined(__cplusplus) && __cplusplus >= 201103L - #if __has_cpp_attribute(fallthrough) - #define CYTHON_FALLTHROUGH [[fallthrough]] - #elif __has_cpp_attribute(clang::fallthrough) - #define CYTHON_FALLTHROUGH [[clang::fallthrough]] - #elif __has_cpp_attribute(gnu::fallthrough) - #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] - #endif - #endif - #ifndef CYTHON_FALLTHROUGH - #if __has_attribute(fallthrough) - #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) - #else - #define CYTHON_FALLTHROUGH - #endif - #endif - #if defined(__clang__ ) && defined(__apple_build_version__) - #if __apple_build_version__ < 7000000 - #undef CYTHON_FALLTHROUGH - #define CYTHON_FALLTHROUGH - #endif - #endif -#endif - -#ifndef CYTHON_INLINE - #if defined(__clang__) - #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) - #elif defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) - #define Py_OptimizeFlag 0 -#endif -#define __PYX_BUILD_PY_SSIZE_T "n" -#define CYTHON_FORMAT_SSIZE_T "z" -#if PY_MAJOR_VERSION < 3 - #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) - #define __Pyx_DefaultClassType PyClass_Type -#else - #define __Pyx_BUILTIN_MODULE_NAME "builtins" -#if PY_VERSION_HEX >= 0x030800A4 && PY_VERSION_HEX < 0x030800B2 - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#else - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#endif - #define __Pyx_DefaultClassType PyType_Type -#endif -#ifndef Py_TPFLAGS_CHECKTYPES - #define Py_TPFLAGS_CHECKTYPES 0 -#endif -#ifndef Py_TPFLAGS_HAVE_INDEX - #define Py_TPFLAGS_HAVE_INDEX 0 -#endif -#ifndef Py_TPFLAGS_HAVE_NEWBUFFER - #define Py_TPFLAGS_HAVE_NEWBUFFER 0 -#endif -#ifndef Py_TPFLAGS_HAVE_FINALIZE - #define Py_TPFLAGS_HAVE_FINALIZE 0 -#endif -#ifndef METH_STACKLESS - #define METH_STACKLESS 0 -#endif -#if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL) - #ifndef METH_FASTCALL - #define METH_FASTCALL 0x80 - #endif - typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); - typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, - Py_ssize_t nargs, PyObject *kwnames); -#else - #define __Pyx_PyCFunctionFast _PyCFunctionFast - #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords -#endif -#if CYTHON_FAST_PYCCALL -#define __Pyx_PyFastCFunction_Check(func)\ - ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))))) -#else -#define __Pyx_PyFastCFunction_Check(func) 0 -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) - #define PyObject_Malloc(s) PyMem_Malloc(s) - #define PyObject_Free(p) PyMem_Free(p) - #define PyObject_Realloc(p) PyMem_Realloc(p) -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030400A1 - #define PyMem_RawMalloc(n) PyMem_Malloc(n) - #define PyMem_RawRealloc(p, n) PyMem_Realloc(p, n) - #define PyMem_RawFree(p) PyMem_Free(p) -#endif -#if CYTHON_COMPILING_IN_PYSTON - #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) - #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) -#else - #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) - #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) -#endif -#if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000 - #define __Pyx_PyThreadState_Current PyThreadState_GET() -#elif PY_VERSION_HEX >= 0x03060000 - #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() -#elif PY_VERSION_HEX >= 0x03000000 - #define __Pyx_PyThreadState_Current PyThreadState_GET() -#else - #define __Pyx_PyThreadState_Current _PyThreadState_Current -#endif -#if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT) -#include "pythread.h" -#define Py_tss_NEEDS_INIT 0 -typedef int Py_tss_t; -static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) { - *key = PyThread_create_key(); - return 0; -} -static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) { - Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t)); - *key = Py_tss_NEEDS_INIT; - return key; -} -static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) { - PyObject_Free(key); -} -static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) { - return *key != Py_tss_NEEDS_INIT; -} -static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) { - PyThread_delete_key(*key); - *key = Py_tss_NEEDS_INIT; -} -static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) { - return PyThread_set_key_value(*key, value); -} -static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { - return PyThread_get_key_value(*key); -} -#endif -#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) -#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) -#else -#define __Pyx_PyDict_NewPresized(n) PyDict_New() -#endif -#if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && CYTHON_USE_UNICODE_INTERNALS -#define __Pyx_PyDict_GetItemStr(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) -#else -#define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name) -#endif -#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) - #define CYTHON_PEP393_ENABLED 1 - #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ - 0 : _PyUnicode_Ready((PyObject *)(op))) - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) - #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) - #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) - #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) - #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) - #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) - #if defined(PyUnicode_IS_READY) && defined(PyUnicode_GET_SIZE) - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) - #else - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) - #endif -#else - #define CYTHON_PEP393_ENABLED 0 - #define PyUnicode_1BYTE_KIND 1 - #define PyUnicode_2BYTE_KIND 2 - #define PyUnicode_4BYTE_KIND 4 - #define __Pyx_PyUnicode_READY(op) (0) - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) - #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) - #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) - #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) - #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) - #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) -#endif -#if CYTHON_COMPILING_IN_PYPY - #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) -#else - #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ - PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) - #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) - #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) - #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) -#endif -#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) -#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) -#else - #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) -#endif -#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) - #define PyObject_ASCII(o) PyObject_Repr(o) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBaseString_Type PyUnicode_Type - #define PyStringObject PyUnicodeObject - #define PyString_Type PyUnicode_Type - #define PyString_Check PyUnicode_Check - #define PyString_CheckExact PyUnicode_CheckExact -#ifndef PyObject_Unicode - #define PyObject_Unicode PyObject_Str -#endif -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) - #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) -#else - #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) - #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) -#endif -#ifndef PySet_CheckExact - #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) -#endif -#if PY_VERSION_HEX >= 0x030900A4 - #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) - #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) -#else - #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) - #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) -#endif -#if CYTHON_ASSUME_SAFE_MACROS - #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) -#else - #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyIntObject PyLongObject - #define PyInt_Type PyLong_Type - #define PyInt_Check(op) PyLong_Check(op) - #define PyInt_CheckExact(op) PyLong_CheckExact(op) - #define PyInt_FromString PyLong_FromString - #define PyInt_FromUnicode PyLong_FromUnicode - #define PyInt_FromLong PyLong_FromLong - #define PyInt_FromSize_t PyLong_FromSize_t - #define PyInt_FromSsize_t PyLong_FromSsize_t - #define PyInt_AsLong PyLong_AsLong - #define PyInt_AS_LONG PyLong_AS_LONG - #define PyInt_AsSsize_t PyLong_AsSsize_t - #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask - #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask - #define PyNumber_Int PyNumber_Long -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBoolObject PyLongObject -#endif -#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY - #ifndef PyUnicode_InternFromString - #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) - #endif -#endif -#if PY_VERSION_HEX < 0x030200A4 - typedef long Py_hash_t; - #define __Pyx_PyInt_FromHash_t PyInt_FromLong - #define __Pyx_PyInt_AsHash_t PyInt_AsLong -#else - #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t - #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyMethod_New(func, self, klass) ((self) ? ((void)(klass), PyMethod_New(func, self)) : __Pyx_NewRef(func)) -#else - #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) -#endif -#if CYTHON_USE_ASYNC_SLOTS - #if PY_VERSION_HEX >= 0x030500B1 - #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods - #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) - #else - #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) - #endif -#else - #define __Pyx_PyType_AsAsync(obj) NULL -#endif -#ifndef __Pyx_PyAsyncMethodsStruct - typedef struct { - unaryfunc am_await; - unaryfunc am_aiter; - unaryfunc am_anext; - } __Pyx_PyAsyncMethodsStruct; -#endif - -#if defined(WIN32) || defined(MS_WINDOWS) - #define _USE_MATH_DEFINES -#endif -#include -#ifdef NAN -#define __PYX_NAN() ((float) NAN) -#else -static CYTHON_INLINE float __PYX_NAN() { - float value; - memset(&value, 0xFF, sizeof(value)); - return value; -} -#endif -#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) -#define __Pyx_truncl trunc -#else -#define __Pyx_truncl truncl -#endif - -#define __PYX_MARK_ERR_POS(f_index, lineno) \ - { __pyx_filename = __pyx_f[f_index]; (void)__pyx_filename; __pyx_lineno = lineno; (void)__pyx_lineno; __pyx_clineno = __LINE__; (void)__pyx_clineno; } -#define __PYX_ERR(f_index, lineno, Ln_error) \ - { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } - -#ifndef __PYX_EXTERN_C - #ifdef __cplusplus - #define __PYX_EXTERN_C extern "C" - #else - #define __PYX_EXTERN_C extern - #endif -#endif - -#define __PYX_HAVE__monotonic_align__core -#define __PYX_HAVE_API__monotonic_align__core -/* Early includes */ -#include "pythread.h" -#include -#include -#include -#include "pystate.h" -#ifdef _OPENMP -#include -#endif /* _OPENMP */ - -#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) -#define CYTHON_WITHOUT_ASSERTIONS -#endif - -typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; - const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; - -#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 -#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 -#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8) -#define __PYX_DEFAULT_STRING_ENCODING "" -#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString -#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#define __Pyx_uchar_cast(c) ((unsigned char)c) -#define __Pyx_long_cast(x) ((long)x) -#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ - (sizeof(type) < sizeof(Py_ssize_t)) ||\ - (sizeof(type) > sizeof(Py_ssize_t) &&\ - likely(v < (type)PY_SSIZE_T_MAX ||\ - v == (type)PY_SSIZE_T_MAX) &&\ - (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ - v == (type)PY_SSIZE_T_MIN))) ||\ - (sizeof(type) == sizeof(Py_ssize_t) &&\ - (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ - v == (type)PY_SSIZE_T_MAX))) ) -static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { - return (size_t) i < (size_t) limit; -} -#if defined (__cplusplus) && __cplusplus >= 201103L - #include - #define __Pyx_sst_abs(value) std::abs(value) -#elif SIZEOF_INT >= SIZEOF_SIZE_T - #define __Pyx_sst_abs(value) abs(value) -#elif SIZEOF_LONG >= SIZEOF_SIZE_T - #define __Pyx_sst_abs(value) labs(value) -#elif defined (_MSC_VER) - #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) -#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define __Pyx_sst_abs(value) llabs(value) -#elif defined (__GNUC__) - #define __Pyx_sst_abs(value) __builtin_llabs(value) -#else - #define __Pyx_sst_abs(value) ((value<0) ? -value : value) -#endif -static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); -static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); -#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) -#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) -#define __Pyx_PyBytes_FromString PyBytes_FromString -#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); -#if PY_MAJOR_VERSION < 3 - #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#else - #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize -#endif -#define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) -#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) -#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) -#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) -#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) -static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { - const Py_UNICODE *u_end = u; - while (*u_end++) ; - return (size_t)(u_end - u - 1); -} -#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) -#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode -#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode -#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) -#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) -static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); -static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); -static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); -#define __Pyx_PySequence_Tuple(obj)\ - (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -#if CYTHON_ASSUME_SAFE_MACROS -#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) -#else -#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) -#endif -#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) -#if PY_MAJOR_VERSION >= 3 -#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) -#else -#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) -#endif -#define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII -static int __Pyx_sys_getdefaultencoding_not_ascii; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - PyObject* ascii_chars_u = NULL; - PyObject* ascii_chars_b = NULL; - const char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - if (strcmp(default_encoding_c, "ascii") == 0) { - __Pyx_sys_getdefaultencoding_not_ascii = 0; - } else { - char ascii_chars[128]; - int c; - for (c = 0; c < 128; c++) { - ascii_chars[c] = c; - } - __Pyx_sys_getdefaultencoding_not_ascii = 1; - ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); - if (!ascii_chars_u) goto bad; - ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); - if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { - PyErr_Format( - PyExc_ValueError, - "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", - default_encoding_c); - goto bad; - } - Py_DECREF(ascii_chars_u); - Py_DECREF(ascii_chars_b); - } - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - Py_XDECREF(ascii_chars_u); - Py_XDECREF(ascii_chars_b); - return -1; -} -#endif -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) -#else -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -static char* __PYX_DEFAULT_STRING_ENCODING; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1); - if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; - strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - return -1; -} -#endif -#endif - - -/* Test for GCC > 2.95 */ -#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) -#else /* !__GNUC__ or GCC < 2.95 */ - #define likely(x) (x) - #define unlikely(x) (x) -#endif /* __GNUC__ */ -static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } - -static PyObject *__pyx_m = NULL; -static PyObject *__pyx_d; -static PyObject *__pyx_b; -static PyObject *__pyx_cython_runtime = NULL; -static PyObject *__pyx_empty_tuple; -static PyObject *__pyx_empty_bytes; -static PyObject *__pyx_empty_unicode; -static int __pyx_lineno; -static int __pyx_clineno = 0; -static const char * __pyx_cfilenm= __FILE__; -static const char *__pyx_filename; - - -static const char *__pyx_f[] = { - "core.pyx", - "stringsource", -}; -/* NoFastGil.proto */ -#define __Pyx_PyGILState_Ensure PyGILState_Ensure -#define __Pyx_PyGILState_Release PyGILState_Release -#define __Pyx_FastGIL_Remember() -#define __Pyx_FastGIL_Forget() -#define __Pyx_FastGilFuncInit() - -/* MemviewSliceStruct.proto */ -struct __pyx_memoryview_obj; -typedef struct { - struct __pyx_memoryview_obj *memview; - char *data; - Py_ssize_t shape[8]; - Py_ssize_t strides[8]; - Py_ssize_t suboffsets[8]; -} __Pyx_memviewslice; -#define __Pyx_MemoryView_Len(m) (m.shape[0]) - -/* Atomics.proto */ -#include -#ifndef CYTHON_ATOMICS - #define CYTHON_ATOMICS 1 -#endif -#define __pyx_atomic_int_type int -#if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 ||\ - (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) &&\ - !defined(__i386__) - #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) - #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) - #ifdef __PYX_DEBUG_ATOMICS - #warning "Using GNU atomics" - #endif -#elif CYTHON_ATOMICS && defined(_MSC_VER) && 0 - #include - #undef __pyx_atomic_int_type - #define __pyx_atomic_int_type LONG - #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) - #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) - #ifdef __PYX_DEBUG_ATOMICS - #pragma message ("Using MSVC atomics") - #endif -#elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 - #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) - #define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value) - #ifdef __PYX_DEBUG_ATOMICS - #warning "Using Intel atomics" - #endif -#else - #undef CYTHON_ATOMICS - #define CYTHON_ATOMICS 0 - #ifdef __PYX_DEBUG_ATOMICS - #warning "Not using atomics" - #endif -#endif -typedef volatile __pyx_atomic_int_type __pyx_atomic_int; -#if CYTHON_ATOMICS - #define __pyx_add_acquisition_count(memview)\ - __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) - #define __pyx_sub_acquisition_count(memview)\ - __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) -#else - #define __pyx_add_acquisition_count(memview)\ - __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) - #define __pyx_sub_acquisition_count(memview)\ - __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) -#endif - -/* ForceInitThreads.proto */ -#ifndef __PYX_FORCE_INIT_THREADS - #define __PYX_FORCE_INIT_THREADS 0 -#endif - -/* BufferFormatStructs.proto */ -#define IS_UNSIGNED(type) (((type) -1) > 0) -struct __Pyx_StructField_; -#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) -typedef struct { - const char* name; - struct __Pyx_StructField_* fields; - size_t size; - size_t arraysize[8]; - int ndim; - char typegroup; - char is_unsigned; - int flags; -} __Pyx_TypeInfo; -typedef struct __Pyx_StructField_ { - __Pyx_TypeInfo* type; - const char* name; - size_t offset; -} __Pyx_StructField; -typedef struct { - __Pyx_StructField* field; - size_t parent_offset; -} __Pyx_BufFmt_StackElem; -typedef struct { - __Pyx_StructField root; - __Pyx_BufFmt_StackElem* head; - size_t fmt_offset; - size_t new_count, enc_count; - size_t struct_alignment; - int is_complex; - char enc_type; - char new_packmode; - char enc_packmode; - char is_valid_array; -} __Pyx_BufFmt_Context; - - -/*--- Type declarations ---*/ -struct __pyx_array_obj; -struct __pyx_MemviewEnum_obj; -struct __pyx_memoryview_obj; -struct __pyx_memoryviewslice_obj; -struct __pyx_opt_args_15monotonic_align_4core_maximum_path_each; - -/* "monotonic_align/core.pyx":7 - * @cython.boundscheck(False) - * @cython.wraparound(False) - * cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_y, int t_x, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<< - * cdef int x - * cdef int y - */ -struct __pyx_opt_args_15monotonic_align_4core_maximum_path_each { - int __pyx_n; - float max_neg_val; -}; - -/* "View.MemoryView":105 - * - * @cname("__pyx_array") - * cdef class array: # <<<<<<<<<<<<<< - * - * cdef: - */ -struct __pyx_array_obj { - PyObject_HEAD - struct __pyx_vtabstruct_array *__pyx_vtab; - char *data; - Py_ssize_t len; - char *format; - int ndim; - Py_ssize_t *_shape; - Py_ssize_t *_strides; - Py_ssize_t itemsize; - PyObject *mode; - PyObject *_format; - void (*callback_free_data)(void *); - int free_data; - int dtype_is_object; -}; - - -/* "View.MemoryView":279 - * - * @cname('__pyx_MemviewEnum') - * cdef class Enum(object): # <<<<<<<<<<<<<< - * cdef object name - * def __init__(self, name): - */ -struct __pyx_MemviewEnum_obj { - PyObject_HEAD - PyObject *name; -}; - - -/* "View.MemoryView":330 - * - * @cname('__pyx_memoryview') - * cdef class memoryview(object): # <<<<<<<<<<<<<< - * - * cdef object obj - */ -struct __pyx_memoryview_obj { - PyObject_HEAD - struct __pyx_vtabstruct_memoryview *__pyx_vtab; - PyObject *obj; - PyObject *_size; - PyObject *_array_interface; - PyThread_type_lock lock; - __pyx_atomic_int acquisition_count[2]; - __pyx_atomic_int *acquisition_count_aligned_p; - Py_buffer view; - int flags; - int dtype_is_object; - __Pyx_TypeInfo *typeinfo; -}; - - -/* "View.MemoryView":965 - * - * @cname('__pyx_memoryviewslice') - * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< - * "Internal class for passing memoryview slices to Python" - * - */ -struct __pyx_memoryviewslice_obj { - struct __pyx_memoryview_obj __pyx_base; - __Pyx_memviewslice from_slice; - PyObject *from_object; - PyObject *(*to_object_func)(char *); - int (*to_dtype_func)(char *, PyObject *); -}; - - - -/* "View.MemoryView":105 - * - * @cname("__pyx_array") - * cdef class array: # <<<<<<<<<<<<<< - * - * cdef: - */ - -struct __pyx_vtabstruct_array { - PyObject *(*get_memview)(struct __pyx_array_obj *); -}; -static struct __pyx_vtabstruct_array *__pyx_vtabptr_array; - - -/* "View.MemoryView":330 - * - * @cname('__pyx_memoryview') - * cdef class memoryview(object): # <<<<<<<<<<<<<< - * - * cdef object obj - */ - -struct __pyx_vtabstruct_memoryview { - char *(*get_item_pointer)(struct __pyx_memoryview_obj *, PyObject *); - PyObject *(*is_slice)(struct __pyx_memoryview_obj *, PyObject *); - PyObject *(*setitem_slice_assignment)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); - PyObject *(*setitem_slice_assign_scalar)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *); - PyObject *(*setitem_indexed)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); - PyObject *(*convert_item_to_object)(struct __pyx_memoryview_obj *, char *); - PyObject *(*assign_item_from_object)(struct __pyx_memoryview_obj *, char *, PyObject *); -}; -static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview; - - -/* "View.MemoryView":965 - * - * @cname('__pyx_memoryviewslice') - * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< - * "Internal class for passing memoryview slices to Python" - * - */ - -struct __pyx_vtabstruct__memoryviewslice { - struct __pyx_vtabstruct_memoryview __pyx_base; -}; -static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; - -/* --- Runtime support code (head) --- */ -/* Refnanny.proto */ -#ifndef CYTHON_REFNANNY - #define CYTHON_REFNANNY 0 -#endif -#if CYTHON_REFNANNY - typedef struct { - void (*INCREF)(void*, PyObject*, int); - void (*DECREF)(void*, PyObject*, int); - void (*GOTREF)(void*, PyObject*, int); - void (*GIVEREF)(void*, PyObject*, int); - void* (*SetupContext)(const char*, int, const char*); - void (*FinishContext)(void**); - } __Pyx_RefNannyAPIStruct; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); - #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; -#ifdef WITH_THREAD - #define __Pyx_RefNannySetupContext(name, acquire_gil)\ - if (acquire_gil) {\ - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ - PyGILState_Release(__pyx_gilstate_save);\ - } else {\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ - } -#else - #define __Pyx_RefNannySetupContext(name, acquire_gil)\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) -#endif - #define __Pyx_RefNannyFinishContext()\ - __Pyx_RefNanny->FinishContext(&__pyx_refnanny) - #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) - #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) - #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) - #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) -#else - #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name, acquire_gil) - #define __Pyx_RefNannyFinishContext() - #define __Pyx_INCREF(r) Py_INCREF(r) - #define __Pyx_DECREF(r) Py_DECREF(r) - #define __Pyx_GOTREF(r) - #define __Pyx_GIVEREF(r) - #define __Pyx_XINCREF(r) Py_XINCREF(r) - #define __Pyx_XDECREF(r) Py_XDECREF(r) - #define __Pyx_XGOTREF(r) - #define __Pyx_XGIVEREF(r) -#endif -#define __Pyx_XDECREF_SET(r, v) do {\ - PyObject *tmp = (PyObject *) r;\ - r = v; __Pyx_XDECREF(tmp);\ - } while (0) -#define __Pyx_DECREF_SET(r, v) do {\ - PyObject *tmp = (PyObject *) r;\ - r = v; __Pyx_DECREF(tmp);\ - } while (0) -#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) -#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) - -/* PyObjectGetAttrStr.proto */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); -#else -#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) -#endif - -/* GetBuiltinName.proto */ -static PyObject *__Pyx_GetBuiltinName(PyObject *name); - -/* MemviewSliceInit.proto */ -#define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d -#define __Pyx_MEMVIEW_DIRECT 1 -#define __Pyx_MEMVIEW_PTR 2 -#define __Pyx_MEMVIEW_FULL 4 -#define __Pyx_MEMVIEW_CONTIG 8 -#define __Pyx_MEMVIEW_STRIDED 16 -#define __Pyx_MEMVIEW_FOLLOW 32 -#define __Pyx_IS_C_CONTIG 1 -#define __Pyx_IS_F_CONTIG 2 -static int __Pyx_init_memviewslice( - struct __pyx_memoryview_obj *memview, - int ndim, - __Pyx_memviewslice *memviewslice, - int memview_is_new_reference); -static CYTHON_INLINE int __pyx_add_acquisition_count_locked( - __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); -static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( - __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); -#define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p) -#define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview)) -#define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__) -#define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__) -static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int); -static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int); - -/* RaiseArgTupleInvalid.proto */ -static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); - -/* RaiseDoubleKeywords.proto */ -static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); - -/* ParseKeywords.proto */ -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ - PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ - const char* function_name); - -/* None.proto */ -static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); - -/* ArgTypeTest.proto */ -#define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ - ((likely((Py_TYPE(obj) == type) | (none_allowed && (obj == Py_None)))) ? 1 :\ - __Pyx__ArgTypeTest(obj, type, name, exact)) -static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); - -/* PyObjectCall.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); -#else -#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) -#endif - -/* PyThreadStateGet.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; -#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; -#define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type -#else -#define __Pyx_PyThreadState_declare -#define __Pyx_PyThreadState_assign -#define __Pyx_PyErr_Occurred() PyErr_Occurred() -#endif - -/* PyErrFetchRestore.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) -#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) -#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) -#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) -#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); -static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) -#else -#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) -#endif -#else -#define __Pyx_PyErr_Clear() PyErr_Clear() -#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) -#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) -#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) -#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) -#endif - -/* RaiseException.proto */ -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); - -/* PyCFunctionFastCall.proto */ -#if CYTHON_FAST_PYCCALL -static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs); -#else -#define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL) -#endif - -/* PyFunctionFastCall.proto */ -#if CYTHON_FAST_PYCALL -#define __Pyx_PyFunction_FastCall(func, args, nargs)\ - __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) -#if 1 || PY_VERSION_HEX < 0x030600B1 -static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); -#else -#define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs) -#endif -#define __Pyx_BUILD_ASSERT_EXPR(cond)\ - (sizeof(char [1 - 2*!(cond)]) - 1) -#ifndef Py_MEMBER_SIZE -#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) -#endif - static size_t __pyx_pyframe_localsplus_offset = 0; - #include "frameobject.h" - #define __Pxy_PyFrame_Initialize_Offsets()\ - ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ - (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) - #define __Pyx_PyFrame_GetLocalsplus(frame)\ - (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) -#endif - -/* PyObjectCall2Args.proto */ -static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); - -/* PyObjectCallMethO.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); -#endif - -/* PyObjectCallOneArg.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); - -/* IncludeStringH.proto */ -#include - -/* BytesEquals.proto */ -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); - -/* UnicodeEquals.proto */ -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); - -/* StrEquals.proto */ -#if PY_MAJOR_VERSION >= 3 -#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals -#else -#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals -#endif - -/* None.proto */ -static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t, Py_ssize_t); - -/* UnaryNegOverflows.proto */ -#define UNARY_NEG_WOULD_OVERFLOW(x)\ - (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) - -static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *); /*proto*/ -/* GetAttr.proto */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); - -/* GetItemInt.proto */ -#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\ - (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ - __Pyx_GetItemInt_Generic(o, to_py_func(i)))) -#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ - (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ - (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, - int is_list, int wraparound, int boundscheck); - -/* ObjectGetItem.proto */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key); -#else -#define __Pyx_PyObject_GetItem(obj, key) PyObject_GetItem(obj, key) -#endif - -/* decode_c_string_utf16.proto */ -static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors) { - int byteorder = 0; - return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); -} -static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16LE(const char *s, Py_ssize_t size, const char *errors) { - int byteorder = -1; - return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); -} -static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16BE(const char *s, Py_ssize_t size, const char *errors) { - int byteorder = 1; - return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); -} - -/* decode_c_string.proto */ -static CYTHON_INLINE PyObject* __Pyx_decode_c_string( - const char* cstring, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); - -/* PyErrExceptionMatches.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) -static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); -#else -#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) -#endif - -/* GetAttr3.proto */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); - -/* PyDictVersioning.proto */ -#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS -#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) -#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) -#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ - (version_var) = __PYX_GET_DICT_VERSION(dict);\ - (cache_var) = (value); -#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ - static PY_UINT64_T __pyx_dict_version = 0;\ - static PyObject *__pyx_dict_cached_value = NULL;\ - if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ - (VAR) = __pyx_dict_cached_value;\ - } else {\ - (VAR) = __pyx_dict_cached_value = (LOOKUP);\ - __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ - }\ -} -static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); -static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); -static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); -#else -#define __PYX_GET_DICT_VERSION(dict) (0) -#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) -#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); -#endif - -/* GetModuleGlobalName.proto */ -#if CYTHON_USE_DICT_VERSIONS -#define __Pyx_GetModuleGlobalName(var, name) {\ - static PY_UINT64_T __pyx_dict_version = 0;\ - static PyObject *__pyx_dict_cached_value = NULL;\ - (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\ - (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ - __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ -} -#define __Pyx_GetModuleGlobalNameUncached(var, name) {\ - PY_UINT64_T __pyx_dict_version;\ - PyObject *__pyx_dict_cached_value;\ - (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ -} -static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); -#else -#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) -#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) -static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); -#endif - -/* RaiseTooManyValuesToUnpack.proto */ -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); - -/* RaiseNeedMoreValuesToUnpack.proto */ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); - -/* RaiseNoneIterError.proto */ -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); - -/* ExtTypeTest.proto */ -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); - -/* GetTopmostException.proto */ -#if CYTHON_USE_EXC_INFO_STACK -static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); -#endif - -/* SaveResetException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); -#else -#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) -#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) -#endif - -/* GetException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) -static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#else -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); -#endif - -/* SwapException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#else -static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); -#endif - -/* Import.proto */ -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); - -/* FastTypeChecks.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) -static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); -static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); -static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); -#else -#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) -#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) -#define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) -#endif -#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) - -static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -/* ListCompAppend.proto */ -#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS -static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { - PyListObject* L = (PyListObject*) list; - Py_ssize_t len = Py_SIZE(list); - if (likely(L->allocated > len)) { - Py_INCREF(x); - PyList_SET_ITEM(list, len, x); - __Pyx_SET_SIZE(list, len + 1); - return 0; - } - return PyList_Append(list, x); -} -#else -#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) -#endif - -/* PyIntBinop.proto */ -#if !CYTHON_COMPILING_IN_PYPY -static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); -#else -#define __Pyx_PyInt_AddObjC(op1, op2, intval, inplace, zerodivision_check)\ - (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2)) -#endif - -/* ListExtend.proto */ -static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { -#if CYTHON_COMPILING_IN_CPYTHON - PyObject* none = _PyList_Extend((PyListObject*)L, v); - if (unlikely(!none)) - return -1; - Py_DECREF(none); - return 0; -#else - return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v); -#endif -} - -/* ListAppend.proto */ -#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS -static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { - PyListObject* L = (PyListObject*) list; - Py_ssize_t len = Py_SIZE(list); - if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { - Py_INCREF(x); - PyList_SET_ITEM(list, len, x); - __Pyx_SET_SIZE(list, len + 1); - return 0; - } - return PyList_Append(list, x); -} -#else -#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) -#endif - -/* None.proto */ -static CYTHON_INLINE long __Pyx_div_long(long, long); - -/* ImportFrom.proto */ -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); - -/* HasAttr.proto */ -static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); - -/* PyObject_GenericGetAttrNoDict.proto */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name); -#else -#define __Pyx_PyObject_GenericGetAttrNoDict PyObject_GenericGetAttr -#endif - -/* PyObject_GenericGetAttr.proto */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name); -#else -#define __Pyx_PyObject_GenericGetAttr PyObject_GenericGetAttr -#endif - -/* SetVTable.proto */ -static int __Pyx_SetVtable(PyObject *dict, void *vtable); - -/* PyObjectGetAttrStrNoError.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); - -/* SetupReduce.proto */ -static int __Pyx_setup_reduce(PyObject* type_obj); - -/* CLineInTraceback.proto */ -#ifdef CYTHON_CLINE_IN_TRACEBACK -#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) -#else -static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); -#endif - -/* CodeObjectCache.proto */ -typedef struct { - PyCodeObject* code_object; - int code_line; -} __Pyx_CodeObjectCacheEntry; -struct __Pyx_CodeObjectCache { - int count; - int max_count; - __Pyx_CodeObjectCacheEntry* entries; -}; -static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); -static PyCodeObject *__pyx_find_code_object(int code_line); -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); - -/* AddTraceback.proto */ -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename); - -#if PY_MAJOR_VERSION < 3 - static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); - static void __Pyx_ReleaseBuffer(Py_buffer *view); -#else - #define __Pyx_GetBuffer PyObject_GetBuffer - #define __Pyx_ReleaseBuffer PyBuffer_Release -#endif - - -/* BufferStructDeclare.proto */ -typedef struct { - Py_ssize_t shape, strides, suboffsets; -} __Pyx_Buf_DimInfo; -typedef struct { - size_t refcount; - Py_buffer pybuffer; -} __Pyx_Buffer; -typedef struct { - __Pyx_Buffer *rcbuffer; - char *data; - __Pyx_Buf_DimInfo diminfo[8]; -} __Pyx_LocalBuf_ND; - -/* MemviewSliceIsContig.proto */ -static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice mvs, char order, int ndim); - -/* OverlappingSlices.proto */ -static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, - __Pyx_memviewslice *slice2, - int ndim, size_t itemsize); - -/* Capsule.proto */ -static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); - -/* IsLittleEndian.proto */ -static CYTHON_INLINE int __Pyx_Is_Little_Endian(void); - -/* BufferFormatCheck.proto */ -static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts); -static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, - __Pyx_BufFmt_StackElem* stack, - __Pyx_TypeInfo* type); - -/* TypeInfoCompare.proto */ -static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); - -/* MemviewSliceValidateAndInit.proto */ -static int __Pyx_ValidateAndInit_memviewslice( - int *axes_specs, - int c_or_f_flag, - int buf_flags, - int ndim, - __Pyx_TypeInfo *dtype, - __Pyx_BufFmt_StackElem stack[], - __Pyx_memviewslice *memviewslice, - PyObject *original_obj); - -/* ObjectToMemviewSlice.proto */ -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_int(PyObject *, int writable_flag); - -/* ObjectToMemviewSlice.proto */ -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_float(PyObject *, int writable_flag); - -/* ObjectToMemviewSlice.proto */ -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_int(PyObject *, int writable_flag); - -/* CIntToPy.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); - -/* CIntToPy.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); - -/* MemviewSliceCopyTemplate.proto */ -static __Pyx_memviewslice -__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, - const char *mode, int ndim, - size_t sizeof_dtype, int contig_flag, - int dtype_is_object); - -/* CIntFromPy.proto */ -static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); - -/* CIntFromPy.proto */ -static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); - -/* CIntFromPy.proto */ -static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *); - -/* CheckBinaryVersion.proto */ -static int __Pyx_check_binary_version(void); - -/* InitStrings.proto */ -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); - -static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *__pyx_v_self); /* proto*/ -static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto*/ -static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj); /* proto*/ -static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src); /* proto*/ -static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value); /* proto*/ -static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto*/ -static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/ -static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/ -static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/ -static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/ - -/* Module declarations from 'cython.view' */ - -/* Module declarations from 'cython' */ - -/* Module declarations from 'monotonic_align.core' */ -static PyTypeObject *__pyx_array_type = 0; -static PyTypeObject *__pyx_MemviewEnum_type = 0; -static PyTypeObject *__pyx_memoryview_type = 0; -static PyTypeObject *__pyx_memoryviewslice_type = 0; -static PyObject *generic = 0; -static PyObject *strided = 0; -static PyObject *indirect = 0; -static PyObject *contiguous = 0; -static PyObject *indirect_contiguous = 0; -static int __pyx_memoryview_thread_locks_used; -static PyThread_type_lock __pyx_memoryview_thread_locks[8]; -static void __pyx_f_15monotonic_align_4core_maximum_path_each(__Pyx_memviewslice, __Pyx_memviewslice, int, int, struct __pyx_opt_args_15monotonic_align_4core_maximum_path_each *__pyx_optional_args); /*proto*/ -static void __pyx_f_15monotonic_align_4core_maximum_path_c(__Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice, int __pyx_skip_dispatch); /*proto*/ -static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ -static void *__pyx_align_pointer(void *, size_t); /*proto*/ -static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/ -static CYTHON_INLINE int __pyx_memoryview_check(PyObject *); /*proto*/ -static PyObject *_unellipsify(PyObject *, int); /*proto*/ -static PyObject *assert_direct_dimensions(Py_ssize_t *, int); /*proto*/ -static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *, PyObject *); /*proto*/ -static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int, int); /*proto*/ -static char *__pyx_pybuffer_index(Py_buffer *, char *, Py_ssize_t, Py_ssize_t); /*proto*/ -static int __pyx_memslice_transpose(__Pyx_memviewslice *); /*proto*/ -static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice, int, PyObject *(*)(char *), int (*)(char *, PyObject *), int); /*proto*/ -static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ -static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ -static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *); /*proto*/ -static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ -static Py_ssize_t abs_py_ssize_t(Py_ssize_t); /*proto*/ -static char __pyx_get_best_slice_order(__Pyx_memviewslice *, int); /*proto*/ -static void _copy_strided_to_strided(char *, Py_ssize_t *, char *, Py_ssize_t *, Py_ssize_t *, Py_ssize_t *, int, size_t); /*proto*/ -static void copy_strided_to_strided(__Pyx_memviewslice *, __Pyx_memviewslice *, int, size_t); /*proto*/ -static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *, int); /*proto*/ -static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *, Py_ssize_t *, Py_ssize_t, int, char); /*proto*/ -static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *, __Pyx_memviewslice *, char, int); /*proto*/ -static int __pyx_memoryview_err_extents(int, Py_ssize_t, Py_ssize_t); /*proto*/ -static int __pyx_memoryview_err_dim(PyObject *, char *, int); /*proto*/ -static int __pyx_memoryview_err(PyObject *, char *); /*proto*/ -static int __pyx_memoryview_copy_contents(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int); /*proto*/ -static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *, int, int); /*proto*/ -static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *, int, int, int); /*proto*/ -static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ -static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ -static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/ -static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/ -static PyObject *__pyx_unpickle_Enum__set_state(struct __pyx_MemviewEnum_obj *, PyObject *); /*proto*/ -static __Pyx_TypeInfo __Pyx_TypeInfo_int = { "int", NULL, sizeof(int), { 0 }, 0, IS_UNSIGNED(int) ? 'U' : 'I', IS_UNSIGNED(int), 0 }; -static __Pyx_TypeInfo __Pyx_TypeInfo_float = { "float", NULL, sizeof(float), { 0 }, 0, 'R', 0, 0 }; -#define __Pyx_MODULE_NAME "monotonic_align.core" -extern int __pyx_module_is_main_monotonic_align__core; -int __pyx_module_is_main_monotonic_align__core = 0; - -/* Implementation of 'monotonic_align.core' */ -static PyObject *__pyx_builtin_range; -static PyObject *__pyx_builtin_ValueError; -static PyObject *__pyx_builtin_MemoryError; -static PyObject *__pyx_builtin_enumerate; -static PyObject *__pyx_builtin_TypeError; -static PyObject *__pyx_builtin_Ellipsis; -static PyObject *__pyx_builtin_id; -static PyObject *__pyx_builtin_IndexError; -static const char __pyx_k_O[] = "O"; -static const char __pyx_k_c[] = "c"; -static const char __pyx_k_id[] = "id"; -static const char __pyx_k_new[] = "__new__"; -static const char __pyx_k_obj[] = "obj"; -static const char __pyx_k_base[] = "base"; -static const char __pyx_k_dict[] = "__dict__"; -static const char __pyx_k_main[] = "__main__"; -static const char __pyx_k_mode[] = "mode"; -static const char __pyx_k_name[] = "name"; -static const char __pyx_k_ndim[] = "ndim"; -static const char __pyx_k_pack[] = "pack"; -static const char __pyx_k_size[] = "size"; -static const char __pyx_k_step[] = "step"; -static const char __pyx_k_stop[] = "stop"; -static const char __pyx_k_t_xs[] = "t_xs"; -static const char __pyx_k_t_ys[] = "t_ys"; -static const char __pyx_k_test[] = "__test__"; -static const char __pyx_k_ASCII[] = "ASCII"; -static const char __pyx_k_class[] = "__class__"; -static const char __pyx_k_error[] = "error"; -static const char __pyx_k_flags[] = "flags"; -static const char __pyx_k_paths[] = "paths"; -static const char __pyx_k_range[] = "range"; -static const char __pyx_k_shape[] = "shape"; -static const char __pyx_k_start[] = "start"; -static const char __pyx_k_encode[] = "encode"; -static const char __pyx_k_format[] = "format"; -static const char __pyx_k_import[] = "__import__"; -static const char __pyx_k_name_2[] = "__name__"; -static const char __pyx_k_pickle[] = "pickle"; -static const char __pyx_k_reduce[] = "__reduce__"; -static const char __pyx_k_struct[] = "struct"; -static const char __pyx_k_unpack[] = "unpack"; -static const char __pyx_k_update[] = "update"; -static const char __pyx_k_values[] = "values"; -static const char __pyx_k_fortran[] = "fortran"; -static const char __pyx_k_memview[] = "memview"; -static const char __pyx_k_Ellipsis[] = "Ellipsis"; -static const char __pyx_k_getstate[] = "__getstate__"; -static const char __pyx_k_itemsize[] = "itemsize"; -static const char __pyx_k_pyx_type[] = "__pyx_type"; -static const char __pyx_k_setstate[] = "__setstate__"; -static const char __pyx_k_TypeError[] = "TypeError"; -static const char __pyx_k_enumerate[] = "enumerate"; -static const char __pyx_k_pyx_state[] = "__pyx_state"; -static const char __pyx_k_reduce_ex[] = "__reduce_ex__"; -static const char __pyx_k_IndexError[] = "IndexError"; -static const char __pyx_k_ValueError[] = "ValueError"; -static const char __pyx_k_pyx_result[] = "__pyx_result"; -static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; -static const char __pyx_k_MemoryError[] = "MemoryError"; -static const char __pyx_k_PickleError[] = "PickleError"; -static const char __pyx_k_pyx_checksum[] = "__pyx_checksum"; -static const char __pyx_k_stringsource[] = "stringsource"; -static const char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; -static const char __pyx_k_reduce_cython[] = "__reduce_cython__"; -static const char __pyx_k_View_MemoryView[] = "View.MemoryView"; -static const char __pyx_k_allocate_buffer[] = "allocate_buffer"; -static const char __pyx_k_dtype_is_object[] = "dtype_is_object"; -static const char __pyx_k_pyx_PickleError[] = "__pyx_PickleError"; -static const char __pyx_k_setstate_cython[] = "__setstate_cython__"; -static const char __pyx_k_pyx_unpickle_Enum[] = "__pyx_unpickle_Enum"; -static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; -static const char __pyx_k_strided_and_direct[] = ""; -static const char __pyx_k_strided_and_indirect[] = ""; -static const char __pyx_k_contiguous_and_direct[] = ""; -static const char __pyx_k_MemoryView_of_r_object[] = ""; -static const char __pyx_k_MemoryView_of_r_at_0x_x[] = ""; -static const char __pyx_k_contiguous_and_indirect[] = ""; -static const char __pyx_k_Cannot_index_with_type_s[] = "Cannot index with type '%s'"; -static const char __pyx_k_Invalid_shape_in_axis_d_d[] = "Invalid shape in axis %d: %d."; -static const char __pyx_k_itemsize_0_for_cython_array[] = "itemsize <= 0 for cython.array"; -static const char __pyx_k_unable_to_allocate_array_data[] = "unable to allocate array data."; -static const char __pyx_k_strided_and_direct_or_indirect[] = ""; -static const char __pyx_k_Buffer_view_does_not_expose_stri[] = "Buffer view does not expose strides"; -static const char __pyx_k_Can_only_create_a_buffer_that_is[] = "Can only create a buffer that is contiguous in memory."; -static const char __pyx_k_Cannot_assign_to_read_only_memor[] = "Cannot assign to read-only memoryview"; -static const char __pyx_k_Cannot_create_writable_memory_vi[] = "Cannot create writable memory view from read-only memoryview"; -static const char __pyx_k_Empty_shape_tuple_for_cython_arr[] = "Empty shape tuple for cython.array"; -static const char __pyx_k_Incompatible_checksums_s_vs_0xb0[] = "Incompatible checksums (%s vs 0xb068931 = (name))"; -static const char __pyx_k_Indirect_dimensions_not_supporte[] = "Indirect dimensions not supported"; -static const char __pyx_k_Invalid_mode_expected_c_or_fortr[] = "Invalid mode, expected 'c' or 'fortran', got %s"; -static const char __pyx_k_Out_of_bounds_on_buffer_access_a[] = "Out of bounds on buffer access (axis %d)"; -static const char __pyx_k_Unable_to_convert_item_to_object[] = "Unable to convert item to object"; -static const char __pyx_k_got_differing_extents_in_dimensi[] = "got differing extents in dimension %d (got %d and %d)"; -static const char __pyx_k_no_default___reduce___due_to_non[] = "no default __reduce__ due to non-trivial __cinit__"; -static const char __pyx_k_unable_to_allocate_shape_and_str[] = "unable to allocate shape and strides."; -static PyObject *__pyx_n_s_ASCII; -static PyObject *__pyx_kp_s_Buffer_view_does_not_expose_stri; -static PyObject *__pyx_kp_s_Can_only_create_a_buffer_that_is; -static PyObject *__pyx_kp_s_Cannot_assign_to_read_only_memor; -static PyObject *__pyx_kp_s_Cannot_create_writable_memory_vi; -static PyObject *__pyx_kp_s_Cannot_index_with_type_s; -static PyObject *__pyx_n_s_Ellipsis; -static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr; -static PyObject *__pyx_kp_s_Incompatible_checksums_s_vs_0xb0; -static PyObject *__pyx_n_s_IndexError; -static PyObject *__pyx_kp_s_Indirect_dimensions_not_supporte; -static PyObject *__pyx_kp_s_Invalid_mode_expected_c_or_fortr; -static PyObject *__pyx_kp_s_Invalid_shape_in_axis_d_d; -static PyObject *__pyx_n_s_MemoryError; -static PyObject *__pyx_kp_s_MemoryView_of_r_at_0x_x; -static PyObject *__pyx_kp_s_MemoryView_of_r_object; -static PyObject *__pyx_n_b_O; -static PyObject *__pyx_kp_s_Out_of_bounds_on_buffer_access_a; -static PyObject *__pyx_n_s_PickleError; -static PyObject *__pyx_n_s_TypeError; -static PyObject *__pyx_kp_s_Unable_to_convert_item_to_object; -static PyObject *__pyx_n_s_ValueError; -static PyObject *__pyx_n_s_View_MemoryView; -static PyObject *__pyx_n_s_allocate_buffer; -static PyObject *__pyx_n_s_base; -static PyObject *__pyx_n_s_c; -static PyObject *__pyx_n_u_c; -static PyObject *__pyx_n_s_class; -static PyObject *__pyx_n_s_cline_in_traceback; -static PyObject *__pyx_kp_s_contiguous_and_direct; -static PyObject *__pyx_kp_s_contiguous_and_indirect; -static PyObject *__pyx_n_s_dict; -static PyObject *__pyx_n_s_dtype_is_object; -static PyObject *__pyx_n_s_encode; -static PyObject *__pyx_n_s_enumerate; -static PyObject *__pyx_n_s_error; -static PyObject *__pyx_n_s_flags; -static PyObject *__pyx_n_s_format; -static PyObject *__pyx_n_s_fortran; -static PyObject *__pyx_n_u_fortran; -static PyObject *__pyx_n_s_getstate; -static PyObject *__pyx_kp_s_got_differing_extents_in_dimensi; -static PyObject *__pyx_n_s_id; -static PyObject *__pyx_n_s_import; -static PyObject *__pyx_n_s_itemsize; -static PyObject *__pyx_kp_s_itemsize_0_for_cython_array; -static PyObject *__pyx_n_s_main; -static PyObject *__pyx_n_s_memview; -static PyObject *__pyx_n_s_mode; -static PyObject *__pyx_n_s_name; -static PyObject *__pyx_n_s_name_2; -static PyObject *__pyx_n_s_ndim; -static PyObject *__pyx_n_s_new; -static PyObject *__pyx_kp_s_no_default___reduce___due_to_non; -static PyObject *__pyx_n_s_obj; -static PyObject *__pyx_n_s_pack; -static PyObject *__pyx_n_s_paths; -static PyObject *__pyx_n_s_pickle; -static PyObject *__pyx_n_s_pyx_PickleError; -static PyObject *__pyx_n_s_pyx_checksum; -static PyObject *__pyx_n_s_pyx_getbuffer; -static PyObject *__pyx_n_s_pyx_result; -static PyObject *__pyx_n_s_pyx_state; -static PyObject *__pyx_n_s_pyx_type; -static PyObject *__pyx_n_s_pyx_unpickle_Enum; -static PyObject *__pyx_n_s_pyx_vtable; -static PyObject *__pyx_n_s_range; -static PyObject *__pyx_n_s_reduce; -static PyObject *__pyx_n_s_reduce_cython; -static PyObject *__pyx_n_s_reduce_ex; -static PyObject *__pyx_n_s_setstate; -static PyObject *__pyx_n_s_setstate_cython; -static PyObject *__pyx_n_s_shape; -static PyObject *__pyx_n_s_size; -static PyObject *__pyx_n_s_start; -static PyObject *__pyx_n_s_step; -static PyObject *__pyx_n_s_stop; -static PyObject *__pyx_kp_s_strided_and_direct; -static PyObject *__pyx_kp_s_strided_and_direct_or_indirect; -static PyObject *__pyx_kp_s_strided_and_indirect; -static PyObject *__pyx_kp_s_stringsource; -static PyObject *__pyx_n_s_struct; -static PyObject *__pyx_n_s_t_xs; -static PyObject *__pyx_n_s_t_ys; -static PyObject *__pyx_n_s_test; -static PyObject *__pyx_kp_s_unable_to_allocate_array_data; -static PyObject *__pyx_kp_s_unable_to_allocate_shape_and_str; -static PyObject *__pyx_n_s_unpack; -static PyObject *__pyx_n_s_update; -static PyObject *__pyx_n_s_values; -static PyObject *__pyx_pf_15monotonic_align_4core_maximum_path_c(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_paths, __Pyx_memviewslice __pyx_v_values, __Pyx_memviewslice __pyx_v_t_ys, __Pyx_memviewslice __pyx_v_t_xs); /* proto */ -static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ -static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ -static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ -static Py_ssize_t __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(struct __pyx_array_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ -static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ -static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ -static PyObject *__pyx_pf___pyx_array___reduce_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_array_2__setstate_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ -static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ -static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_MemviewEnum___reduce_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_MemviewEnum_2__setstate_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v___pyx_state); /* proto */ -static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ -static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ -static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ -static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_memoryview___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_memoryview_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ -static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_memoryviewslice___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_memoryviewslice_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state); /* proto */ -static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_int_0; -static PyObject *__pyx_int_1; -static PyObject *__pyx_int_184977713; -static PyObject *__pyx_int_neg_1; -static float __pyx_k_; -static PyObject *__pyx_tuple__2; -static PyObject *__pyx_tuple__3; -static PyObject *__pyx_tuple__4; -static PyObject *__pyx_tuple__5; -static PyObject *__pyx_tuple__6; -static PyObject *__pyx_tuple__7; -static PyObject *__pyx_tuple__8; -static PyObject *__pyx_tuple__9; -static PyObject *__pyx_slice__16; -static PyObject *__pyx_tuple__10; -static PyObject *__pyx_tuple__11; -static PyObject *__pyx_tuple__12; -static PyObject *__pyx_tuple__13; -static PyObject *__pyx_tuple__14; -static PyObject *__pyx_tuple__15; -static PyObject *__pyx_tuple__17; -static PyObject *__pyx_tuple__18; -static PyObject *__pyx_tuple__19; -static PyObject *__pyx_tuple__20; -static PyObject *__pyx_tuple__21; -static PyObject *__pyx_tuple__22; -static PyObject *__pyx_tuple__23; -static PyObject *__pyx_tuple__24; -static PyObject *__pyx_tuple__25; -static PyObject *__pyx_codeobj__26; -/* Late includes */ - -/* "monotonic_align/core.pyx":7 - * @cython.boundscheck(False) - * @cython.wraparound(False) - * cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_y, int t_x, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<< - * cdef int x - * cdef int y - */ - -static void __pyx_f_15monotonic_align_4core_maximum_path_each(__Pyx_memviewslice __pyx_v_path, __Pyx_memviewslice __pyx_v_value, int __pyx_v_t_y, int __pyx_v_t_x, struct __pyx_opt_args_15monotonic_align_4core_maximum_path_each *__pyx_optional_args) { - float __pyx_v_max_neg_val = __pyx_k_; - int __pyx_v_x; - int __pyx_v_y; - float __pyx_v_v_prev; - float __pyx_v_v_cur; - int __pyx_v_index; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - long __pyx_t_4; - int __pyx_t_5; - long __pyx_t_6; - long __pyx_t_7; - int __pyx_t_8; - Py_ssize_t __pyx_t_9; - Py_ssize_t __pyx_t_10; - float __pyx_t_11; - float __pyx_t_12; - float __pyx_t_13; - int __pyx_t_14; - Py_ssize_t __pyx_t_15; - Py_ssize_t __pyx_t_16; - if (__pyx_optional_args) { - if (__pyx_optional_args->__pyx_n > 0) { - __pyx_v_max_neg_val = __pyx_optional_args->max_neg_val; - } - } - - /* "monotonic_align/core.pyx":13 - * cdef float v_cur - * cdef float tmp - * cdef int index = t_x - 1 # <<<<<<<<<<<<<< - * - * for y in range(t_y): - */ - __pyx_v_index = (__pyx_v_t_x - 1); - - /* "monotonic_align/core.pyx":15 - * cdef int index = t_x - 1 - * - * for y in range(t_y): # <<<<<<<<<<<<<< - * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): - * if x == y: - */ - __pyx_t_1 = __pyx_v_t_y; - __pyx_t_2 = __pyx_t_1; - for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { - __pyx_v_y = __pyx_t_3; - - /* "monotonic_align/core.pyx":16 - * - * for y in range(t_y): - * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): # <<<<<<<<<<<<<< - * if x == y: - * v_cur = max_neg_val - */ - __pyx_t_4 = (__pyx_v_y + 1); - __pyx_t_5 = __pyx_v_t_x; - if (((__pyx_t_4 < __pyx_t_5) != 0)) { - __pyx_t_6 = __pyx_t_4; - } else { - __pyx_t_6 = __pyx_t_5; - } - __pyx_t_4 = __pyx_t_6; - __pyx_t_5 = ((__pyx_v_t_x + __pyx_v_y) - __pyx_v_t_y); - __pyx_t_6 = 0; - if (((__pyx_t_5 > __pyx_t_6) != 0)) { - __pyx_t_7 = __pyx_t_5; - } else { - __pyx_t_7 = __pyx_t_6; - } - __pyx_t_6 = __pyx_t_4; - for (__pyx_t_5 = __pyx_t_7; __pyx_t_5 < __pyx_t_6; __pyx_t_5+=1) { - __pyx_v_x = __pyx_t_5; - - /* "monotonic_align/core.pyx":17 - * for y in range(t_y): - * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): - * if x == y: # <<<<<<<<<<<<<< - * v_cur = max_neg_val - * else: - */ - __pyx_t_8 = ((__pyx_v_x == __pyx_v_y) != 0); - if (__pyx_t_8) { - - /* "monotonic_align/core.pyx":18 - * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): - * if x == y: - * v_cur = max_neg_val # <<<<<<<<<<<<<< - * else: - * v_cur = value[y-1, x] - */ - __pyx_v_v_cur = __pyx_v_max_neg_val; - - /* "monotonic_align/core.pyx":17 - * for y in range(t_y): - * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): - * if x == y: # <<<<<<<<<<<<<< - * v_cur = max_neg_val - * else: - */ - goto __pyx_L7; - } - - /* "monotonic_align/core.pyx":20 - * v_cur = max_neg_val - * else: - * v_cur = value[y-1, x] # <<<<<<<<<<<<<< - * if x == 0: - * if y == 0: - */ - /*else*/ { - __pyx_t_9 = (__pyx_v_y - 1); - __pyx_t_10 = __pyx_v_x; - __pyx_v_v_cur = (*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_9 * __pyx_v_value.strides[0]) )) + __pyx_t_10)) ))); - } - __pyx_L7:; - - /* "monotonic_align/core.pyx":21 - * else: - * v_cur = value[y-1, x] - * if x == 0: # <<<<<<<<<<<<<< - * if y == 0: - * v_prev = 0. - */ - __pyx_t_8 = ((__pyx_v_x == 0) != 0); - if (__pyx_t_8) { - - /* "monotonic_align/core.pyx":22 - * v_cur = value[y-1, x] - * if x == 0: - * if y == 0: # <<<<<<<<<<<<<< - * v_prev = 0. - * else: - */ - __pyx_t_8 = ((__pyx_v_y == 0) != 0); - if (__pyx_t_8) { - - /* "monotonic_align/core.pyx":23 - * if x == 0: - * if y == 0: - * v_prev = 0. # <<<<<<<<<<<<<< - * else: - * v_prev = max_neg_val - */ - __pyx_v_v_prev = 0.; - - /* "monotonic_align/core.pyx":22 - * v_cur = value[y-1, x] - * if x == 0: - * if y == 0: # <<<<<<<<<<<<<< - * v_prev = 0. - * else: - */ - goto __pyx_L9; - } - - /* "monotonic_align/core.pyx":25 - * v_prev = 0. - * else: - * v_prev = max_neg_val # <<<<<<<<<<<<<< - * else: - * v_prev = value[y-1, x-1] - */ - /*else*/ { - __pyx_v_v_prev = __pyx_v_max_neg_val; - } - __pyx_L9:; - - /* "monotonic_align/core.pyx":21 - * else: - * v_cur = value[y-1, x] - * if x == 0: # <<<<<<<<<<<<<< - * if y == 0: - * v_prev = 0. - */ - goto __pyx_L8; - } - - /* "monotonic_align/core.pyx":27 - * v_prev = max_neg_val - * else: - * v_prev = value[y-1, x-1] # <<<<<<<<<<<<<< - * value[y, x] += max(v_prev, v_cur) - * - */ - /*else*/ { - __pyx_t_10 = (__pyx_v_y - 1); - __pyx_t_9 = (__pyx_v_x - 1); - __pyx_v_v_prev = (*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_10 * __pyx_v_value.strides[0]) )) + __pyx_t_9)) ))); - } - __pyx_L8:; - - /* "monotonic_align/core.pyx":28 - * else: - * v_prev = value[y-1, x-1] - * value[y, x] += max(v_prev, v_cur) # <<<<<<<<<<<<<< - * - * for y in range(t_y - 1, -1, -1): - */ - __pyx_t_11 = __pyx_v_v_cur; - __pyx_t_12 = __pyx_v_v_prev; - if (((__pyx_t_11 > __pyx_t_12) != 0)) { - __pyx_t_13 = __pyx_t_11; - } else { - __pyx_t_13 = __pyx_t_12; - } - __pyx_t_9 = __pyx_v_y; - __pyx_t_10 = __pyx_v_x; - *((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_9 * __pyx_v_value.strides[0]) )) + __pyx_t_10)) )) += __pyx_t_13; - } - } - - /* "monotonic_align/core.pyx":30 - * value[y, x] += max(v_prev, v_cur) - * - * for y in range(t_y - 1, -1, -1): # <<<<<<<<<<<<<< - * path[y, index] = 1 - * if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]): - */ - for (__pyx_t_1 = (__pyx_v_t_y - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { - __pyx_v_y = __pyx_t_1; - - /* "monotonic_align/core.pyx":31 - * - * for y in range(t_y - 1, -1, -1): - * path[y, index] = 1 # <<<<<<<<<<<<<< - * if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]): - * index = index - 1 - */ - __pyx_t_10 = __pyx_v_y; - __pyx_t_9 = __pyx_v_index; - *((int *) ( /* dim=1 */ ((char *) (((int *) ( /* dim=0 */ (__pyx_v_path.data + __pyx_t_10 * __pyx_v_path.strides[0]) )) + __pyx_t_9)) )) = 1; - - /* "monotonic_align/core.pyx":32 - * for y in range(t_y - 1, -1, -1): - * path[y, index] = 1 - * if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]): # <<<<<<<<<<<<<< - * index = index - 1 - * - */ - __pyx_t_14 = ((__pyx_v_index != 0) != 0); - if (__pyx_t_14) { - } else { - __pyx_t_8 = __pyx_t_14; - goto __pyx_L13_bool_binop_done; - } - __pyx_t_14 = ((__pyx_v_index == __pyx_v_y) != 0); - if (!__pyx_t_14) { - } else { - __pyx_t_8 = __pyx_t_14; - goto __pyx_L13_bool_binop_done; - } - __pyx_t_9 = (__pyx_v_y - 1); - __pyx_t_10 = __pyx_v_index; - __pyx_t_15 = (__pyx_v_y - 1); - __pyx_t_16 = (__pyx_v_index - 1); - __pyx_t_14 = (((*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_9 * __pyx_v_value.strides[0]) )) + __pyx_t_10)) ))) < (*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_15 * __pyx_v_value.strides[0]) )) + __pyx_t_16)) )))) != 0); - __pyx_t_8 = __pyx_t_14; - __pyx_L13_bool_binop_done:; - if (__pyx_t_8) { - - /* "monotonic_align/core.pyx":33 - * path[y, index] = 1 - * if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]): - * index = index - 1 # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_index = (__pyx_v_index - 1); - - /* "monotonic_align/core.pyx":32 - * for y in range(t_y - 1, -1, -1): - * path[y, index] = 1 - * if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]): # <<<<<<<<<<<<<< - * index = index - 1 - * - */ - } - } - - /* "monotonic_align/core.pyx":7 - * @cython.boundscheck(False) - * @cython.wraparound(False) - * cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_y, int t_x, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<< - * cdef int x - * cdef int y - */ - - /* function exit code */ -} - -/* "monotonic_align/core.pyx":38 - * @cython.boundscheck(False) - * @cython.wraparound(False) - * cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_ys, int[::1] t_xs) nogil: # <<<<<<<<<<<<<< - * cdef int b = paths.shape[0] - * cdef int i - */ - -static PyObject *__pyx_pw_15monotonic_align_4core_1maximum_path_c(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static void __pyx_f_15monotonic_align_4core_maximum_path_c(__Pyx_memviewslice __pyx_v_paths, __Pyx_memviewslice __pyx_v_values, __Pyx_memviewslice __pyx_v_t_ys, __Pyx_memviewslice __pyx_v_t_xs, CYTHON_UNUSED int __pyx_skip_dispatch) { - CYTHON_UNUSED int __pyx_v_b; - int __pyx_v_i; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - __Pyx_memviewslice __pyx_t_4 = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; - Py_ssize_t __pyx_t_6; - Py_ssize_t __pyx_t_7; - - /* "monotonic_align/core.pyx":39 - * @cython.wraparound(False) - * cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_ys, int[::1] t_xs) nogil: - * cdef int b = paths.shape[0] # <<<<<<<<<<<<<< - * cdef int i - * for i in prange(b, nogil=True): - */ - __pyx_v_b = (__pyx_v_paths.shape[0]); - - /* "monotonic_align/core.pyx":41 - * cdef int b = paths.shape[0] - * cdef int i - * for i in prange(b, nogil=True): # <<<<<<<<<<<<<< - * maximum_path_each(paths[i], values[i], t_ys[i], t_xs[i]) - */ - { - #ifdef WITH_THREAD - PyThreadState *_save; - Py_UNBLOCK_THREADS - __Pyx_FastGIL_Remember(); - #endif - /*try:*/ { - __pyx_t_1 = __pyx_v_b; - if ((1 == 0)) abort(); - { - #if ((defined(__APPLE__) || defined(__OSX__)) && (defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))))) - #undef likely - #undef unlikely - #define likely(x) (x) - #define unlikely(x) (x) - #endif - __pyx_t_3 = (__pyx_t_1 - 0 + 1 - 1/abs(1)) / 1; - if (__pyx_t_3 > 0) - { - #ifdef _OPENMP - #pragma omp parallel private(__pyx_t_6, __pyx_t_7) firstprivate(__pyx_t_4, __pyx_t_5) - #endif /* _OPENMP */ - { - #ifdef _OPENMP - #pragma omp for firstprivate(__pyx_v_i) lastprivate(__pyx_v_i) - #endif /* _OPENMP */ - for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_3; __pyx_t_2++){ - { - __pyx_v_i = (int)(0 + 1 * __pyx_t_2); - - /* "monotonic_align/core.pyx":42 - * cdef int i - * for i in prange(b, nogil=True): - * maximum_path_each(paths[i], values[i], t_ys[i], t_xs[i]) # <<<<<<<<<<<<<< - */ - __pyx_t_4.data = __pyx_v_paths.data; - __pyx_t_4.memview = __pyx_v_paths.memview; - __PYX_INC_MEMVIEW(&__pyx_t_4, 0); - { - Py_ssize_t __pyx_tmp_idx = __pyx_v_i; - Py_ssize_t __pyx_tmp_stride = __pyx_v_paths.strides[0]; - __pyx_t_4.data += __pyx_tmp_idx * __pyx_tmp_stride; -} - -__pyx_t_4.shape[0] = __pyx_v_paths.shape[1]; -__pyx_t_4.strides[0] = __pyx_v_paths.strides[1]; - __pyx_t_4.suboffsets[0] = -1; - -__pyx_t_4.shape[1] = __pyx_v_paths.shape[2]; -__pyx_t_4.strides[1] = __pyx_v_paths.strides[2]; - __pyx_t_4.suboffsets[1] = -1; - -__pyx_t_5.data = __pyx_v_values.data; - __pyx_t_5.memview = __pyx_v_values.memview; - __PYX_INC_MEMVIEW(&__pyx_t_5, 0); - { - Py_ssize_t __pyx_tmp_idx = __pyx_v_i; - Py_ssize_t __pyx_tmp_stride = __pyx_v_values.strides[0]; - __pyx_t_5.data += __pyx_tmp_idx * __pyx_tmp_stride; -} - -__pyx_t_5.shape[0] = __pyx_v_values.shape[1]; -__pyx_t_5.strides[0] = __pyx_v_values.strides[1]; - __pyx_t_5.suboffsets[0] = -1; - -__pyx_t_5.shape[1] = __pyx_v_values.shape[2]; -__pyx_t_5.strides[1] = __pyx_v_values.strides[2]; - __pyx_t_5.suboffsets[1] = -1; - -__pyx_t_6 = __pyx_v_i; - __pyx_t_7 = __pyx_v_i; - __pyx_f_15monotonic_align_4core_maximum_path_each(__pyx_t_4, __pyx_t_5, (*((int *) ( /* dim=0 */ ((char *) (((int *) __pyx_v_t_ys.data) + __pyx_t_6)) ))), (*((int *) ( /* dim=0 */ ((char *) (((int *) __pyx_v_t_xs.data) + __pyx_t_7)) ))), NULL); - __PYX_XDEC_MEMVIEW(&__pyx_t_4, 0); - __pyx_t_4.memview = NULL; - __pyx_t_4.data = NULL; - __PYX_XDEC_MEMVIEW(&__pyx_t_5, 0); - __pyx_t_5.memview = NULL; - __pyx_t_5.data = NULL; - } - } - } - } - } - #if ((defined(__APPLE__) || defined(__OSX__)) && (defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))))) - #undef likely - #undef unlikely - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) - #endif - } - - /* "monotonic_align/core.pyx":41 - * cdef int b = paths.shape[0] - * cdef int i - * for i in prange(b, nogil=True): # <<<<<<<<<<<<<< - * maximum_path_each(paths[i], values[i], t_ys[i], t_xs[i]) - */ - /*finally:*/ { - /*normal exit:*/{ - #ifdef WITH_THREAD - __Pyx_FastGIL_Forget(); - Py_BLOCK_THREADS - #endif - goto __pyx_L5; - } - __pyx_L5:; - } - } - - /* "monotonic_align/core.pyx":38 - * @cython.boundscheck(False) - * @cython.wraparound(False) - * cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_ys, int[::1] t_xs) nogil: # <<<<<<<<<<<<<< - * cdef int b = paths.shape[0] - * cdef int i - */ - - /* function exit code */ -} - -/* Python wrapper */ -static PyObject *__pyx_pw_15monotonic_align_4core_1maximum_path_c(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pw_15monotonic_align_4core_1maximum_path_c(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - __Pyx_memviewslice __pyx_v_paths = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_memviewslice __pyx_v_values = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_memviewslice __pyx_v_t_ys = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_memviewslice __pyx_v_t_xs = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("maximum_path_c (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_paths,&__pyx_n_s_values,&__pyx_n_s_t_ys,&__pyx_n_s_t_xs,0}; - PyObject* values[4] = {0,0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_paths)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_values)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("maximum_path_c", 1, 4, 4, 1); __PYX_ERR(0, 38, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_t_ys)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("maximum_path_c", 1, 4, 4, 2); __PYX_ERR(0, 38, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_t_xs)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("maximum_path_c", 1, 4, 4, 3); __PYX_ERR(0, 38, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "maximum_path_c") < 0)) __PYX_ERR(0, 38, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - } - __pyx_v_paths = __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_int(values[0], PyBUF_WRITABLE); if (unlikely(!__pyx_v_paths.memview)) __PYX_ERR(0, 38, __pyx_L3_error) - __pyx_v_values = __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_float(values[1], PyBUF_WRITABLE); if (unlikely(!__pyx_v_values.memview)) __PYX_ERR(0, 38, __pyx_L3_error) - __pyx_v_t_ys = __Pyx_PyObject_to_MemoryviewSlice_dc_int(values[2], PyBUF_WRITABLE); if (unlikely(!__pyx_v_t_ys.memview)) __PYX_ERR(0, 38, __pyx_L3_error) - __pyx_v_t_xs = __Pyx_PyObject_to_MemoryviewSlice_dc_int(values[3], PyBUF_WRITABLE); if (unlikely(!__pyx_v_t_xs.memview)) __PYX_ERR(0, 38, __pyx_L3_error) - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("maximum_path_c", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 38, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("monotonic_align.core.maximum_path_c", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_15monotonic_align_4core_maximum_path_c(__pyx_self, __pyx_v_paths, __pyx_v_values, __pyx_v_t_ys, __pyx_v_t_xs); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15monotonic_align_4core_maximum_path_c(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_paths, __Pyx_memviewslice __pyx_v_values, __Pyx_memviewslice __pyx_v_t_ys, __Pyx_memviewslice __pyx_v_t_xs) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("maximum_path_c", 0); - __Pyx_XDECREF(__pyx_r); - if (unlikely(!__pyx_v_paths.memview)) { __Pyx_RaiseUnboundLocalError("paths"); __PYX_ERR(0, 38, __pyx_L1_error) } - if (unlikely(!__pyx_v_values.memview)) { __Pyx_RaiseUnboundLocalError("values"); __PYX_ERR(0, 38, __pyx_L1_error) } - if (unlikely(!__pyx_v_t_ys.memview)) { __Pyx_RaiseUnboundLocalError("t_ys"); __PYX_ERR(0, 38, __pyx_L1_error) } - if (unlikely(!__pyx_v_t_xs.memview)) { __Pyx_RaiseUnboundLocalError("t_xs"); __PYX_ERR(0, 38, __pyx_L1_error) } - __pyx_t_1 = __Pyx_void_to_None(__pyx_f_15monotonic_align_4core_maximum_path_c(__pyx_v_paths, __pyx_v_values, __pyx_v_t_ys, __pyx_v_t_xs, 0)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 38, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("monotonic_align.core.maximum_path_c", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __PYX_XDEC_MEMVIEW(&__pyx_v_paths, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_values, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_t_ys, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_t_xs, 1); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":122 - * cdef bint dtype_is_object - * - * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< - * mode="c", bint allocate_buffer=True): - * - */ - -/* Python wrapper */ -static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_shape = 0; - Py_ssize_t __pyx_v_itemsize; - PyObject *__pyx_v_format = 0; - PyObject *__pyx_v_mode = 0; - int __pyx_v_allocate_buffer; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_shape,&__pyx_n_s_itemsize,&__pyx_n_s_format,&__pyx_n_s_mode,&__pyx_n_s_allocate_buffer,0}; - PyObject* values[5] = {0,0,0,0,0}; - values[3] = ((PyObject *)__pyx_n_s_c); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - CYTHON_FALLTHROUGH; - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_shape)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_itemsize)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); __PYX_ERR(1, 122, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_format)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); __PYX_ERR(1, 122, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_mode); - if (value) { values[3] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 4: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_allocate_buffer); - if (value) { values[4] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) __PYX_ERR(1, 122, __pyx_L3_error) - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - CYTHON_FALLTHROUGH; - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_shape = ((PyObject*)values[0]); - __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 122, __pyx_L3_error) - __pyx_v_format = values[2]; - __pyx_v_mode = values[3]; - if (values[4]) { - __pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 123, __pyx_L3_error) - } else { - - /* "View.MemoryView":123 - * - * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, - * mode="c", bint allocate_buffer=True): # <<<<<<<<<<<<<< - * - * cdef int idx - */ - __pyx_v_allocate_buffer = ((int)1); - } - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 122, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) __PYX_ERR(1, 122, __pyx_L1_error) - if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { - PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); __PYX_ERR(1, 122, __pyx_L1_error) - } - __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer); - - /* "View.MemoryView":122 - * cdef bint dtype_is_object - * - * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< - * mode="c", bint allocate_buffer=True): - * - */ - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) { - int __pyx_v_idx; - Py_ssize_t __pyx_v_i; - Py_ssize_t __pyx_v_dim; - PyObject **__pyx_v_p; - char __pyx_v_order; - int __pyx_r; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - char *__pyx_t_7; - int __pyx_t_8; - Py_ssize_t __pyx_t_9; - PyObject *__pyx_t_10 = NULL; - Py_ssize_t __pyx_t_11; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__cinit__", 0); - __Pyx_INCREF(__pyx_v_format); - - /* "View.MemoryView":129 - * cdef PyObject **p - * - * self.ndim = len(shape) # <<<<<<<<<<<<<< - * self.itemsize = itemsize - * - */ - if (unlikely(__pyx_v_shape == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - __PYX_ERR(1, 129, __pyx_L1_error) - } - __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(1, 129, __pyx_L1_error) - __pyx_v_self->ndim = ((int)__pyx_t_1); - - /* "View.MemoryView":130 - * - * self.ndim = len(shape) - * self.itemsize = itemsize # <<<<<<<<<<<<<< - * - * if not self.ndim: - */ - __pyx_v_self->itemsize = __pyx_v_itemsize; - - /* "View.MemoryView":132 - * self.itemsize = itemsize - * - * if not self.ndim: # <<<<<<<<<<<<<< - * raise ValueError("Empty shape tuple for cython.array") - * - */ - __pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0); - if (unlikely(__pyx_t_2)) { - - /* "View.MemoryView":133 - * - * if not self.ndim: - * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< - * - * if itemsize <= 0: - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 133, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 133, __pyx_L1_error) - - /* "View.MemoryView":132 - * self.itemsize = itemsize - * - * if not self.ndim: # <<<<<<<<<<<<<< - * raise ValueError("Empty shape tuple for cython.array") - * - */ - } - - /* "View.MemoryView":135 - * raise ValueError("Empty shape tuple for cython.array") - * - * if itemsize <= 0: # <<<<<<<<<<<<<< - * raise ValueError("itemsize <= 0 for cython.array") - * - */ - __pyx_t_2 = ((__pyx_v_itemsize <= 0) != 0); - if (unlikely(__pyx_t_2)) { - - /* "View.MemoryView":136 - * - * if itemsize <= 0: - * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< - * - * if not isinstance(format, bytes): - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 136, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 136, __pyx_L1_error) - - /* "View.MemoryView":135 - * raise ValueError("Empty shape tuple for cython.array") - * - * if itemsize <= 0: # <<<<<<<<<<<<<< - * raise ValueError("itemsize <= 0 for cython.array") - * - */ - } - - /* "View.MemoryView":138 - * raise ValueError("itemsize <= 0 for cython.array") - * - * if not isinstance(format, bytes): # <<<<<<<<<<<<<< - * format = format.encode('ASCII') - * self._format = format # keep a reference to the byte string - */ - __pyx_t_2 = PyBytes_Check(__pyx_v_format); - __pyx_t_4 = ((!(__pyx_t_2 != 0)) != 0); - if (__pyx_t_4) { - - /* "View.MemoryView":139 - * - * if not isinstance(format, bytes): - * format = format.encode('ASCII') # <<<<<<<<<<<<<< - * self._format = format # keep a reference to the byte string - * self.format = self._format - */ - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_format, __pyx_n_s_encode); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 139, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_5))) { - __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_5); - if (likely(__pyx_t_6)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_5, function); - } - } - __pyx_t_3 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_5, __pyx_t_6, __pyx_n_s_ASCII) : __Pyx_PyObject_CallOneArg(__pyx_t_5, __pyx_n_s_ASCII); - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 139, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF_SET(__pyx_v_format, __pyx_t_3); - __pyx_t_3 = 0; - - /* "View.MemoryView":138 - * raise ValueError("itemsize <= 0 for cython.array") - * - * if not isinstance(format, bytes): # <<<<<<<<<<<<<< - * format = format.encode('ASCII') - * self._format = format # keep a reference to the byte string - */ - } - - /* "View.MemoryView":140 - * if not isinstance(format, bytes): - * format = format.encode('ASCII') - * self._format = format # keep a reference to the byte string # <<<<<<<<<<<<<< - * self.format = self._format - * - */ - if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_v_format)->tp_name), 0))) __PYX_ERR(1, 140, __pyx_L1_error) - __pyx_t_3 = __pyx_v_format; - __Pyx_INCREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_GOTREF(__pyx_v_self->_format); - __Pyx_DECREF(__pyx_v_self->_format); - __pyx_v_self->_format = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "View.MemoryView":141 - * format = format.encode('ASCII') - * self._format = format # keep a reference to the byte string - * self.format = self._format # <<<<<<<<<<<<<< - * - * - */ - if (unlikely(__pyx_v_self->_format == Py_None)) { - PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); - __PYX_ERR(1, 141, __pyx_L1_error) - } - __pyx_t_7 = __Pyx_PyBytes_AsWritableString(__pyx_v_self->_format); if (unlikely((!__pyx_t_7) && PyErr_Occurred())) __PYX_ERR(1, 141, __pyx_L1_error) - __pyx_v_self->format = __pyx_t_7; - - /* "View.MemoryView":144 - * - * - * self._shape = PyObject_Malloc(sizeof(Py_ssize_t)*self.ndim*2) # <<<<<<<<<<<<<< - * self._strides = self._shape + self.ndim - * - */ - __pyx_v_self->_shape = ((Py_ssize_t *)PyObject_Malloc((((sizeof(Py_ssize_t)) * __pyx_v_self->ndim) * 2))); - - /* "View.MemoryView":145 - * - * self._shape = PyObject_Malloc(sizeof(Py_ssize_t)*self.ndim*2) - * self._strides = self._shape + self.ndim # <<<<<<<<<<<<<< - * - * if not self._shape: - */ - __pyx_v_self->_strides = (__pyx_v_self->_shape + __pyx_v_self->ndim); - - /* "View.MemoryView":147 - * self._strides = self._shape + self.ndim - * - * if not self._shape: # <<<<<<<<<<<<<< - * raise MemoryError("unable to allocate shape and strides.") - * - */ - __pyx_t_4 = ((!(__pyx_v_self->_shape != 0)) != 0); - if (unlikely(__pyx_t_4)) { - - /* "View.MemoryView":148 - * - * if not self._shape: - * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 148, __pyx_L1_error) - - /* "View.MemoryView":147 - * self._strides = self._shape + self.ndim - * - * if not self._shape: # <<<<<<<<<<<<<< - * raise MemoryError("unable to allocate shape and strides.") - * - */ - } - - /* "View.MemoryView":151 - * - * - * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< - * if dim <= 0: - * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) - */ - __pyx_t_8 = 0; - __pyx_t_3 = __pyx_v_shape; __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0; - for (;;) { - if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_5); __pyx_t_1++; if (unlikely(0 < 0)) __PYX_ERR(1, 151, __pyx_L1_error) - #else - __pyx_t_5 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 151, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - __pyx_t_9 = __Pyx_PyIndex_AsSsize_t(__pyx_t_5); if (unlikely((__pyx_t_9 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 151, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_v_dim = __pyx_t_9; - __pyx_v_idx = __pyx_t_8; - __pyx_t_8 = (__pyx_t_8 + 1); - - /* "View.MemoryView":152 - * - * for idx, dim in enumerate(shape): - * if dim <= 0: # <<<<<<<<<<<<<< - * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) - * self._shape[idx] = dim - */ - __pyx_t_4 = ((__pyx_v_dim <= 0) != 0); - if (unlikely(__pyx_t_4)) { - - /* "View.MemoryView":153 - * for idx, dim in enumerate(shape): - * if dim <= 0: - * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) # <<<<<<<<<<<<<< - * self._shape[idx] = dim - * - */ - __pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_6); - __pyx_t_5 = 0; - __pyx_t_6 = 0; - __pyx_t_6 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_t_10); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_10 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_6); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_Raise(__pyx_t_10, 0, 0, 0); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __PYX_ERR(1, 153, __pyx_L1_error) - - /* "View.MemoryView":152 - * - * for idx, dim in enumerate(shape): - * if dim <= 0: # <<<<<<<<<<<<<< - * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) - * self._shape[idx] = dim - */ - } - - /* "View.MemoryView":154 - * if dim <= 0: - * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) - * self._shape[idx] = dim # <<<<<<<<<<<<<< - * - * cdef char order - */ - (__pyx_v_self->_shape[__pyx_v_idx]) = __pyx_v_dim; - - /* "View.MemoryView":151 - * - * - * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< - * if dim <= 0: - * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) - */ - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":157 - * - * cdef char order - * if mode == 'fortran': # <<<<<<<<<<<<<< - * order = b'F' - * self.mode = u'fortran' - */ - __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_fortran, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(1, 157, __pyx_L1_error) - if (__pyx_t_4) { - - /* "View.MemoryView":158 - * cdef char order - * if mode == 'fortran': - * order = b'F' # <<<<<<<<<<<<<< - * self.mode = u'fortran' - * elif mode == 'c': - */ - __pyx_v_order = 'F'; - - /* "View.MemoryView":159 - * if mode == 'fortran': - * order = b'F' - * self.mode = u'fortran' # <<<<<<<<<<<<<< - * elif mode == 'c': - * order = b'C' - */ - __Pyx_INCREF(__pyx_n_u_fortran); - __Pyx_GIVEREF(__pyx_n_u_fortran); - __Pyx_GOTREF(__pyx_v_self->mode); - __Pyx_DECREF(__pyx_v_self->mode); - __pyx_v_self->mode = __pyx_n_u_fortran; - - /* "View.MemoryView":157 - * - * cdef char order - * if mode == 'fortran': # <<<<<<<<<<<<<< - * order = b'F' - * self.mode = u'fortran' - */ - goto __pyx_L10; - } - - /* "View.MemoryView":160 - * order = b'F' - * self.mode = u'fortran' - * elif mode == 'c': # <<<<<<<<<<<<<< - * order = b'C' - * self.mode = u'c' - */ - __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_c, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(1, 160, __pyx_L1_error) - if (likely(__pyx_t_4)) { - - /* "View.MemoryView":161 - * self.mode = u'fortran' - * elif mode == 'c': - * order = b'C' # <<<<<<<<<<<<<< - * self.mode = u'c' - * else: - */ - __pyx_v_order = 'C'; - - /* "View.MemoryView":162 - * elif mode == 'c': - * order = b'C' - * self.mode = u'c' # <<<<<<<<<<<<<< - * else: - * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) - */ - __Pyx_INCREF(__pyx_n_u_c); - __Pyx_GIVEREF(__pyx_n_u_c); - __Pyx_GOTREF(__pyx_v_self->mode); - __Pyx_DECREF(__pyx_v_self->mode); - __pyx_v_self->mode = __pyx_n_u_c; - - /* "View.MemoryView":160 - * order = b'F' - * self.mode = u'fortran' - * elif mode == 'c': # <<<<<<<<<<<<<< - * order = b'C' - * self.mode = u'c' - */ - goto __pyx_L10; - } - - /* "View.MemoryView":164 - * self.mode = u'c' - * else: - * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) # <<<<<<<<<<<<<< - * - * self.len = fill_contig_strides_array(self._shape, self._strides, - */ - /*else*/ { - __pyx_t_3 = __Pyx_PyString_FormatSafe(__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_v_mode); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 164, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_10 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 164, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_10, 0, 0, 0); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __PYX_ERR(1, 164, __pyx_L1_error) - } - __pyx_L10:; - - /* "View.MemoryView":166 - * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) - * - * self.len = fill_contig_strides_array(self._shape, self._strides, # <<<<<<<<<<<<<< - * itemsize, self.ndim, order) - * - */ - __pyx_v_self->len = __pyx_fill_contig_strides_array(__pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_itemsize, __pyx_v_self->ndim, __pyx_v_order); - - /* "View.MemoryView":169 - * itemsize, self.ndim, order) - * - * self.free_data = allocate_buffer # <<<<<<<<<<<<<< - * self.dtype_is_object = format == b'O' - * if allocate_buffer: - */ - __pyx_v_self->free_data = __pyx_v_allocate_buffer; - - /* "View.MemoryView":170 - * - * self.free_data = allocate_buffer - * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< - * if allocate_buffer: - * - */ - __pyx_t_10 = PyObject_RichCompare(__pyx_v_format, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_10); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 170, __pyx_L1_error) - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_10); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 170, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_v_self->dtype_is_object = __pyx_t_4; - - /* "View.MemoryView":171 - * self.free_data = allocate_buffer - * self.dtype_is_object = format == b'O' - * if allocate_buffer: # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_4 = (__pyx_v_allocate_buffer != 0); - if (__pyx_t_4) { - - /* "View.MemoryView":174 - * - * - * self.data = malloc(self.len) # <<<<<<<<<<<<<< - * if not self.data: - * raise MemoryError("unable to allocate array data.") - */ - __pyx_v_self->data = ((char *)malloc(__pyx_v_self->len)); - - /* "View.MemoryView":175 - * - * self.data = malloc(self.len) - * if not self.data: # <<<<<<<<<<<<<< - * raise MemoryError("unable to allocate array data.") - * - */ - __pyx_t_4 = ((!(__pyx_v_self->data != 0)) != 0); - if (unlikely(__pyx_t_4)) { - - /* "View.MemoryView":176 - * self.data = malloc(self.len) - * if not self.data: - * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< - * - * if self.dtype_is_object: - */ - __pyx_t_10 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 176, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_Raise(__pyx_t_10, 0, 0, 0); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __PYX_ERR(1, 176, __pyx_L1_error) - - /* "View.MemoryView":175 - * - * self.data = malloc(self.len) - * if not self.data: # <<<<<<<<<<<<<< - * raise MemoryError("unable to allocate array data.") - * - */ - } - - /* "View.MemoryView":178 - * raise MemoryError("unable to allocate array data.") - * - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * p = self.data - * for i in range(self.len / itemsize): - */ - __pyx_t_4 = (__pyx_v_self->dtype_is_object != 0); - if (__pyx_t_4) { - - /* "View.MemoryView":179 - * - * if self.dtype_is_object: - * p = self.data # <<<<<<<<<<<<<< - * for i in range(self.len / itemsize): - * p[i] = Py_None - */ - __pyx_v_p = ((PyObject **)__pyx_v_self->data); - - /* "View.MemoryView":180 - * if self.dtype_is_object: - * p = self.data - * for i in range(self.len / itemsize): # <<<<<<<<<<<<<< - * p[i] = Py_None - * Py_INCREF(Py_None) - */ - if (unlikely(__pyx_v_itemsize == 0)) { - PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); - __PYX_ERR(1, 180, __pyx_L1_error) - } - else if (sizeof(Py_ssize_t) == sizeof(long) && (!(((Py_ssize_t)-1) > 0)) && unlikely(__pyx_v_itemsize == (Py_ssize_t)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { - PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); - __PYX_ERR(1, 180, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_div_Py_ssize_t(__pyx_v_self->len, __pyx_v_itemsize); - __pyx_t_9 = __pyx_t_1; - for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_9; __pyx_t_11+=1) { - __pyx_v_i = __pyx_t_11; - - /* "View.MemoryView":181 - * p = self.data - * for i in range(self.len / itemsize): - * p[i] = Py_None # <<<<<<<<<<<<<< - * Py_INCREF(Py_None) - * - */ - (__pyx_v_p[__pyx_v_i]) = Py_None; - - /* "View.MemoryView":182 - * for i in range(self.len / itemsize): - * p[i] = Py_None - * Py_INCREF(Py_None) # <<<<<<<<<<<<<< - * - * @cname('getbuffer') - */ - Py_INCREF(Py_None); - } - - /* "View.MemoryView":178 - * raise MemoryError("unable to allocate array data.") - * - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * p = self.data - * for i in range(self.len / itemsize): - */ - } - - /* "View.MemoryView":171 - * self.free_data = allocate_buffer - * self.dtype_is_object = format == b'O' - * if allocate_buffer: # <<<<<<<<<<<<<< - * - * - */ - } - - /* "View.MemoryView":122 - * cdef bint dtype_is_object - * - * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< - * mode="c", bint allocate_buffer=True): - * - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_format); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":185 - * - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< - * cdef int bufmode = -1 - * if self.mode == u"c": - */ - -/* Python wrapper */ -static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); - __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_v_bufmode; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - char *__pyx_t_4; - Py_ssize_t __pyx_t_5; - int __pyx_t_6; - Py_ssize_t *__pyx_t_7; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - if (__pyx_v_info == NULL) { - PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); - return -1; - } - __Pyx_RefNannySetupContext("__getbuffer__", 0); - __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(__pyx_v_info->obj); - - /* "View.MemoryView":186 - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): - * cdef int bufmode = -1 # <<<<<<<<<<<<<< - * if self.mode == u"c": - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - */ - __pyx_v_bufmode = -1; - - /* "View.MemoryView":187 - * def __getbuffer__(self, Py_buffer *info, int flags): - * cdef int bufmode = -1 - * if self.mode == u"c": # <<<<<<<<<<<<<< - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * elif self.mode == u"fortran": - */ - __pyx_t_1 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_c, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 187, __pyx_L1_error) - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":188 - * cdef int bufmode = -1 - * if self.mode == u"c": - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< - * elif self.mode == u"fortran": - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - */ - __pyx_v_bufmode = (PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); - - /* "View.MemoryView":187 - * def __getbuffer__(self, Py_buffer *info, int flags): - * cdef int bufmode = -1 - * if self.mode == u"c": # <<<<<<<<<<<<<< - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * elif self.mode == u"fortran": - */ - goto __pyx_L3; - } - - /* "View.MemoryView":189 - * if self.mode == u"c": - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * elif self.mode == u"fortran": # <<<<<<<<<<<<<< - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * if not (flags & bufmode): - */ - __pyx_t_2 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_fortran, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(1, 189, __pyx_L1_error) - __pyx_t_1 = (__pyx_t_2 != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":190 - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * elif self.mode == u"fortran": - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< - * if not (flags & bufmode): - * raise ValueError("Can only create a buffer that is contiguous in memory.") - */ - __pyx_v_bufmode = (PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); - - /* "View.MemoryView":189 - * if self.mode == u"c": - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * elif self.mode == u"fortran": # <<<<<<<<<<<<<< - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * if not (flags & bufmode): - */ - } - __pyx_L3:; - - /* "View.MemoryView":191 - * elif self.mode == u"fortran": - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * if not (flags & bufmode): # <<<<<<<<<<<<<< - * raise ValueError("Can only create a buffer that is contiguous in memory.") - * info.buf = self.data - */ - __pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0); - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":192 - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * if not (flags & bufmode): - * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< - * info.buf = self.data - * info.len = self.len - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 192, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 192, __pyx_L1_error) - - /* "View.MemoryView":191 - * elif self.mode == u"fortran": - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * if not (flags & bufmode): # <<<<<<<<<<<<<< - * raise ValueError("Can only create a buffer that is contiguous in memory.") - * info.buf = self.data - */ - } - - /* "View.MemoryView":193 - * if not (flags & bufmode): - * raise ValueError("Can only create a buffer that is contiguous in memory.") - * info.buf = self.data # <<<<<<<<<<<<<< - * info.len = self.len - * info.ndim = self.ndim - */ - __pyx_t_4 = __pyx_v_self->data; - __pyx_v_info->buf = __pyx_t_4; - - /* "View.MemoryView":194 - * raise ValueError("Can only create a buffer that is contiguous in memory.") - * info.buf = self.data - * info.len = self.len # <<<<<<<<<<<<<< - * info.ndim = self.ndim - * info.shape = self._shape - */ - __pyx_t_5 = __pyx_v_self->len; - __pyx_v_info->len = __pyx_t_5; - - /* "View.MemoryView":195 - * info.buf = self.data - * info.len = self.len - * info.ndim = self.ndim # <<<<<<<<<<<<<< - * info.shape = self._shape - * info.strides = self._strides - */ - __pyx_t_6 = __pyx_v_self->ndim; - __pyx_v_info->ndim = __pyx_t_6; - - /* "View.MemoryView":196 - * info.len = self.len - * info.ndim = self.ndim - * info.shape = self._shape # <<<<<<<<<<<<<< - * info.strides = self._strides - * info.suboffsets = NULL - */ - __pyx_t_7 = __pyx_v_self->_shape; - __pyx_v_info->shape = __pyx_t_7; - - /* "View.MemoryView":197 - * info.ndim = self.ndim - * info.shape = self._shape - * info.strides = self._strides # <<<<<<<<<<<<<< - * info.suboffsets = NULL - * info.itemsize = self.itemsize - */ - __pyx_t_7 = __pyx_v_self->_strides; - __pyx_v_info->strides = __pyx_t_7; - - /* "View.MemoryView":198 - * info.shape = self._shape - * info.strides = self._strides - * info.suboffsets = NULL # <<<<<<<<<<<<<< - * info.itemsize = self.itemsize - * info.readonly = 0 - */ - __pyx_v_info->suboffsets = NULL; - - /* "View.MemoryView":199 - * info.strides = self._strides - * info.suboffsets = NULL - * info.itemsize = self.itemsize # <<<<<<<<<<<<<< - * info.readonly = 0 - * - */ - __pyx_t_5 = __pyx_v_self->itemsize; - __pyx_v_info->itemsize = __pyx_t_5; - - /* "View.MemoryView":200 - * info.suboffsets = NULL - * info.itemsize = self.itemsize - * info.readonly = 0 # <<<<<<<<<<<<<< - * - * if flags & PyBUF_FORMAT: - */ - __pyx_v_info->readonly = 0; - - /* "View.MemoryView":202 - * info.readonly = 0 - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * info.format = self.format - * else: - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":203 - * - * if flags & PyBUF_FORMAT: - * info.format = self.format # <<<<<<<<<<<<<< - * else: - * info.format = NULL - */ - __pyx_t_4 = __pyx_v_self->format; - __pyx_v_info->format = __pyx_t_4; - - /* "View.MemoryView":202 - * info.readonly = 0 - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * info.format = self.format - * else: - */ - goto __pyx_L5; - } - - /* "View.MemoryView":205 - * info.format = self.format - * else: - * info.format = NULL # <<<<<<<<<<<<<< - * - * info.obj = self - */ - /*else*/ { - __pyx_v_info->format = NULL; - } - __pyx_L5:; - - /* "View.MemoryView":207 - * info.format = NULL - * - * info.obj = self # <<<<<<<<<<<<<< - * - * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") - */ - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = ((PyObject *)__pyx_v_self); - - /* "View.MemoryView":185 - * - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< - * cdef int bufmode = -1 - * if self.mode == u"c": - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - if (__pyx_v_info->obj != NULL) { - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; - } - goto __pyx_L2; - __pyx_L0:; - if (__pyx_v_info->obj == Py_None) { - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; - } - __pyx_L2:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":211 - * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") - * - * def __dealloc__(array self): # <<<<<<<<<<<<<< - * if self.callback_free_data != NULL: - * self.callback_free_data(self.data) - */ - -/* Python wrapper */ -static void __pyx_array___dealloc__(PyObject *__pyx_v_self); /*proto*/ -static void __pyx_array___dealloc__(PyObject *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); - __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) { - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("__dealloc__", 0); - - /* "View.MemoryView":212 - * - * def __dealloc__(array self): - * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< - * self.callback_free_data(self.data) - * elif self.free_data: - */ - __pyx_t_1 = ((__pyx_v_self->callback_free_data != NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":213 - * def __dealloc__(array self): - * if self.callback_free_data != NULL: - * self.callback_free_data(self.data) # <<<<<<<<<<<<<< - * elif self.free_data: - * if self.dtype_is_object: - */ - __pyx_v_self->callback_free_data(__pyx_v_self->data); - - /* "View.MemoryView":212 - * - * def __dealloc__(array self): - * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< - * self.callback_free_data(self.data) - * elif self.free_data: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":214 - * if self.callback_free_data != NULL: - * self.callback_free_data(self.data) - * elif self.free_data: # <<<<<<<<<<<<<< - * if self.dtype_is_object: - * refcount_objects_in_slice(self.data, self._shape, - */ - __pyx_t_1 = (__pyx_v_self->free_data != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":215 - * self.callback_free_data(self.data) - * elif self.free_data: - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * refcount_objects_in_slice(self.data, self._shape, - * self._strides, self.ndim, False) - */ - __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":216 - * elif self.free_data: - * if self.dtype_is_object: - * refcount_objects_in_slice(self.data, self._shape, # <<<<<<<<<<<<<< - * self._strides, self.ndim, False) - * free(self.data) - */ - __pyx_memoryview_refcount_objects_in_slice(__pyx_v_self->data, __pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_self->ndim, 0); - - /* "View.MemoryView":215 - * self.callback_free_data(self.data) - * elif self.free_data: - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * refcount_objects_in_slice(self.data, self._shape, - * self._strides, self.ndim, False) - */ - } - - /* "View.MemoryView":218 - * refcount_objects_in_slice(self.data, self._shape, - * self._strides, self.ndim, False) - * free(self.data) # <<<<<<<<<<<<<< - * PyObject_Free(self._shape) - * - */ - free(__pyx_v_self->data); - - /* "View.MemoryView":214 - * if self.callback_free_data != NULL: - * self.callback_free_data(self.data) - * elif self.free_data: # <<<<<<<<<<<<<< - * if self.dtype_is_object: - * refcount_objects_in_slice(self.data, self._shape, - */ - } - __pyx_L3:; - - /* "View.MemoryView":219 - * self._strides, self.ndim, False) - * free(self.data) - * PyObject_Free(self._shape) # <<<<<<<<<<<<<< - * - * @property - */ - PyObject_Free(__pyx_v_self->_shape); - - /* "View.MemoryView":211 - * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") - * - * def __dealloc__(array self): # <<<<<<<<<<<<<< - * if self.callback_free_data != NULL: - * self.callback_free_data(self.data) - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "View.MemoryView":222 - * - * @property - * def memview(self): # <<<<<<<<<<<<<< - * return self.get_memview() - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":223 - * @property - * def memview(self): - * return self.get_memview() # <<<<<<<<<<<<<< - * - * @cname('get_memview') - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((struct __pyx_vtabstruct_array *)__pyx_v_self->__pyx_vtab)->get_memview(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 223, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":222 - * - * @property - * def memview(self): # <<<<<<<<<<<<<< - * return self.get_memview() - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":226 - * - * @cname('get_memview') - * cdef get_memview(self): # <<<<<<<<<<<<<< - * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE - * return memoryview(self, flags, self.dtype_is_object) - */ - -static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *__pyx_v_self) { - int __pyx_v_flags; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("get_memview", 0); - - /* "View.MemoryView":227 - * @cname('get_memview') - * cdef get_memview(self): - * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<< - * return memoryview(self, flags, self.dtype_is_object) - * - */ - __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); - - /* "View.MemoryView":228 - * cdef get_memview(self): - * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE - * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< - * - * def __len__(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 228, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 228, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 228, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 228, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":226 - * - * @cname('get_memview') - * cdef get_memview(self): # <<<<<<<<<<<<<< - * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE - * return memoryview(self, flags, self.dtype_is_object) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.array.get_memview", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":230 - * return memoryview(self, flags, self.dtype_is_object) - * - * def __len__(self): # <<<<<<<<<<<<<< - * return self._shape[0] - * - */ - -/* Python wrapper */ -static Py_ssize_t __pyx_array___len__(PyObject *__pyx_v_self); /*proto*/ -static Py_ssize_t __pyx_array___len__(PyObject *__pyx_v_self) { - Py_ssize_t __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); - __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(((struct __pyx_array_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static Py_ssize_t __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(struct __pyx_array_obj *__pyx_v_self) { - Py_ssize_t __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__len__", 0); - - /* "View.MemoryView":231 - * - * def __len__(self): - * return self._shape[0] # <<<<<<<<<<<<<< - * - * def __getattr__(self, attr): - */ - __pyx_r = (__pyx_v_self->_shape[0]); - goto __pyx_L0; - - /* "View.MemoryView":230 - * return memoryview(self, flags, self.dtype_is_object) - * - * def __len__(self): # <<<<<<<<<<<<<< - * return self._shape[0] - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":233 - * return self._shape[0] - * - * def __getattr__(self, attr): # <<<<<<<<<<<<<< - * return getattr(self.memview, attr) - * - */ - -/* Python wrapper */ -static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ -static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); - __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getattr__", 0); - - /* "View.MemoryView":234 - * - * def __getattr__(self, attr): - * return getattr(self.memview, attr) # <<<<<<<<<<<<<< - * - * def __getitem__(self, item): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 234, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 234, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":233 - * return self._shape[0] - * - * def __getattr__(self, attr): # <<<<<<<<<<<<<< - * return getattr(self.memview, attr) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.array.__getattr__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":236 - * return getattr(self.memview, attr) - * - * def __getitem__(self, item): # <<<<<<<<<<<<<< - * return self.memview[item] - * - */ - -/* Python wrapper */ -static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item); /*proto*/ -static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); - __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getitem__", 0); - - /* "View.MemoryView":237 - * - * def __getitem__(self, item): - * return self.memview[item] # <<<<<<<<<<<<<< - * - * def __setitem__(self, item, value): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 237, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 237, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":236 - * return getattr(self.memview, attr) - * - * def __getitem__(self, item): # <<<<<<<<<<<<<< - * return self.memview[item] - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.array.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":239 - * return self.memview[item] - * - * def __setitem__(self, item, value): # <<<<<<<<<<<<<< - * self.memview[item] = value - * - */ - -/* Python wrapper */ -static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); - __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setitem__", 0); - - /* "View.MemoryView":240 - * - * def __setitem__(self, item, value): - * self.memview[item] = value # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 240, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) __PYX_ERR(1, 240, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "View.MemoryView":239 - * return self.memview[item] - * - * def __setitem__(self, item, value): # <<<<<<<<<<<<<< - * self.memview[item] = value - * - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.array.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_array_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw___pyx_array_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_array___reduce_cython__(((struct __pyx_array_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_array___reduce_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 2, __pyx_L1_error) - - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.array.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_array_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw___pyx_array_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_array_2__setstate_cython__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_array_2__setstate_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 4, __pyx_L1_error) - - /* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.array.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":244 - * - * @cname("__pyx_array_new") - * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< - * char *mode, char *buf): - * cdef array result - */ - -static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, char *__pyx_v_format, char *__pyx_v_mode, char *__pyx_v_buf) { - struct __pyx_array_obj *__pyx_v_result = 0; - struct __pyx_array_obj *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("array_cwrapper", 0); - - /* "View.MemoryView":248 - * cdef array result - * - * if buf == NULL: # <<<<<<<<<<<<<< - * result = array(shape, itemsize, format, mode.decode('ASCII')) - * else: - */ - __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":249 - * - * if buf == NULL: - * result = array(shape, itemsize, format, mode.decode('ASCII')) # <<<<<<<<<<<<<< - * else: - * result = array(shape, itemsize, format, mode.decode('ASCII'), - */ - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 249, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 249, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 249, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 249, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(__pyx_v_shape); - __Pyx_GIVEREF(__pyx_v_shape); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_shape); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)__pyx_array_type), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 249, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_4); - __pyx_t_4 = 0; - - /* "View.MemoryView":248 - * cdef array result - * - * if buf == NULL: # <<<<<<<<<<<<<< - * result = array(shape, itemsize, format, mode.decode('ASCII')) - * else: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":251 - * result = array(shape, itemsize, format, mode.decode('ASCII')) - * else: - * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< - * allocate_buffer=False) - * result.data = buf - */ - /*else*/ { - __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_shape); - __Pyx_GIVEREF(__pyx_v_shape); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_3); - __pyx_t_4 = 0; - __pyx_t_5 = 0; - __pyx_t_3 = 0; - - /* "View.MemoryView":252 - * else: - * result = array(shape, itemsize, format, mode.decode('ASCII'), - * allocate_buffer=False) # <<<<<<<<<<<<<< - * result.data = buf - * - */ - __pyx_t_3 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 252, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) __PYX_ERR(1, 252, __pyx_L1_error) - - /* "View.MemoryView":251 - * result = array(shape, itemsize, format, mode.decode('ASCII')) - * else: - * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< - * allocate_buffer=False) - * result.data = buf - */ - __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)__pyx_array_type), __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_5); - __pyx_t_5 = 0; - - /* "View.MemoryView":253 - * result = array(shape, itemsize, format, mode.decode('ASCII'), - * allocate_buffer=False) - * result.data = buf # <<<<<<<<<<<<<< - * - * return result - */ - __pyx_v_result->data = __pyx_v_buf; - } - __pyx_L3:; - - /* "View.MemoryView":255 - * result.data = buf - * - * return result # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(((PyObject *)__pyx_r)); - __Pyx_INCREF(((PyObject *)__pyx_v_result)); - __pyx_r = __pyx_v_result; - goto __pyx_L0; - - /* "View.MemoryView":244 - * - * @cname("__pyx_array_new") - * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< - * char *mode, char *buf): - * cdef array result - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.array_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_result); - __Pyx_XGIVEREF((PyObject *)__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":281 - * cdef class Enum(object): - * cdef object name - * def __init__(self, name): # <<<<<<<<<<<<<< - * self.name = name - * def __repr__(self): - */ - -/* Python wrapper */ -static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_name = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_name,0}; - PyObject* values[1] = {0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_name)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) __PYX_ERR(1, 281, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - } - __pyx_v_name = values[0]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 281, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("View.MemoryView.Enum.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__init__", 0); - - /* "View.MemoryView":282 - * cdef object name - * def __init__(self, name): - * self.name = name # <<<<<<<<<<<<<< - * def __repr__(self): - * return self.name - */ - __Pyx_INCREF(__pyx_v_name); - __Pyx_GIVEREF(__pyx_v_name); - __Pyx_GOTREF(__pyx_v_self->name); - __Pyx_DECREF(__pyx_v_self->name); - __pyx_v_self->name = __pyx_v_name; - - /* "View.MemoryView":281 - * cdef class Enum(object): - * cdef object name - * def __init__(self, name): # <<<<<<<<<<<<<< - * self.name = name - * def __repr__(self): - */ - - /* function exit code */ - __pyx_r = 0; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":283 - * def __init__(self, name): - * self.name = name - * def __repr__(self): # <<<<<<<<<<<<<< - * return self.name - * - */ - -/* Python wrapper */ -static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); - __pyx_r = __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__repr__", 0); - - /* "View.MemoryView":284 - * self.name = name - * def __repr__(self): - * return self.name # <<<<<<<<<<<<<< - * - * cdef generic = Enum("") - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->name); - __pyx_r = __pyx_v_self->name; - goto __pyx_L0; - - /* "View.MemoryView":283 - * def __init__(self, name): - * self.name = name - * def __repr__(self): # <<<<<<<<<<<<<< - * return self.name - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * cdef tuple state - * cdef object _dict - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_MemviewEnum_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw___pyx_MemviewEnum_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_MemviewEnum___reduce_cython__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_MemviewEnum___reduce_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { - PyObject *__pyx_v_state = 0; - PyObject *__pyx_v__dict = 0; - int __pyx_v_use_setstate; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); - - /* "(tree fragment)":5 - * cdef object _dict - * cdef bint use_setstate - * state = (self.name,) # <<<<<<<<<<<<<< - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: - */ - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_self->name); - __Pyx_GIVEREF(__pyx_v_self->name); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->name); - __pyx_v_state = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "(tree fragment)":6 - * cdef bint use_setstate - * state = (self.name,) - * _dict = getattr(self, '__dict__', None) # <<<<<<<<<<<<<< - * if _dict is not None: - * state += (_dict,) - */ - __pyx_t_1 = __Pyx_GetAttr3(((PyObject *)__pyx_v_self), __pyx_n_s_dict, Py_None); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v__dict = __pyx_t_1; - __pyx_t_1 = 0; - - /* "(tree fragment)":7 - * state = (self.name,) - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: # <<<<<<<<<<<<<< - * state += (_dict,) - * use_setstate = True - */ - __pyx_t_2 = (__pyx_v__dict != Py_None); - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - - /* "(tree fragment)":8 - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: - * state += (_dict,) # <<<<<<<<<<<<<< - * use_setstate = True - * else: - */ - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v__dict); - __Pyx_GIVEREF(__pyx_v__dict); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v__dict); - __pyx_t_4 = PyNumber_InPlaceAdd(__pyx_v_state, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF_SET(__pyx_v_state, ((PyObject*)__pyx_t_4)); - __pyx_t_4 = 0; - - /* "(tree fragment)":9 - * if _dict is not None: - * state += (_dict,) - * use_setstate = True # <<<<<<<<<<<<<< - * else: - * use_setstate = self.name is not None - */ - __pyx_v_use_setstate = 1; - - /* "(tree fragment)":7 - * state = (self.name,) - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: # <<<<<<<<<<<<<< - * state += (_dict,) - * use_setstate = True - */ - goto __pyx_L3; - } - - /* "(tree fragment)":11 - * use_setstate = True - * else: - * use_setstate = self.name is not None # <<<<<<<<<<<<<< - * if use_setstate: - * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state - */ - /*else*/ { - __pyx_t_3 = (__pyx_v_self->name != Py_None); - __pyx_v_use_setstate = __pyx_t_3; - } - __pyx_L3:; - - /* "(tree fragment)":12 - * else: - * use_setstate = self.name is not None - * if use_setstate: # <<<<<<<<<<<<<< - * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state - * else: - */ - __pyx_t_3 = (__pyx_v_use_setstate != 0); - if (__pyx_t_3) { - - /* "(tree fragment)":13 - * use_setstate = self.name is not None - * if use_setstate: - * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state # <<<<<<<<<<<<<< - * else: - * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_pyx_unpickle_Enum); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_INCREF(__pyx_int_184977713); - __Pyx_GIVEREF(__pyx_int_184977713); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_184977713); - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - PyTuple_SET_ITEM(__pyx_t_1, 2, Py_None); - __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_1); - __Pyx_INCREF(__pyx_v_state); - __Pyx_GIVEREF(__pyx_v_state); - PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_v_state); - __pyx_t_4 = 0; - __pyx_t_1 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "(tree fragment)":12 - * else: - * use_setstate = self.name is not None - * if use_setstate: # <<<<<<<<<<<<<< - * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state - * else: - */ - } - - /* "(tree fragment)":15 - * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state - * else: - * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * __pyx_unpickle_Enum__set_state(self, __pyx_state) - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_pyx_unpickle_Enum); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_INCREF(__pyx_int_184977713); - __Pyx_GIVEREF(__pyx_int_184977713); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_184977713); - __Pyx_INCREF(__pyx_v_state); - __Pyx_GIVEREF(__pyx_v_state); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_state); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); - __pyx_t_5 = 0; - __pyx_t_1 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - } - - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * cdef tuple state - * cdef object _dict - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.Enum.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_state); - __Pyx_XDECREF(__pyx_v__dict); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":16 - * else: - * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * __pyx_unpickle_Enum__set_state(self, __pyx_state) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_MemviewEnum_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw___pyx_MemviewEnum_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_MemviewEnum_2__setstate_cython__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_MemviewEnum_2__setstate_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); - - /* "(tree fragment)":17 - * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) - * def __setstate_cython__(self, __pyx_state): - * __pyx_unpickle_Enum__set_state(self, __pyx_state) # <<<<<<<<<<<<<< - */ - if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(1, 17, __pyx_L1_error) - __pyx_t_1 = __pyx_unpickle_Enum__set_state(__pyx_v_self, ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 17, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "(tree fragment)":16 - * else: - * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * __pyx_unpickle_Enum__set_state(self, __pyx_state) - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.Enum.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":298 - * - * @cname('__pyx_align_pointer') - * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< - * "Align pointer memory on a given boundary" - * cdef Py_intptr_t aligned_p = memory - */ - -static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) { - Py_intptr_t __pyx_v_aligned_p; - size_t __pyx_v_offset; - void *__pyx_r; - int __pyx_t_1; - - /* "View.MemoryView":300 - * cdef void *align_pointer(void *memory, size_t alignment) nogil: - * "Align pointer memory on a given boundary" - * cdef Py_intptr_t aligned_p = memory # <<<<<<<<<<<<<< - * cdef size_t offset - * - */ - __pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory); - - /* "View.MemoryView":304 - * - * with cython.cdivision(True): - * offset = aligned_p % alignment # <<<<<<<<<<<<<< - * - * if offset > 0: - */ - __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); - - /* "View.MemoryView":306 - * offset = aligned_p % alignment - * - * if offset > 0: # <<<<<<<<<<<<<< - * aligned_p += alignment - offset - * - */ - __pyx_t_1 = ((__pyx_v_offset > 0) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":307 - * - * if offset > 0: - * aligned_p += alignment - offset # <<<<<<<<<<<<<< - * - * return aligned_p - */ - __pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset)); - - /* "View.MemoryView":306 - * offset = aligned_p % alignment - * - * if offset > 0: # <<<<<<<<<<<<<< - * aligned_p += alignment - offset - * - */ - } - - /* "View.MemoryView":309 - * aligned_p += alignment - offset - * - * return aligned_p # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = ((void *)__pyx_v_aligned_p); - goto __pyx_L0; - - /* "View.MemoryView":298 - * - * @cname('__pyx_align_pointer') - * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< - * "Align pointer memory on a given boundary" - * cdef Py_intptr_t aligned_p = memory - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":345 - * cdef __Pyx_TypeInfo *typeinfo - * - * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< - * self.obj = obj - * self.flags = flags - */ - -/* Python wrapper */ -static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_obj = 0; - int __pyx_v_flags; - int __pyx_v_dtype_is_object; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_obj,&__pyx_n_s_flags,&__pyx_n_s_dtype_is_object,0}; - PyObject* values[3] = {0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_obj)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_flags)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); __PYX_ERR(1, 345, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_dtype_is_object); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) __PYX_ERR(1, 345, __pyx_L3_error) - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_obj = values[0]; - __pyx_v_flags = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 345, __pyx_L3_error) - if (values[2]) { - __pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 345, __pyx_L3_error) - } else { - __pyx_v_dtype_is_object = ((int)0); - } - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 345, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__cinit__", 0); - - /* "View.MemoryView":346 - * - * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): - * self.obj = obj # <<<<<<<<<<<<<< - * self.flags = flags - * if type(self) is memoryview or obj is not None: - */ - __Pyx_INCREF(__pyx_v_obj); - __Pyx_GIVEREF(__pyx_v_obj); - __Pyx_GOTREF(__pyx_v_self->obj); - __Pyx_DECREF(__pyx_v_self->obj); - __pyx_v_self->obj = __pyx_v_obj; - - /* "View.MemoryView":347 - * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): - * self.obj = obj - * self.flags = flags # <<<<<<<<<<<<<< - * if type(self) is memoryview or obj is not None: - * __Pyx_GetBuffer(obj, &self.view, flags) - */ - __pyx_v_self->flags = __pyx_v_flags; - - /* "View.MemoryView":348 - * self.obj = obj - * self.flags = flags - * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< - * __Pyx_GetBuffer(obj, &self.view, flags) - * if self.view.obj == NULL: - */ - __pyx_t_2 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)__pyx_memoryview_type)); - __pyx_t_3 = (__pyx_t_2 != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_1 = __pyx_t_3; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_3 = (__pyx_v_obj != Py_None); - __pyx_t_2 = (__pyx_t_3 != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L4_bool_binop_done:; - if (__pyx_t_1) { - - /* "View.MemoryView":349 - * self.flags = flags - * if type(self) is memoryview or obj is not None: - * __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<< - * if self.view.obj == NULL: - * (<__pyx_buffer *> &self.view).obj = Py_None - */ - __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 349, __pyx_L1_error) - - /* "View.MemoryView":350 - * if type(self) is memoryview or obj is not None: - * __Pyx_GetBuffer(obj, &self.view, flags) - * if self.view.obj == NULL: # <<<<<<<<<<<<<< - * (<__pyx_buffer *> &self.view).obj = Py_None - * Py_INCREF(Py_None) - */ - __pyx_t_1 = ((((PyObject *)__pyx_v_self->view.obj) == NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":351 - * __Pyx_GetBuffer(obj, &self.view, flags) - * if self.view.obj == NULL: - * (<__pyx_buffer *> &self.view).obj = Py_None # <<<<<<<<<<<<<< - * Py_INCREF(Py_None) - * - */ - ((Py_buffer *)(&__pyx_v_self->view))->obj = Py_None; - - /* "View.MemoryView":352 - * if self.view.obj == NULL: - * (<__pyx_buffer *> &self.view).obj = Py_None - * Py_INCREF(Py_None) # <<<<<<<<<<<<<< - * - * global __pyx_memoryview_thread_locks_used - */ - Py_INCREF(Py_None); - - /* "View.MemoryView":350 - * if type(self) is memoryview or obj is not None: - * __Pyx_GetBuffer(obj, &self.view, flags) - * if self.view.obj == NULL: # <<<<<<<<<<<<<< - * (<__pyx_buffer *> &self.view).obj = Py_None - * Py_INCREF(Py_None) - */ - } - - /* "View.MemoryView":348 - * self.obj = obj - * self.flags = flags - * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< - * __Pyx_GetBuffer(obj, &self.view, flags) - * if self.view.obj == NULL: - */ - } - - /* "View.MemoryView":355 - * - * global __pyx_memoryview_thread_locks_used - * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: # <<<<<<<<<<<<<< - * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] - * __pyx_memoryview_thread_locks_used += 1 - */ - __pyx_t_1 = ((__pyx_memoryview_thread_locks_used < 8) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":356 - * global __pyx_memoryview_thread_locks_used - * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: - * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] # <<<<<<<<<<<<<< - * __pyx_memoryview_thread_locks_used += 1 - * if self.lock is NULL: - */ - __pyx_v_self->lock = (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]); - - /* "View.MemoryView":357 - * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: - * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] - * __pyx_memoryview_thread_locks_used += 1 # <<<<<<<<<<<<<< - * if self.lock is NULL: - * self.lock = PyThread_allocate_lock() - */ - __pyx_memoryview_thread_locks_used = (__pyx_memoryview_thread_locks_used + 1); - - /* "View.MemoryView":355 - * - * global __pyx_memoryview_thread_locks_used - * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: # <<<<<<<<<<<<<< - * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] - * __pyx_memoryview_thread_locks_used += 1 - */ - } - - /* "View.MemoryView":358 - * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] - * __pyx_memoryview_thread_locks_used += 1 - * if self.lock is NULL: # <<<<<<<<<<<<<< - * self.lock = PyThread_allocate_lock() - * if self.lock is NULL: - */ - __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":359 - * __pyx_memoryview_thread_locks_used += 1 - * if self.lock is NULL: - * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< - * if self.lock is NULL: - * raise MemoryError - */ - __pyx_v_self->lock = PyThread_allocate_lock(); - - /* "View.MemoryView":360 - * if self.lock is NULL: - * self.lock = PyThread_allocate_lock() - * if self.lock is NULL: # <<<<<<<<<<<<<< - * raise MemoryError - * - */ - __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":361 - * self.lock = PyThread_allocate_lock() - * if self.lock is NULL: - * raise MemoryError # <<<<<<<<<<<<<< - * - * if flags & PyBUF_FORMAT: - */ - PyErr_NoMemory(); __PYX_ERR(1, 361, __pyx_L1_error) - - /* "View.MemoryView":360 - * if self.lock is NULL: - * self.lock = PyThread_allocate_lock() - * if self.lock is NULL: # <<<<<<<<<<<<<< - * raise MemoryError - * - */ - } - - /* "View.MemoryView":358 - * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] - * __pyx_memoryview_thread_locks_used += 1 - * if self.lock is NULL: # <<<<<<<<<<<<<< - * self.lock = PyThread_allocate_lock() - * if self.lock is NULL: - */ - } - - /* "View.MemoryView":363 - * raise MemoryError - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') - * else: - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":364 - * - * if flags & PyBUF_FORMAT: - * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') # <<<<<<<<<<<<<< - * else: - * self.dtype_is_object = dtype_is_object - */ - __pyx_t_2 = (((__pyx_v_self->view.format[0]) == 'O') != 0); - if (__pyx_t_2) { - } else { - __pyx_t_1 = __pyx_t_2; - goto __pyx_L11_bool_binop_done; - } - __pyx_t_2 = (((__pyx_v_self->view.format[1]) == '\x00') != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L11_bool_binop_done:; - __pyx_v_self->dtype_is_object = __pyx_t_1; - - /* "View.MemoryView":363 - * raise MemoryError - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') - * else: - */ - goto __pyx_L10; - } - - /* "View.MemoryView":366 - * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') - * else: - * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< - * - * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( - */ - /*else*/ { - __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; - } - __pyx_L10:; - - /* "View.MemoryView":368 - * self.dtype_is_object = dtype_is_object - * - * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( # <<<<<<<<<<<<<< - * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) - * self.typeinfo = NULL - */ - __pyx_v_self->acquisition_count_aligned_p = ((__pyx_atomic_int *)__pyx_align_pointer(((void *)(&(__pyx_v_self->acquisition_count[0]))), (sizeof(__pyx_atomic_int)))); - - /* "View.MemoryView":370 - * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( - * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) - * self.typeinfo = NULL # <<<<<<<<<<<<<< - * - * def __dealloc__(memoryview self): - */ - __pyx_v_self->typeinfo = NULL; - - /* "View.MemoryView":345 - * cdef __Pyx_TypeInfo *typeinfo - * - * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< - * self.obj = obj - * self.flags = flags - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":372 - * self.typeinfo = NULL - * - * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< - * if self.obj is not None: - * __Pyx_ReleaseBuffer(&self.view) - */ - -/* Python wrapper */ -static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self); /*proto*/ -static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); - __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) { - int __pyx_v_i; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - PyThread_type_lock __pyx_t_6; - PyThread_type_lock __pyx_t_7; - __Pyx_RefNannySetupContext("__dealloc__", 0); - - /* "View.MemoryView":373 - * - * def __dealloc__(memoryview self): - * if self.obj is not None: # <<<<<<<<<<<<<< - * __Pyx_ReleaseBuffer(&self.view) - * elif (<__pyx_buffer *> &self.view).obj == Py_None: - */ - __pyx_t_1 = (__pyx_v_self->obj != Py_None); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":374 - * def __dealloc__(memoryview self): - * if self.obj is not None: - * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< - * elif (<__pyx_buffer *> &self.view).obj == Py_None: - * - */ - __Pyx_ReleaseBuffer((&__pyx_v_self->view)); - - /* "View.MemoryView":373 - * - * def __dealloc__(memoryview self): - * if self.obj is not None: # <<<<<<<<<<<<<< - * __Pyx_ReleaseBuffer(&self.view) - * elif (<__pyx_buffer *> &self.view).obj == Py_None: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":375 - * if self.obj is not None: - * __Pyx_ReleaseBuffer(&self.view) - * elif (<__pyx_buffer *> &self.view).obj == Py_None: # <<<<<<<<<<<<<< - * - * (<__pyx_buffer *> &self.view).obj = NULL - */ - __pyx_t_2 = ((((Py_buffer *)(&__pyx_v_self->view))->obj == Py_None) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":377 - * elif (<__pyx_buffer *> &self.view).obj == Py_None: - * - * (<__pyx_buffer *> &self.view).obj = NULL # <<<<<<<<<<<<<< - * Py_DECREF(Py_None) - * - */ - ((Py_buffer *)(&__pyx_v_self->view))->obj = NULL; - - /* "View.MemoryView":378 - * - * (<__pyx_buffer *> &self.view).obj = NULL - * Py_DECREF(Py_None) # <<<<<<<<<<<<<< - * - * cdef int i - */ - Py_DECREF(Py_None); - - /* "View.MemoryView":375 - * if self.obj is not None: - * __Pyx_ReleaseBuffer(&self.view) - * elif (<__pyx_buffer *> &self.view).obj == Py_None: # <<<<<<<<<<<<<< - * - * (<__pyx_buffer *> &self.view).obj = NULL - */ - } - __pyx_L3:; - - /* "View.MemoryView":382 - * cdef int i - * global __pyx_memoryview_thread_locks_used - * if self.lock != NULL: # <<<<<<<<<<<<<< - * for i in range(__pyx_memoryview_thread_locks_used): - * if __pyx_memoryview_thread_locks[i] is self.lock: - */ - __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":383 - * global __pyx_memoryview_thread_locks_used - * if self.lock != NULL: - * for i in range(__pyx_memoryview_thread_locks_used): # <<<<<<<<<<<<<< - * if __pyx_memoryview_thread_locks[i] is self.lock: - * __pyx_memoryview_thread_locks_used -= 1 - */ - __pyx_t_3 = __pyx_memoryview_thread_locks_used; - __pyx_t_4 = __pyx_t_3; - for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { - __pyx_v_i = __pyx_t_5; - - /* "View.MemoryView":384 - * if self.lock != NULL: - * for i in range(__pyx_memoryview_thread_locks_used): - * if __pyx_memoryview_thread_locks[i] is self.lock: # <<<<<<<<<<<<<< - * __pyx_memoryview_thread_locks_used -= 1 - * if i != __pyx_memoryview_thread_locks_used: - */ - __pyx_t_2 = (((__pyx_memoryview_thread_locks[__pyx_v_i]) == __pyx_v_self->lock) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":385 - * for i in range(__pyx_memoryview_thread_locks_used): - * if __pyx_memoryview_thread_locks[i] is self.lock: - * __pyx_memoryview_thread_locks_used -= 1 # <<<<<<<<<<<<<< - * if i != __pyx_memoryview_thread_locks_used: - * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( - */ - __pyx_memoryview_thread_locks_used = (__pyx_memoryview_thread_locks_used - 1); - - /* "View.MemoryView":386 - * if __pyx_memoryview_thread_locks[i] is self.lock: - * __pyx_memoryview_thread_locks_used -= 1 - * if i != __pyx_memoryview_thread_locks_used: # <<<<<<<<<<<<<< - * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( - * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) - */ - __pyx_t_2 = ((__pyx_v_i != __pyx_memoryview_thread_locks_used) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":388 - * if i != __pyx_memoryview_thread_locks_used: - * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( - * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) # <<<<<<<<<<<<<< - * break - * else: - */ - __pyx_t_6 = (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]); - __pyx_t_7 = (__pyx_memoryview_thread_locks[__pyx_v_i]); - - /* "View.MemoryView":387 - * __pyx_memoryview_thread_locks_used -= 1 - * if i != __pyx_memoryview_thread_locks_used: - * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( # <<<<<<<<<<<<<< - * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) - * break - */ - (__pyx_memoryview_thread_locks[__pyx_v_i]) = __pyx_t_6; - (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]) = __pyx_t_7; - - /* "View.MemoryView":386 - * if __pyx_memoryview_thread_locks[i] is self.lock: - * __pyx_memoryview_thread_locks_used -= 1 - * if i != __pyx_memoryview_thread_locks_used: # <<<<<<<<<<<<<< - * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( - * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) - */ - } - - /* "View.MemoryView":389 - * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( - * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) - * break # <<<<<<<<<<<<<< - * else: - * PyThread_free_lock(self.lock) - */ - goto __pyx_L6_break; - - /* "View.MemoryView":384 - * if self.lock != NULL: - * for i in range(__pyx_memoryview_thread_locks_used): - * if __pyx_memoryview_thread_locks[i] is self.lock: # <<<<<<<<<<<<<< - * __pyx_memoryview_thread_locks_used -= 1 - * if i != __pyx_memoryview_thread_locks_used: - */ - } - } - /*else*/ { - - /* "View.MemoryView":391 - * break - * else: - * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< - * - * cdef char *get_item_pointer(memoryview self, object index) except NULL: - */ - PyThread_free_lock(__pyx_v_self->lock); - } - __pyx_L6_break:; - - /* "View.MemoryView":382 - * cdef int i - * global __pyx_memoryview_thread_locks_used - * if self.lock != NULL: # <<<<<<<<<<<<<< - * for i in range(__pyx_memoryview_thread_locks_used): - * if __pyx_memoryview_thread_locks[i] is self.lock: - */ - } - - /* "View.MemoryView":372 - * self.typeinfo = NULL - * - * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< - * if self.obj is not None: - * __Pyx_ReleaseBuffer(&self.view) - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "View.MemoryView":393 - * PyThread_free_lock(self.lock) - * - * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< - * cdef Py_ssize_t dim - * cdef char *itemp = self.view.buf - */ - -static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { - Py_ssize_t __pyx_v_dim; - char *__pyx_v_itemp; - PyObject *__pyx_v_idx = NULL; - char *__pyx_r; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - Py_ssize_t __pyx_t_3; - PyObject *(*__pyx_t_4)(PyObject *); - PyObject *__pyx_t_5 = NULL; - Py_ssize_t __pyx_t_6; - char *__pyx_t_7; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("get_item_pointer", 0); - - /* "View.MemoryView":395 - * cdef char *get_item_pointer(memoryview self, object index) except NULL: - * cdef Py_ssize_t dim - * cdef char *itemp = self.view.buf # <<<<<<<<<<<<<< - * - * for dim, idx in enumerate(index): - */ - __pyx_v_itemp = ((char *)__pyx_v_self->view.buf); - - /* "View.MemoryView":397 - * cdef char *itemp = self.view.buf - * - * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< - * itemp = pybuffer_index(&self.view, itemp, idx, dim) - * - */ - __pyx_t_1 = 0; - if (likely(PyList_CheckExact(__pyx_v_index)) || PyTuple_CheckExact(__pyx_v_index)) { - __pyx_t_2 = __pyx_v_index; __Pyx_INCREF(__pyx_t_2); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - } else { - __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 397, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 397, __pyx_L1_error) - } - for (;;) { - if (likely(!__pyx_t_4)) { - if (likely(PyList_CheckExact(__pyx_t_2))) { - if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_2)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(1, 397, __pyx_L1_error) - #else - __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 397, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - } else { - if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(1, 397, __pyx_L1_error) - #else - __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 397, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - } - } else { - __pyx_t_5 = __pyx_t_4(__pyx_t_2); - if (unlikely(!__pyx_t_5)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(1, 397, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_5); - } - __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_5); - __pyx_t_5 = 0; - __pyx_v_dim = __pyx_t_1; - __pyx_t_1 = (__pyx_t_1 + 1); - - /* "View.MemoryView":398 - * - * for dim, idx in enumerate(index): - * itemp = pybuffer_index(&self.view, itemp, idx, dim) # <<<<<<<<<<<<<< - * - * return itemp - */ - __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 398, __pyx_L1_error) - __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == ((char *)NULL))) __PYX_ERR(1, 398, __pyx_L1_error) - __pyx_v_itemp = __pyx_t_7; - - /* "View.MemoryView":397 - * cdef char *itemp = self.view.buf - * - * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< - * itemp = pybuffer_index(&self.view, itemp, idx, dim) - * - */ - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "View.MemoryView":400 - * itemp = pybuffer_index(&self.view, itemp, idx, dim) - * - * return itemp # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = __pyx_v_itemp; - goto __pyx_L0; - - /* "View.MemoryView":393 - * PyThread_free_lock(self.lock) - * - * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< - * cdef Py_ssize_t dim - * cdef char *itemp = self.view.buf - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.memoryview.get_item_pointer", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_idx); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":403 - * - * - * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< - * if index is Ellipsis: - * return self - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index); /*proto*/ -static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { - PyObject *__pyx_v_have_slices = NULL; - PyObject *__pyx_v_indices = NULL; - char *__pyx_v_itemp; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - char *__pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getitem__", 0); - - /* "View.MemoryView":404 - * - * def __getitem__(memoryview self, object index): - * if index is Ellipsis: # <<<<<<<<<<<<<< - * return self - * - */ - __pyx_t_1 = (__pyx_v_index == __pyx_builtin_Ellipsis); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":405 - * def __getitem__(memoryview self, object index): - * if index is Ellipsis: - * return self # <<<<<<<<<<<<<< - * - * have_slices, indices = _unellipsify(index, self.view.ndim) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __pyx_r = ((PyObject *)__pyx_v_self); - goto __pyx_L0; - - /* "View.MemoryView":404 - * - * def __getitem__(memoryview self, object index): - * if index is Ellipsis: # <<<<<<<<<<<<<< - * return self - * - */ - } - - /* "View.MemoryView":407 - * return self - * - * have_slices, indices = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< - * - * cdef char *itemp - */ - __pyx_t_3 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 407, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (likely(__pyx_t_3 != Py_None)) { - PyObject* sequence = __pyx_t_3; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(1, 407, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - #else - __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 407, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 407, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 407, __pyx_L1_error) - } - __pyx_v_have_slices = __pyx_t_4; - __pyx_t_4 = 0; - __pyx_v_indices = __pyx_t_5; - __pyx_t_5 = 0; - - /* "View.MemoryView":410 - * - * cdef char *itemp - * if have_slices: # <<<<<<<<<<<<<< - * return memview_slice(self, indices) - * else: - */ - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(1, 410, __pyx_L1_error) - if (__pyx_t_2) { - - /* "View.MemoryView":411 - * cdef char *itemp - * if have_slices: - * return memview_slice(self, indices) # <<<<<<<<<<<<<< - * else: - * itemp = self.get_item_pointer(indices) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 411, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "View.MemoryView":410 - * - * cdef char *itemp - * if have_slices: # <<<<<<<<<<<<<< - * return memview_slice(self, indices) - * else: - */ - } - - /* "View.MemoryView":413 - * return memview_slice(self, indices) - * else: - * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< - * return self.convert_item_to_object(itemp) - * - */ - /*else*/ { - __pyx_t_6 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_6 == ((char *)NULL))) __PYX_ERR(1, 413, __pyx_L1_error) - __pyx_v_itemp = __pyx_t_6; - - /* "View.MemoryView":414 - * else: - * itemp = self.get_item_pointer(indices) - * return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<< - * - * def __setitem__(memoryview self, object index, object value): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 414, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - } - - /* "View.MemoryView":403 - * - * - * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< - * if index is Ellipsis: - * return self - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.memoryview.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_have_slices); - __Pyx_XDECREF(__pyx_v_indices); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":416 - * return self.convert_item_to_object(itemp) - * - * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< - * if self.view.readonly: - * raise TypeError("Cannot assign to read-only memoryview") - */ - -/* Python wrapper */ -static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { - PyObject *__pyx_v_have_slices = NULL; - PyObject *__pyx_v_obj = NULL; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setitem__", 0); - __Pyx_INCREF(__pyx_v_index); - - /* "View.MemoryView":417 - * - * def __setitem__(memoryview self, object index, object value): - * if self.view.readonly: # <<<<<<<<<<<<<< - * raise TypeError("Cannot assign to read-only memoryview") - * - */ - __pyx_t_1 = (__pyx_v_self->view.readonly != 0); - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":418 - * def __setitem__(memoryview self, object index, object value): - * if self.view.readonly: - * raise TypeError("Cannot assign to read-only memoryview") # <<<<<<<<<<<<<< - * - * have_slices, index = _unellipsify(index, self.view.ndim) - */ - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 418, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __PYX_ERR(1, 418, __pyx_L1_error) - - /* "View.MemoryView":417 - * - * def __setitem__(memoryview self, object index, object value): - * if self.view.readonly: # <<<<<<<<<<<<<< - * raise TypeError("Cannot assign to read-only memoryview") - * - */ - } - - /* "View.MemoryView":420 - * raise TypeError("Cannot assign to read-only memoryview") - * - * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< - * - * if have_slices: - */ - __pyx_t_2 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 420, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (likely(__pyx_t_2 != Py_None)) { - PyObject* sequence = __pyx_t_2; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(1, 420, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - #else - __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 420, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 420, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } else { - __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 420, __pyx_L1_error) - } - __pyx_v_have_slices = __pyx_t_3; - __pyx_t_3 = 0; - __Pyx_DECREF_SET(__pyx_v_index, __pyx_t_4); - __pyx_t_4 = 0; - - /* "View.MemoryView":422 - * have_slices, index = _unellipsify(index, self.view.ndim) - * - * if have_slices: # <<<<<<<<<<<<<< - * obj = self.is_slice(value) - * if obj: - */ - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 422, __pyx_L1_error) - if (__pyx_t_1) { - - /* "View.MemoryView":423 - * - * if have_slices: - * obj = self.is_slice(value) # <<<<<<<<<<<<<< - * if obj: - * self.setitem_slice_assignment(self[index], obj) - */ - __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 423, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_v_obj = __pyx_t_2; - __pyx_t_2 = 0; - - /* "View.MemoryView":424 - * if have_slices: - * obj = self.is_slice(value) - * if obj: # <<<<<<<<<<<<<< - * self.setitem_slice_assignment(self[index], obj) - * else: - */ - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 424, __pyx_L1_error) - if (__pyx_t_1) { - - /* "View.MemoryView":425 - * obj = self.is_slice(value) - * if obj: - * self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<< - * else: - * self.setitem_slice_assign_scalar(self[index], value) - */ - __pyx_t_2 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 425, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_2, __pyx_v_obj); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 425, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "View.MemoryView":424 - * if have_slices: - * obj = self.is_slice(value) - * if obj: # <<<<<<<<<<<<<< - * self.setitem_slice_assignment(self[index], obj) - * else: - */ - goto __pyx_L5; - } - - /* "View.MemoryView":427 - * self.setitem_slice_assignment(self[index], obj) - * else: - * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< - * else: - * self.setitem_indexed(index, value) - */ - /*else*/ { - __pyx_t_4 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 427, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_memoryview_type))))) __PYX_ERR(1, 427, __pyx_L1_error) - __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_4), __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 427, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __pyx_L5:; - - /* "View.MemoryView":422 - * have_slices, index = _unellipsify(index, self.view.ndim) - * - * if have_slices: # <<<<<<<<<<<<<< - * obj = self.is_slice(value) - * if obj: - */ - goto __pyx_L4; - } - - /* "View.MemoryView":429 - * self.setitem_slice_assign_scalar(self[index], value) - * else: - * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< - * - * cdef is_slice(self, obj): - */ - /*else*/ { - __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 429, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __pyx_L4:; - - /* "View.MemoryView":416 - * return self.convert_item_to_object(itemp) - * - * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< - * if self.view.readonly: - * raise TypeError("Cannot assign to read-only memoryview") - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("View.MemoryView.memoryview.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_have_slices); - __Pyx_XDECREF(__pyx_v_obj); - __Pyx_XDECREF(__pyx_v_index); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":431 - * self.setitem_indexed(index, value) - * - * cdef is_slice(self, obj): # <<<<<<<<<<<<<< - * if not isinstance(obj, memoryview): - * try: - */ - -static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_t_9; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("is_slice", 0); - __Pyx_INCREF(__pyx_v_obj); - - /* "View.MemoryView":432 - * - * cdef is_slice(self, obj): - * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< - * try: - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - */ - __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, __pyx_memoryview_type); - __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":433 - * cdef is_slice(self, obj): - * if not isinstance(obj, memoryview): - * try: # <<<<<<<<<<<<<< - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - * self.dtype_is_object) - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); - __Pyx_XGOTREF(__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_5); - /*try:*/ { - - /* "View.MemoryView":434 - * if not isinstance(obj, memoryview): - * try: - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< - * self.dtype_is_object) - * except TypeError: - */ - __pyx_t_6 = __Pyx_PyInt_From_int(((__pyx_v_self->flags & (~PyBUF_WRITABLE)) | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 434, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_6); - - /* "View.MemoryView":435 - * try: - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - * self.dtype_is_object) # <<<<<<<<<<<<<< - * except TypeError: - * return None - */ - __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 435, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_7); - - /* "View.MemoryView":434 - * if not isinstance(obj, memoryview): - * try: - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< - * self.dtype_is_object) - * except TypeError: - */ - __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 434, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_INCREF(__pyx_v_obj); - __Pyx_GIVEREF(__pyx_v_obj); - PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); - __pyx_t_6 = 0; - __pyx_t_7 = 0; - __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 434, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF_SET(__pyx_v_obj, __pyx_t_7); - __pyx_t_7 = 0; - - /* "View.MemoryView":433 - * cdef is_slice(self, obj): - * if not isinstance(obj, memoryview): - * try: # <<<<<<<<<<<<<< - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - * self.dtype_is_object) - */ - } - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - goto __pyx_L9_try_end; - __pyx_L4_error:; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - - /* "View.MemoryView":436 - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - * self.dtype_is_object) - * except TypeError: # <<<<<<<<<<<<<< - * return None - * - */ - __pyx_t_9 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_TypeError); - if (__pyx_t_9) { - __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) __PYX_ERR(1, 436, __pyx_L6_except_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_GOTREF(__pyx_t_8); - __Pyx_GOTREF(__pyx_t_6); - - /* "View.MemoryView":437 - * self.dtype_is_object) - * except TypeError: - * return None # <<<<<<<<<<<<<< - * - * return obj - */ - __Pyx_XDECREF(__pyx_r); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - goto __pyx_L7_except_return; - } - goto __pyx_L6_except_error; - __pyx_L6_except_error:; - - /* "View.MemoryView":433 - * cdef is_slice(self, obj): - * if not isinstance(obj, memoryview): - * try: # <<<<<<<<<<<<<< - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - * self.dtype_is_object) - */ - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_XGIVEREF(__pyx_t_5); - __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); - goto __pyx_L1_error; - __pyx_L7_except_return:; - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_XGIVEREF(__pyx_t_5); - __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); - goto __pyx_L0; - __pyx_L9_try_end:; - } - - /* "View.MemoryView":432 - * - * cdef is_slice(self, obj): - * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< - * try: - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - */ - } - - /* "View.MemoryView":439 - * return None - * - * return obj # <<<<<<<<<<<<<< - * - * cdef setitem_slice_assignment(self, dst, src): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_obj); - __pyx_r = __pyx_v_obj; - goto __pyx_L0; - - /* "View.MemoryView":431 - * self.setitem_indexed(index, value) - * - * cdef is_slice(self, obj): # <<<<<<<<<<<<<< - * if not isinstance(obj, memoryview): - * try: - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_obj); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":441 - * return obj - * - * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice dst_slice - * cdef __Pyx_memviewslice src_slice - */ - -static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src) { - __Pyx_memviewslice __pyx_v_dst_slice; - __Pyx_memviewslice __pyx_v_src_slice; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_memviewslice *__pyx_t_1; - __Pyx_memviewslice *__pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); - - /* "View.MemoryView":445 - * cdef __Pyx_memviewslice src_slice - * - * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< - * get_slice_from_memview(dst, &dst_slice)[0], - * src.ndim, dst.ndim, self.dtype_is_object) - */ - if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) __PYX_ERR(1, 445, __pyx_L1_error) - __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(1, 445, __pyx_L1_error) - - /* "View.MemoryView":446 - * - * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], - * get_slice_from_memview(dst, &dst_slice)[0], # <<<<<<<<<<<<<< - * src.ndim, dst.ndim, self.dtype_is_object) - * - */ - if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) __PYX_ERR(1, 446, __pyx_L1_error) - __pyx_t_2 = __pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice)); if (unlikely(__pyx_t_2 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(1, 446, __pyx_L1_error) - - /* "View.MemoryView":447 - * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], - * get_slice_from_memview(dst, &dst_slice)[0], - * src.ndim, dst.ndim, self.dtype_is_object) # <<<<<<<<<<<<<< - * - * cdef setitem_slice_assign_scalar(self, memoryview dst, value): - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 447, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 447, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 447, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 447, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":445 - * cdef __Pyx_memviewslice src_slice - * - * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< - * get_slice_from_memview(dst, &dst_slice)[0], - * src.ndim, dst.ndim, self.dtype_is_object) - */ - __pyx_t_6 = __pyx_memoryview_copy_contents((__pyx_t_1[0]), (__pyx_t_2[0]), __pyx_t_4, __pyx_t_5, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(1, 445, __pyx_L1_error) - - /* "View.MemoryView":441 - * return obj - * - * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice dst_slice - * cdef __Pyx_memviewslice src_slice - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assignment", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":449 - * src.ndim, dst.ndim, self.dtype_is_object) - * - * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< - * cdef int array[128] - * cdef void *tmp = NULL - */ - -static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value) { - int __pyx_v_array[0x80]; - void *__pyx_v_tmp; - void *__pyx_v_item; - __Pyx_memviewslice *__pyx_v_dst_slice; - __Pyx_memviewslice __pyx_v_tmp_slice; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_memviewslice *__pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - char const *__pyx_t_6; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - PyObject *__pyx_t_11 = NULL; - PyObject *__pyx_t_12 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); - - /* "View.MemoryView":451 - * cdef setitem_slice_assign_scalar(self, memoryview dst, value): - * cdef int array[128] - * cdef void *tmp = NULL # <<<<<<<<<<<<<< - * cdef void *item - * - */ - __pyx_v_tmp = NULL; - - /* "View.MemoryView":456 - * cdef __Pyx_memviewslice *dst_slice - * cdef __Pyx_memviewslice tmp_slice - * dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<< - * - * if self.view.itemsize > sizeof(array): - */ - __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(1, 456, __pyx_L1_error) - __pyx_v_dst_slice = __pyx_t_1; - - /* "View.MemoryView":458 - * dst_slice = get_slice_from_memview(dst, &tmp_slice) - * - * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< - * tmp = PyMem_Malloc(self.view.itemsize) - * if tmp == NULL: - */ - __pyx_t_2 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":459 - * - * if self.view.itemsize > sizeof(array): - * tmp = PyMem_Malloc(self.view.itemsize) # <<<<<<<<<<<<<< - * if tmp == NULL: - * raise MemoryError - */ - __pyx_v_tmp = PyMem_Malloc(__pyx_v_self->view.itemsize); - - /* "View.MemoryView":460 - * if self.view.itemsize > sizeof(array): - * tmp = PyMem_Malloc(self.view.itemsize) - * if tmp == NULL: # <<<<<<<<<<<<<< - * raise MemoryError - * item = tmp - */ - __pyx_t_2 = ((__pyx_v_tmp == NULL) != 0); - if (unlikely(__pyx_t_2)) { - - /* "View.MemoryView":461 - * tmp = PyMem_Malloc(self.view.itemsize) - * if tmp == NULL: - * raise MemoryError # <<<<<<<<<<<<<< - * item = tmp - * else: - */ - PyErr_NoMemory(); __PYX_ERR(1, 461, __pyx_L1_error) - - /* "View.MemoryView":460 - * if self.view.itemsize > sizeof(array): - * tmp = PyMem_Malloc(self.view.itemsize) - * if tmp == NULL: # <<<<<<<<<<<<<< - * raise MemoryError - * item = tmp - */ - } - - /* "View.MemoryView":462 - * if tmp == NULL: - * raise MemoryError - * item = tmp # <<<<<<<<<<<<<< - * else: - * item = array - */ - __pyx_v_item = __pyx_v_tmp; - - /* "View.MemoryView":458 - * dst_slice = get_slice_from_memview(dst, &tmp_slice) - * - * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< - * tmp = PyMem_Malloc(self.view.itemsize) - * if tmp == NULL: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":464 - * item = tmp - * else: - * item = array # <<<<<<<<<<<<<< - * - * try: - */ - /*else*/ { - __pyx_v_item = ((void *)__pyx_v_array); - } - __pyx_L3:; - - /* "View.MemoryView":466 - * item = array - * - * try: # <<<<<<<<<<<<<< - * if self.dtype_is_object: - * ( item)[0] = value - */ - /*try:*/ { - - /* "View.MemoryView":467 - * - * try: - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * ( item)[0] = value - * else: - */ - __pyx_t_2 = (__pyx_v_self->dtype_is_object != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":468 - * try: - * if self.dtype_is_object: - * ( item)[0] = value # <<<<<<<<<<<<<< - * else: - * self.assign_item_from_object( item, value) - */ - (((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value); - - /* "View.MemoryView":467 - * - * try: - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * ( item)[0] = value - * else: - */ - goto __pyx_L8; - } - - /* "View.MemoryView":470 - * ( item)[0] = value - * else: - * self.assign_item_from_object( item, value) # <<<<<<<<<<<<<< - * - * - */ - /*else*/ { - __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 470, __pyx_L6_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } - __pyx_L8:; - - /* "View.MemoryView":474 - * - * - * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< - * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) - * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, - */ - __pyx_t_2 = ((__pyx_v_self->view.suboffsets != NULL) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":475 - * - * if self.view.suboffsets != NULL: - * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) # <<<<<<<<<<<<<< - * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, - * item, self.dtype_is_object) - */ - __pyx_t_3 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 475, __pyx_L6_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":474 - * - * - * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< - * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) - * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, - */ - } - - /* "View.MemoryView":476 - * if self.view.suboffsets != NULL: - * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) - * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, # <<<<<<<<<<<<<< - * item, self.dtype_is_object) - * finally: - */ - __pyx_memoryview_slice_assign_scalar(__pyx_v_dst_slice, __pyx_v_dst->view.ndim, __pyx_v_self->view.itemsize, __pyx_v_item, __pyx_v_self->dtype_is_object); - } - - /* "View.MemoryView":479 - * item, self.dtype_is_object) - * finally: - * PyMem_Free(tmp) # <<<<<<<<<<<<<< - * - * cdef setitem_indexed(self, index, value): - */ - /*finally:*/ { - /*normal exit:*/{ - PyMem_Free(__pyx_v_tmp); - goto __pyx_L7; - } - __pyx_L6_error:; - /*exception exit:*/{ - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); - if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9) < 0)) __Pyx_ErrFetch(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9); - __Pyx_XGOTREF(__pyx_t_7); - __Pyx_XGOTREF(__pyx_t_8); - __Pyx_XGOTREF(__pyx_t_9); - __Pyx_XGOTREF(__pyx_t_10); - __Pyx_XGOTREF(__pyx_t_11); - __Pyx_XGOTREF(__pyx_t_12); - __pyx_t_4 = __pyx_lineno; __pyx_t_5 = __pyx_clineno; __pyx_t_6 = __pyx_filename; - { - PyMem_Free(__pyx_v_tmp); - } - if (PY_MAJOR_VERSION >= 3) { - __Pyx_XGIVEREF(__pyx_t_10); - __Pyx_XGIVEREF(__pyx_t_11); - __Pyx_XGIVEREF(__pyx_t_12); - __Pyx_ExceptionReset(__pyx_t_10, __pyx_t_11, __pyx_t_12); - } - __Pyx_XGIVEREF(__pyx_t_7); - __Pyx_XGIVEREF(__pyx_t_8); - __Pyx_XGIVEREF(__pyx_t_9); - __Pyx_ErrRestore(__pyx_t_7, __pyx_t_8, __pyx_t_9); - __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; - __pyx_lineno = __pyx_t_4; __pyx_clineno = __pyx_t_5; __pyx_filename = __pyx_t_6; - goto __pyx_L1_error; - } - __pyx_L7:; - } - - /* "View.MemoryView":449 - * src.ndim, dst.ndim, self.dtype_is_object) - * - * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< - * cdef int array[128] - * cdef void *tmp = NULL - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":481 - * PyMem_Free(tmp) - * - * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< - * cdef char *itemp = self.get_item_pointer(index) - * self.assign_item_from_object(itemp, value) - */ - -static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { - char *__pyx_v_itemp; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - char *__pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("setitem_indexed", 0); - - /* "View.MemoryView":482 - * - * cdef setitem_indexed(self, index, value): - * cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<< - * self.assign_item_from_object(itemp, value) - * - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == ((char *)NULL))) __PYX_ERR(1, 482, __pyx_L1_error) - __pyx_v_itemp = __pyx_t_1; - - /* "View.MemoryView":483 - * cdef setitem_indexed(self, index, value): - * cdef char *itemp = self.get_item_pointer(index) - * self.assign_item_from_object(itemp, value) # <<<<<<<<<<<<<< - * - * cdef convert_item_to_object(self, char *itemp): - */ - __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 483, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "View.MemoryView":481 - * PyMem_Free(tmp) - * - * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< - * cdef char *itemp = self.get_item_pointer(index) - * self.assign_item_from_object(itemp, value) - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_indexed", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":485 - * self.assign_item_from_object(itemp, value) - * - * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< - * """Only used if instantiated manually by the user, or if Cython doesn't - * know how to convert the type""" - */ - -static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp) { - PyObject *__pyx_v_struct = NULL; - PyObject *__pyx_v_bytesitem = 0; - PyObject *__pyx_v_result = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - int __pyx_t_8; - PyObject *__pyx_t_9 = NULL; - size_t __pyx_t_10; - int __pyx_t_11; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("convert_item_to_object", 0); - - /* "View.MemoryView":488 - * """Only used if instantiated manually by the user, or if Cython doesn't - * know how to convert the type""" - * import struct # <<<<<<<<<<<<<< - * cdef bytes bytesitem - * - */ - __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 488, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_struct = __pyx_t_1; - __pyx_t_1 = 0; - - /* "View.MemoryView":491 - * cdef bytes bytesitem - * - * bytesitem = itemp[:self.view.itemsize] # <<<<<<<<<<<<<< - * try: - * result = struct.unpack(self.view.format, bytesitem) - */ - __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 491, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":492 - * - * bytesitem = itemp[:self.view.itemsize] - * try: # <<<<<<<<<<<<<< - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_4); - /*try:*/ { - - /* "View.MemoryView":493 - * bytesitem = itemp[:self.view.itemsize] - * try: - * result = struct.unpack(self.view.format, bytesitem) # <<<<<<<<<<<<<< - * except struct.error: - * raise ValueError("Unable to convert item to object") - */ - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_unpack); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 493, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 493, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = NULL; - __pyx_t_8 = 0; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_5))) { - __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_5); - if (likely(__pyx_t_7)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_5, function); - __pyx_t_8 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_5)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_6, __pyx_v_bytesitem}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 493, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_5)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_6, __pyx_v_bytesitem}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 493, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else - #endif - { - __pyx_t_9 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 493, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_9); - if (__pyx_t_7) { - __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_7); __pyx_t_7 = NULL; - } - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_6); - __Pyx_INCREF(__pyx_v_bytesitem); - __Pyx_GIVEREF(__pyx_v_bytesitem); - PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_v_bytesitem); - __pyx_t_6 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 493, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_v_result = __pyx_t_1; - __pyx_t_1 = 0; - - /* "View.MemoryView":492 - * - * bytesitem = itemp[:self.view.itemsize] - * try: # <<<<<<<<<<<<<< - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: - */ - } - - /* "View.MemoryView":497 - * raise ValueError("Unable to convert item to object") - * else: - * if len(self.view.format) == 1: # <<<<<<<<<<<<<< - * return result[0] - * return result - */ - /*else:*/ { - __pyx_t_10 = strlen(__pyx_v_self->view.format); - __pyx_t_11 = ((__pyx_t_10 == 1) != 0); - if (__pyx_t_11) { - - /* "View.MemoryView":498 - * else: - * if len(self.view.format) == 1: - * return result[0] # <<<<<<<<<<<<<< - * return result - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_result, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 498, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L6_except_return; - - /* "View.MemoryView":497 - * raise ValueError("Unable to convert item to object") - * else: - * if len(self.view.format) == 1: # <<<<<<<<<<<<<< - * return result[0] - * return result - */ - } - - /* "View.MemoryView":499 - * if len(self.view.format) == 1: - * return result[0] - * return result # <<<<<<<<<<<<<< - * - * cdef assign_item_from_object(self, char *itemp, object value): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_result); - __pyx_r = __pyx_v_result; - goto __pyx_L6_except_return; - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "View.MemoryView":494 - * try: - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: # <<<<<<<<<<<<<< - * raise ValueError("Unable to convert item to object") - * else: - */ - __Pyx_ErrFetch(&__pyx_t_1, &__pyx_t_5, &__pyx_t_9); - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 494, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_8 = __Pyx_PyErr_GivenExceptionMatches(__pyx_t_1, __pyx_t_6); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_ErrRestore(__pyx_t_1, __pyx_t_5, __pyx_t_9); - __pyx_t_1 = 0; __pyx_t_5 = 0; __pyx_t_9 = 0; - if (__pyx_t_8) { - __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_9, &__pyx_t_5, &__pyx_t_1) < 0) __PYX_ERR(1, 494, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GOTREF(__pyx_t_1); - - /* "View.MemoryView":495 - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: - * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< - * else: - * if len(self.view.format) == 1: - */ - __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 495, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_Raise(__pyx_t_6, 0, 0, 0); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __PYX_ERR(1, 495, __pyx_L5_except_error) - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "View.MemoryView":492 - * - * bytesitem = itemp[:self.view.itemsize] - * try: # <<<<<<<<<<<<<< - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: - */ - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L1_error; - __pyx_L6_except_return:; - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L0; - } - - /* "View.MemoryView":485 - * self.assign_item_from_object(itemp, value) - * - * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< - * """Only used if instantiated manually by the user, or if Cython doesn't - * know how to convert the type""" - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_struct); - __Pyx_XDECREF(__pyx_v_bytesitem); - __Pyx_XDECREF(__pyx_v_result); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":501 - * return result - * - * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< - * """Only used if instantiated manually by the user, or if Cython doesn't - * know how to convert the type""" - */ - -static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { - PyObject *__pyx_v_struct = NULL; - char __pyx_v_c; - PyObject *__pyx_v_bytesvalue = 0; - Py_ssize_t __pyx_v_i; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - Py_ssize_t __pyx_t_9; - PyObject *__pyx_t_10 = NULL; - char *__pyx_t_11; - char *__pyx_t_12; - char *__pyx_t_13; - char *__pyx_t_14; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("assign_item_from_object", 0); - - /* "View.MemoryView":504 - * """Only used if instantiated manually by the user, or if Cython doesn't - * know how to convert the type""" - * import struct # <<<<<<<<<<<<<< - * cdef char c - * cdef bytes bytesvalue - */ - __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 504, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_struct = __pyx_t_1; - __pyx_t_1 = 0; - - /* "View.MemoryView":509 - * cdef Py_ssize_t i - * - * if isinstance(value, tuple): # <<<<<<<<<<<<<< - * bytesvalue = struct.pack(self.view.format, *value) - * else: - */ - __pyx_t_2 = PyTuple_Check(__pyx_v_value); - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - - /* "View.MemoryView":510 - * - * if isinstance(value, tuple): - * bytesvalue = struct.pack(self.view.format, *value) # <<<<<<<<<<<<<< - * else: - * bytesvalue = struct.pack(self.view.format, value) - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 510, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 510, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 510, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 510, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = PyNumber_Add(__pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 510, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 510, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(1, 510, __pyx_L1_error) - __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); - __pyx_t_4 = 0; - - /* "View.MemoryView":509 - * cdef Py_ssize_t i - * - * if isinstance(value, tuple): # <<<<<<<<<<<<<< - * bytesvalue = struct.pack(self.view.format, *value) - * else: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":512 - * bytesvalue = struct.pack(self.view.format, *value) - * else: - * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< - * - * for i, c in enumerate(bytesvalue): - */ - /*else*/ { - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 512, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 512, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_5 = NULL; - __pyx_t_7 = 0; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_6))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_6); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_6, function); - __pyx_t_7 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[3] = {__pyx_t_5, __pyx_t_1, __pyx_v_value}; - __pyx_t_4 = __Pyx_PyFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 512, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[3] = {__pyx_t_5, __pyx_t_1, __pyx_v_value}; - __pyx_t_4 = __Pyx_PyCFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 512, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else - #endif - { - __pyx_t_8 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 512, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - if (__pyx_t_5) { - __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_5); __pyx_t_5 = NULL; - } - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_1); - __Pyx_INCREF(__pyx_v_value); - __Pyx_GIVEREF(__pyx_v_value); - PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_v_value); - __pyx_t_1 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_8, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 512, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - } - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(1, 512, __pyx_L1_error) - __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); - __pyx_t_4 = 0; - } - __pyx_L3:; - - /* "View.MemoryView":514 - * bytesvalue = struct.pack(self.view.format, value) - * - * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< - * itemp[i] = c - * - */ - __pyx_t_9 = 0; - if (unlikely(__pyx_v_bytesvalue == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); - __PYX_ERR(1, 514, __pyx_L1_error) - } - __Pyx_INCREF(__pyx_v_bytesvalue); - __pyx_t_10 = __pyx_v_bytesvalue; - __pyx_t_12 = PyBytes_AS_STRING(__pyx_t_10); - __pyx_t_13 = (__pyx_t_12 + PyBytes_GET_SIZE(__pyx_t_10)); - for (__pyx_t_14 = __pyx_t_12; __pyx_t_14 < __pyx_t_13; __pyx_t_14++) { - __pyx_t_11 = __pyx_t_14; - __pyx_v_c = (__pyx_t_11[0]); - - /* "View.MemoryView":515 - * - * for i, c in enumerate(bytesvalue): - * itemp[i] = c # <<<<<<<<<<<<<< - * - * @cname('getbuffer') - */ - __pyx_v_i = __pyx_t_9; - - /* "View.MemoryView":514 - * bytesvalue = struct.pack(self.view.format, value) - * - * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< - * itemp[i] = c - * - */ - __pyx_t_9 = (__pyx_t_9 + 1); - - /* "View.MemoryView":515 - * - * for i, c in enumerate(bytesvalue): - * itemp[i] = c # <<<<<<<<<<<<<< - * - * @cname('getbuffer') - */ - (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; - } - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - - /* "View.MemoryView":501 - * return result - * - * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< - * """Only used if instantiated manually by the user, or if Cython doesn't - * know how to convert the type""" - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_AddTraceback("View.MemoryView.memoryview.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_struct); - __Pyx_XDECREF(__pyx_v_bytesvalue); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":518 - * - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< - * if flags & PyBUF_WRITABLE and self.view.readonly: - * raise ValueError("Cannot create writable memory view from read-only memoryview") - */ - -/* Python wrapper */ -static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - Py_ssize_t *__pyx_t_4; - char *__pyx_t_5; - void *__pyx_t_6; - int __pyx_t_7; - Py_ssize_t __pyx_t_8; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - if (__pyx_v_info == NULL) { - PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); - return -1; - } - __Pyx_RefNannySetupContext("__getbuffer__", 0); - __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(__pyx_v_info->obj); - - /* "View.MemoryView":519 - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): - * if flags & PyBUF_WRITABLE and self.view.readonly: # <<<<<<<<<<<<<< - * raise ValueError("Cannot create writable memory view from read-only memoryview") - * - */ - __pyx_t_2 = ((__pyx_v_flags & PyBUF_WRITABLE) != 0); - if (__pyx_t_2) { - } else { - __pyx_t_1 = __pyx_t_2; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_2 = (__pyx_v_self->view.readonly != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L4_bool_binop_done:; - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":520 - * def __getbuffer__(self, Py_buffer *info, int flags): - * if flags & PyBUF_WRITABLE and self.view.readonly: - * raise ValueError("Cannot create writable memory view from read-only memoryview") # <<<<<<<<<<<<<< - * - * if flags & PyBUF_ND: - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__11, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 520, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 520, __pyx_L1_error) - - /* "View.MemoryView":519 - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): - * if flags & PyBUF_WRITABLE and self.view.readonly: # <<<<<<<<<<<<<< - * raise ValueError("Cannot create writable memory view from read-only memoryview") - * - */ - } - - /* "View.MemoryView":522 - * raise ValueError("Cannot create writable memory view from read-only memoryview") - * - * if flags & PyBUF_ND: # <<<<<<<<<<<<<< - * info.shape = self.view.shape - * else: - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_ND) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":523 - * - * if flags & PyBUF_ND: - * info.shape = self.view.shape # <<<<<<<<<<<<<< - * else: - * info.shape = NULL - */ - __pyx_t_4 = __pyx_v_self->view.shape; - __pyx_v_info->shape = __pyx_t_4; - - /* "View.MemoryView":522 - * raise ValueError("Cannot create writable memory view from read-only memoryview") - * - * if flags & PyBUF_ND: # <<<<<<<<<<<<<< - * info.shape = self.view.shape - * else: - */ - goto __pyx_L6; - } - - /* "View.MemoryView":525 - * info.shape = self.view.shape - * else: - * info.shape = NULL # <<<<<<<<<<<<<< - * - * if flags & PyBUF_STRIDES: - */ - /*else*/ { - __pyx_v_info->shape = NULL; - } - __pyx_L6:; - - /* "View.MemoryView":527 - * info.shape = NULL - * - * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< - * info.strides = self.view.strides - * else: - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":528 - * - * if flags & PyBUF_STRIDES: - * info.strides = self.view.strides # <<<<<<<<<<<<<< - * else: - * info.strides = NULL - */ - __pyx_t_4 = __pyx_v_self->view.strides; - __pyx_v_info->strides = __pyx_t_4; - - /* "View.MemoryView":527 - * info.shape = NULL - * - * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< - * info.strides = self.view.strides - * else: - */ - goto __pyx_L7; - } - - /* "View.MemoryView":530 - * info.strides = self.view.strides - * else: - * info.strides = NULL # <<<<<<<<<<<<<< - * - * if flags & PyBUF_INDIRECT: - */ - /*else*/ { - __pyx_v_info->strides = NULL; - } - __pyx_L7:; - - /* "View.MemoryView":532 - * info.strides = NULL - * - * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< - * info.suboffsets = self.view.suboffsets - * else: - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":533 - * - * if flags & PyBUF_INDIRECT: - * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< - * else: - * info.suboffsets = NULL - */ - __pyx_t_4 = __pyx_v_self->view.suboffsets; - __pyx_v_info->suboffsets = __pyx_t_4; - - /* "View.MemoryView":532 - * info.strides = NULL - * - * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< - * info.suboffsets = self.view.suboffsets - * else: - */ - goto __pyx_L8; - } - - /* "View.MemoryView":535 - * info.suboffsets = self.view.suboffsets - * else: - * info.suboffsets = NULL # <<<<<<<<<<<<<< - * - * if flags & PyBUF_FORMAT: - */ - /*else*/ { - __pyx_v_info->suboffsets = NULL; - } - __pyx_L8:; - - /* "View.MemoryView":537 - * info.suboffsets = NULL - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * info.format = self.view.format - * else: - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":538 - * - * if flags & PyBUF_FORMAT: - * info.format = self.view.format # <<<<<<<<<<<<<< - * else: - * info.format = NULL - */ - __pyx_t_5 = __pyx_v_self->view.format; - __pyx_v_info->format = __pyx_t_5; - - /* "View.MemoryView":537 - * info.suboffsets = NULL - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * info.format = self.view.format - * else: - */ - goto __pyx_L9; - } - - /* "View.MemoryView":540 - * info.format = self.view.format - * else: - * info.format = NULL # <<<<<<<<<<<<<< - * - * info.buf = self.view.buf - */ - /*else*/ { - __pyx_v_info->format = NULL; - } - __pyx_L9:; - - /* "View.MemoryView":542 - * info.format = NULL - * - * info.buf = self.view.buf # <<<<<<<<<<<<<< - * info.ndim = self.view.ndim - * info.itemsize = self.view.itemsize - */ - __pyx_t_6 = __pyx_v_self->view.buf; - __pyx_v_info->buf = __pyx_t_6; - - /* "View.MemoryView":543 - * - * info.buf = self.view.buf - * info.ndim = self.view.ndim # <<<<<<<<<<<<<< - * info.itemsize = self.view.itemsize - * info.len = self.view.len - */ - __pyx_t_7 = __pyx_v_self->view.ndim; - __pyx_v_info->ndim = __pyx_t_7; - - /* "View.MemoryView":544 - * info.buf = self.view.buf - * info.ndim = self.view.ndim - * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< - * info.len = self.view.len - * info.readonly = self.view.readonly - */ - __pyx_t_8 = __pyx_v_self->view.itemsize; - __pyx_v_info->itemsize = __pyx_t_8; - - /* "View.MemoryView":545 - * info.ndim = self.view.ndim - * info.itemsize = self.view.itemsize - * info.len = self.view.len # <<<<<<<<<<<<<< - * info.readonly = self.view.readonly - * info.obj = self - */ - __pyx_t_8 = __pyx_v_self->view.len; - __pyx_v_info->len = __pyx_t_8; - - /* "View.MemoryView":546 - * info.itemsize = self.view.itemsize - * info.len = self.view.len - * info.readonly = self.view.readonly # <<<<<<<<<<<<<< - * info.obj = self - * - */ - __pyx_t_1 = __pyx_v_self->view.readonly; - __pyx_v_info->readonly = __pyx_t_1; - - /* "View.MemoryView":547 - * info.len = self.view.len - * info.readonly = self.view.readonly - * info.obj = self # <<<<<<<<<<<<<< - * - * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") - */ - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = ((PyObject *)__pyx_v_self); - - /* "View.MemoryView":518 - * - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< - * if flags & PyBUF_WRITABLE and self.view.readonly: - * raise ValueError("Cannot create writable memory view from read-only memoryview") - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - if (__pyx_v_info->obj != NULL) { - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; - } - goto __pyx_L2; - __pyx_L0:; - if (__pyx_v_info->obj == Py_None) { - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; - } - __pyx_L2:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":553 - * - * @property - * def T(self): # <<<<<<<<<<<<<< - * cdef _memoryviewslice result = memoryview_copy(self) - * transpose_memslice(&result.from_slice) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":554 - * @property - * def T(self): - * cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<< - * transpose_memslice(&result.from_slice) - * return result - */ - __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 554, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) __PYX_ERR(1, 554, __pyx_L1_error) - __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":555 - * def T(self): - * cdef _memoryviewslice result = memoryview_copy(self) - * transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<< - * return result - * - */ - __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == ((int)0))) __PYX_ERR(1, 555, __pyx_L1_error) - - /* "View.MemoryView":556 - * cdef _memoryviewslice result = memoryview_copy(self) - * transpose_memslice(&result.from_slice) - * return result # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_result)); - __pyx_r = ((PyObject *)__pyx_v_result); - goto __pyx_L0; - - /* "View.MemoryView":553 - * - * @property - * def T(self): # <<<<<<<<<<<<<< - * cdef _memoryviewslice result = memoryview_copy(self) - * transpose_memslice(&result.from_slice) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.memoryview.T.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_result); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":559 - * - * @property - * def base(self): # <<<<<<<<<<<<<< - * return self.obj - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":560 - * @property - * def base(self): - * return self.obj # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->obj); - __pyx_r = __pyx_v_self->obj; - goto __pyx_L0; - - /* "View.MemoryView":559 - * - * @property - * def base(self): # <<<<<<<<<<<<<< - * return self.obj - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":563 - * - * @property - * def shape(self): # <<<<<<<<<<<<<< - * return tuple([length for length in self.view.shape[:self.view.ndim]]) - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - Py_ssize_t __pyx_v_length; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t *__pyx_t_2; - Py_ssize_t *__pyx_t_3; - Py_ssize_t *__pyx_t_4; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":564 - * @property - * def shape(self): - * return tuple([length for length in self.view.shape[:self.view.ndim]]) # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 564, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = (__pyx_v_self->view.shape + __pyx_v_self->view.ndim); - for (__pyx_t_4 = __pyx_v_self->view.shape; __pyx_t_4 < __pyx_t_3; __pyx_t_4++) { - __pyx_t_2 = __pyx_t_4; - __pyx_v_length = (__pyx_t_2[0]); - __pyx_t_5 = PyInt_FromSsize_t(__pyx_v_length); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 564, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_5))) __PYX_ERR(1, 564, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } - __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 564, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "View.MemoryView":563 - * - * @property - * def shape(self): # <<<<<<<<<<<<<< - * return tuple([length for length in self.view.shape[:self.view.ndim]]) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.memoryview.shape.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":567 - * - * @property - * def strides(self): # <<<<<<<<<<<<<< - * if self.view.strides == NULL: - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - Py_ssize_t __pyx_v_stride; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - Py_ssize_t *__pyx_t_3; - Py_ssize_t *__pyx_t_4; - Py_ssize_t *__pyx_t_5; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":568 - * @property - * def strides(self): - * if self.view.strides == NULL: # <<<<<<<<<<<<<< - * - * raise ValueError("Buffer view does not expose strides") - */ - __pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0); - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":570 - * if self.view.strides == NULL: - * - * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< - * - * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) - */ - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__12, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 570, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __PYX_ERR(1, 570, __pyx_L1_error) - - /* "View.MemoryView":568 - * @property - * def strides(self): - * if self.view.strides == NULL: # <<<<<<<<<<<<<< - * - * raise ValueError("Buffer view does not expose strides") - */ - } - - /* "View.MemoryView":572 - * raise ValueError("Buffer view does not expose strides") - * - * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 572, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = (__pyx_v_self->view.strides + __pyx_v_self->view.ndim); - for (__pyx_t_5 = __pyx_v_self->view.strides; __pyx_t_5 < __pyx_t_4; __pyx_t_5++) { - __pyx_t_3 = __pyx_t_5; - __pyx_v_stride = (__pyx_t_3[0]); - __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_stride); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 572, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_6))) __PYX_ERR(1, 572, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } - __pyx_t_6 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 572, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_6; - __pyx_t_6 = 0; - goto __pyx_L0; - - /* "View.MemoryView":567 - * - * @property - * def strides(self): # <<<<<<<<<<<<<< - * if self.view.strides == NULL: - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("View.MemoryView.memoryview.strides.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":575 - * - * @property - * def suboffsets(self): # <<<<<<<<<<<<<< - * if self.view.suboffsets == NULL: - * return (-1,) * self.view.ndim - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - Py_ssize_t __pyx_v_suboffset; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - Py_ssize_t *__pyx_t_4; - Py_ssize_t *__pyx_t_5; - Py_ssize_t *__pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":576 - * @property - * def suboffsets(self): - * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< - * return (-1,) * self.view.ndim - * - */ - __pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":577 - * def suboffsets(self): - * if self.view.suboffsets == NULL: - * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< - * - * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 577, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Multiply(__pyx_tuple__13, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 577, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "View.MemoryView":576 - * @property - * def suboffsets(self): - * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< - * return (-1,) * self.view.ndim - * - */ - } - - /* "View.MemoryView":579 - * return (-1,) * self.view.ndim - * - * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 579, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = (__pyx_v_self->view.suboffsets + __pyx_v_self->view.ndim); - for (__pyx_t_6 = __pyx_v_self->view.suboffsets; __pyx_t_6 < __pyx_t_5; __pyx_t_6++) { - __pyx_t_4 = __pyx_t_6; - __pyx_v_suboffset = (__pyx_t_4[0]); - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_suboffset); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 579, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (unlikely(__Pyx_ListComp_Append(__pyx_t_3, (PyObject*)__pyx_t_2))) __PYX_ERR(1, 579, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __pyx_t_2 = PyList_AsTuple(((PyObject*)__pyx_t_3)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 579, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":575 - * - * @property - * def suboffsets(self): # <<<<<<<<<<<<<< - * if self.view.suboffsets == NULL: - * return (-1,) * self.view.ndim - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview.suboffsets.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":582 - * - * @property - * def ndim(self): # <<<<<<<<<<<<<< - * return self.view.ndim - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":583 - * @property - * def ndim(self): - * return self.view.ndim # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 583, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":582 - * - * @property - * def ndim(self): # <<<<<<<<<<<<<< - * return self.view.ndim - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.memoryview.ndim.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":586 - * - * @property - * def itemsize(self): # <<<<<<<<<<<<<< - * return self.view.itemsize - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":587 - * @property - * def itemsize(self): - * return self.view.itemsize # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 587, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":586 - * - * @property - * def itemsize(self): # <<<<<<<<<<<<<< - * return self.view.itemsize - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.memoryview.itemsize.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":590 - * - * @property - * def nbytes(self): # <<<<<<<<<<<<<< - * return self.size * self.view.itemsize - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":591 - * @property - * def nbytes(self): - * return self.size * self.view.itemsize # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 591, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 591, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 591, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "View.MemoryView":590 - * - * @property - * def nbytes(self): # <<<<<<<<<<<<<< - * return self.size * self.view.itemsize - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview.nbytes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":594 - * - * @property - * def size(self): # <<<<<<<<<<<<<< - * if self._size is None: - * result = 1 - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_v_result = NULL; - PyObject *__pyx_v_length = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - Py_ssize_t *__pyx_t_3; - Py_ssize_t *__pyx_t_4; - Py_ssize_t *__pyx_t_5; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":595 - * @property - * def size(self): - * if self._size is None: # <<<<<<<<<<<<<< - * result = 1 - * - */ - __pyx_t_1 = (__pyx_v_self->_size == Py_None); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":596 - * def size(self): - * if self._size is None: - * result = 1 # <<<<<<<<<<<<<< - * - * for length in self.view.shape[:self.view.ndim]: - */ - __Pyx_INCREF(__pyx_int_1); - __pyx_v_result = __pyx_int_1; - - /* "View.MemoryView":598 - * result = 1 - * - * for length in self.view.shape[:self.view.ndim]: # <<<<<<<<<<<<<< - * result *= length - * - */ - __pyx_t_4 = (__pyx_v_self->view.shape + __pyx_v_self->view.ndim); - for (__pyx_t_5 = __pyx_v_self->view.shape; __pyx_t_5 < __pyx_t_4; __pyx_t_5++) { - __pyx_t_3 = __pyx_t_5; - __pyx_t_6 = PyInt_FromSsize_t((__pyx_t_3[0])); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 598, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_6); - __pyx_t_6 = 0; - - /* "View.MemoryView":599 - * - * for length in self.view.shape[:self.view.ndim]: - * result *= length # <<<<<<<<<<<<<< - * - * self._size = result - */ - __pyx_t_6 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 599, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_6); - __pyx_t_6 = 0; - } - - /* "View.MemoryView":601 - * result *= length - * - * self._size = result # <<<<<<<<<<<<<< - * - * return self._size - */ - __Pyx_INCREF(__pyx_v_result); - __Pyx_GIVEREF(__pyx_v_result); - __Pyx_GOTREF(__pyx_v_self->_size); - __Pyx_DECREF(__pyx_v_self->_size); - __pyx_v_self->_size = __pyx_v_result; - - /* "View.MemoryView":595 - * @property - * def size(self): - * if self._size is None: # <<<<<<<<<<<<<< - * result = 1 - * - */ - } - - /* "View.MemoryView":603 - * self._size = result - * - * return self._size # <<<<<<<<<<<<<< - * - * def __len__(self): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->_size); - __pyx_r = __pyx_v_self->_size; - goto __pyx_L0; - - /* "View.MemoryView":594 - * - * @property - * def size(self): # <<<<<<<<<<<<<< - * if self._size is None: - * result = 1 - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("View.MemoryView.memoryview.size.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_result); - __Pyx_XDECREF(__pyx_v_length); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":605 - * return self._size - * - * def __len__(self): # <<<<<<<<<<<<<< - * if self.view.ndim >= 1: - * return self.view.shape[0] - */ - -/* Python wrapper */ -static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self); /*proto*/ -static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self) { - Py_ssize_t __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) { - Py_ssize_t __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("__len__", 0); - - /* "View.MemoryView":606 - * - * def __len__(self): - * if self.view.ndim >= 1: # <<<<<<<<<<<<<< - * return self.view.shape[0] - * - */ - __pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":607 - * def __len__(self): - * if self.view.ndim >= 1: - * return self.view.shape[0] # <<<<<<<<<<<<<< - * - * return 0 - */ - __pyx_r = (__pyx_v_self->view.shape[0]); - goto __pyx_L0; - - /* "View.MemoryView":606 - * - * def __len__(self): - * if self.view.ndim >= 1: # <<<<<<<<<<<<<< - * return self.view.shape[0] - * - */ - } - - /* "View.MemoryView":609 - * return self.view.shape[0] - * - * return 0 # <<<<<<<<<<<<<< - * - * def __repr__(self): - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "View.MemoryView":605 - * return self._size - * - * def __len__(self): # <<<<<<<<<<<<<< - * if self.view.ndim >= 1: - * return self.view.shape[0] - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":611 - * return 0 - * - * def __repr__(self): # <<<<<<<<<<<<<< - * return "" % (self.base.__class__.__name__, - * id(self)) - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__repr__", 0); - - /* "View.MemoryView":612 - * - * def __repr__(self): - * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< - * id(self)) - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 612, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 612, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 612, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "View.MemoryView":613 - * def __repr__(self): - * return "" % (self.base.__class__.__name__, - * id(self)) # <<<<<<<<<<<<<< - * - * def __str__(self): - */ - __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_id, ((PyObject *)__pyx_v_self)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 613, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - - /* "View.MemoryView":612 - * - * def __repr__(self): - * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< - * id(self)) - * - */ - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 612, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 612, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":611 - * return 0 - * - * def __repr__(self): # <<<<<<<<<<<<<< - * return "" % (self.base.__class__.__name__, - * id(self)) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":615 - * id(self)) - * - * def __str__(self): # <<<<<<<<<<<<<< - * return "" % (self.base.__class__.__name__,) - * - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__str__", 0); - - /* "View.MemoryView":616 - * - * def __str__(self): - * return "" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 616, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 616, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 616, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 616, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_object, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 616, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":615 - * id(self)) - * - * def __str__(self): # <<<<<<<<<<<<<< - * return "" % (self.base.__class__.__name__,) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.memoryview.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":619 - * - * - * def is_c_contig(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("is_c_contig (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) { - __Pyx_memviewslice *__pyx_v_mslice; - __Pyx_memviewslice __pyx_v_tmp; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_memviewslice *__pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("is_c_contig", 0); - - /* "View.MemoryView":622 - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< - * return slice_is_contig(mslice[0], 'C', self.view.ndim) - * - */ - __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(1, 622, __pyx_L1_error) - __pyx_v_mslice = __pyx_t_1; - - /* "View.MemoryView":623 - * cdef __Pyx_memviewslice tmp - * mslice = get_slice_from_memview(self, &tmp) - * return slice_is_contig(mslice[0], 'C', self.view.ndim) # <<<<<<<<<<<<<< - * - * def is_f_contig(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 623, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":619 - * - * - * def is_c_contig(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.memoryview.is_c_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":625 - * return slice_is_contig(mslice[0], 'C', self.view.ndim) - * - * def is_f_contig(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("is_f_contig (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) { - __Pyx_memviewslice *__pyx_v_mslice; - __Pyx_memviewslice __pyx_v_tmp; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_memviewslice *__pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("is_f_contig", 0); - - /* "View.MemoryView":628 - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< - * return slice_is_contig(mslice[0], 'F', self.view.ndim) - * - */ - __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(1, 628, __pyx_L1_error) - __pyx_v_mslice = __pyx_t_1; - - /* "View.MemoryView":629 - * cdef __Pyx_memviewslice tmp - * mslice = get_slice_from_memview(self, &tmp) - * return slice_is_contig(mslice[0], 'F', self.view.ndim) # <<<<<<<<<<<<<< - * - * def copy(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 629, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":625 - * return slice_is_contig(mslice[0], 'C', self.view.ndim) - * - * def is_f_contig(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.memoryview.is_f_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":631 - * return slice_is_contig(mslice[0], 'F', self.view.ndim) - * - * def copy(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice mslice - * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("copy (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) { - __Pyx_memviewslice __pyx_v_mslice; - int __pyx_v_flags; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_memviewslice __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("copy", 0); - - /* "View.MemoryView":633 - * def copy(self): - * cdef __Pyx_memviewslice mslice - * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<< - * - * slice_copy(self, &mslice) - */ - __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS)); - - /* "View.MemoryView":635 - * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS - * - * slice_copy(self, &mslice) # <<<<<<<<<<<<<< - * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, - * self.view.itemsize, - */ - __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice)); - - /* "View.MemoryView":636 - * - * slice_copy(self, &mslice) - * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, # <<<<<<<<<<<<<< - * self.view.itemsize, - * flags|PyBUF_C_CONTIGUOUS, - */ - __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), ((char *)"c"), __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) __PYX_ERR(1, 636, __pyx_L1_error) - __pyx_v_mslice = __pyx_t_1; - - /* "View.MemoryView":641 - * self.dtype_is_object) - * - * return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<< - * - * def copy_fortran(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 641, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":631 - * return slice_is_contig(mslice[0], 'F', self.view.ndim) - * - * def copy(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice mslice - * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.memoryview.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":643 - * return memoryview_copy_from_slice(self, &mslice) - * - * def copy_fortran(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice src, dst - * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("copy_fortran (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) { - __Pyx_memviewslice __pyx_v_src; - __Pyx_memviewslice __pyx_v_dst; - int __pyx_v_flags; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_memviewslice __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("copy_fortran", 0); - - /* "View.MemoryView":645 - * def copy_fortran(self): - * cdef __Pyx_memviewslice src, dst - * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<< - * - * slice_copy(self, &src) - */ - __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS)); - - /* "View.MemoryView":647 - * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS - * - * slice_copy(self, &src) # <<<<<<<<<<<<<< - * dst = slice_copy_contig(&src, "fortran", self.view.ndim, - * self.view.itemsize, - */ - __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src)); - - /* "View.MemoryView":648 - * - * slice_copy(self, &src) - * dst = slice_copy_contig(&src, "fortran", self.view.ndim, # <<<<<<<<<<<<<< - * self.view.itemsize, - * flags|PyBUF_F_CONTIGUOUS, - */ - __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), ((char *)"fortran"), __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) __PYX_ERR(1, 648, __pyx_L1_error) - __pyx_v_dst = __pyx_t_1; - - /* "View.MemoryView":653 - * self.dtype_is_object) - * - * return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 653, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":643 - * return memoryview_copy_from_slice(self, &mslice) - * - * def copy_fortran(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice src, dst - * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.memoryview.copy_fortran", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_memoryview_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw___pyx_memoryview_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_memoryview___reduce_cython__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_memoryview___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__14, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 2, __pyx_L1_error) - - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.memoryview.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_memoryview_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw___pyx_memoryview_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_memoryview_2__setstate_cython__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_memoryview_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__15, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 4, __pyx_L1_error) - - /* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.memoryview.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":657 - * - * @cname('__pyx_memoryview_new') - * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< - * cdef memoryview result = memoryview(o, flags, dtype_is_object) - * result.typeinfo = typeinfo - */ - -static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) { - struct __pyx_memoryview_obj *__pyx_v_result = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); - - /* "View.MemoryView":658 - * @cname('__pyx_memoryview_new') - * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): - * cdef memoryview result = memoryview(o, flags, dtype_is_object) # <<<<<<<<<<<<<< - * result.typeinfo = typeinfo - * return result - */ - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 658, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 658, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 658, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_o); - __Pyx_GIVEREF(__pyx_v_o); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 658, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_result = ((struct __pyx_memoryview_obj *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "View.MemoryView":659 - * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): - * cdef memoryview result = memoryview(o, flags, dtype_is_object) - * result.typeinfo = typeinfo # <<<<<<<<<<<<<< - * return result - * - */ - __pyx_v_result->typeinfo = __pyx_v_typeinfo; - - /* "View.MemoryView":660 - * cdef memoryview result = memoryview(o, flags, dtype_is_object) - * result.typeinfo = typeinfo - * return result # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_check') - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_result)); - __pyx_r = ((PyObject *)__pyx_v_result); - goto __pyx_L0; - - /* "View.MemoryView":657 - * - * @cname('__pyx_memoryview_new') - * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< - * cdef memoryview result = memoryview(o, flags, dtype_is_object) - * result.typeinfo = typeinfo - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_result); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":663 - * - * @cname('__pyx_memoryview_check') - * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< - * return isinstance(o, memoryview) - * - */ - -static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("memoryview_check", 0); - - /* "View.MemoryView":664 - * @cname('__pyx_memoryview_check') - * cdef inline bint memoryview_check(object o): - * return isinstance(o, memoryview) # <<<<<<<<<<<<<< - * - * cdef tuple _unellipsify(object index, int ndim): - */ - __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, __pyx_memoryview_type); - __pyx_r = __pyx_t_1; - goto __pyx_L0; - - /* "View.MemoryView":663 - * - * @cname('__pyx_memoryview_check') - * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< - * return isinstance(o, memoryview) - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":666 - * return isinstance(o, memoryview) - * - * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< - * """ - * Replace all ellipses with full slices and fill incomplete indices with - */ - -static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { - PyObject *__pyx_v_tup = NULL; - PyObject *__pyx_v_result = NULL; - int __pyx_v_have_slices; - int __pyx_v_seen_ellipsis; - CYTHON_UNUSED PyObject *__pyx_v_idx = NULL; - PyObject *__pyx_v_item = NULL; - Py_ssize_t __pyx_v_nslices; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - Py_ssize_t __pyx_t_5; - PyObject *(*__pyx_t_6)(PyObject *); - PyObject *__pyx_t_7 = NULL; - Py_ssize_t __pyx_t_8; - int __pyx_t_9; - int __pyx_t_10; - PyObject *__pyx_t_11 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_unellipsify", 0); - - /* "View.MemoryView":671 - * full slices. - * """ - * if not isinstance(index, tuple): # <<<<<<<<<<<<<< - * tup = (index,) - * else: - */ - __pyx_t_1 = PyTuple_Check(__pyx_v_index); - __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":672 - * """ - * if not isinstance(index, tuple): - * tup = (index,) # <<<<<<<<<<<<<< - * else: - * tup = index - */ - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 672, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_index); - __Pyx_GIVEREF(__pyx_v_index); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); - __pyx_v_tup = __pyx_t_3; - __pyx_t_3 = 0; - - /* "View.MemoryView":671 - * full slices. - * """ - * if not isinstance(index, tuple): # <<<<<<<<<<<<<< - * tup = (index,) - * else: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":674 - * tup = (index,) - * else: - * tup = index # <<<<<<<<<<<<<< - * - * result = [] - */ - /*else*/ { - __Pyx_INCREF(__pyx_v_index); - __pyx_v_tup = __pyx_v_index; - } - __pyx_L3:; - - /* "View.MemoryView":676 - * tup = index - * - * result = [] # <<<<<<<<<<<<<< - * have_slices = False - * seen_ellipsis = False - */ - __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 676, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_result = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "View.MemoryView":677 - * - * result = [] - * have_slices = False # <<<<<<<<<<<<<< - * seen_ellipsis = False - * for idx, item in enumerate(tup): - */ - __pyx_v_have_slices = 0; - - /* "View.MemoryView":678 - * result = [] - * have_slices = False - * seen_ellipsis = False # <<<<<<<<<<<<<< - * for idx, item in enumerate(tup): - * if item is Ellipsis: - */ - __pyx_v_seen_ellipsis = 0; - - /* "View.MemoryView":679 - * have_slices = False - * seen_ellipsis = False - * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< - * if item is Ellipsis: - * if not seen_ellipsis: - */ - __Pyx_INCREF(__pyx_int_0); - __pyx_t_3 = __pyx_int_0; - if (likely(PyList_CheckExact(__pyx_v_tup)) || PyTuple_CheckExact(__pyx_v_tup)) { - __pyx_t_4 = __pyx_v_tup; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; - __pyx_t_6 = NULL; - } else { - __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 679, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 679, __pyx_L1_error) - } - for (;;) { - if (likely(!__pyx_t_6)) { - if (likely(PyList_CheckExact(__pyx_t_4))) { - if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(1, 679, __pyx_L1_error) - #else - __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 679, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - #endif - } else { - if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(1, 679, __pyx_L1_error) - #else - __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 679, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - #endif - } - } else { - __pyx_t_7 = __pyx_t_6(__pyx_t_4); - if (unlikely(!__pyx_t_7)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(1, 679, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_7); - } - __Pyx_XDECREF_SET(__pyx_v_item, __pyx_t_7); - __pyx_t_7 = 0; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_3); - __pyx_t_7 = __Pyx_PyInt_AddObjC(__pyx_t_3, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 679, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); - __pyx_t_3 = __pyx_t_7; - __pyx_t_7 = 0; - - /* "View.MemoryView":680 - * seen_ellipsis = False - * for idx, item in enumerate(tup): - * if item is Ellipsis: # <<<<<<<<<<<<<< - * if not seen_ellipsis: - * result.extend([slice(None)] * (ndim - len(tup) + 1)) - */ - __pyx_t_2 = (__pyx_v_item == __pyx_builtin_Ellipsis); - __pyx_t_1 = (__pyx_t_2 != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":681 - * for idx, item in enumerate(tup): - * if item is Ellipsis: - * if not seen_ellipsis: # <<<<<<<<<<<<<< - * result.extend([slice(None)] * (ndim - len(tup) + 1)) - * seen_ellipsis = True - */ - __pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":682 - * if item is Ellipsis: - * if not seen_ellipsis: - * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< - * seen_ellipsis = True - * else: - */ - __pyx_t_8 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_8 == ((Py_ssize_t)-1))) __PYX_ERR(1, 682, __pyx_L1_error) - __pyx_t_7 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_8) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_8) + 1))); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 682, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - { Py_ssize_t __pyx_temp; - for (__pyx_temp=0; __pyx_temp < ((__pyx_v_ndim - __pyx_t_8) + 1); __pyx_temp++) { - __Pyx_INCREF(__pyx_slice__16); - __Pyx_GIVEREF(__pyx_slice__16); - PyList_SET_ITEM(__pyx_t_7, __pyx_temp, __pyx_slice__16); - } - } - __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_7); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 682, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - - /* "View.MemoryView":683 - * if not seen_ellipsis: - * result.extend([slice(None)] * (ndim - len(tup) + 1)) - * seen_ellipsis = True # <<<<<<<<<<<<<< - * else: - * result.append(slice(None)) - */ - __pyx_v_seen_ellipsis = 1; - - /* "View.MemoryView":681 - * for idx, item in enumerate(tup): - * if item is Ellipsis: - * if not seen_ellipsis: # <<<<<<<<<<<<<< - * result.extend([slice(None)] * (ndim - len(tup) + 1)) - * seen_ellipsis = True - */ - goto __pyx_L7; - } - - /* "View.MemoryView":685 - * seen_ellipsis = True - * else: - * result.append(slice(None)) # <<<<<<<<<<<<<< - * have_slices = True - * else: - */ - /*else*/ { - __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_slice__16); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 685, __pyx_L1_error) - } - __pyx_L7:; - - /* "View.MemoryView":686 - * else: - * result.append(slice(None)) - * have_slices = True # <<<<<<<<<<<<<< - * else: - * if not isinstance(item, slice) and not PyIndex_Check(item): - */ - __pyx_v_have_slices = 1; - - /* "View.MemoryView":680 - * seen_ellipsis = False - * for idx, item in enumerate(tup): - * if item is Ellipsis: # <<<<<<<<<<<<<< - * if not seen_ellipsis: - * result.extend([slice(None)] * (ndim - len(tup) + 1)) - */ - goto __pyx_L6; - } - - /* "View.MemoryView":688 - * have_slices = True - * else: - * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< - * raise TypeError("Cannot index with type '%s'" % type(item)) - * - */ - /*else*/ { - __pyx_t_2 = PySlice_Check(__pyx_v_item); - __pyx_t_10 = ((!(__pyx_t_2 != 0)) != 0); - if (__pyx_t_10) { - } else { - __pyx_t_1 = __pyx_t_10; - goto __pyx_L9_bool_binop_done; - } - __pyx_t_10 = ((!(PyIndex_Check(__pyx_v_item) != 0)) != 0); - __pyx_t_1 = __pyx_t_10; - __pyx_L9_bool_binop_done:; - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":689 - * else: - * if not isinstance(item, slice) and not PyIndex_Check(item): - * raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<< - * - * have_slices = have_slices or isinstance(item, slice) - */ - __pyx_t_7 = __Pyx_PyString_FormatSafe(__pyx_kp_s_Cannot_index_with_type_s, ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 689, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_11 = __Pyx_PyObject_CallOneArg(__pyx_builtin_TypeError, __pyx_t_7); if (unlikely(!__pyx_t_11)) __PYX_ERR(1, 689, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_Raise(__pyx_t_11, 0, 0, 0); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __PYX_ERR(1, 689, __pyx_L1_error) - - /* "View.MemoryView":688 - * have_slices = True - * else: - * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< - * raise TypeError("Cannot index with type '%s'" % type(item)) - * - */ - } - - /* "View.MemoryView":691 - * raise TypeError("Cannot index with type '%s'" % type(item)) - * - * have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<< - * result.append(item) - * - */ - __pyx_t_10 = (__pyx_v_have_slices != 0); - if (!__pyx_t_10) { - } else { - __pyx_t_1 = __pyx_t_10; - goto __pyx_L11_bool_binop_done; - } - __pyx_t_10 = PySlice_Check(__pyx_v_item); - __pyx_t_2 = (__pyx_t_10 != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L11_bool_binop_done:; - __pyx_v_have_slices = __pyx_t_1; - - /* "View.MemoryView":692 - * - * have_slices = have_slices or isinstance(item, slice) - * result.append(item) # <<<<<<<<<<<<<< - * - * nslices = ndim - len(result) - */ - __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 692, __pyx_L1_error) - } - __pyx_L6:; - - /* "View.MemoryView":679 - * have_slices = False - * seen_ellipsis = False - * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< - * if item is Ellipsis: - * if not seen_ellipsis: - */ - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":694 - * result.append(item) - * - * nslices = ndim - len(result) # <<<<<<<<<<<<<< - * if nslices: - * result.extend([slice(None)] * nslices) - */ - __pyx_t_5 = PyList_GET_SIZE(__pyx_v_result); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(1, 694, __pyx_L1_error) - __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); - - /* "View.MemoryView":695 - * - * nslices = ndim - len(result) - * if nslices: # <<<<<<<<<<<<<< - * result.extend([slice(None)] * nslices) - * - */ - __pyx_t_1 = (__pyx_v_nslices != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":696 - * nslices = ndim - len(result) - * if nslices: - * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< - * - * return have_slices or nslices, tuple(result) - */ - __pyx_t_3 = PyList_New(1 * ((__pyx_v_nslices<0) ? 0:__pyx_v_nslices)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 696, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - { Py_ssize_t __pyx_temp; - for (__pyx_temp=0; __pyx_temp < __pyx_v_nslices; __pyx_temp++) { - __Pyx_INCREF(__pyx_slice__16); - __Pyx_GIVEREF(__pyx_slice__16); - PyList_SET_ITEM(__pyx_t_3, __pyx_temp, __pyx_slice__16); - } - } - __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_3); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 696, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":695 - * - * nslices = ndim - len(result) - * if nslices: # <<<<<<<<<<<<<< - * result.extend([slice(None)] * nslices) - * - */ - } - - /* "View.MemoryView":698 - * result.extend([slice(None)] * nslices) - * - * return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<< - * - * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): - */ - __Pyx_XDECREF(__pyx_r); - if (!__pyx_v_have_slices) { - } else { - __pyx_t_4 = __Pyx_PyBool_FromLong(__pyx_v_have_slices); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L14_bool_binop_done; - } - __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_nslices); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __pyx_t_4; - __pyx_t_4 = 0; - __pyx_L14_bool_binop_done:; - __pyx_t_4 = PyList_AsTuple(__pyx_v_result); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_11 = PyTuple_New(2); if (unlikely(!__pyx_t_11)) __PYX_ERR(1, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_11, 1, __pyx_t_4); - __pyx_t_3 = 0; - __pyx_t_4 = 0; - __pyx_r = ((PyObject*)__pyx_t_11); - __pyx_t_11 = 0; - goto __pyx_L0; - - /* "View.MemoryView":666 - * return isinstance(o, memoryview) - * - * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< - * """ - * Replace all ellipses with full slices and fill incomplete indices with - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_AddTraceback("View.MemoryView._unellipsify", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_tup); - __Pyx_XDECREF(__pyx_v_result); - __Pyx_XDECREF(__pyx_v_idx); - __Pyx_XDECREF(__pyx_v_item); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":700 - * return have_slices or nslices, tuple(result) - * - * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: - */ - -static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __pyx_v_ndim) { - Py_ssize_t __pyx_v_suboffset; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - Py_ssize_t *__pyx_t_1; - Py_ssize_t *__pyx_t_2; - Py_ssize_t *__pyx_t_3; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); - - /* "View.MemoryView":701 - * - * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): - * for suboffset in suboffsets[:ndim]: # <<<<<<<<<<<<<< - * if suboffset >= 0: - * raise ValueError("Indirect dimensions not supported") - */ - __pyx_t_2 = (__pyx_v_suboffsets + __pyx_v_ndim); - for (__pyx_t_3 = __pyx_v_suboffsets; __pyx_t_3 < __pyx_t_2; __pyx_t_3++) { - __pyx_t_1 = __pyx_t_3; - __pyx_v_suboffset = (__pyx_t_1[0]); - - /* "View.MemoryView":702 - * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: # <<<<<<<<<<<<<< - * raise ValueError("Indirect dimensions not supported") - * - */ - __pyx_t_4 = ((__pyx_v_suboffset >= 0) != 0); - if (unlikely(__pyx_t_4)) { - - /* "View.MemoryView":703 - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: - * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__17, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 703, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __PYX_ERR(1, 703, __pyx_L1_error) - - /* "View.MemoryView":702 - * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: # <<<<<<<<<<<<<< - * raise ValueError("Indirect dimensions not supported") - * - */ - } - } - - /* "View.MemoryView":700 - * return have_slices or nslices, tuple(result) - * - * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.assert_direct_dimensions", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":710 - * - * @cname('__pyx_memview_slice') - * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< - * cdef int new_ndim = 0, suboffset_dim = -1, dim - * cdef bint negative_step - */ - -static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *__pyx_v_memview, PyObject *__pyx_v_indices) { - int __pyx_v_new_ndim; - int __pyx_v_suboffset_dim; - int __pyx_v_dim; - __Pyx_memviewslice __pyx_v_src; - __Pyx_memviewslice __pyx_v_dst; - __Pyx_memviewslice *__pyx_v_p_src; - struct __pyx_memoryviewslice_obj *__pyx_v_memviewsliceobj = 0; - __Pyx_memviewslice *__pyx_v_p_dst; - int *__pyx_v_p_suboffset_dim; - Py_ssize_t __pyx_v_start; - Py_ssize_t __pyx_v_stop; - Py_ssize_t __pyx_v_step; - int __pyx_v_have_start; - int __pyx_v_have_stop; - int __pyx_v_have_step; - PyObject *__pyx_v_index = NULL; - struct __pyx_memoryview_obj *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - struct __pyx_memoryview_obj *__pyx_t_4; - char *__pyx_t_5; - int __pyx_t_6; - Py_ssize_t __pyx_t_7; - PyObject *(*__pyx_t_8)(PyObject *); - PyObject *__pyx_t_9 = NULL; - Py_ssize_t __pyx_t_10; - int __pyx_t_11; - Py_ssize_t __pyx_t_12; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("memview_slice", 0); - - /* "View.MemoryView":711 - * @cname('__pyx_memview_slice') - * cdef memoryview memview_slice(memoryview memview, object indices): - * cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<< - * cdef bint negative_step - * cdef __Pyx_memviewslice src, dst - */ - __pyx_v_new_ndim = 0; - __pyx_v_suboffset_dim = -1; - - /* "View.MemoryView":718 - * - * - * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< - * - * cdef _memoryviewslice memviewsliceobj - */ - (void)(memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst)))); - - /* "View.MemoryView":722 - * cdef _memoryviewslice memviewsliceobj - * - * assert memview.view.ndim > 0 # <<<<<<<<<<<<<< - * - * if isinstance(memview, _memoryviewslice): - */ - #ifndef CYTHON_WITHOUT_ASSERTIONS - if (unlikely(!Py_OptimizeFlag)) { - if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) { - PyErr_SetNone(PyExc_AssertionError); - __PYX_ERR(1, 722, __pyx_L1_error) - } - } - #endif - - /* "View.MemoryView":724 - * assert memview.view.ndim > 0 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * memviewsliceobj = memview - * p_src = &memviewsliceobj.from_slice - */ - __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":725 - * - * if isinstance(memview, _memoryviewslice): - * memviewsliceobj = memview # <<<<<<<<<<<<<< - * p_src = &memviewsliceobj.from_slice - * else: - */ - if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) __PYX_ERR(1, 725, __pyx_L1_error) - __pyx_t_3 = ((PyObject *)__pyx_v_memview); - __Pyx_INCREF(__pyx_t_3); - __pyx_v_memviewsliceobj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "View.MemoryView":726 - * if isinstance(memview, _memoryviewslice): - * memviewsliceobj = memview - * p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<< - * else: - * slice_copy(memview, &src) - */ - __pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice); - - /* "View.MemoryView":724 - * assert memview.view.ndim > 0 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * memviewsliceobj = memview - * p_src = &memviewsliceobj.from_slice - */ - goto __pyx_L3; - } - - /* "View.MemoryView":728 - * p_src = &memviewsliceobj.from_slice - * else: - * slice_copy(memview, &src) # <<<<<<<<<<<<<< - * p_src = &src - * - */ - /*else*/ { - __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); - - /* "View.MemoryView":729 - * else: - * slice_copy(memview, &src) - * p_src = &src # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_p_src = (&__pyx_v_src); - } - __pyx_L3:; - - /* "View.MemoryView":735 - * - * - * dst.memview = p_src.memview # <<<<<<<<<<<<<< - * dst.data = p_src.data - * - */ - __pyx_t_4 = __pyx_v_p_src->memview; - __pyx_v_dst.memview = __pyx_t_4; - - /* "View.MemoryView":736 - * - * dst.memview = p_src.memview - * dst.data = p_src.data # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_5 = __pyx_v_p_src->data; - __pyx_v_dst.data = __pyx_t_5; - - /* "View.MemoryView":741 - * - * - * cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<< - * cdef int *p_suboffset_dim = &suboffset_dim - * cdef Py_ssize_t start, stop, step - */ - __pyx_v_p_dst = (&__pyx_v_dst); - - /* "View.MemoryView":742 - * - * cdef __Pyx_memviewslice *p_dst = &dst - * cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<< - * cdef Py_ssize_t start, stop, step - * cdef bint have_start, have_stop, have_step - */ - __pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim); - - /* "View.MemoryView":746 - * cdef bint have_start, have_stop, have_step - * - * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< - * if PyIndex_Check(index): - * slice_memviewslice( - */ - __pyx_t_6 = 0; - if (likely(PyList_CheckExact(__pyx_v_indices)) || PyTuple_CheckExact(__pyx_v_indices)) { - __pyx_t_3 = __pyx_v_indices; __Pyx_INCREF(__pyx_t_3); __pyx_t_7 = 0; - __pyx_t_8 = NULL; - } else { - __pyx_t_7 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 746, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 746, __pyx_L1_error) - } - for (;;) { - if (likely(!__pyx_t_8)) { - if (likely(PyList_CheckExact(__pyx_t_3))) { - if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_9 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) __PYX_ERR(1, 746, __pyx_L1_error) - #else - __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 746, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - #endif - } else { - if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) __PYX_ERR(1, 746, __pyx_L1_error) - #else - __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 746, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - #endif - } - } else { - __pyx_t_9 = __pyx_t_8(__pyx_t_3); - if (unlikely(!__pyx_t_9)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(1, 746, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_9); - } - __Pyx_XDECREF_SET(__pyx_v_index, __pyx_t_9); - __pyx_t_9 = 0; - __pyx_v_dim = __pyx_t_6; - __pyx_t_6 = (__pyx_t_6 + 1); - - /* "View.MemoryView":747 - * - * for dim, index in enumerate(indices): - * if PyIndex_Check(index): # <<<<<<<<<<<<<< - * slice_memviewslice( - * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], - */ - __pyx_t_2 = (PyIndex_Check(__pyx_v_index) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":751 - * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], - * dim, new_ndim, p_suboffset_dim, - * index, 0, 0, # start, stop, step # <<<<<<<<<<<<<< - * 0, 0, 0, # have_{start,stop,step} - * False) - */ - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 751, __pyx_L1_error) - - /* "View.MemoryView":748 - * for dim, index in enumerate(indices): - * if PyIndex_Check(index): - * slice_memviewslice( # <<<<<<<<<<<<<< - * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], - * dim, new_ndim, p_suboffset_dim, - */ - __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(1, 748, __pyx_L1_error) - - /* "View.MemoryView":747 - * - * for dim, index in enumerate(indices): - * if PyIndex_Check(index): # <<<<<<<<<<<<<< - * slice_memviewslice( - * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], - */ - goto __pyx_L6; - } - - /* "View.MemoryView":754 - * 0, 0, 0, # have_{start,stop,step} - * False) - * elif index is None: # <<<<<<<<<<<<<< - * p_dst.shape[new_ndim] = 1 - * p_dst.strides[new_ndim] = 0 - */ - __pyx_t_2 = (__pyx_v_index == Py_None); - __pyx_t_1 = (__pyx_t_2 != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":755 - * False) - * elif index is None: - * p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<< - * p_dst.strides[new_ndim] = 0 - * p_dst.suboffsets[new_ndim] = -1 - */ - (__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1; - - /* "View.MemoryView":756 - * elif index is None: - * p_dst.shape[new_ndim] = 1 - * p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<< - * p_dst.suboffsets[new_ndim] = -1 - * new_ndim += 1 - */ - (__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0; - - /* "View.MemoryView":757 - * p_dst.shape[new_ndim] = 1 - * p_dst.strides[new_ndim] = 0 - * p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<< - * new_ndim += 1 - * else: - */ - (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1L; - - /* "View.MemoryView":758 - * p_dst.strides[new_ndim] = 0 - * p_dst.suboffsets[new_ndim] = -1 - * new_ndim += 1 # <<<<<<<<<<<<<< - * else: - * start = index.start or 0 - */ - __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); - - /* "View.MemoryView":754 - * 0, 0, 0, # have_{start,stop,step} - * False) - * elif index is None: # <<<<<<<<<<<<<< - * p_dst.shape[new_ndim] = 1 - * p_dst.strides[new_ndim] = 0 - */ - goto __pyx_L6; - } - - /* "View.MemoryView":760 - * new_ndim += 1 - * else: - * start = index.start or 0 # <<<<<<<<<<<<<< - * stop = index.stop or 0 - * step = index.step or 0 - */ - /*else*/ { - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 760, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 760, __pyx_L1_error) - if (!__pyx_t_1) { - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } else { - __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 760, __pyx_L1_error) - __pyx_t_10 = __pyx_t_12; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - goto __pyx_L7_bool_binop_done; - } - __pyx_t_10 = 0; - __pyx_L7_bool_binop_done:; - __pyx_v_start = __pyx_t_10; - - /* "View.MemoryView":761 - * else: - * start = index.start or 0 - * stop = index.stop or 0 # <<<<<<<<<<<<<< - * step = index.step or 0 - * - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 761, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 761, __pyx_L1_error) - if (!__pyx_t_1) { - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } else { - __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 761, __pyx_L1_error) - __pyx_t_10 = __pyx_t_12; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - goto __pyx_L9_bool_binop_done; - } - __pyx_t_10 = 0; - __pyx_L9_bool_binop_done:; - __pyx_v_stop = __pyx_t_10; - - /* "View.MemoryView":762 - * start = index.start or 0 - * stop = index.stop or 0 - * step = index.step or 0 # <<<<<<<<<<<<<< - * - * have_start = index.start is not None - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 762, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 762, __pyx_L1_error) - if (!__pyx_t_1) { - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } else { - __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 762, __pyx_L1_error) - __pyx_t_10 = __pyx_t_12; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - goto __pyx_L11_bool_binop_done; - } - __pyx_t_10 = 0; - __pyx_L11_bool_binop_done:; - __pyx_v_step = __pyx_t_10; - - /* "View.MemoryView":764 - * step = index.step or 0 - * - * have_start = index.start is not None # <<<<<<<<<<<<<< - * have_stop = index.stop is not None - * have_step = index.step is not None - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 764, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = (__pyx_t_9 != Py_None); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_v_have_start = __pyx_t_1; - - /* "View.MemoryView":765 - * - * have_start = index.start is not None - * have_stop = index.stop is not None # <<<<<<<<<<<<<< - * have_step = index.step is not None - * - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 765, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = (__pyx_t_9 != Py_None); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_v_have_stop = __pyx_t_1; - - /* "View.MemoryView":766 - * have_start = index.start is not None - * have_stop = index.stop is not None - * have_step = index.step is not None # <<<<<<<<<<<<<< - * - * slice_memviewslice( - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 766, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = (__pyx_t_9 != Py_None); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_v_have_step = __pyx_t_1; - - /* "View.MemoryView":768 - * have_step = index.step is not None - * - * slice_memviewslice( # <<<<<<<<<<<<<< - * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], - * dim, new_ndim, p_suboffset_dim, - */ - __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(1, 768, __pyx_L1_error) - - /* "View.MemoryView":774 - * have_start, have_stop, have_step, - * True) - * new_ndim += 1 # <<<<<<<<<<<<<< - * - * if isinstance(memview, _memoryviewslice): - */ - __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); - } - __pyx_L6:; - - /* "View.MemoryView":746 - * cdef bint have_start, have_stop, have_step - * - * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< - * if PyIndex_Check(index): - * slice_memviewslice( - */ - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":776 - * new_ndim += 1 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * return memoryview_fromslice(dst, new_ndim, - * memviewsliceobj.to_object_func, - */ - __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":777 - * - * if isinstance(memview, _memoryviewslice): - * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< - * memviewsliceobj.to_object_func, - * memviewsliceobj.to_dtype_func, - */ - __Pyx_XDECREF(((PyObject *)__pyx_r)); - - /* "View.MemoryView":778 - * if isinstance(memview, _memoryviewslice): - * return memoryview_fromslice(dst, new_ndim, - * memviewsliceobj.to_object_func, # <<<<<<<<<<<<<< - * memviewsliceobj.to_dtype_func, - * memview.dtype_is_object) - */ - if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); __PYX_ERR(1, 778, __pyx_L1_error) } - - /* "View.MemoryView":779 - * return memoryview_fromslice(dst, new_ndim, - * memviewsliceobj.to_object_func, - * memviewsliceobj.to_dtype_func, # <<<<<<<<<<<<<< - * memview.dtype_is_object) - * else: - */ - if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); __PYX_ERR(1, 779, __pyx_L1_error) } - - /* "View.MemoryView":777 - * - * if isinstance(memview, _memoryviewslice): - * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< - * memviewsliceobj.to_object_func, - * memviewsliceobj.to_dtype_func, - */ - __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 777, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) __PYX_ERR(1, 777, __pyx_L1_error) - __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "View.MemoryView":776 - * new_ndim += 1 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * return memoryview_fromslice(dst, new_ndim, - * memviewsliceobj.to_object_func, - */ - } - - /* "View.MemoryView":782 - * memview.dtype_is_object) - * else: - * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< - * memview.dtype_is_object) - * - */ - /*else*/ { - __Pyx_XDECREF(((PyObject *)__pyx_r)); - - /* "View.MemoryView":783 - * else: - * return memoryview_fromslice(dst, new_ndim, NULL, NULL, - * memview.dtype_is_object) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 782, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - - /* "View.MemoryView":782 - * memview.dtype_is_object) - * else: - * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< - * memview.dtype_is_object) - * - */ - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) __PYX_ERR(1, 782, __pyx_L1_error) - __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); - __pyx_t_3 = 0; - goto __pyx_L0; - } - - /* "View.MemoryView":710 - * - * @cname('__pyx_memview_slice') - * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< - * cdef int new_ndim = 0, suboffset_dim = -1, dim - * cdef bint negative_step - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_AddTraceback("View.MemoryView.memview_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_memviewsliceobj); - __Pyx_XDECREF(__pyx_v_index); - __Pyx_XGIVEREF((PyObject *)__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":807 - * - * @cname('__pyx_memoryview_slice_memviewslice') - * cdef int slice_memviewslice( # <<<<<<<<<<<<<< - * __Pyx_memviewslice *dst, - * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, - */ - -static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, Py_ssize_t __pyx_v_shape, Py_ssize_t __pyx_v_stride, Py_ssize_t __pyx_v_suboffset, int __pyx_v_dim, int __pyx_v_new_ndim, int *__pyx_v_suboffset_dim, Py_ssize_t __pyx_v_start, Py_ssize_t __pyx_v_stop, Py_ssize_t __pyx_v_step, int __pyx_v_have_start, int __pyx_v_have_stop, int __pyx_v_have_step, int __pyx_v_is_slice) { - Py_ssize_t __pyx_v_new_shape; - int __pyx_v_negative_step; - int __pyx_r; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - - /* "View.MemoryView":827 - * cdef bint negative_step - * - * if not is_slice: # <<<<<<<<<<<<<< - * - * if start < 0: - */ - __pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":829 - * if not is_slice: - * - * if start < 0: # <<<<<<<<<<<<<< - * start += shape - * if not 0 <= start < shape: - */ - __pyx_t_1 = ((__pyx_v_start < 0) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":830 - * - * if start < 0: - * start += shape # <<<<<<<<<<<<<< - * if not 0 <= start < shape: - * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) - */ - __pyx_v_start = (__pyx_v_start + __pyx_v_shape); - - /* "View.MemoryView":829 - * if not is_slice: - * - * if start < 0: # <<<<<<<<<<<<<< - * start += shape - * if not 0 <= start < shape: - */ - } - - /* "View.MemoryView":831 - * if start < 0: - * start += shape - * if not 0 <= start < shape: # <<<<<<<<<<<<<< - * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) - * else: - */ - __pyx_t_1 = (0 <= __pyx_v_start); - if (__pyx_t_1) { - __pyx_t_1 = (__pyx_v_start < __pyx_v_shape); - } - __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":832 - * start += shape - * if not 0 <= start < shape: - * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) # <<<<<<<<<<<<<< - * else: - * - */ - __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, ((char *)"Index out of bounds (axis %d)"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(1, 832, __pyx_L1_error) - - /* "View.MemoryView":831 - * if start < 0: - * start += shape - * if not 0 <= start < shape: # <<<<<<<<<<<<<< - * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) - * else: - */ - } - - /* "View.MemoryView":827 - * cdef bint negative_step - * - * if not is_slice: # <<<<<<<<<<<<<< - * - * if start < 0: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":835 - * else: - * - * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< - * - * if have_step and step == 0: - */ - /*else*/ { - __pyx_t_1 = ((__pyx_v_have_step != 0) != 0); - if (__pyx_t_1) { - } else { - __pyx_t_2 = __pyx_t_1; - goto __pyx_L6_bool_binop_done; - } - __pyx_t_1 = ((__pyx_v_step < 0) != 0); - __pyx_t_2 = __pyx_t_1; - __pyx_L6_bool_binop_done:; - __pyx_v_negative_step = __pyx_t_2; - - /* "View.MemoryView":837 - * negative_step = have_step != 0 and step < 0 - * - * if have_step and step == 0: # <<<<<<<<<<<<<< - * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) - * - */ - __pyx_t_1 = (__pyx_v_have_step != 0); - if (__pyx_t_1) { - } else { - __pyx_t_2 = __pyx_t_1; - goto __pyx_L9_bool_binop_done; - } - __pyx_t_1 = ((__pyx_v_step == 0) != 0); - __pyx_t_2 = __pyx_t_1; - __pyx_L9_bool_binop_done:; - if (__pyx_t_2) { - - /* "View.MemoryView":838 - * - * if have_step and step == 0: - * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, ((char *)"Step may not be zero (axis %d)"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(1, 838, __pyx_L1_error) - - /* "View.MemoryView":837 - * negative_step = have_step != 0 and step < 0 - * - * if have_step and step == 0: # <<<<<<<<<<<<<< - * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) - * - */ - } - - /* "View.MemoryView":841 - * - * - * if have_start: # <<<<<<<<<<<<<< - * if start < 0: - * start += shape - */ - __pyx_t_2 = (__pyx_v_have_start != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":842 - * - * if have_start: - * if start < 0: # <<<<<<<<<<<<<< - * start += shape - * if start < 0: - */ - __pyx_t_2 = ((__pyx_v_start < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":843 - * if have_start: - * if start < 0: - * start += shape # <<<<<<<<<<<<<< - * if start < 0: - * start = 0 - */ - __pyx_v_start = (__pyx_v_start + __pyx_v_shape); - - /* "View.MemoryView":844 - * if start < 0: - * start += shape - * if start < 0: # <<<<<<<<<<<<<< - * start = 0 - * elif start >= shape: - */ - __pyx_t_2 = ((__pyx_v_start < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":845 - * start += shape - * if start < 0: - * start = 0 # <<<<<<<<<<<<<< - * elif start >= shape: - * if negative_step: - */ - __pyx_v_start = 0; - - /* "View.MemoryView":844 - * if start < 0: - * start += shape - * if start < 0: # <<<<<<<<<<<<<< - * start = 0 - * elif start >= shape: - */ - } - - /* "View.MemoryView":842 - * - * if have_start: - * if start < 0: # <<<<<<<<<<<<<< - * start += shape - * if start < 0: - */ - goto __pyx_L12; - } - - /* "View.MemoryView":846 - * if start < 0: - * start = 0 - * elif start >= shape: # <<<<<<<<<<<<<< - * if negative_step: - * start = shape - 1 - */ - __pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":847 - * start = 0 - * elif start >= shape: - * if negative_step: # <<<<<<<<<<<<<< - * start = shape - 1 - * else: - */ - __pyx_t_2 = (__pyx_v_negative_step != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":848 - * elif start >= shape: - * if negative_step: - * start = shape - 1 # <<<<<<<<<<<<<< - * else: - * start = shape - */ - __pyx_v_start = (__pyx_v_shape - 1); - - /* "View.MemoryView":847 - * start = 0 - * elif start >= shape: - * if negative_step: # <<<<<<<<<<<<<< - * start = shape - 1 - * else: - */ - goto __pyx_L14; - } - - /* "View.MemoryView":850 - * start = shape - 1 - * else: - * start = shape # <<<<<<<<<<<<<< - * else: - * if negative_step: - */ - /*else*/ { - __pyx_v_start = __pyx_v_shape; - } - __pyx_L14:; - - /* "View.MemoryView":846 - * if start < 0: - * start = 0 - * elif start >= shape: # <<<<<<<<<<<<<< - * if negative_step: - * start = shape - 1 - */ - } - __pyx_L12:; - - /* "View.MemoryView":841 - * - * - * if have_start: # <<<<<<<<<<<<<< - * if start < 0: - * start += shape - */ - goto __pyx_L11; - } - - /* "View.MemoryView":852 - * start = shape - * else: - * if negative_step: # <<<<<<<<<<<<<< - * start = shape - 1 - * else: - */ - /*else*/ { - __pyx_t_2 = (__pyx_v_negative_step != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":853 - * else: - * if negative_step: - * start = shape - 1 # <<<<<<<<<<<<<< - * else: - * start = 0 - */ - __pyx_v_start = (__pyx_v_shape - 1); - - /* "View.MemoryView":852 - * start = shape - * else: - * if negative_step: # <<<<<<<<<<<<<< - * start = shape - 1 - * else: - */ - goto __pyx_L15; - } - - /* "View.MemoryView":855 - * start = shape - 1 - * else: - * start = 0 # <<<<<<<<<<<<<< - * - * if have_stop: - */ - /*else*/ { - __pyx_v_start = 0; - } - __pyx_L15:; - } - __pyx_L11:; - - /* "View.MemoryView":857 - * start = 0 - * - * if have_stop: # <<<<<<<<<<<<<< - * if stop < 0: - * stop += shape - */ - __pyx_t_2 = (__pyx_v_have_stop != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":858 - * - * if have_stop: - * if stop < 0: # <<<<<<<<<<<<<< - * stop += shape - * if stop < 0: - */ - __pyx_t_2 = ((__pyx_v_stop < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":859 - * if have_stop: - * if stop < 0: - * stop += shape # <<<<<<<<<<<<<< - * if stop < 0: - * stop = 0 - */ - __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); - - /* "View.MemoryView":860 - * if stop < 0: - * stop += shape - * if stop < 0: # <<<<<<<<<<<<<< - * stop = 0 - * elif stop > shape: - */ - __pyx_t_2 = ((__pyx_v_stop < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":861 - * stop += shape - * if stop < 0: - * stop = 0 # <<<<<<<<<<<<<< - * elif stop > shape: - * stop = shape - */ - __pyx_v_stop = 0; - - /* "View.MemoryView":860 - * if stop < 0: - * stop += shape - * if stop < 0: # <<<<<<<<<<<<<< - * stop = 0 - * elif stop > shape: - */ - } - - /* "View.MemoryView":858 - * - * if have_stop: - * if stop < 0: # <<<<<<<<<<<<<< - * stop += shape - * if stop < 0: - */ - goto __pyx_L17; - } - - /* "View.MemoryView":862 - * if stop < 0: - * stop = 0 - * elif stop > shape: # <<<<<<<<<<<<<< - * stop = shape - * else: - */ - __pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":863 - * stop = 0 - * elif stop > shape: - * stop = shape # <<<<<<<<<<<<<< - * else: - * if negative_step: - */ - __pyx_v_stop = __pyx_v_shape; - - /* "View.MemoryView":862 - * if stop < 0: - * stop = 0 - * elif stop > shape: # <<<<<<<<<<<<<< - * stop = shape - * else: - */ - } - __pyx_L17:; - - /* "View.MemoryView":857 - * start = 0 - * - * if have_stop: # <<<<<<<<<<<<<< - * if stop < 0: - * stop += shape - */ - goto __pyx_L16; - } - - /* "View.MemoryView":865 - * stop = shape - * else: - * if negative_step: # <<<<<<<<<<<<<< - * stop = -1 - * else: - */ - /*else*/ { - __pyx_t_2 = (__pyx_v_negative_step != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":866 - * else: - * if negative_step: - * stop = -1 # <<<<<<<<<<<<<< - * else: - * stop = shape - */ - __pyx_v_stop = -1L; - - /* "View.MemoryView":865 - * stop = shape - * else: - * if negative_step: # <<<<<<<<<<<<<< - * stop = -1 - * else: - */ - goto __pyx_L19; - } - - /* "View.MemoryView":868 - * stop = -1 - * else: - * stop = shape # <<<<<<<<<<<<<< - * - * if not have_step: - */ - /*else*/ { - __pyx_v_stop = __pyx_v_shape; - } - __pyx_L19:; - } - __pyx_L16:; - - /* "View.MemoryView":870 - * stop = shape - * - * if not have_step: # <<<<<<<<<<<<<< - * step = 1 - * - */ - __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":871 - * - * if not have_step: - * step = 1 # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_step = 1; - - /* "View.MemoryView":870 - * stop = shape - * - * if not have_step: # <<<<<<<<<<<<<< - * step = 1 - * - */ - } - - /* "View.MemoryView":875 - * - * with cython.cdivision(True): - * new_shape = (stop - start) // step # <<<<<<<<<<<<<< - * - * if (stop - start) - step * new_shape: - */ - __pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step); - - /* "View.MemoryView":877 - * new_shape = (stop - start) // step - * - * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< - * new_shape += 1 - * - */ - __pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":878 - * - * if (stop - start) - step * new_shape: - * new_shape += 1 # <<<<<<<<<<<<<< - * - * if new_shape < 0: - */ - __pyx_v_new_shape = (__pyx_v_new_shape + 1); - - /* "View.MemoryView":877 - * new_shape = (stop - start) // step - * - * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< - * new_shape += 1 - * - */ - } - - /* "View.MemoryView":880 - * new_shape += 1 - * - * if new_shape < 0: # <<<<<<<<<<<<<< - * new_shape = 0 - * - */ - __pyx_t_2 = ((__pyx_v_new_shape < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":881 - * - * if new_shape < 0: - * new_shape = 0 # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_new_shape = 0; - - /* "View.MemoryView":880 - * new_shape += 1 - * - * if new_shape < 0: # <<<<<<<<<<<<<< - * new_shape = 0 - * - */ - } - - /* "View.MemoryView":884 - * - * - * dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<< - * dst.shape[new_ndim] = new_shape - * dst.suboffsets[new_ndim] = suboffset - */ - (__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step); - - /* "View.MemoryView":885 - * - * dst.strides[new_ndim] = stride * step - * dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<< - * dst.suboffsets[new_ndim] = suboffset - * - */ - (__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape; - - /* "View.MemoryView":886 - * dst.strides[new_ndim] = stride * step - * dst.shape[new_ndim] = new_shape - * dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<< - * - * - */ - (__pyx_v_dst->suboffsets[__pyx_v_new_ndim]) = __pyx_v_suboffset; - } - __pyx_L3:; - - /* "View.MemoryView":889 - * - * - * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< - * dst.data += start * stride - * else: - */ - __pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":890 - * - * if suboffset_dim[0] < 0: - * dst.data += start * stride # <<<<<<<<<<<<<< - * else: - * dst.suboffsets[suboffset_dim[0]] += start * stride - */ - __pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride)); - - /* "View.MemoryView":889 - * - * - * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< - * dst.data += start * stride - * else: - */ - goto __pyx_L23; - } - - /* "View.MemoryView":892 - * dst.data += start * stride - * else: - * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< - * - * if suboffset >= 0: - */ - /*else*/ { - __pyx_t_3 = (__pyx_v_suboffset_dim[0]); - (__pyx_v_dst->suboffsets[__pyx_t_3]) = ((__pyx_v_dst->suboffsets[__pyx_t_3]) + (__pyx_v_start * __pyx_v_stride)); - } - __pyx_L23:; - - /* "View.MemoryView":894 - * dst.suboffsets[suboffset_dim[0]] += start * stride - * - * if suboffset >= 0: # <<<<<<<<<<<<<< - * if not is_slice: - * if new_ndim == 0: - */ - __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":895 - * - * if suboffset >= 0: - * if not is_slice: # <<<<<<<<<<<<<< - * if new_ndim == 0: - * dst.data = ( dst.data)[0] + suboffset - */ - __pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":896 - * if suboffset >= 0: - * if not is_slice: - * if new_ndim == 0: # <<<<<<<<<<<<<< - * dst.data = ( dst.data)[0] + suboffset - * else: - */ - __pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":897 - * if not is_slice: - * if new_ndim == 0: - * dst.data = ( dst.data)[0] + suboffset # <<<<<<<<<<<<<< - * else: - * _err_dim(IndexError, "All dimensions preceding dimension %d " - */ - __pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset); - - /* "View.MemoryView":896 - * if suboffset >= 0: - * if not is_slice: - * if new_ndim == 0: # <<<<<<<<<<<<<< - * dst.data = ( dst.data)[0] + suboffset - * else: - */ - goto __pyx_L26; - } - - /* "View.MemoryView":899 - * dst.data = ( dst.data)[0] + suboffset - * else: - * _err_dim(IndexError, "All dimensions preceding dimension %d " # <<<<<<<<<<<<<< - * "must be indexed and not sliced", dim) - * else: - */ - /*else*/ { - - /* "View.MemoryView":900 - * else: - * _err_dim(IndexError, "All dimensions preceding dimension %d " - * "must be indexed and not sliced", dim) # <<<<<<<<<<<<<< - * else: - * suboffset_dim[0] = new_ndim - */ - __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, ((char *)"All dimensions preceding dimension %d must be indexed and not sliced"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(1, 899, __pyx_L1_error) - } - __pyx_L26:; - - /* "View.MemoryView":895 - * - * if suboffset >= 0: - * if not is_slice: # <<<<<<<<<<<<<< - * if new_ndim == 0: - * dst.data = ( dst.data)[0] + suboffset - */ - goto __pyx_L25; - } - - /* "View.MemoryView":902 - * "must be indexed and not sliced", dim) - * else: - * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< - * - * return 0 - */ - /*else*/ { - (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; - } - __pyx_L25:; - - /* "View.MemoryView":894 - * dst.suboffsets[suboffset_dim[0]] += start * stride - * - * if suboffset >= 0: # <<<<<<<<<<<<<< - * if not is_slice: - * if new_ndim == 0: - */ - } - - /* "View.MemoryView":904 - * suboffset_dim[0] = new_ndim - * - * return 0 # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "View.MemoryView":807 - * - * @cname('__pyx_memoryview_slice_memviewslice') - * cdef int slice_memviewslice( # <<<<<<<<<<<<<< - * __Pyx_memviewslice *dst, - * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, - */ - - /* function exit code */ - __pyx_L1_error:; - { - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - } - __pyx_r = -1; - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":910 - * - * @cname('__pyx_pybuffer_index') - * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< - * Py_ssize_t dim) except NULL: - * cdef Py_ssize_t shape, stride, suboffset = -1 - */ - -static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, Py_ssize_t __pyx_v_index, Py_ssize_t __pyx_v_dim) { - Py_ssize_t __pyx_v_shape; - Py_ssize_t __pyx_v_stride; - Py_ssize_t __pyx_v_suboffset; - Py_ssize_t __pyx_v_itemsize; - char *__pyx_v_resultp; - char *__pyx_r; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("pybuffer_index", 0); - - /* "View.MemoryView":912 - * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, - * Py_ssize_t dim) except NULL: - * cdef Py_ssize_t shape, stride, suboffset = -1 # <<<<<<<<<<<<<< - * cdef Py_ssize_t itemsize = view.itemsize - * cdef char *resultp - */ - __pyx_v_suboffset = -1L; - - /* "View.MemoryView":913 - * Py_ssize_t dim) except NULL: - * cdef Py_ssize_t shape, stride, suboffset = -1 - * cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<< - * cdef char *resultp - * - */ - __pyx_t_1 = __pyx_v_view->itemsize; - __pyx_v_itemsize = __pyx_t_1; - - /* "View.MemoryView":916 - * cdef char *resultp - * - * if view.ndim == 0: # <<<<<<<<<<<<<< - * shape = view.len / itemsize - * stride = itemsize - */ - __pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":917 - * - * if view.ndim == 0: - * shape = view.len / itemsize # <<<<<<<<<<<<<< - * stride = itemsize - * else: - */ - if (unlikely(__pyx_v_itemsize == 0)) { - PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); - __PYX_ERR(1, 917, __pyx_L1_error) - } - else if (sizeof(Py_ssize_t) == sizeof(long) && (!(((Py_ssize_t)-1) > 0)) && unlikely(__pyx_v_itemsize == (Py_ssize_t)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { - PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); - __PYX_ERR(1, 917, __pyx_L1_error) - } - __pyx_v_shape = __Pyx_div_Py_ssize_t(__pyx_v_view->len, __pyx_v_itemsize); - - /* "View.MemoryView":918 - * if view.ndim == 0: - * shape = view.len / itemsize - * stride = itemsize # <<<<<<<<<<<<<< - * else: - * shape = view.shape[dim] - */ - __pyx_v_stride = __pyx_v_itemsize; - - /* "View.MemoryView":916 - * cdef char *resultp - * - * if view.ndim == 0: # <<<<<<<<<<<<<< - * shape = view.len / itemsize - * stride = itemsize - */ - goto __pyx_L3; - } - - /* "View.MemoryView":920 - * stride = itemsize - * else: - * shape = view.shape[dim] # <<<<<<<<<<<<<< - * stride = view.strides[dim] - * if view.suboffsets != NULL: - */ - /*else*/ { - __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); - - /* "View.MemoryView":921 - * else: - * shape = view.shape[dim] - * stride = view.strides[dim] # <<<<<<<<<<<<<< - * if view.suboffsets != NULL: - * suboffset = view.suboffsets[dim] - */ - __pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]); - - /* "View.MemoryView":922 - * shape = view.shape[dim] - * stride = view.strides[dim] - * if view.suboffsets != NULL: # <<<<<<<<<<<<<< - * suboffset = view.suboffsets[dim] - * - */ - __pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":923 - * stride = view.strides[dim] - * if view.suboffsets != NULL: - * suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<< - * - * if index < 0: - */ - __pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]); - - /* "View.MemoryView":922 - * shape = view.shape[dim] - * stride = view.strides[dim] - * if view.suboffsets != NULL: # <<<<<<<<<<<<<< - * suboffset = view.suboffsets[dim] - * - */ - } - } - __pyx_L3:; - - /* "View.MemoryView":925 - * suboffset = view.suboffsets[dim] - * - * if index < 0: # <<<<<<<<<<<<<< - * index += view.shape[dim] - * if index < 0: - */ - __pyx_t_2 = ((__pyx_v_index < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":926 - * - * if index < 0: - * index += view.shape[dim] # <<<<<<<<<<<<<< - * if index < 0: - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - */ - __pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim])); - - /* "View.MemoryView":927 - * if index < 0: - * index += view.shape[dim] - * if index < 0: # <<<<<<<<<<<<<< - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - */ - __pyx_t_2 = ((__pyx_v_index < 0) != 0); - if (unlikely(__pyx_t_2)) { - - /* "View.MemoryView":928 - * index += view.shape[dim] - * if index < 0: - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< - * - * if index >= shape: - */ - __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 928, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 928, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_IndexError, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 928, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 928, __pyx_L1_error) - - /* "View.MemoryView":927 - * if index < 0: - * index += view.shape[dim] - * if index < 0: # <<<<<<<<<<<<<< - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - */ - } - - /* "View.MemoryView":925 - * suboffset = view.suboffsets[dim] - * - * if index < 0: # <<<<<<<<<<<<<< - * index += view.shape[dim] - * if index < 0: - */ - } - - /* "View.MemoryView":930 - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - * if index >= shape: # <<<<<<<<<<<<<< - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - */ - __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); - if (unlikely(__pyx_t_2)) { - - /* "View.MemoryView":931 - * - * if index >= shape: - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< - * - * resultp = bufp + index * stride - */ - __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 931, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 931, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_IndexError, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 931, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 931, __pyx_L1_error) - - /* "View.MemoryView":930 - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - * if index >= shape: # <<<<<<<<<<<<<< - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - */ - } - - /* "View.MemoryView":933 - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - * resultp = bufp + index * stride # <<<<<<<<<<<<<< - * if suboffset >= 0: - * resultp = ( resultp)[0] + suboffset - */ - __pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride)); - - /* "View.MemoryView":934 - * - * resultp = bufp + index * stride - * if suboffset >= 0: # <<<<<<<<<<<<<< - * resultp = ( resultp)[0] + suboffset - * - */ - __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":935 - * resultp = bufp + index * stride - * if suboffset >= 0: - * resultp = ( resultp)[0] + suboffset # <<<<<<<<<<<<<< - * - * return resultp - */ - __pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset); - - /* "View.MemoryView":934 - * - * resultp = bufp + index * stride - * if suboffset >= 0: # <<<<<<<<<<<<<< - * resultp = ( resultp)[0] + suboffset - * - */ - } - - /* "View.MemoryView":937 - * resultp = ( resultp)[0] + suboffset - * - * return resultp # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = __pyx_v_resultp; - goto __pyx_L0; - - /* "View.MemoryView":910 - * - * @cname('__pyx_pybuffer_index') - * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< - * Py_ssize_t dim) except NULL: - * cdef Py_ssize_t shape, stride, suboffset = -1 - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("View.MemoryView.pybuffer_index", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":943 - * - * @cname('__pyx_memslice_transpose') - * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< - * cdef int ndim = memslice.memview.view.ndim - * - */ - -static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { - int __pyx_v_ndim; - Py_ssize_t *__pyx_v_shape; - Py_ssize_t *__pyx_v_strides; - int __pyx_v_i; - int __pyx_v_j; - int __pyx_r; - int __pyx_t_1; - Py_ssize_t *__pyx_t_2; - long __pyx_t_3; - long __pyx_t_4; - Py_ssize_t __pyx_t_5; - Py_ssize_t __pyx_t_6; - int __pyx_t_7; - int __pyx_t_8; - int __pyx_t_9; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - - /* "View.MemoryView":944 - * @cname('__pyx_memslice_transpose') - * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: - * cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<< - * - * cdef Py_ssize_t *shape = memslice.shape - */ - __pyx_t_1 = __pyx_v_memslice->memview->view.ndim; - __pyx_v_ndim = __pyx_t_1; - - /* "View.MemoryView":946 - * cdef int ndim = memslice.memview.view.ndim - * - * cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<< - * cdef Py_ssize_t *strides = memslice.strides - * - */ - __pyx_t_2 = __pyx_v_memslice->shape; - __pyx_v_shape = __pyx_t_2; - - /* "View.MemoryView":947 - * - * cdef Py_ssize_t *shape = memslice.shape - * cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_2 = __pyx_v_memslice->strides; - __pyx_v_strides = __pyx_t_2; - - /* "View.MemoryView":951 - * - * cdef int i, j - * for i in range(ndim / 2): # <<<<<<<<<<<<<< - * j = ndim - 1 - i - * strides[i], strides[j] = strides[j], strides[i] - */ - __pyx_t_3 = __Pyx_div_long(__pyx_v_ndim, 2); - __pyx_t_4 = __pyx_t_3; - for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_4; __pyx_t_1+=1) { - __pyx_v_i = __pyx_t_1; - - /* "View.MemoryView":952 - * cdef int i, j - * for i in range(ndim / 2): - * j = ndim - 1 - i # <<<<<<<<<<<<<< - * strides[i], strides[j] = strides[j], strides[i] - * shape[i], shape[j] = shape[j], shape[i] - */ - __pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i); - - /* "View.MemoryView":953 - * for i in range(ndim / 2): - * j = ndim - 1 - i - * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< - * shape[i], shape[j] = shape[j], shape[i] - * - */ - __pyx_t_5 = (__pyx_v_strides[__pyx_v_j]); - __pyx_t_6 = (__pyx_v_strides[__pyx_v_i]); - (__pyx_v_strides[__pyx_v_i]) = __pyx_t_5; - (__pyx_v_strides[__pyx_v_j]) = __pyx_t_6; - - /* "View.MemoryView":954 - * j = ndim - 1 - i - * strides[i], strides[j] = strides[j], strides[i] - * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< - * - * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: - */ - __pyx_t_6 = (__pyx_v_shape[__pyx_v_j]); - __pyx_t_5 = (__pyx_v_shape[__pyx_v_i]); - (__pyx_v_shape[__pyx_v_i]) = __pyx_t_6; - (__pyx_v_shape[__pyx_v_j]) = __pyx_t_5; - - /* "View.MemoryView":956 - * shape[i], shape[j] = shape[j], shape[i] - * - * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< - * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") - * - */ - __pyx_t_8 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); - if (!__pyx_t_8) { - } else { - __pyx_t_7 = __pyx_t_8; - goto __pyx_L6_bool_binop_done; - } - __pyx_t_8 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); - __pyx_t_7 = __pyx_t_8; - __pyx_L6_bool_binop_done:; - if (__pyx_t_7) { - - /* "View.MemoryView":957 - * - * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: - * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< - * - * return 1 - */ - __pyx_t_9 = __pyx_memoryview_err(__pyx_builtin_ValueError, ((char *)"Cannot transpose memoryview with indirect dimensions")); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 957, __pyx_L1_error) - - /* "View.MemoryView":956 - * shape[i], shape[j] = shape[j], shape[i] - * - * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< - * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") - * - */ - } - } - - /* "View.MemoryView":959 - * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") - * - * return 1 # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = 1; - goto __pyx_L0; - - /* "View.MemoryView":943 - * - * @cname('__pyx_memslice_transpose') - * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< - * cdef int ndim = memslice.memview.view.ndim - * - */ - - /* function exit code */ - __pyx_L1_error:; - { - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - } - __pyx_r = 0; - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":976 - * cdef int (*to_dtype_func)(char *, object) except 0 - * - * def __dealloc__(self): # <<<<<<<<<<<<<< - * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) - * - */ - -/* Python wrapper */ -static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self); /*proto*/ -static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); - __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__", 0); - - /* "View.MemoryView":977 - * - * def __dealloc__(self): - * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<< - * - * cdef convert_item_to_object(self, char *itemp): - */ - __PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1); - - /* "View.MemoryView":976 - * cdef int (*to_dtype_func)(char *, object) except 0 - * - * def __dealloc__(self): # <<<<<<<<<<<<<< - * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) - * - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "View.MemoryView":979 - * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) - * - * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< - * if self.to_object_func != NULL: - * return self.to_object_func(itemp) - */ - -static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("convert_item_to_object", 0); - - /* "View.MemoryView":980 - * - * cdef convert_item_to_object(self, char *itemp): - * if self.to_object_func != NULL: # <<<<<<<<<<<<<< - * return self.to_object_func(itemp) - * else: - */ - __pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":981 - * cdef convert_item_to_object(self, char *itemp): - * if self.to_object_func != NULL: - * return self.to_object_func(itemp) # <<<<<<<<<<<<<< - * else: - * return memoryview.convert_item_to_object(self, itemp) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 981, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":980 - * - * cdef convert_item_to_object(self, char *itemp): - * if self.to_object_func != NULL: # <<<<<<<<<<<<<< - * return self.to_object_func(itemp) - * else: - */ - } - - /* "View.MemoryView":983 - * return self.to_object_func(itemp) - * else: - * return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<< - * - * cdef assign_item_from_object(self, char *itemp, object value): - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_memoryview_convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 983, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - } - - /* "View.MemoryView":979 - * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) - * - * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< - * if self.to_object_func != NULL: - * return self.to_object_func(itemp) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView._memoryviewslice.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":985 - * return memoryview.convert_item_to_object(self, itemp) - * - * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< - * if self.to_dtype_func != NULL: - * self.to_dtype_func(itemp, value) - */ - -static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("assign_item_from_object", 0); - - /* "View.MemoryView":986 - * - * cdef assign_item_from_object(self, char *itemp, object value): - * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< - * self.to_dtype_func(itemp, value) - * else: - */ - __pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":987 - * cdef assign_item_from_object(self, char *itemp, object value): - * if self.to_dtype_func != NULL: - * self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<< - * else: - * memoryview.assign_item_from_object(self, itemp, value) - */ - __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == ((int)0))) __PYX_ERR(1, 987, __pyx_L1_error) - - /* "View.MemoryView":986 - * - * cdef assign_item_from_object(self, char *itemp, object value): - * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< - * self.to_dtype_func(itemp, value) - * else: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":989 - * self.to_dtype_func(itemp, value) - * else: - * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< - * - * @property - */ - /*else*/ { - __pyx_t_3 = __pyx_memoryview_assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 989, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } - __pyx_L3:; - - /* "View.MemoryView":985 - * return memoryview.convert_item_to_object(self, itemp) - * - * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< - * if self.to_dtype_func != NULL: - * self.to_dtype_func(itemp, value) - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView._memoryviewslice.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":992 - * - * @property - * def base(self): # <<<<<<<<<<<<<< - * return self.from_object - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":993 - * @property - * def base(self): - * return self.from_object # <<<<<<<<<<<<<< - * - * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->from_object); - __pyx_r = __pyx_v_self->from_object; - goto __pyx_L0; - - /* "View.MemoryView":992 - * - * @property - * def base(self): # <<<<<<<<<<<<<< - * return self.from_object - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_memoryviewslice_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw___pyx_memoryviewslice_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_memoryviewslice___reduce_cython__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_memoryviewslice___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__18, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 2, __pyx_L1_error) - - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView._memoryviewslice.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_memoryviewslice_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw___pyx_memoryviewslice_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_memoryviewslice_2__setstate_cython__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_memoryviewslice_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__19, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 4, __pyx_L1_error) - - /* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView._memoryviewslice.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":999 - * - * @cname('__pyx_memoryview_fromslice') - * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< - * int ndim, - * object (*to_object_func)(char *), - */ - -static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewslice, int __pyx_v_ndim, PyObject *(*__pyx_v_to_object_func)(char *), int (*__pyx_v_to_dtype_func)(char *, PyObject *), int __pyx_v_dtype_is_object) { - struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; - Py_ssize_t __pyx_v_suboffset; - PyObject *__pyx_v_length = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - __Pyx_TypeInfo *__pyx_t_4; - Py_buffer __pyx_t_5; - Py_ssize_t *__pyx_t_6; - Py_ssize_t *__pyx_t_7; - Py_ssize_t *__pyx_t_8; - Py_ssize_t __pyx_t_9; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("memoryview_fromslice", 0); - - /* "View.MemoryView":1007 - * cdef _memoryviewslice result - * - * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< - * return None - * - */ - __pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1008 - * - * if memviewslice.memview == Py_None: - * return None # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - - /* "View.MemoryView":1007 - * cdef _memoryviewslice result - * - * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< - * return None - * - */ - } - - /* "View.MemoryView":1013 - * - * - * result = _memoryviewslice(None, 0, dtype_is_object) # <<<<<<<<<<<<<< - * - * result.from_slice = memviewslice - */ - __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1013, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1013, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); - __Pyx_INCREF(__pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryviewslice_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1013, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "View.MemoryView":1015 - * result = _memoryviewslice(None, 0, dtype_is_object) - * - * result.from_slice = memviewslice # <<<<<<<<<<<<<< - * __PYX_INC_MEMVIEW(&memviewslice, 1) - * - */ - __pyx_v_result->from_slice = __pyx_v_memviewslice; - - /* "View.MemoryView":1016 - * - * result.from_slice = memviewslice - * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< - * - * result.from_object = ( memviewslice.memview).base - */ - __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); - - /* "View.MemoryView":1018 - * __PYX_INC_MEMVIEW(&memviewslice, 1) - * - * result.from_object = ( memviewslice.memview).base # <<<<<<<<<<<<<< - * result.typeinfo = memviewslice.memview.typeinfo - * - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s_base); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1018, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __Pyx_GOTREF(__pyx_v_result->from_object); - __Pyx_DECREF(__pyx_v_result->from_object); - __pyx_v_result->from_object = __pyx_t_2; - __pyx_t_2 = 0; - - /* "View.MemoryView":1019 - * - * result.from_object = ( memviewslice.memview).base - * result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<< - * - * result.view = memviewslice.memview.view - */ - __pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo; - __pyx_v_result->__pyx_base.typeinfo = __pyx_t_4; - - /* "View.MemoryView":1021 - * result.typeinfo = memviewslice.memview.typeinfo - * - * result.view = memviewslice.memview.view # <<<<<<<<<<<<<< - * result.view.buf = memviewslice.data - * result.view.ndim = ndim - */ - __pyx_t_5 = __pyx_v_memviewslice.memview->view; - __pyx_v_result->__pyx_base.view = __pyx_t_5; - - /* "View.MemoryView":1022 - * - * result.view = memviewslice.memview.view - * result.view.buf = memviewslice.data # <<<<<<<<<<<<<< - * result.view.ndim = ndim - * (<__pyx_buffer *> &result.view).obj = Py_None - */ - __pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data); - - /* "View.MemoryView":1023 - * result.view = memviewslice.memview.view - * result.view.buf = memviewslice.data - * result.view.ndim = ndim # <<<<<<<<<<<<<< - * (<__pyx_buffer *> &result.view).obj = Py_None - * Py_INCREF(Py_None) - */ - __pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim; - - /* "View.MemoryView":1024 - * result.view.buf = memviewslice.data - * result.view.ndim = ndim - * (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<< - * Py_INCREF(Py_None) - * - */ - ((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None; - - /* "View.MemoryView":1025 - * result.view.ndim = ndim - * (<__pyx_buffer *> &result.view).obj = Py_None - * Py_INCREF(Py_None) # <<<<<<<<<<<<<< - * - * if (memviewslice.memview).flags & PyBUF_WRITABLE: - */ - Py_INCREF(Py_None); - - /* "View.MemoryView":1027 - * Py_INCREF(Py_None) - * - * if (memviewslice.memview).flags & PyBUF_WRITABLE: # <<<<<<<<<<<<<< - * result.flags = PyBUF_RECORDS - * else: - */ - __pyx_t_1 = ((((struct __pyx_memoryview_obj *)__pyx_v_memviewslice.memview)->flags & PyBUF_WRITABLE) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1028 - * - * if (memviewslice.memview).flags & PyBUF_WRITABLE: - * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< - * else: - * result.flags = PyBUF_RECORDS_RO - */ - __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; - - /* "View.MemoryView":1027 - * Py_INCREF(Py_None) - * - * if (memviewslice.memview).flags & PyBUF_WRITABLE: # <<<<<<<<<<<<<< - * result.flags = PyBUF_RECORDS - * else: - */ - goto __pyx_L4; - } - - /* "View.MemoryView":1030 - * result.flags = PyBUF_RECORDS - * else: - * result.flags = PyBUF_RECORDS_RO # <<<<<<<<<<<<<< - * - * result.view.shape = result.from_slice.shape - */ - /*else*/ { - __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS_RO; - } - __pyx_L4:; - - /* "View.MemoryView":1032 - * result.flags = PyBUF_RECORDS_RO - * - * result.view.shape = result.from_slice.shape # <<<<<<<<<<<<<< - * result.view.strides = result.from_slice.strides - * - */ - __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); - - /* "View.MemoryView":1033 - * - * result.view.shape = result.from_slice.shape - * result.view.strides = result.from_slice.strides # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides); - - /* "View.MemoryView":1036 - * - * - * result.view.suboffsets = NULL # <<<<<<<<<<<<<< - * for suboffset in result.from_slice.suboffsets[:ndim]: - * if suboffset >= 0: - */ - __pyx_v_result->__pyx_base.view.suboffsets = NULL; - - /* "View.MemoryView":1037 - * - * result.view.suboffsets = NULL - * for suboffset in result.from_slice.suboffsets[:ndim]: # <<<<<<<<<<<<<< - * if suboffset >= 0: - * result.view.suboffsets = result.from_slice.suboffsets - */ - __pyx_t_7 = (__pyx_v_result->from_slice.suboffsets + __pyx_v_ndim); - for (__pyx_t_8 = __pyx_v_result->from_slice.suboffsets; __pyx_t_8 < __pyx_t_7; __pyx_t_8++) { - __pyx_t_6 = __pyx_t_8; - __pyx_v_suboffset = (__pyx_t_6[0]); - - /* "View.MemoryView":1038 - * result.view.suboffsets = NULL - * for suboffset in result.from_slice.suboffsets[:ndim]: - * if suboffset >= 0: # <<<<<<<<<<<<<< - * result.view.suboffsets = result.from_slice.suboffsets - * break - */ - __pyx_t_1 = ((__pyx_v_suboffset >= 0) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1039 - * for suboffset in result.from_slice.suboffsets[:ndim]: - * if suboffset >= 0: - * result.view.suboffsets = result.from_slice.suboffsets # <<<<<<<<<<<<<< - * break - * - */ - __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); - - /* "View.MemoryView":1040 - * if suboffset >= 0: - * result.view.suboffsets = result.from_slice.suboffsets - * break # <<<<<<<<<<<<<< - * - * result.view.len = result.view.itemsize - */ - goto __pyx_L6_break; - - /* "View.MemoryView":1038 - * result.view.suboffsets = NULL - * for suboffset in result.from_slice.suboffsets[:ndim]: - * if suboffset >= 0: # <<<<<<<<<<<<<< - * result.view.suboffsets = result.from_slice.suboffsets - * break - */ - } - } - __pyx_L6_break:; - - /* "View.MemoryView":1042 - * break - * - * result.view.len = result.view.itemsize # <<<<<<<<<<<<<< - * for length in result.view.shape[:ndim]: - * result.view.len *= length - */ - __pyx_t_9 = __pyx_v_result->__pyx_base.view.itemsize; - __pyx_v_result->__pyx_base.view.len = __pyx_t_9; - - /* "View.MemoryView":1043 - * - * result.view.len = result.view.itemsize - * for length in result.view.shape[:ndim]: # <<<<<<<<<<<<<< - * result.view.len *= length - * - */ - __pyx_t_7 = (__pyx_v_result->__pyx_base.view.shape + __pyx_v_ndim); - for (__pyx_t_8 = __pyx_v_result->__pyx_base.view.shape; __pyx_t_8 < __pyx_t_7; __pyx_t_8++) { - __pyx_t_6 = __pyx_t_8; - __pyx_t_2 = PyInt_FromSsize_t((__pyx_t_6[0])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1043, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_2); - __pyx_t_2 = 0; - - /* "View.MemoryView":1044 - * result.view.len = result.view.itemsize - * for length in result.view.shape[:ndim]: - * result.view.len *= length # <<<<<<<<<<<<<< - * - * result.to_object_func = to_object_func - */ - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_result->__pyx_base.view.len); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1044, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_t_2, __pyx_v_length); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1044, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_9 = __Pyx_PyIndex_AsSsize_t(__pyx_t_3); if (unlikely((__pyx_t_9 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 1044, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_result->__pyx_base.view.len = __pyx_t_9; - } - - /* "View.MemoryView":1046 - * result.view.len *= length - * - * result.to_object_func = to_object_func # <<<<<<<<<<<<<< - * result.to_dtype_func = to_dtype_func - * - */ - __pyx_v_result->to_object_func = __pyx_v_to_object_func; - - /* "View.MemoryView":1047 - * - * result.to_object_func = to_object_func - * result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<< - * - * return result - */ - __pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func; - - /* "View.MemoryView":1049 - * result.to_dtype_func = to_dtype_func - * - * return result # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_get_slice_from_memoryview') - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_result)); - __pyx_r = ((PyObject *)__pyx_v_result); - goto __pyx_L0; - - /* "View.MemoryView":999 - * - * @cname('__pyx_memoryview_fromslice') - * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< - * int ndim, - * object (*to_object_func)(char *), - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview_fromslice", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_result); - __Pyx_XDECREF(__pyx_v_length); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":1052 - * - * @cname('__pyx_memoryview_get_slice_from_memoryview') - * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *mslice) except NULL: - * cdef _memoryviewslice obj - */ - -static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_mslice) { - struct __pyx_memoryviewslice_obj *__pyx_v_obj = 0; - __Pyx_memviewslice *__pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("get_slice_from_memview", 0); - - /* "View.MemoryView":1055 - * __Pyx_memviewslice *mslice) except NULL: - * cdef _memoryviewslice obj - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * obj = memview - * return &obj.from_slice - */ - __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1056 - * cdef _memoryviewslice obj - * if isinstance(memview, _memoryviewslice): - * obj = memview # <<<<<<<<<<<<<< - * return &obj.from_slice - * else: - */ - if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) __PYX_ERR(1, 1056, __pyx_L1_error) - __pyx_t_3 = ((PyObject *)__pyx_v_memview); - __Pyx_INCREF(__pyx_t_3); - __pyx_v_obj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "View.MemoryView":1057 - * if isinstance(memview, _memoryviewslice): - * obj = memview - * return &obj.from_slice # <<<<<<<<<<<<<< - * else: - * slice_copy(memview, mslice) - */ - __pyx_r = (&__pyx_v_obj->from_slice); - goto __pyx_L0; - - /* "View.MemoryView":1055 - * __Pyx_memviewslice *mslice) except NULL: - * cdef _memoryviewslice obj - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * obj = memview - * return &obj.from_slice - */ - } - - /* "View.MemoryView":1059 - * return &obj.from_slice - * else: - * slice_copy(memview, mslice) # <<<<<<<<<<<<<< - * return mslice - * - */ - /*else*/ { - __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); - - /* "View.MemoryView":1060 - * else: - * slice_copy(memview, mslice) - * return mslice # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_slice_copy') - */ - __pyx_r = __pyx_v_mslice; - goto __pyx_L0; - } - - /* "View.MemoryView":1052 - * - * @cname('__pyx_memoryview_get_slice_from_memoryview') - * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *mslice) except NULL: - * cdef _memoryviewslice obj - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_obj); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":1063 - * - * @cname('__pyx_memoryview_slice_copy') - * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< - * cdef int dim - * cdef (Py_ssize_t*) shape, strides, suboffsets - */ - -static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_dst) { - int __pyx_v_dim; - Py_ssize_t *__pyx_v_shape; - Py_ssize_t *__pyx_v_strides; - Py_ssize_t *__pyx_v_suboffsets; - __Pyx_RefNannyDeclarations - Py_ssize_t *__pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - Py_ssize_t __pyx_t_5; - __Pyx_RefNannySetupContext("slice_copy", 0); - - /* "View.MemoryView":1067 - * cdef (Py_ssize_t*) shape, strides, suboffsets - * - * shape = memview.view.shape # <<<<<<<<<<<<<< - * strides = memview.view.strides - * suboffsets = memview.view.suboffsets - */ - __pyx_t_1 = __pyx_v_memview->view.shape; - __pyx_v_shape = __pyx_t_1; - - /* "View.MemoryView":1068 - * - * shape = memview.view.shape - * strides = memview.view.strides # <<<<<<<<<<<<<< - * suboffsets = memview.view.suboffsets - * - */ - __pyx_t_1 = __pyx_v_memview->view.strides; - __pyx_v_strides = __pyx_t_1; - - /* "View.MemoryView":1069 - * shape = memview.view.shape - * strides = memview.view.strides - * suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<< - * - * dst.memview = <__pyx_memoryview *> memview - */ - __pyx_t_1 = __pyx_v_memview->view.suboffsets; - __pyx_v_suboffsets = __pyx_t_1; - - /* "View.MemoryView":1071 - * suboffsets = memview.view.suboffsets - * - * dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<< - * dst.data = memview.view.buf - * - */ - __pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview); - - /* "View.MemoryView":1072 - * - * dst.memview = <__pyx_memoryview *> memview - * dst.data = memview.view.buf # <<<<<<<<<<<<<< - * - * for dim in range(memview.view.ndim): - */ - __pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf); - - /* "View.MemoryView":1074 - * dst.data = memview.view.buf - * - * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< - * dst.shape[dim] = shape[dim] - * dst.strides[dim] = strides[dim] - */ - __pyx_t_2 = __pyx_v_memview->view.ndim; - __pyx_t_3 = __pyx_t_2; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_dim = __pyx_t_4; - - /* "View.MemoryView":1075 - * - * for dim in range(memview.view.ndim): - * dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<< - * dst.strides[dim] = strides[dim] - * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 - */ - (__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]); - - /* "View.MemoryView":1076 - * for dim in range(memview.view.ndim): - * dst.shape[dim] = shape[dim] - * dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<< - * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 - * - */ - (__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]); - - /* "View.MemoryView":1077 - * dst.shape[dim] = shape[dim] - * dst.strides[dim] = strides[dim] - * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_copy_object') - */ - if ((__pyx_v_suboffsets != 0)) { - __pyx_t_5 = (__pyx_v_suboffsets[__pyx_v_dim]); - } else { - __pyx_t_5 = -1L; - } - (__pyx_v_dst->suboffsets[__pyx_v_dim]) = __pyx_t_5; - } - - /* "View.MemoryView":1063 - * - * @cname('__pyx_memoryview_slice_copy') - * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< - * cdef int dim - * cdef (Py_ssize_t*) shape, strides, suboffsets - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "View.MemoryView":1080 - * - * @cname('__pyx_memoryview_copy_object') - * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< - * "Create a new memoryview object" - * cdef __Pyx_memviewslice memviewslice - */ - -static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx_v_memview) { - __Pyx_memviewslice __pyx_v_memviewslice; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("memoryview_copy", 0); - - /* "View.MemoryView":1083 - * "Create a new memoryview object" - * cdef __Pyx_memviewslice memviewslice - * slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<< - * return memoryview_copy_from_slice(memview, &memviewslice) - * - */ - __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice)); - - /* "View.MemoryView":1084 - * cdef __Pyx_memviewslice memviewslice - * slice_copy(memview, &memviewslice) - * return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_copy_object_from_slice') - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1084, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":1080 - * - * @cname('__pyx_memoryview_copy_object') - * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< - * "Create a new memoryview object" - * cdef __Pyx_memviewslice memviewslice - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.memoryview_copy", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":1087 - * - * @cname('__pyx_memoryview_copy_object_from_slice') - * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< - * """ - * Create a new memoryview object from a given memoryview object and slice. - */ - -static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_memviewslice) { - PyObject *(*__pyx_v_to_object_func)(char *); - int (*__pyx_v_to_dtype_func)(char *, PyObject *); - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *(*__pyx_t_3)(char *); - int (*__pyx_t_4)(char *, PyObject *); - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); - - /* "View.MemoryView":1094 - * cdef int (*to_dtype_func)(char *, object) except 0 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * to_object_func = (<_memoryviewslice> memview).to_object_func - * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func - */ - __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1095 - * - * if isinstance(memview, _memoryviewslice): - * to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<< - * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func - * else: - */ - __pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func; - __pyx_v_to_object_func = __pyx_t_3; - - /* "View.MemoryView":1096 - * if isinstance(memview, _memoryviewslice): - * to_object_func = (<_memoryviewslice> memview).to_object_func - * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<< - * else: - * to_object_func = NULL - */ - __pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func; - __pyx_v_to_dtype_func = __pyx_t_4; - - /* "View.MemoryView":1094 - * cdef int (*to_dtype_func)(char *, object) except 0 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * to_object_func = (<_memoryviewslice> memview).to_object_func - * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func - */ - goto __pyx_L3; - } - - /* "View.MemoryView":1098 - * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func - * else: - * to_object_func = NULL # <<<<<<<<<<<<<< - * to_dtype_func = NULL - * - */ - /*else*/ { - __pyx_v_to_object_func = NULL; - - /* "View.MemoryView":1099 - * else: - * to_object_func = NULL - * to_dtype_func = NULL # <<<<<<<<<<<<<< - * - * return memoryview_fromslice(memviewslice[0], memview.view.ndim, - */ - __pyx_v_to_dtype_func = NULL; - } - __pyx_L3:; - - /* "View.MemoryView":1101 - * to_dtype_func = NULL - * - * return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<< - * to_object_func, to_dtype_func, - * memview.dtype_is_object) - */ - __Pyx_XDECREF(__pyx_r); - - /* "View.MemoryView":1103 - * return memoryview_fromslice(memviewslice[0], memview.view.ndim, - * to_object_func, to_dtype_func, - * memview.dtype_is_object) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 1101, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "View.MemoryView":1087 - * - * @cname('__pyx_memoryview_copy_object_from_slice') - * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< - * """ - * Create a new memoryview object from a given memoryview object and slice. - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.memoryview_copy_from_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":1109 - * - * - * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< - * if arg < 0: - * return -arg - */ - -static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { - Py_ssize_t __pyx_r; - int __pyx_t_1; - - /* "View.MemoryView":1110 - * - * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: - * if arg < 0: # <<<<<<<<<<<<<< - * return -arg - * else: - */ - __pyx_t_1 = ((__pyx_v_arg < 0) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1111 - * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: - * if arg < 0: - * return -arg # <<<<<<<<<<<<<< - * else: - * return arg - */ - __pyx_r = (-__pyx_v_arg); - goto __pyx_L0; - - /* "View.MemoryView":1110 - * - * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: - * if arg < 0: # <<<<<<<<<<<<<< - * return -arg - * else: - */ - } - - /* "View.MemoryView":1113 - * return -arg - * else: - * return arg # <<<<<<<<<<<<<< - * - * @cname('__pyx_get_best_slice_order') - */ - /*else*/ { - __pyx_r = __pyx_v_arg; - goto __pyx_L0; - } - - /* "View.MemoryView":1109 - * - * - * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< - * if arg < 0: - * return -arg - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1116 - * - * @cname('__pyx_get_best_slice_order') - * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< - * """ - * Figure out the best memory access order for a given slice. - */ - -static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim) { - int __pyx_v_i; - Py_ssize_t __pyx_v_c_stride; - Py_ssize_t __pyx_v_f_stride; - char __pyx_r; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - - /* "View.MemoryView":1121 - * """ - * cdef int i - * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< - * cdef Py_ssize_t f_stride = 0 - * - */ - __pyx_v_c_stride = 0; - - /* "View.MemoryView":1122 - * cdef int i - * cdef Py_ssize_t c_stride = 0 - * cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<< - * - * for i in range(ndim - 1, -1, -1): - */ - __pyx_v_f_stride = 0; - - /* "View.MemoryView":1124 - * cdef Py_ssize_t f_stride = 0 - * - * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< - * if mslice.shape[i] > 1: - * c_stride = mslice.strides[i] - */ - for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { - __pyx_v_i = __pyx_t_1; - - /* "View.MemoryView":1125 - * - * for i in range(ndim - 1, -1, -1): - * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< - * c_stride = mslice.strides[i] - * break - */ - __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1126 - * for i in range(ndim - 1, -1, -1): - * if mslice.shape[i] > 1: - * c_stride = mslice.strides[i] # <<<<<<<<<<<<<< - * break - * - */ - __pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]); - - /* "View.MemoryView":1127 - * if mslice.shape[i] > 1: - * c_stride = mslice.strides[i] - * break # <<<<<<<<<<<<<< - * - * for i in range(ndim): - */ - goto __pyx_L4_break; - - /* "View.MemoryView":1125 - * - * for i in range(ndim - 1, -1, -1): - * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< - * c_stride = mslice.strides[i] - * break - */ - } - } - __pyx_L4_break:; - - /* "View.MemoryView":1129 - * break - * - * for i in range(ndim): # <<<<<<<<<<<<<< - * if mslice.shape[i] > 1: - * f_stride = mslice.strides[i] - */ - __pyx_t_1 = __pyx_v_ndim; - __pyx_t_3 = __pyx_t_1; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_i = __pyx_t_4; - - /* "View.MemoryView":1130 - * - * for i in range(ndim): - * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< - * f_stride = mslice.strides[i] - * break - */ - __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1131 - * for i in range(ndim): - * if mslice.shape[i] > 1: - * f_stride = mslice.strides[i] # <<<<<<<<<<<<<< - * break - * - */ - __pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]); - - /* "View.MemoryView":1132 - * if mslice.shape[i] > 1: - * f_stride = mslice.strides[i] - * break # <<<<<<<<<<<<<< - * - * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): - */ - goto __pyx_L7_break; - - /* "View.MemoryView":1130 - * - * for i in range(ndim): - * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< - * f_stride = mslice.strides[i] - * break - */ - } - } - __pyx_L7_break:; - - /* "View.MemoryView":1134 - * break - * - * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< - * return 'C' - * else: - */ - __pyx_t_2 = ((abs_py_ssize_t(__pyx_v_c_stride) <= abs_py_ssize_t(__pyx_v_f_stride)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1135 - * - * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): - * return 'C' # <<<<<<<<<<<<<< - * else: - * return 'F' - */ - __pyx_r = 'C'; - goto __pyx_L0; - - /* "View.MemoryView":1134 - * break - * - * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< - * return 'C' - * else: - */ - } - - /* "View.MemoryView":1137 - * return 'C' - * else: - * return 'F' # <<<<<<<<<<<<<< - * - * @cython.cdivision(True) - */ - /*else*/ { - __pyx_r = 'F'; - goto __pyx_L0; - } - - /* "View.MemoryView":1116 - * - * @cname('__pyx_get_best_slice_order') - * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< - * """ - * Figure out the best memory access order for a given slice. - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1140 - * - * @cython.cdivision(True) - * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< - * char *dst_data, Py_ssize_t *dst_strides, - * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, - */ - -static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v_src_strides, char *__pyx_v_dst_data, Py_ssize_t *__pyx_v_dst_strides, Py_ssize_t *__pyx_v_src_shape, Py_ssize_t *__pyx_v_dst_shape, int __pyx_v_ndim, size_t __pyx_v_itemsize) { - CYTHON_UNUSED Py_ssize_t __pyx_v_i; - CYTHON_UNUSED Py_ssize_t __pyx_v_src_extent; - Py_ssize_t __pyx_v_dst_extent; - Py_ssize_t __pyx_v_src_stride; - Py_ssize_t __pyx_v_dst_stride; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - Py_ssize_t __pyx_t_4; - Py_ssize_t __pyx_t_5; - Py_ssize_t __pyx_t_6; - - /* "View.MemoryView":1147 - * - * cdef Py_ssize_t i - * cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<< - * cdef Py_ssize_t dst_extent = dst_shape[0] - * cdef Py_ssize_t src_stride = src_strides[0] - */ - __pyx_v_src_extent = (__pyx_v_src_shape[0]); - - /* "View.MemoryView":1148 - * cdef Py_ssize_t i - * cdef Py_ssize_t src_extent = src_shape[0] - * cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<< - * cdef Py_ssize_t src_stride = src_strides[0] - * cdef Py_ssize_t dst_stride = dst_strides[0] - */ - __pyx_v_dst_extent = (__pyx_v_dst_shape[0]); - - /* "View.MemoryView":1149 - * cdef Py_ssize_t src_extent = src_shape[0] - * cdef Py_ssize_t dst_extent = dst_shape[0] - * cdef Py_ssize_t src_stride = src_strides[0] # <<<<<<<<<<<<<< - * cdef Py_ssize_t dst_stride = dst_strides[0] - * - */ - __pyx_v_src_stride = (__pyx_v_src_strides[0]); - - /* "View.MemoryView":1150 - * cdef Py_ssize_t dst_extent = dst_shape[0] - * cdef Py_ssize_t src_stride = src_strides[0] - * cdef Py_ssize_t dst_stride = dst_strides[0] # <<<<<<<<<<<<<< - * - * if ndim == 1: - */ - __pyx_v_dst_stride = (__pyx_v_dst_strides[0]); - - /* "View.MemoryView":1152 - * cdef Py_ssize_t dst_stride = dst_strides[0] - * - * if ndim == 1: # <<<<<<<<<<<<<< - * if (src_stride > 0 and dst_stride > 0 and - * src_stride == itemsize == dst_stride): - */ - __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1153 - * - * if ndim == 1: - * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< - * src_stride == itemsize == dst_stride): - * memcpy(dst_data, src_data, itemsize * dst_extent) - */ - __pyx_t_2 = ((__pyx_v_src_stride > 0) != 0); - if (__pyx_t_2) { - } else { - __pyx_t_1 = __pyx_t_2; - goto __pyx_L5_bool_binop_done; - } - __pyx_t_2 = ((__pyx_v_dst_stride > 0) != 0); - if (__pyx_t_2) { - } else { - __pyx_t_1 = __pyx_t_2; - goto __pyx_L5_bool_binop_done; - } - - /* "View.MemoryView":1154 - * if ndim == 1: - * if (src_stride > 0 and dst_stride > 0 and - * src_stride == itemsize == dst_stride): # <<<<<<<<<<<<<< - * memcpy(dst_data, src_data, itemsize * dst_extent) - * else: - */ - __pyx_t_2 = (((size_t)__pyx_v_src_stride) == __pyx_v_itemsize); - if (__pyx_t_2) { - __pyx_t_2 = (__pyx_v_itemsize == ((size_t)__pyx_v_dst_stride)); - } - __pyx_t_3 = (__pyx_t_2 != 0); - __pyx_t_1 = __pyx_t_3; - __pyx_L5_bool_binop_done:; - - /* "View.MemoryView":1153 - * - * if ndim == 1: - * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< - * src_stride == itemsize == dst_stride): - * memcpy(dst_data, src_data, itemsize * dst_extent) - */ - if (__pyx_t_1) { - - /* "View.MemoryView":1155 - * if (src_stride > 0 and dst_stride > 0 and - * src_stride == itemsize == dst_stride): - * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< - * else: - * for i in range(dst_extent): - */ - (void)(memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent))); - - /* "View.MemoryView":1153 - * - * if ndim == 1: - * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< - * src_stride == itemsize == dst_stride): - * memcpy(dst_data, src_data, itemsize * dst_extent) - */ - goto __pyx_L4; - } - - /* "View.MemoryView":1157 - * memcpy(dst_data, src_data, itemsize * dst_extent) - * else: - * for i in range(dst_extent): # <<<<<<<<<<<<<< - * memcpy(dst_data, src_data, itemsize) - * src_data += src_stride - */ - /*else*/ { - __pyx_t_4 = __pyx_v_dst_extent; - __pyx_t_5 = __pyx_t_4; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; - - /* "View.MemoryView":1158 - * else: - * for i in range(dst_extent): - * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< - * src_data += src_stride - * dst_data += dst_stride - */ - (void)(memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize)); - - /* "View.MemoryView":1159 - * for i in range(dst_extent): - * memcpy(dst_data, src_data, itemsize) - * src_data += src_stride # <<<<<<<<<<<<<< - * dst_data += dst_stride - * else: - */ - __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); - - /* "View.MemoryView":1160 - * memcpy(dst_data, src_data, itemsize) - * src_data += src_stride - * dst_data += dst_stride # <<<<<<<<<<<<<< - * else: - * for i in range(dst_extent): - */ - __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); - } - } - __pyx_L4:; - - /* "View.MemoryView":1152 - * cdef Py_ssize_t dst_stride = dst_strides[0] - * - * if ndim == 1: # <<<<<<<<<<<<<< - * if (src_stride > 0 and dst_stride > 0 and - * src_stride == itemsize == dst_stride): - */ - goto __pyx_L3; - } - - /* "View.MemoryView":1162 - * dst_data += dst_stride - * else: - * for i in range(dst_extent): # <<<<<<<<<<<<<< - * _copy_strided_to_strided(src_data, src_strides + 1, - * dst_data, dst_strides + 1, - */ - /*else*/ { - __pyx_t_4 = __pyx_v_dst_extent; - __pyx_t_5 = __pyx_t_4; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; - - /* "View.MemoryView":1163 - * else: - * for i in range(dst_extent): - * _copy_strided_to_strided(src_data, src_strides + 1, # <<<<<<<<<<<<<< - * dst_data, dst_strides + 1, - * src_shape + 1, dst_shape + 1, - */ - _copy_strided_to_strided(__pyx_v_src_data, (__pyx_v_src_strides + 1), __pyx_v_dst_data, (__pyx_v_dst_strides + 1), (__pyx_v_src_shape + 1), (__pyx_v_dst_shape + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize); - - /* "View.MemoryView":1167 - * src_shape + 1, dst_shape + 1, - * ndim - 1, itemsize) - * src_data += src_stride # <<<<<<<<<<<<<< - * dst_data += dst_stride - * - */ - __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); - - /* "View.MemoryView":1168 - * ndim - 1, itemsize) - * src_data += src_stride - * dst_data += dst_stride # <<<<<<<<<<<<<< - * - * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, - */ - __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); - } - } - __pyx_L3:; - - /* "View.MemoryView":1140 - * - * @cython.cdivision(True) - * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< - * char *dst_data, Py_ssize_t *dst_strides, - * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, - */ - - /* function exit code */ -} - -/* "View.MemoryView":1170 - * dst_data += dst_stride - * - * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *dst, - * int ndim, size_t itemsize) nogil: - */ - -static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize) { - - /* "View.MemoryView":1173 - * __Pyx_memviewslice *dst, - * int ndim, size_t itemsize) nogil: - * _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, # <<<<<<<<<<<<<< - * src.shape, dst.shape, ndim, itemsize) - * - */ - _copy_strided_to_strided(__pyx_v_src->data, __pyx_v_src->strides, __pyx_v_dst->data, __pyx_v_dst->strides, __pyx_v_src->shape, __pyx_v_dst->shape, __pyx_v_ndim, __pyx_v_itemsize); - - /* "View.MemoryView":1170 - * dst_data += dst_stride - * - * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *dst, - * int ndim, size_t itemsize) nogil: - */ - - /* function exit code */ -} - -/* "View.MemoryView":1177 - * - * @cname('__pyx_memoryview_slice_get_size') - * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< - * "Return the size of the memory occupied by the slice in number of bytes" - * cdef Py_ssize_t shape, size = src.memview.view.itemsize - */ - -static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { - Py_ssize_t __pyx_v_shape; - Py_ssize_t __pyx_v_size; - Py_ssize_t __pyx_r; - Py_ssize_t __pyx_t_1; - Py_ssize_t *__pyx_t_2; - Py_ssize_t *__pyx_t_3; - Py_ssize_t *__pyx_t_4; - - /* "View.MemoryView":1179 - * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: - * "Return the size of the memory occupied by the slice in number of bytes" - * cdef Py_ssize_t shape, size = src.memview.view.itemsize # <<<<<<<<<<<<<< - * - * for shape in src.shape[:ndim]: - */ - __pyx_t_1 = __pyx_v_src->memview->view.itemsize; - __pyx_v_size = __pyx_t_1; - - /* "View.MemoryView":1181 - * cdef Py_ssize_t shape, size = src.memview.view.itemsize - * - * for shape in src.shape[:ndim]: # <<<<<<<<<<<<<< - * size *= shape - * - */ - __pyx_t_3 = (__pyx_v_src->shape + __pyx_v_ndim); - for (__pyx_t_4 = __pyx_v_src->shape; __pyx_t_4 < __pyx_t_3; __pyx_t_4++) { - __pyx_t_2 = __pyx_t_4; - __pyx_v_shape = (__pyx_t_2[0]); - - /* "View.MemoryView":1182 - * - * for shape in src.shape[:ndim]: - * size *= shape # <<<<<<<<<<<<<< - * - * return size - */ - __pyx_v_size = (__pyx_v_size * __pyx_v_shape); - } - - /* "View.MemoryView":1184 - * size *= shape - * - * return size # <<<<<<<<<<<<<< - * - * @cname('__pyx_fill_contig_strides_array') - */ - __pyx_r = __pyx_v_size; - goto __pyx_L0; - - /* "View.MemoryView":1177 - * - * @cname('__pyx_memoryview_slice_get_size') - * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< - * "Return the size of the memory occupied by the slice in number of bytes" - * cdef Py_ssize_t shape, size = src.memview.view.itemsize - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1187 - * - * @cname('__pyx_fill_contig_strides_array') - * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< - * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, - * int ndim, char order) nogil: - */ - -static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, Py_ssize_t __pyx_v_stride, int __pyx_v_ndim, char __pyx_v_order) { - int __pyx_v_idx; - Py_ssize_t __pyx_r; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - - /* "View.MemoryView":1196 - * cdef int idx - * - * if order == 'F': # <<<<<<<<<<<<<< - * for idx in range(ndim): - * strides[idx] = stride - */ - __pyx_t_1 = ((__pyx_v_order == 'F') != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1197 - * - * if order == 'F': - * for idx in range(ndim): # <<<<<<<<<<<<<< - * strides[idx] = stride - * stride *= shape[idx] - */ - __pyx_t_2 = __pyx_v_ndim; - __pyx_t_3 = __pyx_t_2; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_idx = __pyx_t_4; - - /* "View.MemoryView":1198 - * if order == 'F': - * for idx in range(ndim): - * strides[idx] = stride # <<<<<<<<<<<<<< - * stride *= shape[idx] - * else: - */ - (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; - - /* "View.MemoryView":1199 - * for idx in range(ndim): - * strides[idx] = stride - * stride *= shape[idx] # <<<<<<<<<<<<<< - * else: - * for idx in range(ndim - 1, -1, -1): - */ - __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); - } - - /* "View.MemoryView":1196 - * cdef int idx - * - * if order == 'F': # <<<<<<<<<<<<<< - * for idx in range(ndim): - * strides[idx] = stride - */ - goto __pyx_L3; - } - - /* "View.MemoryView":1201 - * stride *= shape[idx] - * else: - * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< - * strides[idx] = stride - * stride *= shape[idx] - */ - /*else*/ { - for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { - __pyx_v_idx = __pyx_t_2; - - /* "View.MemoryView":1202 - * else: - * for idx in range(ndim - 1, -1, -1): - * strides[idx] = stride # <<<<<<<<<<<<<< - * stride *= shape[idx] - * - */ - (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; - - /* "View.MemoryView":1203 - * for idx in range(ndim - 1, -1, -1): - * strides[idx] = stride - * stride *= shape[idx] # <<<<<<<<<<<<<< - * - * return stride - */ - __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); - } - } - __pyx_L3:; - - /* "View.MemoryView":1205 - * stride *= shape[idx] - * - * return stride # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_copy_data_to_temp') - */ - __pyx_r = __pyx_v_stride; - goto __pyx_L0; - - /* "View.MemoryView":1187 - * - * @cname('__pyx_fill_contig_strides_array') - * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< - * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, - * int ndim, char order) nogil: - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1208 - * - * @cname('__pyx_memoryview_copy_data_to_temp') - * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *tmpslice, - * char order, - */ - -static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_tmpslice, char __pyx_v_order, int __pyx_v_ndim) { - int __pyx_v_i; - void *__pyx_v_result; - size_t __pyx_v_itemsize; - size_t __pyx_v_size; - void *__pyx_r; - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - struct __pyx_memoryview_obj *__pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - - /* "View.MemoryView":1219 - * cdef void *result - * - * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< - * cdef size_t size = slice_get_size(src, ndim) - * - */ - __pyx_t_1 = __pyx_v_src->memview->view.itemsize; - __pyx_v_itemsize = __pyx_t_1; - - /* "View.MemoryView":1220 - * - * cdef size_t itemsize = src.memview.view.itemsize - * cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<< - * - * result = malloc(size) - */ - __pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim); - - /* "View.MemoryView":1222 - * cdef size_t size = slice_get_size(src, ndim) - * - * result = malloc(size) # <<<<<<<<<<<<<< - * if not result: - * _err(MemoryError, NULL) - */ - __pyx_v_result = malloc(__pyx_v_size); - - /* "View.MemoryView":1223 - * - * result = malloc(size) - * if not result: # <<<<<<<<<<<<<< - * _err(MemoryError, NULL) - * - */ - __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1224 - * result = malloc(size) - * if not result: - * _err(MemoryError, NULL) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(1, 1224, __pyx_L1_error) - - /* "View.MemoryView":1223 - * - * result = malloc(size) - * if not result: # <<<<<<<<<<<<<< - * _err(MemoryError, NULL) - * - */ - } - - /* "View.MemoryView":1227 - * - * - * tmpslice.data = result # <<<<<<<<<<<<<< - * tmpslice.memview = src.memview - * for i in range(ndim): - */ - __pyx_v_tmpslice->data = ((char *)__pyx_v_result); - - /* "View.MemoryView":1228 - * - * tmpslice.data = result - * tmpslice.memview = src.memview # <<<<<<<<<<<<<< - * for i in range(ndim): - * tmpslice.shape[i] = src.shape[i] - */ - __pyx_t_4 = __pyx_v_src->memview; - __pyx_v_tmpslice->memview = __pyx_t_4; - - /* "View.MemoryView":1229 - * tmpslice.data = result - * tmpslice.memview = src.memview - * for i in range(ndim): # <<<<<<<<<<<<<< - * tmpslice.shape[i] = src.shape[i] - * tmpslice.suboffsets[i] = -1 - */ - __pyx_t_3 = __pyx_v_ndim; - __pyx_t_5 = __pyx_t_3; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; - - /* "View.MemoryView":1230 - * tmpslice.memview = src.memview - * for i in range(ndim): - * tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<< - * tmpslice.suboffsets[i] = -1 - * - */ - (__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]); - - /* "View.MemoryView":1231 - * for i in range(ndim): - * tmpslice.shape[i] = src.shape[i] - * tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< - * - * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, - */ - (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1L; - } - - /* "View.MemoryView":1233 - * tmpslice.suboffsets[i] = -1 - * - * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, # <<<<<<<<<<<<<< - * ndim, order) - * - */ - (void)(__pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order)); - - /* "View.MemoryView":1237 - * - * - * for i in range(ndim): # <<<<<<<<<<<<<< - * if tmpslice.shape[i] == 1: - * tmpslice.strides[i] = 0 - */ - __pyx_t_3 = __pyx_v_ndim; - __pyx_t_5 = __pyx_t_3; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; - - /* "View.MemoryView":1238 - * - * for i in range(ndim): - * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< - * tmpslice.strides[i] = 0 - * - */ - __pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1239 - * for i in range(ndim): - * if tmpslice.shape[i] == 1: - * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< - * - * if slice_is_contig(src[0], order, ndim): - */ - (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; - - /* "View.MemoryView":1238 - * - * for i in range(ndim): - * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< - * tmpslice.strides[i] = 0 - * - */ - } - } - - /* "View.MemoryView":1241 - * tmpslice.strides[i] = 0 - * - * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< - * memcpy(result, src.data, size) - * else: - */ - __pyx_t_2 = (__pyx_memviewslice_is_contig((__pyx_v_src[0]), __pyx_v_order, __pyx_v_ndim) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1242 - * - * if slice_is_contig(src[0], order, ndim): - * memcpy(result, src.data, size) # <<<<<<<<<<<<<< - * else: - * copy_strided_to_strided(src, tmpslice, ndim, itemsize) - */ - (void)(memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size)); - - /* "View.MemoryView":1241 - * tmpslice.strides[i] = 0 - * - * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< - * memcpy(result, src.data, size) - * else: - */ - goto __pyx_L9; - } - - /* "View.MemoryView":1244 - * memcpy(result, src.data, size) - * else: - * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< - * - * return result - */ - /*else*/ { - copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); - } - __pyx_L9:; - - /* "View.MemoryView":1246 - * copy_strided_to_strided(src, tmpslice, ndim, itemsize) - * - * return result # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = __pyx_v_result; - goto __pyx_L0; - - /* "View.MemoryView":1208 - * - * @cname('__pyx_memoryview_copy_data_to_temp') - * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *tmpslice, - * char order, - */ - - /* function exit code */ - __pyx_L1_error:; - { - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - } - __pyx_r = NULL; - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1251 - * - * @cname('__pyx_memoryview_err_extents') - * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< - * Py_ssize_t extent2) except -1 with gil: - * raise ValueError("got differing extents in dimension %d (got %d and %d)" % - */ - -static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent1, Py_ssize_t __pyx_v_extent2) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_RefNannySetupContext("_err_extents", 0); - - /* "View.MemoryView":1254 - * Py_ssize_t extent2) except -1 with gil: - * raise ValueError("got differing extents in dimension %d (got %d and %d)" % - * (i, extent1, extent2)) # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_err_dim') - */ - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1254, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1254, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1254, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 1254, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_3 = 0; - - /* "View.MemoryView":1253 - * cdef int _err_extents(int i, Py_ssize_t extent1, - * Py_ssize_t extent2) except -1 with gil: - * raise ValueError("got differing extents in dimension %d (got %d and %d)" % # <<<<<<<<<<<<<< - * (i, extent1, extent2)) - * - */ - __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1253, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 1253, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __PYX_ERR(1, 1253, __pyx_L1_error) - - /* "View.MemoryView":1251 - * - * @cname('__pyx_memoryview_err_extents') - * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< - * Py_ssize_t extent2) except -1 with gil: - * raise ValueError("got differing extents in dimension %d (got %d and %d)" % - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("View.MemoryView._err_extents", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __Pyx_RefNannyFinishContext(); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - return __pyx_r; -} - -/* "View.MemoryView":1257 - * - * @cname('__pyx_memoryview_err_dim') - * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< - * raise error(msg.decode('ascii') % dim) - * - */ - -static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, int __pyx_v_dim) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_RefNannySetupContext("_err_dim", 0); - __Pyx_INCREF(__pyx_v_error); - - /* "View.MemoryView":1258 - * @cname('__pyx_memoryview_err_dim') - * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: - * raise error(msg.decode('ascii') % dim) # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_err') - */ - __pyx_t_2 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1258, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1258, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyUnicode_Format(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 1258, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_INCREF(__pyx_v_error); - __pyx_t_3 = __pyx_v_error; __pyx_t_2 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_2)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_1 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_2, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1258, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 1258, __pyx_L1_error) - - /* "View.MemoryView":1257 - * - * @cname('__pyx_memoryview_err_dim') - * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< - * raise error(msg.decode('ascii') % dim) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __Pyx_XDECREF(__pyx_v_error); - __Pyx_RefNannyFinishContext(); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - return __pyx_r; -} - -/* "View.MemoryView":1261 - * - * @cname('__pyx_memoryview_err') - * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< - * if msg != NULL: - * raise error(msg.decode('ascii')) - */ - -static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_RefNannySetupContext("_err", 0); - __Pyx_INCREF(__pyx_v_error); - - /* "View.MemoryView":1262 - * @cname('__pyx_memoryview_err') - * cdef int _err(object error, char *msg) except -1 with gil: - * if msg != NULL: # <<<<<<<<<<<<<< - * raise error(msg.decode('ascii')) - * else: - */ - __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":1263 - * cdef int _err(object error, char *msg) except -1 with gil: - * if msg != NULL: - * raise error(msg.decode('ascii')) # <<<<<<<<<<<<<< - * else: - * raise error - */ - __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1263, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_error); - __pyx_t_4 = __pyx_v_error; __pyx_t_5 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - __pyx_t_2 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_5, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1263, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __PYX_ERR(1, 1263, __pyx_L1_error) - - /* "View.MemoryView":1262 - * @cname('__pyx_memoryview_err') - * cdef int _err(object error, char *msg) except -1 with gil: - * if msg != NULL: # <<<<<<<<<<<<<< - * raise error(msg.decode('ascii')) - * else: - */ - } - - /* "View.MemoryView":1265 - * raise error(msg.decode('ascii')) - * else: - * raise error # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_copy_contents') - */ - /*else*/ { - __Pyx_Raise(__pyx_v_error, 0, 0, 0); - __PYX_ERR(1, 1265, __pyx_L1_error) - } - - /* "View.MemoryView":1261 - * - * @cname('__pyx_memoryview_err') - * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< - * if msg != NULL: - * raise error(msg.decode('ascii')) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __Pyx_XDECREF(__pyx_v_error); - __Pyx_RefNannyFinishContext(); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - return __pyx_r; -} - -/* "View.MemoryView":1268 - * - * @cname('__pyx_memoryview_copy_contents') - * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< - * __Pyx_memviewslice dst, - * int src_ndim, int dst_ndim, - */ - -static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_memviewslice __pyx_v_dst, int __pyx_v_src_ndim, int __pyx_v_dst_ndim, int __pyx_v_dtype_is_object) { - void *__pyx_v_tmpdata; - size_t __pyx_v_itemsize; - int __pyx_v_i; - char __pyx_v_order; - int __pyx_v_broadcasting; - int __pyx_v_direct_copy; - __Pyx_memviewslice __pyx_v_tmp; - int __pyx_v_ndim; - int __pyx_r; - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - void *__pyx_t_7; - int __pyx_t_8; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - - /* "View.MemoryView":1276 - * Check for overlapping memory and verify the shapes. - * """ - * cdef void *tmpdata = NULL # <<<<<<<<<<<<<< - * cdef size_t itemsize = src.memview.view.itemsize - * cdef int i - */ - __pyx_v_tmpdata = NULL; - - /* "View.MemoryView":1277 - * """ - * cdef void *tmpdata = NULL - * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< - * cdef int i - * cdef char order = get_best_order(&src, src_ndim) - */ - __pyx_t_1 = __pyx_v_src.memview->view.itemsize; - __pyx_v_itemsize = __pyx_t_1; - - /* "View.MemoryView":1279 - * cdef size_t itemsize = src.memview.view.itemsize - * cdef int i - * cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<< - * cdef bint broadcasting = False - * cdef bint direct_copy = False - */ - __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim); - - /* "View.MemoryView":1280 - * cdef int i - * cdef char order = get_best_order(&src, src_ndim) - * cdef bint broadcasting = False # <<<<<<<<<<<<<< - * cdef bint direct_copy = False - * cdef __Pyx_memviewslice tmp - */ - __pyx_v_broadcasting = 0; - - /* "View.MemoryView":1281 - * cdef char order = get_best_order(&src, src_ndim) - * cdef bint broadcasting = False - * cdef bint direct_copy = False # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice tmp - * - */ - __pyx_v_direct_copy = 0; - - /* "View.MemoryView":1284 - * cdef __Pyx_memviewslice tmp - * - * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< - * broadcast_leading(&src, src_ndim, dst_ndim) - * elif dst_ndim < src_ndim: - */ - __pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1285 - * - * if src_ndim < dst_ndim: - * broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<< - * elif dst_ndim < src_ndim: - * broadcast_leading(&dst, dst_ndim, src_ndim) - */ - __pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim); - - /* "View.MemoryView":1284 - * cdef __Pyx_memviewslice tmp - * - * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< - * broadcast_leading(&src, src_ndim, dst_ndim) - * elif dst_ndim < src_ndim: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":1286 - * if src_ndim < dst_ndim: - * broadcast_leading(&src, src_ndim, dst_ndim) - * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< - * broadcast_leading(&dst, dst_ndim, src_ndim) - * - */ - __pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1287 - * broadcast_leading(&src, src_ndim, dst_ndim) - * elif dst_ndim < src_ndim: - * broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<< - * - * cdef int ndim = max(src_ndim, dst_ndim) - */ - __pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim); - - /* "View.MemoryView":1286 - * if src_ndim < dst_ndim: - * broadcast_leading(&src, src_ndim, dst_ndim) - * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< - * broadcast_leading(&dst, dst_ndim, src_ndim) - * - */ - } - __pyx_L3:; - - /* "View.MemoryView":1289 - * broadcast_leading(&dst, dst_ndim, src_ndim) - * - * cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<< - * - * for i in range(ndim): - */ - __pyx_t_3 = __pyx_v_dst_ndim; - __pyx_t_4 = __pyx_v_src_ndim; - if (((__pyx_t_3 > __pyx_t_4) != 0)) { - __pyx_t_5 = __pyx_t_3; - } else { - __pyx_t_5 = __pyx_t_4; - } - __pyx_v_ndim = __pyx_t_5; - - /* "View.MemoryView":1291 - * cdef int ndim = max(src_ndim, dst_ndim) - * - * for i in range(ndim): # <<<<<<<<<<<<<< - * if src.shape[i] != dst.shape[i]: - * if src.shape[i] == 1: - */ - __pyx_t_5 = __pyx_v_ndim; - __pyx_t_3 = __pyx_t_5; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_i = __pyx_t_4; - - /* "View.MemoryView":1292 - * - * for i in range(ndim): - * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< - * if src.shape[i] == 1: - * broadcasting = True - */ - __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1293 - * for i in range(ndim): - * if src.shape[i] != dst.shape[i]: - * if src.shape[i] == 1: # <<<<<<<<<<<<<< - * broadcasting = True - * src.strides[i] = 0 - */ - __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1294 - * if src.shape[i] != dst.shape[i]: - * if src.shape[i] == 1: - * broadcasting = True # <<<<<<<<<<<<<< - * src.strides[i] = 0 - * else: - */ - __pyx_v_broadcasting = 1; - - /* "View.MemoryView":1295 - * if src.shape[i] == 1: - * broadcasting = True - * src.strides[i] = 0 # <<<<<<<<<<<<<< - * else: - * _err_extents(i, dst.shape[i], src.shape[i]) - */ - (__pyx_v_src.strides[__pyx_v_i]) = 0; - - /* "View.MemoryView":1293 - * for i in range(ndim): - * if src.shape[i] != dst.shape[i]: - * if src.shape[i] == 1: # <<<<<<<<<<<<<< - * broadcasting = True - * src.strides[i] = 0 - */ - goto __pyx_L7; - } - - /* "View.MemoryView":1297 - * src.strides[i] = 0 - * else: - * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< - * - * if src.suboffsets[i] >= 0: - */ - /*else*/ { - __pyx_t_6 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(1, 1297, __pyx_L1_error) - } - __pyx_L7:; - - /* "View.MemoryView":1292 - * - * for i in range(ndim): - * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< - * if src.shape[i] == 1: - * broadcasting = True - */ - } - - /* "View.MemoryView":1299 - * _err_extents(i, dst.shape[i], src.shape[i]) - * - * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< - * _err_dim(ValueError, "Dimension %d is not direct", i) - * - */ - __pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1300 - * - * if src.suboffsets[i] >= 0: - * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< - * - * if slices_overlap(&src, &dst, ndim, itemsize): - */ - __pyx_t_6 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, ((char *)"Dimension %d is not direct"), __pyx_v_i); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(1, 1300, __pyx_L1_error) - - /* "View.MemoryView":1299 - * _err_extents(i, dst.shape[i], src.shape[i]) - * - * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< - * _err_dim(ValueError, "Dimension %d is not direct", i) - * - */ - } - } - - /* "View.MemoryView":1302 - * _err_dim(ValueError, "Dimension %d is not direct", i) - * - * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< - * - * if not slice_is_contig(src, order, ndim): - */ - __pyx_t_2 = (__pyx_slices_overlap((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1304 - * if slices_overlap(&src, &dst, ndim, itemsize): - * - * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< - * order = get_best_order(&dst, ndim) - * - */ - __pyx_t_2 = ((!(__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1305 - * - * if not slice_is_contig(src, order, ndim): - * order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<< - * - * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) - */ - __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim); - - /* "View.MemoryView":1304 - * if slices_overlap(&src, &dst, ndim, itemsize): - * - * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< - * order = get_best_order(&dst, ndim) - * - */ - } - - /* "View.MemoryView":1307 - * order = get_best_order(&dst, ndim) - * - * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< - * src = tmp - * - */ - __pyx_t_7 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_7 == ((void *)NULL))) __PYX_ERR(1, 1307, __pyx_L1_error) - __pyx_v_tmpdata = __pyx_t_7; - - /* "View.MemoryView":1308 - * - * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) - * src = tmp # <<<<<<<<<<<<<< - * - * if not broadcasting: - */ - __pyx_v_src = __pyx_v_tmp; - - /* "View.MemoryView":1302 - * _err_dim(ValueError, "Dimension %d is not direct", i) - * - * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< - * - * if not slice_is_contig(src, order, ndim): - */ - } - - /* "View.MemoryView":1310 - * src = tmp - * - * if not broadcasting: # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1313 - * - * - * if slice_is_contig(src, 'C', ndim): # <<<<<<<<<<<<<< - * direct_copy = slice_is_contig(dst, 'C', ndim) - * elif slice_is_contig(src, 'F', ndim): - */ - __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, 'C', __pyx_v_ndim) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1314 - * - * if slice_is_contig(src, 'C', ndim): - * direct_copy = slice_is_contig(dst, 'C', ndim) # <<<<<<<<<<<<<< - * elif slice_is_contig(src, 'F', ndim): - * direct_copy = slice_is_contig(dst, 'F', ndim) - */ - __pyx_v_direct_copy = __pyx_memviewslice_is_contig(__pyx_v_dst, 'C', __pyx_v_ndim); - - /* "View.MemoryView":1313 - * - * - * if slice_is_contig(src, 'C', ndim): # <<<<<<<<<<<<<< - * direct_copy = slice_is_contig(dst, 'C', ndim) - * elif slice_is_contig(src, 'F', ndim): - */ - goto __pyx_L12; - } - - /* "View.MemoryView":1315 - * if slice_is_contig(src, 'C', ndim): - * direct_copy = slice_is_contig(dst, 'C', ndim) - * elif slice_is_contig(src, 'F', ndim): # <<<<<<<<<<<<<< - * direct_copy = slice_is_contig(dst, 'F', ndim) - * - */ - __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, 'F', __pyx_v_ndim) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1316 - * direct_copy = slice_is_contig(dst, 'C', ndim) - * elif slice_is_contig(src, 'F', ndim): - * direct_copy = slice_is_contig(dst, 'F', ndim) # <<<<<<<<<<<<<< - * - * if direct_copy: - */ - __pyx_v_direct_copy = __pyx_memviewslice_is_contig(__pyx_v_dst, 'F', __pyx_v_ndim); - - /* "View.MemoryView":1315 - * if slice_is_contig(src, 'C', ndim): - * direct_copy = slice_is_contig(dst, 'C', ndim) - * elif slice_is_contig(src, 'F', ndim): # <<<<<<<<<<<<<< - * direct_copy = slice_is_contig(dst, 'F', ndim) - * - */ - } - __pyx_L12:; - - /* "View.MemoryView":1318 - * direct_copy = slice_is_contig(dst, 'F', ndim) - * - * if direct_copy: # <<<<<<<<<<<<<< - * - * refcount_copying(&dst, dtype_is_object, ndim, False) - */ - __pyx_t_2 = (__pyx_v_direct_copy != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1320 - * if direct_copy: - * - * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< - * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) - * refcount_copying(&dst, dtype_is_object, ndim, True) - */ - __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); - - /* "View.MemoryView":1321 - * - * refcount_copying(&dst, dtype_is_object, ndim, False) - * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< - * refcount_copying(&dst, dtype_is_object, ndim, True) - * free(tmpdata) - */ - (void)(memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim))); - - /* "View.MemoryView":1322 - * refcount_copying(&dst, dtype_is_object, ndim, False) - * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) - * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< - * free(tmpdata) - * return 0 - */ - __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); - - /* "View.MemoryView":1323 - * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) - * refcount_copying(&dst, dtype_is_object, ndim, True) - * free(tmpdata) # <<<<<<<<<<<<<< - * return 0 - * - */ - free(__pyx_v_tmpdata); - - /* "View.MemoryView":1324 - * refcount_copying(&dst, dtype_is_object, ndim, True) - * free(tmpdata) - * return 0 # <<<<<<<<<<<<<< - * - * if order == 'F' == get_best_order(&dst, ndim): - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "View.MemoryView":1318 - * direct_copy = slice_is_contig(dst, 'F', ndim) - * - * if direct_copy: # <<<<<<<<<<<<<< - * - * refcount_copying(&dst, dtype_is_object, ndim, False) - */ - } - - /* "View.MemoryView":1310 - * src = tmp - * - * if not broadcasting: # <<<<<<<<<<<<<< - * - * - */ - } - - /* "View.MemoryView":1326 - * return 0 - * - * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_2 = (__pyx_v_order == 'F'); - if (__pyx_t_2) { - __pyx_t_2 = ('F' == __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim)); - } - __pyx_t_8 = (__pyx_t_2 != 0); - if (__pyx_t_8) { - - /* "View.MemoryView":1329 - * - * - * transpose_memslice(&src) # <<<<<<<<<<<<<< - * transpose_memslice(&dst) - * - */ - __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(1, 1329, __pyx_L1_error) - - /* "View.MemoryView":1330 - * - * transpose_memslice(&src) - * transpose_memslice(&dst) # <<<<<<<<<<<<<< - * - * refcount_copying(&dst, dtype_is_object, ndim, False) - */ - __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(1, 1330, __pyx_L1_error) - - /* "View.MemoryView":1326 - * return 0 - * - * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< - * - * - */ - } - - /* "View.MemoryView":1332 - * transpose_memslice(&dst) - * - * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< - * copy_strided_to_strided(&src, &dst, ndim, itemsize) - * refcount_copying(&dst, dtype_is_object, ndim, True) - */ - __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); - - /* "View.MemoryView":1333 - * - * refcount_copying(&dst, dtype_is_object, ndim, False) - * copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<< - * refcount_copying(&dst, dtype_is_object, ndim, True) - * - */ - copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize); - - /* "View.MemoryView":1334 - * refcount_copying(&dst, dtype_is_object, ndim, False) - * copy_strided_to_strided(&src, &dst, ndim, itemsize) - * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< - * - * free(tmpdata) - */ - __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); - - /* "View.MemoryView":1336 - * refcount_copying(&dst, dtype_is_object, ndim, True) - * - * free(tmpdata) # <<<<<<<<<<<<<< - * return 0 - * - */ - free(__pyx_v_tmpdata); - - /* "View.MemoryView":1337 - * - * free(tmpdata) - * return 0 # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_broadcast_leading') - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "View.MemoryView":1268 - * - * @cname('__pyx_memoryview_copy_contents') - * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< - * __Pyx_memviewslice dst, - * int src_ndim, int dst_ndim, - */ - - /* function exit code */ - __pyx_L1_error:; - { - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - } - __pyx_r = -1; - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1340 - * - * @cname('__pyx_memoryview_broadcast_leading') - * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< - * int ndim, - * int ndim_other) nogil: - */ - -static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim, int __pyx_v_ndim_other) { - int __pyx_v_i; - int __pyx_v_offset; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - - /* "View.MemoryView":1344 - * int ndim_other) nogil: - * cdef int i - * cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<< - * - * for i in range(ndim - 1, -1, -1): - */ - __pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim); - - /* "View.MemoryView":1346 - * cdef int offset = ndim_other - ndim - * - * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< - * mslice.shape[i + offset] = mslice.shape[i] - * mslice.strides[i + offset] = mslice.strides[i] - */ - for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { - __pyx_v_i = __pyx_t_1; - - /* "View.MemoryView":1347 - * - * for i in range(ndim - 1, -1, -1): - * mslice.shape[i + offset] = mslice.shape[i] # <<<<<<<<<<<<<< - * mslice.strides[i + offset] = mslice.strides[i] - * mslice.suboffsets[i + offset] = mslice.suboffsets[i] - */ - (__pyx_v_mslice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->shape[__pyx_v_i]); - - /* "View.MemoryView":1348 - * for i in range(ndim - 1, -1, -1): - * mslice.shape[i + offset] = mslice.shape[i] - * mslice.strides[i + offset] = mslice.strides[i] # <<<<<<<<<<<<<< - * mslice.suboffsets[i + offset] = mslice.suboffsets[i] - * - */ - (__pyx_v_mslice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->strides[__pyx_v_i]); - - /* "View.MemoryView":1349 - * mslice.shape[i + offset] = mslice.shape[i] - * mslice.strides[i + offset] = mslice.strides[i] - * mslice.suboffsets[i + offset] = mslice.suboffsets[i] # <<<<<<<<<<<<<< - * - * for i in range(offset): - */ - (__pyx_v_mslice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->suboffsets[__pyx_v_i]); - } - - /* "View.MemoryView":1351 - * mslice.suboffsets[i + offset] = mslice.suboffsets[i] - * - * for i in range(offset): # <<<<<<<<<<<<<< - * mslice.shape[i] = 1 - * mslice.strides[i] = mslice.strides[0] - */ - __pyx_t_1 = __pyx_v_offset; - __pyx_t_2 = __pyx_t_1; - for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { - __pyx_v_i = __pyx_t_3; - - /* "View.MemoryView":1352 - * - * for i in range(offset): - * mslice.shape[i] = 1 # <<<<<<<<<<<<<< - * mslice.strides[i] = mslice.strides[0] - * mslice.suboffsets[i] = -1 - */ - (__pyx_v_mslice->shape[__pyx_v_i]) = 1; - - /* "View.MemoryView":1353 - * for i in range(offset): - * mslice.shape[i] = 1 - * mslice.strides[i] = mslice.strides[0] # <<<<<<<<<<<<<< - * mslice.suboffsets[i] = -1 - * - */ - (__pyx_v_mslice->strides[__pyx_v_i]) = (__pyx_v_mslice->strides[0]); - - /* "View.MemoryView":1354 - * mslice.shape[i] = 1 - * mslice.strides[i] = mslice.strides[0] - * mslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< - * - * - */ - (__pyx_v_mslice->suboffsets[__pyx_v_i]) = -1L; - } - - /* "View.MemoryView":1340 - * - * @cname('__pyx_memoryview_broadcast_leading') - * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< - * int ndim, - * int ndim_other) nogil: - */ - - /* function exit code */ -} - -/* "View.MemoryView":1362 - * - * @cname('__pyx_memoryview_refcount_copying') - * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< - * int ndim, bint inc) nogil: - * - */ - -static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_dtype_is_object, int __pyx_v_ndim, int __pyx_v_inc) { - int __pyx_t_1; - - /* "View.MemoryView":1366 - * - * - * if dtype_is_object: # <<<<<<<<<<<<<< - * refcount_objects_in_slice_with_gil(dst.data, dst.shape, - * dst.strides, ndim, inc) - */ - __pyx_t_1 = (__pyx_v_dtype_is_object != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1367 - * - * if dtype_is_object: - * refcount_objects_in_slice_with_gil(dst.data, dst.shape, # <<<<<<<<<<<<<< - * dst.strides, ndim, inc) - * - */ - __pyx_memoryview_refcount_objects_in_slice_with_gil(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_inc); - - /* "View.MemoryView":1366 - * - * - * if dtype_is_object: # <<<<<<<<<<<<<< - * refcount_objects_in_slice_with_gil(dst.data, dst.shape, - * dst.strides, ndim, inc) - */ - } - - /* "View.MemoryView":1362 - * - * @cname('__pyx_memoryview_refcount_copying') - * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< - * int ndim, bint inc) nogil: - * - */ - - /* function exit code */ -} - -/* "View.MemoryView":1371 - * - * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') - * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< - * Py_ssize_t *strides, int ndim, - * bint inc) with gil: - */ - -static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { - __Pyx_RefNannyDeclarations - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); - - /* "View.MemoryView":1374 - * Py_ssize_t *strides, int ndim, - * bint inc) with gil: - * refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_refcount_objects_in_slice') - */ - __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc); - - /* "View.MemoryView":1371 - * - * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') - * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< - * Py_ssize_t *strides, int ndim, - * bint inc) with gil: - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif -} - -/* "View.MemoryView":1377 - * - * @cname('__pyx_memoryview_refcount_objects_in_slice') - * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< - * Py_ssize_t *strides, int ndim, bint inc): - * cdef Py_ssize_t i - */ - -static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { - CYTHON_UNUSED Py_ssize_t __pyx_v_i; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - Py_ssize_t __pyx_t_2; - Py_ssize_t __pyx_t_3; - int __pyx_t_4; - __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); - - /* "View.MemoryView":1381 - * cdef Py_ssize_t i - * - * for i in range(shape[0]): # <<<<<<<<<<<<<< - * if ndim == 1: - * if inc: - */ - __pyx_t_1 = (__pyx_v_shape[0]); - __pyx_t_2 = __pyx_t_1; - for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { - __pyx_v_i = __pyx_t_3; - - /* "View.MemoryView":1382 - * - * for i in range(shape[0]): - * if ndim == 1: # <<<<<<<<<<<<<< - * if inc: - * Py_INCREF(( data)[0]) - */ - __pyx_t_4 = ((__pyx_v_ndim == 1) != 0); - if (__pyx_t_4) { - - /* "View.MemoryView":1383 - * for i in range(shape[0]): - * if ndim == 1: - * if inc: # <<<<<<<<<<<<<< - * Py_INCREF(( data)[0]) - * else: - */ - __pyx_t_4 = (__pyx_v_inc != 0); - if (__pyx_t_4) { - - /* "View.MemoryView":1384 - * if ndim == 1: - * if inc: - * Py_INCREF(( data)[0]) # <<<<<<<<<<<<<< - * else: - * Py_DECREF(( data)[0]) - */ - Py_INCREF((((PyObject **)__pyx_v_data)[0])); - - /* "View.MemoryView":1383 - * for i in range(shape[0]): - * if ndim == 1: - * if inc: # <<<<<<<<<<<<<< - * Py_INCREF(( data)[0]) - * else: - */ - goto __pyx_L6; - } - - /* "View.MemoryView":1386 - * Py_INCREF(( data)[0]) - * else: - * Py_DECREF(( data)[0]) # <<<<<<<<<<<<<< - * else: - * refcount_objects_in_slice(data, shape + 1, strides + 1, - */ - /*else*/ { - Py_DECREF((((PyObject **)__pyx_v_data)[0])); - } - __pyx_L6:; - - /* "View.MemoryView":1382 - * - * for i in range(shape[0]): - * if ndim == 1: # <<<<<<<<<<<<<< - * if inc: - * Py_INCREF(( data)[0]) - */ - goto __pyx_L5; - } - - /* "View.MemoryView":1388 - * Py_DECREF(( data)[0]) - * else: - * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< - * ndim - 1, inc) - * - */ - /*else*/ { - - /* "View.MemoryView":1389 - * else: - * refcount_objects_in_slice(data, shape + 1, strides + 1, - * ndim - 1, inc) # <<<<<<<<<<<<<< - * - * data += strides[0] - */ - __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_inc); - } - __pyx_L5:; - - /* "View.MemoryView":1391 - * ndim - 1, inc) - * - * data += strides[0] # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); - } - - /* "View.MemoryView":1377 - * - * @cname('__pyx_memoryview_refcount_objects_in_slice') - * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< - * Py_ssize_t *strides, int ndim, bint inc): - * cdef Py_ssize_t i - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "View.MemoryView":1397 - * - * @cname('__pyx_memoryview_slice_assign_scalar') - * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< - * size_t itemsize, void *item, - * bint dtype_is_object) nogil: - */ - -static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item, int __pyx_v_dtype_is_object) { - - /* "View.MemoryView":1400 - * size_t itemsize, void *item, - * bint dtype_is_object) nogil: - * refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< - * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, - * itemsize, item) - */ - __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0); - - /* "View.MemoryView":1401 - * bint dtype_is_object) nogil: - * refcount_copying(dst, dtype_is_object, ndim, False) - * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, # <<<<<<<<<<<<<< - * itemsize, item) - * refcount_copying(dst, dtype_is_object, ndim, True) - */ - __pyx_memoryview__slice_assign_scalar(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_itemsize, __pyx_v_item); - - /* "View.MemoryView":1403 - * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, - * itemsize, item) - * refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< - * - * - */ - __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1); - - /* "View.MemoryView":1397 - * - * @cname('__pyx_memoryview_slice_assign_scalar') - * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< - * size_t itemsize, void *item, - * bint dtype_is_object) nogil: - */ - - /* function exit code */ -} - -/* "View.MemoryView":1407 - * - * @cname('__pyx_memoryview__slice_assign_scalar') - * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< - * Py_ssize_t *strides, int ndim, - * size_t itemsize, void *item) nogil: - */ - -static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item) { - CYTHON_UNUSED Py_ssize_t __pyx_v_i; - Py_ssize_t __pyx_v_stride; - Py_ssize_t __pyx_v_extent; - int __pyx_t_1; - Py_ssize_t __pyx_t_2; - Py_ssize_t __pyx_t_3; - Py_ssize_t __pyx_t_4; - - /* "View.MemoryView":1411 - * size_t itemsize, void *item) nogil: - * cdef Py_ssize_t i - * cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<< - * cdef Py_ssize_t extent = shape[0] - * - */ - __pyx_v_stride = (__pyx_v_strides[0]); - - /* "View.MemoryView":1412 - * cdef Py_ssize_t i - * cdef Py_ssize_t stride = strides[0] - * cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<< - * - * if ndim == 1: - */ - __pyx_v_extent = (__pyx_v_shape[0]); - - /* "View.MemoryView":1414 - * cdef Py_ssize_t extent = shape[0] - * - * if ndim == 1: # <<<<<<<<<<<<<< - * for i in range(extent): - * memcpy(data, item, itemsize) - */ - __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1415 - * - * if ndim == 1: - * for i in range(extent): # <<<<<<<<<<<<<< - * memcpy(data, item, itemsize) - * data += stride - */ - __pyx_t_2 = __pyx_v_extent; - __pyx_t_3 = __pyx_t_2; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_i = __pyx_t_4; - - /* "View.MemoryView":1416 - * if ndim == 1: - * for i in range(extent): - * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< - * data += stride - * else: - */ - (void)(memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize)); - - /* "View.MemoryView":1417 - * for i in range(extent): - * memcpy(data, item, itemsize) - * data += stride # <<<<<<<<<<<<<< - * else: - * for i in range(extent): - */ - __pyx_v_data = (__pyx_v_data + __pyx_v_stride); - } - - /* "View.MemoryView":1414 - * cdef Py_ssize_t extent = shape[0] - * - * if ndim == 1: # <<<<<<<<<<<<<< - * for i in range(extent): - * memcpy(data, item, itemsize) - */ - goto __pyx_L3; - } - - /* "View.MemoryView":1419 - * data += stride - * else: - * for i in range(extent): # <<<<<<<<<<<<<< - * _slice_assign_scalar(data, shape + 1, strides + 1, - * ndim - 1, itemsize, item) - */ - /*else*/ { - __pyx_t_2 = __pyx_v_extent; - __pyx_t_3 = __pyx_t_2; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_i = __pyx_t_4; - - /* "View.MemoryView":1420 - * else: - * for i in range(extent): - * _slice_assign_scalar(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< - * ndim - 1, itemsize, item) - * data += stride - */ - __pyx_memoryview__slice_assign_scalar(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize, __pyx_v_item); - - /* "View.MemoryView":1422 - * _slice_assign_scalar(data, shape + 1, strides + 1, - * ndim - 1, itemsize, item) - * data += stride # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_data = (__pyx_v_data + __pyx_v_stride); - } - } - __pyx_L3:; - - /* "View.MemoryView":1407 - * - * @cname('__pyx_memoryview__slice_assign_scalar') - * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< - * Py_ssize_t *strides, int ndim, - * size_t itemsize, void *item) nogil: - */ - - /* function exit code */ -} - -/* "(tree fragment)":1 - * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_15View_dot_MemoryView_1__pyx_unpickle_Enum = {"__pyx_unpickle_Enum", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum, METH_VARARGS|METH_KEYWORDS, 0}; -static PyObject *__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v___pyx_type = 0; - long __pyx_v___pyx_checksum; - PyObject *__pyx_v___pyx_state = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__pyx_unpickle_Enum (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pyx_type,&__pyx_n_s_pyx_checksum,&__pyx_n_s_pyx_state,0}; - PyObject* values[3] = {0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_type)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_checksum)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, 1); __PYX_ERR(1, 1, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_state)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, 2); __PYX_ERR(1, 1, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_unpickle_Enum") < 0)) __PYX_ERR(1, 1, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - } - __pyx_v___pyx_type = values[0]; - __pyx_v___pyx_checksum = __Pyx_PyInt_As_long(values[1]); if (unlikely((__pyx_v___pyx_checksum == (long)-1) && PyErr_Occurred())) __PYX_ERR(1, 1, __pyx_L3_error) - __pyx_v___pyx_state = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 1, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(__pyx_self, __pyx_v___pyx_type, __pyx_v___pyx_checksum, __pyx_v___pyx_state); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_v___pyx_PickleError = 0; - PyObject *__pyx_v___pyx_result = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__pyx_unpickle_Enum", 0); - - /* "(tree fragment)":4 - * cdef object __pyx_PickleError - * cdef object __pyx_result - * if __pyx_checksum != 0xb068931: # <<<<<<<<<<<<<< - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) - */ - __pyx_t_1 = ((__pyx_v___pyx_checksum != 0xb068931) != 0); - if (__pyx_t_1) { - - /* "(tree fragment)":5 - * cdef object __pyx_result - * if __pyx_checksum != 0xb068931: - * from pickle import PickleError as __pyx_PickleError # <<<<<<<<<<<<<< - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) - * __pyx_result = Enum.__new__(__pyx_type) - */ - __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_n_s_PickleError); - __Pyx_GIVEREF(__pyx_n_s_PickleError); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_PickleError); - __pyx_t_3 = __Pyx_Import(__pyx_n_s_pickle, __pyx_t_2, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_PickleError); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_2); - __pyx_v___pyx_PickleError = __pyx_t_2; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "(tree fragment)":6 - * if __pyx_checksum != 0xb068931: - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) # <<<<<<<<<<<<<< - * __pyx_result = Enum.__new__(__pyx_type) - * if __pyx_state is not None: - */ - __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v___pyx_checksum); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Incompatible_checksums_s_vs_0xb0, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_INCREF(__pyx_v___pyx_PickleError); - __pyx_t_2 = __pyx_v___pyx_PickleError; __pyx_t_5 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_3 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_5, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 6, __pyx_L1_error) - - /* "(tree fragment)":4 - * cdef object __pyx_PickleError - * cdef object __pyx_result - * if __pyx_checksum != 0xb068931: # <<<<<<<<<<<<<< - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) - */ - } - - /* "(tree fragment)":7 - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) - * __pyx_result = Enum.__new__(__pyx_type) # <<<<<<<<<<<<<< - * if __pyx_state is not None: - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_MemviewEnum_type), __pyx_n_s_new); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 7, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_3 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_4, __pyx_v___pyx_type) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v___pyx_type); - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 7, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v___pyx_result = __pyx_t_3; - __pyx_t_3 = 0; - - /* "(tree fragment)":8 - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) - * __pyx_result = Enum.__new__(__pyx_type) - * if __pyx_state is not None: # <<<<<<<<<<<<<< - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - * return __pyx_result - */ - __pyx_t_1 = (__pyx_v___pyx_state != Py_None); - __pyx_t_6 = (__pyx_t_1 != 0); - if (__pyx_t_6) { - - /* "(tree fragment)":9 - * __pyx_result = Enum.__new__(__pyx_type) - * if __pyx_state is not None: - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) # <<<<<<<<<<<<<< - * return __pyx_result - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): - */ - if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(1, 9, __pyx_L1_error) - __pyx_t_3 = __pyx_unpickle_Enum__set_state(((struct __pyx_MemviewEnum_obj *)__pyx_v___pyx_result), ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 9, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "(tree fragment)":8 - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) - * __pyx_result = Enum.__new__(__pyx_type) - * if __pyx_state is not None: # <<<<<<<<<<<<<< - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - * return __pyx_result - */ - } - - /* "(tree fragment)":10 - * if __pyx_state is not None: - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - * return __pyx_result # <<<<<<<<<<<<<< - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): - * __pyx_result.name = __pyx_state[0] - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v___pyx_result); - __pyx_r = __pyx_v___pyx_result; - goto __pyx_L0; - - /* "(tree fragment)":1 - * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v___pyx_PickleError); - __Pyx_XDECREF(__pyx_v___pyx_result); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":11 - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - * return __pyx_result - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< - * __pyx_result.name = __pyx_state[0] - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): - */ - -static PyObject *__pyx_unpickle_Enum__set_state(struct __pyx_MemviewEnum_obj *__pyx_v___pyx_result, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - Py_ssize_t __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__pyx_unpickle_Enum__set_state", 0); - - /* "(tree fragment)":12 - * return __pyx_result - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): - * __pyx_result.name = __pyx_state[0] # <<<<<<<<<<<<<< - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): - * __pyx_result.__dict__.update(__pyx_state[1]) - */ - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->name); - __Pyx_DECREF(__pyx_v___pyx_result->name); - __pyx_v___pyx_result->name = __pyx_t_1; - __pyx_t_1 = 0; - - /* "(tree fragment)":13 - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): - * __pyx_result.name = __pyx_state[0] - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< - * __pyx_result.__dict__.update(__pyx_state[1]) - */ - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - __PYX_ERR(1, 13, __pyx_L1_error) - } - __pyx_t_3 = PyTuple_GET_SIZE(__pyx_v___pyx_state); if (unlikely(__pyx_t_3 == ((Py_ssize_t)-1))) __PYX_ERR(1, 13, __pyx_L1_error) - __pyx_t_4 = ((__pyx_t_3 > 1) != 0); - if (__pyx_t_4) { - } else { - __pyx_t_2 = __pyx_t_4; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_4 = __Pyx_HasAttr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 13, __pyx_L1_error) - __pyx_t_5 = (__pyx_t_4 != 0); - __pyx_t_2 = __pyx_t_5; - __pyx_L4_bool_binop_done:; - if (__pyx_t_2) { - - /* "(tree fragment)":14 - * __pyx_result.name = __pyx_state[0] - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): - * __pyx_result.__dict__.update(__pyx_state[1]) # <<<<<<<<<<<<<< - */ - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_update); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 14, __pyx_L1_error) - } - __pyx_t_6 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_8 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_8)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_8); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - } - } - __pyx_t_1 = (__pyx_t_8) ? __Pyx_PyObject_Call2Args(__pyx_t_7, __pyx_t_8, __pyx_t_6) : __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_6); - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "(tree fragment)":13 - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): - * __pyx_result.name = __pyx_state[0] - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< - * __pyx_result.__dict__.update(__pyx_state[1]) - */ - } - - /* "(tree fragment)":11 - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - * return __pyx_result - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< - * __pyx_result.name = __pyx_state[0] - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -static struct __pyx_vtabstruct_array __pyx_vtable_array; - -static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_array_obj *p; - PyObject *o; - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - p = ((struct __pyx_array_obj *)o); - p->__pyx_vtab = __pyx_vtabptr_array; - p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); - if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) goto bad; - return o; - bad: - Py_DECREF(o); o = 0; - return NULL; -} - -static void __pyx_tp_dealloc_array(PyObject *o) { - struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; - #if CYTHON_USE_TP_FINALIZE - if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - { - PyObject *etype, *eval, *etb; - PyErr_Fetch(&etype, &eval, &etb); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); - __pyx_array___dealloc__(o); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); - PyErr_Restore(etype, eval, etb); - } - Py_CLEAR(p->mode); - Py_CLEAR(p->_format); - (*Py_TYPE(o)->tp_free)(o); -} -static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { - PyObject *r; - PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; - r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); - Py_DECREF(x); - return r; -} - -static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { - if (v) { - return __pyx_array___setitem__(o, i, v); - } - else { - PyErr_Format(PyExc_NotImplementedError, - "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); - return -1; - } -} - -static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { - PyObject *v = __Pyx_PyObject_GenericGetAttr(o, n); - if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - v = __pyx_array___getattr__(o, n); - } - return v; -} - -static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(o); -} - -static PyMethodDef __pyx_methods_array[] = { - {"__getattr__", (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, 0}, - {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_array_1__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_array_3__setstate_cython__, METH_O, 0}, - {0, 0, 0, 0} -}; - -static struct PyGetSetDef __pyx_getsets_array[] = { - {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, (char *)0, 0}, - {0, 0, 0, 0, 0} -}; - -static PySequenceMethods __pyx_tp_as_sequence_array = { - __pyx_array___len__, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - __pyx_sq_item_array, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyMappingMethods __pyx_tp_as_mapping_array = { - __pyx_array___len__, /*mp_length*/ - __pyx_array___getitem__, /*mp_subscript*/ - __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ -}; - -static PyBufferProcs __pyx_tp_as_buffer_array = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - __pyx_array_getbuffer, /*bf_getbuffer*/ - 0, /*bf_releasebuffer*/ -}; - -static PyTypeObject __pyx_type___pyx_array = { - PyVarObject_HEAD_INIT(0, 0) - "monotonic_align.core.array", /*tp_name*/ - sizeof(struct __pyx_array_obj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_array, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - &__pyx_tp_as_sequence_array, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_array, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - __pyx_tp_getattro_array, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_array, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_array, /*tp_methods*/ - 0, /*tp_members*/ - __pyx_getsets_array, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_array, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif -}; - -static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - struct __pyx_MemviewEnum_obj *p; - PyObject *o; - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - p = ((struct __pyx_MemviewEnum_obj *)o); - p->name = Py_None; Py_INCREF(Py_None); - return o; -} - -static void __pyx_tp_dealloc_Enum(PyObject *o) { - struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; - #if CYTHON_USE_TP_FINALIZE - if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - Py_CLEAR(p->name); - (*Py_TYPE(o)->tp_free)(o); -} - -static int __pyx_tp_traverse_Enum(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; - if (p->name) { - e = (*v)(p->name, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_Enum(PyObject *o) { - PyObject* tmp; - struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; - tmp = ((PyObject*)p->name); - p->name = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyMethodDef __pyx_methods_Enum[] = { - {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_MemviewEnum_1__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_MemviewEnum_3__setstate_cython__, METH_O, 0}, - {0, 0, 0, 0} -}; - -static PyTypeObject __pyx_type___pyx_MemviewEnum = { - PyVarObject_HEAD_INIT(0, 0) - "monotonic_align.core.Enum", /*tp_name*/ - sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_Enum, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - __pyx_MemviewEnum___repr__, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_Enum, /*tp_traverse*/ - __pyx_tp_clear_Enum, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_Enum, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - __pyx_MemviewEnum___init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_Enum, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif -}; -static struct __pyx_vtabstruct_memoryview __pyx_vtable_memoryview; - -static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_memoryview_obj *p; - PyObject *o; - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - p = ((struct __pyx_memoryview_obj *)o); - p->__pyx_vtab = __pyx_vtabptr_memoryview; - p->obj = Py_None; Py_INCREF(Py_None); - p->_size = Py_None; Py_INCREF(Py_None); - p->_array_interface = Py_None; Py_INCREF(Py_None); - p->view.obj = NULL; - if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) goto bad; - return o; - bad: - Py_DECREF(o); o = 0; - return NULL; -} - -static void __pyx_tp_dealloc_memoryview(PyObject *o) { - struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; - #if CYTHON_USE_TP_FINALIZE - if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - { - PyObject *etype, *eval, *etb; - PyErr_Fetch(&etype, &eval, &etb); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); - __pyx_memoryview___dealloc__(o); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); - PyErr_Restore(etype, eval, etb); - } - Py_CLEAR(p->obj); - Py_CLEAR(p->_size); - Py_CLEAR(p->_array_interface); - (*Py_TYPE(o)->tp_free)(o); -} - -static int __pyx_tp_traverse_memoryview(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; - if (p->obj) { - e = (*v)(p->obj, a); if (e) return e; - } - if (p->_size) { - e = (*v)(p->_size, a); if (e) return e; - } - if (p->_array_interface) { - e = (*v)(p->_array_interface, a); if (e) return e; - } - if (p->view.obj) { - e = (*v)(p->view.obj, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_memoryview(PyObject *o) { - PyObject* tmp; - struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; - tmp = ((PyObject*)p->obj); - p->obj = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->_size); - p->_size = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->_array_interface); - p->_array_interface = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - Py_CLEAR(p->view.obj); - return 0; -} -static PyObject *__pyx_sq_item_memoryview(PyObject *o, Py_ssize_t i) { - PyObject *r; - PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; - r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); - Py_DECREF(x); - return r; -} - -static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject *v) { - if (v) { - return __pyx_memoryview___setitem__(o, i, v); - } - else { - PyErr_Format(PyExc_NotImplementedError, - "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); - return -1; - } -} - -static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(o); -} - -static PyMethodDef __pyx_methods_memoryview[] = { - {"is_c_contig", (PyCFunction)__pyx_memoryview_is_c_contig, METH_NOARGS, 0}, - {"is_f_contig", (PyCFunction)__pyx_memoryview_is_f_contig, METH_NOARGS, 0}, - {"copy", (PyCFunction)__pyx_memoryview_copy, METH_NOARGS, 0}, - {"copy_fortran", (PyCFunction)__pyx_memoryview_copy_fortran, METH_NOARGS, 0}, - {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_memoryview_1__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_memoryview_3__setstate_cython__, METH_O, 0}, - {0, 0, 0, 0} -}; - -static struct PyGetSetDef __pyx_getsets_memoryview[] = { - {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, (char *)0, 0}, - {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, (char *)0, 0}, - {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, (char *)0, 0}, - {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, (char *)0, 0}, - {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, (char *)0, 0}, - {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, (char *)0, 0}, - {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, (char *)0, 0}, - {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, (char *)0, 0}, - {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, (char *)0, 0}, - {0, 0, 0, 0, 0} -}; - -static PySequenceMethods __pyx_tp_as_sequence_memoryview = { - __pyx_memoryview___len__, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - __pyx_sq_item_memoryview, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyMappingMethods __pyx_tp_as_mapping_memoryview = { - __pyx_memoryview___len__, /*mp_length*/ - __pyx_memoryview___getitem__, /*mp_subscript*/ - __pyx_mp_ass_subscript_memoryview, /*mp_ass_subscript*/ -}; - -static PyBufferProcs __pyx_tp_as_buffer_memoryview = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - __pyx_memoryview_getbuffer, /*bf_getbuffer*/ - 0, /*bf_releasebuffer*/ -}; - -static PyTypeObject __pyx_type___pyx_memoryview = { - PyVarObject_HEAD_INIT(0, 0) - "monotonic_align.core.memoryview", /*tp_name*/ - sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_memoryview, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - __pyx_memoryview___repr__, /*tp_repr*/ - 0, /*tp_as_number*/ - &__pyx_tp_as_sequence_memoryview, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_memoryview, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - __pyx_memoryview___str__, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_memoryview, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_memoryview, /*tp_traverse*/ - __pyx_tp_clear_memoryview, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_memoryview, /*tp_methods*/ - 0, /*tp_members*/ - __pyx_getsets_memoryview, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_memoryview, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif -}; -static struct __pyx_vtabstruct__memoryviewslice __pyx_vtable__memoryviewslice; - -static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_memoryviewslice_obj *p; - PyObject *o = __pyx_tp_new_memoryview(t, a, k); - if (unlikely(!o)) return 0; - p = ((struct __pyx_memoryviewslice_obj *)o); - p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_memoryview*)__pyx_vtabptr__memoryviewslice; - p->from_object = Py_None; Py_INCREF(Py_None); - p->from_slice.memview = NULL; - return o; -} - -static void __pyx_tp_dealloc__memoryviewslice(PyObject *o) { - struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; - #if CYTHON_USE_TP_FINALIZE - if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - { - PyObject *etype, *eval, *etb; - PyErr_Fetch(&etype, &eval, &etb); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); - __pyx_memoryviewslice___dealloc__(o); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); - PyErr_Restore(etype, eval, etb); - } - Py_CLEAR(p->from_object); - PyObject_GC_Track(o); - __pyx_tp_dealloc_memoryview(o); -} - -static int __pyx_tp_traverse__memoryviewslice(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; - e = __pyx_tp_traverse_memoryview(o, v, a); if (e) return e; - if (p->from_object) { - e = (*v)(p->from_object, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear__memoryviewslice(PyObject *o) { - PyObject* tmp; - struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; - __pyx_tp_clear_memoryview(o); - tmp = ((PyObject*)p->from_object); - p->from_object = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - __PYX_XDEC_MEMVIEW(&p->from_slice, 1); - return 0; -} - -static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(o); -} - -static PyMethodDef __pyx_methods__memoryviewslice[] = { - {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_memoryviewslice_1__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_memoryviewslice_3__setstate_cython__, METH_O, 0}, - {0, 0, 0, 0} -}; - -static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { - {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, (char *)0, 0}, - {0, 0, 0, 0, 0} -}; - -static PyTypeObject __pyx_type___pyx_memoryviewslice = { - PyVarObject_HEAD_INIT(0, 0) - "monotonic_align.core._memoryviewslice", /*tp_name*/ - sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - #if CYTHON_COMPILING_IN_PYPY - __pyx_memoryview___repr__, /*tp_repr*/ - #else - 0, /*tp_repr*/ - #endif - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - #if CYTHON_COMPILING_IN_PYPY - __pyx_memoryview___str__, /*tp_str*/ - #else - 0, /*tp_str*/ - #endif - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - "Internal class for passing memoryview slices to Python", /*tp_doc*/ - __pyx_tp_traverse__memoryviewslice, /*tp_traverse*/ - __pyx_tp_clear__memoryviewslice, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods__memoryviewslice, /*tp_methods*/ - 0, /*tp_members*/ - __pyx_getsets__memoryviewslice, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new__memoryviewslice, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif -}; - -static PyMethodDef __pyx_methods[] = { - {"maximum_path_c", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_15monotonic_align_4core_1maximum_path_c, METH_VARARGS|METH_KEYWORDS, 0}, - {0, 0, 0, 0} -}; - -#if PY_MAJOR_VERSION >= 3 -#if CYTHON_PEP489_MULTI_PHASE_INIT -static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ -static int __pyx_pymod_exec_core(PyObject* module); /*proto*/ -static PyModuleDef_Slot __pyx_moduledef_slots[] = { - {Py_mod_create, (void*)__pyx_pymod_create}, - {Py_mod_exec, (void*)__pyx_pymod_exec_core}, - {0, NULL} -}; -#endif - -static struct PyModuleDef __pyx_moduledef = { - PyModuleDef_HEAD_INIT, - "core", - 0, /* m_doc */ - #if CYTHON_PEP489_MULTI_PHASE_INIT - 0, /* m_size */ - #else - -1, /* m_size */ - #endif - __pyx_methods /* m_methods */, - #if CYTHON_PEP489_MULTI_PHASE_INIT - __pyx_moduledef_slots, /* m_slots */ - #else - NULL, /* m_reload */ - #endif - NULL, /* m_traverse */ - NULL, /* m_clear */ - NULL /* m_free */ -}; -#endif -#ifndef CYTHON_SMALL_CODE -#if defined(__clang__) - #define CYTHON_SMALL_CODE -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) - #define CYTHON_SMALL_CODE __attribute__((cold)) -#else - #define CYTHON_SMALL_CODE -#endif -#endif - -static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_n_s_ASCII, __pyx_k_ASCII, sizeof(__pyx_k_ASCII), 0, 0, 1, 1}, - {&__pyx_kp_s_Buffer_view_does_not_expose_stri, __pyx_k_Buffer_view_does_not_expose_stri, sizeof(__pyx_k_Buffer_view_does_not_expose_stri), 0, 0, 1, 0}, - {&__pyx_kp_s_Can_only_create_a_buffer_that_is, __pyx_k_Can_only_create_a_buffer_that_is, sizeof(__pyx_k_Can_only_create_a_buffer_that_is), 0, 0, 1, 0}, - {&__pyx_kp_s_Cannot_assign_to_read_only_memor, __pyx_k_Cannot_assign_to_read_only_memor, sizeof(__pyx_k_Cannot_assign_to_read_only_memor), 0, 0, 1, 0}, - {&__pyx_kp_s_Cannot_create_writable_memory_vi, __pyx_k_Cannot_create_writable_memory_vi, sizeof(__pyx_k_Cannot_create_writable_memory_vi), 0, 0, 1, 0}, - {&__pyx_kp_s_Cannot_index_with_type_s, __pyx_k_Cannot_index_with_type_s, sizeof(__pyx_k_Cannot_index_with_type_s), 0, 0, 1, 0}, - {&__pyx_n_s_Ellipsis, __pyx_k_Ellipsis, sizeof(__pyx_k_Ellipsis), 0, 0, 1, 1}, - {&__pyx_kp_s_Empty_shape_tuple_for_cython_arr, __pyx_k_Empty_shape_tuple_for_cython_arr, sizeof(__pyx_k_Empty_shape_tuple_for_cython_arr), 0, 0, 1, 0}, - {&__pyx_kp_s_Incompatible_checksums_s_vs_0xb0, __pyx_k_Incompatible_checksums_s_vs_0xb0, sizeof(__pyx_k_Incompatible_checksums_s_vs_0xb0), 0, 0, 1, 0}, - {&__pyx_n_s_IndexError, __pyx_k_IndexError, sizeof(__pyx_k_IndexError), 0, 0, 1, 1}, - {&__pyx_kp_s_Indirect_dimensions_not_supporte, __pyx_k_Indirect_dimensions_not_supporte, sizeof(__pyx_k_Indirect_dimensions_not_supporte), 0, 0, 1, 0}, - {&__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_k_Invalid_mode_expected_c_or_fortr, sizeof(__pyx_k_Invalid_mode_expected_c_or_fortr), 0, 0, 1, 0}, - {&__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_k_Invalid_shape_in_axis_d_d, sizeof(__pyx_k_Invalid_shape_in_axis_d_d), 0, 0, 1, 0}, - {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, - {&__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_k_MemoryView_of_r_at_0x_x, sizeof(__pyx_k_MemoryView_of_r_at_0x_x), 0, 0, 1, 0}, - {&__pyx_kp_s_MemoryView_of_r_object, __pyx_k_MemoryView_of_r_object, sizeof(__pyx_k_MemoryView_of_r_object), 0, 0, 1, 0}, - {&__pyx_n_b_O, __pyx_k_O, sizeof(__pyx_k_O), 0, 0, 0, 1}, - {&__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_k_Out_of_bounds_on_buffer_access_a, sizeof(__pyx_k_Out_of_bounds_on_buffer_access_a), 0, 0, 1, 0}, - {&__pyx_n_s_PickleError, __pyx_k_PickleError, sizeof(__pyx_k_PickleError), 0, 0, 1, 1}, - {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, - {&__pyx_kp_s_Unable_to_convert_item_to_object, __pyx_k_Unable_to_convert_item_to_object, sizeof(__pyx_k_Unable_to_convert_item_to_object), 0, 0, 1, 0}, - {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, - {&__pyx_n_s_View_MemoryView, __pyx_k_View_MemoryView, sizeof(__pyx_k_View_MemoryView), 0, 0, 1, 1}, - {&__pyx_n_s_allocate_buffer, __pyx_k_allocate_buffer, sizeof(__pyx_k_allocate_buffer), 0, 0, 1, 1}, - {&__pyx_n_s_base, __pyx_k_base, sizeof(__pyx_k_base), 0, 0, 1, 1}, - {&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1}, - {&__pyx_n_u_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 1, 0, 1}, - {&__pyx_n_s_class, __pyx_k_class, sizeof(__pyx_k_class), 0, 0, 1, 1}, - {&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1}, - {&__pyx_kp_s_contiguous_and_direct, __pyx_k_contiguous_and_direct, sizeof(__pyx_k_contiguous_and_direct), 0, 0, 1, 0}, - {&__pyx_kp_s_contiguous_and_indirect, __pyx_k_contiguous_and_indirect, sizeof(__pyx_k_contiguous_and_indirect), 0, 0, 1, 0}, - {&__pyx_n_s_dict, __pyx_k_dict, sizeof(__pyx_k_dict), 0, 0, 1, 1}, - {&__pyx_n_s_dtype_is_object, __pyx_k_dtype_is_object, sizeof(__pyx_k_dtype_is_object), 0, 0, 1, 1}, - {&__pyx_n_s_encode, __pyx_k_encode, sizeof(__pyx_k_encode), 0, 0, 1, 1}, - {&__pyx_n_s_enumerate, __pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 0, 1, 1}, - {&__pyx_n_s_error, __pyx_k_error, sizeof(__pyx_k_error), 0, 0, 1, 1}, - {&__pyx_n_s_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 0, 0, 1, 1}, - {&__pyx_n_s_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1}, - {&__pyx_n_s_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 0, 1, 1}, - {&__pyx_n_u_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 1, 0, 1}, - {&__pyx_n_s_getstate, __pyx_k_getstate, sizeof(__pyx_k_getstate), 0, 0, 1, 1}, - {&__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_k_got_differing_extents_in_dimensi, sizeof(__pyx_k_got_differing_extents_in_dimensi), 0, 0, 1, 0}, - {&__pyx_n_s_id, __pyx_k_id, sizeof(__pyx_k_id), 0, 0, 1, 1}, - {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, - {&__pyx_n_s_itemsize, __pyx_k_itemsize, sizeof(__pyx_k_itemsize), 0, 0, 1, 1}, - {&__pyx_kp_s_itemsize_0_for_cython_array, __pyx_k_itemsize_0_for_cython_array, sizeof(__pyx_k_itemsize_0_for_cython_array), 0, 0, 1, 0}, - {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, - {&__pyx_n_s_memview, __pyx_k_memview, sizeof(__pyx_k_memview), 0, 0, 1, 1}, - {&__pyx_n_s_mode, __pyx_k_mode, sizeof(__pyx_k_mode), 0, 0, 1, 1}, - {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, - {&__pyx_n_s_name_2, __pyx_k_name_2, sizeof(__pyx_k_name_2), 0, 0, 1, 1}, - {&__pyx_n_s_ndim, __pyx_k_ndim, sizeof(__pyx_k_ndim), 0, 0, 1, 1}, - {&__pyx_n_s_new, __pyx_k_new, sizeof(__pyx_k_new), 0, 0, 1, 1}, - {&__pyx_kp_s_no_default___reduce___due_to_non, __pyx_k_no_default___reduce___due_to_non, sizeof(__pyx_k_no_default___reduce___due_to_non), 0, 0, 1, 0}, - {&__pyx_n_s_obj, __pyx_k_obj, sizeof(__pyx_k_obj), 0, 0, 1, 1}, - {&__pyx_n_s_pack, __pyx_k_pack, sizeof(__pyx_k_pack), 0, 0, 1, 1}, - {&__pyx_n_s_paths, __pyx_k_paths, sizeof(__pyx_k_paths), 0, 0, 1, 1}, - {&__pyx_n_s_pickle, __pyx_k_pickle, sizeof(__pyx_k_pickle), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_PickleError, __pyx_k_pyx_PickleError, sizeof(__pyx_k_pyx_PickleError), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_checksum, __pyx_k_pyx_checksum, sizeof(__pyx_k_pyx_checksum), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_result, __pyx_k_pyx_result, sizeof(__pyx_k_pyx_result), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_state, __pyx_k_pyx_state, sizeof(__pyx_k_pyx_state), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_type, __pyx_k_pyx_type, sizeof(__pyx_k_pyx_type), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_unpickle_Enum, __pyx_k_pyx_unpickle_Enum, sizeof(__pyx_k_pyx_unpickle_Enum), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, - {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, - {&__pyx_n_s_reduce, __pyx_k_reduce, sizeof(__pyx_k_reduce), 0, 0, 1, 1}, - {&__pyx_n_s_reduce_cython, __pyx_k_reduce_cython, sizeof(__pyx_k_reduce_cython), 0, 0, 1, 1}, - {&__pyx_n_s_reduce_ex, __pyx_k_reduce_ex, sizeof(__pyx_k_reduce_ex), 0, 0, 1, 1}, - {&__pyx_n_s_setstate, __pyx_k_setstate, sizeof(__pyx_k_setstate), 0, 0, 1, 1}, - {&__pyx_n_s_setstate_cython, __pyx_k_setstate_cython, sizeof(__pyx_k_setstate_cython), 0, 0, 1, 1}, - {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, - {&__pyx_n_s_size, __pyx_k_size, sizeof(__pyx_k_size), 0, 0, 1, 1}, - {&__pyx_n_s_start, __pyx_k_start, sizeof(__pyx_k_start), 0, 0, 1, 1}, - {&__pyx_n_s_step, __pyx_k_step, sizeof(__pyx_k_step), 0, 0, 1, 1}, - {&__pyx_n_s_stop, __pyx_k_stop, sizeof(__pyx_k_stop), 0, 0, 1, 1}, - {&__pyx_kp_s_strided_and_direct, __pyx_k_strided_and_direct, sizeof(__pyx_k_strided_and_direct), 0, 0, 1, 0}, - {&__pyx_kp_s_strided_and_direct_or_indirect, __pyx_k_strided_and_direct_or_indirect, sizeof(__pyx_k_strided_and_direct_or_indirect), 0, 0, 1, 0}, - {&__pyx_kp_s_strided_and_indirect, __pyx_k_strided_and_indirect, sizeof(__pyx_k_strided_and_indirect), 0, 0, 1, 0}, - {&__pyx_kp_s_stringsource, __pyx_k_stringsource, sizeof(__pyx_k_stringsource), 0, 0, 1, 0}, - {&__pyx_n_s_struct, __pyx_k_struct, sizeof(__pyx_k_struct), 0, 0, 1, 1}, - {&__pyx_n_s_t_xs, __pyx_k_t_xs, sizeof(__pyx_k_t_xs), 0, 0, 1, 1}, - {&__pyx_n_s_t_ys, __pyx_k_t_ys, sizeof(__pyx_k_t_ys), 0, 0, 1, 1}, - {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, - {&__pyx_kp_s_unable_to_allocate_array_data, __pyx_k_unable_to_allocate_array_data, sizeof(__pyx_k_unable_to_allocate_array_data), 0, 0, 1, 0}, - {&__pyx_kp_s_unable_to_allocate_shape_and_str, __pyx_k_unable_to_allocate_shape_and_str, sizeof(__pyx_k_unable_to_allocate_shape_and_str), 0, 0, 1, 0}, - {&__pyx_n_s_unpack, __pyx_k_unpack, sizeof(__pyx_k_unpack), 0, 0, 1, 1}, - {&__pyx_n_s_update, __pyx_k_update, sizeof(__pyx_k_update), 0, 0, 1, 1}, - {&__pyx_n_s_values, __pyx_k_values, sizeof(__pyx_k_values), 0, 0, 1, 1}, - {0, 0, 0, 0, 0, 0, 0} -}; -static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 15, __pyx_L1_error) - __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(1, 133, __pyx_L1_error) - __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(1, 148, __pyx_L1_error) - __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) __PYX_ERR(1, 151, __pyx_L1_error) - __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(1, 2, __pyx_L1_error) - __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) __PYX_ERR(1, 404, __pyx_L1_error) - __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) __PYX_ERR(1, 613, __pyx_L1_error) - __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) __PYX_ERR(1, 832, __pyx_L1_error) - return 0; - __pyx_L1_error:; - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - - /* "View.MemoryView":133 - * - * if not self.ndim: - * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< - * - * if itemsize <= 0: - */ - __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(1, 133, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__2); - __Pyx_GIVEREF(__pyx_tuple__2); - - /* "View.MemoryView":136 - * - * if itemsize <= 0: - * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< - * - * if not isinstance(format, bytes): - */ - __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(1, 136, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__3); - __Pyx_GIVEREF(__pyx_tuple__3); - - /* "View.MemoryView":148 - * - * if not self._shape: - * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< - * - * - */ - __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_and_str); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(1, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__4); - __Pyx_GIVEREF(__pyx_tuple__4); - - /* "View.MemoryView":176 - * self.data = malloc(self.len) - * if not self.data: - * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< - * - * if self.dtype_is_object: - */ - __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(1, 176, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__5); - __Pyx_GIVEREF(__pyx_tuple__5); - - /* "View.MemoryView":192 - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * if not (flags & bufmode): - * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< - * info.buf = self.data - * info.len = self.len - */ - __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(1, 192, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__6); - __Pyx_GIVEREF(__pyx_tuple__6); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__7); - __Pyx_GIVEREF(__pyx_tuple__7); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__8); - __Pyx_GIVEREF(__pyx_tuple__8); - - /* "View.MemoryView":418 - * def __setitem__(memoryview self, object index, object value): - * if self.view.readonly: - * raise TypeError("Cannot assign to read-only memoryview") # <<<<<<<<<<<<<< - * - * have_slices, index = _unellipsify(index, self.view.ndim) - */ - __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_s_Cannot_assign_to_read_only_memor); if (unlikely(!__pyx_tuple__9)) __PYX_ERR(1, 418, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__9); - __Pyx_GIVEREF(__pyx_tuple__9); - - /* "View.MemoryView":495 - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: - * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< - * else: - * if len(self.view.format) == 1: - */ - __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(1, 495, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__10); - __Pyx_GIVEREF(__pyx_tuple__10); - - /* "View.MemoryView":520 - * def __getbuffer__(self, Py_buffer *info, int flags): - * if flags & PyBUF_WRITABLE and self.view.readonly: - * raise ValueError("Cannot create writable memory view from read-only memoryview") # <<<<<<<<<<<<<< - * - * if flags & PyBUF_ND: - */ - __pyx_tuple__11 = PyTuple_Pack(1, __pyx_kp_s_Cannot_create_writable_memory_vi); if (unlikely(!__pyx_tuple__11)) __PYX_ERR(1, 520, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__11); - __Pyx_GIVEREF(__pyx_tuple__11); - - /* "View.MemoryView":570 - * if self.view.strides == NULL: - * - * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< - * - * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) - */ - __pyx_tuple__12 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(1, 570, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__12); - __Pyx_GIVEREF(__pyx_tuple__12); - - /* "View.MemoryView":577 - * def suboffsets(self): - * if self.view.suboffsets == NULL: - * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< - * - * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) - */ - __pyx_tuple__13 = PyTuple_New(1); if (unlikely(!__pyx_tuple__13)) __PYX_ERR(1, 577, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__13); - __Pyx_INCREF(__pyx_int_neg_1); - __Pyx_GIVEREF(__pyx_int_neg_1); - PyTuple_SET_ITEM(__pyx_tuple__13, 0, __pyx_int_neg_1); - __Pyx_GIVEREF(__pyx_tuple__13); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_tuple__14 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__14)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__14); - __Pyx_GIVEREF(__pyx_tuple__14); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_tuple__15 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__15)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__15); - __Pyx_GIVEREF(__pyx_tuple__15); - - /* "View.MemoryView":682 - * if item is Ellipsis: - * if not seen_ellipsis: - * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< - * seen_ellipsis = True - * else: - */ - __pyx_slice__16 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__16)) __PYX_ERR(1, 682, __pyx_L1_error) - __Pyx_GOTREF(__pyx_slice__16); - __Pyx_GIVEREF(__pyx_slice__16); - - /* "View.MemoryView":703 - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: - * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< - * - * - */ - __pyx_tuple__17 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__17)) __PYX_ERR(1, 703, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__17); - __Pyx_GIVEREF(__pyx_tuple__17); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_tuple__18 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__18)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__18); - __Pyx_GIVEREF(__pyx_tuple__18); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_tuple__19 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__19)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__19); - __Pyx_GIVEREF(__pyx_tuple__19); - - /* "View.MemoryView":286 - * return self.name - * - * cdef generic = Enum("") # <<<<<<<<<<<<<< - * cdef strided = Enum("") # default - * cdef indirect = Enum("") - */ - __pyx_tuple__20 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__20)) __PYX_ERR(1, 286, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__20); - __Pyx_GIVEREF(__pyx_tuple__20); - - /* "View.MemoryView":287 - * - * cdef generic = Enum("") - * cdef strided = Enum("") # default # <<<<<<<<<<<<<< - * cdef indirect = Enum("") - * - */ - __pyx_tuple__21 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct); if (unlikely(!__pyx_tuple__21)) __PYX_ERR(1, 287, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__21); - __Pyx_GIVEREF(__pyx_tuple__21); - - /* "View.MemoryView":288 - * cdef generic = Enum("") - * cdef strided = Enum("") # default - * cdef indirect = Enum("") # <<<<<<<<<<<<<< - * - * - */ - __pyx_tuple__22 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__22)) __PYX_ERR(1, 288, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__22); - __Pyx_GIVEREF(__pyx_tuple__22); - - /* "View.MemoryView":291 - * - * - * cdef contiguous = Enum("") # <<<<<<<<<<<<<< - * cdef indirect_contiguous = Enum("") - * - */ - __pyx_tuple__23 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__23)) __PYX_ERR(1, 291, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__23); - __Pyx_GIVEREF(__pyx_tuple__23); - - /* "View.MemoryView":292 - * - * cdef contiguous = Enum("") - * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< - * - * - */ - __pyx_tuple__24 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__24)) __PYX_ERR(1, 292, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__24); - __Pyx_GIVEREF(__pyx_tuple__24); - - /* "(tree fragment)":1 - * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - __pyx_tuple__25 = PyTuple_Pack(5, __pyx_n_s_pyx_type, __pyx_n_s_pyx_checksum, __pyx_n_s_pyx_state, __pyx_n_s_pyx_PickleError, __pyx_n_s_pyx_result); if (unlikely(!__pyx_tuple__25)) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__25); - __Pyx_GIVEREF(__pyx_tuple__25); - __pyx_codeobj__26 = (PyObject*)__Pyx_PyCode_New(3, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__25, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_stringsource, __pyx_n_s_pyx_unpickle_Enum, 1, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__26)) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { - /* InitThreads.init */ - #ifdef WITH_THREAD -PyEval_InitThreads(); -#endif - -if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) - - if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); - __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_184977713 = PyInt_FromLong(184977713L); if (unlikely(!__pyx_int_184977713)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) __PYX_ERR(0, 1, __pyx_L1_error) - return 0; - __pyx_L1_error:; - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/ - -static int __Pyx_modinit_global_init_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); - /*--- Global init code ---*/ - generic = Py_None; Py_INCREF(Py_None); - strided = Py_None; Py_INCREF(Py_None); - indirect = Py_None; Py_INCREF(Py_None); - contiguous = Py_None; Py_INCREF(Py_None); - indirect_contiguous = Py_None; Py_INCREF(Py_None); - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_variable_export_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); - /*--- Variable export code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_function_export_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); - /*--- Function export code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_type_init_code(void) { - __Pyx_RefNannyDeclarations - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); - /*--- Type init code ---*/ - __pyx_vtabptr_array = &__pyx_vtable_array; - __pyx_vtable_array.get_memview = (PyObject *(*)(struct __pyx_array_obj *))__pyx_array_get_memview; - if (PyType_Ready(&__pyx_type___pyx_array) < 0) __PYX_ERR(1, 105, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type___pyx_array.tp_print = 0; - #endif - if (__Pyx_SetVtable(__pyx_type___pyx_array.tp_dict, __pyx_vtabptr_array) < 0) __PYX_ERR(1, 105, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_array) < 0) __PYX_ERR(1, 105, __pyx_L1_error) - __pyx_array_type = &__pyx_type___pyx_array; - if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(1, 279, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type___pyx_MemviewEnum.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_MemviewEnum.tp_dictoffset && __pyx_type___pyx_MemviewEnum.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type___pyx_MemviewEnum.tp_getattro = __Pyx_PyObject_GenericGetAttr; - } - if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(1, 279, __pyx_L1_error) - __pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum; - __pyx_vtabptr_memoryview = &__pyx_vtable_memoryview; - __pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer; - __pyx_vtable_memoryview.is_slice = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_is_slice; - __pyx_vtable_memoryview.setitem_slice_assignment = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_slice_assignment; - __pyx_vtable_memoryview.setitem_slice_assign_scalar = (PyObject *(*)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_setitem_slice_assign_scalar; - __pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed; - __pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object; - __pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object; - if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) __PYX_ERR(1, 330, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type___pyx_memoryview.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_memoryview.tp_dictoffset && __pyx_type___pyx_memoryview.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type___pyx_memoryview.tp_getattro = __Pyx_PyObject_GenericGetAttr; - } - if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) __PYX_ERR(1, 330, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryview) < 0) __PYX_ERR(1, 330, __pyx_L1_error) - __pyx_memoryview_type = &__pyx_type___pyx_memoryview; - __pyx_vtabptr__memoryviewslice = &__pyx_vtable__memoryviewslice; - __pyx_vtable__memoryviewslice.__pyx_base = *__pyx_vtabptr_memoryview; - __pyx_vtable__memoryviewslice.__pyx_base.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryviewslice_convert_item_to_object; - __pyx_vtable__memoryviewslice.__pyx_base.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryviewslice_assign_item_from_object; - __pyx_type___pyx_memoryviewslice.tp_base = __pyx_memoryview_type; - if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(1, 965, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type___pyx_memoryviewslice.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_memoryviewslice.tp_dictoffset && __pyx_type___pyx_memoryviewslice.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type___pyx_memoryviewslice.tp_getattro = __Pyx_PyObject_GenericGetAttr; - } - if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) __PYX_ERR(1, 965, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(1, 965, __pyx_L1_error) - __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static int __Pyx_modinit_type_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); - /*--- Type import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_variable_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); - /*--- Variable import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_function_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); - /*--- Function import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - - -#ifndef CYTHON_NO_PYINIT_EXPORT -#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC -#elif PY_MAJOR_VERSION < 3 -#ifdef __cplusplus -#define __Pyx_PyMODINIT_FUNC extern "C" void -#else -#define __Pyx_PyMODINIT_FUNC void -#endif -#else -#ifdef __cplusplus -#define __Pyx_PyMODINIT_FUNC extern "C" PyObject * -#else -#define __Pyx_PyMODINIT_FUNC PyObject * -#endif -#endif - - -#if PY_MAJOR_VERSION < 3 -__Pyx_PyMODINIT_FUNC initcore(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC initcore(void) -#else -__Pyx_PyMODINIT_FUNC PyInit_core(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC PyInit_core(void) -#if CYTHON_PEP489_MULTI_PHASE_INIT -{ - return PyModuleDef_Init(&__pyx_moduledef); -} -static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { - #if PY_VERSION_HEX >= 0x030700A1 - static PY_INT64_T main_interpreter_id = -1; - PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); - if (main_interpreter_id == -1) { - main_interpreter_id = current_id; - return (unlikely(current_id == -1)) ? -1 : 0; - } else if (unlikely(main_interpreter_id != current_id)) - #else - static PyInterpreterState *main_interpreter = NULL; - PyInterpreterState *current_interpreter = PyThreadState_Get()->interp; - if (!main_interpreter) { - main_interpreter = current_interpreter; - } else if (unlikely(main_interpreter != current_interpreter)) - #endif - { - PyErr_SetString( - PyExc_ImportError, - "Interpreter change detected - this module can only be loaded into one interpreter per process."); - return -1; - } - return 0; -} -static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) { - PyObject *value = PyObject_GetAttrString(spec, from_name); - int result = 0; - if (likely(value)) { - if (allow_none || value != Py_None) { - result = PyDict_SetItemString(moddict, to_name, value); - } - Py_DECREF(value); - } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - } else { - result = -1; - } - return result; -} -static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { - PyObject *module = NULL, *moddict, *modname; - if (__Pyx_check_single_interpreter()) - return NULL; - if (__pyx_m) - return __Pyx_NewRef(__pyx_m); - modname = PyObject_GetAttrString(spec, "name"); - if (unlikely(!modname)) goto bad; - module = PyModule_NewObject(modname); - Py_DECREF(modname); - if (unlikely(!module)) goto bad; - moddict = PyModule_GetDict(module); - if (unlikely(!moddict)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; - return module; -bad: - Py_XDECREF(module); - return NULL; -} - - -static CYTHON_SMALL_CODE int __pyx_pymod_exec_core(PyObject *__pyx_pyinit_module) -#endif -#endif -{ - PyObject *__pyx_t_1 = NULL; - static PyThread_type_lock __pyx_t_2[8]; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannyDeclarations - #if CYTHON_PEP489_MULTI_PHASE_INIT - if (__pyx_m) { - if (__pyx_m == __pyx_pyinit_module) return 0; - PyErr_SetString(PyExc_RuntimeError, "Module 'core' has already been imported. Re-initialisation is not supported."); - return -1; - } - #elif PY_MAJOR_VERSION >= 3 - if (__pyx_m) return __Pyx_NewRef(__pyx_m); - #endif - #if CYTHON_REFNANNY -__Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); -if (!__Pyx_RefNanny) { - PyErr_Clear(); - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); - if (!__Pyx_RefNanny) - Py_FatalError("failed to import 'refnanny' module"); -} -#endif - __Pyx_RefNannySetupContext("__Pyx_PyMODINIT_FUNC PyInit_core(void)", 0); - if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #ifdef __Pxy_PyFrame_Initialize_Offsets - __Pxy_PyFrame_Initialize_Offsets(); - #endif - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) - #ifdef __Pyx_CyFunction_USED - if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_FusedFunction_USED - if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_Coroutine_USED - if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_Generator_USED - if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_AsyncGen_USED - if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_StopAsyncIteration_USED - if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - /*--- Library function declarations ---*/ - /*--- Threads initialization code ---*/ - #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS - #ifdef WITH_THREAD /* Python build with threading support? */ - PyEval_InitThreads(); - #endif - #endif - /*--- Module creation code ---*/ - #if CYTHON_PEP489_MULTI_PHASE_INIT - __pyx_m = __pyx_pyinit_module; - Py_INCREF(__pyx_m); - #else - #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4("core", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); - #else - __pyx_m = PyModule_Create(&__pyx_moduledef); - #endif - if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_d); - __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_b); - __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_cython_runtime); - if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); - /*--- Initialize various global constants etc. ---*/ - if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) - if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - if (__pyx_module_is_main_monotonic_align__core) { - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name_2, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - } - #if PY_MAJOR_VERSION >= 3 - { - PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) - if (!PyDict_GetItemString(modules, "monotonic_align.core")) { - if (unlikely(PyDict_SetItemString(modules, "monotonic_align.core", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) - } - } - #endif - /*--- Builtin init code ---*/ - if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - /*--- Constants init code ---*/ - if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - /*--- Global type/function init code ---*/ - (void)__Pyx_modinit_global_init_code(); - (void)__Pyx_modinit_variable_export_code(); - (void)__Pyx_modinit_function_export_code(); - if (unlikely(__Pyx_modinit_type_init_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error) - (void)__Pyx_modinit_type_import_code(); - (void)__Pyx_modinit_variable_import_code(); - (void)__Pyx_modinit_function_import_code(); - /*--- Execution code ---*/ - #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) - if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - - /* "monotonic_align/core.pyx":7 - * @cython.boundscheck(False) - * @cython.wraparound(False) - * cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_y, int t_x, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<< - * cdef int x - * cdef int y - */ - __pyx_k_ = (-1e9); - - /* "monotonic_align/core.pyx":1 - * cimport cython # <<<<<<<<<<<<<< - * from cython.parallel import prange - * - */ - __pyx_t_1 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "View.MemoryView":209 - * info.obj = self - * - * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< - * - * def __dealloc__(array self): - */ - __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 209, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem((PyObject *)__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 209, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - PyType_Modified(__pyx_array_type); - - /* "View.MemoryView":286 - * return self.name - * - * cdef generic = Enum("") # <<<<<<<<<<<<<< - * cdef strided = Enum("") # default - * cdef indirect = Enum("") - */ - __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__20, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 286, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(generic); - __Pyx_DECREF_SET(generic, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":287 - * - * cdef generic = Enum("") - * cdef strided = Enum("") # default # <<<<<<<<<<<<<< - * cdef indirect = Enum("") - * - */ - __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__21, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 287, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(strided); - __Pyx_DECREF_SET(strided, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":288 - * cdef generic = Enum("") - * cdef strided = Enum("") # default - * cdef indirect = Enum("") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__22, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 288, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(indirect); - __Pyx_DECREF_SET(indirect, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":291 - * - * - * cdef contiguous = Enum("") # <<<<<<<<<<<<<< - * cdef indirect_contiguous = Enum("") - * - */ - __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__23, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 291, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(contiguous); - __Pyx_DECREF_SET(contiguous, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":292 - * - * cdef contiguous = Enum("") - * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__24, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 292, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(indirect_contiguous); - __Pyx_DECREF_SET(indirect_contiguous, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":316 - * - * DEF THREAD_LOCKS_PREALLOCATED = 8 - * cdef int __pyx_memoryview_thread_locks_used = 0 # <<<<<<<<<<<<<< - * cdef PyThread_type_lock[THREAD_LOCKS_PREALLOCATED] __pyx_memoryview_thread_locks = [ - * PyThread_allocate_lock(), - */ - __pyx_memoryview_thread_locks_used = 0; - - /* "View.MemoryView":317 - * DEF THREAD_LOCKS_PREALLOCATED = 8 - * cdef int __pyx_memoryview_thread_locks_used = 0 - * cdef PyThread_type_lock[THREAD_LOCKS_PREALLOCATED] __pyx_memoryview_thread_locks = [ # <<<<<<<<<<<<<< - * PyThread_allocate_lock(), - * PyThread_allocate_lock(), - */ - __pyx_t_2[0] = PyThread_allocate_lock(); - __pyx_t_2[1] = PyThread_allocate_lock(); - __pyx_t_2[2] = PyThread_allocate_lock(); - __pyx_t_2[3] = PyThread_allocate_lock(); - __pyx_t_2[4] = PyThread_allocate_lock(); - __pyx_t_2[5] = PyThread_allocate_lock(); - __pyx_t_2[6] = PyThread_allocate_lock(); - __pyx_t_2[7] = PyThread_allocate_lock(); - memcpy(&(__pyx_memoryview_thread_locks[0]), __pyx_t_2, sizeof(__pyx_memoryview_thread_locks[0]) * (8)); - - /* "View.MemoryView":549 - * info.obj = self - * - * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 549, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem((PyObject *)__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 549, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - PyType_Modified(__pyx_memoryview_type); - - /* "View.MemoryView":995 - * return self.from_object - * - * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 995, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem((PyObject *)__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 995, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - PyType_Modified(__pyx_memoryviewslice_type); - - /* "(tree fragment)":1 - * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_15View_dot_MemoryView_1__pyx_unpickle_Enum, NULL, __pyx_n_s_View_MemoryView); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_pyx_unpickle_Enum, __pyx_t_1) < 0) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "(tree fragment)":11 - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - * return __pyx_result - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< - * __pyx_result.name = __pyx_state[0] - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): - */ - - /*--- Wrapped vars code ---*/ - - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - if (__pyx_m) { - if (__pyx_d) { - __Pyx_AddTraceback("init monotonic_align.core", __pyx_clineno, __pyx_lineno, __pyx_filename); - } - Py_CLEAR(__pyx_m); - } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init monotonic_align.core"); - } - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - #if CYTHON_PEP489_MULTI_PHASE_INIT - return (__pyx_m != NULL) ? 0 : -1; - #elif PY_MAJOR_VERSION >= 3 - return __pyx_m; - #else - return; - #endif -} - -/* --- Runtime support code --- */ -/* Refnanny */ -#if CYTHON_REFNANNY -static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { - PyObject *m = NULL, *p = NULL; - void *r = NULL; - m = PyImport_ImportModule(modname); - if (!m) goto end; - p = PyObject_GetAttrString(m, "RefNannyAPI"); - if (!p) goto end; - r = PyLong_AsVoidPtr(p); -end: - Py_XDECREF(p); - Py_XDECREF(m); - return (__Pyx_RefNannyAPIStruct *)r; -} -#endif - -/* PyObjectGetAttrStr */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_getattro)) - return tp->tp_getattro(obj, attr_name); -#if PY_MAJOR_VERSION < 3 - if (likely(tp->tp_getattr)) - return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); -#endif - return PyObject_GetAttr(obj, attr_name); -} -#endif - -/* GetBuiltinName */ -static PyObject *__Pyx_GetBuiltinName(PyObject *name) { - PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); - if (unlikely(!result)) { - PyErr_Format(PyExc_NameError, -#if PY_MAJOR_VERSION >= 3 - "name '%U' is not defined", name); -#else - "name '%.200s' is not defined", PyString_AS_STRING(name)); -#endif - } - return result; -} - -/* MemviewSliceInit */ -static int -__Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, - int ndim, - __Pyx_memviewslice *memviewslice, - int memview_is_new_reference) -{ - __Pyx_RefNannyDeclarations - int i, retval=-1; - Py_buffer *buf = &memview->view; - __Pyx_RefNannySetupContext("init_memviewslice", 0); - if (unlikely(memviewslice->memview || memviewslice->data)) { - PyErr_SetString(PyExc_ValueError, - "memviewslice is already initialized!"); - goto fail; - } - if (buf->strides) { - for (i = 0; i < ndim; i++) { - memviewslice->strides[i] = buf->strides[i]; - } - } else { - Py_ssize_t stride = buf->itemsize; - for (i = ndim - 1; i >= 0; i--) { - memviewslice->strides[i] = stride; - stride *= buf->shape[i]; - } - } - for (i = 0; i < ndim; i++) { - memviewslice->shape[i] = buf->shape[i]; - if (buf->suboffsets) { - memviewslice->suboffsets[i] = buf->suboffsets[i]; - } else { - memviewslice->suboffsets[i] = -1; - } - } - memviewslice->memview = memview; - memviewslice->data = (char *)buf->buf; - if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { - Py_INCREF(memview); - } - retval = 0; - goto no_fail; -fail: - memviewslice->memview = 0; - memviewslice->data = 0; - retval = -1; -no_fail: - __Pyx_RefNannyFinishContext(); - return retval; -} -#ifndef Py_NO_RETURN -#define Py_NO_RETURN -#endif -static void __pyx_fatalerror(const char *fmt, ...) Py_NO_RETURN { - va_list vargs; - char msg[200]; -#ifdef HAVE_STDARG_PROTOTYPES - va_start(vargs, fmt); -#else - va_start(vargs); -#endif - vsnprintf(msg, 200, fmt, vargs); - va_end(vargs); - Py_FatalError(msg); -} -static CYTHON_INLINE int -__pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, - PyThread_type_lock lock) -{ - int result; - PyThread_acquire_lock(lock, 1); - result = (*acquisition_count)++; - PyThread_release_lock(lock); - return result; -} -static CYTHON_INLINE int -__pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, - PyThread_type_lock lock) -{ - int result; - PyThread_acquire_lock(lock, 1); - result = (*acquisition_count)--; - PyThread_release_lock(lock); - return result; -} -static CYTHON_INLINE void -__Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) -{ - int first_time; - struct __pyx_memoryview_obj *memview = memslice->memview; - if (unlikely(!memview || (PyObject *) memview == Py_None)) - return; - if (unlikely(__pyx_get_slice_count(memview) < 0)) - __pyx_fatalerror("Acquisition count is %d (line %d)", - __pyx_get_slice_count(memview), lineno); - first_time = __pyx_add_acquisition_count(memview) == 0; - if (unlikely(first_time)) { - if (have_gil) { - Py_INCREF((PyObject *) memview); - } else { - PyGILState_STATE _gilstate = PyGILState_Ensure(); - Py_INCREF((PyObject *) memview); - PyGILState_Release(_gilstate); - } - } -} -static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, - int have_gil, int lineno) { - int last_time; - struct __pyx_memoryview_obj *memview = memslice->memview; - if (unlikely(!memview || (PyObject *) memview == Py_None)) { - memslice->memview = NULL; - return; - } - if (unlikely(__pyx_get_slice_count(memview) <= 0)) - __pyx_fatalerror("Acquisition count is %d (line %d)", - __pyx_get_slice_count(memview), lineno); - last_time = __pyx_sub_acquisition_count(memview) == 1; - memslice->data = NULL; - if (unlikely(last_time)) { - if (have_gil) { - Py_CLEAR(memslice->memview); - } else { - PyGILState_STATE _gilstate = PyGILState_Ensure(); - Py_CLEAR(memslice->memview); - PyGILState_Release(_gilstate); - } - } else { - memslice->memview = NULL; - } -} - -/* RaiseArgTupleInvalid */ -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; - } - PyErr_Format(PyExc_TypeError, - "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); -} - -/* RaiseDoubleKeywords */ -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AsString(kw_name)); - #endif -} - -/* ParseKeywords */ -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; - continue; - } - name = first_kw_arg; - #if PY_MAJOR_VERSION < 3 - if (likely(PyString_Check(key))) { - while (*name) { - if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) - && _PyString_Eq(**name, key)) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - if ((**argname == key) || ( - (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) - && _PyString_Eq(**argname, key))) { - goto arg_passed_twice; - } - argname++; - } - } - } else - #endif - if (likely(PyUnicode_Check(key))) { - while (*name) { - int cmp = (**name == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (__Pyx_PyUnicode_GET_LENGTH(**name) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : - #endif - PyUnicode_Compare(**name, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - int cmp = (**argname == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (__Pyx_PyUnicode_GET_LENGTH(**argname) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : - #endif - PyUnicode_Compare(**argname, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) goto arg_passed_twice; - argname++; - } - } - } else - goto invalid_keyword_type; - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } - } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, key); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%.200s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%.200s() got an unexpected keyword argument '%.200s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif -bad: - return -1; -} - -/* None */ -static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { - PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); -} - -/* ArgTypeTest */ -static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) -{ - if (unlikely(!type)) { - PyErr_SetString(PyExc_SystemError, "Missing type object"); - return 0; - } - else if (exact) { - #if PY_MAJOR_VERSION == 2 - if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; - #endif - } - else { - if (likely(__Pyx_TypeCheck(obj, type))) return 1; - } - PyErr_Format(PyExc_TypeError, - "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", - name, type->tp_name, Py_TYPE(obj)->tp_name); - return 0; -} - -/* PyObjectCall */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *result; - ternaryfunc call = func->ob_type->tp_call; - if (unlikely(!call)) - return PyObject_Call(func, arg, kw); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = (*call)(func, arg, kw); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - -/* PyErrFetchRestore */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - tmp_type = tstate->curexc_type; - tmp_value = tstate->curexc_value; - tmp_tb = tstate->curexc_traceback; - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} -static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - *type = tstate->curexc_type; - *value = tstate->curexc_value; - *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -} -#endif - -/* RaiseException */ -#if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, - CYTHON_UNUSED PyObject *cause) { - __Pyx_PyThreadState_declare - Py_XINCREF(type); - if (!value || value == Py_None) - value = NULL; - else - Py_INCREF(value); - if (!tb || tb == Py_None) - tb = NULL; - else { - Py_INCREF(tb); - if (!PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - } - if (PyType_Check(type)) { -#if CYTHON_COMPILING_IN_PYPY - if (!value) { - Py_INCREF(Py_None); - value = Py_None; - } -#endif - PyErr_NormalizeException(&type, &value, &tb); - } else { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto raise_error; - } - value = type; - type = (PyObject*) Py_TYPE(type); - Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } - } - __Pyx_PyThreadState_assign - __Pyx_ErrRestore(type, value, tb); - return; -raise_error: - Py_XDECREF(value); - Py_XDECREF(type); - Py_XDECREF(tb); - return; -} -#else -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - PyObject* owned_instance = NULL; - if (tb == Py_None) { - tb = 0; - } else if (tb && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto bad; - } - if (value == Py_None) - value = 0; - if (PyExceptionInstance_Check(type)) { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto bad; - } - value = type; - type = (PyObject*) Py_TYPE(value); - } else if (PyExceptionClass_Check(type)) { - PyObject *instance_class = NULL; - if (value && PyExceptionInstance_Check(value)) { - instance_class = (PyObject*) Py_TYPE(value); - if (instance_class != type) { - int is_subclass = PyObject_IsSubclass(instance_class, type); - if (!is_subclass) { - instance_class = NULL; - } else if (unlikely(is_subclass == -1)) { - goto bad; - } else { - type = instance_class; - } - } - } - if (!instance_class) { - PyObject *args; - if (!value) - args = PyTuple_New(0); - else if (PyTuple_Check(value)) { - Py_INCREF(value); - args = value; - } else - args = PyTuple_Pack(1, value); - if (!args) - goto bad; - owned_instance = PyObject_Call(type, args, NULL); - Py_DECREF(args); - if (!owned_instance) - goto bad; - value = owned_instance; - if (!PyExceptionInstance_Check(value)) { - PyErr_Format(PyExc_TypeError, - "calling %R should have returned an instance of " - "BaseException, not %R", - type, Py_TYPE(value)); - goto bad; - } - } - } else { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto bad; - } - if (cause) { - PyObject *fixed_cause; - if (cause == Py_None) { - fixed_cause = NULL; - } else if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto bad; - } else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - Py_INCREF(fixed_cause); - } else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto bad; - } - PyException_SetCause(value, fixed_cause); - } - PyErr_SetObject(type, value); - if (tb) { -#if CYTHON_COMPILING_IN_PYPY - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); - Py_INCREF(tb); - PyErr_Restore(tmp_type, tmp_value, tb); - Py_XDECREF(tmp_tb); -#else - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject* tmp_tb = tstate->curexc_traceback; - if (tb != tmp_tb) { - Py_INCREF(tb); - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_tb); - } -#endif - } -bad: - Py_XDECREF(owned_instance); - return; -} -#endif - -/* PyCFunctionFastCall */ -#if CYTHON_FAST_PYCCALL -static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) { - PyCFunctionObject *func = (PyCFunctionObject*)func_obj; - PyCFunction meth = PyCFunction_GET_FUNCTION(func); - PyObject *self = PyCFunction_GET_SELF(func); - int flags = PyCFunction_GET_FLAGS(func); - assert(PyCFunction_Check(func)); - assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))); - assert(nargs >= 0); - assert(nargs == 0 || args != NULL); - /* _PyCFunction_FastCallDict() must not be called with an exception set, - because it may clear it (directly or indirectly) and so the - caller loses its exception */ - assert(!PyErr_Occurred()); - if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) { - return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL); - } else { - return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs); - } -} -#endif - -/* PyFunctionFastCall */ -#if CYTHON_FAST_PYCALL -static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, - PyObject *globals) { - PyFrameObject *f; - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject **fastlocals; - Py_ssize_t i; - PyObject *result; - assert(globals != NULL); - /* XXX Perhaps we should create a specialized - PyFrame_New() that doesn't take locals, but does - take builtins without sanity checking them. - */ - assert(tstate != NULL); - f = PyFrame_New(tstate, co, globals, NULL); - if (f == NULL) { - return NULL; - } - fastlocals = __Pyx_PyFrame_GetLocalsplus(f); - for (i = 0; i < na; i++) { - Py_INCREF(*args); - fastlocals[i] = *args++; - } - result = PyEval_EvalFrameEx(f,0); - ++tstate->recursion_depth; - Py_DECREF(f); - --tstate->recursion_depth; - return result; -} -#if 1 || PY_VERSION_HEX < 0x030600B1 -static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { - PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); - PyObject *globals = PyFunction_GET_GLOBALS(func); - PyObject *argdefs = PyFunction_GET_DEFAULTS(func); - PyObject *closure; -#if PY_MAJOR_VERSION >= 3 - PyObject *kwdefs; -#endif - PyObject *kwtuple, **k; - PyObject **d; - Py_ssize_t nd; - Py_ssize_t nk; - PyObject *result; - assert(kwargs == NULL || PyDict_Check(kwargs)); - nk = kwargs ? PyDict_Size(kwargs) : 0; - if (Py_EnterRecursiveCall((char*)" while calling a Python object")) { - return NULL; - } - if ( -#if PY_MAJOR_VERSION >= 3 - co->co_kwonlyargcount == 0 && -#endif - likely(kwargs == NULL || nk == 0) && - co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { - if (argdefs == NULL && co->co_argcount == nargs) { - result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); - goto done; - } - else if (nargs == 0 && argdefs != NULL - && co->co_argcount == Py_SIZE(argdefs)) { - /* function called with no arguments, but all parameters have - a default value: use default values as arguments .*/ - args = &PyTuple_GET_ITEM(argdefs, 0); - result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); - goto done; - } - } - if (kwargs != NULL) { - Py_ssize_t pos, i; - kwtuple = PyTuple_New(2 * nk); - if (kwtuple == NULL) { - result = NULL; - goto done; - } - k = &PyTuple_GET_ITEM(kwtuple, 0); - pos = i = 0; - while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { - Py_INCREF(k[i]); - Py_INCREF(k[i+1]); - i += 2; - } - nk = i / 2; - } - else { - kwtuple = NULL; - k = NULL; - } - closure = PyFunction_GET_CLOSURE(func); -#if PY_MAJOR_VERSION >= 3 - kwdefs = PyFunction_GET_KW_DEFAULTS(func); -#endif - if (argdefs != NULL) { - d = &PyTuple_GET_ITEM(argdefs, 0); - nd = Py_SIZE(argdefs); - } - else { - d = NULL; - nd = 0; - } -#if PY_MAJOR_VERSION >= 3 - result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, - args, (int)nargs, - k, (int)nk, - d, (int)nd, kwdefs, closure); -#else - result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, - args, (int)nargs, - k, (int)nk, - d, (int)nd, closure); -#endif - Py_XDECREF(kwtuple); -done: - Py_LeaveRecursiveCall(); - return result; -} -#endif -#endif - -/* PyObjectCall2Args */ -static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { - PyObject *args, *result = NULL; - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(function)) { - PyObject *args[2] = {arg1, arg2}; - return __Pyx_PyFunction_FastCall(function, args, 2); - } - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(function)) { - PyObject *args[2] = {arg1, arg2}; - return __Pyx_PyCFunction_FastCall(function, args, 2); - } - #endif - args = PyTuple_New(2); - if (unlikely(!args)) goto done; - Py_INCREF(arg1); - PyTuple_SET_ITEM(args, 0, arg1); - Py_INCREF(arg2); - PyTuple_SET_ITEM(args, 1, arg2); - Py_INCREF(function); - result = __Pyx_PyObject_Call(function, args, NULL); - Py_DECREF(args); - Py_DECREF(function); -done: - return result; -} - -/* PyObjectCallMethO */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { - PyObject *self, *result; - PyCFunction cfunc; - cfunc = PyCFunction_GET_FUNCTION(func); - self = PyCFunction_GET_SELF(func); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = cfunc(self, arg); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - -/* PyObjectCallOneArg */ -#if CYTHON_COMPILING_IN_CPYTHON -static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_New(1); - if (unlikely(!args)) return NULL; - Py_INCREF(arg); - PyTuple_SET_ITEM(args, 0, arg); - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { -#if CYTHON_FAST_PYCALL - if (PyFunction_Check(func)) { - return __Pyx_PyFunction_FastCall(func, &arg, 1); - } -#endif - if (likely(PyCFunction_Check(func))) { - if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { - return __Pyx_PyObject_CallMethO(func, arg); -#if CYTHON_FAST_PYCCALL - } else if (PyCFunction_GET_FLAGS(func) & METH_FASTCALL) { - return __Pyx_PyCFunction_FastCall(func, &arg, 1); -#endif - } - } - return __Pyx__PyObject_CallOneArg(func, arg); -} -#else -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_Pack(1, arg); - if (unlikely(!args)) return NULL; - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} -#endif - -/* BytesEquals */ -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { -#if CYTHON_COMPILING_IN_PYPY - return PyObject_RichCompareBool(s1, s2, equals); -#else - if (s1 == s2) { - return (equals == Py_EQ); - } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { - const char *ps1, *ps2; - Py_ssize_t length = PyBytes_GET_SIZE(s1); - if (length != PyBytes_GET_SIZE(s2)) - return (equals == Py_NE); - ps1 = PyBytes_AS_STRING(s1); - ps2 = PyBytes_AS_STRING(s2); - if (ps1[0] != ps2[0]) { - return (equals == Py_NE); - } else if (length == 1) { - return (equals == Py_EQ); - } else { - int result; -#if CYTHON_USE_UNICODE_INTERNALS - Py_hash_t hash1, hash2; - hash1 = ((PyBytesObject*)s1)->ob_shash; - hash2 = ((PyBytesObject*)s2)->ob_shash; - if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { - return (equals == Py_NE); - } -#endif - result = memcmp(ps1, ps2, (size_t)length); - return (equals == Py_EQ) ? (result == 0) : (result != 0); - } - } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { - return (equals == Py_NE); - } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { - return (equals == Py_NE); - } else { - int result; - PyObject* py_result = PyObject_RichCompare(s1, s2, equals); - if (!py_result) - return -1; - result = __Pyx_PyObject_IsTrue(py_result); - Py_DECREF(py_result); - return result; - } -#endif -} - -/* UnicodeEquals */ -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { -#if CYTHON_COMPILING_IN_PYPY - return PyObject_RichCompareBool(s1, s2, equals); -#else -#if PY_MAJOR_VERSION < 3 - PyObject* owned_ref = NULL; -#endif - int s1_is_unicode, s2_is_unicode; - if (s1 == s2) { - goto return_eq; - } - s1_is_unicode = PyUnicode_CheckExact(s1); - s2_is_unicode = PyUnicode_CheckExact(s2); -#if PY_MAJOR_VERSION < 3 - if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { - owned_ref = PyUnicode_FromObject(s2); - if (unlikely(!owned_ref)) - return -1; - s2 = owned_ref; - s2_is_unicode = 1; - } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { - owned_ref = PyUnicode_FromObject(s1); - if (unlikely(!owned_ref)) - return -1; - s1 = owned_ref; - s1_is_unicode = 1; - } else if (((!s2_is_unicode) & (!s1_is_unicode))) { - return __Pyx_PyBytes_Equals(s1, s2, equals); - } -#endif - if (s1_is_unicode & s2_is_unicode) { - Py_ssize_t length; - int kind; - void *data1, *data2; - if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) - return -1; - length = __Pyx_PyUnicode_GET_LENGTH(s1); - if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { - goto return_ne; - } -#if CYTHON_USE_UNICODE_INTERNALS - { - Py_hash_t hash1, hash2; - #if CYTHON_PEP393_ENABLED - hash1 = ((PyASCIIObject*)s1)->hash; - hash2 = ((PyASCIIObject*)s2)->hash; - #else - hash1 = ((PyUnicodeObject*)s1)->hash; - hash2 = ((PyUnicodeObject*)s2)->hash; - #endif - if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { - goto return_ne; - } - } -#endif - kind = __Pyx_PyUnicode_KIND(s1); - if (kind != __Pyx_PyUnicode_KIND(s2)) { - goto return_ne; - } - data1 = __Pyx_PyUnicode_DATA(s1); - data2 = __Pyx_PyUnicode_DATA(s2); - if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { - goto return_ne; - } else if (length == 1) { - goto return_eq; - } else { - int result = memcmp(data1, data2, (size_t)(length * kind)); - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_EQ) ? (result == 0) : (result != 0); - } - } else if ((s1 == Py_None) & s2_is_unicode) { - goto return_ne; - } else if ((s2 == Py_None) & s1_is_unicode) { - goto return_ne; - } else { - int result; - PyObject* py_result = PyObject_RichCompare(s1, s2, equals); - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - if (!py_result) - return -1; - result = __Pyx_PyObject_IsTrue(py_result); - Py_DECREF(py_result); - return result; - } -return_eq: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_EQ); -return_ne: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_NE); -#endif -} - -/* None */ -static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t a, Py_ssize_t b) { - Py_ssize_t q = a / b; - Py_ssize_t r = a - q*b; - q -= ((r != 0) & ((r ^ b) < 0)); - return q; -} - -/* GetAttr */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { -#if CYTHON_USE_TYPE_SLOTS -#if PY_MAJOR_VERSION >= 3 - if (likely(PyUnicode_Check(n))) -#else - if (likely(PyString_Check(n))) -#endif - return __Pyx_PyObject_GetAttrStr(o, n); -#endif - return PyObject_GetAttr(o, n); -} - -/* GetItemInt */ -static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - Py_ssize_t wrapped_i = i; - if (wraparound & unlikely(i < 0)) { - wrapped_i += PyList_GET_SIZE(o); - } - if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, wrapped_i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - Py_ssize_t wrapped_i = i; - if (wraparound & unlikely(i < 0)) { - wrapped_i += PyTuple_GET_SIZE(o); - } - if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, wrapped_i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS - if (is_list || PyList_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); - if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { - PyObject *r = PyList_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } - else if (PyTuple_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); - if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } else { - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_item)) { - if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (likely(l >= 0)) { - i += l; - } else { - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return NULL; - PyErr_Clear(); - } - } - return m->sq_item(o, i); - } - } -#else - if (is_list || PySequence_Check(o)) { - return PySequence_GetItem(o, i); - } -#endif - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} - -/* ObjectGetItem */ -#if CYTHON_USE_TYPE_SLOTS -static PyObject *__Pyx_PyObject_GetIndex(PyObject *obj, PyObject* index) { - PyObject *runerr; - Py_ssize_t key_value; - PySequenceMethods *m = Py_TYPE(obj)->tp_as_sequence; - if (unlikely(!(m && m->sq_item))) { - PyErr_Format(PyExc_TypeError, "'%.200s' object is not subscriptable", Py_TYPE(obj)->tp_name); - return NULL; - } - key_value = __Pyx_PyIndex_AsSsize_t(index); - if (likely(key_value != -1 || !(runerr = PyErr_Occurred()))) { - return __Pyx_GetItemInt_Fast(obj, key_value, 0, 1, 1); - } - if (PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) { - PyErr_Clear(); - PyErr_Format(PyExc_IndexError, "cannot fit '%.200s' into an index-sized integer", Py_TYPE(index)->tp_name); - } - return NULL; -} -static PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key) { - PyMappingMethods *m = Py_TYPE(obj)->tp_as_mapping; - if (likely(m && m->mp_subscript)) { - return m->mp_subscript(obj, key); - } - return __Pyx_PyObject_GetIndex(obj, key); -} -#endif - -/* decode_c_string */ -static CYTHON_INLINE PyObject* __Pyx_decode_c_string( - const char* cstring, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { - Py_ssize_t length; - if (unlikely((start < 0) | (stop < 0))) { - size_t slen = strlen(cstring); - if (unlikely(slen > (size_t) PY_SSIZE_T_MAX)) { - PyErr_SetString(PyExc_OverflowError, - "c-string too long to convert to Python"); - return NULL; - } - length = (Py_ssize_t) slen; - if (start < 0) { - start += length; - if (start < 0) - start = 0; - } - if (stop < 0) - stop += length; - } - if (unlikely(stop <= start)) - return __Pyx_NewRef(__pyx_empty_unicode); - length = stop - start; - cstring += start; - if (decode_func) { - return decode_func(cstring, length, errors); - } else { - return PyUnicode_Decode(cstring, length, encoding, errors); - } -} - -/* PyErrExceptionMatches */ -#if CYTHON_FAST_THREAD_STATE -static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { - Py_ssize_t i, n; - n = PyTuple_GET_SIZE(tuple); -#if PY_MAJOR_VERSION >= 3 - for (i=0; icurexc_type; - if (exc_type == err) return 1; - if (unlikely(!exc_type)) return 0; - if (unlikely(PyTuple_Check(err))) - return __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); - return __Pyx_PyErr_GivenExceptionMatches(exc_type, err); -} -#endif - -/* GetAttr3 */ -static PyObject *__Pyx_GetAttr3Default(PyObject *d) { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) - return NULL; - __Pyx_PyErr_Clear(); - Py_INCREF(d); - return d; -} -static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { - PyObject *r = __Pyx_GetAttr(o, n); - return (likely(r)) ? r : __Pyx_GetAttr3Default(d); -} - -/* PyDictVersioning */ -#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { - PyObject *dict = Py_TYPE(obj)->tp_dict; - return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; -} -static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { - PyObject **dictptr = NULL; - Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; - if (offset) { -#if CYTHON_COMPILING_IN_CPYTHON - dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); -#else - dictptr = _PyObject_GetDictPtr(obj); -#endif - } - return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; -} -static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { - PyObject *dict = Py_TYPE(obj)->tp_dict; - if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) - return 0; - return obj_dict_version == __Pyx_get_object_dict_version(obj); -} -#endif - -/* GetModuleGlobalName */ -#if CYTHON_USE_DICT_VERSIONS -static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) -#else -static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) -#endif -{ - PyObject *result; -#if !CYTHON_AVOID_BORROWED_REFS -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 - result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } else if (unlikely(PyErr_Occurred())) { - return NULL; - } -#else - result = PyDict_GetItem(__pyx_d, name); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } -#endif -#else - result = PyObject_GetItem(__pyx_d, name); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } - PyErr_Clear(); -#endif - return __Pyx_GetBuiltinName(name); -} - -/* RaiseTooManyValuesToUnpack */ -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { - PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); -} - -/* RaiseNeedMoreValuesToUnpack */ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { - PyErr_Format(PyExc_ValueError, - "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", - index, (index == 1) ? "" : "s"); -} - -/* RaiseNoneIterError */ -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); -} - -/* ExtTypeTest */ -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { - if (unlikely(!type)) { - PyErr_SetString(PyExc_SystemError, "Missing type object"); - return 0; - } - if (likely(__Pyx_TypeCheck(obj, type))) - return 1; - PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", - Py_TYPE(obj)->tp_name, type->tp_name); - return 0; -} - -/* GetTopmostException */ -#if CYTHON_USE_EXC_INFO_STACK -static _PyErr_StackItem * -__Pyx_PyErr_GetTopmostException(PyThreadState *tstate) -{ - _PyErr_StackItem *exc_info = tstate->exc_info; - while ((exc_info->exc_type == NULL || exc_info->exc_type == Py_None) && - exc_info->previous_item != NULL) - { - exc_info = exc_info->previous_item; - } - return exc_info; -} -#endif - -/* SaveResetException */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); - *type = exc_info->exc_type; - *value = exc_info->exc_value; - *tb = exc_info->exc_traceback; - #else - *type = tstate->exc_type; - *value = tstate->exc_value; - *tb = tstate->exc_traceback; - #endif - Py_XINCREF(*type); - Py_XINCREF(*value); - Py_XINCREF(*tb); -} -static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = type; - exc_info->exc_value = value; - exc_info->exc_traceback = tb; - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = type; - tstate->exc_value = value; - tstate->exc_traceback = tb; - #endif - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} -#endif - -/* GetException */ -#if CYTHON_FAST_THREAD_STATE -static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) -#else -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) -#endif -{ - PyObject *local_type, *local_value, *local_tb; -#if CYTHON_FAST_THREAD_STATE - PyObject *tmp_type, *tmp_value, *tmp_tb; - local_type = tstate->curexc_type; - local_value = tstate->curexc_value; - local_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -#else - PyErr_Fetch(&local_type, &local_value, &local_tb); -#endif - PyErr_NormalizeException(&local_type, &local_value, &local_tb); -#if CYTHON_FAST_THREAD_STATE - if (unlikely(tstate->curexc_type)) -#else - if (unlikely(PyErr_Occurred())) -#endif - goto bad; - #if PY_MAJOR_VERSION >= 3 - if (local_tb) { - if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) - goto bad; - } - #endif - Py_XINCREF(local_tb); - Py_XINCREF(local_type); - Py_XINCREF(local_value); - *type = local_type; - *value = local_value; - *tb = local_tb; -#if CYTHON_FAST_THREAD_STATE - #if CYTHON_USE_EXC_INFO_STACK - { - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = local_type; - exc_info->exc_value = local_value; - exc_info->exc_traceback = local_tb; - } - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = local_type; - tstate->exc_value = local_value; - tstate->exc_traceback = local_tb; - #endif - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -#else - PyErr_SetExcInfo(local_type, local_value, local_tb); -#endif - return 0; -bad: - *type = 0; - *value = 0; - *tb = 0; - Py_XDECREF(local_type); - Py_XDECREF(local_value); - Py_XDECREF(local_tb); - return -1; -} - -/* SwapException */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = *type; - exc_info->exc_value = *value; - exc_info->exc_traceback = *tb; - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = *type; - tstate->exc_value = *value; - tstate->exc_traceback = *tb; - #endif - *type = tmp_type; - *value = tmp_value; - *tb = tmp_tb; -} -#else -static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); - PyErr_SetExcInfo(*type, *value, *tb); - *type = tmp_type; - *value = tmp_value; - *tb = tmp_tb; -} -#endif - -/* Import */ -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { - PyObject *empty_list = 0; - PyObject *module = 0; - PyObject *global_dict = 0; - PyObject *empty_dict = 0; - PyObject *list; - #if PY_MAJOR_VERSION < 3 - PyObject *py_import; - py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); - if (!py_import) - goto bad; - #endif - if (from_list) - list = from_list; - else { - empty_list = PyList_New(0); - if (!empty_list) - goto bad; - list = empty_list; - } - global_dict = PyModule_GetDict(__pyx_m); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - { - #if PY_MAJOR_VERSION >= 3 - if (level == -1) { - if ((1) && (strchr(__Pyx_MODULE_NAME, '.'))) { - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, 1); - if (!module) { - if (!PyErr_ExceptionMatches(PyExc_ImportError)) - goto bad; - PyErr_Clear(); - } - } - level = 0; - } - #endif - if (!module) { - #if PY_MAJOR_VERSION < 3 - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, (PyObject *)NULL); - Py_DECREF(py_level); - #else - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, level); - #endif - } - } -bad: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(py_import); - #endif - Py_XDECREF(empty_list); - Py_XDECREF(empty_dict); - return module; -} - -/* FastTypeChecks */ -#if CYTHON_COMPILING_IN_CPYTHON -static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { - while (a) { - a = a->tp_base; - if (a == b) - return 1; - } - return b == &PyBaseObject_Type; -} -static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { - PyObject *mro; - if (a == b) return 1; - mro = a->tp_mro; - if (likely(mro)) { - Py_ssize_t i, n; - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) - return 1; - } - return 0; - } - return __Pyx_InBases(a, b); -} -#if PY_MAJOR_VERSION == 2 -static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { - PyObject *exception, *value, *tb; - int res; - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ErrFetch(&exception, &value, &tb); - res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; - if (unlikely(res == -1)) { - PyErr_WriteUnraisable(err); - res = 0; - } - if (!res) { - res = PyObject_IsSubclass(err, exc_type2); - if (unlikely(res == -1)) { - PyErr_WriteUnraisable(err); - res = 0; - } - } - __Pyx_ErrRestore(exception, value, tb); - return res; -} -#else -static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { - int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0; - if (!res) { - res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); - } - return res; -} -#endif -static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { - Py_ssize_t i, n; - assert(PyExceptionClass_Check(exc_type)); - n = PyTuple_GET_SIZE(tuple); -#if PY_MAJOR_VERSION >= 3 - for (i=0; i= 0 || (x^b) >= 0)) - return PyInt_FromLong(x); - return PyLong_Type.tp_as_number->nb_add(op1, op2); - } - #endif - #if CYTHON_USE_PYLONG_INTERNALS - if (likely(PyLong_CheckExact(op1))) { - const long b = intval; - long a, x; -#ifdef HAVE_LONG_LONG - const PY_LONG_LONG llb = intval; - PY_LONG_LONG lla, llx; -#endif - const digit* digits = ((PyLongObject*)op1)->ob_digit; - const Py_ssize_t size = Py_SIZE(op1); - if (likely(__Pyx_sst_abs(size) <= 1)) { - a = likely(size) ? digits[0] : 0; - if (size == -1) a = -a; - } else { - switch (size) { - case -2: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; -#ifdef HAVE_LONG_LONG - } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { - lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); - goto long_long; -#endif - } - CYTHON_FALLTHROUGH; - case 2: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; -#ifdef HAVE_LONG_LONG - } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { - lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); - goto long_long; -#endif - } - CYTHON_FALLTHROUGH; - case -3: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; -#ifdef HAVE_LONG_LONG - } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { - lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); - goto long_long; -#endif - } - CYTHON_FALLTHROUGH; - case 3: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; -#ifdef HAVE_LONG_LONG - } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { - lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); - goto long_long; -#endif - } - CYTHON_FALLTHROUGH; - case -4: - if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; -#ifdef HAVE_LONG_LONG - } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { - lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); - goto long_long; -#endif - } - CYTHON_FALLTHROUGH; - case 4: - if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; -#ifdef HAVE_LONG_LONG - } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { - lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); - goto long_long; -#endif - } - CYTHON_FALLTHROUGH; - default: return PyLong_Type.tp_as_number->nb_add(op1, op2); - } - } - x = a + b; - return PyLong_FromLong(x); -#ifdef HAVE_LONG_LONG - long_long: - llx = lla + llb; - return PyLong_FromLongLong(llx); -#endif - - - } - #endif - if (PyFloat_CheckExact(op1)) { - const long b = intval; - double a = PyFloat_AS_DOUBLE(op1); - double result; - PyFPE_START_PROTECT("add", return NULL) - result = ((double)a) + (double)b; - PyFPE_END_PROTECT(result) - return PyFloat_FromDouble(result); - } - return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2); -} -#endif - -/* None */ -static CYTHON_INLINE long __Pyx_div_long(long a, long b) { - long q = a / b; - long r = a - q*b; - q -= ((r != 0) & ((r ^ b) < 0)); - return q; -} - -/* ImportFrom */ -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { - PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); - if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Format(PyExc_ImportError, - #if PY_MAJOR_VERSION < 3 - "cannot import name %.230s", PyString_AS_STRING(name)); - #else - "cannot import name %S", name); - #endif - } - return value; -} - -/* HasAttr */ -static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { - PyObject *r; - if (unlikely(!__Pyx_PyBaseString_Check(n))) { - PyErr_SetString(PyExc_TypeError, - "hasattr(): attribute name must be string"); - return -1; - } - r = __Pyx_GetAttr(o, n); - if (unlikely(!r)) { - PyErr_Clear(); - return 0; - } else { - Py_DECREF(r); - return 1; - } -} - -/* PyObject_GenericGetAttrNoDict */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static PyObject *__Pyx_RaiseGenericGetAttributeError(PyTypeObject *tp, PyObject *attr_name) { - PyErr_Format(PyExc_AttributeError, -#if PY_MAJOR_VERSION >= 3 - "'%.50s' object has no attribute '%U'", - tp->tp_name, attr_name); -#else - "'%.50s' object has no attribute '%.400s'", - tp->tp_name, PyString_AS_STRING(attr_name)); -#endif - return NULL; -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name) { - PyObject *descr; - PyTypeObject *tp = Py_TYPE(obj); - if (unlikely(!PyString_Check(attr_name))) { - return PyObject_GenericGetAttr(obj, attr_name); - } - assert(!tp->tp_dictoffset); - descr = _PyType_Lookup(tp, attr_name); - if (unlikely(!descr)) { - return __Pyx_RaiseGenericGetAttributeError(tp, attr_name); - } - Py_INCREF(descr); - #if PY_MAJOR_VERSION < 3 - if (likely(PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_HAVE_CLASS))) - #endif - { - descrgetfunc f = Py_TYPE(descr)->tp_descr_get; - if (unlikely(f)) { - PyObject *res = f(descr, obj, (PyObject *)tp); - Py_DECREF(descr); - return res; - } - } - return descr; -} -#endif - -/* PyObject_GenericGetAttr */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name) { - if (unlikely(Py_TYPE(obj)->tp_dictoffset)) { - return PyObject_GenericGetAttr(obj, attr_name); - } - return __Pyx_PyObject_GenericGetAttrNoDict(obj, attr_name); -} -#endif - -/* SetVTable */ -static int __Pyx_SetVtable(PyObject *dict, void *vtable) { -#if PY_VERSION_HEX >= 0x02070000 - PyObject *ob = PyCapsule_New(vtable, 0, 0); -#else - PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); -#endif - if (!ob) - goto bad; - if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) - goto bad; - Py_DECREF(ob); - return 0; -bad: - Py_XDECREF(ob); - return -1; -} - -/* PyObjectGetAttrStrNoError */ -static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) - __Pyx_PyErr_Clear(); -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { - PyObject *result; -#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS && PY_VERSION_HEX >= 0x030700B1 - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { - return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); - } -#endif - result = __Pyx_PyObject_GetAttrStr(obj, attr_name); - if (unlikely(!result)) { - __Pyx_PyObject_GetAttrStr_ClearAttributeError(); - } - return result; -} - -/* SetupReduce */ -static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { - int ret; - PyObject *name_attr; - name_attr = __Pyx_PyObject_GetAttrStr(meth, __pyx_n_s_name_2); - if (likely(name_attr)) { - ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); - } else { - ret = -1; - } - if (unlikely(ret < 0)) { - PyErr_Clear(); - ret = 0; - } - Py_XDECREF(name_attr); - return ret; -} -static int __Pyx_setup_reduce(PyObject* type_obj) { - int ret = 0; - PyObject *object_reduce = NULL; - PyObject *object_reduce_ex = NULL; - PyObject *reduce = NULL; - PyObject *reduce_ex = NULL; - PyObject *reduce_cython = NULL; - PyObject *setstate = NULL; - PyObject *setstate_cython = NULL; -#if CYTHON_USE_PYTYPE_LOOKUP - if (_PyType_Lookup((PyTypeObject*)type_obj, __pyx_n_s_getstate)) goto __PYX_GOOD; -#else - if (PyObject_HasAttr(type_obj, __pyx_n_s_getstate)) goto __PYX_GOOD; -#endif -#if CYTHON_USE_PYTYPE_LOOKUP - object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; -#else - object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; -#endif - reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce_ex); if (unlikely(!reduce_ex)) goto __PYX_BAD; - if (reduce_ex == object_reduce_ex) { -#if CYTHON_USE_PYTYPE_LOOKUP - object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto __PYX_BAD; -#else - object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto __PYX_BAD; -#endif - reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce); if (unlikely(!reduce)) goto __PYX_BAD; - if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_n_s_reduce_cython)) { - reduce_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_reduce_cython); - if (likely(reduce_cython)) { - ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce, reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - } else if (reduce == object_reduce || PyErr_Occurred()) { - goto __PYX_BAD; - } - setstate = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_setstate); - if (!setstate) PyErr_Clear(); - if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_n_s_setstate_cython)) { - setstate_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_setstate_cython); - if (likely(setstate_cython)) { - ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate, setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - } else if (!setstate || PyErr_Occurred()) { - goto __PYX_BAD; - } - } - PyType_Modified((PyTypeObject*)type_obj); - } - } - goto __PYX_GOOD; -__PYX_BAD: - if (!PyErr_Occurred()) - PyErr_Format(PyExc_RuntimeError, "Unable to initialize pickling for %s", ((PyTypeObject*)type_obj)->tp_name); - ret = -1; -__PYX_GOOD: -#if !CYTHON_USE_PYTYPE_LOOKUP - Py_XDECREF(object_reduce); - Py_XDECREF(object_reduce_ex); -#endif - Py_XDECREF(reduce); - Py_XDECREF(reduce_ex); - Py_XDECREF(reduce_cython); - Py_XDECREF(setstate); - Py_XDECREF(setstate_cython); - return ret; -} - -/* CLineInTraceback */ -#ifndef CYTHON_CLINE_IN_TRACEBACK -static int __Pyx_CLineForTraceback(CYTHON_NCP_UNUSED PyThreadState *tstate, int c_line) { - PyObject *use_cline; - PyObject *ptype, *pvalue, *ptraceback; -#if CYTHON_COMPILING_IN_CPYTHON - PyObject **cython_runtime_dict; -#endif - if (unlikely(!__pyx_cython_runtime)) { - return c_line; - } - __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); -#if CYTHON_COMPILING_IN_CPYTHON - cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); - if (likely(cython_runtime_dict)) { - __PYX_PY_DICT_LOOKUP_IF_MODIFIED( - use_cline, *cython_runtime_dict, - __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback)) - } else -#endif - { - PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); - if (use_cline_obj) { - use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; - Py_DECREF(use_cline_obj); - } else { - PyErr_Clear(); - use_cline = NULL; - } - } - if (!use_cline) { - c_line = 0; - PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); - } - else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { - c_line = 0; - } - __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); - return c_line; -} -#endif - -/* CodeObjectCache */ -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { - int start = 0, mid = 0, end = count - 1; - if (end >= 0 && code_line > entries[end].code_line) { - return count; - } - while (start < end) { - mid = start + (end - start) / 2; - if (code_line < entries[mid].code_line) { - end = mid; - } else if (code_line > entries[mid].code_line) { - start = mid + 1; - } else { - return mid; - } - } - if (code_line <= entries[mid].code_line) { - return mid; - } else { - return mid + 1; - } -} -static PyCodeObject *__pyx_find_code_object(int code_line) { - PyCodeObject* code_object; - int pos; - if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { - return NULL; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { - return NULL; - } - code_object = __pyx_code_cache.entries[pos].code_object; - Py_INCREF(code_object); - return code_object; -} -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { - int pos, i; - __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; - if (unlikely(!code_line)) { - return; - } - if (unlikely(!entries)) { - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); - if (likely(entries)) { - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = 64; - __pyx_code_cache.count = 1; - entries[0].code_line = code_line; - entries[0].code_object = code_object; - Py_INCREF(code_object); - } - return; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { - PyCodeObject* tmp = entries[pos].code_object; - entries[pos].code_object = code_object; - Py_DECREF(tmp); - return; - } - if (__pyx_code_cache.count == __pyx_code_cache.max_count) { - int new_max = __pyx_code_cache.max_count + 64; - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( - __pyx_code_cache.entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); - if (unlikely(!entries)) { - return; - } - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = new_max; - } - for (i=__pyx_code_cache.count; i>pos; i--) { - entries[i] = entries[i-1]; - } - entries[pos].code_line = code_line; - entries[pos].code_object = code_object; - __pyx_code_cache.count++; - Py_INCREF(code_object); -} - -/* AddTraceback */ -#include "compile.h" -#include "frameobject.h" -#include "traceback.h" -static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( - const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(filename); - #else - py_srcfile = PyUnicode_FromString(filename); - #endif - if (!py_srcfile) goto bad; - if (c_line) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - #else - py_funcname = PyUnicode_FromString(funcname); - #endif - } - if (!py_funcname) goto bad; - py_code = __Pyx_PyCode_New( - 0, - 0, - 0, - 0, - 0, - __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - py_line, - __pyx_empty_bytes /*PyObject *lnotab*/ - ); - Py_DECREF(py_srcfile); - Py_DECREF(py_funcname); - return py_code; -bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - return NULL; -} -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - PyThreadState *tstate = __Pyx_PyThreadState_Current; - if (c_line) { - c_line = __Pyx_CLineForTraceback(tstate, c_line); - } - py_code = __pyx_find_code_object(c_line ? -c_line : py_line); - if (!py_code) { - py_code = __Pyx_CreateCodeObjectForTraceback( - funcname, c_line, py_line, filename); - if (!py_code) goto bad; - __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); - } - py_frame = PyFrame_New( - tstate, /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - __pyx_d, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - __Pyx_PyFrame_SetLineNumber(py_frame, py_line); - PyTraceBack_Here(py_frame); -bad: - Py_XDECREF(py_code); - Py_XDECREF(py_frame); -} - -#if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { - if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); - if (__Pyx_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); - if (__Pyx_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); - PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - return -1; -} -static void __Pyx_ReleaseBuffer(Py_buffer *view) { - PyObject *obj = view->obj; - if (!obj) return; - if (PyObject_CheckBuffer(obj)) { - PyBuffer_Release(view); - return; - } - if ((0)) {} - view->obj = NULL; - Py_DECREF(obj); -} -#endif - - -/* MemviewSliceIsContig */ -static int -__pyx_memviewslice_is_contig(const __Pyx_memviewslice mvs, char order, int ndim) -{ - int i, index, step, start; - Py_ssize_t itemsize = mvs.memview->view.itemsize; - if (order == 'F') { - step = 1; - start = 0; - } else { - step = -1; - start = ndim - 1; - } - for (i = 0; i < ndim; i++) { - index = start + step * i; - if (mvs.suboffsets[index] >= 0 || mvs.strides[index] != itemsize) - return 0; - itemsize *= mvs.shape[index]; - } - return 1; -} - -/* OverlappingSlices */ -static void -__pyx_get_array_memory_extents(__Pyx_memviewslice *slice, - void **out_start, void **out_end, - int ndim, size_t itemsize) -{ - char *start, *end; - int i; - start = end = slice->data; - for (i = 0; i < ndim; i++) { - Py_ssize_t stride = slice->strides[i]; - Py_ssize_t extent = slice->shape[i]; - if (extent == 0) { - *out_start = *out_end = start; - return; - } else { - if (stride > 0) - end += stride * (extent - 1); - else - start += stride * (extent - 1); - } - } - *out_start = start; - *out_end = end + itemsize; -} -static int -__pyx_slices_overlap(__Pyx_memviewslice *slice1, - __Pyx_memviewslice *slice2, - int ndim, size_t itemsize) -{ - void *start1, *end1, *start2, *end2; - __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); - __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); - return (start1 < end2) && (start2 < end1); -} - -/* Capsule */ -static CYTHON_INLINE PyObject * -__pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) -{ - PyObject *cobj; -#if PY_VERSION_HEX >= 0x02070000 - cobj = PyCapsule_New(p, sig, NULL); -#else - cobj = PyCObject_FromVoidPtr(p, NULL); -#endif - return cobj; -} - -/* IsLittleEndian */ -static CYTHON_INLINE int __Pyx_Is_Little_Endian(void) -{ - union { - uint32_t u32; - uint8_t u8[4]; - } S; - S.u32 = 0x01020304; - return S.u8[0] == 4; -} - -/* BufferFormatCheck */ -static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, - __Pyx_BufFmt_StackElem* stack, - __Pyx_TypeInfo* type) { - stack[0].field = &ctx->root; - stack[0].parent_offset = 0; - ctx->root.type = type; - ctx->root.name = "buffer dtype"; - ctx->root.offset = 0; - ctx->head = stack; - ctx->head->field = &ctx->root; - ctx->fmt_offset = 0; - ctx->head->parent_offset = 0; - ctx->new_packmode = '@'; - ctx->enc_packmode = '@'; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->is_complex = 0; - ctx->is_valid_array = 0; - ctx->struct_alignment = 0; - while (type->typegroup == 'S') { - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = 0; - type = type->fields->type; - } -} -static int __Pyx_BufFmt_ParseNumber(const char** ts) { - int count; - const char* t = *ts; - if (*t < '0' || *t > '9') { - return -1; - } else { - count = *t++ - '0'; - while (*t >= '0' && *t <= '9') { - count *= 10; - count += *t++ - '0'; - } - } - *ts = t; - return count; -} -static int __Pyx_BufFmt_ExpectNumber(const char **ts) { - int number = __Pyx_BufFmt_ParseNumber(ts); - if (number == -1) - PyErr_Format(PyExc_ValueError,\ - "Does not understand character buffer dtype format string ('%c')", **ts); - return number; -} -static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { - PyErr_Format(PyExc_ValueError, - "Unexpected format string character: '%c'", ch); -} -static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { - switch (ch) { - case '?': return "'bool'"; - case 'c': return "'char'"; - case 'b': return "'signed char'"; - case 'B': return "'unsigned char'"; - case 'h': return "'short'"; - case 'H': return "'unsigned short'"; - case 'i': return "'int'"; - case 'I': return "'unsigned int'"; - case 'l': return "'long'"; - case 'L': return "'unsigned long'"; - case 'q': return "'long long'"; - case 'Q': return "'unsigned long long'"; - case 'f': return (is_complex ? "'complex float'" : "'float'"); - case 'd': return (is_complex ? "'complex double'" : "'double'"); - case 'g': return (is_complex ? "'complex long double'" : "'long double'"); - case 'T': return "a struct"; - case 'O': return "Python object"; - case 'P': return "a pointer"; - case 's': case 'p': return "a string"; - case 0: return "end"; - default: return "unparseable format string"; - } -} -static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return 2; - case 'i': case 'I': case 'l': case 'L': return 4; - case 'q': case 'Q': return 8; - case 'f': return (is_complex ? 8 : 4); - case 'd': return (is_complex ? 16 : 8); - case 'g': { - PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); - return 0; - } - case 'O': case 'P': return sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } -} -static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(short); - case 'i': case 'I': return sizeof(int); - case 'l': case 'L': return sizeof(long); - #ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(PY_LONG_LONG); - #endif - case 'f': return sizeof(float) * (is_complex ? 2 : 1); - case 'd': return sizeof(double) * (is_complex ? 2 : 1); - case 'g': return sizeof(long double) * (is_complex ? 2 : 1); - case 'O': case 'P': return sizeof(void*); - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } - } -} -typedef struct { char c; short x; } __Pyx_st_short; -typedef struct { char c; int x; } __Pyx_st_int; -typedef struct { char c; long x; } __Pyx_st_long; -typedef struct { char c; float x; } __Pyx_st_float; -typedef struct { char c; double x; } __Pyx_st_double; -typedef struct { char c; long double x; } __Pyx_st_longdouble; -typedef struct { char c; void *x; } __Pyx_st_void_p; -#ifdef HAVE_LONG_LONG -typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; -#endif -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); - case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); - case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); -#ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); -#endif - case 'f': return sizeof(__Pyx_st_float) - sizeof(float); - case 'd': return sizeof(__Pyx_st_double) - sizeof(double); - case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); - case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } -} -/* These are for computing the padding at the end of the struct to align - on the first member of the struct. This will probably the same as above, - but we don't have any guarantees. - */ -typedef struct { short x; char c; } __Pyx_pad_short; -typedef struct { int x; char c; } __Pyx_pad_int; -typedef struct { long x; char c; } __Pyx_pad_long; -typedef struct { float x; char c; } __Pyx_pad_float; -typedef struct { double x; char c; } __Pyx_pad_double; -typedef struct { long double x; char c; } __Pyx_pad_longdouble; -typedef struct { void *x; char c; } __Pyx_pad_void_p; -#ifdef HAVE_LONG_LONG -typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; -#endif -static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); - case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); - case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); -#ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); -#endif - case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); - case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); - case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); - case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } -} -static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { - switch (ch) { - case 'c': - return 'H'; - case 'b': case 'h': case 'i': - case 'l': case 'q': case 's': case 'p': - return 'I'; - case '?': case 'B': case 'H': case 'I': case 'L': case 'Q': - return 'U'; - case 'f': case 'd': case 'g': - return (is_complex ? 'C' : 'R'); - case 'O': - return 'O'; - case 'P': - return 'P'; - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } - } -} -static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { - if (ctx->head == NULL || ctx->head->field == &ctx->root) { - const char* expected; - const char* quote; - if (ctx->head == NULL) { - expected = "end"; - quote = ""; - } else { - expected = ctx->head->field->type->name; - quote = "'"; - } - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected %s%s%s but got %s", - quote, expected, quote, - __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); - } else { - __Pyx_StructField* field = ctx->head->field; - __Pyx_StructField* parent = (ctx->head - 1)->field; - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", - field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), - parent->type->name, field->name); - } -} -static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { - char group; - size_t size, offset, arraysize = 1; - if (ctx->enc_type == 0) return 0; - if (ctx->head->field->type->arraysize[0]) { - int i, ndim = 0; - if (ctx->enc_type == 's' || ctx->enc_type == 'p') { - ctx->is_valid_array = ctx->head->field->type->ndim == 1; - ndim = 1; - if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { - PyErr_Format(PyExc_ValueError, - "Expected a dimension of size %zu, got %zu", - ctx->head->field->type->arraysize[0], ctx->enc_count); - return -1; - } - } - if (!ctx->is_valid_array) { - PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", - ctx->head->field->type->ndim, ndim); - return -1; - } - for (i = 0; i < ctx->head->field->type->ndim; i++) { - arraysize *= ctx->head->field->type->arraysize[i]; - } - ctx->is_valid_array = 0; - ctx->enc_count = 1; - } - group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); - do { - __Pyx_StructField* field = ctx->head->field; - __Pyx_TypeInfo* type = field->type; - if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { - size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); - } else { - size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); - } - if (ctx->enc_packmode == '@') { - size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); - size_t align_mod_offset; - if (align_at == 0) return -1; - align_mod_offset = ctx->fmt_offset % align_at; - if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; - if (ctx->struct_alignment == 0) - ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, - ctx->is_complex); - } - if (type->size != size || type->typegroup != group) { - if (type->typegroup == 'C' && type->fields != NULL) { - size_t parent_offset = ctx->head->parent_offset + field->offset; - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = parent_offset; - continue; - } - if ((type->typegroup == 'H' || group == 'H') && type->size == size) { - } else { - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; - } - } - offset = ctx->head->parent_offset + field->offset; - if (ctx->fmt_offset != offset) { - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", - (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); - return -1; - } - ctx->fmt_offset += size; - if (arraysize) - ctx->fmt_offset += (arraysize - 1) * size; - --ctx->enc_count; - while (1) { - if (field == &ctx->root) { - ctx->head = NULL; - if (ctx->enc_count != 0) { - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; - } - break; - } - ctx->head->field = ++field; - if (field->type == NULL) { - --ctx->head; - field = ctx->head->field; - continue; - } else if (field->type->typegroup == 'S') { - size_t parent_offset = ctx->head->parent_offset + field->offset; - if (field->type->fields->type == NULL) continue; - field = field->type->fields; - ++ctx->head; - ctx->head->field = field; - ctx->head->parent_offset = parent_offset; - break; - } else { - break; - } - } - } while (ctx->enc_count); - ctx->enc_type = 0; - ctx->is_complex = 0; - return 0; -} -static PyObject * -__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) -{ - const char *ts = *tsp; - int i = 0, number, ndim; - ++ts; - if (ctx->new_count != 1) { - PyErr_SetString(PyExc_ValueError, - "Cannot handle repeated arrays in format string"); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ndim = ctx->head->field->type->ndim; - while (*ts && *ts != ')') { - switch (*ts) { - case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; - default: break; - } - number = __Pyx_BufFmt_ExpectNumber(&ts); - if (number == -1) return NULL; - if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) - return PyErr_Format(PyExc_ValueError, - "Expected a dimension of size %zu, got %d", - ctx->head->field->type->arraysize[i], number); - if (*ts != ',' && *ts != ')') - return PyErr_Format(PyExc_ValueError, - "Expected a comma in format string, got '%c'", *ts); - if (*ts == ',') ts++; - i++; - } - if (i != ndim) - return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", - ctx->head->field->type->ndim, i); - if (!*ts) { - PyErr_SetString(PyExc_ValueError, - "Unexpected end of format string, expected ')'"); - return NULL; - } - ctx->is_valid_array = 1; - ctx->new_count = 1; - *tsp = ++ts; - return Py_None; -} -static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { - int got_Z = 0; - while (1) { - switch(*ts) { - case 0: - if (ctx->enc_type != 0 && ctx->head == NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - if (ctx->head != NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - return ts; - case ' ': - case '\r': - case '\n': - ++ts; - break; - case '<': - if (!__Pyx_Is_Little_Endian()) { - PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); - return NULL; - } - ctx->new_packmode = '='; - ++ts; - break; - case '>': - case '!': - if (__Pyx_Is_Little_Endian()) { - PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); - return NULL; - } - ctx->new_packmode = '='; - ++ts; - break; - case '=': - case '@': - case '^': - ctx->new_packmode = *ts++; - break; - case 'T': - { - const char* ts_after_sub; - size_t i, struct_count = ctx->new_count; - size_t struct_alignment = ctx->struct_alignment; - ctx->new_count = 1; - ++ts; - if (*ts != '{') { - PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_type = 0; - ctx->enc_count = 0; - ctx->struct_alignment = 0; - ++ts; - ts_after_sub = ts; - for (i = 0; i != struct_count; ++i) { - ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); - if (!ts_after_sub) return NULL; - } - ts = ts_after_sub; - if (struct_alignment) ctx->struct_alignment = struct_alignment; - } - break; - case '}': - { - size_t alignment = ctx->struct_alignment; - ++ts; - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_type = 0; - if (alignment && ctx->fmt_offset % alignment) { - ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); - } - } - return ts; - case 'x': - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->fmt_offset += ctx->new_count; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->enc_packmode = ctx->new_packmode; - ++ts; - break; - case 'Z': - got_Z = 1; - ++ts; - if (*ts != 'f' && *ts != 'd' && *ts != 'g') { - __Pyx_BufFmt_RaiseUnexpectedChar('Z'); - return NULL; - } - CYTHON_FALLTHROUGH; - case '?': case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': - case 'l': case 'L': case 'q': case 'Q': - case 'f': case 'd': case 'g': - case 'O': case 'p': - if ((ctx->enc_type == *ts) && (got_Z == ctx->is_complex) && - (ctx->enc_packmode == ctx->new_packmode) && (!ctx->is_valid_array)) { - ctx->enc_count += ctx->new_count; - ctx->new_count = 1; - got_Z = 0; - ++ts; - break; - } - CYTHON_FALLTHROUGH; - case 's': - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_count = ctx->new_count; - ctx->enc_packmode = ctx->new_packmode; - ctx->enc_type = *ts; - ctx->is_complex = got_Z; - ++ts; - ctx->new_count = 1; - got_Z = 0; - break; - case ':': - ++ts; - while(*ts != ':') ++ts; - ++ts; - break; - case '(': - if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; - break; - default: - { - int number = __Pyx_BufFmt_ExpectNumber(&ts); - if (number == -1) return NULL; - ctx->new_count = (size_t)number; - } - } - } -} - -/* TypeInfoCompare */ - static int -__pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) -{ - int i; - if (!a || !b) - return 0; - if (a == b) - return 1; - if (a->size != b->size || a->typegroup != b->typegroup || - a->is_unsigned != b->is_unsigned || a->ndim != b->ndim) { - if (a->typegroup == 'H' || b->typegroup == 'H') { - return a->size == b->size; - } else { - return 0; - } - } - if (a->ndim) { - for (i = 0; i < a->ndim; i++) - if (a->arraysize[i] != b->arraysize[i]) - return 0; - } - if (a->typegroup == 'S') { - if (a->flags != b->flags) - return 0; - if (a->fields || b->fields) { - if (!(a->fields && b->fields)) - return 0; - for (i = 0; a->fields[i].type && b->fields[i].type; i++) { - __Pyx_StructField *field_a = a->fields + i; - __Pyx_StructField *field_b = b->fields + i; - if (field_a->offset != field_b->offset || - !__pyx_typeinfo_cmp(field_a->type, field_b->type)) - return 0; - } - return !a->fields[i].type && !b->fields[i].type; - } - } - return 1; -} - -/* MemviewSliceValidateAndInit */ - static int -__pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec) -{ - if (buf->shape[dim] <= 1) - return 1; - if (buf->strides) { - if (spec & __Pyx_MEMVIEW_CONTIG) { - if (spec & (__Pyx_MEMVIEW_PTR|__Pyx_MEMVIEW_FULL)) { - if (unlikely(buf->strides[dim] != sizeof(void *))) { - PyErr_Format(PyExc_ValueError, - "Buffer is not indirectly contiguous " - "in dimension %d.", dim); - goto fail; - } - } else if (unlikely(buf->strides[dim] != buf->itemsize)) { - PyErr_SetString(PyExc_ValueError, - "Buffer and memoryview are not contiguous " - "in the same dimension."); - goto fail; - } - } - if (spec & __Pyx_MEMVIEW_FOLLOW) { - Py_ssize_t stride = buf->strides[dim]; - if (stride < 0) - stride = -stride; - if (unlikely(stride < buf->itemsize)) { - PyErr_SetString(PyExc_ValueError, - "Buffer and memoryview are not contiguous " - "in the same dimension."); - goto fail; - } - } - } else { - if (unlikely(spec & __Pyx_MEMVIEW_CONTIG && dim != ndim - 1)) { - PyErr_Format(PyExc_ValueError, - "C-contiguous buffer is not contiguous in " - "dimension %d", dim); - goto fail; - } else if (unlikely(spec & (__Pyx_MEMVIEW_PTR))) { - PyErr_Format(PyExc_ValueError, - "C-contiguous buffer is not indirect in " - "dimension %d", dim); - goto fail; - } else if (unlikely(buf->suboffsets)) { - PyErr_SetString(PyExc_ValueError, - "Buffer exposes suboffsets but no strides"); - goto fail; - } - } - return 1; -fail: - return 0; -} -static int -__pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec) -{ - if (spec & __Pyx_MEMVIEW_DIRECT) { - if (unlikely(buf->suboffsets && buf->suboffsets[dim] >= 0)) { - PyErr_Format(PyExc_ValueError, - "Buffer not compatible with direct access " - "in dimension %d.", dim); - goto fail; - } - } - if (spec & __Pyx_MEMVIEW_PTR) { - if (unlikely(!buf->suboffsets || (buf->suboffsets[dim] < 0))) { - PyErr_Format(PyExc_ValueError, - "Buffer is not indirectly accessible " - "in dimension %d.", dim); - goto fail; - } - } - return 1; -fail: - return 0; -} -static int -__pyx_verify_contig(Py_buffer *buf, int ndim, int c_or_f_flag) -{ - int i; - if (c_or_f_flag & __Pyx_IS_F_CONTIG) { - Py_ssize_t stride = 1; - for (i = 0; i < ndim; i++) { - if (unlikely(stride * buf->itemsize != buf->strides[i] && buf->shape[i] > 1)) { - PyErr_SetString(PyExc_ValueError, - "Buffer not fortran contiguous."); - goto fail; - } - stride = stride * buf->shape[i]; - } - } else if (c_or_f_flag & __Pyx_IS_C_CONTIG) { - Py_ssize_t stride = 1; - for (i = ndim - 1; i >- 1; i--) { - if (unlikely(stride * buf->itemsize != buf->strides[i] && buf->shape[i] > 1)) { - PyErr_SetString(PyExc_ValueError, - "Buffer not C contiguous."); - goto fail; - } - stride = stride * buf->shape[i]; - } - } - return 1; -fail: - return 0; -} -static int __Pyx_ValidateAndInit_memviewslice( - int *axes_specs, - int c_or_f_flag, - int buf_flags, - int ndim, - __Pyx_TypeInfo *dtype, - __Pyx_BufFmt_StackElem stack[], - __Pyx_memviewslice *memviewslice, - PyObject *original_obj) -{ - struct __pyx_memoryview_obj *memview, *new_memview; - __Pyx_RefNannyDeclarations - Py_buffer *buf; - int i, spec = 0, retval = -1; - __Pyx_BufFmt_Context ctx; - int from_memoryview = __pyx_memoryview_check(original_obj); - __Pyx_RefNannySetupContext("ValidateAndInit_memviewslice", 0); - if (from_memoryview && __pyx_typeinfo_cmp(dtype, ((struct __pyx_memoryview_obj *) - original_obj)->typeinfo)) { - memview = (struct __pyx_memoryview_obj *) original_obj; - new_memview = NULL; - } else { - memview = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( - original_obj, buf_flags, 0, dtype); - new_memview = memview; - if (unlikely(!memview)) - goto fail; - } - buf = &memview->view; - if (unlikely(buf->ndim != ndim)) { - PyErr_Format(PyExc_ValueError, - "Buffer has wrong number of dimensions (expected %d, got %d)", - ndim, buf->ndim); - goto fail; - } - if (new_memview) { - __Pyx_BufFmt_Init(&ctx, stack, dtype); - if (unlikely(!__Pyx_BufFmt_CheckString(&ctx, buf->format))) goto fail; - } - if (unlikely((unsigned) buf->itemsize != dtype->size)) { - PyErr_Format(PyExc_ValueError, - "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "u byte%s) " - "does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "u byte%s)", - buf->itemsize, - (buf->itemsize > 1) ? "s" : "", - dtype->name, - dtype->size, - (dtype->size > 1) ? "s" : ""); - goto fail; - } - if (buf->len > 0) { - for (i = 0; i < ndim; i++) { - spec = axes_specs[i]; - if (unlikely(!__pyx_check_strides(buf, i, ndim, spec))) - goto fail; - if (unlikely(!__pyx_check_suboffsets(buf, i, ndim, spec))) - goto fail; - } - if (unlikely(buf->strides && !__pyx_verify_contig(buf, ndim, c_or_f_flag))) - goto fail; - } - if (unlikely(__Pyx_init_memviewslice(memview, ndim, memviewslice, - new_memview != NULL) == -1)) { - goto fail; - } - retval = 0; - goto no_fail; -fail: - Py_XDECREF(new_memview); - retval = -1; -no_fail: - __Pyx_RefNannyFinishContext(); - return retval; -} - -/* ObjectToMemviewSlice */ - static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_int(PyObject *obj, int writable_flag) { - __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_BufFmt_StackElem stack[1]; - int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; - int retcode; - if (obj == Py_None) { - result.memview = (struct __pyx_memoryview_obj *) Py_None; - return result; - } - retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, - (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT) | writable_flag, 3, - &__Pyx_TypeInfo_int, stack, - &result, obj); - if (unlikely(retcode == -1)) - goto __pyx_fail; - return result; -__pyx_fail: - result.memview = NULL; - result.data = NULL; - return result; -} - -/* ObjectToMemviewSlice */ - static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_float(PyObject *obj, int writable_flag) { - __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_BufFmt_StackElem stack[1]; - int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; - int retcode; - if (obj == Py_None) { - result.memview = (struct __pyx_memoryview_obj *) Py_None; - return result; - } - retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, - (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT) | writable_flag, 3, - &__Pyx_TypeInfo_float, stack, - &result, obj); - if (unlikely(retcode == -1)) - goto __pyx_fail; - return result; -__pyx_fail: - result.memview = NULL; - result.data = NULL; - return result; -} - -/* ObjectToMemviewSlice */ - static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_int(PyObject *obj, int writable_flag) { - __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_BufFmt_StackElem stack[1]; - int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; - int retcode; - if (obj == Py_None) { - result.memview = (struct __pyx_memoryview_obj *) Py_None; - return result; - } - retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, - (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT) | writable_flag, 1, - &__Pyx_TypeInfo_int, stack, - &result, obj); - if (unlikely(retcode == -1)) - goto __pyx_fail; - return result; -__pyx_fail: - result.memview = NULL; - result.data = NULL; - return result; -} - -/* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { - const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(int) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(int) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); -#endif - } - } else { - if (sizeof(int) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); -#endif - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(int), - little, !is_unsigned); - } -} - -/* CIntFromPyVerify */ - #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ - __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) -#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ - __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) -#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ - {\ - func_type value = func_value;\ - if (sizeof(target_type) < sizeof(func_type)) {\ - if (unlikely(value != (func_type) (target_type) value)) {\ - func_type zero = 0;\ - if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ - return (target_type) -1;\ - if (is_unsigned && unlikely(value < zero))\ - goto raise_neg_overflow;\ - else\ - goto raise_overflow;\ - }\ - }\ - return (target_type) value;\ - } - -/* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { - const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(long) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(long) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); -#endif - } - } else { - if (sizeof(long) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); -#endif - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(long), - little, !is_unsigned); - } -} - -/* MemviewSliceCopyTemplate */ - static __Pyx_memviewslice -__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, - const char *mode, int ndim, - size_t sizeof_dtype, int contig_flag, - int dtype_is_object) -{ - __Pyx_RefNannyDeclarations - int i; - __Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } }; - struct __pyx_memoryview_obj *from_memview = from_mvs->memview; - Py_buffer *buf = &from_memview->view; - PyObject *shape_tuple = NULL; - PyObject *temp_int = NULL; - struct __pyx_array_obj *array_obj = NULL; - struct __pyx_memoryview_obj *memview_obj = NULL; - __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); - for (i = 0; i < ndim; i++) { - if (unlikely(from_mvs->suboffsets[i] >= 0)) { - PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " - "indirect dimensions (axis %d)", i); - goto fail; - } - } - shape_tuple = PyTuple_New(ndim); - if (unlikely(!shape_tuple)) { - goto fail; - } - __Pyx_GOTREF(shape_tuple); - for(i = 0; i < ndim; i++) { - temp_int = PyInt_FromSsize_t(from_mvs->shape[i]); - if(unlikely(!temp_int)) { - goto fail; - } else { - PyTuple_SET_ITEM(shape_tuple, i, temp_int); - temp_int = NULL; - } - } - array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); - if (unlikely(!array_obj)) { - goto fail; - } - __Pyx_GOTREF(array_obj); - memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( - (PyObject *) array_obj, contig_flag, - dtype_is_object, - from_mvs->memview->typeinfo); - if (unlikely(!memview_obj)) - goto fail; - if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) - goto fail; - if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, - dtype_is_object) < 0)) - goto fail; - goto no_fail; -fail: - __Pyx_XDECREF(new_mvs.memview); - new_mvs.memview = NULL; - new_mvs.data = NULL; -no_fail: - __Pyx_XDECREF(shape_tuple); - __Pyx_XDECREF(temp_int); - __Pyx_XDECREF(array_obj); - __Pyx_RefNannyFinishContext(); - return new_mvs; -} - -/* CIntFromPy */ - static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { - const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(int) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (int) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (int) 0; - case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) - case 2: - if (8 * sizeof(int) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { - return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(int) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { - return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(int) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { - return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (int) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(int) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (int) 0; - case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) - case -2: - if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(int) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(int) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(int) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { - return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - } -#endif - if (sizeof(int) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - int val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (int) -1; - } - } else { - int val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (int) -1; - val = __Pyx_PyInt_As_int(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to int"); - return (int) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to int"); - return (int) -1; -} - -/* CIntFromPy */ - static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { - const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(long) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (long) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (long) 0; - case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) - case 2: - if (8 * sizeof(long) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { - return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(long) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { - return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(long) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { - return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (long) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(long) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (long) 0; - case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) - case -2: - if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(long) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(long) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(long) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - } -#endif - if (sizeof(long) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - long val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (long) -1; - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (long) -1; - val = __Pyx_PyInt_As_long(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to long"); - return (long) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long) -1; -} - -/* CIntFromPy */ - static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { - const char neg_one = (char) ((char) 0 - (char) 1), const_zero = (char) 0; - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(char) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(char, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (char) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (char) 0; - case 1: __PYX_VERIFY_RETURN_INT(char, digit, digits[0]) - case 2: - if (8 * sizeof(char) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) >= 2 * PyLong_SHIFT) { - return (char) (((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(char) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) >= 3 * PyLong_SHIFT) { - return (char) (((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(char) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) >= 4 * PyLong_SHIFT) { - return (char) (((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (char) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(char) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(char, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(char) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(char, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (char) 0; - case -1: __PYX_VERIFY_RETURN_INT(char, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(char, digit, +digits[0]) - case -2: - if (8 * sizeof(char) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { - return (char) (((char)-1)*(((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(char) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { - return (char) ((((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { - return (char) (((char)-1)*(((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(char) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { - return (char) ((((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { - return (char) (((char)-1)*(((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(char) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { - return (char) ((((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); - } - } - break; - } -#endif - if (sizeof(char) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(char, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(char) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(char, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - char val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (char) -1; - } - } else { - char val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (char) -1; - val = __Pyx_PyInt_As_char(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to char"); - return (char) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to char"); - return (char) -1; -} - -/* CheckBinaryVersion */ - static int __Pyx_check_binary_version(void) { - char ctversion[4], rtversion[4]; - PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); - PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); - if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { - char message[200]; - PyOS_snprintf(message, sizeof(message), - "compiletime version %s of module '%.100s' " - "does not match runtime version %s", - ctversion, __Pyx_MODULE_NAME, rtversion); - return PyErr_WarnEx(NULL, message, 1); - } - return 0; -} - -/* InitStrings */ - static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { - while (t->p) { - #if PY_MAJOR_VERSION < 3 - if (t->is_unicode) { - *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); - } else if (t->intern) { - *t->p = PyString_InternFromString(t->s); - } else { - *t->p = PyString_FromStringAndSize(t->s, t->n - 1); - } - #else - if (t->is_unicode | t->is_str) { - if (t->intern) { - *t->p = PyUnicode_InternFromString(t->s); - } else if (t->encoding) { - *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); - } else { - *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); - } - } else { - *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); - } - #endif - if (!*t->p) - return -1; - if (PyObject_Hash(*t->p) == -1) - return -1; - ++t; - } - return 0; -} - -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { - return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); -} -static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { - Py_ssize_t ignore; - return __Pyx_PyObject_AsStringAndSize(o, &ignore); -} -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -#if !CYTHON_PEP393_ENABLED -static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { - char* defenc_c; - PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); - if (!defenc) return NULL; - defenc_c = PyBytes_AS_STRING(defenc); -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - { - char* end = defenc_c + PyBytes_GET_SIZE(defenc); - char* c; - for (c = defenc_c; c < end; c++) { - if ((unsigned char) (*c) >= 128) { - PyUnicode_AsASCIIString(o); - return NULL; - } - } - } -#endif - *length = PyBytes_GET_SIZE(defenc); - return defenc_c; -} -#else -static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { - if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - if (likely(PyUnicode_IS_ASCII(o))) { - *length = PyUnicode_GET_LENGTH(o); - return PyUnicode_AsUTF8(o); - } else { - PyUnicode_AsASCIIString(o); - return NULL; - } -#else - return PyUnicode_AsUTF8AndSize(o, length); -#endif -} -#endif -#endif -static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT - if ( -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - __Pyx_sys_getdefaultencoding_not_ascii && -#endif - PyUnicode_Check(o)) { - return __Pyx_PyUnicode_AsStringAndSize(o, length); - } else -#endif -#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) - if (PyByteArray_Check(o)) { - *length = PyByteArray_GET_SIZE(o); - return PyByteArray_AS_STRING(o); - } else -#endif - { - char* result; - int r = PyBytes_AsStringAndSize(o, &result, length); - if (unlikely(r < 0)) { - return NULL; - } else { - return result; - } - } -} -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { - int is_true = x == Py_True; - if (is_true | (x == Py_False) | (x == Py_None)) return is_true; - else return PyObject_IsTrue(x); -} -static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { - int retval; - if (unlikely(!x)) return -1; - retval = __Pyx_PyObject_IsTrue(x); - Py_DECREF(x); - return retval; -} -static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { -#if PY_MAJOR_VERSION >= 3 - if (PyLong_Check(result)) { - if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, - "__int__ returned non-int (type %.200s). " - "The ability to return an instance of a strict subclass of int " - "is deprecated, and may be removed in a future version of Python.", - Py_TYPE(result)->tp_name)) { - Py_DECREF(result); - return NULL; - } - return result; - } -#endif - PyErr_Format(PyExc_TypeError, - "__%.4s__ returned non-%.4s (type %.200s)", - type_name, type_name, Py_TYPE(result)->tp_name); - Py_DECREF(result); - return NULL; -} -static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { -#if CYTHON_USE_TYPE_SLOTS - PyNumberMethods *m; -#endif - const char *name = NULL; - PyObject *res = NULL; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x) || PyLong_Check(x))) -#else - if (likely(PyLong_Check(x))) -#endif - return __Pyx_NewRef(x); -#if CYTHON_USE_TYPE_SLOTS - m = Py_TYPE(x)->tp_as_number; - #if PY_MAJOR_VERSION < 3 - if (m && m->nb_int) { - name = "int"; - res = m->nb_int(x); - } - else if (m && m->nb_long) { - name = "long"; - res = m->nb_long(x); - } - #else - if (likely(m && m->nb_int)) { - name = "int"; - res = m->nb_int(x); - } - #endif -#else - if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { - res = PyNumber_Int(x); - } -#endif - if (likely(res)) { -#if PY_MAJOR_VERSION < 3 - if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { -#else - if (unlikely(!PyLong_CheckExact(res))) { -#endif - return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); - } - } - else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "an integer is required"); - } - return res; -} -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { - Py_ssize_t ival; - PyObject *x; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(b))) { - if (sizeof(Py_ssize_t) >= sizeof(long)) - return PyInt_AS_LONG(b); - else - return PyInt_AsSsize_t(b); - } -#endif - if (likely(PyLong_CheckExact(b))) { - #if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)b)->ob_digit; - const Py_ssize_t size = Py_SIZE(b); - if (likely(__Pyx_sst_abs(size) <= 1)) { - ival = likely(size) ? digits[0] : 0; - if (size == -1) ival = -ival; - return ival; - } else { - switch (size) { - case 2: - if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { - return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -2: - if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case 3: - if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { - return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -3: - if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case 4: - if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { - return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -4: - if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - } - } - #endif - return PyLong_AsSsize_t(b); - } - x = PyNumber_Index(b); - if (!x) return -1; - ival = PyInt_AsSsize_t(x); - Py_DECREF(x); - return ival; -} -static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { - return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); -} -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { - return PyInt_FromSize_t(ival); -} - - -#endif /* Py_PYTHON_H */ diff --git a/spaces/PrabhuKiranKonda/fastapi-postgres-todo-api/schemas.py b/spaces/PrabhuKiranKonda/fastapi-postgres-todo-api/schemas.py deleted file mode 100644 index 6eaf9bda1961f0858a15056cce1f8e26232e5811..0000000000000000000000000000000000000000 --- a/spaces/PrabhuKiranKonda/fastapi-postgres-todo-api/schemas.py +++ /dev/null @@ -1,54 +0,0 @@ -# why schemas? it is a way to define the structure of the data sent to the server and the data received from the server -from pydantic import BaseModel, Field -import datetime as dt - -# template for user data. this is used to validate the data sent to the server - - -class userBase(BaseModel): - first_name: str = Field(...) - last_name: str = Field(...) - email: str = Field(...,) - - -class userCreate(userBase): - password: str = Field(...) # hashed password - - class Config: - orm_mode = True # to tell pydantic to read the data even if it is not a dict but an ORM model - schema_extra = { - "example": { - "first_name": "John", - "last_name": "Doe", - "email": "qpmzj@example.com", - "password": "password", - } - } - - -class User(userBase): - user_id: int - - class Config: - orm_mode = True - - -class TodoBase(BaseModel): - task_name: str - task_description: str - priority: int - category: str - due_date: dt.date - status: bool = False - - -class TodoCreate(TodoBase): - pass - - -class Todo(TodoBase): - todo_id: int - user_id: int - - class Config: - orm_mode = True diff --git a/spaces/QianFeng/White-box-Cartoonization2308/wbc/network.py b/spaces/QianFeng/White-box-Cartoonization2308/wbc/network.py deleted file mode 100644 index 6f16cee1aa1994d0a78c524f459764de5164e637..0000000000000000000000000000000000000000 --- a/spaces/QianFeng/White-box-Cartoonization2308/wbc/network.py +++ /dev/null @@ -1,62 +0,0 @@ -import tensorflow as tf -import numpy as np -import tensorflow.contrib.slim as slim - - - -def resblock(inputs, out_channel=32, name='resblock'): - - with tf.variable_scope(name): - - x = slim.convolution2d(inputs, out_channel, [3, 3], - activation_fn=None, scope='conv1') - x = tf.nn.leaky_relu(x) - x = slim.convolution2d(x, out_channel, [3, 3], - activation_fn=None, scope='conv2') - - return x + inputs - - - - -def unet_generator(inputs, channel=32, num_blocks=4, name='generator', reuse=False): - with tf.variable_scope(name, reuse=reuse): - - x0 = slim.convolution2d(inputs, channel, [7, 7], activation_fn=None) - x0 = tf.nn.leaky_relu(x0) - - x1 = slim.convolution2d(x0, channel, [3, 3], stride=2, activation_fn=None) - x1 = tf.nn.leaky_relu(x1) - x1 = slim.convolution2d(x1, channel*2, [3, 3], activation_fn=None) - x1 = tf.nn.leaky_relu(x1) - - x2 = slim.convolution2d(x1, channel*2, [3, 3], stride=2, activation_fn=None) - x2 = tf.nn.leaky_relu(x2) - x2 = slim.convolution2d(x2, channel*4, [3, 3], activation_fn=None) - x2 = tf.nn.leaky_relu(x2) - - for idx in range(num_blocks): - x2 = resblock(x2, out_channel=channel*4, name='block_{}'.format(idx)) - - x2 = slim.convolution2d(x2, channel*2, [3, 3], activation_fn=None) - x2 = tf.nn.leaky_relu(x2) - - h1, w1 = tf.shape(x2)[1], tf.shape(x2)[2] - x3 = tf.image.resize_bilinear(x2, (h1*2, w1*2)) - x3 = slim.convolution2d(x3+x1, channel*2, [3, 3], activation_fn=None) - x3 = tf.nn.leaky_relu(x3) - x3 = slim.convolution2d(x3, channel, [3, 3], activation_fn=None) - x3 = tf.nn.leaky_relu(x3) - - h2, w2 = tf.shape(x3)[1], tf.shape(x3)[2] - x4 = tf.image.resize_bilinear(x3, (h2*2, w2*2)) - x4 = slim.convolution2d(x4+x0, channel, [3, 3], activation_fn=None) - x4 = tf.nn.leaky_relu(x4) - x4 = slim.convolution2d(x4, 3, [7, 7], activation_fn=None) - - return x4 - -if __name__ == '__main__': - - - pass \ No newline at end of file diff --git a/spaces/Qrstud/ChatGPT-prompt-generator/README.md b/spaces/Qrstud/ChatGPT-prompt-generator/README.md deleted file mode 100644 index 9765db2c80dd4c4b938060743922163b1718e003..0000000000000000000000000000000000000000 --- a/spaces/Qrstud/ChatGPT-prompt-generator/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: ChatGPT Prompt Generator -emoji: 👨🏻‍🎤 -colorFrom: purple -colorTo: pink -sdk: gradio -sdk_version: 3.16.2 -app_file: app.py -pinned: false -license: apache-2.0 -duplicated_from: merve/ChatGPT-prompt-generator ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/RamziRebai/hf_sum/app.py b/spaces/RamziRebai/hf_sum/app.py deleted file mode 100644 index d4e0bf9b38a2ffa21e4fcc878e791f406122c3b3..0000000000000000000000000000000000000000 --- a/spaces/RamziRebai/hf_sum/app.py +++ /dev/null @@ -1,15 +0,0 @@ -from transformers import pipeline -import gradio as gr - -summarizer= pipeline("summarization", model="facebook/bart-large-cnn", framework="tf", truncation=True) - -def summarize(text): - result= summarizer(text, truncation=True, min_length=30, max_length=130) - return result[0]["summary_text"] - -iface= gr.Interface( - fn= summarize, - inputs= gr.inputs.Textbox(lines=10, placeholder="please put your text here"), - outputs="text" -) -iface.launch() \ No newline at end of file diff --git a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/cachecontrol/__init__.py b/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/cachecontrol/__init__.py deleted file mode 100644 index f631ae6df4747b808cac7c03b38e3e1d48bea00b..0000000000000000000000000000000000000000 --- a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/cachecontrol/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -# SPDX-FileCopyrightText: 2015 Eric Larson -# -# SPDX-License-Identifier: Apache-2.0 - -"""CacheControl import Interface. - -Make it easy to import from cachecontrol without long namespaces. -""" -__author__ = "Eric Larson" -__email__ = "eric@ionrock.org" -__version__ = "0.12.11" - -from .wrapper import CacheControl -from .adapter import CacheControlAdapter -from .controller import CacheController - -import logging -logging.getLogger(__name__).addHandler(logging.NullHandler()) diff --git a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/pygments/formatter.py b/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/pygments/formatter.py deleted file mode 100644 index a2349ef8652c659388ba69477c01989f2e4ce17d..0000000000000000000000000000000000000000 --- a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/pygments/formatter.py +++ /dev/null @@ -1,94 +0,0 @@ -""" - pygments.formatter - ~~~~~~~~~~~~~~~~~~ - - Base formatter class. - - :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import codecs - -from pip._vendor.pygments.util import get_bool_opt -from pip._vendor.pygments.styles import get_style_by_name - -__all__ = ['Formatter'] - - -def _lookup_style(style): - if isinstance(style, str): - return get_style_by_name(style) - return style - - -class Formatter: - """ - Converts a token stream to text. - - Options accepted: - - ``style`` - The style to use, can be a string or a Style subclass - (default: "default"). Not used by e.g. the - TerminalFormatter. - ``full`` - Tells the formatter to output a "full" document, i.e. - a complete self-contained document. This doesn't have - any effect for some formatters (default: false). - ``title`` - If ``full`` is true, the title that should be used to - caption the document (default: ''). - ``encoding`` - If given, must be an encoding name. This will be used to - convert the Unicode token strings to byte strings in the - output. If it is "" or None, Unicode strings will be written - to the output file, which most file-like objects do not - support (default: None). - ``outencoding`` - Overrides ``encoding`` if given. - """ - - #: Name of the formatter - name = None - - #: Shortcuts for the formatter - aliases = [] - - #: fn match rules - filenames = [] - - #: If True, this formatter outputs Unicode strings when no encoding - #: option is given. - unicodeoutput = True - - def __init__(self, **options): - self.style = _lookup_style(options.get('style', 'default')) - self.full = get_bool_opt(options, 'full', False) - self.title = options.get('title', '') - self.encoding = options.get('encoding', None) or None - if self.encoding in ('guess', 'chardet'): - # can happen for e.g. pygmentize -O encoding=guess - self.encoding = 'utf-8' - self.encoding = options.get('outencoding') or self.encoding - self.options = options - - def get_style_defs(self, arg=''): - """ - Return the style definitions for the current style as a string. - - ``arg`` is an additional argument whose meaning depends on the - formatter used. Note that ``arg`` can also be a list or tuple - for some formatters like the html formatter. - """ - return '' - - def format(self, tokensource, outfile): - """ - Format ``tokensource``, an iterable of ``(tokentype, tokenstring)`` - tuples and write it into ``outfile``. - """ - if self.encoding: - # wrap the outfile in a StreamWriter - outfile = codecs.lookup(self.encoding)[3](outfile) - return self.format_unencoded(tokensource, outfile) diff --git a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/setuptools/_distutils/command/bdist_dumb.py b/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/setuptools/_distutils/command/bdist_dumb.py deleted file mode 100644 index 0f52330f67728e5f02d1673dc9683e95f6f9d294..0000000000000000000000000000000000000000 --- a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/setuptools/_distutils/command/bdist_dumb.py +++ /dev/null @@ -1,144 +0,0 @@ -"""distutils.command.bdist_dumb - -Implements the Distutils 'bdist_dumb' command (create a "dumb" built -distribution -- i.e., just an archive to be unpacked under $prefix or -$exec_prefix).""" - -import os -from distutils.core import Command -from distutils.util import get_platform -from distutils.dir_util import remove_tree, ensure_relative -from distutils.errors import DistutilsPlatformError -from distutils.sysconfig import get_python_version -from distutils import log - - -class bdist_dumb(Command): - - description = "create a \"dumb\" built distribution" - - user_options = [ - ('bdist-dir=', 'd', "temporary directory for creating the distribution"), - ( - 'plat-name=', - 'p', - "platform name to embed in generated filenames " - "(default: %s)" % get_platform(), - ), - ( - 'format=', - 'f', - "archive format to create (tar, gztar, bztar, xztar, " "ztar, zip)", - ), - ( - 'keep-temp', - 'k', - "keep the pseudo-installation tree around after " - + "creating the distribution archive", - ), - ('dist-dir=', 'd', "directory to put final built distributions in"), - ('skip-build', None, "skip rebuilding everything (for testing/debugging)"), - ( - 'relative', - None, - "build the archive using relative paths " "(default: false)", - ), - ( - 'owner=', - 'u', - "Owner name used when creating a tar file" " [default: current user]", - ), - ( - 'group=', - 'g', - "Group name used when creating a tar file" " [default: current group]", - ), - ] - - boolean_options = ['keep-temp', 'skip-build', 'relative'] - - default_format = {'posix': 'gztar', 'nt': 'zip'} - - def initialize_options(self): - self.bdist_dir = None - self.plat_name = None - self.format = None - self.keep_temp = 0 - self.dist_dir = None - self.skip_build = None - self.relative = 0 - self.owner = None - self.group = None - - def finalize_options(self): - if self.bdist_dir is None: - bdist_base = self.get_finalized_command('bdist').bdist_base - self.bdist_dir = os.path.join(bdist_base, 'dumb') - - if self.format is None: - try: - self.format = self.default_format[os.name] - except KeyError: - raise DistutilsPlatformError( - "don't know how to create dumb built distributions " - "on platform %s" % os.name - ) - - self.set_undefined_options( - 'bdist', - ('dist_dir', 'dist_dir'), - ('plat_name', 'plat_name'), - ('skip_build', 'skip_build'), - ) - - def run(self): - if not self.skip_build: - self.run_command('build') - - install = self.reinitialize_command('install', reinit_subcommands=1) - install.root = self.bdist_dir - install.skip_build = self.skip_build - install.warn_dir = 0 - - log.info("installing to %s", self.bdist_dir) - self.run_command('install') - - # And make an archive relative to the root of the - # pseudo-installation tree. - archive_basename = "{}.{}".format( - self.distribution.get_fullname(), self.plat_name - ) - - pseudoinstall_root = os.path.join(self.dist_dir, archive_basename) - if not self.relative: - archive_root = self.bdist_dir - else: - if self.distribution.has_ext_modules() and ( - install.install_base != install.install_platbase - ): - raise DistutilsPlatformError( - "can't make a dumb built distribution where " - "base and platbase are different (%s, %s)" - % (repr(install.install_base), repr(install.install_platbase)) - ) - else: - archive_root = os.path.join( - self.bdist_dir, ensure_relative(install.install_base) - ) - - # Make the archive - filename = self.make_archive( - pseudoinstall_root, - self.format, - root_dir=archive_root, - owner=self.owner, - group=self.group, - ) - if self.distribution.has_ext_modules(): - pyversion = get_python_version() - else: - pyversion = 'any' - self.distribution.dist_files.append(('bdist_dumb', pyversion, filename)) - - if not self.keep_temp: - remove_tree(self.bdist_dir, dry_run=self.dry_run) diff --git a/spaces/Realcat/image-matching-webui/third_party/SOLD2/sold2/config/__init__.py b/spaces/Realcat/image-matching-webui/third_party/SOLD2/sold2/config/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmcv/runner/hooks/__init__.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmcv/runner/hooks/__init__.py deleted file mode 100644 index 915af28cefab14a14c1188ed861161080fd138a3..0000000000000000000000000000000000000000 --- a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmcv/runner/hooks/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from .checkpoint import CheckpointHook -from .closure import ClosureHook -from .ema import EMAHook -from .evaluation import DistEvalHook, EvalHook -from .hook import HOOKS, Hook -from .iter_timer import IterTimerHook -from .logger import (DvcliveLoggerHook, LoggerHook, MlflowLoggerHook, - NeptuneLoggerHook, PaviLoggerHook, TensorboardLoggerHook, - TextLoggerHook, WandbLoggerHook) -from .lr_updater import LrUpdaterHook -from .memory import EmptyCacheHook -from .momentum_updater import MomentumUpdaterHook -from .optimizer import (Fp16OptimizerHook, GradientCumulativeFp16OptimizerHook, - GradientCumulativeOptimizerHook, OptimizerHook) -from .profiler import ProfilerHook -from .sampler_seed import DistSamplerSeedHook -from .sync_buffer import SyncBuffersHook - -__all__ = [ - 'HOOKS', 'Hook', 'CheckpointHook', 'ClosureHook', 'LrUpdaterHook', - 'OptimizerHook', 'Fp16OptimizerHook', 'IterTimerHook', - 'DistSamplerSeedHook', 'EmptyCacheHook', 'LoggerHook', 'MlflowLoggerHook', - 'PaviLoggerHook', 'TextLoggerHook', 'TensorboardLoggerHook', - 'NeptuneLoggerHook', 'WandbLoggerHook', 'DvcliveLoggerHook', - 'MomentumUpdaterHook', 'SyncBuffersHook', 'EMAHook', 'EvalHook', - 'DistEvalHook', 'ProfilerHook', 'GradientCumulativeOptimizerHook', - 'GradientCumulativeFp16OptimizerHook' -] diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet_null/core/bbox/samplers/__init__.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet_null/core/bbox/samplers/__init__.py deleted file mode 100644 index 0b06303fe1000e11c5486c40c70606a34a5208e3..0000000000000000000000000000000000000000 --- a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet_null/core/bbox/samplers/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -from .base_sampler import BaseSampler -from .combined_sampler import CombinedSampler -from .instance_balanced_pos_sampler import InstanceBalancedPosSampler -from .iou_balanced_neg_sampler import IoUBalancedNegSampler -from .ohem_sampler import OHEMSampler -from .pseudo_sampler import PseudoSampler -from .random_sampler import RandomSampler -from .sampling_result import SamplingResult -from .score_hlr_sampler import ScoreHLRSampler - -__all__ = [ - 'BaseSampler', 'PseudoSampler', 'RandomSampler', - 'InstanceBalancedPosSampler', 'IoUBalancedNegSampler', 'CombinedSampler', - 'OHEMSampler', 'SamplingResult', 'ScoreHLRSampler' -] diff --git a/spaces/Rongjiehuang/ProDiff/modules/parallel_wavegan/layers/upsample.py b/spaces/Rongjiehuang/ProDiff/modules/parallel_wavegan/layers/upsample.py deleted file mode 100644 index 18c6397c420a81fadc5320e3a48f3249534decd8..0000000000000000000000000000000000000000 --- a/spaces/Rongjiehuang/ProDiff/modules/parallel_wavegan/layers/upsample.py +++ /dev/null @@ -1,183 +0,0 @@ -# -*- coding: utf-8 -*- - -"""Upsampling module. - -This code is modified from https://github.com/r9y9/wavenet_vocoder. - -""" - -import numpy as np -import torch -import torch.nn.functional as F - -from . import Conv1d - - -class Stretch2d(torch.nn.Module): - """Stretch2d module.""" - - def __init__(self, x_scale, y_scale, mode="nearest"): - """Initialize Stretch2d module. - - Args: - x_scale (int): X scaling factor (Time axis in spectrogram). - y_scale (int): Y scaling factor (Frequency axis in spectrogram). - mode (str): Interpolation mode. - - """ - super(Stretch2d, self).__init__() - self.x_scale = x_scale - self.y_scale = y_scale - self.mode = mode - - def forward(self, x): - """Calculate forward propagation. - - Args: - x (Tensor): Input tensor (B, C, F, T). - - Returns: - Tensor: Interpolated tensor (B, C, F * y_scale, T * x_scale), - - """ - return F.interpolate( - x, scale_factor=(self.y_scale, self.x_scale), mode=self.mode) - - -class Conv2d(torch.nn.Conv2d): - """Conv2d module with customized initialization.""" - - def __init__(self, *args, **kwargs): - """Initialize Conv2d module.""" - super(Conv2d, self).__init__(*args, **kwargs) - - def reset_parameters(self): - """Reset parameters.""" - self.weight.data.fill_(1. / np.prod(self.kernel_size)) - if self.bias is not None: - torch.nn.init.constant_(self.bias, 0.0) - - -class UpsampleNetwork(torch.nn.Module): - """Upsampling network module.""" - - def __init__(self, - upsample_scales, - nonlinear_activation=None, - nonlinear_activation_params={}, - interpolate_mode="nearest", - freq_axis_kernel_size=1, - use_causal_conv=False, - ): - """Initialize upsampling network module. - - Args: - upsample_scales (list): List of upsampling scales. - nonlinear_activation (str): Activation function name. - nonlinear_activation_params (dict): Arguments for specified activation function. - interpolate_mode (str): Interpolation mode. - freq_axis_kernel_size (int): Kernel size in the direction of frequency axis. - - """ - super(UpsampleNetwork, self).__init__() - self.use_causal_conv = use_causal_conv - self.up_layers = torch.nn.ModuleList() - for scale in upsample_scales: - # interpolation layer - stretch = Stretch2d(scale, 1, interpolate_mode) - self.up_layers += [stretch] - - # conv layer - assert (freq_axis_kernel_size - 1) % 2 == 0, "Not support even number freq axis kernel size." - freq_axis_padding = (freq_axis_kernel_size - 1) // 2 - kernel_size = (freq_axis_kernel_size, scale * 2 + 1) - if use_causal_conv: - padding = (freq_axis_padding, scale * 2) - else: - padding = (freq_axis_padding, scale) - conv = Conv2d(1, 1, kernel_size=kernel_size, padding=padding, bias=False) - self.up_layers += [conv] - - # nonlinear - if nonlinear_activation is not None: - nonlinear = getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params) - self.up_layers += [nonlinear] - - def forward(self, c): - """Calculate forward propagation. - - Args: - c : Input tensor (B, C, T). - - Returns: - Tensor: Upsampled tensor (B, C, T'), where T' = T * prod(upsample_scales). - - """ - c = c.unsqueeze(1) # (B, 1, C, T) - for f in self.up_layers: - if self.use_causal_conv and isinstance(f, Conv2d): - c = f(c)[..., :c.size(-1)] - else: - c = f(c) - return c.squeeze(1) # (B, C, T') - - -class ConvInUpsampleNetwork(torch.nn.Module): - """Convolution + upsampling network module.""" - - def __init__(self, - upsample_scales, - nonlinear_activation=None, - nonlinear_activation_params={}, - interpolate_mode="nearest", - freq_axis_kernel_size=1, - aux_channels=80, - aux_context_window=0, - use_causal_conv=False - ): - """Initialize convolution + upsampling network module. - - Args: - upsample_scales (list): List of upsampling scales. - nonlinear_activation (str): Activation function name. - nonlinear_activation_params (dict): Arguments for specified activation function. - mode (str): Interpolation mode. - freq_axis_kernel_size (int): Kernel size in the direction of frequency axis. - aux_channels (int): Number of channels of pre-convolutional layer. - aux_context_window (int): Context window size of the pre-convolutional layer. - use_causal_conv (bool): Whether to use causal structure. - - """ - super(ConvInUpsampleNetwork, self).__init__() - self.aux_context_window = aux_context_window - self.use_causal_conv = use_causal_conv and aux_context_window > 0 - # To capture wide-context information in conditional features - kernel_size = aux_context_window + 1 if use_causal_conv else 2 * aux_context_window + 1 - # NOTE(kan-bayashi): Here do not use padding because the input is already padded - self.conv_in = Conv1d(aux_channels, aux_channels, kernel_size=kernel_size, bias=False) - self.upsample = UpsampleNetwork( - upsample_scales=upsample_scales, - nonlinear_activation=nonlinear_activation, - nonlinear_activation_params=nonlinear_activation_params, - interpolate_mode=interpolate_mode, - freq_axis_kernel_size=freq_axis_kernel_size, - use_causal_conv=use_causal_conv, - ) - - def forward(self, c): - """Calculate forward propagation. - - Args: - c : Input tensor (B, C, T'). - - Returns: - Tensor: Upsampled tensor (B, C, T), - where T = (T' - aux_context_window * 2) * prod(upsample_scales). - - Note: - The length of inputs considers the context window size. - - """ - c_ = self.conv_in(c) - c = c_[:, :, :-self.aux_context_window] if self.use_causal_conv else c_ - return self.upsample(c) diff --git a/spaces/Rongjiehuang/ProDiff/modules/parallel_wavegan/optimizers/__init__.py b/spaces/Rongjiehuang/ProDiff/modules/parallel_wavegan/optimizers/__init__.py deleted file mode 100644 index a0e0c5932838281e912079e5784d84d43444a61a..0000000000000000000000000000000000000000 --- a/spaces/Rongjiehuang/ProDiff/modules/parallel_wavegan/optimizers/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from torch.optim import * # NOQA -from .radam import * # NOQA diff --git a/spaces/Sarst/VITS-Umamusume-voice-synthesizer2/attentions.py b/spaces/Sarst/VITS-Umamusume-voice-synthesizer2/attentions.py deleted file mode 100644 index 86bc73b5fe98cc7b443e9078553920346c996707..0000000000000000000000000000000000000000 --- a/spaces/Sarst/VITS-Umamusume-voice-synthesizer2/attentions.py +++ /dev/null @@ -1,300 +0,0 @@ -import math -import torch -from torch import nn -from torch.nn import functional as F - -import commons -from modules import LayerNorm - - -class Encoder(nn.Module): - def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4, **kwargs): - super().__init__() - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.window_size = window_size - - self.drop = nn.Dropout(p_dropout) - self.attn_layers = nn.ModuleList() - self.norm_layers_1 = nn.ModuleList() - self.ffn_layers = nn.ModuleList() - self.norm_layers_2 = nn.ModuleList() - for i in range(self.n_layers): - self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size)) - self.norm_layers_1.append(LayerNorm(hidden_channels)) - self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout)) - self.norm_layers_2.append(LayerNorm(hidden_channels)) - - def forward(self, x, x_mask): - attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1) - x = x * x_mask - for i in range(self.n_layers): - y = self.attn_layers[i](x, x, attn_mask) - y = self.drop(y) - x = self.norm_layers_1[i](x + y) - - y = self.ffn_layers[i](x, x_mask) - y = self.drop(y) - x = self.norm_layers_2[i](x + y) - x = x * x_mask - return x - - -class Decoder(nn.Module): - def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., proximal_bias=False, proximal_init=True, **kwargs): - super().__init__() - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.proximal_bias = proximal_bias - self.proximal_init = proximal_init - - self.drop = nn.Dropout(p_dropout) - self.self_attn_layers = nn.ModuleList() - self.norm_layers_0 = nn.ModuleList() - self.encdec_attn_layers = nn.ModuleList() - self.norm_layers_1 = nn.ModuleList() - self.ffn_layers = nn.ModuleList() - self.norm_layers_2 = nn.ModuleList() - for i in range(self.n_layers): - self.self_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, proximal_init=proximal_init)) - self.norm_layers_0.append(LayerNorm(hidden_channels)) - self.encdec_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout)) - self.norm_layers_1.append(LayerNorm(hidden_channels)) - self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True)) - self.norm_layers_2.append(LayerNorm(hidden_channels)) - - def forward(self, x, x_mask, h, h_mask): - """ - x: decoder input - h: encoder output - """ - self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype) - encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1) - x = x * x_mask - for i in range(self.n_layers): - y = self.self_attn_layers[i](x, x, self_attn_mask) - y = self.drop(y) - x = self.norm_layers_0[i](x + y) - - y = self.encdec_attn_layers[i](x, h, encdec_attn_mask) - y = self.drop(y) - x = self.norm_layers_1[i](x + y) - - y = self.ffn_layers[i](x, x_mask) - y = self.drop(y) - x = self.norm_layers_2[i](x + y) - x = x * x_mask - return x - - -class MultiHeadAttention(nn.Module): - def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False): - super().__init__() - assert channels % n_heads == 0 - - self.channels = channels - self.out_channels = out_channels - self.n_heads = n_heads - self.p_dropout = p_dropout - self.window_size = window_size - self.heads_share = heads_share - self.block_length = block_length - self.proximal_bias = proximal_bias - self.proximal_init = proximal_init - self.attn = None - - self.k_channels = channels // n_heads - self.conv_q = nn.Conv1d(channels, channels, 1) - self.conv_k = nn.Conv1d(channels, channels, 1) - self.conv_v = nn.Conv1d(channels, channels, 1) - self.conv_o = nn.Conv1d(channels, out_channels, 1) - self.drop = nn.Dropout(p_dropout) - - if window_size is not None: - n_heads_rel = 1 if heads_share else n_heads - rel_stddev = self.k_channels**-0.5 - self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev) - self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev) - - nn.init.xavier_uniform_(self.conv_q.weight) - nn.init.xavier_uniform_(self.conv_k.weight) - nn.init.xavier_uniform_(self.conv_v.weight) - if proximal_init: - with torch.no_grad(): - self.conv_k.weight.copy_(self.conv_q.weight) - self.conv_k.bias.copy_(self.conv_q.bias) - - def forward(self, x, c, attn_mask=None): - q = self.conv_q(x) - k = self.conv_k(c) - v = self.conv_v(c) - - x, self.attn = self.attention(q, k, v, mask=attn_mask) - - x = self.conv_o(x) - return x - - def attention(self, query, key, value, mask=None): - # reshape [b, d, t] -> [b, n_h, t, d_k] - b, d, t_s, t_t = (*key.size(), query.size(2)) - query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3) - key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3) - value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3) - - scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1)) - if self.window_size is not None: - assert t_s == t_t, "Relative attention is only available for self-attention." - key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s) - rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings) - scores_local = self._relative_position_to_absolute_position(rel_logits) - scores = scores + scores_local - if self.proximal_bias: - assert t_s == t_t, "Proximal bias is only available for self-attention." - scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype) - if mask is not None: - scores = scores.masked_fill(mask == 0, -1e4) - if self.block_length is not None: - assert t_s == t_t, "Local attention is only available for self-attention." - block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length) - scores = scores.masked_fill(block_mask == 0, -1e4) - p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s] - p_attn = self.drop(p_attn) - output = torch.matmul(p_attn, value) - if self.window_size is not None: - relative_weights = self._absolute_position_to_relative_position(p_attn) - value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s) - output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings) - output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t] - return output, p_attn - - def _matmul_with_relative_values(self, x, y): - """ - x: [b, h, l, m] - y: [h or 1, m, d] - ret: [b, h, l, d] - """ - ret = torch.matmul(x, y.unsqueeze(0)) - return ret - - def _matmul_with_relative_keys(self, x, y): - """ - x: [b, h, l, d] - y: [h or 1, m, d] - ret: [b, h, l, m] - """ - ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1)) - return ret - - def _get_relative_embeddings(self, relative_embeddings, length): - max_relative_position = 2 * self.window_size + 1 - # Pad first before slice to avoid using cond ops. - pad_length = max(length - (self.window_size + 1), 0) - slice_start_position = max((self.window_size + 1) - length, 0) - slice_end_position = slice_start_position + 2 * length - 1 - if pad_length > 0: - padded_relative_embeddings = F.pad( - relative_embeddings, - commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]])) - else: - padded_relative_embeddings = relative_embeddings - used_relative_embeddings = padded_relative_embeddings[:,slice_start_position:slice_end_position] - return used_relative_embeddings - - def _relative_position_to_absolute_position(self, x): - """ - x: [b, h, l, 2*l-1] - ret: [b, h, l, l] - """ - batch, heads, length, _ = x.size() - # Concat columns of pad to shift from relative to absolute indexing. - x = F.pad(x, commons.convert_pad_shape([[0,0],[0,0],[0,0],[0,1]])) - - # Concat extra elements so to add up to shape (len+1, 2*len-1). - x_flat = x.view([batch, heads, length * 2 * length]) - x_flat = F.pad(x_flat, commons.convert_pad_shape([[0,0],[0,0],[0,length-1]])) - - # Reshape and slice out the padded elements. - x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:] - return x_final - - def _absolute_position_to_relative_position(self, x): - """ - x: [b, h, l, l] - ret: [b, h, l, 2*l-1] - """ - batch, heads, length, _ = x.size() - # padd along column - x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]])) - x_flat = x.view([batch, heads, length**2 + length*(length -1)]) - # add 0's in the beginning that will skew the elements after reshape - x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]])) - x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:] - return x_final - - def _attention_bias_proximal(self, length): - """Bias for self-attention to encourage attention to close positions. - Args: - length: an integer scalar. - Returns: - a Tensor with shape [1, 1, length, length] - """ - r = torch.arange(length, dtype=torch.float32) - diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1) - return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0) - - -class FFN(nn.Module): - def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.activation = activation - self.causal = causal - - if causal: - self.padding = self._causal_padding - else: - self.padding = self._same_padding - - self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size) - self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size) - self.drop = nn.Dropout(p_dropout) - - def forward(self, x, x_mask): - x = self.conv_1(self.padding(x * x_mask)) - if self.activation == "gelu": - x = x * torch.sigmoid(1.702 * x) - else: - x = torch.relu(x) - x = self.drop(x) - x = self.conv_2(self.padding(x * x_mask)) - return x * x_mask - - def _causal_padding(self, x): - if self.kernel_size == 1: - return x - pad_l = self.kernel_size - 1 - pad_r = 0 - padding = [[0, 0], [0, 0], [pad_l, pad_r]] - x = F.pad(x, commons.convert_pad_shape(padding)) - return x - - def _same_padding(self, x): - if self.kernel_size == 1: - return x - pad_l = (self.kernel_size - 1) // 2 - pad_r = self.kernel_size // 2 - padding = [[0, 0], [0, 0], [pad_l, pad_r]] - x = F.pad(x, commons.convert_pad_shape(padding)) - return x diff --git a/spaces/Shad0ws/Information_Extraction_with_ChatGPT/README.md b/spaces/Shad0ws/Information_Extraction_with_ChatGPT/README.md deleted file mode 100644 index b7e203a277b7a79eb5b9eea5b4107c1ff08e88f1..0000000000000000000000000000000000000000 --- a/spaces/Shad0ws/Information_Extraction_with_ChatGPT/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Information Extraction With ChatGPT -emoji: 📉 -colorFrom: indigo -colorTo: red -sdk: gradio -sdk_version: 3.16.2 -app_file: app.py -pinned: false -license: mit ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Shakeb100/GroomingGenie_AI/clipseg/setup.py b/spaces/Shakeb100/GroomingGenie_AI/clipseg/setup.py deleted file mode 100644 index 2bf28ffe269cba3033af263db5f98313772818f0..0000000000000000000000000000000000000000 --- a/spaces/Shakeb100/GroomingGenie_AI/clipseg/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -from setuptools import setup - -with open("README.md", "r", encoding="utf-8") as readme_file: - readme = readme_file.read() - -requirements = [ - "numpy", - "scipy", - "matplotlib", - "torch", - "torchvision", - "opencv-python", - "CLIP @ git+https://github.com/openai/CLIP.git" -] - -setup( - name='clipseg', - packages=['clipseg'], - package_dir={'clipseg': 'models'}, - package_data={'clipseg': [ - "../weights/*.pth", - ]}, - version='0.0.1', - url='https://github.com/timojl/clipseg', - python_requires='>=3.9', - install_requires=requirements, - description='This repository contains the code used in the paper "Image Segmentation Using Text and Image Prompts".', - long_description=readme, - long_description_content_type="text/markdown", -) diff --git a/spaces/SilenWang/ReviewGPT/utils/pubmed.py b/spaces/SilenWang/ReviewGPT/utils/pubmed.py deleted file mode 100644 index 77ed4caeec8cc2e3406c167c1e3a7b49760ab0e9..0000000000000000000000000000000000000000 --- a/spaces/SilenWang/ReviewGPT/utils/pubmed.py +++ /dev/null @@ -1,44 +0,0 @@ -from Bio import Entrez - -try: - from utils.config import EMAIL -except ImportError: - from utils.config_sample import EMAIL - - -class PubMedFetcher: - def __init__(self, email=None, pmids=None): - self.email = email if email else EMAIL - self.pmids = pmids - - - def fetch_abstract(self): - # 设置email和搜索关键词 - Entrez.email = self.email - - # 使用文章ID批量获取文章的题录和摘要信息 - handle = Entrez.efetch(db="pubmed", id=self.pmids, rettype="abstract", retmode="xml") - fetch_record = Entrez.read(handle) - - # print(self.pmids) - - articles = [] - for idx, rec in enumerate(fetch_record["PubmedArticle"]): - articles.append({ - 'PMID': self.pmids[idx], - 'Title': rec["MedlineCitation"]["Article"]["ArticleTitle"], - 'Abstract': rec["MedlineCitation"]["Article"]["Abstract"]["AbstractText"][0] if "Abstract" in rec["MedlineCitation"]["Article"] else "" - }) - - return articles - - -if __name__ == '__main__': - - # 设置邮箱地址,提供给NCBI用于联系 - - id_list = [26502953, 19016404, 25837277, 34209617, 35602107] - - fetcher = PubMedFetcher(email=EMAIL, pmids=id_list) - - print(fetcher.fetch_abstract()) diff --git a/spaces/Sonnt/Fracture_Webapp/ui/UIConfigs.py b/spaces/Sonnt/Fracture_Webapp/ui/UIConfigs.py deleted file mode 100644 index d893162a3dea24503c6efe974240dae24d3c9842..0000000000000000000000000000000000000000 --- a/spaces/Sonnt/Fracture_Webapp/ui/UIConfigs.py +++ /dev/null @@ -1,41 +0,0 @@ -import streamlit as st -from PIL import Image - -def hide_menu_button(): - st.markdown(""" """, unsafe_allow_html=True - ) - -def condense_layout(): - padding = 0 - st.markdown(f""" """, unsafe_allow_html=True - ) - -def set_page_config(page:str='home', logo_size:str=200, pagetile:str=None): - img = Image.open("/home/user/app/LogoVPI.png") - st.set_page_config(# Alternate names: setup_page, page, layout - layout="wide", # Can be "centered" or "wide". In the future also "dashboard", etc. - initial_sidebar_state="auto", # Can be "auto", "expanded", "collapsed" - page_title="VPI-MLogs", # String or None. Strings get appended with "• Streamlit". - page_icon=img, # String, anything supported by st.image, or None. - ) - if page == 'home': - col_1, col_2, col_3, col_4, col_5, = st.columns(5) - with col_3: - st.image("https://i.ibb.co/Yd42K98/LogoVPI.png", width=logo_size) - elif page == 'sub': - logo, info = st.columns([3, 7]) - with logo: - st.image("https://i.ibb.co/Yd42K98/LogoVPI.png", width=logo_size) - with info: - st.markdown(pagetile, unsafe_allow_html=True) - - \ No newline at end of file diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/utils/py3compat.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/utils/py3compat.py deleted file mode 100644 index 34af4c58f42bad6de0e9562b2029089f41d813a2..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/utils/py3compat.py +++ /dev/null @@ -1,67 +0,0 @@ -# coding: utf-8 -"""Compatibility tricks for Python 3. Mainly to do with unicode. - -This file is deprecated and will be removed in a future version. -""" -import platform -import builtins as builtin_mod - -from .encoding import DEFAULT_ENCODING - - -def decode(s, encoding=None): - encoding = encoding or DEFAULT_ENCODING - return s.decode(encoding, "replace") - - -def encode(u, encoding=None): - encoding = encoding or DEFAULT_ENCODING - return u.encode(encoding, "replace") - - -def cast_unicode(s, encoding=None): - if isinstance(s, bytes): - return decode(s, encoding) - return s - - -def safe_unicode(e): - """unicode(e) with various fallbacks. Used for exceptions, which may not be - safe to call unicode() on. - """ - try: - return str(e) - except UnicodeError: - pass - - try: - return repr(e) - except UnicodeError: - pass - - return "Unrecoverably corrupt evalue" - - -# keep reference to builtin_mod because the kernel overrides that value -# to forward requests to a frontend. -def input(prompt=""): - return builtin_mod.input(prompt) - - -def execfile(fname, glob, loc=None, compiler=None): - loc = loc if (loc is not None) else glob - with open(fname, "rb") as f: - compiler = compiler or compile - exec(compiler(f.read(), fname, "exec"), glob, loc) - - -PYPY = platform.python_implementation() == "PyPy" - -# Cython still rely on that as a Dec 28 2019 -# See https://github.com/cython/cython/pull/3291 and -# https://github.com/ipython/ipython/issues/12068 -def no_code(x, encoding=None): - return x - - -unicode_to_str = cast_bytes_py2 = no_code diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/PIL/MpoImagePlugin.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/PIL/MpoImagePlugin.py deleted file mode 100644 index f9261c77d6862d7def90c6136dff6449241b0690..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/PIL/MpoImagePlugin.py +++ /dev/null @@ -1,197 +0,0 @@ -# -# The Python Imaging Library. -# $Id$ -# -# MPO file handling -# -# See "Multi-Picture Format" (CIPA DC-007-Translation 2009, Standard of the -# Camera & Imaging Products Association) -# -# The multi-picture object combines multiple JPEG images (with a modified EXIF -# data format) into a single file. While it can theoretically be used much like -# a GIF animation, it is commonly used to represent 3D photographs and is (as -# of this writing) the most commonly used format by 3D cameras. -# -# History: -# 2014-03-13 Feneric Created -# -# See the README file for information on usage and redistribution. -# - -import itertools -import os -import struct - -from . import ( - ExifTags, - Image, - ImageFile, - ImageSequence, - JpegImagePlugin, - TiffImagePlugin, -) -from ._binary import i16be as i16 -from ._binary import o32le - -# def _accept(prefix): -# return JpegImagePlugin._accept(prefix) - - -def _save(im, fp, filename): - JpegImagePlugin._save(im, fp, filename) - - -def _save_all(im, fp, filename): - append_images = im.encoderinfo.get("append_images", []) - if not append_images: - try: - animated = im.is_animated - except AttributeError: - animated = False - if not animated: - _save(im, fp, filename) - return - - mpf_offset = 28 - offsets = [] - for imSequence in itertools.chain([im], append_images): - for im_frame in ImageSequence.Iterator(imSequence): - if not offsets: - # APP2 marker - im_frame.encoderinfo["extra"] = ( - b"\xFF\xE2" + struct.pack(">H", 6 + 82) + b"MPF\0" + b" " * 82 - ) - exif = im_frame.encoderinfo.get("exif") - if isinstance(exif, Image.Exif): - exif = exif.tobytes() - im_frame.encoderinfo["exif"] = exif - if exif: - mpf_offset += 4 + len(exif) - - JpegImagePlugin._save(im_frame, fp, filename) - offsets.append(fp.tell()) - else: - im_frame.save(fp, "JPEG") - offsets.append(fp.tell() - offsets[-1]) - - ifd = TiffImagePlugin.ImageFileDirectory_v2() - ifd[0xB000] = b"0100" - ifd[0xB001] = len(offsets) - - mpentries = b"" - data_offset = 0 - for i, size in enumerate(offsets): - if i == 0: - mptype = 0x030000 # Baseline MP Primary Image - else: - mptype = 0x000000 # Undefined - mpentries += struct.pack(" 1 - self._fp = self.fp # FIXME: hack - self._fp.seek(self.__mpoffsets[0]) # get ready to read first frame - self.__frame = 0 - self.offset = 0 - # for now we can only handle reading and individual frame extraction - self.readonly = 1 - - def load_seek(self, pos): - self._fp.seek(pos) - - def seek(self, frame): - if not self._seek_check(frame): - return - self.fp = self._fp - self.offset = self.__mpoffsets[frame] - - self.fp.seek(self.offset + 2) # skip SOI marker - segment = self.fp.read(2) - if not segment: - msg = "No data found for frame" - raise ValueError(msg) - self._size = self._initial_size - if i16(segment) == 0xFFE1: # APP1 - n = i16(self.fp.read(2)) - 2 - self.info["exif"] = ImageFile._safe_read(self.fp, n) - self._reload_exif() - - mptype = self.mpinfo[0xB002][frame]["Attribute"]["MPType"] - if mptype.startswith("Large Thumbnail"): - exif = self.getexif().get_ifd(ExifTags.IFD.Exif) - if 40962 in exif and 40963 in exif: - self._size = (exif[40962], exif[40963]) - elif "exif" in self.info: - del self.info["exif"] - self._reload_exif() - - self.tile = [("jpeg", (0, 0) + self.size, self.offset, (self.mode, ""))] - self.__frame = frame - - def tell(self): - return self.__frame - - @staticmethod - def adopt(jpeg_instance, mpheader=None): - """ - Transform the instance of JpegImageFile into - an instance of MpoImageFile. - After the call, the JpegImageFile is extended - to be an MpoImageFile. - - This is essentially useful when opening a JPEG - file that reveals itself as an MPO, to avoid - double call to _open. - """ - jpeg_instance.__class__ = MpoImageFile - jpeg_instance._after_jpeg_open(mpheader) - return jpeg_instance - - -# --------------------------------------------------------------------- -# Registry stuff - -# Note that since MPO shares a factory with JPEG, we do not need to do a -# separate registration for it here. -# Image.register_open(MpoImageFile.format, -# JpegImagePlugin.jpeg_factory, _accept) -Image.register_save(MpoImageFile.format, _save) -Image.register_save_all(MpoImageFile.format, _save_all) - -Image.register_extension(MpoImageFile.format, ".mpo") - -Image.register_mime(MpoImageFile.format, "image/mpo") diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/adodbapi/adodbapi.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/adodbapi/adodbapi.py deleted file mode 100644 index 8f7c045ea7531fc6ea91405252aaaf20c5eb6e9a..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/adodbapi/adodbapi.py +++ /dev/null @@ -1,1223 +0,0 @@ -"""adodbapi - A python DB API 2.0 (PEP 249) interface to Microsoft ADO - -Copyright (C) 2002 Henrik Ekelund, versions 2.1 and later by Vernon Cole -* http://sourceforge.net/projects/pywin32 -* https://github.com/mhammond/pywin32 -* http://sourceforge.net/projects/adodbapi - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - django adaptations and refactoring by Adam Vandenberg - -DB-API 2.0 specification: http://www.python.org/dev/peps/pep-0249/ - -This module source should run correctly in CPython versions 2.7 and later, -or IronPython version 2.7 and later, -or, after running through 2to3.py, CPython 3.4 or later. -""" - -__version__ = "2.6.2.0" -version = "adodbapi v" + __version__ - -import copy -import decimal -import os -import sys -import weakref - -from . import ado_consts as adc, apibase as api, process_connect_string - -try: - verbose = int(os.environ["ADODBAPI_VERBOSE"]) -except: - verbose = False -if verbose: - print(version) - -# --- define objects to smooth out IronPython <-> CPython differences -onWin32 = False # assume the worst -if api.onIronPython: - from clr import Reference - from System import ( - Activator, - Array, - Byte, - DateTime, - DBNull, - Decimal as SystemDecimal, - Type, - ) - - def Dispatch(dispatch): - type = Type.GetTypeFromProgID(dispatch) - return Activator.CreateInstance(type) - - def getIndexedValue(obj, index): - return obj.Item[index] - -else: # try pywin32 - try: - import pythoncom - import pywintypes - import win32com.client - - onWin32 = True - - def Dispatch(dispatch): - return win32com.client.Dispatch(dispatch) - - except ImportError: - import warnings - - warnings.warn( - "pywin32 package (or IronPython) required for adodbapi.", ImportWarning - ) - - def getIndexedValue(obj, index): - return obj(index) - - -from collections.abc import Mapping - -# --- define objects to smooth out Python3000 <-> Python 2.x differences -unicodeType = str -longType = int -StringTypes = str -maxint = sys.maxsize - - -# ----------------- The .connect method ----------------- -def make_COM_connecter(): - try: - if onWin32: - pythoncom.CoInitialize() # v2.1 Paj - c = Dispatch("ADODB.Connection") # connect _after_ CoIninialize v2.1.1 adamvan - except: - raise api.InterfaceError( - "Windows COM Error: Dispatch('ADODB.Connection') failed." - ) - return c - - -def connect(*args, **kwargs): # --> a db-api connection object - """Connect to a database. - - call using: - :connection_string -- An ADODB formatted connection string, see: - * http://www.connectionstrings.com - * http://www.asp101.com/articles/john/connstring/default.asp - :timeout -- A command timeout value, in seconds (default 30 seconds) - """ - co = Connection() # make an empty connection object - - kwargs = process_connect_string.process(args, kwargs, True) - - try: # connect to the database, using the connection information in kwargs - co.connect(kwargs) - return co - except Exception as e: - message = 'Error opening connection to "%s"' % co.connection_string - raise api.OperationalError(e, message) - - -# so you could use something like: -# myConnection.paramstyle = 'named' -# The programmer may also change the default. -# For example, if I were using django, I would say: -# import adodbapi as Database -# Database.adodbapi.paramstyle = 'format' - -# ------- other module level defaults -------- -defaultIsolationLevel = adc.adXactReadCommitted -# Set defaultIsolationLevel on module level before creating the connection. -# For example: -# import adodbapi, ado_consts -# adodbapi.adodbapi.defaultIsolationLevel=ado_consts.adXactBrowse" -# -# Set defaultCursorLocation on module level before creating the connection. -# It may be one of the "adUse..." consts. -defaultCursorLocation = adc.adUseClient # changed from adUseServer as of v 2.3.0 - -dateconverter = api.pythonDateTimeConverter() # default - - -def format_parameters(ADOparameters, show_value=False): - """Format a collection of ADO Command Parameters. - - Used by error reporting in _execute_command. - """ - try: - if show_value: - desc = [ - 'Name: %s, Dir.: %s, Type: %s, Size: %s, Value: "%s", Precision: %s, NumericScale: %s' - % ( - p.Name, - adc.directions[p.Direction], - adc.adTypeNames.get(p.Type, str(p.Type) + " (unknown type)"), - p.Size, - p.Value, - p.Precision, - p.NumericScale, - ) - for p in ADOparameters - ] - else: - desc = [ - "Name: %s, Dir.: %s, Type: %s, Size: %s, Precision: %s, NumericScale: %s" - % ( - p.Name, - adc.directions[p.Direction], - adc.adTypeNames.get(p.Type, str(p.Type) + " (unknown type)"), - p.Size, - p.Precision, - p.NumericScale, - ) - for p in ADOparameters - ] - return "[" + "\n".join(desc) + "]" - except: - return "[]" - - -def _configure_parameter(p, value, adotype, settings_known): - """Configure the given ADO Parameter 'p' with the Python 'value'.""" - - if adotype in api.adoBinaryTypes: - p.Size = len(value) - p.AppendChunk(value) - - elif isinstance(value, StringTypes): # v2.1 Jevon - L = len(value) - if adotype in api.adoStringTypes: # v2.2.1 Cole - if settings_known: - L = min(L, p.Size) # v2.1 Cole limit data to defined size - p.Value = value[:L] # v2.1 Jevon & v2.1 Cole - else: - p.Value = value # dont limit if db column is numeric - if L > 0: # v2.1 Cole something does not like p.Size as Zero - p.Size = L # v2.1 Jevon - - elif isinstance(value, decimal.Decimal): - if api.onIronPython: - s = str(value) - p.Value = s - p.Size = len(s) - else: - p.Value = value - exponent = value.as_tuple()[2] - digit_count = len(value.as_tuple()[1]) - p.Precision = digit_count - if exponent == 0: - p.NumericScale = 0 - elif exponent < 0: - p.NumericScale = -exponent - if p.Precision < p.NumericScale: - p.Precision = p.NumericScale - else: # exponent > 0: - p.NumericScale = 0 - p.Precision = digit_count + exponent - - elif type(value) in dateconverter.types: - if settings_known and adotype in api.adoDateTimeTypes: - p.Value = dateconverter.COMDate(value) - else: # probably a string - # provide the date as a string in the format 'YYYY-MM-dd' - s = dateconverter.DateObjectToIsoFormatString(value) - p.Value = s - p.Size = len(s) - - elif api.onIronPython and isinstance(value, longType): # Iron Python Long - s = str(value) # feature workaround for IPy 2.0 - p.Value = s - - elif adotype == adc.adEmpty: # ADO will not let you specify a null column - p.Type = ( - adc.adInteger - ) # so we will fake it to be an integer (just to have something) - p.Value = None # and pass in a Null *value* - - # For any other type, set the value and let pythoncom do the right thing. - else: - p.Value = value - - -# # # # # ----- the Class that defines a connection ----- # # # # # -class Connection(object): - # include connection attributes as class attributes required by api definition. - Warning = api.Warning - Error = api.Error - InterfaceError = api.InterfaceError - DataError = api.DataError - DatabaseError = api.DatabaseError - OperationalError = api.OperationalError - IntegrityError = api.IntegrityError - InternalError = api.InternalError - NotSupportedError = api.NotSupportedError - ProgrammingError = api.ProgrammingError - FetchFailedError = api.FetchFailedError # (special for django) - # ...class attributes... (can be overridden by instance attributes) - verbose = api.verbose - - @property - def dbapi(self): # a proposed db-api version 3 extension. - "Return a reference to the DBAPI module for this Connection." - return api - - def __init__(self): # now define the instance attributes - self.connector = None - self.paramstyle = api.paramstyle - self.supportsTransactions = False - self.connection_string = "" - self.cursors = weakref.WeakValueDictionary() - self.dbms_name = "" - self.dbms_version = "" - self.errorhandler = None # use the standard error handler for this instance - self.transaction_level = 0 # 0 == Not in a transaction, at the top level - self._autocommit = False - - def connect(self, kwargs, connection_maker=make_COM_connecter): - if verbose > 9: - print("kwargs=", repr(kwargs)) - try: - self.connection_string = ( - kwargs["connection_string"] % kwargs - ) # insert keyword arguments - except Exception as e: - self._raiseConnectionError( - KeyError, "Python string format error in connection string->" - ) - self.timeout = kwargs.get("timeout", 30) - self.mode = kwargs.get("mode", adc.adModeUnknown) - self.kwargs = kwargs - if verbose: - print('%s attempting: "%s"' % (version, self.connection_string)) - self.connector = connection_maker() - self.connector.ConnectionTimeout = self.timeout - self.connector.ConnectionString = self.connection_string - self.connector.Mode = self.mode - - try: - self.connector.Open() # Open the ADO connection - except api.Error: - self._raiseConnectionError( - api.DatabaseError, - "ADO error trying to Open=%s" % self.connection_string, - ) - - try: # Stefan Fuchs; support WINCCOLEDBProvider - if getIndexedValue(self.connector.Properties, "Transaction DDL").Value != 0: - self.supportsTransactions = True - except pywintypes.com_error: - pass # Stefan Fuchs - self.dbms_name = getIndexedValue(self.connector.Properties, "DBMS Name").Value - try: # Stefan Fuchs - self.dbms_version = getIndexedValue( - self.connector.Properties, "DBMS Version" - ).Value - except pywintypes.com_error: - pass # Stefan Fuchs - self.connector.CursorLocation = defaultCursorLocation # v2.1 Rose - if self.supportsTransactions: - self.connector.IsolationLevel = defaultIsolationLevel - self._autocommit = bool(kwargs.get("autocommit", False)) - if not self._autocommit: - self.transaction_level = ( - self.connector.BeginTrans() - ) # Disables autocommit & inits transaction_level - else: - self._autocommit = True - if "paramstyle" in kwargs: - self.paramstyle = kwargs["paramstyle"] # let setattr do the error checking - self.messages = [] - if verbose: - print("adodbapi New connection at %X" % id(self)) - - def _raiseConnectionError(self, errorclass, errorvalue): - eh = self.errorhandler - if eh is None: - eh = api.standardErrorHandler - eh(self, None, errorclass, errorvalue) - - def _closeAdoConnection(self): # all v2.1 Rose - """close the underlying ADO Connection object, - rolling it back first if it supports transactions.""" - if self.connector is None: - return - if not self._autocommit: - if self.transaction_level: - try: - self.connector.RollbackTrans() - except: - pass - self.connector.Close() - if verbose: - print("adodbapi Closed connection at %X" % id(self)) - - def close(self): - """Close the connection now (rather than whenever __del__ is called). - - The connection will be unusable from this point forward; - an Error (or subclass) exception will be raised if any operation is attempted with the connection. - The same applies to all cursor objects trying to use the connection. - """ - for crsr in list(self.cursors.values())[ - : - ]: # copy the list, then close each one - crsr.close(dont_tell_me=True) # close without back-link clearing - self.messages = [] - try: - self._closeAdoConnection() # v2.1 Rose - except Exception as e: - self._raiseConnectionError(sys.exc_info()[0], sys.exc_info()[1]) - - self.connector = None # v2.4.2.2 fix subtle timeout bug - # per M.Hammond: "I expect the benefits of uninitializing are probably fairly small, - # so never uninitializing will probably not cause any problems." - - def commit(self): - """Commit any pending transaction to the database. - - Note that if the database supports an auto-commit feature, - this must be initially off. An interface method may be provided to turn it back on. - Database modules that do not support transactions should implement this method with void functionality. - """ - self.messages = [] - if not self.supportsTransactions: - return - - try: - self.transaction_level = self.connector.CommitTrans() - if verbose > 1: - print("commit done on connection at %X" % id(self)) - if not ( - self._autocommit - or (self.connector.Attributes & adc.adXactAbortRetaining) - ): - # If attributes has adXactCommitRetaining it performs retaining commits that is, - # calling CommitTrans automatically starts a new transaction. Not all providers support this. - # If not, we will have to start a new transaction by this command: - self.transaction_level = self.connector.BeginTrans() - except Exception as e: - self._raiseConnectionError(api.ProgrammingError, e) - - def _rollback(self): - """In case a database does provide transactions this method causes the the database to roll back to - the start of any pending transaction. Closing a connection without committing the changes first will - cause an implicit rollback to be performed. - - If the database does not support the functionality required by the method, the interface should - throw an exception in case the method is used. - The preferred approach is to not implement the method and thus have Python generate - an AttributeError in case the method is requested. This allows the programmer to check for database - capabilities using the standard hasattr() function. - - For some dynamically configured interfaces it may not be appropriate to require dynamically making - the method available. These interfaces should then raise a NotSupportedError to indicate the - non-ability to perform the roll back when the method is invoked. - """ - self.messages = [] - if ( - self.transaction_level - ): # trying to roll back with no open transaction causes an error - try: - self.transaction_level = self.connector.RollbackTrans() - if verbose > 1: - print("rollback done on connection at %X" % id(self)) - if not self._autocommit and not ( - self.connector.Attributes & adc.adXactAbortRetaining - ): - # If attributes has adXactAbortRetaining it performs retaining aborts that is, - # calling RollbackTrans automatically starts a new transaction. Not all providers support this. - # If not, we will have to start a new transaction by this command: - if ( - not self.transaction_level - ): # if self.transaction_level == 0 or self.transaction_level is None: - self.transaction_level = self.connector.BeginTrans() - except Exception as e: - self._raiseConnectionError(api.ProgrammingError, e) - - def __setattr__(self, name, value): - if name == "autocommit": # extension: allow user to turn autocommit on or off - if self.supportsTransactions: - object.__setattr__(self, "_autocommit", bool(value)) - try: - self._rollback() # must clear any outstanding transactions - except: - pass - return - elif name == "paramstyle": - if value not in api.accepted_paramstyles: - self._raiseConnectionError( - api.NotSupportedError, - 'paramstyle="%s" not in:%s' - % (value, repr(api.accepted_paramstyles)), - ) - elif name == "variantConversions": - value = copy.copy( - value - ) # make a new copy -- no changes in the default, please - object.__setattr__(self, name, value) - - def __getattr__(self, item): - if ( - item == "rollback" - ): # the rollback method only appears if the database supports transactions - if self.supportsTransactions: - return ( - self._rollback - ) # return the rollback method so the caller can execute it. - else: - raise AttributeError("this data provider does not support Rollback") - elif item == "autocommit": - return self._autocommit - else: - raise AttributeError( - 'no such attribute in ADO connection object as="%s"' % item - ) - - def cursor(self): - "Return a new Cursor Object using the connection." - self.messages = [] - c = Cursor(self) - return c - - def _i_am_here(self, crsr): - "message from a new cursor proclaiming its existence" - oid = id(crsr) - self.cursors[oid] = crsr - - def _i_am_closing(self, crsr): - "message from a cursor giving connection a chance to clean up" - try: - del self.cursors[id(crsr)] - except: - pass - - def printADOerrors(self): - j = self.connector.Errors.Count - if j: - print("ADO Errors:(%i)" % j) - for e in self.connector.Errors: - print("Description: %s" % e.Description) - print("Error: %s %s " % (e.Number, adc.adoErrors.get(e.Number, "unknown"))) - if e.Number == adc.ado_error_TIMEOUT: - print( - "Timeout Error: Try using adodbpi.connect(constr,timeout=Nseconds)" - ) - print("Source: %s" % e.Source) - print("NativeError: %s" % e.NativeError) - print("SQL State: %s" % e.SQLState) - - def _suggest_error_class(self): - """Introspect the current ADO Errors and determine an appropriate error class. - - Error.SQLState is a SQL-defined error condition, per the SQL specification: - http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt - - The 23000 class of errors are integrity errors. - Error 40002 is a transactional integrity error. - """ - if self.connector is not None: - for e in self.connector.Errors: - state = str(e.SQLState) - if state.startswith("23") or state == "40002": - return api.IntegrityError - return api.DatabaseError - - def __del__(self): - try: - self._closeAdoConnection() # v2.1 Rose - except: - pass - self.connector = None - - def __enter__(self): # Connections are context managers - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - if exc_type: - self._rollback() # automatic rollback on errors - else: - self.commit() - - def get_table_names(self): - schema = self.connector.OpenSchema(20) # constant = adSchemaTables - - tables = [] - while not schema.EOF: - name = getIndexedValue(schema.Fields, "TABLE_NAME").Value - tables.append(name) - schema.MoveNext() - del schema - return tables - - -# # # # # ----- the Class that defines a cursor ----- # # # # # -class Cursor(object): - ## ** api required attributes: - ## description... - ## This read-only attribute is a sequence of 7-item sequences. - ## Each of these sequences contains information describing one result column: - ## (name, type_code, display_size, internal_size, precision, scale, null_ok). - ## This attribute will be None for operations that do not return rows or if the - ## cursor has not had an operation invoked via the executeXXX() method yet. - ## The type_code can be interpreted by comparing it to the Type Objects specified in the section below. - ## rowcount... - ## This read-only attribute specifies the number of rows that the last executeXXX() produced - ## (for DQL statements like select) or affected (for DML statements like update or insert). - ## The attribute is -1 in case no executeXXX() has been performed on the cursor or - ## the rowcount of the last operation is not determinable by the interface.[7] - ## arraysize... - ## This read/write attribute specifies the number of rows to fetch at a time with fetchmany(). - ## It defaults to 1 meaning to fetch a single row at a time. - ## Implementations must observe this value with respect to the fetchmany() method, - ## but are free to interact with the database a single row at a time. - ## It may also be used in the implementation of executemany(). - ## ** extension attributes: - ## paramstyle... - ## allows the programmer to override the connection's default paramstyle - ## errorhandler... - ## allows the programmer to override the connection's default error handler - - def __init__(self, connection): - self.command = None - self._ado_prepared = False - self.messages = [] - self.connection = connection - self.paramstyle = connection.paramstyle # used for overriding the paramstyle - self._parameter_names = [] - self.recordset_is_remote = False - self.rs = None # the ADO recordset for this cursor - self.converters = [] # conversion function for each column - self.columnNames = {} # names of columns {lowercase name : number,...} - self.numberOfColumns = 0 - self._description = None - self.rowcount = -1 - self.errorhandler = connection.errorhandler - self.arraysize = 1 - connection._i_am_here(self) - if verbose: - print( - "%s New cursor at %X on conn %X" - % (version, id(self), id(self.connection)) - ) - - def __iter__(self): # [2.1 Zamarev] - return iter(self.fetchone, None) # [2.1 Zamarev] - - def prepare(self, operation): - self.command = operation - self._description = None - self._ado_prepared = "setup" - - def __next__(self): - r = self.fetchone() - if r: - return r - raise StopIteration - - def __enter__(self): - "Allow database cursors to be used with context managers." - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - "Allow database cursors to be used with context managers." - self.close() - - def _raiseCursorError(self, errorclass, errorvalue): - eh = self.errorhandler - if eh is None: - eh = api.standardErrorHandler - eh(self.connection, self, errorclass, errorvalue) - - def build_column_info(self, recordset): - self.converters = [] # convertion function for each column - self.columnNames = {} # names of columns {lowercase name : number,...} - self._description = None - - # if EOF and BOF are true at the same time, there are no records in the recordset - if (recordset is None) or (recordset.State == adc.adStateClosed): - self.rs = None - self.numberOfColumns = 0 - return - self.rs = recordset # v2.1.1 bkline - self.recordset_format = api.RS_ARRAY if api.onIronPython else api.RS_WIN_32 - self.numberOfColumns = recordset.Fields.Count - try: - varCon = self.connection.variantConversions - except AttributeError: - varCon = api.variantConversions - for i in range(self.numberOfColumns): - f = getIndexedValue(self.rs.Fields, i) - try: - self.converters.append( - varCon[f.Type] - ) # conversion function for this column - except KeyError: - self._raiseCursorError( - api.InternalError, "Data column of Unknown ADO type=%s" % f.Type - ) - self.columnNames[f.Name.lower()] = i # columnNames lookup - - def _makeDescriptionFromRS(self): - # Abort if closed or no recordset. - if self.rs is None: - self._description = None - return - desc = [] - for i in range(self.numberOfColumns): - f = getIndexedValue(self.rs.Fields, i) - if self.rs.EOF or self.rs.BOF: - display_size = None - else: - display_size = ( - f.ActualSize - ) # TODO: Is this the correct defintion according to the DB API 2 Spec ? - null_ok = bool(f.Attributes & adc.adFldMayBeNull) # v2.1 Cole - desc.append( - ( - f.Name, - f.Type, - display_size, - f.DefinedSize, - f.Precision, - f.NumericScale, - null_ok, - ) - ) - self._description = desc - - def get_description(self): - if not self._description: - self._makeDescriptionFromRS() - return self._description - - def __getattr__(self, item): - if item == "description": - return self.get_description() - object.__getattribute__( - self, item - ) # may get here on Remote attribute calls for existing attributes - - def format_description(self, d): - """Format db_api description tuple for printing.""" - if self.description is None: - self._makeDescriptionFromRS() - if isinstance(d, int): - d = self.description[d] - desc = ( - "Name= %s, Type= %s, DispSize= %s, IntSize= %s, Precision= %s, Scale= %s NullOK=%s" - % ( - d[0], - adc.adTypeNames.get(d[1], str(d[1]) + " (unknown type)"), - d[2], - d[3], - d[4], - d[5], - d[6], - ) - ) - return desc - - def close(self, dont_tell_me=False): - """Close the cursor now (rather than whenever __del__ is called). - The cursor will be unusable from this point forward; an Error (or subclass) - exception will be raised if any operation is attempted with the cursor. - """ - if self.connection is None: - return - self.messages = [] - if ( - self.rs and self.rs.State != adc.adStateClosed - ): # rs exists and is open #v2.1 Rose - self.rs.Close() # v2.1 Rose - self.rs = None # let go of the recordset so ADO will let it be disposed #v2.1 Rose - if not dont_tell_me: - self.connection._i_am_closing( - self - ) # take me off the connection's cursors list - self.connection = ( - None # this will make all future method calls on me throw an exception - ) - if verbose: - print("adodbapi Closed cursor at %X" % id(self)) - - def __del__(self): - try: - self.close() - except: - pass - - def _new_command(self, command_type=adc.adCmdText): - self.cmd = None - self.messages = [] - - if self.connection is None: - self._raiseCursorError(api.InterfaceError, None) - return - try: - self.cmd = Dispatch("ADODB.Command") - self.cmd.ActiveConnection = self.connection.connector - self.cmd.CommandTimeout = self.connection.timeout - self.cmd.CommandType = command_type - self.cmd.CommandText = self.commandText - self.cmd.Prepared = bool(self._ado_prepared) - except: - self._raiseCursorError( - api.DatabaseError, - 'Error creating new ADODB.Command object for "%s"' - % repr(self.commandText), - ) - - def _execute_command(self): - # Stored procedures may have an integer return value - self.return_value = None - recordset = None - count = -1 # default value - if verbose: - print('Executing command="%s"' % self.commandText) - try: - # ----- the actual SQL is executed here --- - if api.onIronPython: - ra = Reference[int]() - recordset = self.cmd.Execute(ra) - count = ra.Value - else: # pywin32 - recordset, count = self.cmd.Execute() - # ----- ------------------------------- --- - except Exception as e: - _message = "" - if hasattr(e, "args"): - _message += str(e.args) + "\n" - _message += "Command:\n%s\nParameters:\n%s" % ( - self.commandText, - format_parameters(self.cmd.Parameters, True), - ) - klass = self.connection._suggest_error_class() - self._raiseCursorError(klass, _message) - try: - self.rowcount = recordset.RecordCount - except: - self.rowcount = count - self.build_column_info(recordset) - - # The ADO documentation hints that obtaining the recordcount may be timeconsuming - # "If the Recordset object does not support approximate positioning, this property - # may be a significant drain on resources # [ekelund] - # Therefore, COM will not return rowcount for server-side cursors. [Cole] - # Client-side cursors (the default since v2.8) will force a static - # cursor, and rowcount will then be set accurately [Cole] - - def get_rowcount(self): - return self.rowcount - - def get_returned_parameters(self): - """with some providers, returned parameters and the .return_value are not available until - after the last recordset has been read. In that case, you must coll nextset() until it - returns None, then call this method to get your returned information.""" - - retLst = ( - [] - ) # store procedures may return altered parameters, including an added "return value" item - for p in tuple(self.cmd.Parameters): - if verbose > 2: - print( - 'Returned=Name: %s, Dir.: %s, Type: %s, Size: %s, Value: "%s",' - " Precision: %s, NumericScale: %s" - % ( - p.Name, - adc.directions[p.Direction], - adc.adTypeNames.get(p.Type, str(p.Type) + " (unknown type)"), - p.Size, - p.Value, - p.Precision, - p.NumericScale, - ) - ) - pyObject = api.convert_to_python(p.Value, api.variantConversions[p.Type]) - if p.Direction == adc.adParamReturnValue: - self.returnValue = ( - pyObject # also load the undocumented attribute (Vernon's Error!) - ) - self.return_value = pyObject - else: - retLst.append(pyObject) - return retLst # return the parameter list to the caller - - def callproc(self, procname, parameters=None): - """Call a stored database procedure with the given name. - The sequence of parameters must contain one entry for each - argument that the sproc expects. The result of the - call is returned as modified copy of the input - sequence. Input parameters are left untouched, output and - input/output parameters replaced with possibly new values. - - The sproc may also provide a result set as output, - which is available through the standard .fetch*() methods. - Extension: A "return_value" property may be set on the - cursor if the sproc defines an integer return value. - """ - self._parameter_names = [] - self.commandText = procname - self._new_command(command_type=adc.adCmdStoredProc) - self._buildADOparameterList(parameters, sproc=True) - if verbose > 2: - print( - "Calling Stored Proc with Params=", - format_parameters(self.cmd.Parameters, True), - ) - self._execute_command() - return self.get_returned_parameters() - - def _reformat_operation(self, operation, parameters): - if self.paramstyle in ("format", "pyformat"): # convert %s to ? - operation, self._parameter_names = api.changeFormatToQmark(operation) - elif self.paramstyle == "named" or ( - self.paramstyle == "dynamic" and isinstance(parameters, Mapping) - ): - operation, self._parameter_names = api.changeNamedToQmark( - operation - ) # convert :name to ? - return operation - - def _buildADOparameterList(self, parameters, sproc=False): - self.parameters = parameters - if parameters is None: - parameters = [] - - # Note: ADO does not preserve the parameter list, even if "Prepared" is True, so we must build every time. - parameters_known = False - if sproc: # needed only if we are calling a stored procedure - try: # attempt to use ADO's parameter list - self.cmd.Parameters.Refresh() - if verbose > 2: - print( - "ADO detected Params=", - format_parameters(self.cmd.Parameters, True), - ) - print("Program Parameters=", repr(parameters)) - parameters_known = True - except api.Error: - if verbose: - print("ADO Parameter Refresh failed") - pass - else: - if len(parameters) != self.cmd.Parameters.Count - 1: - raise api.ProgrammingError( - "You must supply %d parameters for this stored procedure" - % (self.cmd.Parameters.Count - 1) - ) - if sproc or parameters != []: - i = 0 - if parameters_known: # use ado parameter list - if self._parameter_names: # named parameters - for i, pm_name in enumerate(self._parameter_names): - p = getIndexedValue(self.cmd.Parameters, i) - try: - _configure_parameter( - p, parameters[pm_name], p.Type, parameters_known - ) - except Exception as e: - _message = ( - "Error Converting Parameter %s: %s, %s <- %s\n" - % ( - p.Name, - adc.ado_type_name(p.Type), - p.Value, - repr(parameters[pm_name]), - ) - ) - self._raiseCursorError( - api.DataError, _message + "->" + repr(e.args) - ) - else: # regular sequence of parameters - for value in parameters: - p = getIndexedValue(self.cmd.Parameters, i) - if ( - p.Direction == adc.adParamReturnValue - ): # this is an extra parameter added by ADO - i += 1 # skip the extra - p = getIndexedValue(self.cmd.Parameters, i) - try: - _configure_parameter(p, value, p.Type, parameters_known) - except Exception as e: - _message = ( - "Error Converting Parameter %s: %s, %s <- %s\n" - % ( - p.Name, - adc.ado_type_name(p.Type), - p.Value, - repr(value), - ) - ) - self._raiseCursorError( - api.DataError, _message + "->" + repr(e.args) - ) - i += 1 - else: # -- build own parameter list - if ( - self._parameter_names - ): # we expect a dictionary of parameters, this is the list of expected names - for parm_name in self._parameter_names: - elem = parameters[parm_name] - adotype = api.pyTypeToADOType(elem) - p = self.cmd.CreateParameter( - parm_name, adotype, adc.adParamInput - ) - _configure_parameter(p, elem, adotype, parameters_known) - try: - self.cmd.Parameters.Append(p) - except Exception as e: - _message = "Error Building Parameter %s: %s, %s <- %s\n" % ( - p.Name, - adc.ado_type_name(p.Type), - p.Value, - repr(elem), - ) - self._raiseCursorError( - api.DataError, _message + "->" + repr(e.args) - ) - else: # expecting the usual sequence of parameters - if sproc: - p = self.cmd.CreateParameter( - "@RETURN_VALUE", adc.adInteger, adc.adParamReturnValue - ) - self.cmd.Parameters.Append(p) - - for elem in parameters: - name = "p%i" % i - adotype = api.pyTypeToADOType(elem) - p = self.cmd.CreateParameter( - name, adotype, adc.adParamInput - ) # Name, Type, Direction, Size, Value - _configure_parameter(p, elem, adotype, parameters_known) - try: - self.cmd.Parameters.Append(p) - except Exception as e: - _message = "Error Building Parameter %s: %s, %s <- %s\n" % ( - p.Name, - adc.ado_type_name(p.Type), - p.Value, - repr(elem), - ) - self._raiseCursorError( - api.DataError, _message + "->" + repr(e.args) - ) - i += 1 - if self._ado_prepared == "setup": - self._ado_prepared = ( - True # parameters will be "known" by ADO next loop - ) - - def execute(self, operation, parameters=None): - """Prepare and execute a database operation (query or command). - - Parameters may be provided as sequence or mapping and will be bound to variables in the operation. - Variables are specified in a database-specific notation - (see the module's paramstyle attribute for details). [5] - A reference to the operation will be retained by the cursor. - If the same operation object is passed in again, then the cursor - can optimize its behavior. This is most effective for algorithms - where the same operation is used, but different parameters are bound to it (many times). - - For maximum efficiency when reusing an operation, it is best to use - the setinputsizes() method to specify the parameter types and sizes ahead of time. - It is legal for a parameter to not match the predefined information; - the implementation should compensate, possibly with a loss of efficiency. - - The parameters may also be specified as list of tuples to e.g. insert multiple rows in - a single operation, but this kind of usage is depreciated: executemany() should be used instead. - - Return value is not defined. - - [5] The module will use the __getitem__ method of the parameters object to map either positions - (integers) or names (strings) to parameter values. This allows for both sequences and mappings - to be used as input. - The term "bound" refers to the process of binding an input value to a database execution buffer. - In practical terms, this means that the input value is directly used as a value in the operation. - The client should not be required to "escape" the value so that it can be used -- the value - should be equal to the actual database value.""" - if ( - self.command is not operation - or self._ado_prepared == "setup" - or not hasattr(self, "commandText") - ): - if self.command is not operation: - self._ado_prepared = False - self.command = operation - self._parameter_names = [] - self.commandText = ( - operation - if (self.paramstyle == "qmark" or not parameters) - else self._reformat_operation(operation, parameters) - ) - self._new_command() - self._buildADOparameterList(parameters) - if verbose > 3: - print("Params=", format_parameters(self.cmd.Parameters, True)) - self._execute_command() - - def executemany(self, operation, seq_of_parameters): - """Prepare a database operation (query or command) - and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters. - - Return values are not defined. - """ - self.messages = list() - total_recordcount = 0 - - self.prepare(operation) - for params in seq_of_parameters: - self.execute(self.command, params) - if self.rowcount == -1: - total_recordcount = -1 - if total_recordcount != -1: - total_recordcount += self.rowcount - self.rowcount = total_recordcount - - def _fetch(self, limit=None): - """Fetch rows from the current recordset. - - limit -- Number of rows to fetch, or None (default) to fetch all rows. - """ - if self.connection is None or self.rs is None: - self._raiseCursorError( - api.FetchFailedError, "fetch() on closed connection or empty query set" - ) - return - - if self.rs.State == adc.adStateClosed or self.rs.BOF or self.rs.EOF: - return list() - if limit: # limit number of rows retrieved - ado_results = self.rs.GetRows(limit) - else: # get all rows - ado_results = self.rs.GetRows() - if ( - self.recordset_format == api.RS_ARRAY - ): # result of GetRows is a two-dimension array - length = ( - len(ado_results) // self.numberOfColumns - ) # length of first dimension - else: # pywin32 - length = len(ado_results[0]) # result of GetRows is tuples in a tuple - fetchObject = api.SQLrows( - ado_results, length, self - ) # new object to hold the results of the fetch - return fetchObject - - def fetchone(self): - """Fetch the next row of a query result set, returning a single sequence, - or None when no more data is available. - - An Error (or subclass) exception is raised if the previous call to executeXXX() - did not produce any result set or no call was issued yet. - """ - self.messages = [] - result = self._fetch(1) - if result: # return record (not list of records) - return result[0] - return None - - def fetchmany(self, size=None): - """Fetch the next set of rows of a query result, returning a list of tuples. An empty sequence is returned when no more rows are available. - - The number of rows to fetch per call is specified by the parameter. - If it is not given, the cursor's arraysize determines the number of rows to be fetched. - The method should try to fetch as many rows as indicated by the size parameter. - If this is not possible due to the specified number of rows not being available, - fewer rows may be returned. - - An Error (or subclass) exception is raised if the previous call to executeXXX() - did not produce any result set or no call was issued yet. - - Note there are performance considerations involved with the size parameter. - For optimal performance, it is usually best to use the arraysize attribute. - If the size parameter is used, then it is best for it to retain the same value from - one fetchmany() call to the next. - """ - self.messages = [] - if size is None: - size = self.arraysize - return self._fetch(size) - - def fetchall(self): - """Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples). - - Note that the cursor's arraysize attribute - can affect the performance of this operation. - An Error (or subclass) exception is raised if the previous call to executeXXX() - did not produce any result set or no call was issued yet. - """ - self.messages = [] - return self._fetch() - - def nextset(self): - """Skip to the next available recordset, discarding any remaining rows from the current recordset. - - If there are no more sets, the method returns None. Otherwise, it returns a true - value and subsequent calls to the fetch methods will return rows from the next result set. - - An Error (or subclass) exception is raised if the previous call to executeXXX() - did not produce any result set or no call was issued yet. - """ - self.messages = [] - if self.connection is None or self.rs is None: - self._raiseCursorError( - api.OperationalError, - ("nextset() on closed connection or empty query set"), - ) - return None - - if api.onIronPython: - try: - recordset = self.rs.NextRecordset() - except TypeError: - recordset = None - except api.Error as exc: - self._raiseCursorError(api.NotSupportedError, exc.args) - else: # pywin32 - try: # [begin 2.1 ekelund] - rsTuple = self.rs.NextRecordset() # - except pywintypes.com_error as exc: # return appropriate error - self._raiseCursorError( - api.NotSupportedError, exc.args - ) # [end 2.1 ekelund] - recordset = rsTuple[0] - if recordset is None: - return None - self.build_column_info(recordset) - return True - - def setinputsizes(self, sizes): - pass - - def setoutputsize(self, size, column=None): - pass - - def _last_query(self): # let the programmer see what query we actually used - try: - if self.parameters == None: - ret = self.commandText - else: - ret = "%s,parameters=%s" % (self.commandText, repr(self.parameters)) - except: - ret = None - return ret - - query = property(_last_query, None, None, "returns the last query executed") - - -if __name__ == "__main__": - raise api.ProgrammingError(version + " cannot be run as a main program.") diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/debugpy/_vendored/pydevd/pydevd_tracing.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/debugpy/_vendored/pydevd/pydevd_tracing.py deleted file mode 100644 index d658b12483d89883d2d4954de5437d6e8c7703e5..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/debugpy/_vendored/pydevd/pydevd_tracing.py +++ /dev/null @@ -1,385 +0,0 @@ -from _pydevd_bundle.pydevd_constants import get_frame, IS_CPYTHON, IS_64BIT_PROCESS, IS_WINDOWS, \ - IS_LINUX, IS_MAC, DebugInfoHolder, LOAD_NATIVE_LIB_FLAG, \ - ENV_FALSE_LOWER_VALUES, ForkSafeLock -from _pydev_bundle._pydev_saved_modules import thread, threading -from _pydev_bundle import pydev_log, pydev_monkey -import os.path -import platform -import ctypes -from io import StringIO -import sys -import traceback - -_original_settrace = sys.settrace - - -class TracingFunctionHolder: - '''This class exists just to keep some variables (so that we don't keep them in the global namespace). - ''' - _original_tracing = None - _warn = True - _traceback_limit = 1 - _warnings_shown = {} - - -def get_exception_traceback_str(): - exc_info = sys.exc_info() - s = StringIO() - traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], file=s) - return s.getvalue() - - -def _get_stack_str(frame): - - msg = '\nIf this is needed, please check: ' + \ - '\nhttp://pydev.blogspot.com/2007/06/why-cant-pydev-debugger-work-with.html' + \ - '\nto see how to restore the debug tracing back correctly.\n' - - if TracingFunctionHolder._traceback_limit: - s = StringIO() - s.write('Call Location:\n') - traceback.print_stack(f=frame, limit=TracingFunctionHolder._traceback_limit, file=s) - msg = msg + s.getvalue() - - return msg - - -def _internal_set_trace(tracing_func): - if TracingFunctionHolder._warn: - frame = get_frame() - if frame is not None and frame.f_back is not None: - filename = os.path.splitext(frame.f_back.f_code.co_filename.lower())[0] - if filename.endswith('threadpool') and 'gevent' in filename: - if tracing_func is None: - pydev_log.debug('Disabled internal sys.settrace from gevent threadpool.') - return - - elif not filename.endswith( - ( - 'threading', - 'pydevd_tracing', - ) - ): - - message = \ - '\nPYDEV DEBUGGER WARNING:' + \ - '\nsys.settrace() should not be used when the debugger is being used.' + \ - '\nThis may cause the debugger to stop working correctly.' + \ - '%s' % _get_stack_str(frame.f_back) - - if message not in TracingFunctionHolder._warnings_shown: - # only warn about each message once... - TracingFunctionHolder._warnings_shown[message] = 1 - sys.stderr.write('%s\n' % (message,)) - sys.stderr.flush() - - if TracingFunctionHolder._original_tracing: - TracingFunctionHolder._original_tracing(tracing_func) - - -_last_tracing_func_thread_local = threading.local() - - -def SetTrace(tracing_func): - _last_tracing_func_thread_local.tracing_func = tracing_func - - if tracing_func is not None: - if set_trace_to_threads(tracing_func, thread_idents=[thread.get_ident()], create_dummy_thread=False) == 0: - # If we can use our own tracer instead of the one from sys.settrace, do it (the reason - # is that this is faster than the Python version because we don't call - # PyFrame_FastToLocalsWithError and PyFrame_LocalsToFast at each event! - # (the difference can be huge when checking line events on frames as the - # time increases based on the number of local variables in the scope) - # See: InternalCallTrampoline (on the C side) for details. - return - - # If it didn't work (or if it was None), use the Python version. - set_trace = TracingFunctionHolder._original_tracing or sys.settrace - set_trace(tracing_func) - - -def reapply_settrace(): - try: - tracing_func = _last_tracing_func_thread_local.tracing_func - except AttributeError: - return - else: - SetTrace(tracing_func) - - -def replace_sys_set_trace_func(): - if TracingFunctionHolder._original_tracing is None: - TracingFunctionHolder._original_tracing = sys.settrace - sys.settrace = _internal_set_trace - - -def restore_sys_set_trace_func(): - if TracingFunctionHolder._original_tracing is not None: - sys.settrace = TracingFunctionHolder._original_tracing - TracingFunctionHolder._original_tracing = None - - -_lock = ForkSafeLock() - - -def _load_python_helper_lib(): - try: - # If it's already loaded, just return it. - return _load_python_helper_lib.__lib__ - except AttributeError: - pass - with _lock: - try: - return _load_python_helper_lib.__lib__ - except AttributeError: - pass - - lib = _load_python_helper_lib_uncached() - _load_python_helper_lib.__lib__ = lib - return lib - - -def get_python_helper_lib_filename(): - # Note: we have an independent (and similar -- but not equal) version of this method in - # `add_code_to_python_process.py` which should be kept synchronized with this one (we do a copy - # because the `pydevd_attach_to_process` is mostly independent and shouldn't be imported in the - # debugger -- the only situation where it's imported is if the user actually does an attach to - # process, through `attach_pydevd.py`, but this should usually be called from the IDE directly - # and not from the debugger). - libdir = os.path.join(os.path.dirname(__file__), 'pydevd_attach_to_process') - - arch = '' - if IS_WINDOWS: - # prefer not using platform.machine() when possible (it's a bit heavyweight as it may - # spawn a subprocess). - arch = os.environ.get("PROCESSOR_ARCHITEW6432", os.environ.get('PROCESSOR_ARCHITECTURE', '')) - - if not arch: - arch = platform.machine() - if not arch: - pydev_log.info('platform.machine() did not return valid value.') # This shouldn't happen... - return None - - if IS_WINDOWS: - extension = '.dll' - suffix_64 = 'amd64' - suffix_32 = 'x86' - - elif IS_LINUX: - extension = '.so' - suffix_64 = 'amd64' - suffix_32 = 'x86' - - elif IS_MAC: - extension = '.dylib' - suffix_64 = 'x86_64' - suffix_32 = 'x86' - - else: - pydev_log.info('Unable to set trace to all threads in platform: %s', sys.platform) - return None - - if arch.lower() not in ('amd64', 'x86', 'x86_64', 'i386', 'x86'): - # We don't support this processor by default. Still, let's support the case where the - # user manually compiled it himself with some heuristics. - # - # Ideally the user would provide a library in the format: "attach_." - # based on the way it's currently compiled -- see: - # - windows/compile_windows.bat - # - linux_and_mac/compile_linux.sh - # - linux_and_mac/compile_mac.sh - - try: - found = [name for name in os.listdir(libdir) if name.startswith('attach_') and name.endswith(extension)] - except: - if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1: - # There is no need to show this unless debug tracing is enabled. - pydev_log.exception('Error listing dir: %s', libdir) - return None - - expected_name = 'attach_' + arch + extension - expected_name_linux = 'attach_linux_' + arch + extension - - filename = None - if expected_name in found: # Heuristic: user compiled with "attach_." - filename = os.path.join(libdir, expected_name) - - elif IS_LINUX and expected_name_linux in found: # Heuristic: user compiled with "attach_linux_." - filename = os.path.join(libdir, expected_name_linux) - - elif len(found) == 1: # Heuristic: user removed all libraries and just left his own lib. - filename = os.path.join(libdir, found[0]) - - else: # Heuristic: there's one additional library which doesn't seem to be our own. Find the odd one. - filtered = [name for name in found if not name.endswith((suffix_64 + extension, suffix_32 + extension))] - if len(filtered) == 1: # If more than one is available we can't be sure... - filename = os.path.join(libdir, found[0]) - - if filename is None: - pydev_log.info( - 'Unable to set trace to all threads in arch: %s (did not find a %s lib in %s).', - arch, expected_name, libdir - - ) - return None - - pydev_log.info('Using %s lib in arch: %s.', filename, arch) - - else: - # Happy path for which we have pre-compiled binaries. - if IS_64BIT_PROCESS: - suffix = suffix_64 - else: - suffix = suffix_32 - - if IS_WINDOWS or IS_MAC: # just the extension changes - prefix = 'attach_' - elif IS_LINUX: # - prefix = 'attach_linux_' # historically it has a different name - else: - pydev_log.info('Unable to set trace to all threads in platform: %s', sys.platform) - return None - - filename = os.path.join(libdir, '%s%s%s' % (prefix, suffix, extension)) - - if not os.path.exists(filename): - pydev_log.critical('Expected: %s to exist.', filename) - return None - - return filename - - -def _load_python_helper_lib_uncached(): - if (not IS_CPYTHON or sys.version_info[:2] > (3, 11) - or hasattr(sys, 'gettotalrefcount') or LOAD_NATIVE_LIB_FLAG in ENV_FALSE_LOWER_VALUES): - pydev_log.info('Helper lib to set tracing to all threads not loaded.') - return None - - try: - filename = get_python_helper_lib_filename() - if filename is None: - return None - # Load as pydll so that we don't release the gil. - lib = ctypes.pydll.LoadLibrary(filename) - pydev_log.info('Successfully Loaded helper lib to set tracing to all threads.') - return lib - except: - if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1: - # Only show message if tracing is on (we don't have pre-compiled - # binaries for all architectures -- i.e.: ARM). - pydev_log.exception('Error loading: %s', filename) - return None - - -def set_trace_to_threads(tracing_func, thread_idents=None, create_dummy_thread=True): - assert tracing_func is not None - - ret = 0 - - # Note: use sys._current_frames() keys to get the thread ids because it'll return - # thread ids created in C/C++ where there's user code running, unlike the APIs - # from the threading module which see only threads created through it (unless - # a call for threading.current_thread() was previously done in that thread, - # in which case a dummy thread would've been created for it). - if thread_idents is None: - thread_idents = set(sys._current_frames().keys()) - - for t in threading.enumerate(): - # PY-44778: ignore pydevd threads and also add any thread that wasn't found on - # sys._current_frames() as some existing threads may not appear in - # sys._current_frames() but may be available through the `threading` module. - if getattr(t, 'pydev_do_not_trace', False): - thread_idents.discard(t.ident) - else: - thread_idents.add(t.ident) - - curr_ident = thread.get_ident() - curr_thread = threading._active.get(curr_ident) - - if curr_ident in thread_idents and len(thread_idents) != 1: - # The current thread must be updated first (because we need to set - # the reference to `curr_thread`). - thread_idents = list(thread_idents) - thread_idents.remove(curr_ident) - thread_idents.insert(0, curr_ident) - - for thread_ident in thread_idents: - # If that thread is not available in the threading module we also need to create a - # dummy thread for it (otherwise it'll be invisible to the debugger). - if create_dummy_thread: - if thread_ident not in threading._active: - - class _DummyThread(threading._DummyThread): - - def _set_ident(self): - # Note: Hack to set the thread ident that we want. - self._ident = thread_ident - - t = _DummyThread() - # Reset to the base class (don't expose our own version of the class). - t.__class__ = threading._DummyThread - - if thread_ident == curr_ident: - curr_thread = t - - with threading._active_limbo_lock: - # On Py2 it'll put in active getting the current indent, not using the - # ident that was set, so, we have to update it (should be harmless on Py3 - # so, do it always). - threading._active[thread_ident] = t - threading._active[curr_ident] = curr_thread - - if t.ident != thread_ident: - # Check if it actually worked. - pydev_log.critical('pydevd: creation of _DummyThread with fixed thread ident did not succeed.') - - # Some (ptvsd) tests failed because of this, so, leave it always disabled for now. - # show_debug_info = 1 if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1 else 0 - show_debug_info = 0 - - # Hack to increase _Py_TracingPossible. - # See comments on py_custom_pyeval_settrace.hpp - proceed = thread.allocate_lock() - proceed.acquire() - - def dummy_trace(frame, event, arg): - return dummy_trace - - def increase_tracing_count(): - set_trace = TracingFunctionHolder._original_tracing or sys.settrace - set_trace(dummy_trace) - proceed.release() - - start_new_thread = pydev_monkey.get_original_start_new_thread(thread) - start_new_thread(increase_tracing_count, ()) - proceed.acquire() # Only proceed after the release() is done. - proceed = None - - # Note: The set_trace_func is not really used anymore in the C side. - set_trace_func = TracingFunctionHolder._original_tracing or sys.settrace - - lib = _load_python_helper_lib() - if lib is None: # This is the case if it's not CPython. - pydev_log.info('Unable to load helper lib to set tracing to all threads (unsupported python vm).') - ret = -1 - else: - try: - result = lib.AttachDebuggerTracing( - ctypes.c_int(show_debug_info), - ctypes.py_object(set_trace_func), - ctypes.py_object(tracing_func), - ctypes.c_uint(thread_ident), - ctypes.py_object(None), - ) - except: - if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1: - # There is no need to show this unless debug tracing is enabled. - pydev_log.exception('Error attaching debugger tracing') - ret = -1 - else: - if result != 0: - pydev_log.info('Unable to set tracing for existing thread. Result: %s', result) - ret = result - - return ret - diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/docarray/display/tensor_display.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/docarray/display/tensor_display.py deleted file mode 100644 index 1bf884b518fc27f5781537705eb2687f00214094..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/docarray/display/tensor_display.py +++ /dev/null @@ -1,74 +0,0 @@ -from typing_extensions import TYPE_CHECKING - -if TYPE_CHECKING: - from rich.console import Console, ConsoleOptions, RenderResult - from rich.measure import Measurement - - from docarray.typing.tensor.abstract_tensor import AbstractTensor - - -class TensorDisplay: - """ - Rich representation of a tensor. - """ - - tensor_min_width: int = 30 - - def __init__(self, tensor: 'AbstractTensor'): - self.tensor = tensor - - def __rich_console__( - self, console: 'Console', options: 'ConsoleOptions' - ) -> 'RenderResult': - comp_be = self.tensor.get_comp_backend() - t_squeezed = comp_be.squeeze(comp_be.detach(self.tensor)) - - if comp_be.n_dim(t_squeezed) == 1 and comp_be.shape(t_squeezed)[0] < 200: - import colorsys - - from rich.color import Color - from rich.segment import Segment - from rich.style import Style - - tensor_normalized = comp_be.minmax_normalize(t_squeezed, (0, 5)) - - hue = 0.75 - saturation = 1.0 - for idx, y in enumerate(tensor_normalized): - luminance = 0.1 + ((y / 5) * 0.7) - r, g, b = colorsys.hls_to_rgb(hue, luminance + 0.07, saturation) - color = Color.from_rgb(r * 255, g * 255, b * 255) - yield Segment('▄', Style(color=color, bgcolor=color)) - if idx != 0 and idx % options.max_width == 0: - yield Segment.line() - else: - from rich.text import Text - - yield Text( - f'{self.tensor.__class__.__name__} of ' - f'shape {comp_be.shape(self.tensor)}, ' - f'dtype: {str(comp_be.dtype(self.tensor))}' - ) - - def __rich_measure__( - self, console: 'Console', options: 'ConsoleOptions' - ) -> 'Measurement': - from rich.measure import Measurement - - width = self._compute_table_width(max_width=options.max_width) - return Measurement(1, width) - - def _compute_table_width(self, max_width: int) -> int: - """ - Compute the width of the table. Depending on the length of the tensor, the width - should be in the range of 30 (min) and a given `max_width`. - :return: the width of the table - """ - comp_be = self.tensor.get_comp_backend() - t_squeezed = comp_be.squeeze(comp_be.detach(self.tensor)) - if comp_be.n_dim(t_squeezed) == 1 and comp_be.shape(t_squeezed)[0] < max_width: - min_capped = max(comp_be.shape(t_squeezed)[0], self.tensor_min_width) - min_max_capped = min(min_capped, max_width) - return min_max_capped - else: - return max_width diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/docarray/utils/_internal/__init__.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/docarray/utils/_internal/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/TYH71/gradio-ml-skeleton/app.py b/spaces/TYH71/gradio-ml-skeleton/app.py deleted file mode 100644 index d7eb1905cf09914bca2c9e30cae396dab14e36c1..0000000000000000000000000000000000000000 --- a/spaces/TYH71/gradio-ml-skeleton/app.py +++ /dev/null @@ -1,21 +0,0 @@ -''' -main script for gradio application -''' -import argparse -import gradio as gr -from src.core.logger import logger -from src.interface.yolov5 import yolov5_demo - -demo = gr.TabbedInterface( - [yolov5_demo], - ["YOLOv5 Demo"] -) - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--host", default="0.0.0.0", type=str) - parser.add_argument( - "--port", help="will start gradio app on this port (if available)", default=7860, type=int) - args_all = parser.parse_args() - logger.info("Gradio Application live and running !") - demo.queue().launch(share=False, server_name=args_all.host, server_port=args_all.port) diff --git a/spaces/Tristan/static-rlhf-interface/Makefile b/spaces/Tristan/static-rlhf-interface/Makefile deleted file mode 100644 index de6c7edf2325840ecd5daefa52b7dd6172ffaa37..0000000000000000000000000000000000000000 --- a/spaces/Tristan/static-rlhf-interface/Makefile +++ /dev/null @@ -1,10 +0,0 @@ -.PHONY: style quality - -style: - python -m black --line-length 119 --target-version py38 . - python -m isort . - -quality: - python -m black --check --line-length 119 --target-version py38 . - python -m isort --check-only . - python -m flake8 --max-line-length 119 . diff --git a/spaces/Tuana/find-the-animal/utils/haystack.py b/spaces/Tuana/find-the-animal/utils/haystack.py deleted file mode 100644 index d53964669dd8501229055e29c0d198028619d28f..0000000000000000000000000000000000000000 --- a/spaces/Tuana/find-the-animal/utils/haystack.py +++ /dev/null @@ -1,80 +0,0 @@ -import shutil -from haystack.document_stores import FAISSDocumentStore -from haystack.nodes.retriever import EmbeddingRetriever, MultiModalRetriever -from haystack.nodes.reader import FARMReader -from haystack import Pipeline -from utils.config import (INDEX_DIR) -from typing import List -from haystack import BaseComponent, Answer -import streamlit as st - - - -class AnswerToQuery(BaseComponent): - - outgoing_edges = 1 - - def run(self, query: str, answers: List[Answer]): - return {"query": answers[0].answer}, "output_1" - - def run_batch(self): - raise NotImplementedError() - -# cached to make index and models load only at start -@st.cache( - hash_funcs={"builtins.SwigPyObject": lambda _: None}, allow_output_mutation=True -) -def start_haystack(): - """ - load document store, retrievers for images and text, reader and create pipeline - """ - shutil.copy(f"{INDEX_DIR}/text.db", ".") - shutil.copy(f"{INDEX_DIR}/images.db", ".") - - document_store_text = FAISSDocumentStore( - faiss_index_path=f"{INDEX_DIR}/text.faiss", - faiss_config_path=f"{INDEX_DIR}/text.json", - ) - - document_store_images = FAISSDocumentStore( - faiss_index_path=f"{INDEX_DIR}/images.faiss", - faiss_config_path=f"{INDEX_DIR}/images.json", - ) - - retriever_text = EmbeddingRetriever( - document_store=document_store_text, - embedding_model="sentence-transformers/multi-qa-mpnet-base-dot-v1", - model_format="sentence_transformers", - ) - - reader = FARMReader(model_name_or_path="deepset/deberta-v3-base-squad2", use_gpu=True) - - - retriever_images = MultiModalRetriever( - document_store=document_store_images, - query_embedding_model = "sentence-transformers/clip-ViT-B-32", - query_type="text", - document_embedding_models = { - "image": "sentence-transformers/clip-ViT-B-32" - } - ) - - answer_to_query = AnswerToQuery() - - pipe = Pipeline() - - pipe.add_node(retriever_text, name="text_retriever", inputs=["Query"]) - pipe.add_node(reader, name="text_reader", inputs=["text_retriever"]) - pipe.add_node(answer_to_query, name="answer2query", inputs=["text_reader"]) - pipe.add_node(retriever_images, name="image_retriever", inputs=["answer2query"]) - - return pipe - -pipe = start_haystack() - -@st.cache(allow_output_mutation=True) -def query(statement: str, text_reader_top_k: int = 5): - """Run query""" - params = {"text_reader": {"top_k": text_reader_top_k},"image_retriever": {"top_k": 1},"text_retriever": {"top_k": 5} } - results = pipe.run(statement, params=params) - return results \ No newline at end of file diff --git a/spaces/Vasanthgx/demo_minima_vasanth/README.md b/spaces/Vasanthgx/demo_minima_vasanth/README.md deleted file mode 100644 index 86e6c217a9ea4343ba474bda20e44e235cf7d99f..0000000000000000000000000000000000000000 --- a/spaces/Vasanthgx/demo_minima_vasanth/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Demo Minima Vasanth -emoji: ⚡ -colorFrom: blue -colorTo: indigo -sdk: gradio -sdk_version: 3.27.0 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/VincentZB/Stable-Diffusion-ControlNet-WebUI/diffusion_webui/diffusion_models/stable_diffusion/__init__.py b/spaces/VincentZB/Stable-Diffusion-ControlNet-WebUI/diffusion_webui/diffusion_models/stable_diffusion/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/WZUN666/vits-uma-genshin-honkai/text/symbols.py b/spaces/WZUN666/vits-uma-genshin-honkai/text/symbols.py deleted file mode 100644 index edfbd24247be8c757275ce80b9ec27a0ffa808f3..0000000000000000000000000000000000000000 --- a/spaces/WZUN666/vits-uma-genshin-honkai/text/symbols.py +++ /dev/null @@ -1,39 +0,0 @@ -''' -Defines the set of symbols used in text input to the model. -''' - -'''# japanese_cleaners -_pad = '_' -_punctuation = ',.!?-' -_letters = 'AEINOQUabdefghijkmnoprstuvwyzʃʧ↓↑ ' -''' - -'''# japanese_cleaners2 -_pad = '_' -_punctuation = ',.!?-~…' -_letters = 'AEINOQUabdefghijkmnoprstuvwyzʃʧʦ↓↑ ' -''' - -'''# korean_cleaners -_pad = '_' -_punctuation = ',.!?…~' -_letters = 'ㄱㄴㄷㄹㅁㅂㅅㅇㅈㅊㅋㅌㅍㅎㄲㄸㅃㅆㅉㅏㅓㅗㅜㅡㅣㅐㅔ ' -''' - -'''# chinese_cleaners -_pad = '_' -_punctuation = ',。!?—…' -_letters = 'ㄅㄆㄇㄈㄉㄊㄋㄌㄍㄎㄏㄐㄑㄒㄓㄔㄕㄖㄗㄘㄙㄚㄛㄜㄝㄞㄟㄠㄡㄢㄣㄤㄥㄦㄧㄨㄩˉˊˇˋ˙ ' -''' - -# zh_ja_mixture_cleaners -_pad = '_' -_punctuation = ',.!?-~…' -_letters = 'AEINOQUabdefghijklmnoprstuvwyzʃʧʦɯɹəɥ⁼ʰ`→↓↑ ' - - -# Export all symbols: -symbols = [_pad] + list(_punctuation) + list(_letters) - -# Special symbol ids -SPACE_ID = symbols.index(" ") \ No newline at end of file diff --git a/spaces/Whatcoldwind/csgo_investment/app.py b/spaces/Whatcoldwind/csgo_investment/app.py deleted file mode 100644 index a4c862b1c384d212cff6762579ac70d9d820a3ba..0000000000000000000000000000000000000000 --- a/spaces/Whatcoldwind/csgo_investment/app.py +++ /dev/null @@ -1,474 +0,0 @@ -import functools -from pathlib import Path - -from api import Goods, Inventory, test_tokens -import streamlit as st -from st_aggrid import AgGrid -from st_aggrid import DataReturnMode, GridUpdateMode -from st_aggrid.shared import JsCode -from st_aggrid.grid_options_builder import GridOptionsBuilder -import pandas as pd -from pyecharts.charts import Bar, Pie -from pyecharts import options as opts -from pyecharts.globals import ThemeType -import streamlit_echarts -import json - - - -def delete_goods(inventory, index): - for i in index: - inventory.delete(i['库存编号']) - - -def sell_goods(inventory, index): - for i in index: - try: - inventory()[i['库存编号']].sell(eval(i['卖出价格'])) - except: - st.error("卖出价格输入错误,请检查输入") - -def lease_goods(inventory, index): - for i in index: - inventory()[i['库存编号']].lease() - - -def back_goods(inventory, index): - for i in index: - inventory()[i['库存编号']].back() - - - -def open_inventory(path): - if type(path) == str: - st.session_state.inventory=Inventory(path) - st.session_state.inventory.save() - else: - with st.spinner("加载库存中..."): - st.session_state.inventory = Inventory(path.name) - st.success("库存已打开 ✅") - with open(st.session_state.inventory.path,'wb+') as file: - file.write(path.getvalue()) - with st.spinner("更新饰品信息..."): - progress_bar = st.progress(0) - if len(st.session_state.inventory())<=0: - rate=1 - else: - rate = 1 / len(st.session_state.inventory()) - for p, i in enumerate(st.session_state.inventory): - progress_bar.progress(rate * p) - st.session_state.inventory()[i].refresh() - progress_bar.empty() - - -def save_inventory(path): - with st.spinner("保存库存中..."): - st.session_state.inventory.save() - st.success("库存保存成功 ✅") - with st.sidebar: - with open(st.session_state.inventory.path, 'rb') as f: - st.download_button('下载到本地', f, file_name=st.session_state.inventory.path) -def update_token(token): - if not test_tokens(token): - st.error("Token无效,请重新登陆悠悠,按F12查找token,格式为 Bearer xxx") - return - USER_TOKEN=token - if 'inventory' in st.session_state: - for good in st.session_state.inventory(): - st.session_state.inventory()[good].token=USER_TOKEN - st.success("Token更新成功,请及时保存!!✅") - - - -cellsytle_jscode = JsCode( - """ -function (params) { - if (params.value < 0) { - return { - 'color': 'white', - 'backgroundColor': 'forestgreen' - } - } else { - return { - 'color': 'white', - 'backgroundColor': 'crimson' - } - } - }; - """ -) - -def import_from_file(path,token): - if not "inventory" in st.session_state: - st.error("请新建仓库在导入数据") - return - if not test_tokens(token): - st.error("悠悠token不正确") - return - try: - if path.name.endswith('.csv'): - data=pd.read_csv(path.getvalue()) - elif path.name.endswith('.xlsx'): - data=pd.read_excel(path.getvalue()) - else: - st.error('%s 文件类型不支持'%path.name) - return - for i in range(data.shape[0]): - tmp = Goods(str(data.iloc[i]['Buff id']), int(data.iloc[i]['购入花费(元)']),token=token) - tmp.refresh() - st.session_state.inventory.add(tmp) - st.success(tmp.name + "已添加 ✅") - except: - st.error('检查%s中是否包含 <购入花费(元)>字段'%path) - -def main() -> None: - global USER_TOKEN - st.header("CSGO 饰品投资追踪 :moneybag: :dollar: :bar_chart:") - st.caption("Made by Shevon & Lishuai, maintained by whatcoldwind") - st.text("请在左侧打开库存文件") - with st.sidebar: - st.subheader("选择库存") - path = st.file_uploader("上传本地库存文件") - if path: - launch = st.button('打开库存', on_click=open_inventory, args=(path,)) - new_name=st.text_input("输入新建库存的名称",value="xxxxx") - if new_name: - new_one = st.button('新建库存', on_click=open_inventory, args=(new_name+'.pkl',)) - save = st.button('保存库存更改', on_click=save_inventory, args=(path,)) - token_value = st.text_input("token值", value=USER_TOKEN) - token = st.button('更新悠悠有品token', on_click=update_token, args=(token_value,)) - - if 'inventory' in st.session_state: - import_file_path = st.file_uploader("上传导出表格文件并导入到当前仓库 *.csv *.xlsx") - if import_file_path: - import_bt = st.button('导入', on_click=import_from_file, args=(import_file_path,USER_TOKEN)) - st.caption('目前已启动库存 ' + st.session_state.inventory.path) - st.subheader("添加饰品") - form_track = st.form(key="track") - with form_track: - code = st.text_input("请输入饰品buff代码") - cost = eval(st.text_input("请输入购买价格,0表示仅观望", "0")) - submitted = st.form_submit_button(label="添加") - if submitted: - with st.spinner("加载饰品信息..."): - try: - tmp = Goods(code, cost,token=USER_TOKEN) - tmp.refresh() - st.session_state.inventory.add(tmp) - st.success(tmp.name + "已添加 ✅") - except: - st.error("饰品信息加载失败,请检查代码和token是否正确") - - if 'inventory' in st.session_state: - for good in st.session_state.inventory(): - validation=test_tokens(st.session_state.inventory()[good].token) - if validation : - USER_TOKEN=st.session_state.inventory()[good].token - st.success("✅ 你当前token有效:%s"%USER_TOKEN) - break - st.subheader("投资信息") - if len(st.session_state.inventory()) > 0: - col = st.columns(4) - col2 = st.columns(4) - col3 = st.columns(4) - col[0].metric( - "总投资额", value=f"{st.session_state.inventory.total_cost():.2f} 元", - help="购买饰品总花费" - ) - col[1].metric("追踪总量", value=f"{len(st.session_state.inventory())} 件",help="加入库存文件的饰品数量") - col[2].metric( - "库存价值(Buff计,含租出)", - value=f"{st.session_state.inventory.calc_price():.2f} 元", - help="库存饰品和已租出饰品总价值" - ) - col[3].metric( - "总套现", value=f"{st.session_state.inventory.sell_price():.2f} 元", - help="卖出饰品总收入" - ) - earn = ( - st.session_state.inventory.calc_price() - + st.session_state.inventory.sell_price() - - st.session_state.inventory.total_cost() - ) - col2[0].metric("盈利(Buff计)", value=f"{earn:.2f} 元", - help="总套现 + 库存价值 - 总投资额") - col2[1].metric( - "总收益率", - value=f"{earn/st.session_state.inventory.total_cost()*100:.2f} %", - help="盈利 / 总投资额 * 100" - ) - yyyp_earn = ( - st.session_state.inventory.calc_yyyp_price() - + st.session_state.inventory.sell_price() - - st.session_state.inventory.total_cost() - ) - col2[2].metric("盈利(悠悠有品计)", value=f"{yyyp_earn:.2f} 元") - col2[3].metric( - "总收益率", - value=f"{yyyp_earn/st.session_state.inventory.total_cost()*100:.2f} %", - help="盈利 / 总投资额 * 100" - ) - col3[0].metric( - "持有饰品收益(Buff计)", - value=f"{st.session_state.inventory.calc_price() - st.session_state.inventory.total_cost_in_inventory():.2f} 元", - help="库存价值 - 库存内和已租出饰品总花费" - ) - col3[1].metric( - "持有饰品收益率(Buff计)", - value=f"{100 * (st.session_state.inventory.calc_price() - st.session_state.inventory.total_cost_in_inventory())/st.session_state.inventory.total_cost_in_inventory():.2f} %", - help="( 持有饰品收益 - 库存内和已租出饰品总花费 ) * 100" - ) - col3[2].metric( - "持有饰品收益(悠悠有品计)", - value=f"{st.session_state.inventory.calc_yyyp_price() - st.session_state.inventory.total_cost_in_inventory():.2f} 元", - help="库存价值 - 库存内和已租出饰品总花费" - ) - col3[3].metric( - "持有饰品收益率(悠悠有品计)", - value=f"{100 * (st.session_state.inventory.calc_yyyp_price() - st.session_state.inventory.total_cost_in_inventory())/st.session_state.inventory.total_cost_in_inventory():.2f} %", - help="( 持有饰品收益 - 库存内和已租出饰品总花费 ) * 100" - ) - st.subheader("目前资金组成") - col4 = st.columns(2) - with col4[0]: - fig1 = Pie(init_opts=opts.InitOpts(theme=ThemeType.MACARONS)).add( - "库存资金组成", - [('出租',sum( - [ - st.session_state.inventory()[good].price - for good in st.session_state.inventory() - if st.session_state.inventory()[good].status == 1 - ] - )), - ('在库',sum( - [ - st.session_state.inventory()[good].price - for good in st.session_state.inventory() - if ( - st.session_state.inventory()[good].status == 0 - and st.session_state.inventory()[good].cost != 0 - ) - ] - ))], - radius=["30%", "75%"], - ) - streamlit_echarts.st_pyecharts(fig1, height="400px", key="fig1") - with col4[1]: - fig2 = Pie(init_opts=opts.InitOpts(theme=ThemeType.MACARONS)).add( - "盈利资金组成", - [('库存增值',st.session_state.inventory.calc_price() - - st.session_state.inventory.total_cost_in_inventory(),), ('卖出收益',st.session_state.inventory.sell_earn(),)], - radius=["30%", "75%"], - ) - streamlit_echarts.st_pyecharts(fig2, height="400px", key="fig2") - else: - st.caption("当前库存为空") - # 追踪列表 - st.subheader("追踪列表") - st.text("右键表格可以导出表格") - if len(st.session_state.inventory()) > 0: - data = pd.DataFrame( - columns=['库存编号', 'Buff id', '名称', '状态', '购入花费(元)', '卖出价格'] - ) - for xx in st.session_state.inventory: - xx = st.session_state.inventory()[xx] - data.loc[len(data)] = [ - xx.index, - xx.id, - xx.name, - xx.get_status(), - xx.cost, - xx.sell_price, - ] - - gb = GridOptionsBuilder.from_dataframe(data) - - gb.configure_selection( - selection_mode='multiple', - use_checkbox=True, - ) - gb.configure_side_bar() - gb.configure_grid_options(domLayout='normal') - gridOptions = gb.build() - grid = AgGrid( - data, - gridOptions=gridOptions, - allow_unsafe_jscode=True, - return_mode_value=DataReturnMode.FILTERED, - update_mode=GridUpdateMode.MODEL_CHANGED, - enable_enterprise_modules=True, - ) - selected = grid["selected_rows"] - if selected != []: - print(selected) - st.button( - '删除选中饰品', - on_click=delete_goods, - args=(st.session_state.inventory, selected), - ) - st.button( - '出售选中饰品', - on_click=sell_goods, - args=(st.session_state.inventory, selected), - ) - st.button( - '租出选中饰品', - on_click=lease_goods, - args=(st.session_state.inventory, selected), - ) - st.button( - '回仓选中饰品', - on_click=back_goods, - args=(st.session_state.inventory, selected), - ) - else: - st.caption("暂无饰品记录") - - goods = [st.session_state.inventory()[xx] for xx in st.session_state.inventory] - # 已购列表 - st.subheader("已购列表") - st.text("右键表格可以导出表格") - track = [xx for xx in goods if xx.cost != 0] - if len(track) > 0: - data_track = pd.DataFrame([xx() for xx in track]) - data_track['Status'] = data_track['Status'].map( - {0: '在库中', 1: '已租出', 2: '已卖出'} - ) - - data_track.columns = [ - 'Buff id', - '有品 id', - '名称', - '购入花费(元)', - 'Buff 价格', - '有品价格', - 'Steam 价格(元)', - '状态', - '有品在售', - '有品在租', - '短租价格(元)', - '长租价格(元)', - '押金(元)', - '租售比', - '理论目前收益(元)', - '理论目前收益率(%)', - '租金比例(%)', - '押金比例(%)', - '年化短租比例(%)', - '年化长租比例(%)', - '套现比例(%)', - 'buff和有品价格比例', - ] - data_track = data_track.round(4) - #del data_track['Buff id'] - #del data_track['有品 id'] - gb0 = GridOptionsBuilder.from_dataframe(data_track) - gb0.configure_columns(["Buff id", "有品 id", "名称"], pinned=True) - gb0.configure_columns( - ['理论目前收益(元)', '理论目前收益率(%)'], - cellStyle=cellsytle_jscode, - ) - gb0.configure_side_bar() - gb0.configure_grid_options(domLayout='normal') - - gridOptions = gb0.build() - grid_track = AgGrid( - data_track, - gridOptions=gridOptions, - allow_unsafe_jscode=True, - enable_enterprise_modules=True, - ) - st.subheader("理论收益分析") - # Plot - x = data_track.sort_values( - by='理论目前收益率(%)', - )['名称'].tolist() - y1 = data_track.sort_values( - by='理论目前收益率(%)', - )['理论目前收益率(%)'].tolist() - y2 = data_track.sort_values( - by='理论目前收益率(%)', - )['理论目前收益(元)'].tolist() - fig0 = ( - Bar(init_opts=opts.InitOpts(theme=ThemeType.MACARONS)) - .add_xaxis(x) - .add_yaxis("理论目前收益率(%)", y1) - .add_yaxis("理论目前收益(元)", y2) - .reversal_axis() - .set_global_opts( - # 设置操作图表缩放功能,orient="vertical" 为Y轴 滑动 - datazoom_opts=[ - opts.DataZoomOpts(), - opts.DataZoomOpts(type_="inside", range_start=0, range_end=100), - opts.DataZoomOpts( - orient="vertical", - range_start=0, - range_end=100, - ), - ], - ) - # .render("bar_datazoom_both.html") - ) - - streamlit_echarts.st_pyecharts(fig0, height="900px", key="fig0") - - else: - st.caption("暂无已购饰品") - - # 观望列表 - st.subheader("观望列表") - observe = [xx for xx in goods if xx.cost == 0] - if len(observe) > 0: - data_observe = pd.DataFrame([xx() for xx in observe]) - del data_observe['Cost'] - data_observe['Status'] = data_observe['Status'].map({0: '观望中'}) - - data_observe.columns = [ - 'Buff id', - '有品 id', - '名称', - 'Buff 价格(元)', - '有品价格(元)', - 'Steam 价格(元)', - '状态', - '有品在售', - '有品在租', - '短租价格(元)', - '长租价格(元)', - '押金', - '租售比', - '租金比例(%)', - '押金比例(%)', - '年化短租比例(%)', - '年化长租比例(%)', - '套现比例(%)', - 'buff和有品价格比例', - ] - data_observe = data_observe.round(4) - del data_observe['Buff id'] - del data_observe['有品 id'] - gb1 = GridOptionsBuilder.from_dataframe(data_observe) - gb1.configure_columns(["Buff id", "有品 id", "名称"], pinned=True) - gb1.configure_side_bar() - gb1.configure_grid_options(domLayout='normal') - - gridOptions = gb1.build() - grid_observe = AgGrid( - data_observe, - gridOptions=gridOptions, - allow_unsafe_jscode=True, - enable_enterprise_modules=True, - ) - - else: - st.caption("暂无观望饰品") - - -if __name__ == "__main__": - st.set_page_config( - "CSGO 饰品投资追踪", - "💰", - layout="wide", - ) - USER_TOKEN="Bearer xxx" - main() diff --git a/spaces/XAI/CHM-Corr/common/logger.py b/spaces/XAI/CHM-Corr/common/logger.py deleted file mode 100644 index 062895e2355eb83abe2f8be3ed0957ef9155d007..0000000000000000000000000000000000000000 --- a/spaces/XAI/CHM-Corr/common/logger.py +++ /dev/null @@ -1,117 +0,0 @@ -r""" Logging """ - -import datetime -import logging -import os - -from tensorboardX import SummaryWriter -import torch - - -class Logger: - r""" Writes results of training/testing """ - @classmethod - def initialize(cls, args, training): - logtime = datetime.datetime.now().__format__('_%m%d_%H%M%S') - logpath = args.logpath if training else '_TEST_' + args.load.split('/')[-1].split('.')[0] + logtime - if logpath == '': logpath = logtime - - cls.logpath = os.path.join('logs', logpath + '.log') - cls.benchmark = args.benchmark - os.makedirs(cls.logpath) - - logging.basicConfig(filemode='w', - filename=os.path.join(cls.logpath, 'log.txt'), - level=logging.INFO, - format='%(message)s', - datefmt='%m-%d %H:%M:%S') - - # Console log config - console = logging.StreamHandler() - console.setLevel(logging.INFO) - formatter = logging.Formatter('%(message)s') - console.setFormatter(formatter) - logging.getLogger('').addHandler(console) - - # Tensorboard writer - cls.tbd_writer = SummaryWriter(os.path.join(cls.logpath, 'tbd/runs')) - - # Log arguments - if training: - logging.info(':======== Convolutional Hough Matching Networks =========') - for arg_key in args.__dict__: - logging.info('| %20s: %-24s' % (arg_key, str(args.__dict__[arg_key]))) - logging.info(':========================================================\n') - - @classmethod - def info(cls, msg): - r""" Writes message to .txt """ - logging.info(msg) - - @classmethod - def save_model(cls, model, epoch, val_pck): - torch.save(model.state_dict(), os.path.join(cls.logpath, 'pck_best_model.pt')) - cls.info('Model saved @%d w/ val. PCK: %5.2f.\n' % (epoch, val_pck)) - - -class AverageMeter: - r""" Stores loss, evaluation results, selected layers """ - def __init__(self, benchamrk): - r""" Constructor of AverageMeter """ - self.buffer_keys = ['pck'] - self.buffer = {} - for key in self.buffer_keys: - self.buffer[key] = [] - - self.loss_buffer = [] - - def update(self, eval_result, loss=None): - for key in self.buffer_keys: - self.buffer[key] += eval_result[key] - - if loss is not None: - self.loss_buffer.append(loss) - - def write_result(self, split, epoch): - msg = '\n*** %s ' % split - msg += '[@Epoch %02d] ' % epoch - - if len(self.loss_buffer) > 0: - msg += 'Loss: %5.2f ' % (sum(self.loss_buffer) / len(self.loss_buffer)) - - for key in self.buffer_keys: - msg += '%s: %6.2f ' % (key.upper(), sum(self.buffer[key]) / len(self.buffer[key])) - msg += '***\n' - Logger.info(msg) - - def write_process(self, batch_idx, datalen, epoch): - msg = '[Epoch: %02d] ' % epoch - msg += '[Batch: %04d/%04d] ' % (batch_idx+1, datalen) - if len(self.loss_buffer) > 0: - msg += 'Loss: %5.2f ' % self.loss_buffer[-1] - msg += 'Avg Loss: %5.5f ' % (sum(self.loss_buffer) / len(self.loss_buffer)) - - for key in self.buffer_keys: - msg += 'Avg %s: %5.2f ' % (key.upper(), sum(self.buffer[key]) / len(self.buffer[key]) * 100) - Logger.info(msg) - - def write_test_process(self, batch_idx, datalen): - msg = '[Batch: %04d/%04d] ' % (batch_idx+1, datalen) - - for key in self.buffer_keys: - if key == 'pck': - pcks = torch.stack(self.buffer[key]).mean(dim=0) * 100 - val = '' - for p in pcks: - val += '%5.2f ' % p.item() - msg += 'Avg %s: %s ' % (key.upper(), val) - else: - msg += 'Avg %s: %5.2f ' % (key.upper(), sum(self.buffer[key]) / len(self.buffer[key])) - Logger.info(msg) - - def get_test_result(self): - result = {} - for key in self.buffer_keys: - result[key] = torch.stack(self.buffer[key]).mean(dim=0) * 100 - - return result diff --git a/spaces/XS-1/BW_IMAGE_VIDEO_COLORIZER/fastai/vision/models/xresnet2.py b/spaces/XS-1/BW_IMAGE_VIDEO_COLORIZER/fastai/vision/models/xresnet2.py deleted file mode 100644 index 58c1a94154062de89cfe6ee10f1526a0375819d0..0000000000000000000000000000000000000000 --- a/spaces/XS-1/BW_IMAGE_VIDEO_COLORIZER/fastai/vision/models/xresnet2.py +++ /dev/null @@ -1,202 +0,0 @@ -import torch.nn as nn -import torch -import math -import torch.utils.model_zoo as model_zoo -from ...torch_core import Module - - -__all__ = ['XResNet', 'xresnet18', 'xresnet34_2', 'xresnet50_2', 'xresnet101', 'xresnet152'] - - -def conv3x3(in_planes, out_planes, stride=1): - return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) - - -class BasicBlock(Module): - expansion = 1 - - def __init__(self, inplanes, planes, stride=1, downsample=None): - super(BasicBlock, self).__init__() - self.conv1 = conv3x3(inplanes, planes, stride) - self.bn1 = nn.BatchNorm2d(planes) - self.relu = nn.ReLU(inplace=True) - self.conv2 = conv3x3(planes, planes) - self.bn2 = nn.BatchNorm2d(planes) - self.downsample = downsample - self.stride = stride - - def forward(self, x): - residual = x - - out = self.conv1(x) - out = self.bn1(out) - out = self.relu(out) - - out = self.conv2(out) - out = self.bn2(out) - - if self.downsample is not None: residual = self.downsample(x) - - out += residual - out = self.relu(out) - - return out - - -class Bottleneck(Module): - expansion = 4 - - def __init__(self, inplanes, planes, stride=1, downsample=None): - super(Bottleneck, self).__init__() - self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) - self.bn1 = nn.BatchNorm2d(planes) - self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, - padding=1, bias=False) - self.bn2 = nn.BatchNorm2d(planes) - self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False) - self.bn3 = nn.BatchNorm2d(planes * self.expansion) - self.relu = nn.ReLU(inplace=True) - self.downsample = downsample - self.stride = stride - - def forward(self, x): - residual = x - - out = self.conv1(x) - out = self.bn1(out) - out = self.relu(out) - - out = self.conv2(out) - out = self.bn2(out) - out = self.relu(out) - - out = self.conv3(out) - out = self.bn3(out) - - if self.downsample is not None: residual = self.downsample(x) - - out += residual - out = self.relu(out) - - return out - -def conv2d(ni, nf, stride): - return nn.Sequential(nn.Conv2d(ni, nf, kernel_size=3, stride=stride, padding=1, bias=False), - nn.BatchNorm2d(nf), nn.ReLU(inplace=True)) - -class XResNet(Module): - - def __init__(self, block, layers, c_out=1000): - self.inplanes = 64 - super(XResNet, self).__init__() - self.conv1 = conv2d(3, 32, 2) - self.conv2 = conv2d(32, 32, 1) - self.conv3 = conv2d(32, 64, 1) - self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) - self.layer1 = self._make_layer(block, 64, layers[0]) - self.layer2 = self._make_layer(block, 128, layers[1], stride=2) - self.layer3 = self._make_layer(block, 256, layers[2], stride=2) - self.layer4 = self._make_layer(block, 512, layers[3], stride=2) - self.avgpool = nn.AdaptiveAvgPool2d(1) - self.fc = nn.Linear(512 * block.expansion, c_out) - - for m in self.modules(): - if isinstance(m, nn.Conv2d): - nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') - elif isinstance(m, nn.BatchNorm2d): - nn.init.constant_(m.weight, 1) - nn.init.constant_(m.bias, 0) - - for m in self.modules(): - if isinstance(m, BasicBlock): m.bn2.weight = nn.Parameter(torch.zeros_like(m.bn2.weight)) - if isinstance(m, Bottleneck): m.bn3.weight = nn.Parameter(torch.zeros_like(m.bn3.weight)) - if isinstance(m, nn.Linear): m.weight.data.normal_(0, 0.01) - - def _make_layer(self, block, planes, blocks, stride=1): - downsample = None - if stride != 1 or self.inplanes != planes * block.expansion: - layers = [] - if stride==2: layers.append(nn.AvgPool2d(kernel_size=2, stride=2)) - layers += [ - nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=1, bias=False), - nn.BatchNorm2d(planes * block.expansion) ] - downsample = nn.Sequential(*layers) - - layers = [] - layers.append(block(self.inplanes, planes, stride, downsample)) - self.inplanes = planes * block.expansion - for i in range(1, blocks): layers.append(block(self.inplanes, planes)) - return nn.Sequential(*layers) - - def forward(self, x): - x = self.conv1(x) - x = self.conv2(x) - x = self.conv3(x) - x = self.maxpool(x) - - x = self.layer1(x) - x = self.layer2(x) - x = self.layer3(x) - x = self.layer4(x) - - x = self.avgpool(x) - x = x.view(x.size(0), -1) - x = self.fc(x) - - return x - - -def xresnet18(pretrained=False, **kwargs): - """Constructs a XResNet-18 model. - - Args: - pretrained (bool): If True, returns a model pre-trained on ImageNet - """ - model = XResNet(BasicBlock, [2, 2, 2, 2], **kwargs) - if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['xresnet18'])) - return model - - -def xresnet34_2(pretrained=False, **kwargs): - """Constructs a XResNet-34 model. - - Args: - pretrained (bool): If True, returns a model pre-trained on ImageNet - """ - model = XResNet(BasicBlock, [3, 4, 6, 3], **kwargs) - if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['xresnet34'])) - return model - - -def xresnet50_2(pretrained=False, **kwargs): - """Constructs a XResNet-50 model. - - Args: - pretrained (bool): If True, returns a model pre-trained on ImageNet - """ - model = XResNet(Bottleneck, [3, 4, 6, 3], **kwargs) - if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['xresnet50'])) - return model - - -def xresnet101(pretrained=False, **kwargs): - """Constructs a XResNet-101 model. - - Args: - pretrained (bool): If True, returns a model pre-trained on ImageNet - """ - model = XResNet(Bottleneck, [3, 4, 23, 3], **kwargs) - if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['xresnet101'])) - return model - - -def xresnet152(pretrained=False, **kwargs): - """Constructs a XResNet-152 model. - - Args: - pretrained (bool): If True, returns a model pre-trained on ImageNet - """ - model = XResNet(Bottleneck, [3, 8, 36, 3], **kwargs) - if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['xresnet152'])) - return model - diff --git a/spaces/Xhaheen/ASR_Whisper_OpenAI/app.py b/spaces/Xhaheen/ASR_Whisper_OpenAI/app.py deleted file mode 100644 index 37d969c71c639b9581642ea1948b0fc722ec0cde..0000000000000000000000000000000000000000 --- a/spaces/Xhaheen/ASR_Whisper_OpenAI/app.py +++ /dev/null @@ -1,177 +0,0 @@ -import gradio as gr -import whisper - -model = whisper.load_model("base") - - - -def inference(audio): - audio = whisper.load_audio(audio) - audio = whisper.pad_or_trim(audio) - - mel = whisper.log_mel_spectrogram(audio).to(model.device) - - _, probs = model.detect_language(mel) - lang = max(probs, key=probs.get) - - options = whisper.DecodingOptions(fp16 = False) - result = whisper.decode(model, mel, options) - - return lang.upper(), result.text - - -title="Open AI Whisper" - -description="Whisper is a general-purpose speech recognition model. It is trained on a large dataset of diverse audio and is also a multi-task model that can perform multilingual speech recognition as well as speech translation and language identification." - -css = """ - .gradio-container { - font-family: 'IBM Plex Sans', sans-serif; - } - .gr-button { - color: white; - border-color: black; - background: black; - } - input[type='range'] { - accent-color: black; - } - .dark input[type='range'] { - accent-color: #dfdfdf; - } - .container { - max-width: 730px; - margin: auto; - padding-top: 1.5rem; - } - - .details:hover { - text-decoration: underline; - } - .gr-button { - white-space: nowrap; - } - .gr-button:focus { - border-color: rgb(147 197 253 / var(--tw-border-opacity)); - outline: none; - box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); - --tw-border-opacity: 1; - --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); - --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color); - --tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity)); - --tw-ring-opacity: .5; - } - .footer { - margin-bottom: 45px; - margin-top: 35px; - text-align: center; - border-bottom: 1px solid #e5e5e5; - } - .footer>p { - font-size: .8rem; - display: inline-block; - padding: 0 10px; - transform: translateY(10px); - background: white; - } - .dark .footer { - border-color: #303030; - } - .dark .footer>p { - background: #0b0f19; - } - .prompt h4{ - margin: 1.25em 0 .25em 0; - font-weight: bold; - font-size: 115%; - } -""" - -block = gr.Blocks(css=css) - - - -with block: - gr.HTML( - """ -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - -

- OpenAI Whisper -

-
-

- Whisper is a general-purpose speech recognition model. It is trained on a large dataset of diverse audio and is also a multi-task model that can perform multilingual speech recognition as well as speech translation and language identification. -

-
- """ - ) - with gr.Group(): - with gr.Box(): - with gr.Row().style(mobile_collapse=False, equal_height=True): - audio = gr.Audio( - label="Input Audio", - show_label=False, - source="microphone", - type="filepath" - ) - - btn = gr.Button("Transcribe") - - lang_str = gr.Textbox(label="language") - - text = gr.Textbox(label="Transcription") - - - - - btn.click(inference, inputs=[audio], outputs=[lang_str,text]) - - gr.HTML(''' - - ''') - -block.launch() diff --git a/spaces/Xule/ChuanhuChatGPT/modules/presets.py b/spaces/Xule/ChuanhuChatGPT/modules/presets.py deleted file mode 100644 index 969f122198a360f8c3eb126b156d056ab81d53e1..0000000000000000000000000000000000000000 --- a/spaces/Xule/ChuanhuChatGPT/modules/presets.py +++ /dev/null @@ -1,222 +0,0 @@ -# -*- coding:utf-8 -*- -import os -from pathlib import Path -import gradio as gr -from .webui_locale import I18nAuto - -i18n = I18nAuto() # internationalization - -CHATGLM_MODEL = None -CHATGLM_TOKENIZER = None -LLAMA_MODEL = None -LLAMA_INFERENCER = None - -# ChatGPT 设置 -INITIAL_SYSTEM_PROMPT = "You are a helpful assistant." -API_HOST = "api.openai.com" -COMPLETION_URL = "https://api.openai.com/v1/chat/completions" -BALANCE_API_URL="https://api.openai.com/dashboard/billing/credit_grants" -USAGE_API_URL="https://api.openai.com/dashboard/billing/usage" -HISTORY_DIR = Path("history") -HISTORY_DIR = "history" -TEMPLATES_DIR = "templates" - -# 错误信息 -STANDARD_ERROR_MSG = i18n("☹️发生了错误:") # 错误信息的标准前缀 -GENERAL_ERROR_MSG = i18n("获取对话时发生错误,请查看后台日志") -ERROR_RETRIEVE_MSG = i18n("请检查网络连接,或者API-Key是否有效。") -CONNECTION_TIMEOUT_MSG = i18n("连接超时,无法获取对话。") # 连接超时 -READ_TIMEOUT_MSG = i18n("读取超时,无法获取对话。") # 读取超时 -PROXY_ERROR_MSG = i18n("代理错误,无法获取对话。") # 代理错误 -SSL_ERROR_PROMPT = i18n("SSL错误,无法获取对话。") # SSL 错误 -NO_APIKEY_MSG = i18n("API key为空,请检查是否输入正确。") # API key 长度不足 51 位 -NO_INPUT_MSG = i18n("请输入对话内容。") # 未输入对话内容 -BILLING_NOT_APPLICABLE_MSG = i18n("账单信息不适用") # 本地运行的模型返回的账单信息 - -TIMEOUT_STREAMING = 60 # 流式对话时的超时时间 -TIMEOUT_ALL = 200 # 非流式对话时的超时时间 -ENABLE_STREAMING_OPTION = True # 是否启用选择选择是否实时显示回答的勾选框 -HIDE_MY_KEY = False # 如果你想在UI中隐藏你的 API 密钥,将此值设置为 True -CONCURRENT_COUNT = 100 # 允许同时使用的用户数量 - -SIM_K = 5 -INDEX_QUERY_TEMPRATURE = 1.0 - -CHUANHU_TITLE = i18n("川虎Chat 🚀") - -CHUANHU_DESCRIPTION = i18n("由Bilibili [土川虎虎虎](https://space.bilibili.com/29125536) 和 [明昭MZhao](https://space.bilibili.com/24807452)开发
访问川虎Chat的 [GitHub项目](https://github.com/GaiZhenbiao/ChuanhuChatGPT) 下载最新版脚本") - -FOOTER = """
{versions}
""" - -APPEARANCE_SWITCHER = """ -
-"""+ i18n("切换亮暗色主题") + """ - -
-""" - -SUMMARIZE_PROMPT = "你是谁?我们刚才聊了什么?" # 总结对话时的 prompt - -ONLINE_MODELS = [ - "gpt-3.5-turbo", - "gpt-3.5-turbo-0301", - "gpt-4", - "gpt-4-0314", - "gpt-4-32k", - "gpt-4-32k-0314", - "xmchat", -] - -LOCAL_MODELS = [ - "chatglm-6b", - "chatglm-6b-int4", - "chatglm-6b-int4-qe", - "llama-7b-hf", - "llama-13b-hf", - "llama-30b-hf", - "llama-65b-hf" -] - -if os.environ.get('HIDE_LOCAL_MODELS', 'false') == 'true': - MODELS = ONLINE_MODELS -else: - MODELS = ONLINE_MODELS + LOCAL_MODELS - -DEFAULT_MODEL = 0 - -os.makedirs("models", exist_ok=True) -os.makedirs("lora", exist_ok=True) -os.makedirs("history", exist_ok=True) -for dir_name in os.listdir("models"): - if os.path.isdir(os.path.join("models", dir_name)): - if dir_name not in MODELS: - MODELS.append(dir_name) - -MODEL_TOKEN_LIMIT = { - "gpt-3.5-turbo": 4096, - "gpt-3.5-turbo-0301": 4096, - "gpt-4": 8192, - "gpt-4-0314": 8192, - "gpt-4-32k": 32768, - "gpt-4-32k-0314": 32768 -} - -TOKEN_OFFSET = 1000 # 模型的token上限减去这个值,得到软上限。到达软上限之后,自动尝试减少token占用。 -DEFAULT_TOKEN_LIMIT = 3000 # 默认的token上限 -REDUCE_TOKEN_FACTOR = 0.5 # 与模型token上限想乘,得到目标token数。减少token占用时,将token占用减少到目标token数以下。 - -REPLY_LANGUAGES = [ - "简体中文", - "繁體中文", - "English", - "日本語", - "Español", - "Français", - "Deutsch", - "跟随问题语言(不稳定)" -] - - -WEBSEARCH_PTOMPT_TEMPLATE = """\ -Web search results: - -{web_results} -Current date: {current_date} - -Instructions: Using the provided web search results, write a comprehensive reply to the given query. Make sure to cite results using [[number](URL)] notation after the reference. If the provided search results refer to multiple subjects with the same name, write separate answers for each subject. -Query: {query} -Reply in {reply_language} -""" - -PROMPT_TEMPLATE = """\ -Context information is below. ---------------------- -{context_str} ---------------------- -Current date: {current_date}. -Using the provided context information, write a comprehensive reply to the given query. -Make sure to cite results using [number] notation after the reference. -If the provided context information refer to multiple subjects with the same name, write separate answers for each subject. -Use prior knowledge only if the given context didn't provide enough information. -Answer the question: {query_str} -Reply in {reply_language} -""" - -REFINE_TEMPLATE = """\ -The original question is as follows: {query_str} -We have provided an existing answer: {existing_answer} -We have the opportunity to refine the existing answer -(only if needed) with some more context below. ------------- -{context_msg} ------------- -Given the new context, refine the original answer to better -Reply in {reply_language} -If the context isn't useful, return the original answer. -""" - -ALREADY_CONVERTED_MARK = "" - -small_and_beautiful_theme = gr.themes.Soft( - primary_hue=gr.themes.Color( - c50="#02C160", - c100="rgba(2, 193, 96, 0.2)", - c200="#02C160", - c300="rgba(2, 193, 96, 0.32)", - c400="rgba(2, 193, 96, 0.32)", - c500="rgba(2, 193, 96, 1.0)", - c600="rgba(2, 193, 96, 1.0)", - c700="rgba(2, 193, 96, 0.32)", - c800="rgba(2, 193, 96, 0.32)", - c900="#02C160", - c950="#02C160", - ), - secondary_hue=gr.themes.Color( - c50="#576b95", - c100="#576b95", - c200="#576b95", - c300="#576b95", - c400="#576b95", - c500="#576b95", - c600="#576b95", - c700="#576b95", - c800="#576b95", - c900="#576b95", - c950="#576b95", - ), - neutral_hue=gr.themes.Color( - name="gray", - c50="#f9fafb", - c100="#f3f4f6", - c200="#e5e7eb", - c300="#d1d5db", - c400="#B2B2B2", - c500="#808080", - c600="#636363", - c700="#515151", - c800="#393939", - c900="#272727", - c950="#171717", - ), - radius_size=gr.themes.sizes.radius_sm, - ).set( - button_primary_background_fill="#06AE56", - button_primary_background_fill_dark="#06AE56", - button_primary_background_fill_hover="#07C863", - button_primary_border_color="#06AE56", - button_primary_border_color_dark="#06AE56", - button_primary_text_color="#FFFFFF", - button_primary_text_color_dark="#FFFFFF", - button_secondary_background_fill="#F2F2F2", - button_secondary_background_fill_dark="#2B2B2B", - button_secondary_text_color="#393939", - button_secondary_text_color_dark="#FFFFFF", - # background_fill_primary="#F7F7F7", - # background_fill_primary_dark="#1F1F1F", - block_title_text_color="*primary_500", - block_title_background_fill="*primary_100", - input_background_fill="#F6F6F6", - ) diff --git a/spaces/XzJosh/Bekki-Bert-VITS2/preprocess_text.py b/spaces/XzJosh/Bekki-Bert-VITS2/preprocess_text.py deleted file mode 100644 index 5eb0f3b9e929fcbe91dcbeb653391227a2518a15..0000000000000000000000000000000000000000 --- a/spaces/XzJosh/Bekki-Bert-VITS2/preprocess_text.py +++ /dev/null @@ -1,64 +0,0 @@ -import json -from random import shuffle - -import tqdm -from text.cleaner import clean_text -from collections import defaultdict -stage = [1,2,3] - -transcription_path = 'filelists/genshin.list' -train_path = 'filelists/train.list' -val_path = 'filelists/val.list' -config_path = "configs/config.json" -val_per_spk = 4 -max_val_total = 8 - -if 1 in stage: - with open( transcription_path+'.cleaned', 'w', encoding='utf-8') as f: - for line in tqdm.tqdm(open(transcription_path, encoding='utf-8').readlines()): - try: - utt, spk, language, text = line.strip().split('|') - norm_text, phones, tones, word2ph = clean_text(text, language) - f.write('{}|{}|{}|{}|{}|{}|{}\n'.format(utt, spk, language, norm_text, ' '.join(phones), - " ".join([str(i) for i in tones]), - " ".join([str(i) for i in word2ph]))) - except Exception as error : - print("err!", utt, error) - -if 2 in stage: - spk_utt_map = defaultdict(list) - spk_id_map = {} - current_sid = 0 - - with open( transcription_path+'.cleaned', encoding='utf-8') as f: - for line in f.readlines(): - utt, spk, language, text, phones, tones, word2ph = line.strip().split('|') - spk_utt_map[spk].append(line) - if spk not in spk_id_map.keys(): - spk_id_map[spk] = current_sid - current_sid += 1 - train_list = [] - val_list = [] - - for spk, utts in spk_utt_map.items(): - shuffle(utts) - val_list+=utts[:val_per_spk] - train_list+=utts[val_per_spk:] - if len(val_list) > max_val_total: - train_list+=val_list[max_val_total:] - val_list = val_list[:max_val_total] - - with open( train_path,"w", encoding='utf-8') as f: - for line in train_list: - f.write(line) - - with open(val_path, "w", encoding='utf-8') as f: - for line in val_list: - f.write(line) - -if 3 in stage: - assert 2 in stage - config = json.load(open(config_path, encoding='utf-8')) - config["data"]['spk2id'] = spk_id_map - with open(config_path, 'w', encoding='utf-8') as f: - json.dump(config, f, indent=2, ensure_ascii=False) diff --git a/spaces/XzJosh/Carol-Bert-VITS2/monotonic_align/core.py b/spaces/XzJosh/Carol-Bert-VITS2/monotonic_align/core.py deleted file mode 100644 index dddc688d76172b880054e544b7a217acd013f14f..0000000000000000000000000000000000000000 --- a/spaces/XzJosh/Carol-Bert-VITS2/monotonic_align/core.py +++ /dev/null @@ -1,35 +0,0 @@ -import numba - - -@numba.jit(numba.void(numba.int32[:,:,::1], numba.float32[:,:,::1], numba.int32[::1], numba.int32[::1]), nopython=True, nogil=True) -def maximum_path_jit(paths, values, t_ys, t_xs): - b = paths.shape[0] - max_neg_val=-1e9 - for i in range(int(b)): - path = paths[i] - value = values[i] - t_y = t_ys[i] - t_x = t_xs[i] - - v_prev = v_cur = 0.0 - index = t_x - 1 - - for y in range(t_y): - for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): - if x == y: - v_cur = max_neg_val - else: - v_cur = value[y-1, x] - if x == 0: - if y == 0: - v_prev = 0. - else: - v_prev = max_neg_val - else: - v_prev = value[y-1, x-1] - value[y, x] += max(v_prev, v_cur) - - for y in range(t_y - 1, -1, -1): - path[y, index] = 1 - if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]): - index = index - 1 diff --git a/spaces/Yassine/Stego/app.py b/spaces/Yassine/Stego/app.py deleted file mode 100644 index 77294271d07c3f975cea138541e3ac969fb04c98..0000000000000000000000000000000000000000 --- a/spaces/Yassine/Stego/app.py +++ /dev/null @@ -1,63 +0,0 @@ -import stc -import cv2 -import random -import numpy as np -import gradio as gr -from PIL import Image -from scipy import signal - - -title = "Steganography" -description = '''Explore hiding messages in images using content adaptive steganography and STCs (Syndrome Trellis Codes). - http://dde.binghamton.edu/download/syndrome/ . - We use HILL https://ieeexplore.ieee.org/document/7025854 . - Python implementation adapted from Daniel Lerch's https://github.com/daniellerch/pySTC . - To encode: - Drag and drop a PNG file, write a message and enter a key (remember the key), the generated image has the secret message encoded. - To decode: - Drag and drop the stego file that you just generated, enter the key. - Note that this software is supplied "as is," without any services or security guaranties. - ''' - -def HILL(input_image, operation, message, key): - tmp_name = str(random.randint(100,500)) - try: - buffer = input_image - I = cv2.imdecode(np.frombuffer(buffer, np.uint8), 1) - I = cv2.cvtColor(I,cv2.COLOR_BGR2GRAY) - cv2.imwrite('tmp/'+tmp_name+'.png',I) - except Exception as e: - print(e) - raise ValueError('Unable to read image') - - if operation == 'decode': - try: - stc.extract('tmp/'+tmp_name+'.png', key, 'tmp/'+tmp_name+'.txt') - return 'tmp/'+tmp_name+'.txt' - except: - raise ValueError('Unable to decode') - - else: - H = np.array( - [[-1, 2, -1], - [ 2, -4, 2], - [-1, 2, -1]]) - L1 = np.ones((3, 3)).astype('float32')/(3**2) - L2 = np.ones((15, 15)).astype('float32')/(15**2) - costs = signal.convolve2d(I, H, mode='same', boundary='symm') - costs = abs(costs) - costs = signal.convolve2d(costs, L1, mode='same', boundary='symm') - costs = 1/costs - costs = signal.convolve2d(costs, L2, mode='same', boundary='symm') - costs[costs == np.inf] = 1 - stc.embed('tmp/'+tmp_name+'.png', costs, message, key, 'tmp/'+tmp_name+'.png') - return 'tmp/'+tmp_name+'.png' - -iface = gr.Interface(fn=HILL, - inputs=[gr.components.File(type='binary'), gr.components.Radio(['encode', 'decode']), gr.components.Textbox(), gr.components.Textbox()], - outputs=gr.components.File(), - examples=[['tmp/8825.png', 'encode', 'This is a secret message', 'secret-key'], - ['tmp/9390.png', 'encode', 'This is another secret message', 'secret-key-2']], - title=title, - description=description) -iface.launch() \ No newline at end of file diff --git a/spaces/Yntec/DreamAnything/app.py b/spaces/Yntec/DreamAnything/app.py deleted file mode 100644 index c8d7249ad493dc95d4a294a20fe09b7809292c68..0000000000000000000000000000000000000000 --- a/spaces/Yntec/DreamAnything/app.py +++ /dev/null @@ -1,230 +0,0 @@ -import gradio as gr -import os -import sys -from pathlib import Path -import random -import string -import time -from queue import Queue -from threading import Thread -import emoji - -text_gen=gr.Interface.load("spaces/phenomenon1981/MagicPrompt-Stable-Diffusion") -def get_prompts(prompt_text): - if prompt_text: - return text_gen(prompt_text + " Dream") - else: - return text_gen("") -proc1=gr.Interface.load("models/Yntec/DreamAnything") - -def restart_script_periodically(): - while True: - random_time = random.randint(5400, 6000) - time.sleep(random_time) - os.execl(sys.executable, sys.executable, *sys.argv) - - -restart_thread = Thread(target=restart_script_periodically, daemon=True) -restart_thread.start() - - -queue = Queue() -queue_threshold = 100 - -#Don't add noise to the first picture no matter what (the point of noise is to get varied outputs, the first one doesn't need to vary about anything) -def noadd_random_noise(prompt, noise_level=0.00): - if noise_level == 0: - noise_level = 0.00 - percentage_noise = noise_level * 5 - num_noise_chars = int(len(prompt) * (percentage_noise/100)) - noise_indices = random.sample(range(len(prompt)), num_noise_chars) - prompt_list = list(prompt) - noise_chars = list(string.ascii_letters + string.punctuation + '' + string.digits) - noise_chars.extend(['']) - for index in noise_indices: - prompt_list[index] = random.choice(noise_chars) - return "".join(prompt_list) - -#normal behavior -def add_random_noise(prompt, noise_level=0.00): - if noise_level == 0: - noise_level = 0.00 - percentage_noise = noise_level * 5 - num_noise_chars = int(len(prompt) * (percentage_noise/100)) - noise_indices = random.sample(range(len(prompt)), num_noise_chars) - prompt_list = list(prompt) - noise_chars = list(string.ascii_letters + string.punctuation + ' ' + string.digits) - noise_chars.extend(['😍', 'beautiful', '😂', '🤔', '😊', '🤗', '😭', '🙄', 'pretty', '🤯', '🤫', '🥴', 'sitting', '🤩', '🥳', '😔', '😩', '🤪', '😇', 'retro', '😈', '👹', 'masterpiece', '🤖', '👽', 'high quality', '🎃', '🎅', '🎄', '🎁', '🎂', '🎉', '🎈', '🎊', '🎮', '❤️', '💔', '💕', '💖', '💗', '🐶', '🐱', 'visible', '🐹', '🦊', '🐻', '🐨', '🐯', '🦁', '🐘', '🔥', '🌧️', '🌞', '🌈', '💥', '🌴', '🌊', '🌺', '🌻', '🌸', '🎨', '🌅', '🌌', '☁️', '⛈️', '❄️', '☀️', '🌤️', '⛅️', '🌥️', '🌦️', '🌧️', '🌩️', '🌨️', '🌫️', '☔️', '🌬️', '💨', '🌪️', 'cute', 'kawaii', 'little']) - for index in noise_indices: - prompt_list[index] = random.choice(noise_chars) - return "".join(prompt_list) - -def send_it1(inputs, noise_level, proc1=proc1): - prompt_with_noise = noadd_random_noise(inputs, noise_level) - while queue.qsize() >= queue_threshold: - time.sleep(2) - queue.put(prompt_with_noise) - output1 = proc1(prompt_with_noise) - return output1 - -def send_it2(inputs, noise_level, proc1=proc1): - prompt_with_noise = add_random_noise(inputs, noise_level) - while queue.qsize() >= queue_threshold: - time.sleep(2) - queue.put(prompt_with_noise) - output2 = proc1(prompt_with_noise) - return output2 - -def send_itX(inputs, noise_level, proc1=proc1): - prompt_with_noise = add_random_noise(inputs, noise_level) - while queue.qsize() >= queue_threshold: - time.sleep(2) - queue.put(prompt_with_noise) - outputX = proc1(prompt_with_noise) - return outputX - -def send_it3(inputs, noise_level, proc1=proc1): - prompt_with_noise = add_random_noise(inputs, noise_level) - while queue.qsize() >= queue_threshold: - time.sleep(2) - queue.put(prompt_with_noise) - output3 = proc1(prompt_with_noise) - return output3 - -def send_it4(inputs, noise_level, proc1=proc1): - prompt_with_noise = add_random_noise(inputs, noise_level) - while queue.qsize() >= queue_threshold: - time.sleep(2) - queue.put(prompt_with_noise) - output4 = proc1(prompt_with_noise) - return output4 - -def send_it5(inputs, noise_level, proc1=proc1): - prompt_with_noise = add_random_noise(inputs, noise_level) - while queue.qsize() >= queue_threshold: - time.sleep(2) - queue.put(prompt_with_noise) - output5 = proc1(prompt_with_noise) - return output5 - -#def send_it7(inputs, noise_level, proc1=proc1): - #prompt_with_noise = add_random_noise(inputs, noise_level) - #while queue.qsize() >= queue_threshold: - # time.sleep(2) - #queue.put(prompt_with_noise) - #output5 = proc1(prompt_with_noise) - #return output0 - - -with gr.Blocks(css='style.css') as demo: - gr.HTML( - """ -
-
- - -

DreamAnything

-
- -
-

- If you have an idea, put it on the first box to expand it, if you have a full prompt, you can leave the first box empty and just put it on the second one and click generate images! - Noise Level: Controls how much randomness is added to the input of the boxes after the first one before it is sent to the model, so you can get 6 unique 768x768 images. Higher noise level produces more diverse outputs, while lower noise level produces similar outputs, - original space created by Phenomenon1981. -

-

- ❤️ Press the Like Button if you enjoy my space! ❤️ -

-
- """ - ) - with gr.Column(elem_id="col-container"): - with gr.Row(variant="compact"): - input_text = gr.Textbox( - label="Short Prompt", - show_label=False, - max_lines=2, - placeholder="Enter a basic idea and click 'Magic Prompt'. Got no ideas? No problem, Simply just hit the magic button!", - ).style( - container=False,min_width=1200 - ) - see_prompts = gr.Button("✨Magic✨ ✨Prompt✨").style(full_width=False) - - - with gr.Row(variant="compact"): - prompt = gr.Textbox( - label="Enter your prompt", - show_label=False, - max_lines=2, - placeholder="Full Prompt", - ).style( - container=False, - ) - run = gr.Button("Generate Images").style(full_width=False) - - with gr.Row(): - with gr.Row(): - #Now that the first box generates a picture with noise=0 having the default at 0 makes no sense as it'd generate the same image 6 times. - noise_level = gr.Slider(minimum=0.2, maximum=3, step=0.1, label="Noise Level (0.1 or less was generating the same pic 6 times! 🤣)") - gr.HTML( - """ -
-
- -

Please allow up to 1 minute for each image to generate, for a total of 6 minutes max.

-
- -
-
- """ - ) - with gr.Row(): - with gr.Row(): - output1=gr.Image(label="DreamAnything",show_label=False,min_width=640) - output2=gr.Image(label="DreamAnything",show_label=False,min_width=640) - with gr.Row(): - with gr.Row(): - output3=gr.Image(label="DreamAnything",show_label=False,min_width=640) - output4=gr.Image(label="DreamAnything",show_label=False,min_width=640) - with gr.Row(): - with gr.Row(): - output5=gr.Image(label="DreamAnything",show_label=False,min_width=640) - outputX=gr.Image(label="DreamAnything",show_label=False,min_width=640) - #with gr.Row(): - #with gr.Row(): - #output0=gr.Image(label="DreamAnything",show_label=False,min_width=640) - - see_prompts.click(get_prompts, inputs=[input_text], outputs=[prompt], queue=False) - run.click(send_it1, inputs=[prompt, noise_level], outputs=[output1]) - #run.click(send_it7, inputs=[prompt, noise_level], outputs=[output0]) - run.click(send_it2, inputs=[prompt, noise_level], outputs=[output2]) - run.click(send_it3, inputs=[prompt, noise_level], outputs=[output3]) - run.click(send_it4, inputs=[prompt, noise_level], outputs=[output4]) - run.click(send_it5, inputs=[prompt, noise_level], outputs=[output5]) - run.click(send_itX, inputs=[prompt, noise_level], outputs=[outputX]) - - - with gr.Row(): - gr.HTML( - """ - -
-

Unleash your creative side and generate mesmerizing images with just a few clicks! Enter a spark of inspiration in the "Basic Idea" text box and click the "Magic Prompt" button to elevate it to a polished masterpiece. Make any final tweaks in the "Full Prompt" box and hit the "Generate Images" button to watch your vision come to life. Experiment with the "Noise Level" for a diverse range of outputs, from similar to wildly unique. Let the fun begin! -

-
- """ -) - - demo.launch(enable_queue=True, inline=True) - block.queue(concurrency_count=100) diff --git a/spaces/Yuliang/ECON/lib/pixielib/models/FLAME.py b/spaces/Yuliang/ECON/lib/pixielib/models/FLAME.py deleted file mode 100644 index fb9ca09c4890f17206905546f4373ab186a5e6d1..0000000000000000000000000000000000000000 --- a/spaces/Yuliang/ECON/lib/pixielib/models/FLAME.py +++ /dev/null @@ -1,107 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is -# holder of all proprietary rights on this computer program. -# Using this computer program means that you agree to the terms -# in the LICENSE file included with this software distribution. -# Any use not explicitly granted by the LICENSE is prohibited. -# -# Copyright©2019 Max-Planck-Gesellschaft zur Förderung -# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute -# for Intelligent Systems. All rights reserved. -# -# For comments or questions, please email us at pixie@tue.mpg.de -# For commercial licensing contact, please contact ps-license@tuebingen.mpg.de - -import pickle - -import numpy as np -import torch -import torch.nn as nn -import torch.nn.functional as F - - -class FLAMETex(nn.Module): - """ - FLAME texture: - https://github.com/TimoBolkart/TF_FLAME/blob/ade0ab152300ec5f0e8555d6765411555c5ed43d/sample_texture.py#L64 - FLAME texture converted from BFM: - https://github.com/TimoBolkart/BFM_to_FLAME - """ - def __init__(self, config): - super(FLAMETex, self).__init__() - if config.tex_type == "BFM": - mu_key = "MU" - pc_key = "PC" - n_pc = 199 - tex_path = config.tex_path - tex_space = np.load(tex_path) - texture_mean = tex_space[mu_key].reshape(1, -1) - texture_basis = tex_space[pc_key].reshape(-1, n_pc) - - elif config.tex_type == "FLAME": - mu_key = "mean" - pc_key = "tex_dir" - n_pc = 200 - tex_path = config.flame_tex_path - tex_space = np.load(tex_path) - texture_mean = tex_space[mu_key].reshape(1, -1) / 255.0 - texture_basis = tex_space[pc_key].reshape(-1, n_pc) / 255.0 - else: - print("texture type ", config.tex_type, "not exist!") - raise NotImplementedError - - n_tex = config.n_tex - num_components = texture_basis.shape[1] - texture_mean = torch.from_numpy(texture_mean).float()[None, ...] - texture_basis = torch.from_numpy(texture_basis[:, :n_tex]).float()[None, ...] - self.register_buffer("texture_mean", texture_mean) - self.register_buffer("texture_basis", texture_basis) - - def forward(self, texcode=None): - """ - texcode: [batchsize, n_tex] - texture: [bz, 3, 256, 256], range: 0-1 - """ - texture = self.texture_mean + (self.texture_basis * texcode[:, None, :]).sum(-1) - texture = texture.reshape(texcode.shape[0], 512, 512, 3).permute(0, 3, 1, 2) - texture = F.interpolate(texture, [256, 256]) - texture = texture[:, [2, 1, 0], :, :] - return texture - - -def texture_flame2smplx(cached_data, flame_texture, smplx_texture): - """Convert flame texture map (face-only) into smplx texture map (includes body texture) - TODO: pytorch version ==> grid sample - """ - if smplx_texture.shape[0] != smplx_texture.shape[1]: - print("SMPL-X texture not squared (%d != %d)" % (smplx_texture[0], smplx_texture[1])) - return - if smplx_texture.shape[0] != cached_data["target_resolution"]: - print( - "SMPL-X texture size does not match cached image resolution (%d != %d)" % - (smplx_texture.shape[0], cached_data["target_resolution"]) - ) - return - x_coords = cached_data["x_coords"] - y_coords = cached_data["y_coords"] - target_pixel_ids = cached_data["target_pixel_ids"] - source_uv_points = cached_data["source_uv_points"] - - source_tex_coords = np.zeros_like((source_uv_points)).astype(int) - source_tex_coords[:, 0] = np.clip( - flame_texture.shape[0] * (1.0 - source_uv_points[:, 1]), - 0.0, - flame_texture.shape[0], - ).astype(int) - source_tex_coords[:, 1] = np.clip( - flame_texture.shape[1] * (source_uv_points[:, 0]), 0.0, flame_texture.shape[1] - ).astype(int) - - smplx_texture[y_coords[target_pixel_ids].astype(int), - x_coords[target_pixel_ids].astype(int), :, ] = flame_texture[source_tex_coords[:, - 0], - source_tex_coords[:, - 1]] - - return smplx_texture diff --git a/spaces/Zengwengen/nb/README.md b/spaces/Zengwengen/nb/README.md deleted file mode 100644 index 7aa73b96193a8b426d961a1418e4a18a38e05b06..0000000000000000000000000000000000000000 --- a/spaces/Zengwengen/nb/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Nb -emoji: 📊 -colorFrom: yellow -colorTo: purple -sdk: docker -pinned: false -license: mit -app_port: 8080 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/abdvl/datahub_qa_bot/docs/actions/guides/developing-an-action.md b/spaces/abdvl/datahub_qa_bot/docs/actions/guides/developing-an-action.md deleted file mode 100644 index a8b47954a7876b976cbcefbcc8258cbc8a625f7c..0000000000000000000000000000000000000000 --- a/spaces/abdvl/datahub_qa_bot/docs/actions/guides/developing-an-action.md +++ /dev/null @@ -1,132 +0,0 @@ -# Developing an Action - -In this guide, we will outline each step to developing a Action for the DataHub Actions Framework. - -## Overview - -Developing a DataHub Action is a matter of extending the `Action` base class in Python, installing your -Action to make it visible to the framework, and then configuring the framework to use the new Action. - - -## Step 1: Defining an Action - -To implement an Action, we'll need to extend the `Action` base class and override the following functions: - -- `create()` - This function is invoked to instantiate the action, with a free-form configuration dictionary - extracted from the Actions configuration file as input. -- `act()` - This function is invoked when an Action is received. It should contain the core logic of the Action. -- `close()` - This function is invoked when the framework has issued a shutdown of the pipeline. It should be used - to cleanup any processes happening inside the Action. - -Let's start by defining a new implementation of Action called `CustomAction`. We'll keep it simple-- this Action will -print the configuration that is provided when it is created, and print any Events that it receives. - -```python -# custom_action.py -from datahub_actions.action.action import Action -from datahub_actions.event.event_envelope import EventEnvelope -from datahub_actions.pipeline.pipeline_context import PipelineContext - -class CustomAction(Action): - @classmethod - def create(cls, config_dict: dict, ctx: PipelineContext) -> "Action": - # Simply print the config_dict. - print(config_dict) - return cls(ctx) - - def __init__(self, ctx: PipelineContext): - self.ctx = ctx - - def act(self, event: EventEnvelope) -> None: - # Do something super important. - # For now, just print. :) - print(event) - - def close(self) -> None: - pass -``` - - -## Step 2: Installing the Action - -Now that we've defined the Action, we need to make it visible to the framework by making it -available in the Python runtime environment. - -The easiest way to do this is to just place it in the same directory as your configuration file, in which case the module name is the same as the file -name - in this case it will be `custom_action`. - -### Advanced: Installing as a Package - -Alternatively, create a `setup.py` file in the same directory as the new Action to convert it into a package that pip can understand. - -``` -from setuptools import find_packages, setup - -setup( - name="custom_action_example", - version="1.0", - packages=find_packages(), - # if you don't already have DataHub Actions installed, add it under install_requires - # install_requires=["acryl-datahub-actions"] -) -``` - -Next, install the package - -```shell -pip install -e . -``` - -inside the module. (alt.`python setup.py`). - -Once we have done this, our class will be referencable via `custom_action_example.custom_action:CustomAction`. - - -## Step 3: Running the Action - -Now that we've defined our Action, we can create an Action configuration file that refers to the new Action. -We will need to provide the fully-qualified Python module & class name when doing so. - -*Example Configuration* - -```yaml -# custom_action.yaml -name: "custom_action_test" -source: - type: "kafka" - config: - connection: - bootstrap: ${KAFKA_BOOTSTRAP_SERVER:-localhost:9092} - schema_registry_url: ${SCHEMA_REGISTRY_URL:-http://localhost:8081} -action: - type: "custom_action_example.custom_action:CustomAction" - config: - # Some sample configuration which should be printed on create. - config1: value1 -``` - -Next, run the `datahub actions` command as usual: - -```shell -datahub actions -c custom_action.yaml -``` - -If all is well, your Action should now be receiving & printing Events. - - -## (Optional) Step 4: Contributing the Action - -If your Action is generally applicable, you can raise a PR to include it in the core Action library -provided by DataHub. All Actions will live under the `datahub_actions/plugin/action` directory inside the -[datahub-actions](https://github.com/acryldata/datahub-actions) repository. - -Once you've added your new Action there, make sure that you make it discoverable by updating the `entry_points` section -of the `setup.py` file. This allows you to assign a globally unique name for you Action, so that people can use -it without defining the full module path. - -### Prerequisites: - -Prerequisites to consideration for inclusion in the core Actions library include - -- **Testing** Define unit tests for your Action -- **Deduplication** Confirm that no existing Action serves the same purpose, or can be easily extended to serve the same purpose diff --git a/spaces/abdvl/datahub_qa_bot/docs/managed-datahub/datahub-api/graphql-api/getting-started.md b/spaces/abdvl/datahub_qa_bot/docs/managed-datahub/datahub-api/graphql-api/getting-started.md deleted file mode 100644 index 3c57b0a21d96e43a4d3943246f50725885619356..0000000000000000000000000000000000000000 --- a/spaces/abdvl/datahub_qa_bot/docs/managed-datahub/datahub-api/graphql-api/getting-started.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -description: Getting started with the DataHub GraphQL API. ---- - -# Getting Started - -The Acryl DataHub GraphQL API is an extension of the open source [DataHub GraphQL API.](docs/api/graphql/overview.md) - -For a full reference to the Queries & Mutations available for consumption, check out [Queries](graphql/queries.md) & [Mutations](graphql/mutations.md). - -### Connecting to the API - -![](../../imgs/saas/image-(3).png) - -When you generate the token you will see an example of `curl` command which you can use to connect to the GraphQL API. - -Note that there is a single URL mentioned there but it can be any of these - -- https://`your-account`.acryl.io/api/graphql -- https://`your-account`.acryl.io/api/gms/graphql - -If there is any example that requires you to connect to GMS then you can use the second URL and change the endpoints. - -e.g. to get configuration of your GMS server you can use - -``` -curl -X GET 'https://your-account.acryl.io/api/gms/config' --header -``` - -e.g. to connect to ingestion endpoint for doing ingestion programmatically you can use the below URL - -- https://your-account.acryl.io/api/gms/aspects?action=ingestProposal - -### Exploring the API - -The entire GraphQL API can be explored & [introspected](https://graphql.org/learn/introspection/) using GraphiQL, an interactive query tool which allows you to navigate the entire Acryl GraphQL schema as well as craft & issue using an intuitive UI. - -[GraphiQL](https://www.gatsbyjs.com/docs/how-to/querying-data/running-queries-with-graphiql/) is available for each Acryl DataHub deployment, locating at `https://your-account.acryl.io/api/graphiql`. - -### Querying the API - -Currently, we do not offer language-specific SDKs for accessing the DataHub GraphQL API. For querying the API, you can make use of a variety of per-language client libraries. For a full list, see [GraphQL Code Libraries, Tools, & Services](https://graphql.org/code/). diff --git a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet_null/models/necks/__init__.py b/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet_null/models/necks/__init__.py deleted file mode 100644 index 02f833a8a0f538a8c06fef622d1cadc1a1b66ea2..0000000000000000000000000000000000000000 --- a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet_null/models/necks/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -from .bfp import BFP -from .channel_mapper import ChannelMapper -from .fpg import FPG -from .fpn import FPN -from .fpn_carafe import FPN_CARAFE -from .hrfpn import HRFPN -from .nas_fpn import NASFPN -from .nasfcos_fpn import NASFCOS_FPN -from .pafpn import PAFPN -from .rfp import RFP -from .yolo_neck import YOLOV3Neck - -__all__ = [ - 'FPN', 'BFP', 'ChannelMapper', 'HRFPN', 'NASFPN', 'FPN_CARAFE', 'PAFPN', - 'NASFCOS_FPN', 'RFP', 'YOLOV3Neck', 'FPG' -] diff --git a/spaces/abidlabs/streaming-asr/README.md b/spaces/abidlabs/streaming-asr/README.md deleted file mode 100644 index 5d8fb4eb0033d3a11f759b8decfc62669adcc224..0000000000000000000000000000000000000000 --- a/spaces/abidlabs/streaming-asr/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Streaming Asr -emoji: 🐢 -colorFrom: pink -colorTo: green -sdk: gradio -sdk_version: 3.21.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference diff --git a/spaces/akashagarwal/ASRGenerateStory/README.md b/spaces/akashagarwal/ASRGenerateStory/README.md deleted file mode 100644 index 4fac87b15d3c6a8f83581d798b385d0db99620e7..0000000000000000000000000000000000000000 --- a/spaces/akashagarwal/ASRGenerateStory/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: ASRGenerateStory -emoji: 🐢 -colorFrom: red -colorTo: gray -sdk: gradio -sdk_version: 3.0.24 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference - diff --git a/spaces/akhaliq/deeplab2/model/layers/axial_block_groups_test.py b/spaces/akhaliq/deeplab2/model/layers/axial_block_groups_test.py deleted file mode 100644 index b1283bc2f2623035e5b8374ade1974db6d474141..0000000000000000000000000000000000000000 --- a/spaces/akhaliq/deeplab2/model/layers/axial_block_groups_test.py +++ /dev/null @@ -1,182 +0,0 @@ -# coding=utf-8 -# Copyright 2021 The Deeplab2 Authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tests for axial_block_groups.""" - -import numpy as np -import tensorflow as tf - -from deeplab2.model import test_utils -from deeplab2.model.layers import axial_block_groups - - -class AxialBlockGroupsTest(tf.test.TestCase): - - def test_axial_attention_follows_bottleneck_block(self): - layer = axial_block_groups.BlockGroup( - filters=512, - num_blocks=2, - name='block_group', - original_resnet_stride=2, - original_resnet_input_stride=16, - use_axial_beyond_stride=32, - output_stride=16) - _, pixel_output, memory_output = layer((tf.zeros([2, 65, 65, 1024]), - tf.zeros([2, 128, 147]))) - self.assertListEqual(pixel_output.get_shape().as_list(), - [2, 65, 65, 2048]) - self.assertListEqual(memory_output.get_shape().as_list(), - [2, 128, 147]) - - def test_global_attention_follows_basic_block(self): - layer = axial_block_groups.BlockGroup( - filters=256, - num_blocks=2, - name='block_group', - backbone_type='wider_resnet', - original_resnet_stride=2, - original_resnet_input_stride=8, - use_global_beyond_stride=16, - positional_encoding_type='1D') - - _, pixel_output, memory_output = layer((tf.zeros([2, 65, 65, 32]), - tf.zeros([2, 128, 147]))) - self.assertListEqual(pixel_output.get_shape().as_list(), - [2, 33, 33, 1024]) - self.assertListEqual(memory_output.get_shape().as_list(), - [2, 128, 147]) - - def test_atrous_consistency_basic_block(self): - tf.random.set_seed(0) - pixel_inputs = test_utils.create_test_input(2, 11, 11, 3) - # Dense feature extraction followed by subsampling. - layer1 = axial_block_groups.BlockGroup( - filters=2, - num_blocks=2, - name='stage3', - backbone_type='wider_resnet', - original_resnet_stride=2, - original_resnet_input_stride=8, - output_stride=8, - use_axial_beyond_stride=0, - use_global_beyond_stride=0, - use_transformer_beyond_stride=0) - # Create the weights - layer1((pixel_inputs, None)) - weights = layer1.get_weights() - # Set the batch norm gamma as non-zero so that the 3x3 convolution affects - # the output. - for index in range(len(weights)): - if np.sum(weights[index]) == 0.0: - weights[index] = weights[index] + 1 - layer1.set_weights(weights) - _, pixel_outputs, _ = layer1((pixel_inputs, None)) - output = pixel_outputs[:, ::2, ::2, :] - # Feature extraction at the nominal network rate. - layer2 = axial_block_groups.BlockGroup( - filters=2, - num_blocks=2, - name='stage3', - backbone_type='wider_resnet', - original_resnet_stride=2, - original_resnet_input_stride=8, - output_stride=16, - use_axial_beyond_stride=0, - use_global_beyond_stride=0, - use_transformer_beyond_stride=0) - # Create the weights - layer2((pixel_inputs, None)) - # Make the two networks use the same weights. - layer2.set_weights(layer1.get_weights()) - _, expected, _ = layer2((pixel_inputs, None)) - self.assertAllClose(output, expected, atol=1e-4, rtol=1e-4) - - def test_atrous_consistency_bottleneck_block(self): - tf.random.set_seed(0) - pixel_inputs = test_utils.create_test_input(2, 11, 11, 3) - # Dense feature extraction followed by subsampling. - layer1 = axial_block_groups.BlockGroup( - filters=2, - num_blocks=2, - name='stage3', - backbone_type='wider_resnet', - original_resnet_stride=2, - original_resnet_input_stride=16, - output_stride=16, - use_axial_beyond_stride=0, - use_global_beyond_stride=0, - use_transformer_beyond_stride=0) - # Create the weights - layer1((pixel_inputs, None)) - weights = layer1.get_weights() - # Set the batch norm gamma as non-zero so that the 3x3 convolution affects - # the output. - for index in range(len(weights)): - if np.sum(weights[index]) == 0.0: - weights[index] = weights[index] + 1 - layer1.set_weights(weights) - _, pixel_outputs, _ = layer1((pixel_inputs, None)) - output = pixel_outputs[:, ::2, ::2, :] - # Feature extraction at the nominal network rate. - layer2 = axial_block_groups.BlockGroup( - filters=2, - num_blocks=2, - name='stage3', - backbone_type='wider_resnet', - original_resnet_stride=2, - original_resnet_input_stride=16, - output_stride=32, - use_axial_beyond_stride=0, - use_global_beyond_stride=0, - use_transformer_beyond_stride=0) - # Create the weights - layer2((pixel_inputs, None)) - # Make the two networks use the same weights. - layer2.set_weights(layer1.get_weights()) - _, expected, _ = layer2((pixel_inputs, None)) - self.assertAllClose(output, expected, atol=1e-4, rtol=1e-4) - - def test_use_se_sac_recompute_drop_path_schedule(self): - _ = axial_block_groups.BlockGroup( - filters=512, - num_blocks=2, - name='block_group', - original_resnet_stride=2, - original_resnet_input_stride=8, - use_axial_beyond_stride=0, - use_squeeze_and_excite=True, # True - use_sac_beyond_stride=16, # True - recompute_within_stride=16, # True - drop_path_beyond_stride=16, - drop_path_schedule='linear', # 1.0, 0.85 - output_stride=16) - - def test_nouse_se_sac_recompute_drop_path_schedule(self): - _ = axial_block_groups.BlockGroup( - filters=512, - num_blocks=2, - name='block_group', - original_resnet_stride=2, - original_resnet_input_stride=8, - use_axial_beyond_stride=0, - use_squeeze_and_excite=False, # False - use_sac_beyond_stride=32, # False - recompute_within_stride=8, # False - drop_path_beyond_stride=32, # 1.0, 1.0 - drop_path_schedule='constant', - output_stride=16) - -if __name__ == '__main__': - tf.test.main() diff --git a/spaces/alexrods/Smartcity-Traffic-Detection/centroidtracker.py b/spaces/alexrods/Smartcity-Traffic-Detection/centroidtracker.py deleted file mode 100644 index 3b89b0a3627f8d71bfd0f7f5f1ef1c9b73142856..0000000000000000000000000000000000000000 --- a/spaces/alexrods/Smartcity-Traffic-Detection/centroidtracker.py +++ /dev/null @@ -1,163 +0,0 @@ -# import the necessary packages -from scipy.spatial import distance as dist -from collections import OrderedDict -import numpy as np - -class CentroidTracker: - def __init__(self, maxDisappeared=50, maxDistance=50): - # initialize the next unique object ID along with two ordered - # dictionaries used to keep track of mapping a given object - # ID to its centroid and number of consecutive frames it has - # been marked as "disappeared", respectively - self.nextObjectID = 0 - self.objects = OrderedDict() - self.disappeared = OrderedDict() - - # store the number of maximum consecutive frames a given - # object is allowed to be marked as "disappeared" until we - # need to deregister the object from tracking - self.maxDisappeared = maxDisappeared - - # store the maximum distance between centroids to associate - # an object -- if the distance is larger than this maximum - # distance we'll start to mark the object as "disappeared" - self.maxDistance = maxDistance - - def register(self, centroid): - # when registering an object we use the next available object - # ID to store the centroid - self.objects[self.nextObjectID] = centroid - self.disappeared[self.nextObjectID] = 0 - self.nextObjectID += 1 - - def deregister(self, objectID): - # to deregister an object ID we delete the object ID from - # both of our respective dictionaries - del self.objects[objectID] - del self.disappeared[objectID] - - def update(self, rects): - # check to see if the list of input bounding box rectangles - # is empty - if len(rects) == 0: - # loop over any existing tracked objects and mark them - # as disappeared - for objectID in list(self.disappeared.keys()): - self.disappeared[objectID] += 1 - - # if we have reached a maximum number of consecutive - # frames where a given object has been marked as - # missing, deregister it - if self.disappeared[objectID] > self.maxDisappeared: - self.deregister(objectID) - - # return early as there are no centroids or tracking info - # to update - return self.objects - - # initialize an array of input centroids for the current frame - inputCentroids = np.zeros((len(rects), 2), dtype="int") - - # loop over the bounding box rectangles - for (i, (startX, startY, endX, endY)) in enumerate(rects): - # use the bounding box coordinates to derive the centroid - cX = int((startX + endX) / 2.0) - cY = int((startY + endY) / 2.0) - inputCentroids[i] = (cX, cY) - - # if we are currently not tracking any objects take the input - # centroids and register each of them - if len(self.objects) == 0: - for i in range(0, len(inputCentroids)): - self.register(inputCentroids[i]) - - # otherwise, are are currently tracking objects so we need to - # try to match the input centroids to existing object - # centroids - else: - # grab the set of object IDs and corresponding centroids - objectIDs = list(self.objects.keys()) - objectCentroids = list(self.objects.values()) - - # compute the distance between each pair of object - # centroids and input centroids, respectively -- our - # goal will be to match an input centroid to an existing - # object centroid - D = dist.cdist(np.array(objectCentroids), inputCentroids) - - # in order to perform this matching we must (1) find the - # smallest value in each row and then (2) sort the row - # indexes based on their minimum values so that the row - # with the smallest value as at the *front* of the index - # list - rows = D.min(axis=1).argsort() - - # next, we perform a similar process on the columns by - # finding the smallest value in each column and then - # sorting using the previously computed row index list - cols = D.argmin(axis=1)[rows] - - # in order to determine if we need to update, register, - # or deregister an object we need to keep track of which - # of the rows and column indexes we have already examined - usedRows = set() - usedCols = set() - - # loop over the combination of the (row, column) index - # tuples - for (row, col) in zip(rows, cols): - # if we have already examined either the row or - # column value before, ignore it - if row in usedRows or col in usedCols: - continue - - # if the distance between centroids is greater than - # the maximum distance, do not associate the two - # centroids to the same object - if D[row, col] > self.maxDistance: - continue - - # otherwise, grab the object ID for the current row, - # set its new centroid, and reset the disappeared - # counter - objectID = objectIDs[row] - self.objects[objectID] = inputCentroids[col] - self.disappeared[objectID] = 0 - - # indicate that we have examined each of the row and - # column indexes, respectively - usedRows.add(row) - usedCols.add(col) - - # compute both the row and column index we have NOT yet - # examined - unusedRows = set(range(0, D.shape[0])).difference(usedRows) - unusedCols = set(range(0, D.shape[1])).difference(usedCols) - - # in the event that the number of object centroids is - # equal or greater than the number of input centroids - # we need to check and see if some of these objects have - # potentially disappeared - if D.shape[0] >= D.shape[1]: - # loop over the unused row indexes - for row in unusedRows: - # grab the object ID for the corresponding row - # index and increment the disappeared counter - objectID = objectIDs[row] - self.disappeared[objectID] += 1 - - # check to see if the number of consecutive - # frames the object has been marked "disappeared" - # for warrants deregistering the object - if self.disappeared[objectID] > self.maxDisappeared: - self.deregister(objectID) - - # otherwise, if the number of input centroids is greater - # than the number of existing object centroids we need to - # register each new input centroid as a trackable object - else: - for col in unusedCols: - self.register(inputCentroids[col]) - - # return the set of trackable objects - return self.objects \ No newline at end of file diff --git a/spaces/ali-ghamdan/deoldify/fastai/script.py b/spaces/ali-ghamdan/deoldify/fastai/script.py deleted file mode 100644 index c66c6b9992cd0c2a5e20fd97819bc34f9e1435b8..0000000000000000000000000000000000000000 --- a/spaces/ali-ghamdan/deoldify/fastai/script.py +++ /dev/null @@ -1,51 +0,0 @@ -import os, sys, subprocess, inspect -from dataclasses import dataclass -from typing import Any -from argparse import ArgumentParser - - -@dataclass -class Param(): - "A parameter in a function used in `anno_parser` or `call_parse`" - help:str=None - type:type=None - opt:bool=True - action:str=None - nargs:str=None - const:str=None - choices:str=None - required:bool=None - - @property - def pre(self): return '--' if self.opt else '' - @property - def kwargs(self): return {k:v for k,v in self.__dict__.items() - if v is not None and k!='opt'} - -def anno_parser(func): - "Look at params (annotated with `Param`) in func and return an `ArgumentParser`" - p = ArgumentParser(description=func.__doc__) - for k,v in inspect.signature(func).parameters.items(): - param = func.__annotations__.get(k, Param()) - kwargs = param.kwargs - if v.default != inspect.Parameter.empty: kwargs['default'] = v.default - p.add_argument(f"{param.pre}{k}", **kwargs) - return p - -def call_parse(func): - "Decorator to create a simple CLI from `func` using `anno_parser`" - name = inspect.currentframe().f_back.f_globals['__name__'] - if name == "__main__": - args = anno_parser(func).parse_args() - func(**args.__dict__) - else: return func - -def call_plac(f): - "Decorator to create a simple CLI from `func` using `plac`" - name = inspect.currentframe().f_back.f_globals['__name__'] - if name == '__main__': - import plac - res = plac.call(f) - if callable(res): res() - else: return f - diff --git a/spaces/ali-ghamdan/deoldify/fastai/utils/show_install.py b/spaces/ali-ghamdan/deoldify/fastai/utils/show_install.py deleted file mode 100644 index b9e6cc3be84ed684ec6984b1a7cfe7b673a72c8d..0000000000000000000000000000000000000000 --- a/spaces/ali-ghamdan/deoldify/fastai/utils/show_install.py +++ /dev/null @@ -1,8 +0,0 @@ -from ..script import * -from .collect_env import * - -# Temporary POC for module-based script -@call_parse -def main(show_nvidia_smi:Param(opt=False, nargs='?', type=bool)=False): - return show_install(show_nvidia_smi) - diff --git a/spaces/ali-ghamdan/realesrgan-models/tests/test_model.py b/spaces/ali-ghamdan/realesrgan-models/tests/test_model.py deleted file mode 100644 index c20bb1d56ed20222e929e9c94026f6ea383c6026..0000000000000000000000000000000000000000 --- a/spaces/ali-ghamdan/realesrgan-models/tests/test_model.py +++ /dev/null @@ -1,126 +0,0 @@ -import torch -import yaml -from basicsr.archs.rrdbnet_arch import RRDBNet -from basicsr.data.paired_image_dataset import PairedImageDataset -from basicsr.losses.losses import GANLoss, L1Loss, PerceptualLoss - -from realesrgan.archs.discriminator_arch import UNetDiscriminatorSN -from realesrgan.models.realesrgan_model import RealESRGANModel -from realesrgan.models.realesrnet_model import RealESRNetModel - - -def test_realesrnet_model(): - with open('tests/data/test_realesrnet_model.yml', mode='r') as f: - opt = yaml.load(f, Loader=yaml.FullLoader) - - # build model - model = RealESRNetModel(opt) - # test attributes - assert model.__class__.__name__ == 'RealESRNetModel' - assert isinstance(model.net_g, RRDBNet) - assert isinstance(model.cri_pix, L1Loss) - assert isinstance(model.optimizers[0], torch.optim.Adam) - - # prepare data - gt = torch.rand((1, 3, 32, 32), dtype=torch.float32) - kernel1 = torch.rand((1, 5, 5), dtype=torch.float32) - kernel2 = torch.rand((1, 5, 5), dtype=torch.float32) - sinc_kernel = torch.rand((1, 5, 5), dtype=torch.float32) - data = dict(gt=gt, kernel1=kernel1, kernel2=kernel2, sinc_kernel=sinc_kernel) - model.feed_data(data) - # check dequeue - model.feed_data(data) - # check data shape - assert model.lq.shape == (1, 3, 8, 8) - assert model.gt.shape == (1, 3, 32, 32) - - # change probability to test if-else - model.opt['gaussian_noise_prob'] = 0 - model.opt['gray_noise_prob'] = 0 - model.opt['second_blur_prob'] = 0 - model.opt['gaussian_noise_prob2'] = 0 - model.opt['gray_noise_prob2'] = 0 - model.feed_data(data) - # check data shape - assert model.lq.shape == (1, 3, 8, 8) - assert model.gt.shape == (1, 3, 32, 32) - - # ----------------- test nondist_validation -------------------- # - # construct dataloader - dataset_opt = dict( - name='Demo', - dataroot_gt='tests/data/gt', - dataroot_lq='tests/data/lq', - io_backend=dict(type='disk'), - scale=4, - phase='val') - dataset = PairedImageDataset(dataset_opt) - dataloader = torch.utils.data.DataLoader(dataset=dataset, batch_size=1, shuffle=False, num_workers=0) - assert model.is_train is True - model.nondist_validation(dataloader, 1, None, False) - assert model.is_train is True - - -def test_realesrgan_model(): - with open('tests/data/test_realesrgan_model.yml', mode='r') as f: - opt = yaml.load(f, Loader=yaml.FullLoader) - - # build model - model = RealESRGANModel(opt) - # test attributes - assert model.__class__.__name__ == 'RealESRGANModel' - assert isinstance(model.net_g, RRDBNet) # generator - assert isinstance(model.net_d, UNetDiscriminatorSN) # discriminator - assert isinstance(model.cri_pix, L1Loss) - assert isinstance(model.cri_perceptual, PerceptualLoss) - assert isinstance(model.cri_gan, GANLoss) - assert isinstance(model.optimizers[0], torch.optim.Adam) - assert isinstance(model.optimizers[1], torch.optim.Adam) - - # prepare data - gt = torch.rand((1, 3, 32, 32), dtype=torch.float32) - kernel1 = torch.rand((1, 5, 5), dtype=torch.float32) - kernel2 = torch.rand((1, 5, 5), dtype=torch.float32) - sinc_kernel = torch.rand((1, 5, 5), dtype=torch.float32) - data = dict(gt=gt, kernel1=kernel1, kernel2=kernel2, sinc_kernel=sinc_kernel) - model.feed_data(data) - # check dequeue - model.feed_data(data) - # check data shape - assert model.lq.shape == (1, 3, 8, 8) - assert model.gt.shape == (1, 3, 32, 32) - - # change probability to test if-else - model.opt['gaussian_noise_prob'] = 0 - model.opt['gray_noise_prob'] = 0 - model.opt['second_blur_prob'] = 0 - model.opt['gaussian_noise_prob2'] = 0 - model.opt['gray_noise_prob2'] = 0 - model.feed_data(data) - # check data shape - assert model.lq.shape == (1, 3, 8, 8) - assert model.gt.shape == (1, 3, 32, 32) - - # ----------------- test nondist_validation -------------------- # - # construct dataloader - dataset_opt = dict( - name='Demo', - dataroot_gt='tests/data/gt', - dataroot_lq='tests/data/lq', - io_backend=dict(type='disk'), - scale=4, - phase='val') - dataset = PairedImageDataset(dataset_opt) - dataloader = torch.utils.data.DataLoader(dataset=dataset, batch_size=1, shuffle=False, num_workers=0) - assert model.is_train is True - model.nondist_validation(dataloader, 1, None, False) - assert model.is_train is True - - # ----------------- test optimize_parameters -------------------- # - model.feed_data(data) - model.optimize_parameters(1) - assert model.output.shape == (1, 3, 32, 32) - assert isinstance(model.log_dict, dict) - # check returned keys - expected_keys = ['l_g_pix', 'l_g_percep', 'l_g_gan', 'l_d_real', 'out_d_real', 'l_d_fake', 'out_d_fake'] - assert set(expected_keys).issubset(set(model.log_dict.keys())) diff --git a/spaces/allknowingroger/Image-Models-Test131/README.md b/spaces/allknowingroger/Image-Models-Test131/README.md deleted file mode 100644 index a77e6ec0a97abeffb4689a3fc6da9bfab7bcf6fb..0000000000000000000000000000000000000000 --- a/spaces/allknowingroger/Image-Models-Test131/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: More Image Models -emoji: 😻 -colorFrom: red -colorTo: gray -sdk: gradio -sdk_version: 3.23.0 -app_file: app.py -duplicated_from: allknowingroger/Image-Models-Test130 ---- - - \ No newline at end of file diff --git a/spaces/amarchheda/ChordDuplicate/portaudio/cmake_support/FindJack.cmake b/spaces/amarchheda/ChordDuplicate/portaudio/cmake_support/FindJack.cmake deleted file mode 100644 index 96e0b501b6c6c053a7a96f80b744ac3c1c8c68b2..0000000000000000000000000000000000000000 --- a/spaces/amarchheda/ChordDuplicate/portaudio/cmake_support/FindJack.cmake +++ /dev/null @@ -1,41 +0,0 @@ -# - Try to find jack -# Once done this will define -# JACK_FOUND - System has jack -# JACK_INCLUDE_DIRS - The jack include directories -# JACK_LIBRARIES - The libraries needed to use jack -# JACK_DEFINITIONS - Compiler switches required for using jack - -if (JACK_LIBRARIES AND JACK_INCLUDE_DIRS) - - # in cache already - set(JACK_FOUND TRUE) - -else (JACK_LIBRARIES AND JACK_INCLUDE_DIRS) - - set(JACK_DEFINITIONS "") - - # Look for pkg-config and use it (if available) to find package - find_package(PkgConfig QUIET) - if (PKG_CONFIG_FOUND) - pkg_search_module(JACK QUIET jack) - endif (PKG_CONFIG_FOUND) - - if (NOT JACK_FOUND) - - find_path(JACK_INCLUDE_DIR jack/jack.h HINTS ${JACK_INCLUDEDIR} ${JACK_INCLUDE_DIRS} PATH_SUFFIXES jack) - find_library(JACK_LIBRARY NAMES jack HINTS ${JACK_LIBDIR} ${JACK_LIBRARY_DIRS}) - - set(JACK_LIBRARIES ${JACK_LIBRARY}) - set(JACK_INCLUDE_DIRS ${JACK_INCLUDE_DIR}) - - include(FindPackageHandleStandardArgs) - - # Set JACK_FOUND if the library and include paths were found - find_package_handle_standard_args(jack DEFAULT_MSG JACK_LIBRARY JACK_INCLUDE_DIR) - - # Don't show include/library paths in cmake GUI - mark_as_advanced(JACK_INCLUDE_DIR JACK_LIBRARY) - - endif (NOT JACK_FOUND) - -endif (JACK_LIBRARIES AND JACK_INCLUDE_DIRS) diff --git a/spaces/anton-l/youtube-subs-wav2vec/app.py b/spaces/anton-l/youtube-subs-wav2vec/app.py deleted file mode 100644 index 83cac746296c491fd6385912fbcd760ae13292a1..0000000000000000000000000000000000000000 --- a/spaces/anton-l/youtube-subs-wav2vec/app.py +++ /dev/null @@ -1,107 +0,0 @@ -from collections import deque - -import streamlit as st -import torch -from streamlit_player import st_player -from transformers import AutoModelForCTC, Wav2Vec2Processor - -from streaming import ffmpeg_stream - -device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') -player_options = { - "events": ["onProgress"], - "progress_interval": 200, - "volume": 1.0, - "playing": True, - "loop": False, - "controls": False, - "muted": False, - "config": {"youtube": {"playerVars": {"start": 1}}}, -} - -# disable rapid fading in and out on `st.code` updates -st.markdown("", unsafe_allow_html=True) - -@st.cache(hash_funcs={torch.nn.parameter.Parameter: lambda _: None}) -def load_model(model_path="facebook/wav2vec2-large-robust-ft-swbd-300h"): - processor = Wav2Vec2Processor.from_pretrained(model_path) - model = AutoModelForCTC.from_pretrained(model_path).to(device) - return processor, model - - -processor, model = load_model() - - -def stream_text(url, chunk_duration_ms, pad_duration_ms): - sampling_rate = processor.feature_extractor.sampling_rate - - # calculate the length of logits to cut from the sides of the output to account for input padding - output_pad_len = model._get_feat_extract_output_lengths(int(sampling_rate * pad_duration_ms / 1000)) - - # define the audio chunk generator - stream = ffmpeg_stream(url, sampling_rate, chunk_duration_ms=chunk_duration_ms, pad_duration_ms=pad_duration_ms) - - leftover_text = "" - for i, chunk in enumerate(stream): - input_values = processor(chunk, sampling_rate=sampling_rate, return_tensors="pt").input_values - - with torch.no_grad(): - logits = model(input_values.to(device)).logits[0] - if i > 0: - logits = logits[output_pad_len : len(logits) - output_pad_len] - else: # don't count padding at the start of the clip - logits = logits[: len(logits) - output_pad_len] - - predicted_ids = torch.argmax(logits, dim=-1).cpu().tolist() - if processor.decode(predicted_ids).strip(): - leftover_ids = processor.tokenizer.encode(leftover_text) - # concat the last word (or its part) from the last frame with the current text - text = processor.decode(leftover_ids + predicted_ids) - # don't return the last word in case it's just partially recognized - text, leftover_text = text.rsplit(" ", 1) - yield text - else: - yield leftover_text - leftover_text = "" - - yield leftover_text - - -def main(): - state = st.session_state - st.header("YouTube Streaming ASR with Robust Wav2Vec2") - - with st.form(key="inputs_form"): - state.youtube_url = st.text_input("YouTube URL", "https://www.youtube.com/watch?v=yJmiZ1Mo1cQ") - state.chunk_duration_ms = st.slider("Audio chunk duration (ms)", 2000, 10000, 3000, 100) - state.pad_duration_ms = st.slider("Padding duration (ms)", 100, 5000, 1000, 100) - submit_button = st.form_submit_button(label="Submit") - - if submit_button or "asr_stream" not in state: - # a hack to update the video player on value changes - state.youtube_url = ( - state.youtube_url.split("&hash=")[0] - + f"&hash={state.chunk_duration_ms}-{state.pad_duration_ms}" - ) - state.asr_stream = stream_text( - state.youtube_url, state.chunk_duration_ms, state.pad_duration_ms - ) - state.chunks_taken = 0 - state.lines = deque([], maxlen=5) # limit to the last 5 lines of subs - - player = st_player(state.youtube_url, **player_options, key="youtube_player") - - if "asr_stream" in state and player.data and player.data["played"] < 1.0: - # check how many seconds were played, and if more than processed - write the next text chunk - processed_seconds = state.chunks_taken * (state.chunk_duration_ms / 1000) - if processed_seconds < player.data["playedSeconds"]: - text = next(state.asr_stream) - state.lines.append(text) - state.chunks_taken += 1 - if "lines" in state: - # print the last 3 lines of subs - st.code("\n".join(state.lines)) - - -if __name__ == "__main__": - main() diff --git a/spaces/aodianyun/stable-diffusion-webui/javascript/imageParams.js b/spaces/aodianyun/stable-diffusion-webui/javascript/imageParams.js deleted file mode 100644 index 67404a89ba6084a065ab5ac188e01ed29952113b..0000000000000000000000000000000000000000 --- a/spaces/aodianyun/stable-diffusion-webui/javascript/imageParams.js +++ /dev/null @@ -1,19 +0,0 @@ -window.onload = (function(){ - window.addEventListener('drop', e => { - const target = e.composedPath()[0]; - const idx = selected_gallery_index(); - if (target.placeholder.indexOf("Prompt") == -1) return; - - let prompt_target = get_tab_index('tabs') == 1 ? "img2img_prompt_image" : "txt2img_prompt_image"; - - e.stopPropagation(); - e.preventDefault(); - const imgParent = gradioApp().getElementById(prompt_target); - const files = e.dataTransfer.files; - const fileInput = imgParent.querySelector('input[type="file"]'); - if ( fileInput ) { - fileInput.files = files; - fileInput.dispatchEvent(new Event('change')); - } - }); -}); diff --git a/spaces/arseny-chebyshev/vox-diffusion/app.py b/spaces/arseny-chebyshev/vox-diffusion/app.py deleted file mode 100644 index 0f6a28507b7f2ddb15b034c0143aa04365164752..0000000000000000000000000000000000000000 --- a/spaces/arseny-chebyshev/vox-diffusion/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/plasmo/vox2").launch() \ No newline at end of file diff --git a/spaces/artificialguybr/video-dubbing/TTS/TTS/tts/models/delightful_tts.py b/spaces/artificialguybr/video-dubbing/TTS/TTS/tts/models/delightful_tts.py deleted file mode 100644 index b1cf886bea1f22a0ec1b0524f5a80ea8db0b55f8..0000000000000000000000000000000000000000 --- a/spaces/artificialguybr/video-dubbing/TTS/TTS/tts/models/delightful_tts.py +++ /dev/null @@ -1,1770 +0,0 @@ -import os -from dataclasses import dataclass, field -from itertools import chain -from pathlib import Path -from typing import Dict, List, Optional, Tuple, Union - -import numpy as np -import torch -import torch.distributed as dist -import torchaudio -from coqpit import Coqpit -from librosa.filters import mel as librosa_mel_fn -from torch import nn -from torch.cuda.amp.autocast_mode import autocast -from torch.nn import functional as F -from torch.utils.data import DataLoader -from torch.utils.data.sampler import WeightedRandomSampler -from trainer.torch import DistributedSampler, DistributedSamplerWrapper -from trainer.trainer_utils import get_optimizer, get_scheduler - -from TTS.tts.datasets.dataset import F0Dataset, TTSDataset, _parse_sample -from TTS.tts.layers.delightful_tts.acoustic_model import AcousticModel -from TTS.tts.layers.losses import ForwardSumLoss, VitsDiscriminatorLoss -from TTS.tts.layers.vits.discriminator import VitsDiscriminator -from TTS.tts.models.base_tts import BaseTTSE2E -from TTS.tts.utils.helpers import average_over_durations, compute_attn_prior, rand_segments, segment, sequence_mask -from TTS.tts.utils.speakers import SpeakerManager -from TTS.tts.utils.text.tokenizer import TTSTokenizer -from TTS.tts.utils.visual import plot_alignment, plot_avg_pitch, plot_pitch, plot_spectrogram -from TTS.utils.audio.numpy_transforms import build_mel_basis, compute_f0 -from TTS.utils.audio.numpy_transforms import db_to_amp as db_to_amp_numpy -from TTS.utils.audio.numpy_transforms import mel_to_wav as mel_to_wav_numpy -from TTS.utils.audio.processor import AudioProcessor -from TTS.utils.io import load_fsspec -from TTS.vocoder.layers.losses import MultiScaleSTFTLoss -from TTS.vocoder.models.hifigan_generator import HifiganGenerator -from TTS.vocoder.utils.generic_utils import plot_results - - -def id_to_torch(aux_id, cuda=False): - if aux_id is not None: - aux_id = np.asarray(aux_id) - aux_id = torch.from_numpy(aux_id) - if cuda: - return aux_id.cuda() - return aux_id - - -def embedding_to_torch(d_vector, cuda=False): - if d_vector is not None: - d_vector = np.asarray(d_vector) - d_vector = torch.from_numpy(d_vector).float() - d_vector = d_vector.squeeze().unsqueeze(0) - if cuda: - return d_vector.cuda() - return d_vector - - -def numpy_to_torch(np_array, dtype, cuda=False): - if np_array is None: - return None - tensor = torch.as_tensor(np_array, dtype=dtype) - if cuda: - return tensor.cuda() - return tensor - - -def get_mask_from_lengths(lengths: torch.Tensor) -> torch.Tensor: - batch_size = lengths.shape[0] - max_len = torch.max(lengths).item() - ids = torch.arange(0, max_len, device=lengths.device).unsqueeze(0).expand(batch_size, -1) - mask = ids >= lengths.unsqueeze(1).expand(-1, max_len) - return mask - - -def pad(input_ele: List[torch.Tensor], max_len: int) -> torch.Tensor: - out_list = torch.jit.annotate(List[torch.Tensor], []) - for batch in input_ele: - if len(batch.shape) == 1: - one_batch_padded = F.pad(batch, (0, max_len - batch.size(0)), "constant", 0.0) - else: - one_batch_padded = F.pad(batch, (0, 0, 0, max_len - batch.size(0)), "constant", 0.0) - out_list.append(one_batch_padded) - out_padded = torch.stack(out_list) - return out_padded - - -def init_weights(m: nn.Module, mean: float = 0.0, std: float = 0.01): - classname = m.__class__.__name__ - if classname.find("Conv") != -1: - m.weight.data.normal_(mean, std) - - -def stride_lens(lens: torch.Tensor, stride: int = 2) -> torch.Tensor: - return torch.ceil(lens / stride).int() - - -def initialize_embeddings(shape: Tuple[int]) -> torch.Tensor: - assert len(shape) == 2, "Can only initialize 2-D embedding matrices ..." - return torch.randn(shape) * np.sqrt(2 / shape[1]) - - -# pylint: disable=redefined-outer-name -def calc_same_padding(kernel_size: int) -> Tuple[int, int]: - pad = kernel_size // 2 - return (pad, pad - (kernel_size + 1) % 2) - - -hann_window = {} -mel_basis = {} - - -@torch.no_grad() -def weights_reset(m: nn.Module): - # check if the current module has reset_parameters and if it is reset the weight - reset_parameters = getattr(m, "reset_parameters", None) - if callable(reset_parameters): - m.reset_parameters() - - -def get_module_weights_sum(mdl: nn.Module): - dict_sums = {} - for name, w in mdl.named_parameters(): - if "weight" in name: - value = w.data.sum().item() - dict_sums[name] = value - return dict_sums - - -def load_audio(file_path: str): - """Load the audio file normalized in [-1, 1] - - Return Shapes: - - x: :math:`[1, T]` - """ - x, sr = torchaudio.load( - file_path, - ) - assert (x > 1).sum() + (x < -1).sum() == 0 - return x, sr - - -def _amp_to_db(x, C=1, clip_val=1e-5): - return torch.log(torch.clamp(x, min=clip_val) * C) - - -def _db_to_amp(x, C=1): - return torch.exp(x) / C - - -def amp_to_db(magnitudes): - output = _amp_to_db(magnitudes) - return output - - -def db_to_amp(magnitudes): - output = _db_to_amp(magnitudes) - return output - - -def _wav_to_spec(y, n_fft, hop_length, win_length, center=False): - y = y.squeeze(1) - - if torch.min(y) < -1.0: - print("min value is ", torch.min(y)) - if torch.max(y) > 1.0: - print("max value is ", torch.max(y)) - - global hann_window # pylint: disable=global-statement - dtype_device = str(y.dtype) + "_" + str(y.device) - wnsize_dtype_device = str(win_length) + "_" + dtype_device - if wnsize_dtype_device not in hann_window: - hann_window[wnsize_dtype_device] = torch.hann_window(win_length).to(dtype=y.dtype, device=y.device) - - y = torch.nn.functional.pad( - y.unsqueeze(1), - (int((n_fft - hop_length) / 2), int((n_fft - hop_length) / 2)), - mode="reflect", - ) - y = y.squeeze(1) - - spec = torch.stft( - y, - n_fft, - hop_length=hop_length, - win_length=win_length, - window=hann_window[wnsize_dtype_device], - center=center, - pad_mode="reflect", - normalized=False, - onesided=True, - return_complex=False, - ) - - return spec - - -def wav_to_spec(y, n_fft, hop_length, win_length, center=False): - """ - Args Shapes: - - y : :math:`[B, 1, T]` - - Return Shapes: - - spec : :math:`[B,C,T]` - """ - spec = _wav_to_spec(y, n_fft, hop_length, win_length, center=center) - spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6) - return spec - - -def wav_to_energy(y, n_fft, hop_length, win_length, center=False): - spec = _wav_to_spec(y, n_fft, hop_length, win_length, center=center) - - spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6) - return torch.norm(spec, dim=1, keepdim=True) - - -def name_mel_basis(spec, n_fft, fmax): - n_fft_len = f"{n_fft}_{fmax}_{spec.dtype}_{spec.device}" - return n_fft_len - - -def spec_to_mel(spec, n_fft, num_mels, sample_rate, fmin, fmax): - """ - Args Shapes: - - spec : :math:`[B,C,T]` - - Return Shapes: - - mel : :math:`[B,C,T]` - """ - global mel_basis # pylint: disable=global-statement - mel_basis_key = name_mel_basis(spec, n_fft, fmax) - # pylint: disable=too-many-function-args - if mel_basis_key not in mel_basis: - # pylint: disable=missing-kwoa - mel = librosa_mel_fn(sample_rate, n_fft, num_mels, fmin, fmax) - mel_basis[mel_basis_key] = torch.from_numpy(mel).to(dtype=spec.dtype, device=spec.device) - mel = torch.matmul(mel_basis[mel_basis_key], spec) - mel = amp_to_db(mel) - return mel - - -def wav_to_mel(y, n_fft, num_mels, sample_rate, hop_length, win_length, fmin, fmax, center=False): - """ - Args Shapes: - - y : :math:`[B, 1, T_y]` - - Return Shapes: - - spec : :math:`[B,C,T_spec]` - """ - y = y.squeeze(1) - - if torch.min(y) < -1.0: - print("min value is ", torch.min(y)) - if torch.max(y) > 1.0: - print("max value is ", torch.max(y)) - - global mel_basis, hann_window # pylint: disable=global-statement - mel_basis_key = name_mel_basis(y, n_fft, fmax) - wnsize_dtype_device = str(win_length) + "_" + str(y.dtype) + "_" + str(y.device) - if mel_basis_key not in mel_basis: - # pylint: disable=missing-kwoa - mel = librosa_mel_fn( - sr=sample_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax - ) # pylint: disable=too-many-function-args - mel_basis[mel_basis_key] = torch.from_numpy(mel).to(dtype=y.dtype, device=y.device) - if wnsize_dtype_device not in hann_window: - hann_window[wnsize_dtype_device] = torch.hann_window(win_length).to(dtype=y.dtype, device=y.device) - - y = torch.nn.functional.pad( - y.unsqueeze(1), - (int((n_fft - hop_length) / 2), int((n_fft - hop_length) / 2)), - mode="reflect", - ) - y = y.squeeze(1) - - spec = torch.stft( - y, - n_fft, - hop_length=hop_length, - win_length=win_length, - window=hann_window[wnsize_dtype_device], - center=center, - pad_mode="reflect", - normalized=False, - onesided=True, - return_complex=False, - ) - - spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6) - spec = torch.matmul(mel_basis[mel_basis_key], spec) - spec = amp_to_db(spec) - return spec - - -############################## -# DATASET -############################## - - -def get_attribute_balancer_weights(items: list, attr_name: str, multi_dict: dict = None): - """Create balancer weight for torch WeightedSampler""" - attr_names_samples = np.array([item[attr_name] for item in items]) - unique_attr_names = np.unique(attr_names_samples).tolist() - attr_idx = [unique_attr_names.index(l) for l in attr_names_samples] - attr_count = np.array([len(np.where(attr_names_samples == l)[0]) for l in unique_attr_names]) - weight_attr = 1.0 / attr_count - dataset_samples_weight = np.array([weight_attr[l] for l in attr_idx]) - dataset_samples_weight = dataset_samples_weight / np.linalg.norm(dataset_samples_weight) - if multi_dict is not None: - multiplier_samples = np.array([multi_dict.get(item[attr_name], 1.0) for item in items]) - dataset_samples_weight *= multiplier_samples - return ( - torch.from_numpy(dataset_samples_weight).float(), - unique_attr_names, - np.unique(dataset_samples_weight).tolist(), - ) - - -class ForwardTTSE2eF0Dataset(F0Dataset): - """Override F0Dataset to avoid slow computing of pitches""" - - def __init__( - self, - ap, - samples: Union[List[List], List[Dict]], - verbose=False, - cache_path: str = None, - precompute_num_workers=0, - normalize_f0=True, - ): - super().__init__( - samples=samples, - ap=ap, - verbose=verbose, - cache_path=cache_path, - precompute_num_workers=precompute_num_workers, - normalize_f0=normalize_f0, - ) - - def _compute_and_save_pitch(self, wav_file, pitch_file=None): - wav, _ = load_audio(wav_file) - f0 = compute_f0( - x=wav.numpy()[0], - sample_rate=self.ap.sample_rate, - hop_length=self.ap.hop_length, - pitch_fmax=self.ap.pitch_fmax, - pitch_fmin=self.ap.pitch_fmin, - win_length=self.ap.win_length, - ) - # skip the last F0 value to align with the spectrogram - if wav.shape[1] % self.ap.hop_length != 0: - f0 = f0[:-1] - if pitch_file: - np.save(pitch_file, f0) - return f0 - - def compute_or_load(self, wav_file, audio_name): - """ - compute pitch and return a numpy array of pitch values - """ - pitch_file = self.create_pitch_file_path(audio_name, self.cache_path) - if not os.path.exists(pitch_file): - pitch = self._compute_and_save_pitch(wav_file=wav_file, pitch_file=pitch_file) - else: - pitch = np.load(pitch_file) - return pitch.astype(np.float32) - - -class ForwardTTSE2eDataset(TTSDataset): - def __init__(self, *args, **kwargs): - # don't init the default F0Dataset in TTSDataset - compute_f0 = kwargs.pop("compute_f0", False) - kwargs["compute_f0"] = False - self.attn_prior_cache_path = kwargs.pop("attn_prior_cache_path") - - super().__init__(*args, **kwargs) - - self.compute_f0 = compute_f0 - self.pad_id = self.tokenizer.characters.pad_id - self.ap = kwargs["ap"] - - if self.compute_f0: - self.f0_dataset = ForwardTTSE2eF0Dataset( - ap=self.ap, - samples=self.samples, - cache_path=kwargs["f0_cache_path"], - precompute_num_workers=kwargs["precompute_num_workers"], - ) - - if self.attn_prior_cache_path is not None: - os.makedirs(self.attn_prior_cache_path, exist_ok=True) - - def __getitem__(self, idx): - item = self.samples[idx] - - rel_wav_path = Path(item["audio_file"]).relative_to(item["root_path"]).with_suffix("") - rel_wav_path = str(rel_wav_path).replace("/", "_") - - raw_text = item["text"] - wav, _ = load_audio(item["audio_file"]) - wav_filename = os.path.basename(item["audio_file"]) - - try: - token_ids = self.get_token_ids(idx, item["text"]) - except: - print(idx, item) - # pylint: disable=raise-missing-from - raise OSError - f0 = None - if self.compute_f0: - f0 = self.get_f0(idx)["f0"] - - # after phonemization the text length may change - # this is a shameful 🤭 hack to prevent longer phonemes - # TODO: find a better fix - if len(token_ids) > self.max_text_len or wav.shape[1] < self.min_audio_len: - self.rescue_item_idx += 1 - return self.__getitem__(self.rescue_item_idx) - - attn_prior = None - if self.attn_prior_cache_path is not None: - attn_prior = self.load_or_compute_attn_prior(token_ids, wav, rel_wav_path) - - return { - "raw_text": raw_text, - "token_ids": token_ids, - "token_len": len(token_ids), - "wav": wav, - "pitch": f0, - "wav_file": wav_filename, - "speaker_name": item["speaker_name"], - "language_name": item["language"], - "attn_prior": attn_prior, - "audio_unique_name": item["audio_unique_name"], - } - - def load_or_compute_attn_prior(self, token_ids, wav, rel_wav_path): - """Load or compute and save the attention prior.""" - attn_prior_file = os.path.join(self.attn_prior_cache_path, f"{rel_wav_path}.npy") - # pylint: disable=no-else-return - if os.path.exists(attn_prior_file): - return np.load(attn_prior_file) - else: - token_len = len(token_ids) - mel_len = wav.shape[1] // self.ap.hop_length - attn_prior = compute_attn_prior(token_len, mel_len) - np.save(attn_prior_file, attn_prior) - return attn_prior - - @property - def lengths(self): - lens = [] - for item in self.samples: - _, wav_file, *_ = _parse_sample(item) - audio_len = os.path.getsize(wav_file) / 16 * 8 # assuming 16bit audio - lens.append(audio_len) - return lens - - def collate_fn(self, batch): - """ - Return Shapes: - - tokens: :math:`[B, T]` - - token_lens :math:`[B]` - - token_rel_lens :math:`[B]` - - pitch :math:`[B, T]` - - waveform: :math:`[B, 1, T]` - - waveform_lens: :math:`[B]` - - waveform_rel_lens: :math:`[B]` - - speaker_names: :math:`[B]` - - language_names: :math:`[B]` - - audiofile_paths: :math:`[B]` - - raw_texts: :math:`[B]` - - attn_prior: :math:`[[T_token, T_mel]]` - """ - B = len(batch) - batch = {k: [dic[k] for dic in batch] for k in batch[0]} - - max_text_len = max([len(x) for x in batch["token_ids"]]) - token_lens = torch.LongTensor(batch["token_len"]) - token_rel_lens = token_lens / token_lens.max() - - wav_lens = [w.shape[1] for w in batch["wav"]] - wav_lens = torch.LongTensor(wav_lens) - wav_lens_max = torch.max(wav_lens) - wav_rel_lens = wav_lens / wav_lens_max - - pitch_padded = None - if self.compute_f0: - pitch_lens = [p.shape[0] for p in batch["pitch"]] - pitch_lens = torch.LongTensor(pitch_lens) - pitch_lens_max = torch.max(pitch_lens) - pitch_padded = torch.FloatTensor(B, 1, pitch_lens_max) - pitch_padded = pitch_padded.zero_() + self.pad_id - - token_padded = torch.LongTensor(B, max_text_len) - wav_padded = torch.FloatTensor(B, 1, wav_lens_max) - - token_padded = token_padded.zero_() + self.pad_id - wav_padded = wav_padded.zero_() + self.pad_id - - for i in range(B): - token_ids = batch["token_ids"][i] - token_padded[i, : batch["token_len"][i]] = torch.LongTensor(token_ids) - - wav = batch["wav"][i] - wav_padded[i, :, : wav.size(1)] = torch.FloatTensor(wav) - - if self.compute_f0: - pitch = batch["pitch"][i] - pitch_padded[i, 0, : len(pitch)] = torch.FloatTensor(pitch) - - return { - "text_input": token_padded, - "text_lengths": token_lens, - "text_rel_lens": token_rel_lens, - "pitch": pitch_padded, - "waveform": wav_padded, # (B x T) - "waveform_lens": wav_lens, # (B) - "waveform_rel_lens": wav_rel_lens, - "speaker_names": batch["speaker_name"], - "language_names": batch["language_name"], - "audio_unique_names": batch["audio_unique_name"], - "audio_files": batch["wav_file"], - "raw_text": batch["raw_text"], - "attn_priors": batch["attn_prior"] if batch["attn_prior"][0] is not None else None, - } - - -############################## -# CONFIG DEFINITIONS -############################## - - -@dataclass -class VocoderConfig(Coqpit): - resblock_type_decoder: str = "1" - resblock_kernel_sizes_decoder: List[int] = field(default_factory=lambda: [3, 7, 11]) - resblock_dilation_sizes_decoder: List[List[int]] = field(default_factory=lambda: [[1, 3, 5], [1, 3, 5], [1, 3, 5]]) - upsample_rates_decoder: List[int] = field(default_factory=lambda: [8, 8, 2, 2]) - upsample_initial_channel_decoder: int = 512 - upsample_kernel_sizes_decoder: List[int] = field(default_factory=lambda: [16, 16, 4, 4]) - use_spectral_norm_discriminator: bool = False - upsampling_rates_discriminator: List[int] = field(default_factory=lambda: [4, 4, 4, 4]) - periods_discriminator: List[int] = field(default_factory=lambda: [2, 3, 5, 7, 11]) - pretrained_model_path: Optional[str] = None - - -@dataclass -class DelightfulTtsAudioConfig(Coqpit): - sample_rate: int = 22050 - hop_length: int = 256 - win_length: int = 1024 - fft_size: int = 1024 - mel_fmin: float = 0.0 - mel_fmax: float = 8000 - num_mels: int = 100 - pitch_fmax: float = 640.0 - pitch_fmin: float = 1.0 - resample: bool = False - preemphasis: float = 0.0 - ref_level_db: int = 20 - do_sound_norm: bool = False - log_func: str = "np.log10" - do_trim_silence: bool = True - trim_db: int = 45 - do_rms_norm: bool = False - db_level: float = None - power: float = 1.5 - griffin_lim_iters: int = 60 - spec_gain: int = 20 - do_amp_to_db_linear: bool = True - do_amp_to_db_mel: bool = True - min_level_db: int = -100 - max_norm: float = 4.0 - - -@dataclass -class DelightfulTtsArgs(Coqpit): - num_chars: int = 100 - spec_segment_size: int = 32 - n_hidden_conformer_encoder: int = 512 - n_layers_conformer_encoder: int = 6 - n_heads_conformer_encoder: int = 8 - dropout_conformer_encoder: float = 0.1 - kernel_size_conv_mod_conformer_encoder: int = 7 - kernel_size_depthwise_conformer_encoder: int = 7 - lrelu_slope: float = 0.3 - n_hidden_conformer_decoder: int = 512 - n_layers_conformer_decoder: int = 6 - n_heads_conformer_decoder: int = 8 - dropout_conformer_decoder: float = 0.1 - kernel_size_conv_mod_conformer_decoder: int = 11 - kernel_size_depthwise_conformer_decoder: int = 11 - bottleneck_size_p_reference_encoder: int = 4 - bottleneck_size_u_reference_encoder: int = 512 - ref_enc_filters_reference_encoder = [32, 32, 64, 64, 128, 128] - ref_enc_size_reference_encoder: int = 3 - ref_enc_strides_reference_encoder = [1, 2, 1, 2, 1] - ref_enc_pad_reference_encoder = [1, 1] - ref_enc_gru_size_reference_encoder: int = 32 - ref_attention_dropout_reference_encoder: float = 0.2 - token_num_reference_encoder: int = 32 - predictor_kernel_size_reference_encoder: int = 5 - n_hidden_variance_adaptor: int = 512 - kernel_size_variance_adaptor: int = 5 - dropout_variance_adaptor: float = 0.5 - n_bins_variance_adaptor: int = 256 - emb_kernel_size_variance_adaptor: int = 3 - use_speaker_embedding: bool = False - num_speakers: int = 0 - speakers_file: str = None - d_vector_file: str = None - speaker_embedding_channels: int = 384 - use_d_vector_file: bool = False - d_vector_dim: int = 0 - freeze_vocoder: bool = False - freeze_text_encoder: bool = False - freeze_duration_predictor: bool = False - freeze_pitch_predictor: bool = False - freeze_energy_predictor: bool = False - freeze_basis_vectors_predictor: bool = False - freeze_decoder: bool = False - length_scale: float = 1.0 - - -############################## -# MODEL DEFINITION -############################## -class DelightfulTTS(BaseTTSE2E): - """ - Paper:: - https://arxiv.org/pdf/2110.12612.pdf - - Paper Abstract:: - This paper describes the Microsoft end-to-end neural text to speech (TTS) system: DelightfulTTS for Blizzard Challenge 2021. - The goal of this challenge is to synthesize natural and high-quality speech from text, and we approach this goal in two perspectives: - The first is to directly model and generate waveform in 48 kHz sampling rate, which brings higher perception quality than previous systems - with 16 kHz or 24 kHz sampling rate; The second is to model the variation information in speech through a systematic design, which improves - the prosody and naturalness. Specifically, for 48 kHz modeling, we predict 16 kHz mel-spectrogram in acoustic model, and - propose a vocoder called HiFiNet to directly generate 48 kHz waveform from predicted 16 kHz mel-spectrogram, which can better trade off training - efficiency, modelling stability and voice quality. We model variation information systematically from both explicit (speaker ID, language ID, pitch and duration) and - implicit (utterance-level and phoneme-level prosody) perspectives: 1) For speaker and language ID, we use lookup embedding in training and - inference; 2) For pitch and duration, we extract the values from paired text-speech data in training and use two predictors to predict the values in inference; 3) - For utterance-level and phoneme-level prosody, we use two reference encoders to extract the values in training, and use two separate predictors to predict the values in inference. - Additionally, we introduce an improved Conformer block to better model the local and global dependency in acoustic model. For task SH1, DelightfulTTS achieves 4.17 mean score in MOS test - and 4.35 in SMOS test, which indicates the effectiveness of our proposed system - - - Model training:: - text --> ForwardTTS() --> spec_hat --> rand_seg_select()--> GANVocoder() --> waveform_seg - spec --------^ - - Examples: - >>> from TTS.tts.models.forward_tts_e2e import ForwardTTSE2e, ForwardTTSE2eConfig - >>> config = ForwardTTSE2eConfig() - >>> model = ForwardTTSE2e(config) - """ - - # pylint: disable=dangerous-default-value - def __init__( - self, - config: Coqpit, - ap, - tokenizer: "TTSTokenizer" = None, - speaker_manager: SpeakerManager = None, - ): - super().__init__(config=config, ap=ap, tokenizer=tokenizer, speaker_manager=speaker_manager) - self.ap = ap - - self._set_model_args(config) - self.init_multispeaker(config) - self.binary_loss_weight = None - - self.args.out_channels = self.config.audio.num_mels - self.args.num_mels = self.config.audio.num_mels - self.acoustic_model = AcousticModel(args=self.args, tokenizer=tokenizer, speaker_manager=speaker_manager) - - self.waveform_decoder = HifiganGenerator( - self.config.audio.num_mels, - 1, - self.config.vocoder.resblock_type_decoder, - self.config.vocoder.resblock_dilation_sizes_decoder, - self.config.vocoder.resblock_kernel_sizes_decoder, - self.config.vocoder.upsample_kernel_sizes_decoder, - self.config.vocoder.upsample_initial_channel_decoder, - self.config.vocoder.upsample_rates_decoder, - inference_padding=0, - # cond_channels=self.embedded_speaker_dim, - conv_pre_weight_norm=False, - conv_post_weight_norm=False, - conv_post_bias=False, - ) - - if self.config.init_discriminator: - self.disc = VitsDiscriminator( - use_spectral_norm=self.config.vocoder.use_spectral_norm_discriminator, - periods=self.config.vocoder.periods_discriminator, - ) - - @property - def device(self): - return next(self.parameters()).device - - @property - def energy_scaler(self): - return self.acoustic_model.energy_scaler - - @property - def length_scale(self): - return self.acoustic_model.length_scale - - @length_scale.setter - def length_scale(self, value): - self.acoustic_model.length_scale = value - - @property - def pitch_mean(self): - return self.acoustic_model.pitch_mean - - @pitch_mean.setter - def pitch_mean(self, value): - self.acoustic_model.pitch_mean = value - - @property - def pitch_std(self): - return self.acoustic_model.pitch_std - - @pitch_std.setter - def pitch_std(self, value): - self.acoustic_model.pitch_std = value - - @property - def mel_basis(self): - return build_mel_basis( - sample_rate=self.ap.sample_rate, - fft_size=self.ap.fft_size, - num_mels=self.ap.num_mels, - mel_fmax=self.ap.mel_fmax, - mel_fmin=self.ap.mel_fmin, - ) # pylint: disable=function-redefined - - def init_for_training(self) -> None: - self.train_disc = ( # pylint: disable=attribute-defined-outside-init - self.config.steps_to_start_discriminator <= 0 - ) # pylint: disable=attribute-defined-outside-init - self.update_energy_scaler = True # pylint: disable=attribute-defined-outside-init - - def init_multispeaker(self, config: Coqpit): - """Init for multi-speaker training. - - Args: - config (Coqpit): Model configuration. - """ - self.embedded_speaker_dim = 0 - self.num_speakers = self.args.num_speakers - self.audio_transform = None - - if self.speaker_manager: - self.num_speakers = self.speaker_manager.num_speakers - self.args.num_speakers = self.speaker_manager.num_speakers - - if self.args.use_speaker_embedding: - self._init_speaker_embedding() - - if self.args.use_d_vector_file: - self._init_d_vector() - - def _init_speaker_embedding(self): - # pylint: disable=attribute-defined-outside-init - if self.num_speakers > 0: - print(" > initialization of speaker-embedding layers.") - self.embedded_speaker_dim = self.args.speaker_embedding_channels - self.args.embedded_speaker_dim = self.args.speaker_embedding_channels - - def _init_d_vector(self): - # pylint: disable=attribute-defined-outside-init - if hasattr(self, "emb_g"): - raise ValueError("[!] Speaker embedding layer already initialized before d_vector settings.") - self.embedded_speaker_dim = self.args.d_vector_dim - self.args.embedded_speaker_dim = self.args.d_vector_dim - - def _freeze_layers(self): - if self.args.freeze_vocoder: - for param in self.vocoder.paramseters(): - param.requires_grad = False - - if self.args.freeze_text_encoder: - for param in self.text_encoder.parameters(): - param.requires_grad = False - - if self.args.freeze_duration_predictor: - for param in self.durarion_predictor.parameters(): - param.requires_grad = False - - if self.args.freeze_pitch_predictor: - for param in self.pitch_predictor.parameters(): - param.requires_grad = False - - if self.args.freeze_energy_predictor: - for param in self.energy_predictor.parameters(): - param.requires_grad = False - - if self.args.freeze_decoder: - for param in self.decoder.parameters(): - param.requires_grad = False - - def forward( - self, - x: torch.LongTensor, - x_lengths: torch.LongTensor, - spec_lengths: torch.LongTensor, - spec: torch.FloatTensor, - waveform: torch.FloatTensor, - pitch: torch.FloatTensor = None, - energy: torch.FloatTensor = None, - attn_priors: torch.FloatTensor = None, - d_vectors: torch.FloatTensor = None, - speaker_idx: torch.LongTensor = None, - ) -> Dict: - """Model's forward pass. - - Args: - x (torch.LongTensor): Input character sequences. - x_lengths (torch.LongTensor): Input sequence lengths. - spec_lengths (torch.LongTensor): Spectrogram sequnce lengths. Defaults to None. - spec (torch.FloatTensor): Spectrogram frames. Only used when the alignment network is on. Defaults to None. - waveform (torch.FloatTensor): Waveform. Defaults to None. - pitch (torch.FloatTensor): Pitch values for each spectrogram frame. Only used when the pitch predictor is on. Defaults to None. - energy (torch.FloatTensor): Spectral energy values for each spectrogram frame. Only used when the energy predictor is on. Defaults to None. - attn_priors (torch.FloatTentrasor): Attention priors for the aligner network. Defaults to None. - aux_input (Dict): Auxiliary model inputs for multi-speaker training. Defaults to `{"d_vectors": 0, "speaker_ids": None}`. - - Shapes: - - x: :math:`[B, T_max]` - - x_lengths: :math:`[B]` - - spec_lengths: :math:`[B]` - - spec: :math:`[B, T_max2, C_spec]` - - waveform: :math:`[B, 1, T_max2 * hop_length]` - - g: :math:`[B, C]` - - pitch: :math:`[B, 1, T_max2]` - - energy: :math:`[B, 1, T_max2]` - """ - encoder_outputs = self.acoustic_model( - tokens=x, - src_lens=x_lengths, - mel_lens=spec_lengths, - mels=spec, - pitches=pitch, - energies=energy, - attn_priors=attn_priors, - d_vectors=d_vectors, - speaker_idx=speaker_idx, - ) - - # use mel-spec from the decoder - vocoder_input = encoder_outputs["model_outputs"] # [B, T_max2, C_mel] - - vocoder_input_slices, slice_ids = rand_segments( - x=vocoder_input.transpose(1, 2), - x_lengths=spec_lengths, - segment_size=self.args.spec_segment_size, - let_short_samples=True, - pad_short=True, - ) - if encoder_outputs["spk_emb"] is not None: - g = encoder_outputs["spk_emb"].unsqueeze(-1) - else: - g = None - - vocoder_output = self.waveform_decoder(x=vocoder_input_slices.detach(), g=g) - wav_seg = segment( - waveform, - slice_ids * self.ap.hop_length, - self.args.spec_segment_size * self.ap.hop_length, - pad_short=True, - ) - model_outputs = {**encoder_outputs} - model_outputs["acoustic_model_outputs"] = encoder_outputs["model_outputs"] - model_outputs["model_outputs"] = vocoder_output - model_outputs["waveform_seg"] = wav_seg - model_outputs["slice_ids"] = slice_ids - return model_outputs - - @torch.no_grad() - def inference( - self, x, aux_input={"d_vectors": None, "speaker_ids": None}, pitch_transform=None, energy_transform=None - ): - encoder_outputs = self.acoustic_model.inference( - tokens=x, - d_vectors=aux_input["d_vectors"], - speaker_idx=aux_input["speaker_ids"], - pitch_transform=pitch_transform, - energy_transform=energy_transform, - p_control=None, - d_control=None, - ) - vocoder_input = encoder_outputs["model_outputs"].transpose(1, 2) # [B, T_max2, C_mel] -> [B, C_mel, T_max2] - if encoder_outputs["spk_emb"] is not None: - g = encoder_outputs["spk_emb"].unsqueeze(-1) - else: - g = None - - vocoder_output = self.waveform_decoder(x=vocoder_input, g=g) - model_outputs = {**encoder_outputs} - model_outputs["model_outputs"] = vocoder_output - return model_outputs - - @torch.no_grad() - def inference_spec_decoder(self, x, aux_input={"d_vectors": None, "speaker_ids": None}): - encoder_outputs = self.acoustic_model.inference( - tokens=x, - d_vectors=aux_input["d_vectors"], - speaker_idx=aux_input["speaker_ids"], - ) - model_outputs = {**encoder_outputs} - return model_outputs - - def train_step(self, batch: dict, criterion: nn.Module, optimizer_idx: int): - if optimizer_idx == 0: - tokens = batch["text_input"] - token_lenghts = batch["text_lengths"] - mel = batch["mel_input"] - mel_lens = batch["mel_lengths"] - waveform = batch["waveform"] # [B, T, C] -> [B, C, T] - pitch = batch["pitch"] - d_vectors = batch["d_vectors"] - speaker_ids = batch["speaker_ids"] - attn_priors = batch["attn_priors"] - energy = batch["energy"] - - # generator pass - outputs = self.forward( - x=tokens, - x_lengths=token_lenghts, - spec_lengths=mel_lens, - spec=mel, - waveform=waveform, - pitch=pitch, - energy=energy, - attn_priors=attn_priors, - d_vectors=d_vectors, - speaker_idx=speaker_ids, - ) - - # cache tensors for the generator pass - self.model_outputs_cache = outputs # pylint: disable=attribute-defined-outside-init - - if self.train_disc: - # compute scores and features - scores_d_fake, _, scores_d_real, _ = self.disc( - outputs["model_outputs"].detach(), outputs["waveform_seg"] - ) - - # compute loss - with autocast(enabled=False): # use float32 for the criterion - loss_dict = criterion[optimizer_idx]( - scores_disc_fake=scores_d_fake, - scores_disc_real=scores_d_real, - ) - return outputs, loss_dict - return None, None - - if optimizer_idx == 1: - mel = batch["mel_input"] - # compute melspec segment - with autocast(enabled=False): - mel_slice = segment( - mel.float(), self.model_outputs_cache["slice_ids"], self.args.spec_segment_size, pad_short=True - ) - - mel_slice_hat = wav_to_mel( - y=self.model_outputs_cache["model_outputs"].float(), - n_fft=self.ap.fft_size, - sample_rate=self.ap.sample_rate, - num_mels=self.ap.num_mels, - hop_length=self.ap.hop_length, - win_length=self.ap.win_length, - fmin=self.ap.mel_fmin, - fmax=self.ap.mel_fmax, - center=False, - ) - - scores_d_fake = None - feats_d_fake = None - feats_d_real = None - - if self.train_disc: - # compute discriminator scores and features - scores_d_fake, feats_d_fake, _, feats_d_real = self.disc( - self.model_outputs_cache["model_outputs"], self.model_outputs_cache["waveform_seg"] - ) - - # compute losses - with autocast(enabled=True): # use float32 for the criterion - loss_dict = criterion[optimizer_idx]( - mel_output=self.model_outputs_cache["acoustic_model_outputs"].transpose(1, 2), - mel_target=batch["mel_input"], - mel_lens=batch["mel_lengths"], - dur_output=self.model_outputs_cache["dr_log_pred"], - dur_target=self.model_outputs_cache["dr_log_target"].detach(), - pitch_output=self.model_outputs_cache["pitch_pred"], - pitch_target=self.model_outputs_cache["pitch_target"], - energy_output=self.model_outputs_cache["energy_pred"], - energy_target=self.model_outputs_cache["energy_target"], - src_lens=batch["text_lengths"], - waveform=self.model_outputs_cache["waveform_seg"], - waveform_hat=self.model_outputs_cache["model_outputs"], - p_prosody_ref=self.model_outputs_cache["p_prosody_ref"], - p_prosody_pred=self.model_outputs_cache["p_prosody_pred"], - u_prosody_ref=self.model_outputs_cache["u_prosody_ref"], - u_prosody_pred=self.model_outputs_cache["u_prosody_pred"], - aligner_logprob=self.model_outputs_cache["aligner_logprob"], - aligner_hard=self.model_outputs_cache["aligner_mas"], - aligner_soft=self.model_outputs_cache["aligner_soft"], - binary_loss_weight=self.binary_loss_weight, - feats_fake=feats_d_fake, - feats_real=feats_d_real, - scores_fake=scores_d_fake, - spec_slice=mel_slice, - spec_slice_hat=mel_slice_hat, - skip_disc=not self.train_disc, - ) - - loss_dict["avg_text_length"] = batch["text_lengths"].float().mean() - loss_dict["avg_mel_length"] = batch["mel_lengths"].float().mean() - loss_dict["avg_text_batch_occupancy"] = ( - batch["text_lengths"].float() / batch["text_lengths"].float().max() - ).mean() - loss_dict["avg_mel_batch_occupancy"] = ( - batch["mel_lengths"].float() / batch["mel_lengths"].float().max() - ).mean() - - return self.model_outputs_cache, loss_dict - raise ValueError(" [!] Unexpected `optimizer_idx`.") - - def eval_step(self, batch: dict, criterion: nn.Module, optimizer_idx: int): - return self.train_step(batch, criterion, optimizer_idx) - - def _log(self, batch, outputs, name_prefix="train"): - figures, audios = {}, {} - - # encoder outputs - model_outputs = outputs[1]["acoustic_model_outputs"] - alignments = outputs[1]["alignments"] - mel_input = batch["mel_input"] - - pred_spec = model_outputs[0].data.cpu().numpy() - gt_spec = mel_input[0].data.cpu().numpy() - align_img = alignments[0].data.cpu().numpy() - - figures = { - "prediction": plot_spectrogram(pred_spec, None, output_fig=False), - "ground_truth": plot_spectrogram(gt_spec.T, None, output_fig=False), - "alignment": plot_alignment(align_img, output_fig=False), - } - - # plot pitch figures - pitch_avg = abs(outputs[1]["pitch_target"][0, 0].data.cpu().numpy()) - pitch_avg_hat = abs(outputs[1]["pitch_pred"][0, 0].data.cpu().numpy()) - chars = self.tokenizer.decode(batch["text_input"][0].data.cpu().numpy()) - pitch_figures = { - "pitch_ground_truth": plot_avg_pitch(pitch_avg, chars, output_fig=False), - "pitch_avg_predicted": plot_avg_pitch(pitch_avg_hat, chars, output_fig=False), - } - figures.update(pitch_figures) - - # plot energy figures - energy_avg = abs(outputs[1]["energy_target"][0, 0].data.cpu().numpy()) - energy_avg_hat = abs(outputs[1]["energy_pred"][0, 0].data.cpu().numpy()) - chars = self.tokenizer.decode(batch["text_input"][0].data.cpu().numpy()) - energy_figures = { - "energy_ground_truth": plot_avg_pitch(energy_avg, chars, output_fig=False), - "energy_avg_predicted": plot_avg_pitch(energy_avg_hat, chars, output_fig=False), - } - figures.update(energy_figures) - - # plot the attention mask computed from the predicted durations - alignments_hat = outputs[1]["alignments_dp"][0].data.cpu().numpy() - figures["alignment_hat"] = plot_alignment(alignments_hat.T, output_fig=False) - - # Sample audio - encoder_audio = mel_to_wav_numpy( - mel=db_to_amp_numpy(x=pred_spec.T, gain=1, base=None), mel_basis=self.mel_basis, **self.config.audio - ) - audios[f"{name_prefix}/encoder_audio"] = encoder_audio - - # vocoder outputs - y_hat = outputs[1]["model_outputs"] - y = outputs[1]["waveform_seg"] - - vocoder_figures = plot_results(y_hat=y_hat, y=y, ap=self.ap, name_prefix=name_prefix) - figures.update(vocoder_figures) - - sample_voice = y_hat[0].squeeze(0).detach().cpu().numpy() - audios[f"{name_prefix}/vocoder_audio"] = sample_voice - return figures, audios - - def train_log( - self, batch: dict, outputs: dict, logger: "Logger", assets: dict, steps: int - ): # pylint: disable=no-self-use, unused-argument - """Create visualizations and waveform examples. - - For example, here you can plot spectrograms and generate sample sample waveforms from these spectrograms to - be projected onto Tensorboard. - - Args: - batch (Dict): Model inputs used at the previous training step. - outputs (Dict): Model outputs generated at the previous training step. - - Returns: - Tuple[Dict, np.ndarray]: training plots and output waveform. - """ - figures, audios = self._log(batch=batch, outputs=outputs, name_prefix="vocoder/") - logger.train_figures(steps, figures) - logger.train_audios(steps, audios, self.ap.sample_rate) - - def eval_log(self, batch: dict, outputs: dict, logger: "Logger", assets: dict, steps: int) -> None: - figures, audios = self._log(batch=batch, outputs=outputs, name_prefix="vocoder/") - logger.eval_figures(steps, figures) - logger.eval_audios(steps, audios, self.ap.sample_rate) - - def get_aux_input_from_test_sentences(self, sentence_info): - if hasattr(self.config, "model_args"): - config = self.config.model_args - else: - config = self.config - - # extract speaker and language info - text, speaker_name, style_wav = None, None, None - - if isinstance(sentence_info, list): - if len(sentence_info) == 1: - text = sentence_info[0] - elif len(sentence_info) == 2: - text, speaker_name = sentence_info - elif len(sentence_info) == 3: - text, speaker_name, style_wav = sentence_info - else: - text = sentence_info - - # get speaker id/d_vector - speaker_id, d_vector = None, None - if hasattr(self, "speaker_manager"): - if config.use_d_vector_file: - if speaker_name is None: - d_vector = self.speaker_manager.get_random_embedding() - else: - d_vector = self.speaker_manager.get_mean_embedding(speaker_name, num_samples=None, randomize=False) - elif config.use_speaker_embedding: - if speaker_name is None: - speaker_id = self.speaker_manager.get_random_id() - else: - speaker_id = self.speaker_manager.name_to_id[speaker_name] - - return {"text": text, "speaker_id": speaker_id, "style_wav": style_wav, "d_vector": d_vector} - - def plot_outputs(self, text, wav, alignment, outputs): - figures = {} - pitch_avg_pred = outputs["pitch"].cpu() - energy_avg_pred = outputs["energy"].cpu() - spec = wav_to_mel( - y=torch.from_numpy(wav[None, :]), - n_fft=self.ap.fft_size, - sample_rate=self.ap.sample_rate, - num_mels=self.ap.num_mels, - hop_length=self.ap.hop_length, - win_length=self.ap.win_length, - fmin=self.ap.mel_fmin, - fmax=self.ap.mel_fmax, - center=False, - )[0].transpose(0, 1) - pitch = compute_f0( - x=wav[0], - sample_rate=self.ap.sample_rate, - hop_length=self.ap.hop_length, - pitch_fmax=self.ap.pitch_fmax, - ) - input_text = self.tokenizer.ids_to_text(self.tokenizer.text_to_ids(text, language="en")) - input_text = input_text.replace("", "_") - durations = outputs["durations"] - pitch_avg = average_over_durations(torch.from_numpy(pitch)[None, None, :], durations.cpu()) # [1, 1, n_frames] - pitch_avg_pred_denorm = (pitch_avg_pred * self.pitch_std) + self.pitch_mean - figures["alignment"] = plot_alignment(alignment.transpose(1, 2), output_fig=False) - figures["spectrogram"] = plot_spectrogram(spec) - figures["pitch_from_wav"] = plot_pitch(pitch, spec) - figures["pitch_avg_from_wav"] = plot_avg_pitch(pitch_avg.squeeze(), input_text) - figures["pitch_avg_pred"] = plot_avg_pitch(pitch_avg_pred_denorm.squeeze(), input_text) - figures["energy_avg_pred"] = plot_avg_pitch(energy_avg_pred.squeeze(), input_text) - return figures - - def synthesize( - self, - text: str, - speaker_id: str = None, - d_vector: torch.tensor = None, - pitch_transform=None, - **kwargs, - ): # pylint: disable=unused-argument - # TODO: add cloning support with ref_waveform - is_cuda = next(self.parameters()).is_cuda - - # convert text to sequence of token IDs - text_inputs = np.asarray( - self.tokenizer.text_to_ids(text, language=None), - dtype=np.int32, - ) - - # set speaker inputs - _speaker_id = None - if speaker_id is not None and self.args.use_speaker_embedding: - if isinstance(speaker_id, str) and self.args.use_speaker_embedding: - # get the speaker id for the speaker embedding layer - _speaker_id = self.speaker_manager.name_to_id[speaker_id] - _speaker_id = id_to_torch(_speaker_id, cuda=is_cuda) - - if speaker_id is not None and self.args.use_d_vector_file: - # get the average d_vector for the speaker - d_vector = self.speaker_manager.get_mean_embedding(speaker_id, num_samples=None, randomize=False) - d_vector = embedding_to_torch(d_vector, cuda=is_cuda) - - text_inputs = numpy_to_torch(text_inputs, torch.long, cuda=is_cuda) - text_inputs = text_inputs.unsqueeze(0) - - # synthesize voice - outputs = self.inference( - text_inputs, - aux_input={"d_vectors": d_vector, "speaker_ids": _speaker_id}, - pitch_transform=pitch_transform, - # energy_transform=energy_transform - ) - - # collect outputs - wav = outputs["model_outputs"][0].data.cpu().numpy() - alignments = outputs["alignments"] - return_dict = { - "wav": wav, - "alignments": alignments, - "text_inputs": text_inputs, - "outputs": outputs, - } - return return_dict - - def synthesize_with_gl(self, text: str, speaker_id, d_vector): - is_cuda = next(self.parameters()).is_cuda - - # convert text to sequence of token IDs - text_inputs = np.asarray( - self.tokenizer.text_to_ids(text, language=None), - dtype=np.int32, - ) - # pass tensors to backend - if speaker_id is not None: - speaker_id = id_to_torch(speaker_id, cuda=is_cuda) - - if d_vector is not None: - d_vector = embedding_to_torch(d_vector, cuda=is_cuda) - - text_inputs = numpy_to_torch(text_inputs, torch.long, cuda=is_cuda) - text_inputs = text_inputs.unsqueeze(0) - - # synthesize voice - outputs = self.inference_spec_decoder( - x=text_inputs, - aux_input={"d_vectors": d_vector, "speaker_ids": speaker_id}, - ) - - # collect outputs - S = outputs["model_outputs"].cpu().numpy()[0].T - S = db_to_amp_numpy(x=S, gain=1, base=None) - wav = mel_to_wav_numpy(mel=S, mel_basis=self.mel_basis, **self.config.audio) - alignments = outputs["alignments"] - return_dict = { - "wav": wav[None, :], - "alignments": alignments, - "text_inputs": text_inputs, - "outputs": outputs, - } - return return_dict - - @torch.no_grad() - def test_run(self, assets) -> Tuple[Dict, Dict]: - """Generic test run for `tts` models used by `Trainer`. - - You can override this for a different behaviour. - - Returns: - Tuple[Dict, Dict]: Test figures and audios to be projected to Tensorboard. - """ - print(" | > Synthesizing test sentences.") - test_audios = {} - test_figures = {} - test_sentences = self.config.test_sentences - for idx, s_info in enumerate(test_sentences): - aux_inputs = self.get_aux_input_from_test_sentences(s_info) - outputs = self.synthesize( - aux_inputs["text"], - config=self.config, - speaker_id=aux_inputs["speaker_id"], - d_vector=aux_inputs["d_vector"], - ) - outputs_gl = self.synthesize_with_gl( - aux_inputs["text"], - speaker_id=aux_inputs["speaker_id"], - d_vector=aux_inputs["d_vector"], - ) - # speaker_name = self.speaker_manager.speaker_names[aux_inputs["speaker_id"]] - test_audios["{}-audio".format(idx)] = outputs["wav"].T - test_audios["{}-audio_encoder".format(idx)] = outputs_gl["wav"].T - test_figures["{}-alignment".format(idx)] = plot_alignment(outputs["alignments"], output_fig=False) - return {"figures": test_figures, "audios": test_audios} - - def test_log( - self, outputs: dict, logger: "Logger", assets: dict, steps: int # pylint: disable=unused-argument - ) -> None: - logger.test_audios(steps, outputs["audios"], self.config.audio.sample_rate) - logger.test_figures(steps, outputs["figures"]) - - def format_batch(self, batch: Dict) -> Dict: - """Compute speaker, langugage IDs and d_vector for the batch if necessary.""" - speaker_ids = None - d_vectors = None - - # get numerical speaker ids from speaker names - if self.speaker_manager is not None and self.speaker_manager.speaker_names and self.args.use_speaker_embedding: - speaker_ids = [self.speaker_manager.name_to_id[sn] for sn in batch["speaker_names"]] - - if speaker_ids is not None: - speaker_ids = torch.LongTensor(speaker_ids) - batch["speaker_ids"] = speaker_ids - - # get d_vectors from audio file names - if self.speaker_manager is not None and self.speaker_manager.embeddings and self.args.use_d_vector_file: - d_vector_mapping = self.speaker_manager.embeddings - d_vectors = [d_vector_mapping[w]["embedding"] for w in batch["audio_unique_names"]] - d_vectors = torch.FloatTensor(d_vectors) - - batch["d_vectors"] = d_vectors - batch["speaker_ids"] = speaker_ids - return batch - - def format_batch_on_device(self, batch): - """Compute spectrograms on the device.""" - - ac = self.ap - - # compute spectrograms - batch["mel_input"] = wav_to_mel( - batch["waveform"], - hop_length=ac.hop_length, - win_length=ac.win_length, - n_fft=ac.fft_size, - num_mels=ac.num_mels, - sample_rate=ac.sample_rate, - fmin=ac.mel_fmin, - fmax=ac.mel_fmax, - center=False, - ) - - # TODO: Align pitch properly - # assert ( - # batch["pitch"].shape[2] == batch["mel_input"].shape[2] - # ), f"{batch['pitch'].shape[2]}, {batch['mel_input'].shape[2]}" - batch["pitch"] = batch["pitch"][:, :, : batch["mel_input"].shape[2]] if batch["pitch"] is not None else None - batch["mel_lengths"] = (batch["mel_input"].shape[2] * batch["waveform_rel_lens"]).int() - - # zero the padding frames - batch["mel_input"] = batch["mel_input"] * sequence_mask(batch["mel_lengths"]).unsqueeze(1) - - # format attn priors as we now the max mel length - # TODO: fix 1 diff b/w mel_lengths and attn_priors - - if self.config.use_attn_priors: - attn_priors_np = batch["attn_priors"] - - batch["attn_priors"] = torch.zeros( - batch["mel_input"].shape[0], - batch["mel_lengths"].max(), - batch["text_lengths"].max(), - device=batch["mel_input"].device, - ) - - for i in range(batch["mel_input"].shape[0]): - batch["attn_priors"][i, : attn_priors_np[i].shape[0], : attn_priors_np[i].shape[1]] = torch.from_numpy( - attn_priors_np[i] - ) - - batch["energy"] = None - batch["energy"] = wav_to_energy( # [B, 1, T_max2] - batch["waveform"], - hop_length=ac.hop_length, - win_length=ac.win_length, - n_fft=ac.fft_size, - center=False, - ) - batch["energy"] = self.energy_scaler(batch["energy"]) - return batch - - def get_sampler(self, config: Coqpit, dataset: TTSDataset, num_gpus=1): - weights = None - data_items = dataset.samples - if getattr(config, "use_weighted_sampler", False): - for attr_name, alpha in config.weighted_sampler_attrs.items(): - print(f" > Using weighted sampler for attribute '{attr_name}' with alpha '{alpha}'") - multi_dict = config.weighted_sampler_multipliers.get(attr_name, None) - print(multi_dict) - weights, attr_names, attr_weights = get_attribute_balancer_weights( - attr_name=attr_name, items=data_items, multi_dict=multi_dict - ) - weights = weights * alpha - print(f" > Attribute weights for '{attr_names}' \n | > {attr_weights}") - - if weights is not None: - sampler = WeightedRandomSampler(weights, len(weights)) - else: - sampler = None - # sampler for DDP - if sampler is None: - sampler = DistributedSampler(dataset) if num_gpus > 1 else None - else: # If a sampler is already defined use this sampler and DDP sampler together - sampler = DistributedSamplerWrapper(sampler) if num_gpus > 1 else sampler - return sampler - - def get_data_loader( - self, - config: Coqpit, - assets: Dict, - is_eval: bool, - samples: Union[List[Dict], List[List]], - verbose: bool, - num_gpus: int, - rank: int = None, - ) -> "DataLoader": - if is_eval and not config.run_eval: - loader = None - else: - # init dataloader - dataset = ForwardTTSE2eDataset( - samples=samples, - ap=self.ap, - batch_group_size=0 if is_eval else config.batch_group_size * config.batch_size, - min_text_len=config.min_text_len, - max_text_len=config.max_text_len, - min_audio_len=config.min_audio_len, - max_audio_len=config.max_audio_len, - phoneme_cache_path=config.phoneme_cache_path, - precompute_num_workers=config.precompute_num_workers, - compute_f0=config.compute_f0, - f0_cache_path=config.f0_cache_path, - attn_prior_cache_path=config.attn_prior_cache_path if config.use_attn_priors else None, - verbose=verbose, - tokenizer=self.tokenizer, - start_by_longest=config.start_by_longest, - ) - - # wait all the DDP process to be ready - if num_gpus > 1: - dist.barrier() - - # sort input sequences ascendingly by length - dataset.preprocess_samples() - - # get samplers - sampler = self.get_sampler(config, dataset, num_gpus) - - loader = DataLoader( - dataset, - batch_size=config.eval_batch_size if is_eval else config.batch_size, - shuffle=False, # shuffle is done in the dataset. - drop_last=False, # setting this False might cause issues in AMP training. - sampler=sampler, - collate_fn=dataset.collate_fn, - num_workers=config.num_eval_loader_workers if is_eval else config.num_loader_workers, - pin_memory=True, - ) - - # get pitch mean and std - self.pitch_mean = dataset.f0_dataset.mean - self.pitch_std = dataset.f0_dataset.std - return loader - - def get_criterion(self): - return [VitsDiscriminatorLoss(self.config), DelightfulTTSLoss(self.config)] - - def get_optimizer(self) -> List: - """Initiate and return the GAN optimizers based on the config parameters. - It returnes 2 optimizers in a list. First one is for the generator and the second one is for the discriminator. - Returns: - List: optimizers. - """ - optimizer_disc = get_optimizer( - self.config.optimizer, self.config.optimizer_params, self.config.lr_disc, self.disc - ) - gen_parameters = chain(params for k, params in self.named_parameters() if not k.startswith("disc.")) - optimizer_gen = get_optimizer( - self.config.optimizer, self.config.optimizer_params, self.config.lr_gen, parameters=gen_parameters - ) - return [optimizer_disc, optimizer_gen] - - def get_lr(self) -> List: - """Set the initial learning rates for each optimizer. - - Returns: - List: learning rates for each optimizer. - """ - return [self.config.lr_disc, self.config.lr_gen] - - def get_scheduler(self, optimizer) -> List: - """Set the schedulers for each optimizer. - - Args: - optimizer (List[`torch.optim.Optimizer`]): List of optimizers. - - Returns: - List: Schedulers, one for each optimizer. - """ - scheduler_D = get_scheduler(self.config.lr_scheduler_gen, self.config.lr_scheduler_gen_params, optimizer[0]) - scheduler_G = get_scheduler(self.config.lr_scheduler_disc, self.config.lr_scheduler_disc_params, optimizer[1]) - return [scheduler_D, scheduler_G] - - def on_epoch_end(self, trainer): # pylint: disable=unused-argument - # stop updating mean and var - # TODO: do the same for F0 - self.energy_scaler.eval() - - @staticmethod - def init_from_config( - config: "DelightfulTTSConfig", samples: Union[List[List], List[Dict]] = None, verbose=False - ): # pylint: disable=unused-argument - """Initiate model from config - - Args: - config (ForwardTTSE2eConfig): Model config. - samples (Union[List[List], List[Dict]]): Training samples to parse speaker ids for training. - Defaults to None. - """ - - tokenizer, new_config = TTSTokenizer.init_from_config(config) - speaker_manager = SpeakerManager.init_from_config(config.model_args, samples) - ap = AudioProcessor.init_from_config(config=config) - return DelightfulTTS(config=new_config, tokenizer=tokenizer, speaker_manager=speaker_manager, ap=ap) - - def load_checkpoint(self, config, checkpoint_path, eval=False): - """Load model from a checkpoint created by the 👟""" - # pylint: disable=unused-argument, redefined-builtin - state = load_fsspec(checkpoint_path, map_location=torch.device("cpu")) - self.load_state_dict(state["model"]) - if eval: - self.eval() - assert not self.training - - def get_state_dict(self): - """Custom state dict of the model with all the necessary components for inference.""" - save_state = {"config": self.config.to_dict(), "args": self.args.to_dict(), "model": self.state_dict} - - if hasattr(self, "emb_g"): - save_state["speaker_ids"] = self.speaker_manager.speaker_names - - if self.args.use_d_vector_file: - # TODO: implement saving of d_vectors - ... - return save_state - - def save(self, config, checkpoint_path): - """Save model to a file.""" - save_state = self.get_state_dict(config, checkpoint_path) # pylint: disable=too-many-function-args - save_state["pitch_mean"] = self.pitch_mean - save_state["pitch_std"] = self.pitch_std - torch.save(save_state, checkpoint_path) - - def on_train_step_start(self, trainer) -> None: - """Enable the discriminator training based on `steps_to_start_discriminator` - - Args: - trainer (Trainer): Trainer object. - """ - self.binary_loss_weight = min(trainer.epochs_done / self.config.binary_loss_warmup_epochs, 1.0) * 1.0 - self.train_disc = ( # pylint: disable=attribute-defined-outside-init - trainer.total_steps_done >= self.config.steps_to_start_discriminator - ) - - -class DelightfulTTSLoss(nn.Module): - def __init__(self, config): - super().__init__() - - self.mse_loss = nn.MSELoss() - self.mae_loss = nn.L1Loss() - self.forward_sum_loss = ForwardSumLoss() - self.multi_scale_stft_loss = MultiScaleSTFTLoss(**config.multi_scale_stft_loss_params) - - self.mel_loss_alpha = config.mel_loss_alpha - self.aligner_loss_alpha = config.aligner_loss_alpha - self.pitch_loss_alpha = config.pitch_loss_alpha - self.energy_loss_alpha = config.energy_loss_alpha - self.u_prosody_loss_alpha = config.u_prosody_loss_alpha - self.p_prosody_loss_alpha = config.p_prosody_loss_alpha - self.dur_loss_alpha = config.dur_loss_alpha - self.char_dur_loss_alpha = config.char_dur_loss_alpha - self.binary_alignment_loss_alpha = config.binary_align_loss_alpha - - self.vocoder_mel_loss_alpha = config.vocoder_mel_loss_alpha - self.feat_loss_alpha = config.feat_loss_alpha - self.gen_loss_alpha = config.gen_loss_alpha - self.multi_scale_stft_loss_alpha = config.multi_scale_stft_loss_alpha - - @staticmethod - def _binary_alignment_loss(alignment_hard, alignment_soft): - """Binary loss that forces soft alignments to match the hard alignments as - explained in `https://arxiv.org/pdf/2108.10447.pdf`. - """ - log_sum = torch.log(torch.clamp(alignment_soft[alignment_hard == 1], min=1e-12)).sum() - return -log_sum / alignment_hard.sum() - - @staticmethod - def feature_loss(feats_real, feats_generated): - loss = 0 - for dr, dg in zip(feats_real, feats_generated): - for rl, gl in zip(dr, dg): - rl = rl.float().detach() - gl = gl.float() - loss += torch.mean(torch.abs(rl - gl)) - return loss * 2 - - @staticmethod - def generator_loss(scores_fake): - loss = 0 - gen_losses = [] - for dg in scores_fake: - dg = dg.float() - l = torch.mean((1 - dg) ** 2) - gen_losses.append(l) - loss += l - - return loss, gen_losses - - def forward( - self, - mel_output, - mel_target, - mel_lens, - dur_output, - dur_target, - pitch_output, - pitch_target, - energy_output, - energy_target, - src_lens, - waveform, - waveform_hat, - p_prosody_ref, - p_prosody_pred, - u_prosody_ref, - u_prosody_pred, - aligner_logprob, - aligner_hard, - aligner_soft, - binary_loss_weight=None, - feats_fake=None, - feats_real=None, - scores_fake=None, - spec_slice=None, - spec_slice_hat=None, - skip_disc=False, - ): - """ - Shapes: - - mel_output: :math:`(B, C_mel, T_mel)` - - mel_target: :math:`(B, C_mel, T_mel)` - - mel_lens: :math:`(B)` - - dur_output: :math:`(B, T_src)` - - dur_target: :math:`(B, T_src)` - - pitch_output: :math:`(B, 1, T_src)` - - pitch_target: :math:`(B, 1, T_src)` - - energy_output: :math:`(B, 1, T_src)` - - energy_target: :math:`(B, 1, T_src)` - - src_lens: :math:`(B)` - - waveform: :math:`(B, 1, T_wav)` - - waveform_hat: :math:`(B, 1, T_wav)` - - p_prosody_ref: :math:`(B, T_src, 4)` - - p_prosody_pred: :math:`(B, T_src, 4)` - - u_prosody_ref: :math:`(B, 1, 256) - - u_prosody_pred: :math:`(B, 1, 256) - - aligner_logprob: :math:`(B, 1, T_mel, T_src)` - - aligner_hard: :math:`(B, T_mel, T_src)` - - aligner_soft: :math:`(B, T_mel, T_src)` - - spec_slice: :math:`(B, C_mel, T_mel)` - - spec_slice_hat: :math:`(B, C_mel, T_mel)` - """ - loss_dict = {} - src_mask = sequence_mask(src_lens).to(mel_output.device) # (B, T_src) - mel_mask = sequence_mask(mel_lens).to(mel_output.device) # (B, T_mel) - - dur_target.requires_grad = False - mel_target.requires_grad = False - pitch_target.requires_grad = False - - masked_mel_predictions = mel_output.masked_select(mel_mask[:, None]) - mel_targets = mel_target.masked_select(mel_mask[:, None]) - mel_loss = self.mae_loss(masked_mel_predictions, mel_targets) - - p_prosody_ref = p_prosody_ref.detach() - p_prosody_loss = 0.5 * self.mae_loss( - p_prosody_ref.masked_select(src_mask.unsqueeze(-1)), - p_prosody_pred.masked_select(src_mask.unsqueeze(-1)), - ) - - u_prosody_ref = u_prosody_ref.detach() - u_prosody_loss = 0.5 * self.mae_loss(u_prosody_ref, u_prosody_pred) - - duration_loss = self.mse_loss(dur_output, dur_target) - - pitch_output = pitch_output.masked_select(src_mask[:, None]) - pitch_target = pitch_target.masked_select(src_mask[:, None]) - pitch_loss = self.mse_loss(pitch_output, pitch_target) - - energy_output = energy_output.masked_select(src_mask[:, None]) - energy_target = energy_target.masked_select(src_mask[:, None]) - energy_loss = self.mse_loss(energy_output, energy_target) - - forward_sum_loss = self.forward_sum_loss(aligner_logprob, src_lens, mel_lens) - - total_loss = ( - (mel_loss * self.mel_loss_alpha) - + (duration_loss * self.dur_loss_alpha) - + (u_prosody_loss * self.u_prosody_loss_alpha) - + (p_prosody_loss * self.p_prosody_loss_alpha) - + (pitch_loss * self.pitch_loss_alpha) - + (energy_loss * self.energy_loss_alpha) - + (forward_sum_loss * self.aligner_loss_alpha) - ) - - if self.binary_alignment_loss_alpha > 0 and aligner_hard is not None: - binary_alignment_loss = self._binary_alignment_loss(aligner_hard, aligner_soft) - total_loss = total_loss + self.binary_alignment_loss_alpha * binary_alignment_loss * binary_loss_weight - if binary_loss_weight: - loss_dict["loss_binary_alignment"] = ( - self.binary_alignment_loss_alpha * binary_alignment_loss * binary_loss_weight - ) - else: - loss_dict["loss_binary_alignment"] = self.binary_alignment_loss_alpha * binary_alignment_loss - - loss_dict["loss_aligner"] = self.aligner_loss_alpha * forward_sum_loss - loss_dict["loss_mel"] = self.mel_loss_alpha * mel_loss - loss_dict["loss_duration"] = self.dur_loss_alpha * duration_loss - loss_dict["loss_u_prosody"] = self.u_prosody_loss_alpha * u_prosody_loss - loss_dict["loss_p_prosody"] = self.p_prosody_loss_alpha * p_prosody_loss - loss_dict["loss_pitch"] = self.pitch_loss_alpha * pitch_loss - loss_dict["loss_energy"] = self.energy_loss_alpha * energy_loss - loss_dict["loss"] = total_loss - - # vocoder losses - if not skip_disc: - loss_feat = self.feature_loss(feats_real=feats_real, feats_generated=feats_fake) * self.feat_loss_alpha - loss_gen = self.generator_loss(scores_fake=scores_fake)[0] * self.gen_loss_alpha - loss_dict["vocoder_loss_feat"] = loss_feat - loss_dict["vocoder_loss_gen"] = loss_gen - loss_dict["loss"] = loss_dict["loss"] + loss_feat + loss_gen - - loss_mel = torch.nn.functional.l1_loss(spec_slice, spec_slice_hat) * self.vocoder_mel_loss_alpha - loss_stft_mg, loss_stft_sc = self.multi_scale_stft_loss(y_hat=waveform_hat, y=waveform) - loss_stft_mg = loss_stft_mg * self.multi_scale_stft_loss_alpha - loss_stft_sc = loss_stft_sc * self.multi_scale_stft_loss_alpha - - loss_dict["vocoder_loss_mel"] = loss_mel - loss_dict["vocoder_loss_stft_mg"] = loss_stft_mg - loss_dict["vocoder_loss_stft_sc"] = loss_stft_sc - - loss_dict["loss"] = loss_dict["loss"] + loss_mel + loss_stft_sc + loss_stft_mg - return loss_dict diff --git a/spaces/artificialguybr/video-dubbing/Wav2Lip/models/conv.py b/spaces/artificialguybr/video-dubbing/Wav2Lip/models/conv.py deleted file mode 100644 index ed83da00cb199e027ef217fd360352d91a7891ff..0000000000000000000000000000000000000000 --- a/spaces/artificialguybr/video-dubbing/Wav2Lip/models/conv.py +++ /dev/null @@ -1,44 +0,0 @@ -import torch -from torch import nn -from torch.nn import functional as F - -class Conv2d(nn.Module): - def __init__(self, cin, cout, kernel_size, stride, padding, residual=False, *args, **kwargs): - super().__init__(*args, **kwargs) - self.conv_block = nn.Sequential( - nn.Conv2d(cin, cout, kernel_size, stride, padding), - nn.BatchNorm2d(cout) - ) - self.act = nn.ReLU() - self.residual = residual - - def forward(self, x): - out = self.conv_block(x) - if self.residual: - out += x - return self.act(out) - -class nonorm_Conv2d(nn.Module): - def __init__(self, cin, cout, kernel_size, stride, padding, residual=False, *args, **kwargs): - super().__init__(*args, **kwargs) - self.conv_block = nn.Sequential( - nn.Conv2d(cin, cout, kernel_size, stride, padding), - ) - self.act = nn.LeakyReLU(0.01, inplace=True) - - def forward(self, x): - out = self.conv_block(x) - return self.act(out) - -class Conv2dTranspose(nn.Module): - def __init__(self, cin, cout, kernel_size, stride, padding, output_padding=0, *args, **kwargs): - super().__init__(*args, **kwargs) - self.conv_block = nn.Sequential( - nn.ConvTranspose2d(cin, cout, kernel_size, stride, padding, output_padding), - nn.BatchNorm2d(cout) - ) - self.act = nn.ReLU() - - def forward(self, x): - out = self.conv_block(x) - return self.act(out) diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Crypto/SelfTest/Cipher/common.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Crypto/SelfTest/Cipher/common.py deleted file mode 100644 index c5bc755abb555148ab7c46f1e82fcfeacac31366..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Crypto/SelfTest/Cipher/common.py +++ /dev/null @@ -1,510 +0,0 @@ -# -*- coding: utf-8 -*- -# -# SelfTest/Hash/common.py: Common code for Crypto.SelfTest.Hash -# -# Written in 2008 by Dwayne C. Litzenberger -# -# =================================================================== -# The contents of this file are dedicated to the public domain. To -# the extent that dedication to the public domain is not available, -# everyone is granted a worldwide, perpetual, royalty-free, -# non-exclusive license to exercise all rights associated with the -# contents of this file for any purpose whatsoever. -# No rights are reserved. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS -# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -# =================================================================== - -"""Self-testing for PyCrypto hash modules""" - -import unittest -from binascii import a2b_hex, b2a_hex, hexlify - -from Crypto.Util.py3compat import b -from Crypto.Util.strxor import strxor_c - -class _NoDefault: pass # sentinel object -def _extract(d, k, default=_NoDefault): - """Get an item from a dictionary, and remove it from the dictionary.""" - try: - retval = d[k] - except KeyError: - if default is _NoDefault: - raise - return default - del d[k] - return retval - -# Generic cipher test case -class CipherSelfTest(unittest.TestCase): - - def __init__(self, module, params): - unittest.TestCase.__init__(self) - self.module = module - - # Extract the parameters - params = params.copy() - self.description = _extract(params, 'description') - self.key = b(_extract(params, 'key')) - self.plaintext = b(_extract(params, 'plaintext')) - self.ciphertext = b(_extract(params, 'ciphertext')) - self.module_name = _extract(params, 'module_name', None) - self.assoc_data = _extract(params, 'assoc_data', None) - self.mac = _extract(params, 'mac', None) - if self.assoc_data: - self.mac = b(self.mac) - - mode = _extract(params, 'mode', None) - self.mode_name = str(mode) - - if mode is not None: - # Block cipher - self.mode = getattr(self.module, "MODE_" + mode) - - self.iv = _extract(params, 'iv', None) - if self.iv is None: - self.iv = _extract(params, 'nonce', None) - if self.iv is not None: - self.iv = b(self.iv) - - else: - # Stream cipher - self.mode = None - self.iv = _extract(params, 'iv', None) - if self.iv is not None: - self.iv = b(self.iv) - - self.extra_params = params - - def shortDescription(self): - return self.description - - def _new(self): - params = self.extra_params.copy() - key = a2b_hex(self.key) - - old_style = [] - if self.mode is not None: - old_style = [ self.mode ] - if self.iv is not None: - old_style += [ a2b_hex(self.iv) ] - - return self.module.new(key, *old_style, **params) - - def isMode(self, name): - if not hasattr(self.module, "MODE_"+name): - return False - return self.mode == getattr(self.module, "MODE_"+name) - - def runTest(self): - plaintext = a2b_hex(self.plaintext) - ciphertext = a2b_hex(self.ciphertext) - assoc_data = [] - if self.assoc_data: - assoc_data = [ a2b_hex(b(x)) for x in self.assoc_data] - - ct = None - pt = None - - # - # Repeat the same encryption or decryption twice and verify - # that the result is always the same - # - for i in range(2): - cipher = self._new() - decipher = self._new() - - # Only AEAD modes - for comp in assoc_data: - cipher.update(comp) - decipher.update(comp) - - ctX = b2a_hex(cipher.encrypt(plaintext)) - ptX = b2a_hex(decipher.decrypt(ciphertext)) - - if ct: - self.assertEqual(ct, ctX) - self.assertEqual(pt, ptX) - ct, pt = ctX, ptX - - self.assertEqual(self.ciphertext, ct) # encrypt - self.assertEqual(self.plaintext, pt) # decrypt - - if self.mac: - mac = b2a_hex(cipher.digest()) - self.assertEqual(self.mac, mac) - decipher.verify(a2b_hex(self.mac)) - -class CipherStreamingSelfTest(CipherSelfTest): - - def shortDescription(self): - desc = self.module_name - if self.mode is not None: - desc += " in %s mode" % (self.mode_name,) - return "%s should behave like a stream cipher" % (desc,) - - def runTest(self): - plaintext = a2b_hex(self.plaintext) - ciphertext = a2b_hex(self.ciphertext) - - # The cipher should work like a stream cipher - - # Test counter mode encryption, 3 bytes at a time - ct3 = [] - cipher = self._new() - for i in range(0, len(plaintext), 3): - ct3.append(cipher.encrypt(plaintext[i:i+3])) - ct3 = b2a_hex(b("").join(ct3)) - self.assertEqual(self.ciphertext, ct3) # encryption (3 bytes at a time) - - # Test counter mode decryption, 3 bytes at a time - pt3 = [] - cipher = self._new() - for i in range(0, len(ciphertext), 3): - pt3.append(cipher.encrypt(ciphertext[i:i+3])) - # PY3K: This is meant to be text, do not change to bytes (data) - pt3 = b2a_hex(b("").join(pt3)) - self.assertEqual(self.plaintext, pt3) # decryption (3 bytes at a time) - - -class RoundtripTest(unittest.TestCase): - def __init__(self, module, params): - from Crypto import Random - unittest.TestCase.__init__(self) - self.module = module - self.iv = Random.get_random_bytes(module.block_size) - self.key = b(params['key']) - self.plaintext = 100 * b(params['plaintext']) - self.module_name = params.get('module_name', None) - - def shortDescription(self): - return """%s .decrypt() output of .encrypt() should not be garbled""" % (self.module_name,) - - def runTest(self): - - ## ECB mode - mode = self.module.MODE_ECB - encryption_cipher = self.module.new(a2b_hex(self.key), mode) - ciphertext = encryption_cipher.encrypt(self.plaintext) - decryption_cipher = self.module.new(a2b_hex(self.key), mode) - decrypted_plaintext = decryption_cipher.decrypt(ciphertext) - self.assertEqual(self.plaintext, decrypted_plaintext) - - -class IVLengthTest(unittest.TestCase): - def __init__(self, module, params): - unittest.TestCase.__init__(self) - self.module = module - self.key = b(params['key']) - - def shortDescription(self): - return "Check that all modes except MODE_ECB and MODE_CTR require an IV of the proper length" - - def runTest(self): - self.assertRaises(TypeError, self.module.new, a2b_hex(self.key), - self.module.MODE_ECB, b("")) - - def _dummy_counter(self): - return "\0" * self.module.block_size - - -class NoDefaultECBTest(unittest.TestCase): - def __init__(self, module, params): - unittest.TestCase.__init__(self) - self.module = module - self.key = b(params['key']) - - def runTest(self): - self.assertRaises(TypeError, self.module.new, a2b_hex(self.key)) - - -class BlockSizeTest(unittest.TestCase): - def __init__(self, module, params): - unittest.TestCase.__init__(self) - self.module = module - self.key = a2b_hex(b(params['key'])) - - def runTest(self): - cipher = self.module.new(self.key, self.module.MODE_ECB) - self.assertEqual(cipher.block_size, self.module.block_size) - - -class ByteArrayTest(unittest.TestCase): - """Verify we can use bytearray's for encrypting and decrypting""" - - def __init__(self, module, params): - unittest.TestCase.__init__(self) - self.module = module - - # Extract the parameters - params = params.copy() - self.description = _extract(params, 'description') - self.key = b(_extract(params, 'key')) - self.plaintext = b(_extract(params, 'plaintext')) - self.ciphertext = b(_extract(params, 'ciphertext')) - self.module_name = _extract(params, 'module_name', None) - self.assoc_data = _extract(params, 'assoc_data', None) - self.mac = _extract(params, 'mac', None) - if self.assoc_data: - self.mac = b(self.mac) - - mode = _extract(params, 'mode', None) - self.mode_name = str(mode) - - if mode is not None: - # Block cipher - self.mode = getattr(self.module, "MODE_" + mode) - - self.iv = _extract(params, 'iv', None) - if self.iv is None: - self.iv = _extract(params, 'nonce', None) - if self.iv is not None: - self.iv = b(self.iv) - else: - # Stream cipher - self.mode = None - self.iv = _extract(params, 'iv', None) - if self.iv is not None: - self.iv = b(self.iv) - - self.extra_params = params - - def _new(self): - params = self.extra_params.copy() - key = a2b_hex(self.key) - - old_style = [] - if self.mode is not None: - old_style = [ self.mode ] - if self.iv is not None: - old_style += [ a2b_hex(self.iv) ] - - return self.module.new(key, *old_style, **params) - - def runTest(self): - - plaintext = a2b_hex(self.plaintext) - ciphertext = a2b_hex(self.ciphertext) - assoc_data = [] - if self.assoc_data: - assoc_data = [ bytearray(a2b_hex(b(x))) for x in self.assoc_data] - - cipher = self._new() - decipher = self._new() - - # Only AEAD modes - for comp in assoc_data: - cipher.update(comp) - decipher.update(comp) - - ct = b2a_hex(cipher.encrypt(bytearray(plaintext))) - pt = b2a_hex(decipher.decrypt(bytearray(ciphertext))) - - self.assertEqual(self.ciphertext, ct) # encrypt - self.assertEqual(self.plaintext, pt) # decrypt - - if self.mac: - mac = b2a_hex(cipher.digest()) - self.assertEqual(self.mac, mac) - decipher.verify(bytearray(a2b_hex(self.mac))) - - -class MemoryviewTest(unittest.TestCase): - """Verify we can use memoryviews for encrypting and decrypting""" - - def __init__(self, module, params): - unittest.TestCase.__init__(self) - self.module = module - - # Extract the parameters - params = params.copy() - self.description = _extract(params, 'description') - self.key = b(_extract(params, 'key')) - self.plaintext = b(_extract(params, 'plaintext')) - self.ciphertext = b(_extract(params, 'ciphertext')) - self.module_name = _extract(params, 'module_name', None) - self.assoc_data = _extract(params, 'assoc_data', None) - self.mac = _extract(params, 'mac', None) - if self.assoc_data: - self.mac = b(self.mac) - - mode = _extract(params, 'mode', None) - self.mode_name = str(mode) - - if mode is not None: - # Block cipher - self.mode = getattr(self.module, "MODE_" + mode) - - self.iv = _extract(params, 'iv', None) - if self.iv is None: - self.iv = _extract(params, 'nonce', None) - if self.iv is not None: - self.iv = b(self.iv) - else: - # Stream cipher - self.mode = None - self.iv = _extract(params, 'iv', None) - if self.iv is not None: - self.iv = b(self.iv) - - self.extra_params = params - - def _new(self): - params = self.extra_params.copy() - key = a2b_hex(self.key) - - old_style = [] - if self.mode is not None: - old_style = [ self.mode ] - if self.iv is not None: - old_style += [ a2b_hex(self.iv) ] - - return self.module.new(key, *old_style, **params) - - def runTest(self): - - plaintext = a2b_hex(self.plaintext) - ciphertext = a2b_hex(self.ciphertext) - assoc_data = [] - if self.assoc_data: - assoc_data = [ memoryview(a2b_hex(b(x))) for x in self.assoc_data] - - cipher = self._new() - decipher = self._new() - - # Only AEAD modes - for comp in assoc_data: - cipher.update(comp) - decipher.update(comp) - - ct = b2a_hex(cipher.encrypt(memoryview(plaintext))) - pt = b2a_hex(decipher.decrypt(memoryview(ciphertext))) - - self.assertEqual(self.ciphertext, ct) # encrypt - self.assertEqual(self.plaintext, pt) # decrypt - - if self.mac: - mac = b2a_hex(cipher.digest()) - self.assertEqual(self.mac, mac) - decipher.verify(memoryview(a2b_hex(self.mac))) - - -def make_block_tests(module, module_name, test_data, additional_params=dict()): - tests = [] - extra_tests_added = False - for i in range(len(test_data)): - row = test_data[i] - - # Build the "params" dictionary with - # - plaintext - # - ciphertext - # - key - # - mode (default is ECB) - # - (optionally) description - # - (optionally) any other parameter that this cipher mode requires - params = {} - if len(row) == 3: - (params['plaintext'], params['ciphertext'], params['key']) = row - elif len(row) == 4: - (params['plaintext'], params['ciphertext'], params['key'], params['description']) = row - elif len(row) == 5: - (params['plaintext'], params['ciphertext'], params['key'], params['description'], extra_params) = row - params.update(extra_params) - else: - raise AssertionError("Unsupported tuple size %d" % (len(row),)) - - if not "mode" in params: - params["mode"] = "ECB" - - # Build the display-name for the test - p2 = params.copy() - p_key = _extract(p2, 'key') - p_plaintext = _extract(p2, 'plaintext') - p_ciphertext = _extract(p2, 'ciphertext') - p_mode = _extract(p2, 'mode') - p_description = _extract(p2, 'description', None) - - if p_description is not None: - description = p_description - elif p_mode == 'ECB' and not p2: - description = "p=%s, k=%s" % (p_plaintext, p_key) - else: - description = "p=%s, k=%s, %r" % (p_plaintext, p_key, p2) - name = "%s #%d: %s" % (module_name, i+1, description) - params['description'] = name - params['module_name'] = module_name - params.update(additional_params) - - # Add extra test(s) to the test suite before the current test - if not extra_tests_added: - tests += [ - RoundtripTest(module, params), - IVLengthTest(module, params), - NoDefaultECBTest(module, params), - ByteArrayTest(module, params), - BlockSizeTest(module, params), - ] - extra_tests_added = True - - # Add the current test to the test suite - tests.append(CipherSelfTest(module, params)) - - return tests - -def make_stream_tests(module, module_name, test_data): - tests = [] - extra_tests_added = False - for i in range(len(test_data)): - row = test_data[i] - - # Build the "params" dictionary - params = {} - if len(row) == 3: - (params['plaintext'], params['ciphertext'], params['key']) = row - elif len(row) == 4: - (params['plaintext'], params['ciphertext'], params['key'], params['description']) = row - elif len(row) == 5: - (params['plaintext'], params['ciphertext'], params['key'], params['description'], extra_params) = row - params.update(extra_params) - else: - raise AssertionError("Unsupported tuple size %d" % (len(row),)) - - # Build the display-name for the test - p2 = params.copy() - p_key = _extract(p2, 'key') - p_plaintext = _extract(p2, 'plaintext') - p_ciphertext = _extract(p2, 'ciphertext') - p_description = _extract(p2, 'description', None) - - if p_description is not None: - description = p_description - elif not p2: - description = "p=%s, k=%s" % (p_plaintext, p_key) - else: - description = "p=%s, k=%s, %r" % (p_plaintext, p_key, p2) - name = "%s #%d: %s" % (module_name, i+1, description) - params['description'] = name - params['module_name'] = module_name - - # Add extra test(s) to the test suite before the current test - if not extra_tests_added: - tests += [ - ByteArrayTest(module, params), - ] - - tests.append(MemoryviewTest(module, params)) - extra_tests_added = True - - # Add the test to the test suite - tests.append(CipherSelfTest(module, params)) - tests.append(CipherStreamingSelfTest(module, params)) - return tests - -# vim:set ts=4 sw=4 sts=4 expandtab: diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Cython/Plex/DFA.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Cython/Plex/DFA.py deleted file mode 100644 index 76324621fcaec820d0d561d2f1beae6f614451d9..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Cython/Plex/DFA.py +++ /dev/null @@ -1,164 +0,0 @@ -#======================================================================= -# -# Python Lexical Analyser -# -# Converting NFA to DFA -# -#======================================================================= - -from __future__ import absolute_import - -from . import Machines -from .Machines import LOWEST_PRIORITY -from .Transitions import TransitionMap - - -def nfa_to_dfa(old_machine, debug=None): - """ - Given a nondeterministic Machine, return a new equivalent - Machine which is deterministic. - """ - # We build a new machine whose states correspond to sets of states - # in the old machine. Initially we add a new state corresponding to - # the epsilon-closure of each initial old state. Then we give transitions - # to each new state which are the union of all transitions out of any - # of the corresponding old states. The new state reached on a given - # character is the one corresponding to the set of states reachable - # on that character from any of the old states. As new combinations of - # old states are created, new states are added as needed until closure - # is reached. - new_machine = Machines.FastMachine() - state_map = StateMap(new_machine) - # Seed the process using the initial states of the old machine. - # Make the corresponding new states into initial states of the new - # machine with the same names. - for (key, old_state) in old_machine.initial_states.items(): - new_state = state_map.old_to_new(epsilon_closure(old_state)) - new_machine.make_initial_state(key, new_state) - # Tricky bit here: we add things to the end of this list while we're - # iterating over it. The iteration stops when closure is achieved. - for new_state in new_machine.states: - transitions = TransitionMap() - for old_state in state_map.new_to_old(new_state): - for event, old_target_states in old_state.transitions.items(): - if event and old_target_states: - transitions.add_set(event, set_epsilon_closure(old_target_states)) - for event, old_states in transitions.items(): - new_machine.add_transitions(new_state, event, state_map.old_to_new(old_states)) - if debug: - debug.write("\n===== State Mapping =====\n") - state_map.dump(debug) - return new_machine - - -def set_epsilon_closure(state_set): - """ - Given a set of states, return the union of the epsilon - closures of its member states. - """ - result = {} - for state1 in state_set: - for state2 in epsilon_closure(state1): - result[state2] = 1 - return result - - -def epsilon_closure(state): - """ - Return the set of states reachable from the given state - by epsilon moves. - """ - # Cache the result - result = state.epsilon_closure - if result is None: - result = {} - state.epsilon_closure = result - add_to_epsilon_closure(result, state) - return result - - -def add_to_epsilon_closure(state_set, state): - """ - Recursively add to |state_set| states reachable from the given state - by epsilon moves. - """ - if not state_set.get(state, 0): - state_set[state] = 1 - state_set_2 = state.transitions.get_epsilon() - if state_set_2: - for state2 in state_set_2: - add_to_epsilon_closure(state_set, state2) - - -class StateMap(object): - """ - Helper class used by nfa_to_dfa() to map back and forth between - sets of states from the old machine and states of the new machine. - """ - new_machine = None # Machine - old_to_new_dict = None # {(old_state,...) : new_state} - new_to_old_dict = None # {id(new_state) : old_state_set} - - def __init__(self, new_machine): - self.new_machine = new_machine - self.old_to_new_dict = {} - self.new_to_old_dict = {} - - def old_to_new(self, old_state_set): - """ - Return the state of the new machine corresponding to the - set of old machine states represented by |state_set|. A new - state will be created if necessary. If any of the old states - are accepting states, the new state will be an accepting state - with the highest priority action from the old states. - """ - key = self.make_key(old_state_set) - new_state = self.old_to_new_dict.get(key, None) - if not new_state: - action = self.highest_priority_action(old_state_set) - new_state = self.new_machine.new_state(action) - self.old_to_new_dict[key] = new_state - self.new_to_old_dict[id(new_state)] = old_state_set - #for old_state in old_state_set.keys(): - #new_state.merge_actions(old_state) - return new_state - - def highest_priority_action(self, state_set): - best_action = None - best_priority = LOWEST_PRIORITY - for state in state_set: - priority = state.action_priority - if priority > best_priority: - best_action = state.action - best_priority = priority - return best_action - - # def old_to_new_set(self, old_state_set): - # """ - # Return the new state corresponding to a set of old states as - # a singleton set. - # """ - # return {self.old_to_new(old_state_set):1} - - def new_to_old(self, new_state): - """Given a new state, return a set of corresponding old states.""" - return self.new_to_old_dict[id(new_state)] - - def make_key(self, state_set): - """ - Convert a set of states into a uniquified - sorted tuple suitable for use as a dictionary key. - """ - lst = list(state_set) - lst.sort() - return tuple(lst) - - def dump(self, file): - from .Transitions import state_set_str - - for new_state in self.new_machine.states: - old_state_set = self.new_to_old_dict[id(new_state)] - file.write(" State %s <-- %s\n" % ( - new_state['number'], state_set_str(old_state_set))) - - diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/fairseq/distributed/fully_sharded_data_parallel.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/fairseq/distributed/fully_sharded_data_parallel.py deleted file mode 100644 index 88dc698b4d14db5b1bb694cab86ccac4d16d555b..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/fairseq/distributed/fully_sharded_data_parallel.py +++ /dev/null @@ -1,135 +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 contextlib -from typing import Optional - -import torch -from fairseq.dataclass.configs import DistributedTrainingConfig -from fairseq.distributed import utils as dist_utils - - -try: - from fairscale.nn.data_parallel import FullyShardedDataParallel as FSDP - - has_FSDP = True -except ImportError: - FSDP = torch.nn.Module - has_FSDP = False - - -class FullyShardedDataParallel(FSDP): - """ - A small wrapper around fairscale's FullyShardedDataParallel (FSDP) with some - fairseq-specific checkpoint saving/loading logic. - - Args: - use_sharded_state (bool): if True, then ``state_dict`` will return - ``FSDP.local_state_dict`` and ``load_state_dict`` will call - ``FSDP.load_local_state_dict``. Otherwise, ``state_dict`` will - return the full model weights on data parallel rank 0 (empty on - other ranks) and ``load_state_dict`` will broadcast model weights - from rank 0 to other ranks. - """ - - def __init__(self, *args, use_sharded_state: bool = False, **kwargs): - if not has_FSDP: - raise ImportError( - "Cannot find FullyShardedDataParallel. " - "Please install fairscale with: pip install fairscale" - ) - super().__init__(*args, **kwargs) - self.use_sharded_state = use_sharded_state - - @property - def unwrapped_module(self) -> torch.nn.Module: - if self.flatten_parameters: - return self.module.module - else: - return self.module - - def state_dict(self, destination=None, prefix="", keep_vars=False): - if self.use_sharded_state: - return super().local_state_dict( - destination=destination, prefix=prefix, keep_vars=keep_vars - ) - else: - if self.rank == 0: - return super().state_dict( - destination=destination, prefix=prefix, keep_vars=keep_vars - ) - else: - # We must call state_dict() due to use of communication - # primitives. But we don't use the result. - super().state_dict() - return destination or {} - - def load_state_dict(self, state_dict, strict=True, model_cfg=None): - if self.use_sharded_state: - return super().load_local_state_dict(state_dict, strict=strict) - else: - state_dict = dist_utils.broadcast_object( - state_dict, src_rank=0, group=self.process_group - ) - return super().load_state_dict(state_dict, strict=strict) - - -@contextlib.contextmanager -def fsdp_enable_wrap(cfg: DistributedTrainingConfig): - try: - from fairscale.nn import enable_wrap - except ImportError: - raise ImportError( - "Cannot find FullyShardedDataParallel. " - "Please install fairscale with: pip install fairscale" - ) - if cfg.memory_efficient_fp16: - assert cfg.fp16 # memory_efficient_fp16 should imply fp16 - group = dist_utils.get_data_parallel_group() - if group is None and cfg.distributed_world_size == 1: - from fairscale.utils.testing import DummyProcessGroup - - group = DummyProcessGroup(rank=0, size=1) - fsdp_config = { - "process_group": group, - "reshard_after_forward": not cfg.no_reshard_after_forward, - "mixed_precision": cfg.fp16 and not cfg.memory_efficient_fp16, - "fp32_reduce_scatter": cfg.fp32_reduce_scatter, - "flatten_parameters": not cfg.not_fsdp_flatten_parameters, - "cpu_offload": cfg.cpu_offload, - "compute_dtype": torch.float16 if cfg.fp16 else torch.float32, - "bucket_cap_mb": cfg.bucket_cap_mb, - "state_dict_device": torch.device("cpu"), # reduce GPU mem usage - } - with enable_wrap( - wrapper_cls=FullyShardedDataParallel, - use_sharded_state=cfg.use_sharded_state, - **fsdp_config, - ): - yield - - -def fsdp_wrap(module, min_num_params: Optional[int] = None, **kwargs): - """ - Helper to wrap layers/modules in FSDP. This falls back to a no-op if - fairscale is not available. - - Args: - module (nn.Module): module to (maybe) wrap - min_num_params (int, Optional): minimum number of layer params to wrap - """ - try: - from fairscale.nn import wrap - - if min_num_params is not None: - num_params = sum(p.numel() for p in module.parameters()) - if num_params >= min_num_params: - return wrap(module, **kwargs) - else: - return module - else: - return wrap(module, **kwargs) - except ImportError: - return module diff --git a/spaces/ashzzf/vits-uma-genshin-honkai/commons.py b/spaces/ashzzf/vits-uma-genshin-honkai/commons.py deleted file mode 100644 index 40fcc05364d4815971f5c6f9dbb8dcef8e3ec1e9..0000000000000000000000000000000000000000 --- a/spaces/ashzzf/vits-uma-genshin-honkai/commons.py +++ /dev/null @@ -1,172 +0,0 @@ -import math -import torch -from torch.nn import functional as F -import torch.jit - - -def script_method(fn, _rcb=None): - return fn - - -def script(obj, optimize=True, _frames_up=0, _rcb=None): - return obj - - -torch.jit.script_method = script_method -torch.jit.script = script - - -def init_weights(m, mean=0.0, std=0.01): - classname = m.__class__.__name__ - if classname.find("Conv") != -1: - m.weight.data.normal_(mean, std) - - -def get_padding(kernel_size, dilation=1): - return int((kernel_size*dilation - dilation)/2) - - -def convert_pad_shape(pad_shape): - l = pad_shape[::-1] - pad_shape = [item for sublist in l for item in sublist] - return pad_shape - - -def intersperse(lst, item): - result = [item] * (len(lst) * 2 + 1) - result[1::2] = lst - return result - - -def kl_divergence(m_p, logs_p, m_q, logs_q): - """KL(P||Q)""" - kl = (logs_q - logs_p) - 0.5 - kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q) - return kl - - -def rand_gumbel(shape): - """Sample from the Gumbel distribution, protect from overflows.""" - uniform_samples = torch.rand(shape) * 0.99998 + 0.00001 - return -torch.log(-torch.log(uniform_samples)) - - -def rand_gumbel_like(x): - g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device) - return g - - -def slice_segments(x, ids_str, segment_size=4): - ret = torch.zeros_like(x[:, :, :segment_size]) - for i in range(x.size(0)): - idx_str = ids_str[i] - idx_end = idx_str + segment_size - ret[i] = x[i, :, idx_str:idx_end] - return ret - - -def rand_slice_segments(x, x_lengths=None, segment_size=4): - b, d, t = x.size() - if x_lengths is None: - x_lengths = t - ids_str_max = x_lengths - segment_size + 1 - ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long) - ret = slice_segments(x, ids_str, segment_size) - return ret, ids_str - - -def get_timing_signal_1d( - length, channels, min_timescale=1.0, max_timescale=1.0e4): - position = torch.arange(length, dtype=torch.float) - num_timescales = channels // 2 - log_timescale_increment = ( - math.log(float(max_timescale) / float(min_timescale)) / - (num_timescales - 1)) - inv_timescales = min_timescale * torch.exp( - torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment) - scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1) - signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0) - signal = F.pad(signal, [0, 0, 0, channels % 2]) - signal = signal.view(1, channels, length) - return signal - - -def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4): - b, channels, length = x.size() - signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale) - return x + signal.to(dtype=x.dtype, device=x.device) - - -def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1): - b, channels, length = x.size() - signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale) - return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis) - - -def subsequent_mask(length): - mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0) - return mask - - -@torch.jit.script -def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels): - n_channels_int = n_channels[0] - in_act = input_a + input_b - t_act = torch.tanh(in_act[:, :n_channels_int, :]) - s_act = torch.sigmoid(in_act[:, n_channels_int:, :]) - acts = t_act * s_act - return acts - - -def convert_pad_shape(pad_shape): - l = pad_shape[::-1] - pad_shape = [item for sublist in l for item in sublist] - return pad_shape - - -def shift_1d(x): - x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1] - return x - - -def sequence_mask(length, max_length=None): - if max_length is None: - max_length = length.max() - x = torch.arange(max_length, dtype=length.dtype, device=length.device) - return x.unsqueeze(0) < length.unsqueeze(1) - - -def generate_path(duration, mask): - """ - duration: [b, 1, t_x] - mask: [b, 1, t_y, t_x] - """ - device = duration.device - - b, _, t_y, t_x = mask.shape - cum_duration = torch.cumsum(duration, -1) - - cum_duration_flat = cum_duration.view(b * t_x) - path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype) - path = path.view(b, t_x, t_y) - path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1] - path = path.unsqueeze(1).transpose(2,3) * mask - return path - - -def clip_grad_value_(parameters, clip_value, norm_type=2): - if isinstance(parameters, torch.Tensor): - parameters = [parameters] - parameters = list(filter(lambda p: p.grad is not None, parameters)) - norm_type = float(norm_type) - if clip_value is not None: - clip_value = float(clip_value) - - total_norm = 0 - for p in parameters: - param_norm = p.grad.data.norm(norm_type) - total_norm += param_norm.item() ** norm_type - if clip_value is not None: - p.grad.data.clamp_(min=-clip_value, max=clip_value) - total_norm = total_norm ** (1. / norm_type) - return total_norm diff --git a/spaces/awacke1/PoetandKnowIt/app.py b/spaces/awacke1/PoetandKnowIt/app.py deleted file mode 100644 index e715907e3b07d5018948b9467e985b66bf55f19c..0000000000000000000000000000000000000000 --- a/spaces/awacke1/PoetandKnowIt/app.py +++ /dev/null @@ -1,33 +0,0 @@ -import emoji - -poem = """ -In the land of code where the streamlit gleams, -A tale of an inbox, a place for dreams. -Messages fluttered like leaves on the wind, -Replying with wisdom, friendships begin. - -In this digital haven, hearts intertwined, -Through lines of poetry, secrets unwind. -In the realm of streamlit, love's code is designed. -""" - -emojis_to_use = { - 'code': ':computer:', - 'streamlit': ':sparkles:', - 'inbox': ':inbox_tray:', - 'dreams': ':cloud:', - 'messages': ':email:', - 'wind': ':dash:', - 'wisdom': ':owl:', - 'friendships': ':people_holding_hands:', - 'digital': ':satellite:', - 'hearts': ':heartpulse:', - 'poetry': ':scroll:', - 'secrets': ':key:', - 'love': ':heart:' -} - -for word, emoji_code in emojis_to_use.items(): - poem = poem.replace(word, emoji.emojize(emoji_code, use_aliases=True)) - -print(poem) diff --git a/spaces/awacke1/Search_Streamlit/app.py b/spaces/awacke1/Search_Streamlit/app.py deleted file mode 100644 index 12da2add760ca1f503368371f07748774e043859..0000000000000000000000000000000000000000 --- a/spaces/awacke1/Search_Streamlit/app.py +++ /dev/null @@ -1,209 +0,0 @@ -import time -import re -import pandas as pd -import numpy as np -import torch -import torch.nn.functional as F -from transformers import AutoTokenizer, AutoModel -from tokenizers import Tokenizer, AddedToken -import streamlit as st -from st_click_detector import click_detector - -# This lil dealio is my test of the new experiemntal primitives which promise to put cach in streamlit within striking distance of simulating cognitive episodic memory (personalized feelings about a moment through space time), and semantic memory (factual memories we are ready to share and communicate like your email address or physical address yo -# Goal of this is to solve AI problem of two types of memory and their part in cognitive AGI along with the theory of model making as functional design of intelligence : -# Type 1 Memory - Semantic Memory: -# Semantic memory is conscious long-term memory for meaning, understanding, and conceptual facts about the world. Semantic memory is one of the two main varieties of explicit, conscious, long-term memory, which is memory that can be retrieved into conscious awareness after a long delay (from several seconds to years). -# Type 2 Memory - Episodic Memory: -# Episodic memory refers to the conscious recollection of a personal experience that contains information on what has happened and also where and when it happened. Recollection from episodic memory also implies a kind of first-person subjectivity that has been termed autonoetic consciousness. -# Functional Design of Intelligence: The brain uses map like structures to build a models repeatedly as part of LTM and STM memory by creating hundreds of thousands of models of everything we know. This allows us to answer important questions about how we perceive the world, why we have a sense of self, and the origin of higher level thought processes. -# Research Interests: AGI and ML Pipelines, Ambient IoT AI, Behavior Cognitive and Memory AI, Clinical Medical and Nursing AI, Genomics AI, GAN Gaming GAIL AR VR XR and Simulation AI, Graph Ontology KR KE AI, Languages and NLP AI, Quantum Compute GPU TPU NPU AI, Vision Image Document and Audio/Video AI -# Layman terms for interest with keyword intersection for plot search. - - -# callback to update query param on selectbox change -def update_params(): - try: - print("update1") - #st.experimental_set_query_params(option=st.session_state.query) - except ValueError: - pass - -# RADIO BUTTON SET PERSIST -# radio button persistance - plan is to hydrate when selected and change url along with textbox and search -options = ["artificial intelligence", "robot", "VR", "medicine", "genomics", "cure", "heal", "brain", "support", "friendship", "memory", "aging", "pharma", "virus", "nurse", "doctor", "therapist", "nutrition", "technology", "computer", "software", "neuroscience", "birth", "death", "soul", "space", "sci-fi"] # these options come from my research interests blended with keywords across film genres - -query_params = st.experimental_get_query_params() -ix = 0 -if query_params: - try: - q0 = query_params['query'][0] - ix = options.index(q0) - except ValueError: - pass -selected_option = st.radio( - "Param", options, index=ix, key="query", on_change=update_params -) -st.write("", unsafe_allow_html=True) - - -st.experimental_set_query_params(option=selected_option) - -try: - st.session_state.query = query # if set already above. this prevents two interface elements setting it first time once -except: # catch exception and set query param to predefined value - print("Error cant set after init") - - -# Text Input, check the query params set the text input to query value if in session -# check if here for the first time then set the query -if 'query' not in st.session_state: - #st.session_state['query'] = 'AI' - query = st.text_input("", value="artificial intelligence", key="query") - #st.session_state.query = 'AI' - #st.write(st.session_state.query) -else: - query = st.text_input("", value=st.session_state["query"], key="query") -try: - query_params = st.experimental_get_query_params() - query_option = query_params['query'][0] #throws an exception when visiting http://host:port - option_selected = st.sidebar.selectbox('Pick option', options, index=options.index(query_option)) -except: # catch exception and set query param to predefined value - st.experimental_set_query_params(query="health") # set default - query_params = st.experimental_get_query_params() - query_option = query_params['query'][0] - query_option = "ai" - -DEVICE = "cpu" -MODEL_OPTIONS = ["msmarco-distilbert-base-tas-b", "all-mpnet-base-v2"] -DESCRIPTION = """ -# Semantic search -**Enter your query and hit enter** -Built with 🤗 Hugging Face's [transformers](https://huggingface.co/transformers/) library, [SentenceBert](https://www.sbert.net/) models, [Streamlit](https://streamlit.io/) and 44k movie descriptions from the Kaggle [Movies Dataset](https://www.kaggle.com/rounakbanik/the-movies-dataset) -""" - -# Session state - search parms -if 'key' not in st.session_state: - st.session_state['key'] = 'value' -if 'key' not in st.session_state: - st.session_state.key = 'value' -st.write(st.session_state.key) -st.write(st.session_state) - -#st.session_state -for key in st.session_state.keys(): - del st.session_state[key] -#st.text_input("Your name", key="name") -#st.session_state.name - -@st.cache( - show_spinner=False, - hash_funcs={ - AutoModel: lambda _: None, - AutoTokenizer: lambda _: None, - dict: lambda _: None, - }, -) -def load(): - models, tokenizers, embeddings = [], [], [] - for model_option in MODEL_OPTIONS: - tokenizers.append( - AutoTokenizer.from_pretrained(f"sentence-transformers/{model_option}") - ) - models.append( - AutoModel.from_pretrained(f"sentence-transformers/{model_option}").to( - DEVICE - ) - ) - embeddings.append(np.load("embeddings.npy")) - embeddings.append(np.load("embeddings2.npy")) - df = pd.read_csv("movies.csv") - return tokenizers, models, embeddings, df - -tokenizers, models, embeddings, df = load() -def pooling(model_output): - return model_output.last_hidden_state[:, 0] - -def compute_embeddings(texts): - encoded_input = tokenizers[0]( - texts, padding=True, truncation=True, return_tensors="pt" - ).to(DEVICE) - - with torch.no_grad(): - model_output = models[0](**encoded_input, return_dict=True) - - embeddings = pooling(model_output) - return embeddings.cpu().numpy() - -def pooling2(model_output, attention_mask): - token_embeddings = model_output[0] - input_mask_expanded = ( - attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float() - ) - return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp( - input_mask_expanded.sum(1), min=1e-9 - ) - -def compute_embeddings2(list_of_strings): - encoded_input = tokenizers[1]( - list_of_strings, padding=True, truncation=True, return_tensors="pt" - ).to(DEVICE) - with torch.no_grad(): - model_output = models[1](**encoded_input) - sentence_embeddings = pooling2(model_output, encoded_input["attention_mask"]) - return F.normalize(sentence_embeddings, p=2, dim=1).cpu().numpy() - -@st.cache( - show_spinner=False, - hash_funcs={Tokenizer: lambda _: None, AddedToken: lambda _: None}, -) -def semantic_search(query, model_id): - start = time.time() - if len(query.strip()) == 0: - return "" - if "[Similar:" not in query: - if model_id == 0: - query_embedding = compute_embeddings([query]) - else: - query_embedding = compute_embeddings2([query]) - else: - match = re.match(r"\[Similar:(\d{1,5}).*", query) - if match: - idx = int(match.groups()[0]) - query_embedding = embeddings[model_id][idx : idx + 1, :] - if query_embedding.shape[0] == 0: - return "" - else: - return "" - indices = np.argsort(embeddings[model_id] @ np.transpose(query_embedding)[:, 0])[ - -1:-11:-1 - ] - if len(indices) == 0: - return "" - result = "
    " - for i in indices: - result += f"
  1. {df.iloc[i].title} ({df.iloc[i].release_date}). {df.iloc[i].overview} " - #result += f"Similar movies
  2. " - #result += f"IMDB" - delay = "%.3f" % (time.time() - start) - return f"

    Computation time: {delay} seconds

    {result}
" - -st.sidebar.markdown(DESCRIPTION) - -model_choice = st.sidebar.selectbox("Similarity model", options=MODEL_OPTIONS) -model_id = 0 if model_choice == MODEL_OPTIONS[0] else 1 - -clicked = click_detector(semantic_search(query, model_id)) - -if clicked != "": - st.markdown(clicked) - change_query = False - if "last_clicked" not in st.session_state: - st.session_state["last_clicked"] = clicked - change_query = True - else: - if clicked != st.session_state["last_clicked"]: - st.session_state["last_clicked"] = clicked - change_query = True - if change_query: - st.session_state["query"] = f"[Similar:{clicked}] {df.iloc[int(clicked)].title}" - st.experimental_rerun() diff --git a/spaces/awacke1/VideoSwap/README.md b/spaces/awacke1/VideoSwap/README.md deleted file mode 100644 index 658b03c049132a1a03fe089e802d3af07b742c44..0000000000000000000000000000000000000000 --- a/spaces/awacke1/VideoSwap/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: 🦄VideoSwap🦙 -emoji: 🦄🦙 -colorFrom: green -colorTo: gray -sdk: gradio -sdk_version: 3.0.22 -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/banana-projects/web3d/node_modules/three/examples/js/loaders/AWDLoader.js b/spaces/banana-projects/web3d/node_modules/three/examples/js/loaders/AWDLoader.js deleted file mode 100644 index 5bb0c03c5c9121aec07ffd444120d8c175b4f3ae..0000000000000000000000000000000000000000 --- a/spaces/banana-projects/web3d/node_modules/three/examples/js/loaders/AWDLoader.js +++ /dev/null @@ -1,1239 +0,0 @@ -/** - * Author: Pierre Lepers - * Date: 09/12/2013 17:21 - */ - -( function () { - - var UNCOMPRESSED = 0, - DEFLATE = 1, - LZMA = 2, - - AWD_FIELD_INT8 = 1, - AWD_FIELD_INT16 = 2, - AWD_FIELD_INT32 = 3, - AWD_FIELD_UINT8 = 4, - AWD_FIELD_UINT16 = 5, - AWD_FIELD_UINT32 = 6, - AWD_FIELD_FLOAT32 = 7, - AWD_FIELD_FLOAT64 = 8, - AWD_FIELD_BOOL = 21, - AWD_FIELD_COLOR = 22, - AWD_FIELD_BADDR = 23, - AWD_FIELD_STRING = 31, - AWD_FIELD_BYTEARRAY = 32, - AWD_FIELD_VECTOR2x1 = 41, - AWD_FIELD_VECTOR3x1 = 42, - AWD_FIELD_VECTOR4x1 = 43, - AWD_FIELD_MTX3x2 = 44, - AWD_FIELD_MTX3x3 = 45, - AWD_FIELD_MTX4x3 = 46, - AWD_FIELD_MTX4x4 = 47, - - BOOL = 21, - COLOR = 22, - BADDR = 23, - - INT8 = 1, - INT16 = 2, - INT32 = 3, - UINT8 = 4, - UINT16 = 5, - UINT32 = 6, - FLOAT32 = 7, - FLOAT64 = 8; - - var littleEndian = true; - - function Block() { - - this.id = 0; - this.data = null; - - } - - function AWDProperties() {} - - AWDProperties.prototype = { - set: function ( key, value ) { - - this[ key ] = value; - - }, - - get: function ( key, fallback ) { - - if ( this.hasOwnProperty( key ) ) { - - return this[ key ]; - - } else { - - return fallback; - - } - - } - }; - - THREE.AWDLoader = function ( manager ) { - - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - - this.trunk = new THREE.Object3D(); - - this.materialFactory = undefined; - - this._url = ''; - this._baseDir = ''; - - this._data = undefined; - this._ptr = 0; - - this._version = []; - this._streaming = false; - this._optimized_for_accuracy = false; - this._compression = 0; - this._bodylen = 0xFFFFFFFF; - - this._blocks = [ new Block() ]; - - this._accuracyMatrix = false; - this._accuracyGeo = false; - this._accuracyProps = false; - - }; - - THREE.AWDLoader.prototype = { - - constructor: THREE.AWDLoader, - - load: function ( url, onLoad, onProgress, onError ) { - - var scope = this; - - this._url = url; - this._baseDir = url.substr( 0, url.lastIndexOf( '/' ) + 1 ); - - var loader = new THREE.FileLoader( this.manager ); - loader.setPath( this.path ); - loader.setResponseType( 'arraybuffer' ); - loader.load( url, function ( text ) { - - onLoad( scope.parse( text ) ); - - }, onProgress, onError ); - - }, - - setPath: function ( value ) { - - this.path = value; - return this; - - }, - - parse: function ( data ) { - - var blen = data.byteLength; - - this._ptr = 0; - this._data = new DataView( data ); - - this._parseHeader( ); - - if ( this._compression != 0 ) { - - console.error( 'compressed AWD not supported' ); - - } - - if ( ! this._streaming && this._bodylen != data.byteLength - this._ptr ) { - - console.error( 'AWDLoader: body len does not match file length', this._bodylen, blen - this._ptr ); - - } - - while ( this._ptr < blen ) { - - this.parseNextBlock(); - - } - - return this.trunk; - - }, - - parseNextBlock: function () { - - var assetData, - ns, type, len, block, - blockId = this.readU32(), - ns = this.readU8(), - type = this.readU8(), - flags = this.readU8(), - len = this.readU32(); - - - switch ( type ) { - - case 1: - assetData = this.parseMeshData( len ); - break; - - case 22: - assetData = this.parseContainer( len ); - break; - - case 23: - assetData = this.parseMeshInstance( len ); - break; - - case 81: - assetData = this.parseMaterial( len ); - break; - - case 82: - assetData = this.parseTexture( len ); - break; - - case 101: - assetData = this.parseSkeleton( len ); - break; - - // case 111: - // assetData = this.parseMeshPoseAnimation(len, true); - // break; - - case 112: - assetData = this.parseMeshPoseAnimation( len, false ); - break; - - case 113: - assetData = this.parseVertexAnimationSet( len ); - break; - - case 102: - assetData = this.parseSkeletonPose( len ); - break; - - case 103: - assetData = this.parseSkeletonAnimation( len ); - break; - - case 122: - assetData = this.parseAnimatorSet( len ); - break; - - // case 121: - // assetData = parseUVAnimation(len); - // break; - - default: - //debug('Ignoring block!',type, len); - this._ptr += len; - break; - - } - - - // Store block reference for later use - this._blocks[ blockId ] = block = new Block(); - block.data = assetData; - block.id = blockId; - - - }, - - _parseHeader: function () { - - var version = this._version, - awdmagic = ( this.readU8() << 16 ) | ( this.readU8() << 8 ) | this.readU8(); - - if ( awdmagic != 4282180 ) - throw new Error( "AWDLoader - bad magic" ); - - version[ 0 ] = this.readU8(); - version[ 1 ] = this.readU8(); - - var flags = this.readU16(); - - this._streaming = ( flags & 0x1 ) == 0x1; - - if ( ( version[ 0 ] === 2 ) && ( version[ 1 ] === 1 ) ) { - - this._accuracyMatrix = ( flags & 0x2 ) === 0x2; - this._accuracyGeo = ( flags & 0x4 ) === 0x4; - this._accuracyProps = ( flags & 0x8 ) === 0x8; - - } - - this._geoNrType = this._accuracyGeo ? FLOAT64 : FLOAT32; - this._matrixNrType = this._accuracyMatrix ? FLOAT64 : FLOAT32; - this._propsNrType = this._accuracyProps ? FLOAT64 : FLOAT32; - - this._optimized_for_accuracy = ( flags & 0x2 ) === 0x2; - - this._compression = this.readU8(); - this._bodylen = this.readU32(); - - }, - - parseContainer: function ( len ) { - - var parent, - ctr = new THREE.Object3D(), - par_id = this.readU32(), - mtx = this.parseMatrix4(); - - ctr.name = this.readUTF(); - ctr.applyMatrix( mtx ); - - parent = this._blocks[ par_id ].data || this.trunk; - parent.add( ctr ); - - this.parseProperties( { - 1: this._matrixNrType, - 2: this._matrixNrType, - 3: this._matrixNrType, - 4: UINT8 - } ); - - ctr.extra = this.parseUserAttributes(); - - return ctr; - - }, - - parseMeshInstance: function ( len ) { - - var name, - mesh, geometries, meshLen, meshes, - par_id, data_id, - mtx, - materials, mat, mat_id, - num_materials, - parent, - i; - - par_id = this.readU32(); - mtx = this.parseMatrix4(); - name = this.readUTF(); - data_id = this.readU32(); - num_materials = this.readU16(); - - geometries = this.getBlock( data_id ); - - materials = []; - - for ( i = 0; i < num_materials; i ++ ) { - - mat_id = this.readU32(); - mat = this.getBlock( mat_id ); - materials.push( mat ); - - } - - meshLen = geometries.length; - meshes = []; - - // TODO : BufferGeometry don't support "geometryGroups" for now. - // so we create sub meshes for each groups - if ( meshLen > 1 ) { - - mesh = new THREE.Object3D(); - for ( i = 0; i < meshLen; i ++ ) { - - var sm = new THREE.Mesh( geometries[ i ] ); - meshes.push( sm ); - mesh.add( sm ); - - } - - } else { - - mesh = new THREE.Mesh( geometries[ 0 ] ); - meshes.push( mesh ); - - } - - mesh.applyMatrix( mtx ); - mesh.name = name; - - - parent = this.getBlock( par_id ) || this.trunk; - parent.add( mesh ); - - - var matLen = materials.length; - var maxLen = Math.max( meshLen, matLen ); - for ( i = 0; i < maxLen; i ++ ) - meshes[ i % meshLen ].material = materials[ i % matLen ]; - - - // Ignore for now - this.parseProperties( null ); - mesh.extra = this.parseUserAttributes(); - - return mesh; - - }, - - parseMaterial: function ( len ) { - - var name, - type, - props, - mat, - attributes, - finalize, - num_methods, - methods_parsed; - - name = this.readUTF(); - type = this.readU8(); - num_methods = this.readU8(); - - //log( "AWDLoader parseMaterial ",name ) - - // Read material numerical properties - // (1=color, 2=bitmap url, 11=alpha_blending, 12=alpha_threshold, 13=repeat) - props = this.parseProperties( { - 1: AWD_FIELD_INT32, - 2: AWD_FIELD_BADDR, - 11: AWD_FIELD_BOOL, - 12: AWD_FIELD_FLOAT32, - 13: AWD_FIELD_BOOL - } ); - - methods_parsed = 0; - - while ( methods_parsed < num_methods ) { - - var method_type = this.readU16(); - this.parseProperties( null ); - this.parseUserAttributes(); - - } - - attributes = this.parseUserAttributes(); - - if ( this.materialFactory !== undefined ) { - - mat = this.materialFactory( name ); - if ( mat ) return mat; - - } - - mat = new THREE.MeshPhongMaterial(); - - if ( type === 1 ) { - - // Color material - mat.color.setHex( props.get( 1, 0xcccccc ) ); - - } else if ( type === 2 ) { - - // Bitmap material - var tex_addr = props.get( 2, 0 ); - mat.map = this.getBlock( tex_addr ); - - } - - mat.extra = attributes; - mat.alphaThreshold = props.get( 12, 0.0 ); - mat.repeat = props.get( 13, false ); - - - return mat; - - }, - - parseTexture: function ( len ) { - - var name = this.readUTF(), - type = this.readU8(), - asset, - data_len; - - // External - if ( type === 0 ) { - - data_len = this.readU32(); - var url = this.readUTFBytes( data_len ); - console.log( url ); - - asset = this.loadTexture( url ); - - } else { - // embed texture not supported - } - // Ignore for now - this.parseProperties( null ); - - this.parseUserAttributes(); - return asset; - - }, - - loadTexture: function ( url ) { - - var tex = new THREE.Texture(); - - var loader = new THREE.ImageLoader( this.manager ); - - loader.load( this._baseDir + url, function ( image ) { - - tex.image = image; - tex.needsUpdate = true; - - } ); - - return tex; - - }, - - parseSkeleton: function ( len ) { - - // Array - var name = this.readUTF(), - num_joints = this.readU16(), - skeleton = [], - joints_parsed = 0; - - this.parseProperties( null ); - - while ( joints_parsed < num_joints ) { - - var joint, ibp; - - // Ignore joint id - this.readU16(); - - joint = new THREE.Bone(); - joint.parent = this.readU16() - 1; // 0=null in AWD - joint.name = this.readUTF(); - - ibp = this.parseMatrix4(); - joint.skinMatrix = ibp; - - // Ignore joint props/attributes for now - this.parseProperties( null ); - this.parseUserAttributes(); - - skeleton.push( joint ); - joints_parsed ++; - - } - - // Discard attributes for now - this.parseUserAttributes(); - - - return skeleton; - - }, - - parseSkeletonPose: function ( blockID ) { - - var name = this.readUTF(); - - var num_joints = this.readU16(); - this.parseProperties( null ); - - // debug( 'parse Skeleton Pose. joints : ' + num_joints); - - var pose = []; - - var joints_parsed = 0; - - while ( joints_parsed < num_joints ) { - - var joint_pose; - - var has_transform; //:uint; - var mtx_data; - - has_transform = this.readU8(); - - if ( has_transform === 1 ) { - - mtx_data = this.parseMatrix4(); - - } else { - - mtx_data = new THREE.Matrix4(); - - } - pose[ joints_parsed ] = mtx_data; - joints_parsed ++; - - } - - // Skip attributes for now - this.parseUserAttributes(); - - return pose; - - }, - - parseSkeletonAnimation: function ( blockID ) { - - var frame_dur; - var pose_addr; - var pose; - - var name = this.readUTF(); - - var clip = []; - - var num_frames = this.readU16(); - this.parseProperties( null ); - - var frames_parsed = 0; - var returnedArray; - - // debug( 'parse Skeleton Animation. frames : ' + num_frames); - - while ( frames_parsed < num_frames ) { - - pose_addr = this.readU32(); - frame_dur = this.readU16(); - - pose = this._blocks[ pose_addr ].data; - // debug( 'pose address ',pose[2].elements[12],pose[2].elements[13],pose[2].elements[14] ); - clip.push( { - pose: pose, - duration: frame_dur - } ); - - frames_parsed ++; - - } - - if ( clip.length === 0 ) { - - // debug("Could not this SkeletonClipNode, because no Frames where set."); - return; - - } - // Ignore attributes for now - this.parseUserAttributes(); - return clip; - - }, - - parseVertexAnimationSet: function ( len ) { - - var poseBlockAdress, - name = this.readUTF(), - num_frames = this.readU16(), - props = this.parseProperties( { 1: UINT16 } ), - frames_parsed = 0, - skeletonFrames = []; - - while ( frames_parsed < num_frames ) { - - poseBlockAdress = this.readU32(); - skeletonFrames.push( this._blocks[ poseBlockAdress ].data ); - frames_parsed ++; - - } - - this.parseUserAttributes(); - - - return skeletonFrames; - - }, - - parseAnimatorSet: function ( len ) { - - var targetMesh; - - var animSetBlockAdress; //:int - - var targetAnimationSet; //:AnimationSetBase; - var outputString = ""; //:String = ""; - var name = this.readUTF(); - var type = this.readU16(); - - var props = this.parseProperties( { 1: BADDR } ); - - animSetBlockAdress = this.readU32(); - var targetMeshLength = this.readU16(); - - var meshAdresses = []; //:Vector. = new Vector.; - - for ( var i = 0; i < targetMeshLength; i ++ ) - meshAdresses.push( this.readU32() ); - - var activeState = this.readU16(); - var autoplay = Boolean( this.readU8() ); - this.parseUserAttributes(); - this.parseUserAttributes(); - - var returnedArray; - var targetMeshes = []; //:Vector. = new Vector.; - - for ( i = 0; i < meshAdresses.length; i ++ ) { - - // returnedArray = getAssetByID(meshAdresses[i], [AssetType.MESH]); - // if (returnedArray[0]) - targetMeshes.push( this._blocks[ meshAdresses[ i ] ].data ); - - } - - targetAnimationSet = this._blocks[ animSetBlockAdress ].data; - var thisAnimator; - - if ( type == 1 ) { - - - thisAnimator = { - animationSet: targetAnimationSet, - skeleton: this._blocks[ props.get( 1, 0 ) ].data - }; - - } else if ( type == 2 ) { - // debug( "vertex Anim???"); - } - - - for ( i = 0; i < targetMeshes.length; i ++ ) { - - targetMeshes[ i ].animator = thisAnimator; - - } - // debug("Parsed a Animator: Name = " + name); - - return thisAnimator; - - }, - - parseMeshData: function ( len ) { - - var name = this.readUTF(), - num_subs = this.readU16(), - geom, - subs_parsed = 0, - buffer, - skinW, skinI, - geometries = []; - - // Ignore for now - this.parseProperties( { 1: this._geoNrType, 2: this._geoNrType } ); - - // Loop through sub meshes - while ( subs_parsed < num_subs ) { - - var sm_len, sm_end, attrib; - - geom = new THREE.BufferGeometry(); - geom.name = name; - geometries.push( geom ); - - - sm_len = this.readU32(); - sm_end = this._ptr + sm_len; - - - // Ignore for now - this.parseProperties( { 1: this._geoNrType, 2: this._geoNrType } ); - - // Loop through data streams - while ( this._ptr < sm_end ) { - - var idx = 0, - str_type = this.readU8(), - str_ftype = this.readU8(), - str_len = this.readU32(), - str_end = str_len + this._ptr; - - if ( str_type === 1 ) { - - // VERTICES - - buffer = new Float32Array( ( str_len / 12 ) * 3 ); - attrib = new THREE.BufferAttribute( buffer, 3 ); - - geom.addAttribute( 'position', attrib ); - idx = 0; - - while ( this._ptr < str_end ) { - - buffer[ idx ] = - this.readF32(); - buffer[ idx + 1 ] = this.readF32(); - buffer[ idx + 2 ] = this.readF32(); - idx += 3; - - } - - } else if ( str_type === 2 ) { - - // INDICES - - buffer = new Uint16Array( str_len / 2 ); - attrib = new THREE.BufferAttribute( buffer, 1 ); - geom.setIndex( attrib ); - - idx = 0; - - while ( this._ptr < str_end ) { - - buffer[ idx + 1 ] = this.readU16(); - buffer[ idx ] = this.readU16(); - buffer[ idx + 2 ] = this.readU16(); - idx += 3; - - } - - } else if ( str_type === 3 ) { - - // UVS - - buffer = new Float32Array( ( str_len / 8 ) * 2 ); - attrib = new THREE.BufferAttribute( buffer, 2 ); - - geom.addAttribute( 'uv', attrib ); - idx = 0; - - while ( this._ptr < str_end ) { - - buffer[ idx ] = this.readF32(); - buffer[ idx + 1 ] = 1.0 - this.readF32(); - idx += 2; - - } - - } else if ( str_type === 4 ) { - - // NORMALS - - buffer = new Float32Array( ( str_len / 12 ) * 3 ); - attrib = new THREE.BufferAttribute( buffer, 3 ); - geom.addAttribute( 'normal', attrib ); - idx = 0; - - while ( this._ptr < str_end ) { - - buffer[ idx ] = - this.readF32(); - buffer[ idx + 1 ] = this.readF32(); - buffer[ idx + 2 ] = this.readF32(); - idx += 3; - - } - - } else { - - this._ptr = str_end; - - } - - } - - this.parseUserAttributes(); - - geom.computeBoundingSphere(); - subs_parsed ++; - - } - - //geom.computeFaceNormals(); - - this.parseUserAttributes(); - //finalizeAsset(geom, name); - - return geometries; - - }, - - parseMeshPoseAnimation: function ( len, poseOnly ) { - - var num_frames = 1, - num_submeshes, - frames_parsed, - subMeshParsed, - frame_dur, - x, y, z, - - str_len, - str_end, - geom, - subGeom, - idx = 0, - clip = {}, - indices, - verts, - num_Streams, - streamsParsed, - streamtypes = [], - - props, - thisGeo, - name = this.readUTF(), - geoAdress = this.readU32(); - - var mesh = this.getBlock( geoAdress ); - - if ( mesh === null ) { - - console.log( "parseMeshPoseAnimation target mesh not found at:", geoAdress ); - return; - - } - - geom = mesh.geometry; - geom.morphTargets = []; - - if ( ! poseOnly ) - num_frames = this.readU16(); - - num_submeshes = this.readU16(); - num_Streams = this.readU16(); - - // debug("VA num_frames : ", num_frames ); - // debug("VA num_submeshes : ", num_submeshes ); - // debug("VA numstreams : ", num_Streams ); - - streamsParsed = 0; - while ( streamsParsed < num_Streams ) { - - streamtypes.push( this.readU16() ); - streamsParsed ++; - - } - props = this.parseProperties( { 1: BOOL, 2: BOOL } ); - - clip.looping = props.get( 1, true ); - clip.stitchFinalFrame = props.get( 2, false ); - - frames_parsed = 0; - - while ( frames_parsed < num_frames ) { - - frame_dur = this.readU16(); - subMeshParsed = 0; - - while ( subMeshParsed < num_submeshes ) { - - streamsParsed = 0; - str_len = this.readU32(); - str_end = this._ptr + str_len; - - while ( streamsParsed < num_Streams ) { - - if ( streamtypes[ streamsParsed ] === 1 ) { - - //geom.addAttribute( 'morphTarget'+frames_parsed, Float32Array, str_len/12, 3 ); - var buffer = new Float32Array( str_len / 4 ); - geom.morphTargets.push( { - array: buffer - } ); - - //buffer = geom.attributes['morphTarget'+frames_parsed].array - idx = 0; - - while ( this._ptr < str_end ) { - - buffer[ idx ] = this.readF32(); - buffer[ idx + 1 ] = this.readF32(); - buffer[ idx + 2 ] = this.readF32(); - idx += 3; - - } - - - subMeshParsed ++; - - } else - this._ptr = str_end; - streamsParsed ++; - - } - - } - - - frames_parsed ++; - - } - - this.parseUserAttributes(); - - return null; - - }, - - getBlock: function ( id ) { - - return this._blocks[ id ].data; - - }, - - parseMatrix4: function () { - - var mtx = new THREE.Matrix4(); - var e = mtx.elements; - - e[ 0 ] = this.readF32(); - e[ 1 ] = this.readF32(); - e[ 2 ] = this.readF32(); - e[ 3 ] = 0.0; - //e[3] = 0.0; - - e[ 4 ] = this.readF32(); - e[ 5 ] = this.readF32(); - e[ 6 ] = this.readF32(); - //e[7] = this.readF32(); - e[ 7 ] = 0.0; - - e[ 8 ] = this.readF32(); - e[ 9 ] = this.readF32(); - e[ 10 ] = this.readF32(); - //e[11] = this.readF32(); - e[ 11 ] = 0.0; - - e[ 12 ] = - this.readF32(); - e[ 13 ] = this.readF32(); - e[ 14 ] = this.readF32(); - //e[15] = this.readF32(); - e[ 15 ] = 1.0; - return mtx; - - }, - - parseProperties: function ( expected ) { - - var list_len = this.readU32(); - var list_end = this._ptr + list_len; - - var props = new AWDProperties(); - - if ( expected ) { - - while ( this._ptr < list_end ) { - - var key = this.readU16(); - var len = this.readU32(); - var type; - - if ( expected.hasOwnProperty( key ) ) { - - type = expected[ key ]; - props.set( key, this.parseAttrValue( type, len ) ); - - } else { - - this._ptr += len; - - } - - } - - } - - return props; - - }, - - parseUserAttributes: function () { - - // skip for now - this._ptr = this.readU32() + this._ptr; - return null; - - }, - - parseAttrValue: function ( type, len ) { - - var elem_len; - var read_func; - - switch ( type ) { - - case AWD_FIELD_INT8: - elem_len = 1; - read_func = this.readI8; - break; - - case AWD_FIELD_INT16: - elem_len = 2; - read_func = this.readI16; - break; - - case AWD_FIELD_INT32: - elem_len = 4; - read_func = this.readI32; - break; - - case AWD_FIELD_BOOL: - case AWD_FIELD_UINT8: - elem_len = 1; - read_func = this.readU8; - break; - - case AWD_FIELD_UINT16: - elem_len = 2; - read_func = this.readU16; - break; - - case AWD_FIELD_UINT32: - case AWD_FIELD_BADDR: - elem_len = 4; - read_func = this.readU32; - break; - - case AWD_FIELD_FLOAT32: - elem_len = 4; - read_func = this.readF32; - break; - - case AWD_FIELD_FLOAT64: - elem_len = 8; - read_func = this.readF64; - break; - - case AWD_FIELD_VECTOR2x1: - case AWD_FIELD_VECTOR3x1: - case AWD_FIELD_VECTOR4x1: - case AWD_FIELD_MTX3x2: - case AWD_FIELD_MTX3x3: - case AWD_FIELD_MTX4x3: - case AWD_FIELD_MTX4x4: - elem_len = 8; - read_func = this.readF64; - break; - - } - - if ( elem_len < len ) { - - var list; - var num_read; - var num_elems; - - list = []; - num_read = 0; - num_elems = len / elem_len; - - while ( num_read < num_elems ) { - - list.push( read_func.call( this ) ); - num_read ++; - - } - - return list; - - } else { - - return read_func.call( this ); - - } - - }, - - readU8: function () { - - return this._data.getUint8( this._ptr ++ ); - - }, - readI8: function () { - - return this._data.getInt8( this._ptr ++ ); - - }, - readU16: function () { - - var a = this._data.getUint16( this._ptr, littleEndian ); - this._ptr += 2; - return a; - - }, - readI16: function () { - - var a = this._data.getInt16( this._ptr, littleEndian ); - this._ptr += 2; - return a; - - }, - readU32: function () { - - var a = this._data.getUint32( this._ptr, littleEndian ); - this._ptr += 4; - return a; - - }, - readI32: function () { - - var a = this._data.getInt32( this._ptr, littleEndian ); - this._ptr += 4; - return a; - - }, - readF32: function () { - - var a = this._data.getFloat32( this._ptr, littleEndian ); - this._ptr += 4; - return a; - - }, - readF64: function () { - - var a = this._data.getFloat64( this._ptr, littleEndian ); - this._ptr += 8; - return a; - - }, - - /** - * Converts a UTF-8 byte array to JavaScript's 16-bit Unicode. - * @param {Array.} bytes UTF-8 byte array. - * @return {string} 16-bit Unicode string. - */ - readUTF: function () { - - var len = this.readU16(); - return this.readUTFBytes( len ); - - }, - - /** - * Converts a UTF-8 byte array to JavaScript's 16-bit Unicode. - * @param {Array.} bytes UTF-8 byte array. - * @return {string} 16-bit Unicode string. - */ - readUTFBytes: function ( len ) { - - // TODO(user): Use native implementations if/when available - var out = [], c = 0; - - while ( out.length < len ) { - - var c1 = this._data.getUint8( this._ptr ++, littleEndian ); - if ( c1 < 128 ) { - - out[ c ++ ] = String.fromCharCode( c1 ); - - } else if ( c1 > 191 && c1 < 224 ) { - - var c2 = this._data.getUint8( this._ptr ++, littleEndian ); - out[ c ++ ] = String.fromCharCode( ( c1 & 31 ) << 6 | c2 & 63 ); - - } else { - - var c2 = this._data.getUint8( this._ptr ++, littleEndian ); - var c3 = this._data.getUint8( this._ptr ++, littleEndian ); - out[ c ++ ] = String.fromCharCode( ( c1 & 15 ) << 12 | ( c2 & 63 ) << 6 | c3 & 63 ); - - } - - } - return out.join( '' ); - - } - - }; - -} )(); diff --git a/spaces/banana-projects/web3d/node_modules/three/examples/js/shaders/HorizontalTiltShiftShader.js b/spaces/banana-projects/web3d/node_modules/three/examples/js/shaders/HorizontalTiltShiftShader.js deleted file mode 100644 index 3114aba742fb473dc9d43fea58a3c81a2d8efb66..0000000000000000000000000000000000000000 --- a/spaces/banana-projects/web3d/node_modules/three/examples/js/shaders/HorizontalTiltShiftShader.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @author alteredq / http://alteredqualia.com/ - * - * Simple fake tilt-shift effect, modulating two pass Gaussian blur (see above) by vertical position - * - * - 9 samples per pass - * - standard deviation 2.7 - * - "h" and "v" parameters should be set to "1 / width" and "1 / height" - * - "r" parameter control where "focused" horizontal line lies - */ - -THREE.HorizontalTiltShiftShader = { - - uniforms: { - - "tDiffuse": { value: null }, - "h": { value: 1.0 / 512.0 }, - "r": { value: 0.35 } - - }, - - vertexShader: [ - - "varying vec2 vUv;", - - "void main() {", - - "vUv = uv;", - "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", - - "}" - - ].join( "\n" ), - - fragmentShader: [ - - "uniform sampler2D tDiffuse;", - "uniform float h;", - "uniform float r;", - - "varying vec2 vUv;", - - "void main() {", - - "vec4 sum = vec4( 0.0 );", - - "float hh = h * abs( r - vUv.y );", - - "sum += texture2D( tDiffuse, vec2( vUv.x - 4.0 * hh, vUv.y ) ) * 0.051;", - "sum += texture2D( tDiffuse, vec2( vUv.x - 3.0 * hh, vUv.y ) ) * 0.0918;", - "sum += texture2D( tDiffuse, vec2( vUv.x - 2.0 * hh, vUv.y ) ) * 0.12245;", - "sum += texture2D( tDiffuse, vec2( vUv.x - 1.0 * hh, vUv.y ) ) * 0.1531;", - "sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;", - "sum += texture2D( tDiffuse, vec2( vUv.x + 1.0 * hh, vUv.y ) ) * 0.1531;", - "sum += texture2D( tDiffuse, vec2( vUv.x + 2.0 * hh, vUv.y ) ) * 0.12245;", - "sum += texture2D( tDiffuse, vec2( vUv.x + 3.0 * hh, vUv.y ) ) * 0.0918;", - "sum += texture2D( tDiffuse, vec2( vUv.x + 4.0 * hh, vUv.y ) ) * 0.051;", - - "gl_FragColor = sum;", - - "}" - - ].join( "\n" ) - -}; diff --git a/spaces/bioriAsaeru/text-to-voice/Advent Vega Apx Driver Zip [HOT].md b/spaces/bioriAsaeru/text-to-voice/Advent Vega Apx Driver Zip [HOT].md deleted file mode 100644 index 2674d630b4c3a7b9283980cb364f618577469151..0000000000000000000000000000000000000000 --- a/spaces/bioriAsaeru/text-to-voice/Advent Vega Apx Driver Zip [HOT].md +++ /dev/null @@ -1,47 +0,0 @@ - -

How to Download and Install Advent Vega APX Driver Zip

-

If you own an Advent Vega tablet and want to update its ROM or fix its USB driver problem, you will need to download and install the Advent Vega APX driver zip file. This file contains the NVFlash USB driver, which is a tool that allows you to flash your tablet with a custom ROM. In this article, we will show you how to get the Advent Vega APX driver zip file and how to use it to update your tablet.

-

advent vega apx driver zip


Download > https://urloso.com/2uyOr9



- -

What is Advent Vega APX Driver Zip?

-

Advent Vega APX driver zip is a file that contains the NVFlash USB driver for Advent Vega tablets. NVFlash is a software that allows you to flash your tablet with a custom ROM, which can improve its performance, features, and stability. A custom ROM is a modified version of the Android operating system that can be installed on your tablet.

- -

To use NVFlash, you will need to put your tablet into APX mode, which is a special mode that allows you to communicate with your PC via USB. To do this, you will need to install the Advent Vega APX driver on your PC, which is included in the Advent Vega APX driver zip file.

- -

Where to Download Advent Vega APX Driver Zip?

-

You can download the Advent Vega APX driver zip file from various sources online, such as XDA Forums, MoDaCo, or Android Enthusiasts Stack Exchange. However, you should always check the credibility and reliability of the source before downloading any file, as some files may contain viruses or malware that can harm your PC or tablet.

- -

One of the most trusted sources for downloading the Advent Vega APX driver zip file is the r8-vega-update-modacocustomrom file, which is a 97MB file that includes the tools, custom ROM, and drivers for Advent Vega tablets. You can download this file from MoDaCo or XDA Forums.

- -

How to Install Advent Vega APX Driver Zip?

-

Once you have downloaded the Advent Vega APX driver zip file, you will need to extract it to a folder on your PC. Then, follow these steps to install the Advent Vega APX driver on your PC:

-

- -
    -
  1. On your PC, go to Device Manager and look for an "APX" device without drivers.
  2. -
  3. Right-click on the "APX" device and choose to update the device driver.
  4. -
  5. Browse to the folder where you extracted the Advent Vega APX driver zip file and select the NvidiaUsb.inf file.
  6. -
  7. Follow the instructions on the screen to complete the installation of the Advent Vega APX driver.
  8. -
- -

Now, you have successfully installed the Advent Vega APX driver on your PC and you are ready to use NVFlash to flash your tablet with a custom ROM.

- -

How to Use NVFlash to Flash Your Tablet with a Custom ROM?

-

To use NVFlash to flash your tablet with a custom ROM, you will need to follow these steps:

- -
    -
  1. Make sure your tablet is fully charged and turn it off.
  2. -
  3. Connect your tablet to your PC via USB cable.
  4. -
  5. Press and hold the Back button on your tablet and then press and release the Power button. This will put your tablet into APX mode.
  6. -
  7. On your PC, go to the folder where you extracted the Advent Vega APX driver zip file and run the NVFlash.exe file.
  8. -
  9. Follow the instructions on the screen to flash your tablet with a custom ROM of your choice.
  10. -
  11. Once the flashing process is completed, disconnect your tablet from your PC and reboot it.
  12. -
- -

Congratulations! You have successfully flashed your tablet with a custom ROM using NVFlash and Advent Vega APX driver zip. Enjoy your new and improved tablet!

-

Conclusion

-

In this article, we have shown you how to download and install the Advent Vega APX driver zip file, which contains the NVFlash USB driver for Advent Vega tablets. We have also explained how to use NVFlash to flash your tablet with a custom ROM, which can enhance your tablet's performance, features, and stability. By following these steps, you can update your tablet and enjoy a better user experience.

- -

We hope you found this article helpful and informative. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading!

3cee63e6c2
-
-
\ No newline at end of file diff --git a/spaces/bioriAsaeru/text-to-voice/Dont Mess With An Angel English Version Full 58 _TOP_.md b/spaces/bioriAsaeru/text-to-voice/Dont Mess With An Angel English Version Full 58 _TOP_.md deleted file mode 100644 index e13cb4391917790e434f66283958c68f7c3b3107..0000000000000000000000000000000000000000 --- a/spaces/bioriAsaeru/text-to-voice/Dont Mess With An Angel English Version Full 58 _TOP_.md +++ /dev/null @@ -1,6 +0,0 @@ -

Don't Mess With An Angel English Version Full 58


Download Ziphttps://urloso.com/2uyS2p



- -One of my favourite versions at the moment is this Cajun style red beans and rice ... that andouille sausage ought to go into that shoulder and red beans mess up. ... different species of holly trees, such as the American holly and English holly. ... Red Kidney beans are typically harvested at complete maturity as dry beans. 4d29de3e1b
-
-
-

diff --git a/spaces/bioriAsaeru/text-to-voice/Filmes Despachado Para A India Dublado WORK.md b/spaces/bioriAsaeru/text-to-voice/Filmes Despachado Para A India Dublado WORK.md deleted file mode 100644 index 518e91a5fd0479117c5fada46d66e6092bdc8671..0000000000000000000000000000000000000000 --- a/spaces/bioriAsaeru/text-to-voice/Filmes Despachado Para A India Dublado WORK.md +++ /dev/null @@ -1,6 +0,0 @@ -

Filmes Despachado Para A India Dublado WORK


Download ✺✺✺ https://urloso.com/2uyQxj



- - aaccfb2cb3
-
-
-

diff --git a/spaces/bioriAsaeru/text-to-voice/Free Torrent Teri Meri Kahaani Hindi Movie Download.md b/spaces/bioriAsaeru/text-to-voice/Free Torrent Teri Meri Kahaani Hindi Movie Download.md deleted file mode 100644 index cc960a13eb7c820be039945d323dc2d7a4f958d6..0000000000000000000000000000000000000000 --- a/spaces/bioriAsaeru/text-to-voice/Free Torrent Teri Meri Kahaani Hindi Movie Download.md +++ /dev/null @@ -1,6 +0,0 @@ -

Free Torrent Teri Meri Kahaani Hindi Movie Download


Download File ————— https://urloso.com/2uyRTU



-
-This story takes us through a journey of eternal love between a couple who has vowed to love each other not only in this life but in every life to follow. Th... 4d29de3e1b
-
-
-

diff --git a/spaces/bioriAsaeru/text-to-voice/Jimmy Dorsey metodo para saxofon pdf cmo dominar el saxofn con el famoso msico de jazz.md b/spaces/bioriAsaeru/text-to-voice/Jimmy Dorsey metodo para saxofon pdf cmo dominar el saxofn con el famoso msico de jazz.md deleted file mode 100644 index 9b187388440efbcf07256b5b446fe4c4a02e62a7..0000000000000000000000000000000000000000 --- a/spaces/bioriAsaeru/text-to-voice/Jimmy Dorsey metodo para saxofon pdf cmo dominar el saxofn con el famoso msico de jazz.md +++ /dev/null @@ -1,6 +0,0 @@ -

jimmy dorsey metodo para saxofon pdf


DOWNLOADhttps://urloso.com/2uyOmK



-
- aaccfb2cb3
-
-
-

diff --git a/spaces/birsardar/stable-diffusion-mat-outpainting-primer/datasets/mask_generator_256_small.py b/spaces/birsardar/stable-diffusion-mat-outpainting-primer/datasets/mask_generator_256_small.py deleted file mode 100644 index 288eba3ac3b249fc22b2503aad7651ce368c68a4..0000000000000000000000000000000000000000 --- a/spaces/birsardar/stable-diffusion-mat-outpainting-primer/datasets/mask_generator_256_small.py +++ /dev/null @@ -1,93 +0,0 @@ -import numpy as np -from PIL import Image, ImageDraw -import math -import random - - -def RandomBrush( - max_tries, - s, - min_num_vertex = 4, - max_num_vertex = 18, - mean_angle = 2*math.pi / 5, - angle_range = 2*math.pi / 15, - min_width = 12, - max_width = 48): - H, W = s, s - average_radius = math.sqrt(H*H+W*W) / 8 - mask = Image.new('L', (W, H), 0) - for _ in range(np.random.randint(max_tries)): - num_vertex = np.random.randint(min_num_vertex, max_num_vertex) - angle_min = mean_angle - np.random.uniform(0, angle_range) - angle_max = mean_angle + np.random.uniform(0, angle_range) - angles = [] - vertex = [] - for i in range(num_vertex): - if i % 2 == 0: - angles.append(2*math.pi - np.random.uniform(angle_min, angle_max)) - else: - angles.append(np.random.uniform(angle_min, angle_max)) - - h, w = mask.size - vertex.append((int(np.random.randint(0, w)), int(np.random.randint(0, h)))) - for i in range(num_vertex): - r = np.clip( - np.random.normal(loc=average_radius, scale=average_radius//2), - 0, 2*average_radius) - new_x = np.clip(vertex[-1][0] + r * math.cos(angles[i]), 0, w) - new_y = np.clip(vertex[-1][1] + r * math.sin(angles[i]), 0, h) - vertex.append((int(new_x), int(new_y))) - - draw = ImageDraw.Draw(mask) - width = int(np.random.uniform(min_width, max_width)) - draw.line(vertex, fill=1, width=width) - for v in vertex: - draw.ellipse((v[0] - width//2, - v[1] - width//2, - v[0] + width//2, - v[1] + width//2), - fill=1) - if np.random.random() > 0.5: - mask.transpose(Image.FLIP_LEFT_RIGHT) - if np.random.random() > 0.5: - mask.transpose(Image.FLIP_TOP_BOTTOM) - mask = np.asarray(mask, np.uint8) - if np.random.random() > 0.5: - mask = np.flip(mask, 0) - if np.random.random() > 0.5: - mask = np.flip(mask, 1) - return mask - -def RandomMask(s, hole_range=[0,1]): - coef = min(hole_range[0] + hole_range[1], 1.0) - while True: - mask = np.ones((s, s), np.uint8) - def Fill(max_size): - w, h = np.random.randint(max_size), np.random.randint(max_size) - ww, hh = w // 2, h // 2 - x, y = np.random.randint(-ww, s - w + ww), np.random.randint(-hh, s - h + hh) - mask[max(y, 0): min(y + h, s), max(x, 0): min(x + w, s)] = 0 - def MultiFill(max_tries, max_size): - for _ in range(np.random.randint(max_tries)): - Fill(max_size) - MultiFill(int(2 * coef), s // 2) - MultiFill(int(2 * coef), s) - mask = np.logical_and(mask, 1 - RandomBrush(int(3 * coef), s)) # hole denoted as 0, reserved as 1 - hole_ratio = 1 - np.mean(mask) - if hole_range is not None and (hole_ratio <= hole_range[0] or hole_ratio >= hole_range[1]): - continue - return mask[np.newaxis, ...].astype(np.float32) - -def BatchRandomMask(batch_size, s, hole_range=[0, 1]): - return np.stack([RandomMask(s, hole_range=hole_range) for _ in range(batch_size)], axis=0) - - -if __name__ == '__main__': - # res = 512 - res = 256 - cnt = 2000 - tot = 0 - for i in range(cnt): - mask = RandomMask(s=res) - tot += mask.mean() - print(tot / cnt) diff --git a/spaces/bla/tranny/App/app.py b/spaces/bla/tranny/App/app.py deleted file mode 100644 index d400d19ec77f6509d2ac44e4d1d460e79a0106b4..0000000000000000000000000000000000000000 --- a/spaces/bla/tranny/App/app.py +++ /dev/null @@ -1,83 +0,0 @@ -from fastapi import FastAPI, Request -from fastapi.responses import JSONResponse -from fastapi.middleware.gzip import GZipMiddleware -from App import bot -from telethon import TelegramClient -from telethon.sessions import StringSession -from .Users.UserRoutes import user_router -from .modelInit import models, database -from .Transcription.TranscriptionRoutes import transcription_router -from .Streaming.StreamingRoutes import streaming_router -from .UserTranscriptions.UserTranscriptionsRoutes import user_transcriptions_router -from .Monitor.monitorRoutes import monitor_router - -from .Embedding.EmbeddingRoutes import embeddigs_router -from .Chat.ChatRoutes import chat_router - -from fastapi.middleware.cors import CORSMiddleware -from fastapi_jwt_auth.exceptions import AuthJWTException - -import logging, orm - - -# Configure logging -logging.basicConfig( - level=logging.DEBUG, - format="%(asctime)s - %(levelname)s - %(message)s", - datefmt="%Y-%m-%d %H:%M:%S", -) - - -app = FastAPI() -origins = ["*"] - -app.add_middleware( - CORSMiddleware, - allow_origins=origins, - allow_credentials=True, - allow_methods=["*"], - allow_headers=["*"], -) -app.add_middleware(GZipMiddleware, minimum_size=1000) - - -@app.exception_handler(AuthJWTException) -def authjwt_exception_handler(request: Request, exc: AuthJWTException): - return JSONResponse(status_code=exc.status_code, content={"detail": exc.message}) - - -@app.on_event("startup") -async def startup_event(): - await bot.start() - # await upload_bot.start() - # await models.create_all() - # models.metadata.create_all() - - if not database.is_connected: - await database.connect() - print("connected!") - - -@app.on_event("shutdown") -async def shutdown_event(): - # bot.session.save() - # await bot.disconnect() - - # await upload_bot.stop() - if not database.is_connected: - await database.disconnect() - print("shutting down!") - - -@app.get("/") -async def landing_page(): - return {"code": 200, "message": "we are back!"} - - -app.include_router(user_router) -app.include_router(transcription_router) -app.include_router(streaming_router) -app.include_router(monitor_router) -app.include_router(user_transcriptions_router) -app.include_router(embeddigs_router) -# app.include_router(chat_router) diff --git a/spaces/bluebalam/paper-rec/app.py b/spaces/bluebalam/paper-rec/app.py deleted file mode 100644 index 7b68eb2c63c318b773ea7bdee82bf5241866c599..0000000000000000000000000000000000000000 --- a/spaces/bluebalam/paper-rec/app.py +++ /dev/null @@ -1,76 +0,0 @@ -import gradio as gr -import torch - - -from paper_rec import recommender, etl -from gradio.inputs import Textbox - - -def recommend(txt): - if len(txt.strip()) <= 0: - return {"msg": "no recommendations available for the input text."} - - top_n = 10 - # model user preferences: - cleaned_txt = etl.clean_text(txt) - sentences = etl.get_sentences_from_txt(txt) - rec = recommender.Recommender() - # loading data and model from HF - rec.load_data() - rec.load_model() - # compute user embedding - user_embedding = torch.from_numpy(rec.embedding(sentences)) - # get recommendations based on user preferences - recs = rec.recommend(user_embedding, top_k=100) - # deduplicate - recs_output = [] - seen_paper = set() - for p in recs: - if p["id"] not in seen_paper: - recs_output.append({"id": p["id"], - "title": p["title"], - "abstract": p["authors"], - "abstract": p["abstract"] - }) - seen_paper.add(p["id"]) - if len(recs_output) >= top_n: - break - - # report top-n - return recs_output - - -title = "Interactive demo: paper-rec" -description = """What paper in ML/AI should I read next? It is difficult to choose from all great research publications -published daily. This demo gives you a personalized selection of papers from the latest scientific contributions -available in arXiv – https://arxiv.org/. - -You just input the title or abstract (or both) of paper(s) you liked in the past or you can also use keywords of topics -of interest and get the top-10 article recommendations tailored to your taste. - -Enjoy!""" - -examples = ["""Attention Is All You Need – The dominant sequence transduction models are based on complex recurrent or -convolutional neural networks in an encoder-decoder configuration. The best performing models also connect the encoder -and decoder through an attention mechanism. We propose a new simple network architecture, the Transformer, based solely -on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two machine translation -tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time -to train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task, improving over the existing -best results, including ensembles by over 2 BLEU. On the WMT 2014 English-to-French translation task, our model -establishes a new single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small -fraction of the training costs of the best models from the literature. We show that the Transformer generalizes well to -other tasks by applying it successfully to English constituency parsing both with large and limited training data.""", - "GANs, Diffusion Models, Art"] - -iface = gr.Interface(fn=recommend, - inputs=[Textbox(lines=10, placeholder="Titles and abstracts from papers you like", default="", - label="""Sample of what I like: title(s) or abstract(s) of papers you love or a set - of keywords about your interests (e.g., Transformers, GANs, Recommender Systems): - """)], - outputs="json", - layout='vertical', - title=title, - description=description, - examples=examples - ) -iface.launch() \ No newline at end of file diff --git a/spaces/brainstone/qr/README.md b/spaces/brainstone/qr/README.md deleted file mode 100644 index 860f52bc491a642273e52a088b0ad23d8949c04b..0000000000000000000000000000000000000000 --- a/spaces/brainstone/qr/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Qr -emoji: 🐢 -colorFrom: pink -colorTo: green -sdk: gradio -sdk_version: 3.35.2 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/tools/deploy/export_model.py b/spaces/brjathu/HMR2.0/vendor/detectron2/tools/deploy/export_model.py deleted file mode 100644 index f507dffe56a4121756874186eacdc9be0cbcdee1..0000000000000000000000000000000000000000 --- a/spaces/brjathu/HMR2.0/vendor/detectron2/tools/deploy/export_model.py +++ /dev/null @@ -1,240 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) Facebook, Inc. and its affiliates. -import argparse -import os -from typing import Dict, List, Tuple -import torch -from torch import Tensor, nn - -import detectron2.data.transforms as T -from detectron2.checkpoint import DetectionCheckpointer -from detectron2.config import get_cfg -from detectron2.data import build_detection_test_loader, detection_utils -from detectron2.evaluation import COCOEvaluator, inference_on_dataset, print_csv_format -from detectron2.export import ( - STABLE_ONNX_OPSET_VERSION, - TracingAdapter, - dump_torchscript_IR, - scripting_with_instances, -) -from detectron2.modeling import GeneralizedRCNN, RetinaNet, build_model -from detectron2.modeling.postprocessing import detector_postprocess -from detectron2.projects.point_rend import add_pointrend_config -from detectron2.structures import Boxes -from detectron2.utils.env import TORCH_VERSION -from detectron2.utils.file_io import PathManager -from detectron2.utils.logger import setup_logger - - -def setup_cfg(args): - cfg = get_cfg() - # cuda context is initialized before creating dataloader, so we don't fork anymore - cfg.DATALOADER.NUM_WORKERS = 0 - add_pointrend_config(cfg) - cfg.merge_from_file(args.config_file) - cfg.merge_from_list(args.opts) - cfg.freeze() - return cfg - - -def export_caffe2_tracing(cfg, torch_model, inputs): - from detectron2.export import Caffe2Tracer - - tracer = Caffe2Tracer(cfg, torch_model, inputs) - if args.format == "caffe2": - caffe2_model = tracer.export_caffe2() - caffe2_model.save_protobuf(args.output) - # draw the caffe2 graph - caffe2_model.save_graph(os.path.join(args.output, "model.svg"), inputs=inputs) - return caffe2_model - elif args.format == "onnx": - import onnx - - onnx_model = tracer.export_onnx() - onnx.save(onnx_model, os.path.join(args.output, "model.onnx")) - elif args.format == "torchscript": - ts_model = tracer.export_torchscript() - with PathManager.open(os.path.join(args.output, "model.ts"), "wb") as f: - torch.jit.save(ts_model, f) - dump_torchscript_IR(ts_model, args.output) - - -# experimental. API not yet final -def export_scripting(torch_model): - assert TORCH_VERSION >= (1, 8) - fields = { - "proposal_boxes": Boxes, - "objectness_logits": Tensor, - "pred_boxes": Boxes, - "scores": Tensor, - "pred_classes": Tensor, - "pred_masks": Tensor, - "pred_keypoints": torch.Tensor, - "pred_keypoint_heatmaps": torch.Tensor, - } - assert args.format == "torchscript", "Scripting only supports torchscript format." - - class ScriptableAdapterBase(nn.Module): - # Use this adapter to workaround https://github.com/pytorch/pytorch/issues/46944 - # by not retuning instances but dicts. Otherwise the exported model is not deployable - def __init__(self): - super().__init__() - self.model = torch_model - self.eval() - - if isinstance(torch_model, GeneralizedRCNN): - - class ScriptableAdapter(ScriptableAdapterBase): - def forward(self, inputs: Tuple[Dict[str, torch.Tensor]]) -> List[Dict[str, Tensor]]: - instances = self.model.inference(inputs, do_postprocess=False) - return [i.get_fields() for i in instances] - - else: - - class ScriptableAdapter(ScriptableAdapterBase): - def forward(self, inputs: Tuple[Dict[str, torch.Tensor]]) -> List[Dict[str, Tensor]]: - instances = self.model(inputs) - return [i.get_fields() for i in instances] - - ts_model = scripting_with_instances(ScriptableAdapter(), fields) - with PathManager.open(os.path.join(args.output, "model.ts"), "wb") as f: - torch.jit.save(ts_model, f) - dump_torchscript_IR(ts_model, args.output) - # TODO inference in Python now missing postprocessing glue code - return None - - -# experimental. API not yet final -def export_tracing(torch_model, inputs): - assert TORCH_VERSION >= (1, 8) - image = inputs[0]["image"] - inputs = [{"image": image}] # remove other unused keys - - if isinstance(torch_model, GeneralizedRCNN): - - def inference(model, inputs): - # use do_postprocess=False so it returns ROI mask - inst = model.inference(inputs, do_postprocess=False)[0] - return [{"instances": inst}] - - else: - inference = None # assume that we just call the model directly - - traceable_model = TracingAdapter(torch_model, inputs, inference) - - if args.format == "torchscript": - ts_model = torch.jit.trace(traceable_model, (image,)) - with PathManager.open(os.path.join(args.output, "model.ts"), "wb") as f: - torch.jit.save(ts_model, f) - dump_torchscript_IR(ts_model, args.output) - elif args.format == "onnx": - with PathManager.open(os.path.join(args.output, "model.onnx"), "wb") as f: - torch.onnx.export(traceable_model, (image,), f, opset_version=STABLE_ONNX_OPSET_VERSION) - logger.info("Inputs schema: " + str(traceable_model.inputs_schema)) - logger.info("Outputs schema: " + str(traceable_model.outputs_schema)) - - if args.format != "torchscript": - return None - if not isinstance(torch_model, (GeneralizedRCNN, RetinaNet)): - return None - - def eval_wrapper(inputs): - """ - The exported model does not contain the final resize step, which is typically - unused in deployment but needed for evaluation. We add it manually here. - """ - input = inputs[0] - instances = traceable_model.outputs_schema(ts_model(input["image"]))[0]["instances"] - postprocessed = detector_postprocess(instances, input["height"], input["width"]) - return [{"instances": postprocessed}] - - return eval_wrapper - - -def get_sample_inputs(args): - - if args.sample_image is None: - # get a first batch from dataset - data_loader = build_detection_test_loader(cfg, cfg.DATASETS.TEST[0]) - first_batch = next(iter(data_loader)) - return first_batch - else: - # get a sample data - original_image = detection_utils.read_image(args.sample_image, format=cfg.INPUT.FORMAT) - # Do same preprocessing as DefaultPredictor - aug = T.ResizeShortestEdge( - [cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST], cfg.INPUT.MAX_SIZE_TEST - ) - height, width = original_image.shape[:2] - image = aug.get_transform(original_image).apply_image(original_image) - image = torch.as_tensor(image.astype("float32").transpose(2, 0, 1)) - - inputs = {"image": image, "height": height, "width": width} - - # Sample ready - sample_inputs = [inputs] - return sample_inputs - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Export a model for deployment.") - parser.add_argument( - "--format", - choices=["caffe2", "onnx", "torchscript"], - help="output format", - default="torchscript", - ) - parser.add_argument( - "--export-method", - choices=["caffe2_tracing", "tracing", "scripting"], - help="Method to export models", - default="tracing", - ) - parser.add_argument("--config-file", default="", metavar="FILE", help="path to config file") - parser.add_argument("--sample-image", default=None, type=str, help="sample image for input") - parser.add_argument("--run-eval", action="store_true") - parser.add_argument("--output", help="output directory for the converted model") - parser.add_argument( - "opts", - help="Modify config options using the command-line", - default=None, - nargs=argparse.REMAINDER, - ) - args = parser.parse_args() - logger = setup_logger() - logger.info("Command line arguments: " + str(args)) - PathManager.mkdirs(args.output) - # Disable re-specialization on new shapes. Otherwise --run-eval will be slow - torch._C._jit_set_bailout_depth(1) - - cfg = setup_cfg(args) - - # create a torch model - torch_model = build_model(cfg) - DetectionCheckpointer(torch_model).resume_or_load(cfg.MODEL.WEIGHTS) - torch_model.eval() - - # convert and save model - if args.export_method == "caffe2_tracing": - sample_inputs = get_sample_inputs(args) - exported_model = export_caffe2_tracing(cfg, torch_model, sample_inputs) - elif args.export_method == "scripting": - exported_model = export_scripting(torch_model) - elif args.export_method == "tracing": - sample_inputs = get_sample_inputs(args) - exported_model = export_tracing(torch_model, sample_inputs) - - # run evaluation with the converted model - if args.run_eval: - assert exported_model is not None, ( - "Python inference is not yet implemented for " - f"export_method={args.export_method}, format={args.format}." - ) - logger.info("Running evaluation ... this takes a long time if you export to CPU.") - dataset = cfg.DATASETS.TEST[0] - data_loader = build_detection_test_loader(cfg, dataset) - # NOTE: hard-coded evaluator. change to the evaluator for your dataset - evaluator = COCOEvaluator(dataset, output_dir=args.output) - metrics = inference_on_dataset(exported_model, data_loader, evaluator) - print_csv_format(metrics) - logger.info("Success.") diff --git a/spaces/captainChan/CaptainChan/main.py b/spaces/captainChan/CaptainChan/main.py deleted file mode 100644 index def41731ed4cbe77051e496caf2b2d37dd95611f..0000000000000000000000000000000000000000 --- a/spaces/captainChan/CaptainChan/main.py +++ /dev/null @@ -1,246 +0,0 @@ -import argparse -import logging -import os -import random - -import torch -from fastai.callbacks.general_sched import GeneralScheduler, TrainingPhase -from fastai.distributed import * -from fastai.vision import * -from torch.backends import cudnn - -from callbacks import DumpPrediction, IterationCallback, TextAccuracy, TopKTextAccuracy -from dataset import ImageDataset, TextDataset -from losses import MultiLosses -from utils import Config, Logger, MyDataParallel, MyConcatDataset - - -def _set_random_seed(seed): - if seed is not None: - random.seed(seed) - torch.manual_seed(seed) - cudnn.deterministic = True - logging.warning('You have chosen to seed training. ' - 'This will slow down your training!') - -def _get_training_phases(config, n): - lr = np.array(config.optimizer_lr) - periods = config.optimizer_scheduler_periods - sigma = [config.optimizer_scheduler_gamma ** i for i in range(len(periods))] - phases = [TrainingPhase(n * periods[i]).schedule_hp('lr', lr * sigma[i]) - for i in range(len(periods))] - return phases - -def _get_dataset(ds_type, paths, is_training, config, **kwargs): - kwargs.update({ - 'img_h': config.dataset_image_height, - 'img_w': config.dataset_image_width, - 'max_length': config.dataset_max_length, - 'case_sensitive': config.dataset_case_sensitive, - 'charset_path': config.dataset_charset_path, - 'data_aug': config.dataset_data_aug, - 'deteriorate_ratio': config.dataset_deteriorate_ratio, - 'is_training': is_training, - 'multiscales': config.dataset_multiscales, - 'one_hot_y': config.dataset_one_hot_y, - }) - datasets = [ds_type(p, **kwargs) for p in paths] - if len(datasets) > 1: return MyConcatDataset(datasets) - else: return datasets[0] - - -def _get_language_databaunch(config): - kwargs = { - 'max_length': config.dataset_max_length, - 'case_sensitive': config.dataset_case_sensitive, - 'charset_path': config.dataset_charset_path, - 'smooth_label': config.dataset_smooth_label, - 'smooth_factor': config.dataset_smooth_factor, - 'one_hot_y': config.dataset_one_hot_y, - 'use_sm': config.dataset_use_sm, - } - train_ds = TextDataset(config.dataset_train_roots[0], is_training=True, **kwargs) - valid_ds = TextDataset(config.dataset_test_roots[0], is_training=False, **kwargs) - data = DataBunch.create( - path=train_ds.path, - train_ds=train_ds, - valid_ds=valid_ds, - bs=config.dataset_train_batch_size, - val_bs=config.dataset_test_batch_size, - num_workers=config.dataset_num_workers, - pin_memory=config.dataset_pin_memory) - logging.info(f'{len(data.train_ds)} training items found.') - if not data.empty_val: - logging.info(f'{len(data.valid_ds)} valid items found.') - return data - -def _get_databaunch(config): - # An awkward way to reduce loadding data time during test - if config.global_phase == 'test': config.dataset_train_roots = config.dataset_test_roots - train_ds = _get_dataset(ImageDataset, config.dataset_train_roots, True, config) - valid_ds = _get_dataset(ImageDataset, config.dataset_test_roots, False, config) - data = ImageDataBunch.create( - train_ds=train_ds, - valid_ds=valid_ds, - bs=config.dataset_train_batch_size, - val_bs=config.dataset_test_batch_size, - num_workers=config.dataset_num_workers, - pin_memory=config.dataset_pin_memory).normalize(imagenet_stats) - ar_tfm = lambda x: ((x[0], x[1]), x[1]) # auto-regression only for dtd - data.add_tfm(ar_tfm) - - logging.info(f'{len(data.train_ds)} training items found.') - if not data.empty_val: - logging.info(f'{len(data.valid_ds)} valid items found.') - - return data - -def _get_model(config): - import importlib - names = config.model_name.split('.') - module_name, class_name = '.'.join(names[:-1]), names[-1] - cls = getattr(importlib.import_module(module_name), class_name) - model = cls(config) - logging.info(model) - return model - - -def _get_learner(config, data, model, local_rank=None): - strict = ifnone(config.model_strict, True) - if config.global_stage == 'pretrain-language': - metrics = [TopKTextAccuracy( - k=ifnone(config.model_k, 5), - charset_path=config.dataset_charset_path, - max_length=config.dataset_max_length + 1, - case_sensitive=config.dataset_eval_case_sensisitves, - model_eval=config.model_eval)] - else: - metrics = [TextAccuracy( - charset_path=config.dataset_charset_path, - max_length=config.dataset_max_length + 1, - case_sensitive=config.dataset_eval_case_sensisitves, - model_eval=config.model_eval)] - opt_type = getattr(torch.optim, config.optimizer_type) - learner = Learner(data, model, silent=True, model_dir='.', - true_wd=config.optimizer_true_wd, - wd=config.optimizer_wd, - bn_wd=config.optimizer_bn_wd, - path=config.global_workdir, - metrics=metrics, - opt_func=partial(opt_type, **config.optimizer_args or dict()), - loss_func=MultiLosses(one_hot=config.dataset_one_hot_y)) - learner.split(lambda m: children(m)) - - if config.global_phase == 'train': - num_replicas = 1 if local_rank is None else torch.distributed.get_world_size() - phases = _get_training_phases(config, len(learner.data.train_dl)//num_replicas) - learner.callback_fns += [ - partial(GeneralScheduler, phases=phases), - partial(GradientClipping, clip=config.optimizer_clip_grad), - partial(IterationCallback, name=config.global_name, - show_iters=config.training_show_iters, - eval_iters=config.training_eval_iters, - save_iters=config.training_save_iters, - start_iters=config.training_start_iters, - stats_iters=config.training_stats_iters)] - else: - learner.callbacks += [ - DumpPrediction(learn=learner, - dataset='-'.join([Path(p).name for p in config.dataset_test_roots]),charset_path=config.dataset_charset_path, - model_eval=config.model_eval, - debug=config.global_debug, - image_only=config.global_image_only)] - - learner.rank = local_rank - if local_rank is not None: - logging.info(f'Set model to distributed with rank {local_rank}.') - learner.model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(learner.model) - learner.model.to(local_rank) - learner = learner.to_distributed(local_rank) - - if torch.cuda.device_count() > 1 and local_rank is None: - logging.info(f'Use {torch.cuda.device_count()} GPUs.') - learner.model = MyDataParallel(learner.model) - - if config.model_checkpoint: - if Path(config.model_checkpoint).exists(): - with open(config.model_checkpoint, 'rb') as f: - buffer = io.BytesIO(f.read()) - learner.load(buffer, strict=strict) - else: - from distutils.dir_util import copy_tree - src = Path('/data/fangsc/model')/config.global_name - trg = Path('/output')/config.global_name - if src.exists(): copy_tree(str(src), str(trg)) - learner.load(config.model_checkpoint, strict=strict) - logging.info(f'Read model from {config.model_checkpoint}') - elif config.global_phase == 'test': - learner.load(f'best-{config.global_name}', strict=strict) - logging.info(f'Read model from best-{config.global_name}') - - if learner.opt_func.func.__name__ == 'Adadelta': # fastai bug, fix after 1.0.60 - learner.fit(epochs=0, lr=config.optimizer_lr) - learner.opt.mom = 0. - - return learner - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument('--config', type=str, required=True, - help='path to config file') - parser.add_argument('--phase', type=str, default=None, choices=['train', 'test']) - parser.add_argument('--name', type=str, default=None) - parser.add_argument('--checkpoint', type=str, default=None) - parser.add_argument('--test_root', type=str, default=None) - parser.add_argument("--local_rank", type=int, default=None) - parser.add_argument('--debug', action='store_true', default=None) - parser.add_argument('--image_only', action='store_true', default=None) - parser.add_argument('--model_strict', action='store_false', default=None) - parser.add_argument('--model_eval', type=str, default=None, - choices=['alignment', 'vision', 'language']) - args = parser.parse_args() - config = Config(args.config) - if args.name is not None: config.global_name = args.name - if args.phase is not None: config.global_phase = args.phase - if args.test_root is not None: config.dataset_test_roots = [args.test_root] - if args.checkpoint is not None: config.model_checkpoint = args.checkpoint - if args.debug is not None: config.global_debug = args.debug - if args.image_only is not None: config.global_image_only = args.image_only - if args.model_eval is not None: config.model_eval = args.model_eval - if args.model_strict is not None: config.model_strict = args.model_strict - - Logger.init(config.global_workdir, config.global_name, config.global_phase) - Logger.enable_file() - _set_random_seed(config.global_seed) - logging.info(config) - - if args.local_rank is not None: - logging.info(f'Init distribution training at device {args.local_rank}.') - torch.cuda.set_device(args.local_rank) - torch.distributed.init_process_group(backend='nccl', init_method='env://') - - logging.info('Construct dataset.') - if config.global_stage == 'pretrain-language': data = _get_language_databaunch(config) - else: data = _get_databaunch(config) - - logging.info('Construct model.') - model = _get_model(config) - - logging.info('Construct learner.') - learner = _get_learner(config, data, model, args.local_rank) - - if config.global_phase == 'train': - logging.info('Start training.') - learner.fit(epochs=config.training_epochs, - lr=config.optimizer_lr) - else: - logging.info('Start validate') - last_metrics = learner.validate() - log_str = f'eval loss = {last_metrics[0]:6.3f}, ' \ - f'ccr = {last_metrics[1]:6.3f}, cwr = {last_metrics[2]:6.3f}, ' \ - f'ted = {last_metrics[3]:6.3f}, ned = {last_metrics[4]:6.0f}, ' \ - f'ted/w = {last_metrics[5]:6.3f}, ' - logging.info(log_str) - -if __name__ == '__main__': - main() diff --git a/spaces/captchaboy/fastest-8kun-captchas-solver/app.py b/spaces/captchaboy/fastest-8kun-captchas-solver/app.py deleted file mode 100644 index 6e4f84dbd37eb922466c230e71913fbf1b546830..0000000000000000000000000000000000000000 --- a/spaces/captchaboy/fastest-8kun-captchas-solver/app.py +++ /dev/null @@ -1,104 +0,0 @@ -# from transformers import AutoModel -import argparse -import logging -import os -import glob -import tqdm -import torch, re -import PIL -import cv2 -import numpy as np -import torch.nn.functional as F -from torchvision import transforms -from utils import Config, Logger, CharsetMapper -import gradio as gr - -import gdown -gdown.download(id='16PF_b4dURVkBt4OT7E-a-vq-SRxi0uDl', output='lol.pth') -gdown.download(id='19rGjfo73P25O_keQv30snfe3IHrK0uV2', output='config.yaml') - -gdown.download(id='1qyNV80qmYHx_r4KsG3_8PXQ6ff1a1dov', output='modules.zip') - -gdown.download(id='1UMZ7i8SpfuNw0N2JvVY8euaNx9gu3x6N', output='configs.zip') - -gdown.download(id='1yHD7_4DD_keUwGs2nenAYDaQ2CNEA5IU', output='data.zip') -os.system('unzip data.zip && unzip configs.zip && unzip modules.zip') - - -def get_model(config): - import importlib - names = config.model_name.split('.') - module_name, class_name = '.'.join(names[:-1]), names[-1] - cls = getattr(importlib.import_module(module_name), class_name) - model = cls(config) - logging.info(model) - model = model.eval() - return model - - -def load(model, file, device=None, strict=True): - if device is None: device = 'cpu' - elif isinstance(device, int): device = torch.device('cuda', device) - assert os.path.isfile(file) - state = torch.load(file, map_location=device) - if set(state.keys()) == {'model', 'opt'}: - state = state['model'] - model.load_state_dict(state, strict=strict) - return model - -config = Config('config.yaml') -config.model_vision_checkpoint = None -model = get_model(config) -model = load(model, 'lol.pth') - - -def postprocess(output, charset, model_eval): - def _get_output(last_output, model_eval): - if isinstance(last_output, (tuple, list)): - for res in last_output: - if res['name'] == model_eval: output = res - else: output = last_output - return output - - def _decode(logit): - """ Greed decode """ - out = F.softmax(logit, dim=2) - pt_text, pt_scores, pt_lengths = [], [], [] - for o in out: - text = charset.get_text(o.argmax(dim=1), padding=False, trim=False) - text = text.split(charset.null_char)[0] # end at end-token - pt_text.append(text) - pt_scores.append(o.max(dim=1)[0]) - pt_lengths.append(min(len(text) + 1, charset.max_length)) # one for end-token - return pt_text, pt_scores, pt_lengths - - output = _get_output(output, model_eval) - logits, pt_lengths = output['logits'], output['pt_lengths'] - pt_text, pt_scores, pt_lengths_ = _decode(logits) - - return pt_text, pt_scores, pt_lengths_ - -def preprocess(img, width, height): - img = cv2.resize(np.array(img), (width, height)) - img = transforms.ToTensor()(img).unsqueeze(0) - mean = torch.tensor([0.485, 0.456, 0.406]) - std = torch.tensor([0.229, 0.224, 0.225]) - return (img-mean[...,None,None]) / std[...,None,None] - -def process_image(image): - charset = CharsetMapper(filename=config.dataset_charset_path, max_length=config.dataset_max_length + 1) - - img = image.convert('RGB') - img = preprocess(img, config.dataset_image_width, config.dataset_image_height) - res = model(img) - return postprocess(res, charset, 'alignment')[0][0] - -iface = gr.Interface(fn=process_image, - inputs=gr.inputs.Image(type="pil"), - outputs=gr.outputs.Textbox(), - title="8kun kek", - description="Making Jim Watkins sheete because he is a techlet pedo", - # article=article, - # examples=glob.glob('figs/test/*.png') - ) -iface.launch(debug=True) \ No newline at end of file diff --git a/spaces/caslabs/midi-autocompletion/musicautobot/vocab.py b/spaces/caslabs/midi-autocompletion/musicautobot/vocab.py deleted file mode 100644 index f363f618f90501eda745d35c358565d15e80e338..0000000000000000000000000000000000000000 --- a/spaces/caslabs/midi-autocompletion/musicautobot/vocab.py +++ /dev/null @@ -1,93 +0,0 @@ -from fastai.basics import * -from .numpy_encode import * -from .music_transformer import transform - -BOS = 'xxbos' -PAD = 'xxpad' -EOS = 'xxeos' -MASK = 'xxmask' # Used for BERT masked language modeling. -CSEQ = 'xxcseq' # Used for Seq2Seq translation - denotes start of chord sequence -MSEQ = 'xxmseq' # Used for Seq2Seq translation - denotes start of melody sequence - -# Deprecated tokens. Kept for compatibility -S2SCLS = 'xxs2scls' # deprecated -NSCLS = 'xxnscls' # deprecated - -SEP = 'xxsep' # Used to denote end of timestep (required for polyphony). separator idx = -1 (part of notes) - -SPECIAL_TOKS = [BOS, PAD, EOS, S2SCLS, MASK, CSEQ, MSEQ, NSCLS, SEP] # Important: SEP token must be last - -NOTE_TOKS = [f'n{i}' for i in range(NOTE_SIZE)] -DUR_TOKS = [f'd{i}' for i in range(DUR_SIZE)] -NOTE_START, NOTE_END = NOTE_TOKS[0], NOTE_TOKS[-1] -DUR_START, DUR_END = DUR_TOKS[0], DUR_TOKS[-1] - -MTEMPO_SIZE = 10 -MTEMPO_OFF = 'mt0' -MTEMPO_TOKS = [f'mt{i}' for i in range(MTEMPO_SIZE)] - -# Vocab - token to index mapping -class MusicVocab(): - "Contain the correspondence between numbers and tokens and numericalize." - def __init__(self, itos:Collection[str]): - self.itos = itos - self.stoi = {v:k for k,v in enumerate(self.itos)} - - def numericalize(self, t:Collection[str]) -> List[int]: - "Convert a list of tokens `t` to their ids." - return [self.stoi[w] for w in t] - - def textify(self, nums:Collection[int], sep=' ') -> List[str]: - "Convert a list of `nums` to their tokens." - items = [self.itos[i] for i in nums] - return sep.join(items) if sep is not None else items - - def to_music_item(self, idxenc): - return transform.MusicItem(idxenc, self) - - @property - def mask_idx(self): return self.stoi[MASK] - @property - def pad_idx(self): return self.stoi[PAD] - @property - def bos_idx(self): return self.stoi[BOS] - @property - def sep_idx(self): return self.stoi[SEP] - @property - def npenc_range(self): return (self.stoi[SEP], self.stoi[DUR_END]+1) - @property - def note_range(self): return self.stoi[NOTE_START], self.stoi[NOTE_END]+1 - @property - def dur_range(self): return self.stoi[DUR_START], self.stoi[DUR_END]+1 - - def is_duration(self, idx): - return idx >= self.dur_range[0] and idx < self.dur_range[1] - def is_duration_or_pad(self, idx): - return idx == self.pad_idx or self.is_duration(idx) - - def __getstate__(self): - return {'itos':self.itos} - - def __setstate__(self, state:dict): - self.itos = state['itos'] - self.stoi = {v:k for k,v in enumerate(self.itos)} - - def __len__(self): return len(self.itos) - - def save(self, path): - "Save `self.itos` in `path`" - pickle.dump(self.itos, open(path, 'wb')) - - @classmethod - def create(cls) -> 'Vocab': - "Create a vocabulary from a set of `tokens`." - itos = SPECIAL_TOKS + NOTE_TOKS + DUR_TOKS + MTEMPO_TOKS - if len(itos)%8 != 0: - itos = itos + [f'dummy{i}' for i in range(len(itos)%8)] - return cls(itos) - - @classmethod - def load(cls, path): - "Load the `Vocab` contained in `path`" - itos = pickle.load(open(path, 'rb')) - return cls(itos) diff --git a/spaces/cc1799/vits-uma-genshin-honkai/commons.py b/spaces/cc1799/vits-uma-genshin-honkai/commons.py deleted file mode 100644 index 40fcc05364d4815971f5c6f9dbb8dcef8e3ec1e9..0000000000000000000000000000000000000000 --- a/spaces/cc1799/vits-uma-genshin-honkai/commons.py +++ /dev/null @@ -1,172 +0,0 @@ -import math -import torch -from torch.nn import functional as F -import torch.jit - - -def script_method(fn, _rcb=None): - return fn - - -def script(obj, optimize=True, _frames_up=0, _rcb=None): - return obj - - -torch.jit.script_method = script_method -torch.jit.script = script - - -def init_weights(m, mean=0.0, std=0.01): - classname = m.__class__.__name__ - if classname.find("Conv") != -1: - m.weight.data.normal_(mean, std) - - -def get_padding(kernel_size, dilation=1): - return int((kernel_size*dilation - dilation)/2) - - -def convert_pad_shape(pad_shape): - l = pad_shape[::-1] - pad_shape = [item for sublist in l for item in sublist] - return pad_shape - - -def intersperse(lst, item): - result = [item] * (len(lst) * 2 + 1) - result[1::2] = lst - return result - - -def kl_divergence(m_p, logs_p, m_q, logs_q): - """KL(P||Q)""" - kl = (logs_q - logs_p) - 0.5 - kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q) - return kl - - -def rand_gumbel(shape): - """Sample from the Gumbel distribution, protect from overflows.""" - uniform_samples = torch.rand(shape) * 0.99998 + 0.00001 - return -torch.log(-torch.log(uniform_samples)) - - -def rand_gumbel_like(x): - g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device) - return g - - -def slice_segments(x, ids_str, segment_size=4): - ret = torch.zeros_like(x[:, :, :segment_size]) - for i in range(x.size(0)): - idx_str = ids_str[i] - idx_end = idx_str + segment_size - ret[i] = x[i, :, idx_str:idx_end] - return ret - - -def rand_slice_segments(x, x_lengths=None, segment_size=4): - b, d, t = x.size() - if x_lengths is None: - x_lengths = t - ids_str_max = x_lengths - segment_size + 1 - ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long) - ret = slice_segments(x, ids_str, segment_size) - return ret, ids_str - - -def get_timing_signal_1d( - length, channels, min_timescale=1.0, max_timescale=1.0e4): - position = torch.arange(length, dtype=torch.float) - num_timescales = channels // 2 - log_timescale_increment = ( - math.log(float(max_timescale) / float(min_timescale)) / - (num_timescales - 1)) - inv_timescales = min_timescale * torch.exp( - torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment) - scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1) - signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0) - signal = F.pad(signal, [0, 0, 0, channels % 2]) - signal = signal.view(1, channels, length) - return signal - - -def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4): - b, channels, length = x.size() - signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale) - return x + signal.to(dtype=x.dtype, device=x.device) - - -def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1): - b, channels, length = x.size() - signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale) - return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis) - - -def subsequent_mask(length): - mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0) - return mask - - -@torch.jit.script -def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels): - n_channels_int = n_channels[0] - in_act = input_a + input_b - t_act = torch.tanh(in_act[:, :n_channels_int, :]) - s_act = torch.sigmoid(in_act[:, n_channels_int:, :]) - acts = t_act * s_act - return acts - - -def convert_pad_shape(pad_shape): - l = pad_shape[::-1] - pad_shape = [item for sublist in l for item in sublist] - return pad_shape - - -def shift_1d(x): - x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1] - return x - - -def sequence_mask(length, max_length=None): - if max_length is None: - max_length = length.max() - x = torch.arange(max_length, dtype=length.dtype, device=length.device) - return x.unsqueeze(0) < length.unsqueeze(1) - - -def generate_path(duration, mask): - """ - duration: [b, 1, t_x] - mask: [b, 1, t_y, t_x] - """ - device = duration.device - - b, _, t_y, t_x = mask.shape - cum_duration = torch.cumsum(duration, -1) - - cum_duration_flat = cum_duration.view(b * t_x) - path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype) - path = path.view(b, t_x, t_y) - path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1] - path = path.unsqueeze(1).transpose(2,3) * mask - return path - - -def clip_grad_value_(parameters, clip_value, norm_type=2): - if isinstance(parameters, torch.Tensor): - parameters = [parameters] - parameters = list(filter(lambda p: p.grad is not None, parameters)) - norm_type = float(norm_type) - if clip_value is not None: - clip_value = float(clip_value) - - total_norm = 0 - for p in parameters: - param_norm = p.grad.data.norm(norm_type) - total_norm += param_norm.item() ** norm_type - if clip_value is not None: - p.grad.data.clamp_(min=-clip_value, max=clip_value) - total_norm = total_norm ** (1. / norm_type) - return total_norm diff --git a/spaces/ccolas/TastyPiano/src/music/utilities/handcoded_rep_utilities/tht/tests/__init__.py b/spaces/ccolas/TastyPiano/src/music/utilities/handcoded_rep_utilities/tht/tests/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/celise88/Pathfinder/scrape_onet.py b/spaces/celise88/Pathfinder/scrape_onet.py deleted file mode 100644 index 6b6182f2978a51677132baad33a62bee09079773..0000000000000000000000000000000000000000 --- a/spaces/celise88/Pathfinder/scrape_onet.py +++ /dev/null @@ -1,56 +0,0 @@ -import requests -from bs4 import BeautifulSoup -from cleantext import clean -import pandas as pd -import numpy as np - -onet = pd.read_csv('static/ONET_JobTitles.csv') -headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15'} - -def remove_new_line(value): - return ''.join(value.splitlines()) - -def get_onet_code(jobtitle): - onetCode = onet.loc[onet['JobTitle'] == jobtitle, 'onetCode'] - onetCode = onetCode.reindex().tolist()[0] - return onetCode - -def get_onet_description(onetCode): - url = "https://www.onetonline.org/link/summary/" + onetCode - response = requests.get(url, headers=headers) - soup = BeautifulSoup(response.text, 'html.parser') - jobdescription = soup.p.get_text() - return jobdescription - -def get_onet_tasks(onetCode): - headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15'} - url = "https://www.onetonline.org/link/result/" + onetCode + "?c=tk&n_tk=0&s_tk=IM&c_tk=0" - response = requests.get(url, headers=headers) - soup = BeautifulSoup(response.text, 'html.parser') - tasks = str(soup.get_text('reportsubdesc')).replace("reportsubdesc", " ").replace("ImportanceCategoryTask ", "") - tasks = clean(tasks) - tasks = tasks.split('show all show top 10')[1] - tasks = tasks.split('occupations related to multiple tasks')[0] - tasks = remove_new_line(tasks).replace("related occupations", " ").replace("core", " - ").replace(" )importance category task", "").replace(" find ", "") - tasks = tasks.split(". ") - tasks = [''.join(map(lambda c: '' if c in '0123456789-' else c, task)) for task in tasks] - return tasks - -def get_job_postings(onetCode, state): - headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15'} - url = "https://www.onetonline.org/link/localjobs/" + onetCode + "?st=" + state - response = requests.get(url, headers=headers) - soup = BeautifulSoup(response.text, 'html.parser') - jobs = str(soup.get_text("tbody")).split('PostedtbodyTitle and CompanytbodyLocation')[1].split('Sources:')[0].split("tbody") - jobs = jobs[5:45] - starts = np.linspace(start=0, stop=len(jobs)-4,num= 10) - stops = np.linspace(start=3, stop=len(jobs)-1, num= 10) - jobpostings = [] - for i in range(0,10): - jobpostings.append(str([' '.join(jobs[int(starts[i]):int(stops[i])])]).replace("['", '').replace("']", '')) - links = str(soup.find_all('a', href=True)).split("")[1].split(', ')[0].replace("href=", "") - linklist.append(links[i].replace('"', '')) - return jobpostings, linklist \ No newline at end of file diff --git a/spaces/cfwef/gpt/crazy_functions/test_project/cpp/cppipc/prod_cons.h b/spaces/cfwef/gpt/crazy_functions/test_project/cpp/cppipc/prod_cons.h deleted file mode 100644 index c9004bb8043a12e32814436baa6262a00c8ef68e..0000000000000000000000000000000000000000 --- a/spaces/cfwef/gpt/crazy_functions/test_project/cpp/cppipc/prod_cons.h +++ /dev/null @@ -1,433 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -#include "libipc/def.h" - -#include "libipc/platform/detail.h" -#include "libipc/circ/elem_def.h" -#include "libipc/utility/log.h" -#include "libipc/utility/utility.h" - -namespace ipc { - -//////////////////////////////////////////////////////////////// -/// producer-consumer implementation -//////////////////////////////////////////////////////////////// - -template -struct prod_cons_impl; - -template <> -struct prod_cons_impl> { - - template - struct elem_t { - std::aligned_storage_t data_ {}; - }; - - alignas(cache_line_size) std::atomic rd_; // read index - alignas(cache_line_size) std::atomic wt_; // write index - - constexpr circ::u2_t cursor() const noexcept { - return 0; - } - - template - bool push(W* /*wrapper*/, F&& f, E* elems) { - auto cur_wt = circ::index_of(wt_.load(std::memory_order_relaxed)); - if (cur_wt == circ::index_of(rd_.load(std::memory_order_acquire) - 1)) { - return false; // full - } - std::forward(f)(&(elems[cur_wt].data_)); - wt_.fetch_add(1, std::memory_order_release); - return true; - } - - /** - * In single-single-unicast, 'force_push' means 'no reader' or 'the only one reader is dead'. - * So we could just disconnect all connections of receiver, and return false. - */ - template - bool force_push(W* wrapper, F&&, E*) { - wrapper->elems()->disconnect_receiver(~static_cast(0u)); - return false; - } - - template - bool pop(W* /*wrapper*/, circ::u2_t& /*cur*/, F&& f, R&& out, E* elems) { - auto cur_rd = circ::index_of(rd_.load(std::memory_order_relaxed)); - if (cur_rd == circ::index_of(wt_.load(std::memory_order_acquire))) { - return false; // empty - } - std::forward(f)(&(elems[cur_rd].data_)); - std::forward(out)(true); - rd_.fetch_add(1, std::memory_order_release); - return true; - } -}; - -template <> -struct prod_cons_impl> - : prod_cons_impl> { - - template - bool force_push(W* wrapper, F&&, E*) { - wrapper->elems()->disconnect_receiver(1); - return false; - } - - template class E, std::size_t DS, std::size_t AS> - bool pop(W* /*wrapper*/, circ::u2_t& /*cur*/, F&& f, R&& out, E* elems) { - byte_t buff[DS]; - for (unsigned k = 0;;) { - auto cur_rd = rd_.load(std::memory_order_relaxed); - if (circ::index_of(cur_rd) == - circ::index_of(wt_.load(std::memory_order_acquire))) { - return false; // empty - } - std::memcpy(buff, &(elems[circ::index_of(cur_rd)].data_), sizeof(buff)); - if (rd_.compare_exchange_weak(cur_rd, cur_rd + 1, std::memory_order_release)) { - std::forward(f)(buff); - std::forward(out)(true); - return true; - } - ipc::yield(k); - } - } -}; - -template <> -struct prod_cons_impl> - : prod_cons_impl> { - - using flag_t = std::uint64_t; - - template - struct elem_t { - std::aligned_storage_t data_ {}; - std::atomic f_ct_ { 0 }; // commit flag - }; - - alignas(cache_line_size) std::atomic ct_; // commit index - - template - bool push(W* /*wrapper*/, F&& f, E* elems) { - circ::u2_t cur_ct, nxt_ct; - for (unsigned k = 0;;) { - cur_ct = ct_.load(std::memory_order_relaxed); - if (circ::index_of(nxt_ct = cur_ct + 1) == - circ::index_of(rd_.load(std::memory_order_acquire))) { - return false; // full - } - if (ct_.compare_exchange_weak(cur_ct, nxt_ct, std::memory_order_acq_rel)) { - break; - } - ipc::yield(k); - } - auto* el = elems + circ::index_of(cur_ct); - std::forward(f)(&(el->data_)); - // set flag & try update wt - el->f_ct_.store(~static_cast(cur_ct), std::memory_order_release); - while (1) { - auto cac_ct = el->f_ct_.load(std::memory_order_acquire); - if (cur_ct != wt_.load(std::memory_order_relaxed)) { - return true; - } - if ((~cac_ct) != cur_ct) { - return true; - } - if (!el->f_ct_.compare_exchange_strong(cac_ct, 0, std::memory_order_relaxed)) { - return true; - } - wt_.store(nxt_ct, std::memory_order_release); - cur_ct = nxt_ct; - nxt_ct = cur_ct + 1; - el = elems + circ::index_of(cur_ct); - } - return true; - } - - template - bool force_push(W* wrapper, F&&, E*) { - wrapper->elems()->disconnect_receiver(1); - return false; - } - - template class E, std::size_t DS, std::size_t AS> - bool pop(W* /*wrapper*/, circ::u2_t& /*cur*/, F&& f, R&& out, E* elems) { - byte_t buff[DS]; - for (unsigned k = 0;;) { - auto cur_rd = rd_.load(std::memory_order_relaxed); - auto cur_wt = wt_.load(std::memory_order_acquire); - auto id_rd = circ::index_of(cur_rd); - auto id_wt = circ::index_of(cur_wt); - if (id_rd == id_wt) { - auto* el = elems + id_wt; - auto cac_ct = el->f_ct_.load(std::memory_order_acquire); - if ((~cac_ct) != cur_wt) { - return false; // empty - } - if (el->f_ct_.compare_exchange_weak(cac_ct, 0, std::memory_order_relaxed)) { - wt_.store(cur_wt + 1, std::memory_order_release); - } - k = 0; - } - else { - std::memcpy(buff, &(elems[circ::index_of(cur_rd)].data_), sizeof(buff)); - if (rd_.compare_exchange_weak(cur_rd, cur_rd + 1, std::memory_order_release)) { - std::forward(f)(buff); - std::forward(out)(true); - return true; - } - ipc::yield(k); - } - } - } -}; - -template <> -struct prod_cons_impl> { - - using rc_t = std::uint64_t; - - enum : rc_t { - ep_mask = 0x00000000ffffffffull, - ep_incr = 0x0000000100000000ull - }; - - template - struct elem_t { - std::aligned_storage_t data_ {}; - std::atomic rc_ { 0 }; // read-counter - }; - - alignas(cache_line_size) std::atomic wt_; // write index - alignas(cache_line_size) rc_t epoch_ { 0 }; // only one writer - - circ::u2_t cursor() const noexcept { - return wt_.load(std::memory_order_acquire); - } - - template - bool push(W* wrapper, F&& f, E* elems) { - E* el; - for (unsigned k = 0;;) { - circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed); - if (cc == 0) return false; // no reader - el = elems + circ::index_of(wt_.load(std::memory_order_relaxed)); - // check all consumers have finished reading this element - auto cur_rc = el->rc_.load(std::memory_order_acquire); - circ::cc_t rem_cc = cur_rc & ep_mask; - if ((cc & rem_cc) && ((cur_rc & ~ep_mask) == epoch_)) { - return false; // has not finished yet - } - // consider rem_cc to be 0 here - if (el->rc_.compare_exchange_weak( - cur_rc, epoch_ | static_cast(cc), std::memory_order_release)) { - break; - } - ipc::yield(k); - } - std::forward(f)(&(el->data_)); - wt_.fetch_add(1, std::memory_order_release); - return true; - } - - template - bool force_push(W* wrapper, F&& f, E* elems) { - E* el; - epoch_ += ep_incr; - for (unsigned k = 0;;) { - circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed); - if (cc == 0) return false; // no reader - el = elems + circ::index_of(wt_.load(std::memory_order_relaxed)); - // check all consumers have finished reading this element - auto cur_rc = el->rc_.load(std::memory_order_acquire); - circ::cc_t rem_cc = cur_rc & ep_mask; - if (cc & rem_cc) { - ipc::log("force_push: k = %u, cc = %u, rem_cc = %u\n", k, cc, rem_cc); - cc = wrapper->elems()->disconnect_receiver(rem_cc); // disconnect all invalid readers - if (cc == 0) return false; // no reader - } - // just compare & exchange - if (el->rc_.compare_exchange_weak( - cur_rc, epoch_ | static_cast(cc), std::memory_order_release)) { - break; - } - ipc::yield(k); - } - std::forward(f)(&(el->data_)); - wt_.fetch_add(1, std::memory_order_release); - return true; - } - - template - bool pop(W* wrapper, circ::u2_t& cur, F&& f, R&& out, E* elems) { - if (cur == cursor()) return false; // acquire - auto* el = elems + circ::index_of(cur++); - std::forward(f)(&(el->data_)); - for (unsigned k = 0;;) { - auto cur_rc = el->rc_.load(std::memory_order_acquire); - if ((cur_rc & ep_mask) == 0) { - std::forward(out)(true); - return true; - } - auto nxt_rc = cur_rc & ~static_cast(wrapper->connected_id()); - if (el->rc_.compare_exchange_weak(cur_rc, nxt_rc, std::memory_order_release)) { - std::forward(out)((nxt_rc & ep_mask) == 0); - return true; - } - ipc::yield(k); - } - } -}; - -template <> -struct prod_cons_impl> { - - using rc_t = std::uint64_t; - using flag_t = std::uint64_t; - - enum : rc_t { - rc_mask = 0x00000000ffffffffull, - ep_mask = 0x00ffffffffffffffull, - ep_incr = 0x0100000000000000ull, - ic_mask = 0xff000000ffffffffull, - ic_incr = 0x0000000100000000ull - }; - - template - struct elem_t { - std::aligned_storage_t data_ {}; - std::atomic rc_ { 0 }; // read-counter - std::atomic f_ct_ { 0 }; // commit flag - }; - - alignas(cache_line_size) std::atomic ct_; // commit index - alignas(cache_line_size) std::atomic epoch_ { 0 }; - - circ::u2_t cursor() const noexcept { - return ct_.load(std::memory_order_acquire); - } - - constexpr static rc_t inc_rc(rc_t rc) noexcept { - return (rc & ic_mask) | ((rc + ic_incr) & ~ic_mask); - } - - constexpr static rc_t inc_mask(rc_t rc) noexcept { - return inc_rc(rc) & ~rc_mask; - } - - template - bool push(W* wrapper, F&& f, E* elems) { - E* el; - circ::u2_t cur_ct; - rc_t epoch = epoch_.load(std::memory_order_acquire); - for (unsigned k = 0;;) { - circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed); - if (cc == 0) return false; // no reader - el = elems + circ::index_of(cur_ct = ct_.load(std::memory_order_relaxed)); - // check all consumers have finished reading this element - auto cur_rc = el->rc_.load(std::memory_order_relaxed); - circ::cc_t rem_cc = cur_rc & rc_mask; - if ((cc & rem_cc) && ((cur_rc & ~ep_mask) == epoch)) { - return false; // has not finished yet - } - else if (!rem_cc) { - auto cur_fl = el->f_ct_.load(std::memory_order_acquire); - if ((cur_fl != cur_ct) && cur_fl) { - return false; // full - } - } - // consider rem_cc to be 0 here - if (el->rc_.compare_exchange_weak( - cur_rc, inc_mask(epoch | (cur_rc & ep_mask)) | static_cast(cc), std::memory_order_relaxed) && - epoch_.compare_exchange_weak(epoch, epoch, std::memory_order_acq_rel)) { - break; - } - ipc::yield(k); - } - // only one thread/process would touch here at one time - ct_.store(cur_ct + 1, std::memory_order_release); - std::forward(f)(&(el->data_)); - // set flag & try update wt - el->f_ct_.store(~static_cast(cur_ct), std::memory_order_release); - return true; - } - - template - bool force_push(W* wrapper, F&& f, E* elems) { - E* el; - circ::u2_t cur_ct; - rc_t epoch = epoch_.fetch_add(ep_incr, std::memory_order_release) + ep_incr; - for (unsigned k = 0;;) { - circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed); - if (cc == 0) return false; // no reader - el = elems + circ::index_of(cur_ct = ct_.load(std::memory_order_relaxed)); - // check all consumers have finished reading this element - auto cur_rc = el->rc_.load(std::memory_order_acquire); - circ::cc_t rem_cc = cur_rc & rc_mask; - if (cc & rem_cc) { - ipc::log("force_push: k = %u, cc = %u, rem_cc = %u\n", k, cc, rem_cc); - cc = wrapper->elems()->disconnect_receiver(rem_cc); // disconnect all invalid readers - if (cc == 0) return false; // no reader - } - // just compare & exchange - if (el->rc_.compare_exchange_weak( - cur_rc, inc_mask(epoch | (cur_rc & ep_mask)) | static_cast(cc), std::memory_order_relaxed)) { - if (epoch == epoch_.load(std::memory_order_acquire)) { - break; - } - else if (push(wrapper, std::forward(f), elems)) { - return true; - } - epoch = epoch_.fetch_add(ep_incr, std::memory_order_release) + ep_incr; - } - ipc::yield(k); - } - // only one thread/process would touch here at one time - ct_.store(cur_ct + 1, std::memory_order_release); - std::forward(f)(&(el->data_)); - // set flag & try update wt - el->f_ct_.store(~static_cast(cur_ct), std::memory_order_release); - return true; - } - - template - bool pop(W* wrapper, circ::u2_t& cur, F&& f, R&& out, E(& elems)[N]) { - auto* el = elems + circ::index_of(cur); - auto cur_fl = el->f_ct_.load(std::memory_order_acquire); - if (cur_fl != ~static_cast(cur)) { - return false; // empty - } - ++cur; - std::forward(f)(&(el->data_)); - for (unsigned k = 0;;) { - auto cur_rc = el->rc_.load(std::memory_order_acquire); - if ((cur_rc & rc_mask) == 0) { - std::forward(out)(true); - el->f_ct_.store(cur + N - 1, std::memory_order_release); - return true; - } - auto nxt_rc = inc_rc(cur_rc) & ~static_cast(wrapper->connected_id()); - bool last_one = false; - if ((last_one = (nxt_rc & rc_mask) == 0)) { - el->f_ct_.store(cur + N - 1, std::memory_order_release); - } - if (el->rc_.compare_exchange_weak(cur_rc, nxt_rc, std::memory_order_release)) { - std::forward(out)(last_one); - return true; - } - ipc::yield(k); - } - } -}; - -} // namespace ipc diff --git a/spaces/chasemcdo/hf_localai/examples/langchain-python/test.py b/spaces/chasemcdo/hf_localai/examples/langchain-python/test.py deleted file mode 100644 index a9fac3513897f6d328ba38d733e1909d9e8df0a4..0000000000000000000000000000000000000000 --- a/spaces/chasemcdo/hf_localai/examples/langchain-python/test.py +++ /dev/null @@ -1,6 +0,0 @@ - -from langchain.llms import OpenAI - -llm = OpenAI(temperature=0.9,model_name="gpt-3.5-turbo") -text = "What would be a good company name for a company that makes colorful socks?" -print(llm(text)) diff --git a/spaces/chendl/compositional_test/transformers/scripts/fsmt/fsmt-make-super-tiny-model.py b/spaces/chendl/compositional_test/transformers/scripts/fsmt/fsmt-make-super-tiny-model.py deleted file mode 100644 index 4a6b8e0c1b4cc3d8170780bfbfcedd807bd68af4..0000000000000000000000000000000000000000 --- a/spaces/chendl/compositional_test/transformers/scripts/fsmt/fsmt-make-super-tiny-model.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 -# Copyright 2020 The HuggingFace Team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# This script creates a super tiny model that is useful inside tests, when we just want to test that -# the machinery works, without needing to the check the quality of the outcomes. -# -# This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - -# all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and -# emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files. -# The latter is done by `fsmt-make-super-tiny-model.py`. -# -# It will be used then as "stas/tiny-wmt19-en-ru" - -from pathlib import Path -import json -import tempfile - -from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration -from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES - -mname_tiny = "tiny-wmt19-en-ru" - -# Build - -# borrowed from a test -vocab = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "w", "r", "t", "lo", "low", "er", "low", "lowest", "newer", "wider", "", ] -vocab_tokens = dict(zip(vocab, range(len(vocab)))) -merges = ["l o 123", "lo w 1456", "e r 1789", ""] - -with tempfile.TemporaryDirectory() as tmpdirname: - build_dir = Path(tmpdirname) - src_vocab_file = build_dir / VOCAB_FILES_NAMES["src_vocab_file"] - tgt_vocab_file = build_dir / VOCAB_FILES_NAMES["tgt_vocab_file"] - merges_file = build_dir / VOCAB_FILES_NAMES["merges_file"] - with open(src_vocab_file, "w") as fp: fp.write(json.dumps(vocab_tokens)) - with open(tgt_vocab_file, "w") as fp: fp.write(json.dumps(vocab_tokens)) - with open(merges_file, "w") as fp : fp.write("\n".join(merges)) - - tokenizer = FSMTTokenizer( - langs=["en", "ru"], - src_vocab_size = len(vocab), - tgt_vocab_size = len(vocab), - src_vocab_file=src_vocab_file, - tgt_vocab_file=tgt_vocab_file, - merges_file=merges_file, - ) - -config = FSMTConfig( - langs=['ru', 'en'], - src_vocab_size=1000, tgt_vocab_size=1000, - d_model=4, - encoder_layers=1, decoder_layers=1, - encoder_ffn_dim=4, decoder_ffn_dim=4, - encoder_attention_heads=1, decoder_attention_heads=1, -) - -tiny_model = FSMTForConditionalGeneration(config) -print(f"num of params {tiny_model.num_parameters()}") - -# Test -batch = tokenizer(["Making tiny model"], return_tensors="pt") -outputs = tiny_model(**batch) - -print("test output:", len(outputs.logits[0])) - -# Save -tiny_model.half() # makes it smaller -tiny_model.save_pretrained(mname_tiny) -tokenizer.save_pretrained(mname_tiny) - -print(f"Generated {mname_tiny}") - -# Upload -# transformers-cli upload tiny-wmt19-en-ru diff --git a/spaces/chikoto/Umamusume-DeBERTa-VITS2-TTS-JP/bert_gen.py b/spaces/chikoto/Umamusume-DeBERTa-VITS2-TTS-JP/bert_gen.py deleted file mode 100644 index 25cd7d97bafa02c514d0e1a34621546eac10da53..0000000000000000000000000000000000000000 --- a/spaces/chikoto/Umamusume-DeBERTa-VITS2-TTS-JP/bert_gen.py +++ /dev/null @@ -1,59 +0,0 @@ -import torch -from multiprocessing import Pool -import commons -import utils -from tqdm import tqdm -from text import cleaned_text_to_sequence, get_bert -import argparse -import torch.multiprocessing as mp - - -def process_line(line): - rank = mp.current_process()._identity - rank = rank[0] if len(rank) > 0 else 0 - if torch.cuda.is_available(): - gpu_id = rank % torch.cuda.device_count() - device = torch.device(f"cuda:{gpu_id}") - wav_path, _, language_str, text, phones, tone, word2ph = line.strip().split("|") - phone = phones.split(" ") - tone = [int(i) for i in tone.split(" ")] - word2ph = [int(i) for i in word2ph.split(" ")] - word2ph = [i for i in word2ph] - phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str) - - phone = commons.intersperse(phone, 0) - tone = commons.intersperse(tone, 0) - language = commons.intersperse(language, 0) - for i in range(len(word2ph)): - word2ph[i] = word2ph[i] * 2 - word2ph[0] += 1 - - bert_path = wav_path.replace(".wav", ".bert.pt") - - try: - bert = torch.load(bert_path) - assert bert.shape[-1] == len(phone) - except Exception: - bert = get_bert(text, word2ph, language_str, device) - assert bert.shape[-1] == len(phone) - torch.save(bert, bert_path) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("-c", "--config", type=str, default="configs/config.json") - parser.add_argument("--num_processes", type=int, default=2) - args = parser.parse_args() - config_path = args.config - hps = utils.get_hparams_from_file(config_path) - lines = [] - with open(hps.data.training_files, encoding="utf-8") as f: - lines.extend(f.readlines()) - - with open(hps.data.validation_files, encoding="utf-8") as f: - lines.extend(f.readlines()) - - num_processes = args.num_processes - with Pool(processes=num_processes) as pool: - for _ in tqdm(pool.imap_unordered(process_line, lines), total=len(lines)): - pass diff --git a/spaces/chilge/taoli/add_speaker.py b/spaces/chilge/taoli/add_speaker.py deleted file mode 100644 index e224f07c892a5fe1837e3cbf1745e0d8992ea283..0000000000000000000000000000000000000000 --- a/spaces/chilge/taoli/add_speaker.py +++ /dev/null @@ -1,62 +0,0 @@ -import os -import argparse -from tqdm import tqdm -from random import shuffle -import json - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--train_list", type=str, default="./filelists/train.txt", help="path to train list") - parser.add_argument("--val_list", type=str, default="./filelists/val.txt", help="path to val list") - parser.add_argument("--test_list", type=str, default="./filelists/test.txt", help="path to test list") - parser.add_argument("--source_dir", type=str, default="./dataset/32k", help="path to source dir") - args = parser.parse_args() - - previous_config = json.load(open("configs/config.json", "rb")) - - train = [] - val = [] - test = [] - idx = 0 - spk_dict = previous_config["spk"] - spk_id = max([i for i in spk_dict.values()]) + 1 - for speaker in tqdm(os.listdir(args.source_dir)): - if speaker not in spk_dict.keys(): - spk_dict[speaker] = spk_id - spk_id += 1 - wavs = [os.path.join(args.source_dir, speaker, i)for i in os.listdir(os.path.join(args.source_dir, speaker))] - wavs = [i for i in wavs if i.endswith("wav")] - shuffle(wavs) - train += wavs[2:-10] - val += wavs[:2] - test += wavs[-10:] - - assert previous_config["model"]["n_speakers"] > len(spk_dict.keys()) - shuffle(train) - shuffle(val) - shuffle(test) - - print("Writing", args.train_list) - with open(args.train_list, "w") as f: - for fname in tqdm(train): - wavpath = fname - f.write(wavpath + "\n") - - print("Writing", args.val_list) - with open(args.val_list, "w") as f: - for fname in tqdm(val): - wavpath = fname - f.write(wavpath + "\n") - - print("Writing", args.test_list) - with open(args.test_list, "w") as f: - for fname in tqdm(test): - wavpath = fname - f.write(wavpath + "\n") - - previous_config["spk"] = spk_dict - - print("Writing configs/config.json") - with open("configs/config.json", "w") as f: - json.dump(previous_config, f, indent=2) diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/ttLib/tables/S__i_l_l.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/ttLib/tables/S__i_l_l.py deleted file mode 100644 index 12b0b8f6cc55b337db857df99e27e7bb69bb5bbc..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/ttLib/tables/S__i_l_l.py +++ /dev/null @@ -1,87 +0,0 @@ -from fontTools.misc import sstruct -from fontTools.misc.fixedTools import floatToFixedToStr -from fontTools.misc.textTools import safeEval -from . import DefaultTable -from . import grUtils -import struct - -Sill_hdr = """ - > - version: 16.16F -""" - - -class table_S__i_l_l(DefaultTable.DefaultTable): - def __init__(self, tag=None): - DefaultTable.DefaultTable.__init__(self, tag) - self.langs = {} - - def decompile(self, data, ttFont): - (_, data) = sstruct.unpack2(Sill_hdr, data, self) - self.version = float(floatToFixedToStr(self.version, precisionBits=16)) - (numLangs,) = struct.unpack(">H", data[:2]) - data = data[8:] - maxsetting = 0 - langinfo = [] - for i in range(numLangs): - (langcode, numsettings, offset) = struct.unpack( - ">4sHH", data[i * 8 : (i + 1) * 8] - ) - offset = int(offset / 8) - (numLangs + 1) - langcode = langcode.replace(b"\000", b"") - langinfo.append((langcode.decode("utf-8"), numsettings, offset)) - maxsetting = max(maxsetting, offset + numsettings) - data = data[numLangs * 8 :] - finfo = [] - for i in range(maxsetting): - (fid, val, _) = struct.unpack(">LHH", data[i * 8 : (i + 1) * 8]) - finfo.append((fid, val)) - self.langs = {} - for c, n, o in langinfo: - self.langs[c] = [] - for i in range(o, o + n): - self.langs[c].append(finfo[i]) - - def compile(self, ttFont): - ldat = b"" - fdat = b"" - offset = len(self.langs) - for c, inf in sorted(self.langs.items()): - ldat += struct.pack(">4sHH", c.encode("utf8"), len(inf), 8 * offset + 20) - for fid, val in inf: - fdat += struct.pack(">LHH", fid, val, 0) - offset += len(inf) - ldat += struct.pack(">LHH", 0x80808080, 0, 8 * offset + 20) - return ( - sstruct.pack(Sill_hdr, self) - + grUtils.bininfo(len(self.langs)) - + ldat - + fdat - ) - - def toXML(self, writer, ttFont): - writer.simpletag("version", version=self.version) - writer.newline() - for c, inf in sorted(self.langs.items()): - writer.begintag("lang", name=c) - writer.newline() - for fid, val in inf: - writer.simpletag("feature", fid=grUtils.num2tag(fid), val=val) - writer.newline() - writer.endtag("lang") - writer.newline() - - def fromXML(self, name, attrs, content, ttFont): - if name == "version": - self.version = float(safeEval(attrs["version"])) - elif name == "lang": - c = attrs["name"] - self.langs[c] = [] - for element in content: - if not isinstance(element, tuple): - continue - tag, a, subcontent = element - if tag == "feature": - self.langs[c].append( - (grUtils.tag2num(a["fid"]), int(safeEval(a["val"]))) - ) diff --git a/spaces/cihyFjudo/fairness-paper-search/Bitty Mclean Forever Be Mine MP3 Learn More About the Artist and His Music.md b/spaces/cihyFjudo/fairness-paper-search/Bitty Mclean Forever Be Mine MP3 Learn More About the Artist and His Music.md deleted file mode 100644 index 3c8f2aa3afe4c6a3b223f92dfa732873dcf7ddd3..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/Bitty Mclean Forever Be Mine MP3 Learn More About the Artist and His Music.md +++ /dev/null @@ -1,10 +0,0 @@ - -

You can currently download the Bitty Mclean - Just To Let You Know... album for free in mp3, flac formats at mp3-lucky.com. It is also possible to buy "Bitty Mclean - Just To Let You Know..." on Amazon, Discogs as listen or rent it on Spotify, Apple Music.

-

Download free Waptrick Bitty McLean songs from Waptrick.com music download site. Listen Forever Be Mine Mp3 and download free Bitty McLean mp3 albums from Waptrick.com.

-

bitty mclean forever be mine mp3 free download


DOWNLOAD 🆓 https://tinurli.com/2uwjzP



-

Mp3 Juice is the most popular free mp3 search engine tool and music downloader, is very popular. MP3 Juice is a great tool to convert and download youtube videos and music. The Mp3 Juice website is the best way to quickly and easily download mp3 music. Its simplicity makes Mp3juice easy to use, so anyone can search for and download high-quality audio files

-

This website offers unlimited downloading of youtube music and Mp3 juice song free download in HD quality. You can also click "PLAY" to play the audio file before you download it. Mp3juices take only 2-5 seconds to convert and download audio files.

-

You can access this free mp3 download website online via an internet connection or WiFi. Bookmark this website to make it easy to access on a regular basis. Once you have downloaded the audio file, open it in any audio player to listen offline in high-quality.

-

MP3 juice music is easy to navigate through and provides a simple interface for downloading the audio. You might be wondering why people prefer mp3juices to get mp3 juice for free. This tool provides high-speed audio downloads, and users don't need to give any personal information.

aaccfb2cb3
-
-
\ No newline at end of file diff --git a/spaces/cihyFjudo/fairness-paper-search/Download Full Movie C.D. Kand Dubbed In Hindi ((LINK)).md b/spaces/cihyFjudo/fairness-paper-search/Download Full Movie C.D. Kand Dubbed In Hindi ((LINK)).md deleted file mode 100644 index 4555b80381b9c9d4e04e836fa528c23789075713..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/Download Full Movie C.D. Kand Dubbed In Hindi ((LINK)).md +++ /dev/null @@ -1,6 +0,0 @@ -

download full movie C.D. Kand dubbed in hindi


Download Zip 🗸🗸🗸 https://tinurli.com/2uwka8



- - aaccfb2cb3
-
-
-

diff --git a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/fontTools/feaLib/__init__.py b/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/fontTools/feaLib/__init__.py deleted file mode 100644 index ae532cd31b6eb54bdd5778c13989c1475b643db3..0000000000000000000000000000000000000000 --- a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/fontTools/feaLib/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -"""fontTools.feaLib -- a package for dealing with OpenType feature files.""" - -# The structure of OpenType feature files is defined here: -# http://www.adobe.com/devnet/opentype/afdko/topic_feature_file_syntax.html diff --git a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/fontTools/ttLib/tables/_c_i_d_g.py b/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/fontTools/ttLib/tables/_c_i_d_g.py deleted file mode 100644 index f11901baebf12fa8671730011ef27142b7d4cc04..0000000000000000000000000000000000000000 --- a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/fontTools/ttLib/tables/_c_i_d_g.py +++ /dev/null @@ -1,19 +0,0 @@ -# coding: utf-8 -from .otBase import BaseTTXConverter - - -class table__c_i_d_g(BaseTTXConverter): - """The AAT ``cidg`` table has almost the same structure as ``gidc``, - just mapping CIDs to GlyphIDs instead of the reverse direction. - - It is useful for fonts that may be used by a PDF renderer in lieu of - a font reference with a known glyph collection but no subsetted - glyphs. For instance, a PDF can say “please use a font conforming - to Adobe-Japan-1”; the ``cidg`` mapping is necessary if the font is, - say, a TrueType font. ``gidc`` is lossy for this purpose and is - obsoleted by ``cidg``. - - For example, the first font in ``/System/Library/Fonts/PingFang.ttc`` - (which Apple ships pre-installed on MacOS 10.12.6) has a ``cidg`` table.""" - - pass diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/aarch64/vc1dsp_init_aarch64.c b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/aarch64/vc1dsp_init_aarch64.c deleted file mode 100644 index 3bc0bd17ee5fd0effc07ba707e3f80e5bd0bbd06..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/aarch64/vc1dsp_init_aarch64.c +++ /dev/null @@ -1,141 +0,0 @@ -/* - * This file is part of FFmpeg. - * - * FFmpeg is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * FFmpeg is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with FFmpeg; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#include "libavutil/attributes.h" -#include "libavutil/cpu.h" -#include "libavutil/aarch64/cpu.h" -#include "libavutil/intreadwrite.h" -#include "libavcodec/vc1dsp.h" - -#include "config.h" - -void ff_vc1_inv_trans_8x8_neon(int16_t *block); -void ff_vc1_inv_trans_8x4_neon(uint8_t *dest, ptrdiff_t stride, int16_t *block); -void ff_vc1_inv_trans_4x8_neon(uint8_t *dest, ptrdiff_t stride, int16_t *block); -void ff_vc1_inv_trans_4x4_neon(uint8_t *dest, ptrdiff_t stride, int16_t *block); - -void ff_vc1_inv_trans_8x8_dc_neon(uint8_t *dest, ptrdiff_t stride, int16_t *block); -void ff_vc1_inv_trans_8x4_dc_neon(uint8_t *dest, ptrdiff_t stride, int16_t *block); -void ff_vc1_inv_trans_4x8_dc_neon(uint8_t *dest, ptrdiff_t stride, int16_t *block); -void ff_vc1_inv_trans_4x4_dc_neon(uint8_t *dest, ptrdiff_t stride, int16_t *block); - -void ff_vc1_v_loop_filter4_neon(uint8_t *src, ptrdiff_t stride, int pq); -void ff_vc1_h_loop_filter4_neon(uint8_t *src, ptrdiff_t stride, int pq); -void ff_vc1_v_loop_filter8_neon(uint8_t *src, ptrdiff_t stride, int pq); -void ff_vc1_h_loop_filter8_neon(uint8_t *src, ptrdiff_t stride, int pq); -void ff_vc1_v_loop_filter16_neon(uint8_t *src, ptrdiff_t stride, int pq); -void ff_vc1_h_loop_filter16_neon(uint8_t *src, ptrdiff_t stride, int pq); - -void ff_put_vc1_chroma_mc8_neon(uint8_t *dst, const uint8_t *src, ptrdiff_t stride, - int h, int x, int y); -void ff_avg_vc1_chroma_mc8_neon(uint8_t *dst, const uint8_t *src, ptrdiff_t stride, - int h, int x, int y); -void ff_put_vc1_chroma_mc4_neon(uint8_t *dst, const uint8_t *src, ptrdiff_t stride, - int h, int x, int y); -void ff_avg_vc1_chroma_mc4_neon(uint8_t *dst, const uint8_t *src, ptrdiff_t stride, - int h, int x, int y); - -int ff_vc1_unescape_buffer_helper_neon(const uint8_t *src, int size, uint8_t *dst); - -static int vc1_unescape_buffer_neon(const uint8_t *src, int size, uint8_t *dst) -{ - /* Dealing with starting and stopping, and removing escape bytes, are - * comparatively less time-sensitive, so are more clearly expressed using - * a C wrapper around the assembly inner loop. Note that we assume a - * little-endian machine that supports unaligned loads. */ - int dsize = 0; - while (size >= 4) - { - int found = 0; - while (!found && (((uintptr_t) dst) & 7) && size >= 4) - { - found = (AV_RL32(src) &~ 0x03000000) == 0x00030000; - if (!found) - { - *dst++ = *src++; - --size; - ++dsize; - } - } - if (!found) - { - int skip = size - ff_vc1_unescape_buffer_helper_neon(src, size, dst); - dst += skip; - src += skip; - size -= skip; - dsize += skip; - while (!found && size >= 4) - { - found = (AV_RL32(src) &~ 0x03000000) == 0x00030000; - if (!found) - { - *dst++ = *src++; - --size; - ++dsize; - } - } - } - if (found) - { - *dst++ = *src++; - *dst++ = *src++; - ++src; - size -= 3; - dsize += 2; - } - } - while (size > 0) - { - *dst++ = *src++; - --size; - ++dsize; - } - return dsize; -} - -av_cold void ff_vc1dsp_init_aarch64(VC1DSPContext *dsp) -{ - int cpu_flags = av_get_cpu_flags(); - - if (have_neon(cpu_flags)) { - dsp->vc1_inv_trans_8x8 = ff_vc1_inv_trans_8x8_neon; - dsp->vc1_inv_trans_8x4 = ff_vc1_inv_trans_8x4_neon; - dsp->vc1_inv_trans_4x8 = ff_vc1_inv_trans_4x8_neon; - dsp->vc1_inv_trans_4x4 = ff_vc1_inv_trans_4x4_neon; - dsp->vc1_inv_trans_8x8_dc = ff_vc1_inv_trans_8x8_dc_neon; - dsp->vc1_inv_trans_8x4_dc = ff_vc1_inv_trans_8x4_dc_neon; - dsp->vc1_inv_trans_4x8_dc = ff_vc1_inv_trans_4x8_dc_neon; - dsp->vc1_inv_trans_4x4_dc = ff_vc1_inv_trans_4x4_dc_neon; - - dsp->vc1_v_loop_filter4 = ff_vc1_v_loop_filter4_neon; - dsp->vc1_h_loop_filter4 = ff_vc1_h_loop_filter4_neon; - dsp->vc1_v_loop_filter8 = ff_vc1_v_loop_filter8_neon; - dsp->vc1_h_loop_filter8 = ff_vc1_h_loop_filter8_neon; - dsp->vc1_v_loop_filter16 = ff_vc1_v_loop_filter16_neon; - dsp->vc1_h_loop_filter16 = ff_vc1_h_loop_filter16_neon; - - dsp->put_no_rnd_vc1_chroma_pixels_tab[0] = ff_put_vc1_chroma_mc8_neon; - dsp->avg_no_rnd_vc1_chroma_pixels_tab[0] = ff_avg_vc1_chroma_mc8_neon; - dsp->put_no_rnd_vc1_chroma_pixels_tab[1] = ff_put_vc1_chroma_mc4_neon; - dsp->avg_no_rnd_vc1_chroma_pixels_tab[1] = ff_avg_vc1_chroma_mc4_neon; - - dsp->vc1_unescape_buffer = vc1_unescape_buffer_neon; - } -} diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/arm/hpeldsp_init_arm.c b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/arm/hpeldsp_init_arm.c deleted file mode 100644 index 1977b1379b2b414da0c7f78585c758e6b81b210f..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/arm/hpeldsp_init_arm.c +++ /dev/null @@ -1,71 +0,0 @@ -/* - * ARM-optimized halfpel functions - * Copyright (c) 2001 Lionel Ulmer - * - * This file is part of FFmpeg. - * - * FFmpeg is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * FFmpeg is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with FFmpeg; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "libavutil/arm/cpu.h" -#include "libavutil/attributes.h" -#include "libavcodec/pixels.h" -#include "hpeldsp_arm.h" - -void ff_put_pixels8_arm(uint8_t *block, const uint8_t *pixels, ptrdiff_t line_size, int h); -void ff_put_pixels8_x2_arm(uint8_t *block, const uint8_t *pixels, ptrdiff_t line_size, int h); -void ff_put_pixels8_y2_arm(uint8_t *block, const uint8_t *pixels, ptrdiff_t line_size, int h); -void ff_put_pixels8_xy2_arm(uint8_t *block, const uint8_t *pixels, ptrdiff_t line_size, int h); - -void ff_put_no_rnd_pixels8_x2_arm(uint8_t *block, const uint8_t *pixels, ptrdiff_t line_size, int h); -void ff_put_no_rnd_pixels8_y2_arm(uint8_t *block, const uint8_t *pixels, ptrdiff_t line_size, int h); -void ff_put_no_rnd_pixels8_xy2_arm(uint8_t *block, const uint8_t *pixels, ptrdiff_t line_size, int h); - -void ff_put_pixels16_arm(uint8_t *block, const uint8_t *pixels, ptrdiff_t line_size, int h); - -CALL_2X_PIXELS(ff_put_pixels16_x2_arm, ff_put_pixels8_x2_arm, 8) -CALL_2X_PIXELS(ff_put_pixels16_y2_arm, ff_put_pixels8_y2_arm, 8) -CALL_2X_PIXELS(ff_put_pixels16_xy2_arm, ff_put_pixels8_xy2_arm, 8) -CALL_2X_PIXELS(ff_put_no_rnd_pixels16_x2_arm, ff_put_no_rnd_pixels8_x2_arm, 8) -CALL_2X_PIXELS(ff_put_no_rnd_pixels16_y2_arm, ff_put_no_rnd_pixels8_y2_arm, 8) -CALL_2X_PIXELS(ff_put_no_rnd_pixels16_xy2_arm, ff_put_no_rnd_pixels8_xy2_arm,8) - -av_cold void ff_hpeldsp_init_arm(HpelDSPContext *c, int flags) -{ - int cpu_flags = av_get_cpu_flags(); - - c->put_pixels_tab[0][0] = ff_put_pixels16_arm; - c->put_pixels_tab[0][1] = ff_put_pixels16_x2_arm; - c->put_pixels_tab[0][2] = ff_put_pixels16_y2_arm; - c->put_pixels_tab[0][3] = ff_put_pixels16_xy2_arm; - c->put_pixels_tab[1][0] = ff_put_pixels8_arm; - c->put_pixels_tab[1][1] = ff_put_pixels8_x2_arm; - c->put_pixels_tab[1][2] = ff_put_pixels8_y2_arm; - c->put_pixels_tab[1][3] = ff_put_pixels8_xy2_arm; - - c->put_no_rnd_pixels_tab[0][0] = ff_put_pixels16_arm; - c->put_no_rnd_pixels_tab[0][1] = ff_put_no_rnd_pixels16_x2_arm; - c->put_no_rnd_pixels_tab[0][2] = ff_put_no_rnd_pixels16_y2_arm; - c->put_no_rnd_pixels_tab[0][3] = ff_put_no_rnd_pixels16_xy2_arm; - c->put_no_rnd_pixels_tab[1][0] = ff_put_pixels8_arm; - c->put_no_rnd_pixels_tab[1][1] = ff_put_no_rnd_pixels8_x2_arm; - c->put_no_rnd_pixels_tab[1][2] = ff_put_no_rnd_pixels8_y2_arm; - c->put_no_rnd_pixels_tab[1][3] = ff_put_no_rnd_pixels8_xy2_arm; - - if (have_armv6(cpu_flags)) - ff_hpeldsp_init_armv6(c, flags); - if (have_neon(cpu_flags)) - ff_hpeldsp_init_neon(c, flags); -} diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/golomb.h b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/golomb.h deleted file mode 100644 index 164c2583b6c8b5c7060dcb4c951104989b739db1..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/golomb.h +++ /dev/null @@ -1,616 +0,0 @@ -/* - * exp golomb vlc stuff - * Copyright (c) 2003 Michael Niedermayer - * Copyright (c) 2004 Alex Beregszaszi - * - * This file is part of FFmpeg. - * - * FFmpeg is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * FFmpeg is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with FFmpeg; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -/** - * @file - * @brief - * exp golomb vlc stuff - * @author Michael Niedermayer and Alex Beregszaszi - */ - -#ifndef AVCODEC_GOLOMB_H -#define AVCODEC_GOLOMB_H - -#include - -#include "get_bits.h" - -#define INVALID_VLC 0x80000000 - -extern const uint8_t ff_golomb_vlc_len[512]; -extern const uint8_t ff_ue_golomb_vlc_code[512]; -extern const int8_t ff_se_golomb_vlc_code[512]; - -extern const uint8_t ff_interleaved_golomb_vlc_len[256]; -extern const uint8_t ff_interleaved_ue_golomb_vlc_code[256]; -extern const int8_t ff_interleaved_se_golomb_vlc_code[256]; -extern const uint8_t ff_interleaved_dirac_golomb_vlc_code[256]; - -/** - * Read an unsigned Exp-Golomb code in the range 0 to 8190. - * - * @returns the read value or a negative error code. - */ -static inline int get_ue_golomb(GetBitContext *gb) -{ - unsigned int buf; - -#if CACHED_BITSTREAM_READER - buf = show_bits_long(gb, 32); - - if (buf >= (1 << 27)) { - buf >>= 32 - 9; - skip_bits_long(gb, ff_golomb_vlc_len[buf]); - - return ff_ue_golomb_vlc_code[buf]; - } else { - int log = 2 * av_log2(buf) - 31; - - skip_bits_long(gb, 32 - log); - if (log < 7) - return AVERROR_INVALIDDATA; - buf >>= log; - buf--; - - return buf; - } -#else - OPEN_READER(re, gb); - UPDATE_CACHE(re, gb); - buf = GET_CACHE(re, gb); - - if (buf >= (1 << 27)) { - buf >>= 32 - 9; - LAST_SKIP_BITS(re, gb, ff_golomb_vlc_len[buf]); - CLOSE_READER(re, gb); - - return ff_ue_golomb_vlc_code[buf]; - } else { - int log = 2 * av_log2(buf) - 31; - LAST_SKIP_BITS(re, gb, 32 - log); - CLOSE_READER(re, gb); - if (log < 7) - return AVERROR_INVALIDDATA; - buf >>= log; - buf--; - - return buf; - } -#endif -} - -/** - * Read an unsigned Exp-Golomb code in the range 0 to UINT32_MAX-1. - */ -static inline unsigned get_ue_golomb_long(GetBitContext *gb) -{ - unsigned buf, log; - - buf = show_bits_long(gb, 32); - log = 31 - av_log2(buf); - skip_bits_long(gb, log); - - return get_bits_long(gb, log + 1) - 1; -} - -/** - * read unsigned exp golomb code, constraint to a max of 31. - * If the value encountered is not in 0..31, the return value - * is outside the range 0..30. - */ -static inline int get_ue_golomb_31(GetBitContext *gb) -{ - unsigned int buf; - -#if CACHED_BITSTREAM_READER - buf = show_bits_long(gb, 32); - - buf >>= 32 - 9; - skip_bits_long(gb, ff_golomb_vlc_len[buf]); -#else - - OPEN_READER(re, gb); - UPDATE_CACHE(re, gb); - buf = GET_CACHE(re, gb); - - buf >>= 32 - 9; - LAST_SKIP_BITS(re, gb, ff_golomb_vlc_len[buf]); - CLOSE_READER(re, gb); -#endif - - return ff_ue_golomb_vlc_code[buf]; -} - -static inline unsigned get_interleaved_ue_golomb(GetBitContext *gb) -{ - uint32_t buf; - -#if CACHED_BITSTREAM_READER - buf = show_bits_long(gb, 32); - - if (buf & 0xAA800000) { - buf >>= 32 - 8; - skip_bits_long(gb, ff_interleaved_golomb_vlc_len[buf]); - - return ff_interleaved_ue_golomb_vlc_code[buf]; - } else { - unsigned ret = 1; - - do { - buf >>= 32 - 8; - skip_bits_long(gb, FFMIN(ff_interleaved_golomb_vlc_len[buf], 8)); - - if (ff_interleaved_golomb_vlc_len[buf] != 9) { - ret <<= (ff_interleaved_golomb_vlc_len[buf] - 1) >> 1; - ret |= ff_interleaved_dirac_golomb_vlc_code[buf]; - break; - } - ret = (ret << 4) | ff_interleaved_dirac_golomb_vlc_code[buf]; - buf = show_bits_long(gb, 32); - } while (get_bits_left(gb) > 0); - - return ret - 1; - } -#else - OPEN_READER(re, gb); - UPDATE_CACHE(re, gb); - buf = GET_CACHE(re, gb); - - if (buf & 0xAA800000) { - buf >>= 32 - 8; - LAST_SKIP_BITS(re, gb, ff_interleaved_golomb_vlc_len[buf]); - CLOSE_READER(re, gb); - - return ff_interleaved_ue_golomb_vlc_code[buf]; - } else { - unsigned ret = 1; - - do { - buf >>= 32 - 8; - LAST_SKIP_BITS(re, gb, - FFMIN(ff_interleaved_golomb_vlc_len[buf], 8)); - - if (ff_interleaved_golomb_vlc_len[buf] != 9) { - ret <<= (ff_interleaved_golomb_vlc_len[buf] - 1) >> 1; - ret |= ff_interleaved_dirac_golomb_vlc_code[buf]; - break; - } - ret = (ret << 4) | ff_interleaved_dirac_golomb_vlc_code[buf]; - UPDATE_CACHE(re, gb); - buf = GET_CACHE(re, gb); - } while (ret<0x8000000U && BITS_AVAILABLE(re, gb)); - - CLOSE_READER(re, gb); - return ret - 1; - } -#endif -} - -/** - * read unsigned truncated exp golomb code. - */ -static inline int get_te0_golomb(GetBitContext *gb, int range) -{ - av_assert2(range >= 1); - - if (range == 1) - return 0; - else if (range == 2) - return get_bits1(gb) ^ 1; - else - return get_ue_golomb(gb); -} - -/** - * read unsigned truncated exp golomb code. - */ -static inline int get_te_golomb(GetBitContext *gb, int range) -{ - av_assert2(range >= 1); - - if (range == 2) - return get_bits1(gb) ^ 1; - else - return get_ue_golomb(gb); -} - -/** - * read signed exp golomb code. - */ -static inline int get_se_golomb(GetBitContext *gb) -{ - unsigned int buf; - -#if CACHED_BITSTREAM_READER - buf = show_bits_long(gb, 32); - - if (buf >= (1 << 27)) { - buf >>= 32 - 9; - skip_bits_long(gb, ff_golomb_vlc_len[buf]); - - return ff_se_golomb_vlc_code[buf]; - } else { - int log = 2 * av_log2(buf) - 31; - buf >>= log; - - skip_bits_long(gb, 32 - log); - - if (buf & 1) - buf = -(buf >> 1); - else - buf = (buf >> 1); - - return buf; - } -#else - OPEN_READER(re, gb); - UPDATE_CACHE(re, gb); - buf = GET_CACHE(re, gb); - - if (buf >= (1 << 27)) { - buf >>= 32 - 9; - LAST_SKIP_BITS(re, gb, ff_golomb_vlc_len[buf]); - CLOSE_READER(re, gb); - - return ff_se_golomb_vlc_code[buf]; - } else { - int log = av_log2(buf), sign; - LAST_SKIP_BITS(re, gb, 31 - log); - UPDATE_CACHE(re, gb); - buf = GET_CACHE(re, gb); - - buf >>= log; - - LAST_SKIP_BITS(re, gb, 32 - log); - CLOSE_READER(re, gb); - - sign = -(buf & 1); - buf = ((buf >> 1) ^ sign) - sign; - - return buf; - } -#endif -} - -static inline int get_se_golomb_long(GetBitContext *gb) -{ - unsigned int buf = get_ue_golomb_long(gb); - int sign = (buf & 1) - 1; - return ((buf >> 1) ^ sign) + 1; -} - -static inline int get_interleaved_se_golomb(GetBitContext *gb) -{ - unsigned int buf; - -#if CACHED_BITSTREAM_READER - buf = show_bits_long(gb, 32); - - if (buf & 0xAA800000) { - buf >>= 32 - 8; - skip_bits_long(gb, ff_interleaved_golomb_vlc_len[buf]); - - return ff_interleaved_se_golomb_vlc_code[buf]; - } else { - int log; - skip_bits(gb, 8); - buf |= 1 | show_bits(gb, 24); - - if ((buf & 0xAAAAAAAA) == 0) - return INVALID_VLC; - - for (log = 31; (buf & 0x80000000) == 0; log--) - buf = (buf << 2) - ((buf << log) >> (log - 1)) + (buf >> 30); - - skip_bits_long(gb, 63 - 2 * log - 8); - - return (signed) (((((buf << log) >> log) - 1) ^ -(buf & 0x1)) + 1) >> 1; - } -#else - OPEN_READER(re, gb); - UPDATE_CACHE(re, gb); - buf = GET_CACHE(re, gb); - - if (buf & 0xAA800000) { - buf >>= 32 - 8; - LAST_SKIP_BITS(re, gb, ff_interleaved_golomb_vlc_len[buf]); - CLOSE_READER(re, gb); - - return ff_interleaved_se_golomb_vlc_code[buf]; - } else { - int log; - LAST_SKIP_BITS(re, gb, 8); - UPDATE_CACHE(re, gb); - buf |= 1 | (GET_CACHE(re, gb) >> 8); - - if ((buf & 0xAAAAAAAA) == 0) - return INVALID_VLC; - - for (log = 31; (buf & 0x80000000) == 0; log--) - buf = (buf << 2) - ((buf << log) >> (log - 1)) + (buf >> 30); - - LAST_SKIP_BITS(re, gb, 63 - 2 * log - 8); - CLOSE_READER(re, gb); - - return (signed) (((((buf << log) >> log) - 1) ^ -(buf & 0x1)) + 1) >> 1; - } -#endif -} - -static inline int dirac_get_se_golomb(GetBitContext *gb) -{ - uint32_t ret = get_interleaved_ue_golomb(gb); - - if (ret) { - int sign = -get_bits1(gb); - ret = (ret ^ sign) - sign; - } - - return ret; -} - -/** - * read unsigned golomb rice code (ffv1). - */ -static inline int get_ur_golomb(GetBitContext *gb, int k, int limit, - int esc_len) -{ - unsigned int buf; - int log; - -#if CACHED_BITSTREAM_READER - buf = show_bits_long(gb, 32); - - log = av_log2(buf); - - if (log > 31 - limit) { - buf >>= log - k; - buf += (30 - log) << k; - skip_bits_long(gb, 32 + k - log); - - return buf; - } else { - skip_bits_long(gb, limit); - buf = get_bits_long(gb, esc_len); - - return buf + limit - 1; - } -#else - OPEN_READER(re, gb); - UPDATE_CACHE(re, gb); - buf = GET_CACHE(re, gb); - - log = av_log2(buf); - - if (log > 31 - limit) { - buf >>= log - k; - buf += (30U - log) << k; - LAST_SKIP_BITS(re, gb, 32 + k - log); - CLOSE_READER(re, gb); - - return buf; - } else { - LAST_SKIP_BITS(re, gb, limit); - UPDATE_CACHE(re, gb); - - buf = SHOW_UBITS(re, gb, esc_len); - - LAST_SKIP_BITS(re, gb, esc_len); - CLOSE_READER(re, gb); - - return buf + limit - 1; - } -#endif -} - -/** - * read unsigned golomb rice code (jpegls). - */ -static inline int get_ur_golomb_jpegls(GetBitContext *gb, int k, int limit, - int esc_len) -{ - unsigned int buf; - int log; - -#if CACHED_BITSTREAM_READER - buf = show_bits_long(gb, 32); - - log = av_log2(buf); - - if (log - k >= 1 && 32 - log < limit) { - buf >>= log - k; - buf += (30 - log) << k; - skip_bits_long(gb, 32 + k - log); - - return buf; - } else { - int i; - for (i = 0; - i < limit && get_bits1(gb) == 0 && get_bits_left(gb) > 0; - i++); - - if (i < limit - 1) { - buf = get_bits_long(gb, k); - - return buf + (i << k); - } else if (i == limit - 1) { - buf = get_bits_long(gb, esc_len); - - return buf + 1; - } else - return -1; - } -#else - OPEN_READER(re, gb); - UPDATE_CACHE(re, gb); - buf = GET_CACHE(re, gb); - - log = av_log2(buf); - - av_assert2(k <= 31); - - if (log - k >= 32 - MIN_CACHE_BITS + (MIN_CACHE_BITS == 32) && - 32 - log < limit) { - buf >>= log - k; - buf += (30U - log) << k; - LAST_SKIP_BITS(re, gb, 32 + k - log); - CLOSE_READER(re, gb); - - return buf; - } else { - int i; - for (i = 0; i + MIN_CACHE_BITS <= limit && SHOW_UBITS(re, gb, MIN_CACHE_BITS) == 0; i += MIN_CACHE_BITS) { - if (gb->size_in_bits <= re_index) { - CLOSE_READER(re, gb); - return -1; - } - LAST_SKIP_BITS(re, gb, MIN_CACHE_BITS); - UPDATE_CACHE(re, gb); - } - for (; i < limit && SHOW_UBITS(re, gb, 1) == 0; i++) { - SKIP_BITS(re, gb, 1); - } - LAST_SKIP_BITS(re, gb, 1); - UPDATE_CACHE(re, gb); - - if (i < limit - 1) { - if (k) { - if (k > MIN_CACHE_BITS - 1) { - buf = SHOW_UBITS(re, gb, 16) << (k-16); - LAST_SKIP_BITS(re, gb, 16); - UPDATE_CACHE(re, gb); - buf |= SHOW_UBITS(re, gb, k-16); - LAST_SKIP_BITS(re, gb, k-16); - } else { - buf = SHOW_UBITS(re, gb, k); - LAST_SKIP_BITS(re, gb, k); - } - } else { - buf = 0; - } - - buf += ((SUINT)i << k); - } else if (i == limit - 1) { - buf = SHOW_UBITS(re, gb, esc_len); - LAST_SKIP_BITS(re, gb, esc_len); - - buf ++; - } else { - buf = -1; - } - CLOSE_READER(re, gb); - return buf; - } -#endif -} - -/** - * read signed golomb rice code (ffv1). - */ -static inline int get_sr_golomb(GetBitContext *gb, int k, int limit, - int esc_len) -{ - unsigned v = get_ur_golomb(gb, k, limit, esc_len); - return (v >> 1) ^ -(v & 1); -} - -/** - * read signed golomb rice code (flac). - */ -static inline int get_sr_golomb_flac(GetBitContext *gb, int k, int limit, - int esc_len) -{ - unsigned v = get_ur_golomb_jpegls(gb, k, limit, esc_len); - return (v >> 1) ^ -(v & 1); -} - -/** - * read unsigned golomb rice code (shorten). - */ -static inline unsigned int get_ur_golomb_shorten(GetBitContext *gb, int k) -{ - return get_ur_golomb_jpegls(gb, k, INT_MAX, 0); -} - -/** - * read signed golomb rice code (shorten). - */ -static inline int get_sr_golomb_shorten(GetBitContext *gb, int k) -{ - int uvar = get_ur_golomb_jpegls(gb, k + 1, INT_MAX, 0); - return (uvar >> 1) ^ -(uvar & 1); -} - -#ifdef TRACE - -static inline int get_ue(GetBitContext *s, const char *file, const char *func, - int line) -{ - int show = show_bits(s, 24); - int pos = get_bits_count(s); - int i = get_ue_golomb(s); - int len = get_bits_count(s) - pos; - int bits = show >> (24 - len); - - av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d ue @%5d in %s %s:%d\n", - bits, len, i, pos, file, func, line); - - return i; -} - -static inline int get_se(GetBitContext *s, const char *file, const char *func, - int line) -{ - int show = show_bits(s, 24); - int pos = get_bits_count(s); - int i = get_se_golomb(s); - int len = get_bits_count(s) - pos; - int bits = show >> (24 - len); - - av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d se @%5d in %s %s:%d\n", - bits, len, i, pos, file, func, line); - - return i; -} - -static inline int get_te(GetBitContext *s, int r, char *file, const char *func, - int line) -{ - int show = show_bits(s, 24); - int pos = get_bits_count(s); - int i = get_te0_golomb(s, r); - int len = get_bits_count(s) - pos; - int bits = show >> (24 - len); - - av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d te @%5d in %s %s:%d\n", - bits, len, i, pos, file, func, line); - - return i; -} - -#define get_ue_golomb(a) get_ue(a, __FILE__, __func__, __LINE__) -#define get_se_golomb(a) get_se(a, __FILE__, __func__, __LINE__) -#define get_te_golomb(a, r) get_te(a, r, __FILE__, __func__, __LINE__) -#define get_te0_golomb(a, r) get_te(a, r, __FILE__, __func__, __LINE__) - -#endif /* TRACE */ -#endif /* AVCODEC_GOLOMB_H */ diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/h264_mb.c b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/h264_mb.c deleted file mode 100644 index 0b317745566f796b9703a187c043bddb01cb9b99..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/h264_mb.c +++ /dev/null @@ -1,817 +0,0 @@ -/* - * H.26L/H.264/AVC/JVT/14496-10/... decoder - * Copyright (c) 2003 Michael Niedermayer - * - * This file is part of FFmpeg. - * - * FFmpeg is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * FFmpeg is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with FFmpeg; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -/** - * @file - * H.264 / AVC / MPEG-4 part10 macroblock decoding - */ - -#include - -#include "config.h" - -#include "libavutil/common.h" -#include "libavutil/intreadwrite.h" -#include "avcodec.h" -#include "h264dec.h" -#include "h264_ps.h" -#include "qpeldsp.h" -#include "threadframe.h" - -static inline int get_lowest_part_list_y(H264SliceContext *sl, - int n, int height, int y_offset, int list) -{ - int raw_my = sl->mv_cache[list][scan8[n]][1]; - int filter_height_down = (raw_my & 3) ? 3 : 0; - int full_my = (raw_my >> 2) + y_offset; - int bottom = full_my + filter_height_down + height; - - av_assert2(height >= 0); - - return FFMAX(0, bottom); -} - -static inline void get_lowest_part_y(const H264Context *h, H264SliceContext *sl, - int16_t refs[2][48], int n, - int height, int y_offset, int list0, - int list1, int *nrefs) -{ - int my; - - y_offset += 16 * (sl->mb_y >> MB_FIELD(sl)); - - if (list0) { - int ref_n = sl->ref_cache[0][scan8[n]]; - H264Ref *ref = &sl->ref_list[0][ref_n]; - - // Error resilience puts the current picture in the ref list. - // Don't try to wait on these as it will cause a deadlock. - // Fields can wait on each other, though. - if (ref->parent->tf.progress->data != h->cur_pic.tf.progress->data || - (ref->reference & 3) != h->picture_structure) { - my = get_lowest_part_list_y(sl, n, height, y_offset, 0); - if (refs[0][ref_n] < 0) - nrefs[0] += 1; - refs[0][ref_n] = FFMAX(refs[0][ref_n], my); - } - } - - if (list1) { - int ref_n = sl->ref_cache[1][scan8[n]]; - H264Ref *ref = &sl->ref_list[1][ref_n]; - - if (ref->parent->tf.progress->data != h->cur_pic.tf.progress->data || - (ref->reference & 3) != h->picture_structure) { - my = get_lowest_part_list_y(sl, n, height, y_offset, 1); - if (refs[1][ref_n] < 0) - nrefs[1] += 1; - refs[1][ref_n] = FFMAX(refs[1][ref_n], my); - } - } -} - -/** - * Wait until all reference frames are available for MC operations. - * - * @param h the H.264 context - */ -static void await_references(const H264Context *h, H264SliceContext *sl) -{ - const int mb_xy = sl->mb_xy; - const int mb_type = h->cur_pic.mb_type[mb_xy]; - int16_t refs[2][48]; - int nrefs[2] = { 0 }; - int ref, list; - - memset(refs, -1, sizeof(refs)); - - if (IS_16X16(mb_type)) { - get_lowest_part_y(h, sl, refs, 0, 16, 0, - IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs); - } else if (IS_16X8(mb_type)) { - get_lowest_part_y(h, sl, refs, 0, 8, 0, - IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs); - get_lowest_part_y(h, sl, refs, 8, 8, 8, - IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs); - } else if (IS_8X16(mb_type)) { - get_lowest_part_y(h, sl, refs, 0, 16, 0, - IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs); - get_lowest_part_y(h, sl, refs, 4, 16, 0, - IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs); - } else { - int i; - - av_assert2(IS_8X8(mb_type)); - - for (i = 0; i < 4; i++) { - const int sub_mb_type = sl->sub_mb_type[i]; - const int n = 4 * i; - int y_offset = (i & 2) << 2; - - if (IS_SUB_8X8(sub_mb_type)) { - get_lowest_part_y(h, sl, refs, n, 8, y_offset, - IS_DIR(sub_mb_type, 0, 0), - IS_DIR(sub_mb_type, 0, 1), - nrefs); - } else if (IS_SUB_8X4(sub_mb_type)) { - get_lowest_part_y(h, sl, refs, n, 4, y_offset, - IS_DIR(sub_mb_type, 0, 0), - IS_DIR(sub_mb_type, 0, 1), - nrefs); - get_lowest_part_y(h, sl, refs, n + 2, 4, y_offset + 4, - IS_DIR(sub_mb_type, 0, 0), - IS_DIR(sub_mb_type, 0, 1), - nrefs); - } else if (IS_SUB_4X8(sub_mb_type)) { - get_lowest_part_y(h, sl, refs, n, 8, y_offset, - IS_DIR(sub_mb_type, 0, 0), - IS_DIR(sub_mb_type, 0, 1), - nrefs); - get_lowest_part_y(h, sl, refs, n + 1, 8, y_offset, - IS_DIR(sub_mb_type, 0, 0), - IS_DIR(sub_mb_type, 0, 1), - nrefs); - } else { - int j; - av_assert2(IS_SUB_4X4(sub_mb_type)); - for (j = 0; j < 4; j++) { - int sub_y_offset = y_offset + 2 * (j & 2); - get_lowest_part_y(h, sl, refs, n + j, 4, sub_y_offset, - IS_DIR(sub_mb_type, 0, 0), - IS_DIR(sub_mb_type, 0, 1), - nrefs); - } - } - } - } - - for (list = sl->list_count - 1; list >= 0; list--) - for (ref = 0; ref < 48 && nrefs[list]; ref++) { - int row = refs[list][ref]; - if (row >= 0) { - H264Ref *ref_pic = &sl->ref_list[list][ref]; - int ref_field = ref_pic->reference - 1; - int ref_field_picture = ref_pic->parent->field_picture; - int pic_height = 16 * h->mb_height >> ref_field_picture; - - row <<= MB_MBAFF(sl); - nrefs[list]--; - - if (!FIELD_PICTURE(h) && ref_field_picture) { // frame referencing two fields - av_assert2((ref_pic->parent->reference & 3) == 3); - ff_thread_await_progress(&ref_pic->parent->tf, - FFMIN((row >> 1) - !(row & 1), - pic_height - 1), - 1); - ff_thread_await_progress(&ref_pic->parent->tf, - FFMIN((row >> 1), pic_height - 1), - 0); - } else if (FIELD_PICTURE(h) && !ref_field_picture) { // field referencing one field of a frame - ff_thread_await_progress(&ref_pic->parent->tf, - FFMIN(row * 2 + ref_field, - pic_height - 1), - 0); - } else if (FIELD_PICTURE(h)) { - ff_thread_await_progress(&ref_pic->parent->tf, - FFMIN(row, pic_height - 1), - ref_field); - } else { - ff_thread_await_progress(&ref_pic->parent->tf, - FFMIN(row, pic_height - 1), - 0); - } - } - } -} - -static av_always_inline void mc_dir_part(const H264Context *h, H264SliceContext *sl, - H264Ref *pic, - int n, int square, int height, - int delta, int list, - uint8_t *dest_y, uint8_t *dest_cb, - uint8_t *dest_cr, - int src_x_offset, int src_y_offset, - const qpel_mc_func *qpix_op, - h264_chroma_mc_func chroma_op, - int pixel_shift, int chroma_idc) -{ - const int mx = sl->mv_cache[list][scan8[n]][0] + src_x_offset * 8; - int my = sl->mv_cache[list][scan8[n]][1] + src_y_offset * 8; - const int luma_xy = (mx & 3) + ((my & 3) << 2); - ptrdiff_t offset = (mx >> 2) * (1 << pixel_shift) + (my >> 2) * sl->mb_linesize; - uint8_t *src_y = pic->data[0] + offset; - uint8_t *src_cb, *src_cr; - int extra_width = 0; - int extra_height = 0; - int emu = 0; - const int full_mx = mx >> 2; - const int full_my = my >> 2; - const int pic_width = 16 * h->mb_width; - const int pic_height = 16 * h->mb_height >> MB_FIELD(sl); - int ysh; - - if (mx & 7) - extra_width -= 3; - if (my & 7) - extra_height -= 3; - - if (full_mx < 0 - extra_width || - full_my < 0 - extra_height || - full_mx + 16 /*FIXME*/ > pic_width + extra_width || - full_my + 16 /*FIXME*/ > pic_height + extra_height) { - h->vdsp.emulated_edge_mc(sl->edge_emu_buffer, - src_y - (2 << pixel_shift) - 2 * sl->mb_linesize, - sl->mb_linesize, sl->mb_linesize, - 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2, - full_my - 2, pic_width, pic_height); - src_y = sl->edge_emu_buffer + (2 << pixel_shift) + 2 * sl->mb_linesize; - emu = 1; - } - - qpix_op[luma_xy](dest_y, src_y, sl->mb_linesize); // FIXME try variable height perhaps? - if (!square) - qpix_op[luma_xy](dest_y + delta, src_y + delta, sl->mb_linesize); - - if (CONFIG_GRAY && h->flags & AV_CODEC_FLAG_GRAY) - return; - - if (chroma_idc == 3 /* yuv444 */) { - src_cb = pic->data[1] + offset; - if (emu) { - h->vdsp.emulated_edge_mc(sl->edge_emu_buffer, - src_cb - (2 << pixel_shift) - 2 * sl->mb_linesize, - sl->mb_linesize, sl->mb_linesize, - 16 + 5, 16 + 5 /*FIXME*/, - full_mx - 2, full_my - 2, - pic_width, pic_height); - src_cb = sl->edge_emu_buffer + (2 << pixel_shift) + 2 * sl->mb_linesize; - } - qpix_op[luma_xy](dest_cb, src_cb, sl->mb_linesize); // FIXME try variable height perhaps? - if (!square) - qpix_op[luma_xy](dest_cb + delta, src_cb + delta, sl->mb_linesize); - - src_cr = pic->data[2] + offset; - if (emu) { - h->vdsp.emulated_edge_mc(sl->edge_emu_buffer, - src_cr - (2 << pixel_shift) - 2 * sl->mb_linesize, - sl->mb_linesize, sl->mb_linesize, - 16 + 5, 16 + 5 /*FIXME*/, - full_mx - 2, full_my - 2, - pic_width, pic_height); - src_cr = sl->edge_emu_buffer + (2 << pixel_shift) + 2 * sl->mb_linesize; - } - qpix_op[luma_xy](dest_cr, src_cr, sl->mb_linesize); // FIXME try variable height perhaps? - if (!square) - qpix_op[luma_xy](dest_cr + delta, src_cr + delta, sl->mb_linesize); - return; - } - - ysh = 3 - (chroma_idc == 2 /* yuv422 */); - if (chroma_idc == 1 /* yuv420 */ && MB_FIELD(sl)) { - // chroma offset when predicting from a field of opposite parity - my += 2 * ((sl->mb_y & 1) - (pic->reference - 1)); - emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1); - } - - src_cb = pic->data[1] + ((mx >> 3) * (1 << pixel_shift)) + - (my >> ysh) * sl->mb_uvlinesize; - src_cr = pic->data[2] + ((mx >> 3) * (1 << pixel_shift)) + - (my >> ysh) * sl->mb_uvlinesize; - - if (emu) { - h->vdsp.emulated_edge_mc(sl->edge_emu_buffer, src_cb, - sl->mb_uvlinesize, sl->mb_uvlinesize, - 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh), - pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */)); - src_cb = sl->edge_emu_buffer; - } - chroma_op(dest_cb, src_cb, sl->mb_uvlinesize, - height >> (chroma_idc == 1 /* yuv420 */), - mx & 7, ((unsigned)my << (chroma_idc == 2 /* yuv422 */)) & 7); - - if (emu) { - h->vdsp.emulated_edge_mc(sl->edge_emu_buffer, src_cr, - sl->mb_uvlinesize, sl->mb_uvlinesize, - 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh), - pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */)); - src_cr = sl->edge_emu_buffer; - } - chroma_op(dest_cr, src_cr, sl->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */), - mx & 7, ((unsigned)my << (chroma_idc == 2 /* yuv422 */)) & 7); -} - -static av_always_inline void mc_part_std(const H264Context *h, H264SliceContext *sl, - int n, int square, - int height, int delta, - uint8_t *dest_y, uint8_t *dest_cb, - uint8_t *dest_cr, - int x_offset, int y_offset, - const qpel_mc_func *qpix_put, - h264_chroma_mc_func chroma_put, - const qpel_mc_func *qpix_avg, - h264_chroma_mc_func chroma_avg, - int list0, int list1, - int pixel_shift, int chroma_idc) -{ - const qpel_mc_func *qpix_op = qpix_put; - h264_chroma_mc_func chroma_op = chroma_put; - - dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * sl->mb_linesize; - if (chroma_idc == 3 /* yuv444 */) { - dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * sl->mb_linesize; - dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * sl->mb_linesize; - } else if (chroma_idc == 2 /* yuv422 */) { - dest_cb += (x_offset << pixel_shift) + 2 * y_offset * sl->mb_uvlinesize; - dest_cr += (x_offset << pixel_shift) + 2 * y_offset * sl->mb_uvlinesize; - } else { /* yuv420 */ - dest_cb += (x_offset << pixel_shift) + y_offset * sl->mb_uvlinesize; - dest_cr += (x_offset << pixel_shift) + y_offset * sl->mb_uvlinesize; - } - x_offset += 8 * sl->mb_x; - y_offset += 8 * (sl->mb_y >> MB_FIELD(sl)); - - if (list0) { - H264Ref *ref = &sl->ref_list[0][sl->ref_cache[0][scan8[n]]]; - mc_dir_part(h, sl, ref, n, square, height, delta, 0, - dest_y, dest_cb, dest_cr, x_offset, y_offset, - qpix_op, chroma_op, pixel_shift, chroma_idc); - - qpix_op = qpix_avg; - chroma_op = chroma_avg; - } - - if (list1) { - H264Ref *ref = &sl->ref_list[1][sl->ref_cache[1][scan8[n]]]; - mc_dir_part(h, sl, ref, n, square, height, delta, 1, - dest_y, dest_cb, dest_cr, x_offset, y_offset, - qpix_op, chroma_op, pixel_shift, chroma_idc); - } -} - -static av_always_inline void mc_part_weighted(const H264Context *h, H264SliceContext *sl, - int n, int square, - int height, int delta, - uint8_t *dest_y, uint8_t *dest_cb, - uint8_t *dest_cr, - int x_offset, int y_offset, - const qpel_mc_func *qpix_put, - h264_chroma_mc_func chroma_put, - h264_weight_func luma_weight_op, - h264_weight_func chroma_weight_op, - h264_biweight_func luma_weight_avg, - h264_biweight_func chroma_weight_avg, - int list0, int list1, - int pixel_shift, int chroma_idc) -{ - int chroma_height; - - dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * sl->mb_linesize; - if (chroma_idc == 3 /* yuv444 */) { - chroma_height = height; - chroma_weight_avg = luma_weight_avg; - chroma_weight_op = luma_weight_op; - dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * sl->mb_linesize; - dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * sl->mb_linesize; - } else if (chroma_idc == 2 /* yuv422 */) { - chroma_height = height; - dest_cb += (x_offset << pixel_shift) + 2 * y_offset * sl->mb_uvlinesize; - dest_cr += (x_offset << pixel_shift) + 2 * y_offset * sl->mb_uvlinesize; - } else { /* yuv420 */ - chroma_height = height >> 1; - dest_cb += (x_offset << pixel_shift) + y_offset * sl->mb_uvlinesize; - dest_cr += (x_offset << pixel_shift) + y_offset * sl->mb_uvlinesize; - } - x_offset += 8 * sl->mb_x; - y_offset += 8 * (sl->mb_y >> MB_FIELD(sl)); - - if (list0 && list1) { - /* don't optimize for luma-only case, since B-frames usually - * use implicit weights => chroma too. */ - uint8_t *tmp_cb = sl->bipred_scratchpad; - uint8_t *tmp_cr = sl->bipred_scratchpad + (16 << pixel_shift); - uint8_t *tmp_y = sl->bipred_scratchpad + 16 * sl->mb_uvlinesize; - int refn0 = sl->ref_cache[0][scan8[n]]; - int refn1 = sl->ref_cache[1][scan8[n]]; - - mc_dir_part(h, sl, &sl->ref_list[0][refn0], n, square, height, delta, 0, - dest_y, dest_cb, dest_cr, - x_offset, y_offset, qpix_put, chroma_put, - pixel_shift, chroma_idc); - mc_dir_part(h, sl, &sl->ref_list[1][refn1], n, square, height, delta, 1, - tmp_y, tmp_cb, tmp_cr, - x_offset, y_offset, qpix_put, chroma_put, - pixel_shift, chroma_idc); - - if (sl->pwt.use_weight == 2) { - int weight0 = sl->pwt.implicit_weight[refn0][refn1][sl->mb_y & 1]; - int weight1 = 64 - weight0; - luma_weight_avg(dest_y, tmp_y, sl->mb_linesize, - height, 5, weight0, weight1, 0); - if (!CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) { - chroma_weight_avg(dest_cb, tmp_cb, sl->mb_uvlinesize, - chroma_height, 5, weight0, weight1, 0); - chroma_weight_avg(dest_cr, tmp_cr, sl->mb_uvlinesize, - chroma_height, 5, weight0, weight1, 0); - } - } else { - luma_weight_avg(dest_y, tmp_y, sl->mb_linesize, height, - sl->pwt.luma_log2_weight_denom, - sl->pwt.luma_weight[refn0][0][0], - sl->pwt.luma_weight[refn1][1][0], - sl->pwt.luma_weight[refn0][0][1] + - sl->pwt.luma_weight[refn1][1][1]); - if (!CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) { - chroma_weight_avg(dest_cb, tmp_cb, sl->mb_uvlinesize, chroma_height, - sl->pwt.chroma_log2_weight_denom, - sl->pwt.chroma_weight[refn0][0][0][0], - sl->pwt.chroma_weight[refn1][1][0][0], - sl->pwt.chroma_weight[refn0][0][0][1] + - sl->pwt.chroma_weight[refn1][1][0][1]); - chroma_weight_avg(dest_cr, tmp_cr, sl->mb_uvlinesize, chroma_height, - sl->pwt.chroma_log2_weight_denom, - sl->pwt.chroma_weight[refn0][0][1][0], - sl->pwt.chroma_weight[refn1][1][1][0], - sl->pwt.chroma_weight[refn0][0][1][1] + - sl->pwt.chroma_weight[refn1][1][1][1]); - } - } - } else { - int list = list1 ? 1 : 0; - int refn = sl->ref_cache[list][scan8[n]]; - H264Ref *ref = &sl->ref_list[list][refn]; - mc_dir_part(h, sl, ref, n, square, height, delta, list, - dest_y, dest_cb, dest_cr, x_offset, y_offset, - qpix_put, chroma_put, pixel_shift, chroma_idc); - - luma_weight_op(dest_y, sl->mb_linesize, height, - sl->pwt.luma_log2_weight_denom, - sl->pwt.luma_weight[refn][list][0], - sl->pwt.luma_weight[refn][list][1]); - if (!CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) { - if (sl->pwt.use_weight_chroma) { - chroma_weight_op(dest_cb, sl->mb_uvlinesize, chroma_height, - sl->pwt.chroma_log2_weight_denom, - sl->pwt.chroma_weight[refn][list][0][0], - sl->pwt.chroma_weight[refn][list][0][1]); - chroma_weight_op(dest_cr, sl->mb_uvlinesize, chroma_height, - sl->pwt.chroma_log2_weight_denom, - sl->pwt.chroma_weight[refn][list][1][0], - sl->pwt.chroma_weight[refn][list][1][1]); - } - } - } -} - -static av_always_inline void prefetch_motion(const H264Context *h, H264SliceContext *sl, - int list, int pixel_shift, - int chroma_idc) -{ - /* fetch pixels for estimated mv 4 macroblocks ahead - * optimized for 64byte cache lines */ - const int refn = sl->ref_cache[list][scan8[0]]; - if (refn >= 0) { - const int mx = (sl->mv_cache[list][scan8[0]][0] >> 2) + 16 * sl->mb_x + 8; - const int my = (sl->mv_cache[list][scan8[0]][1] >> 2) + 16 * sl->mb_y; - uint8_t **src = sl->ref_list[list][refn].data; - int off = mx * (1<< pixel_shift) + - (my + (sl->mb_x & 3) * 4) * sl->mb_linesize + - (64 << pixel_shift); - h->vdsp.prefetch(src[0] + off, sl->linesize, 4); - if (chroma_idc == 3 /* yuv444 */) { - h->vdsp.prefetch(src[1] + off, sl->linesize, 4); - h->vdsp.prefetch(src[2] + off, sl->linesize, 4); - } else { - off= ((mx>>1)+64) * (1<>1) + (sl->mb_x&7))*sl->uvlinesize; - h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2); - } - } -} - -static av_always_inline void xchg_mb_border(const H264Context *h, H264SliceContext *sl, - uint8_t *src_y, - uint8_t *src_cb, uint8_t *src_cr, - int linesize, int uvlinesize, - int xchg, int chroma444, - int simple, int pixel_shift) -{ - int deblock_topleft; - int deblock_top; - int top_idx = 1; - uint8_t *top_border_m1; - uint8_t *top_border; - - if (!simple && FRAME_MBAFF(h)) { - if (sl->mb_y & 1) { - if (!MB_MBAFF(sl)) - return; - } else { - top_idx = MB_MBAFF(sl) ? 0 : 1; - } - } - - if (sl->deblocking_filter == 2) { - deblock_topleft = h->slice_table[sl->mb_xy - 1 - h->mb_stride] == sl->slice_num; - deblock_top = sl->top_type; - } else { - deblock_topleft = (sl->mb_x > 0); - deblock_top = (sl->mb_y > !!MB_FIELD(sl)); - } - - src_y -= linesize + 1 + pixel_shift; - src_cb -= uvlinesize + 1 + pixel_shift; - src_cr -= uvlinesize + 1 + pixel_shift; - - top_border_m1 = sl->top_borders[top_idx][sl->mb_x - 1]; - top_border = sl->top_borders[top_idx][sl->mb_x]; - -#define XCHG(a, b, xchg) \ - if (pixel_shift) { \ - if (xchg) { \ - AV_SWAP64(b + 0, a + 0); \ - AV_SWAP64(b + 8, a + 8); \ - } else { \ - AV_COPY128(b, a); \ - } \ - } else if (xchg) \ - AV_SWAP64(b, a); \ - else \ - AV_COPY64(b, a); - - if (deblock_top) { - if (deblock_topleft) { - XCHG(top_border_m1 + (8 << pixel_shift), - src_y - (7 << pixel_shift), 1); - } - XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg); - XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1); - if (sl->mb_x + 1 < h->mb_width) { - XCHG(sl->top_borders[top_idx][sl->mb_x + 1], - src_y + (17 << pixel_shift), 1); - } - if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) { - if (chroma444) { - if (deblock_topleft) { - XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1); - XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1); - } - XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg); - XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1); - XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg); - XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1); - if (sl->mb_x + 1 < h->mb_width) { - XCHG(sl->top_borders[top_idx][sl->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1); - XCHG(sl->top_borders[top_idx][sl->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1); - } - } else { - if (deblock_topleft) { - XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1); - XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1); - } - XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1); - XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1); - } - } - } -} - -static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth, - int index) -{ - if (high_bit_depth) { - return AV_RN32A(((int32_t *)mb) + index); - } else - return AV_RN16A(mb + index); -} - -static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth, - int index, int value) -{ - if (high_bit_depth) { - AV_WN32A(((int32_t *)mb) + index, value); - } else - AV_WN16A(mb + index, value); -} - -static av_always_inline void hl_decode_mb_predict_luma(const H264Context *h, - H264SliceContext *sl, - int mb_type, int simple, - int transform_bypass, - int pixel_shift, - const int *block_offset, - int linesize, - uint8_t *dest_y, int p) -{ - void (*idct_add)(uint8_t *dst, int16_t *block, int stride); - void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride); - int i; - int qscale = p == 0 ? sl->qscale : sl->chroma_qp[p - 1]; - block_offset += 16 * p; - if (IS_INTRA4x4(mb_type)) { - if (IS_8x8DCT(mb_type)) { - if (transform_bypass) { - idct_dc_add = - idct_add = h->h264dsp.h264_add_pixels8_clear; - } else { - idct_dc_add = h->h264dsp.h264_idct8_dc_add; - idct_add = h->h264dsp.h264_idct8_add; - } - for (i = 0; i < 16; i += 4) { - uint8_t *const ptr = dest_y + block_offset[i]; - const int dir = sl->intra4x4_pred_mode_cache[scan8[i]]; - if (transform_bypass && h->ps.sps->profile_idc == 244 && dir <= 1) { - if (h->x264_build < 151U) { - h->hpc.pred8x8l_add[dir](ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize); - } else - h->hpc.pred8x8l_filter_add[dir](ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), - (sl-> topleft_samples_available << i) & 0x8000, - (sl->topright_samples_available << i) & 0x4000, linesize); - } else { - const int nnz = sl->non_zero_count_cache[scan8[i + p * 16]]; - h->hpc.pred8x8l[dir](ptr, (sl->topleft_samples_available << i) & 0x8000, - (sl->topright_samples_available << i) & 0x4000, linesize); - if (nnz) { - if (nnz == 1 && dctcoef_get(sl->mb, pixel_shift, i * 16 + p * 256)) - idct_dc_add(ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize); - else - idct_add(ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize); - } - } - } - } else { - if (transform_bypass) { - idct_dc_add = - idct_add = h->h264dsp.h264_add_pixels4_clear; - } else { - idct_dc_add = h->h264dsp.h264_idct_dc_add; - idct_add = h->h264dsp.h264_idct_add; - } - for (i = 0; i < 16; i++) { - uint8_t *const ptr = dest_y + block_offset[i]; - const int dir = sl->intra4x4_pred_mode_cache[scan8[i]]; - - if (transform_bypass && h->ps.sps->profile_idc == 244 && dir <= 1) { - h->hpc.pred4x4_add[dir](ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize); - } else { - uint8_t *topright; - int nnz, tr; - uint64_t tr_high; - if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) { - const int topright_avail = (sl->topright_samples_available << i) & 0x8000; - av_assert2(sl->mb_y || linesize <= block_offset[i]); - if (!topright_avail) { - if (pixel_shift) { - tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL; - topright = (uint8_t *)&tr_high; - } else { - tr = ptr[3 - linesize] * 0x01010101u; - topright = (uint8_t *)&tr; - } - } else - topright = ptr + (4 << pixel_shift) - linesize; - } else - topright = NULL; - - h->hpc.pred4x4[dir](ptr, topright, linesize); - nnz = sl->non_zero_count_cache[scan8[i + p * 16]]; - if (nnz) { - if (nnz == 1 && dctcoef_get(sl->mb, pixel_shift, i * 16 + p * 256)) - idct_dc_add(ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize); - else - idct_add(ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize); - } - } - } - } - } else { - h->hpc.pred16x16[sl->intra16x16_pred_mode](dest_y, linesize); - if (sl->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) { - if (!transform_bypass) - h->h264dsp.h264_luma_dc_dequant_idct(sl->mb + (p * 256 << pixel_shift), - sl->mb_luma_dc[p], - h->ps.pps->dequant4_coeff[p][qscale][0]); - else { - static const uint8_t dc_mapping[16] = { - 0 * 16, 1 * 16, 4 * 16, 5 * 16, - 2 * 16, 3 * 16, 6 * 16, 7 * 16, - 8 * 16, 9 * 16, 12 * 16, 13 * 16, - 10 * 16, 11 * 16, 14 * 16, 15 * 16 - }; - for (i = 0; i < 16; i++) - dctcoef_set(sl->mb + (p * 256 << pixel_shift), - pixel_shift, dc_mapping[i], - dctcoef_get(sl->mb_luma_dc[p], - pixel_shift, i)); - } - } - } -} - -static av_always_inline void hl_decode_mb_idct_luma(const H264Context *h, H264SliceContext *sl, - int mb_type, int simple, - int transform_bypass, - int pixel_shift, - const int *block_offset, - int linesize, - uint8_t *dest_y, int p) -{ - void (*idct_add)(uint8_t *dst, int16_t *block, int stride); - int i; - block_offset += 16 * p; - if (!IS_INTRA4x4(mb_type)) { - if (IS_INTRA16x16(mb_type)) { - if (transform_bypass) { - if (h->ps.sps->profile_idc == 244 && - (sl->intra16x16_pred_mode == VERT_PRED8x8 || - sl->intra16x16_pred_mode == HOR_PRED8x8)) { - h->hpc.pred16x16_add[sl->intra16x16_pred_mode](dest_y, block_offset, - sl->mb + (p * 256 << pixel_shift), - linesize); - } else { - for (i = 0; i < 16; i++) - if (sl->non_zero_count_cache[scan8[i + p * 16]] || - dctcoef_get(sl->mb, pixel_shift, i * 16 + p * 256)) - h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i], - sl->mb + (i * 16 + p * 256 << pixel_shift), - linesize); - } - } else { - h->h264dsp.h264_idct_add16intra(dest_y, block_offset, - sl->mb + (p * 256 << pixel_shift), - linesize, - sl->non_zero_count_cache + p * 5 * 8); - } - } else if (sl->cbp & 15) { - if (transform_bypass) { - const int di = IS_8x8DCT(mb_type) ? 4 : 1; - idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear - : h->h264dsp.h264_add_pixels4_clear; - for (i = 0; i < 16; i += di) - if (sl->non_zero_count_cache[scan8[i + p * 16]]) - idct_add(dest_y + block_offset[i], - sl->mb + (i * 16 + p * 256 << pixel_shift), - linesize); - } else { - if (IS_8x8DCT(mb_type)) - h->h264dsp.h264_idct8_add4(dest_y, block_offset, - sl->mb + (p * 256 << pixel_shift), - linesize, - sl->non_zero_count_cache + p * 5 * 8); - else - h->h264dsp.h264_idct_add16(dest_y, block_offset, - sl->mb + (p * 256 << pixel_shift), - linesize, - sl->non_zero_count_cache + p * 5 * 8); - } - } - } -} - -#define BITS 8 -#define SIMPLE 1 -#include "h264_mb_template.c" - -#undef BITS -#define BITS 16 -#include "h264_mb_template.c" - -#undef SIMPLE -#define SIMPLE 0 -#include "h264_mb_template.c" - -void ff_h264_hl_decode_mb(const H264Context *h, H264SliceContext *sl) -{ - const int mb_xy = sl->mb_xy; - const int mb_type = h->cur_pic.mb_type[mb_xy]; - int is_complex = CONFIG_SMALL || sl->is_complex || - IS_INTRA_PCM(mb_type) || sl->qscale == 0; - - if (CHROMA444(h)) { - if (is_complex || h->pixel_shift) - hl_decode_mb_444_complex(h, sl); - else - hl_decode_mb_444_simple_8(h, sl); - } else if (is_complex) { - hl_decode_mb_complex(h, sl); - } else if (h->pixel_shift) { - hl_decode_mb_simple_16(h, sl); - } else - hl_decode_mb_simple_8(h, sl); -} diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/indeo5data.h b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/indeo5data.h deleted file mode 100644 index a6217d0bf822ed77063c303aa59564745f25299d..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/indeo5data.h +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Indeo Video Interactive 5 compatible decoder - * Copyright (c) 2009 Maxim Poliakovski - * - * This file is part of FFmpeg. - * - * FFmpeg is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * FFmpeg is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with FFmpeg; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -/** - * @file - * This file contains data needed for the Indeo5 decoder. - */ - -#ifndef AVCODEC_INDEO5DATA_H -#define AVCODEC_INDEO5DATA_H - -#include - -/** - * standard picture dimensions (width, height divided by 4) - */ -static const uint8_t ivi5_common_pic_sizes[30] = { - 160, 120, 80, 60, 40, 30, 176, 120, 88, 60, 88, 72, 44, 36, 60, 45, 160, 60, - 176, 60, 20, 15, 22, 18, 0, 0, 0, 0, 0, 0 -}; - - -/** - * Indeo5 dequantization matrixes consist of two tables: base table - * and scale table. The base table defines the dequantization matrix - * itself and the scale table tells how this matrix should be scaled - * for a particular quant level (0...24). - * - * ivi5_base_quant_bbb_ttt - base tables for block size 'bbb' of type 'ttt' - * ivi5_scale_quant_bbb_ttt - scale tables for block size 'bbb' of type 'ttt' - */ -static const uint16_t ivi5_base_quant_8x8_inter[5][64] = { - {0x26, 0x3a, 0x3e, 0x46, 0x4a, 0x4e, 0x52, 0x5a, 0x3a, 0x3e, 0x42, 0x46, 0x4a, 0x4e, 0x56, 0x5e, - 0x3e, 0x42, 0x46, 0x48, 0x4c, 0x52, 0x5a, 0x62, 0x46, 0x46, 0x48, 0x4a, 0x4e, 0x56, 0x5e, 0x66, - 0x4a, 0x4a, 0x4c, 0x4e, 0x52, 0x5a, 0x62, 0x6a, 0x4e, 0x4e, 0x52, 0x56, 0x5a, 0x5e, 0x66, 0x6e, - 0x52, 0x56, 0x5a, 0x5e, 0x62, 0x66, 0x6a, 0x72, 0x5a, 0x5e, 0x62, 0x66, 0x6a, 0x6e, 0x72, 0x76, - }, - {0x26, 0x3a, 0x3e, 0x46, 0x4a, 0x4e, 0x52, 0x5a, 0x3a, 0x3e, 0x42, 0x46, 0x4a, 0x4e, 0x56, 0x5e, - 0x3e, 0x42, 0x46, 0x48, 0x4c, 0x52, 0x5a, 0x62, 0x46, 0x46, 0x48, 0x4a, 0x4e, 0x56, 0x5e, 0x66, - 0x4a, 0x4a, 0x4c, 0x4e, 0x52, 0x5a, 0x62, 0x6a, 0x4e, 0x4e, 0x52, 0x56, 0x5a, 0x5e, 0x66, 0x6e, - 0x52, 0x56, 0x5a, 0x5e, 0x62, 0x66, 0x6a, 0x72, 0x5a, 0x5e, 0x62, 0x66, 0x6a, 0x6e, 0x72, 0x76, - }, - {0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, - 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, - 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, - 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, - }, - {0x4e, 0x4e, 0x4e, 0x4e, 0x4e, 0x4e, 0x4e, 0x4e, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, - 0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, - 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, - }, - {0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, - 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, - 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, - 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, - } -}; - -static const uint16_t ivi5_base_quant_8x8_intra[5][64] = { - {0x1a, 0x2e, 0x36, 0x42, 0x46, 0x4a, 0x4e, 0x5a, 0x2e, 0x32, 0x3e, 0x42, 0x46, 0x4e, 0x56, 0x6a, - 0x36, 0x3e, 0x3e, 0x44, 0x4a, 0x54, 0x66, 0x72, 0x42, 0x42, 0x44, 0x4a, 0x52, 0x62, 0x6c, 0x7a, - 0x46, 0x46, 0x4a, 0x52, 0x5e, 0x66, 0x72, 0x8e, 0x4a, 0x4e, 0x54, 0x62, 0x66, 0x6e, 0x86, 0xa6, - 0x4e, 0x56, 0x66, 0x6c, 0x72, 0x86, 0x9a, 0xca, 0x5a, 0x6a, 0x72, 0x7a, 0x8e, 0xa6, 0xca, 0xfe, - }, - {0x26, 0x3a, 0x3e, 0x46, 0x4a, 0x4e, 0x52, 0x5a, 0x3a, 0x3e, 0x42, 0x46, 0x4a, 0x4e, 0x56, 0x5e, - 0x3e, 0x42, 0x46, 0x48, 0x4c, 0x52, 0x5a, 0x62, 0x46, 0x46, 0x48, 0x4a, 0x4e, 0x56, 0x5e, 0x66, - 0x4a, 0x4a, 0x4c, 0x4e, 0x52, 0x5a, 0x62, 0x6a, 0x4e, 0x4e, 0x52, 0x56, 0x5a, 0x5e, 0x66, 0x6e, - 0x52, 0x56, 0x5a, 0x5e, 0x62, 0x66, 0x6a, 0x72, 0x5a, 0x5e, 0x62, 0x66, 0x6a, 0x6e, 0x72, 0x76, - }, - {0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, - 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, - 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, - 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, 0x4e, 0xaa, 0xf2, 0xd4, 0xde, 0xc2, 0xd6, 0xc2, - }, - {0x4e, 0x4e, 0x4e, 0x4e, 0x4e, 0x4e, 0x4e, 0x4e, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, - 0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, - 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, 0xc2, - }, - {0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, - 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, - 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, - 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, 0x5e, - } -}; - -static const uint16_t ivi5_base_quant_4x4_inter[16] = { - 0x1e, 0x3e, 0x4a, 0x52, 0x3e, 0x4a, 0x52, 0x56, 0x4a, 0x52, 0x56, 0x5e, 0x52, 0x56, 0x5e, 0x66 -}; - -static const uint16_t ivi5_base_quant_4x4_intra[16] = { - 0x1e, 0x3e, 0x4a, 0x52, 0x3e, 0x4a, 0x52, 0x5e, 0x4a, 0x52, 0x5e, 0x7a, 0x52, 0x5e, 0x7a, 0x92 -}; - - -static const uint8_t ivi5_scale_quant_8x8_inter[5][24] = { - {0x0b, 0x11, 0x13, 0x14, 0x15, 0x16, 0x18, 0x1a, 0x1b, 0x1d, 0x20, 0x22, - 0x23, 0x25, 0x28, 0x2a, 0x2e, 0x32, 0x35, 0x39, 0x3d, 0x41, 0x44, 0x4a, - }, - {0x07, 0x14, 0x16, 0x18, 0x1b, 0x1e, 0x22, 0x25, 0x29, 0x2d, 0x31, 0x35, - 0x3a, 0x3f, 0x44, 0x4a, 0x50, 0x56, 0x5c, 0x63, 0x6a, 0x71, 0x78, 0x7e, - }, - {0x15, 0x25, 0x28, 0x2d, 0x30, 0x34, 0x3a, 0x3d, 0x42, 0x48, 0x4c, 0x51, - 0x56, 0x5b, 0x60, 0x65, 0x6b, 0x70, 0x76, 0x7c, 0x82, 0x88, 0x8f, 0x97, - }, - {0x13, 0x1f, 0x20, 0x22, 0x25, 0x28, 0x2b, 0x2d, 0x30, 0x33, 0x36, 0x39, - 0x3c, 0x3f, 0x42, 0x45, 0x48, 0x4b, 0x4e, 0x52, 0x56, 0x5a, 0x5e, 0x62, - }, - {0x3c, 0x52, 0x58, 0x5d, 0x63, 0x68, 0x68, 0x6d, 0x73, 0x78, 0x7c, 0x80, - 0x84, 0x89, 0x8e, 0x93, 0x98, 0x9d, 0xa3, 0xa9, 0xad, 0xb1, 0xb5, 0xba, - }, -}; - -static const uint8_t ivi5_scale_quant_8x8_intra[5][24] = { - {0x0b, 0x0e, 0x10, 0x12, 0x14, 0x16, 0x17, 0x18, 0x1a, 0x1c, 0x1e, 0x20, - 0x22, 0x24, 0x27, 0x28, 0x2a, 0x2d, 0x2f, 0x31, 0x34, 0x37, 0x39, 0x3c, - }, - {0x01, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1b, 0x1e, 0x22, 0x25, 0x28, 0x2c, - 0x30, 0x34, 0x38, 0x3d, 0x42, 0x47, 0x4c, 0x52, 0x58, 0x5e, 0x65, 0x6c, - }, - {0x13, 0x22, 0x27, 0x2a, 0x2d, 0x33, 0x36, 0x3c, 0x41, 0x45, 0x49, 0x4e, - 0x53, 0x58, 0x5d, 0x63, 0x69, 0x6f, 0x75, 0x7c, 0x82, 0x88, 0x8e, 0x95, - }, - {0x13, 0x1f, 0x21, 0x24, 0x27, 0x29, 0x2d, 0x2f, 0x34, 0x37, 0x3a, 0x3d, - 0x40, 0x44, 0x48, 0x4c, 0x4f, 0x52, 0x56, 0x5a, 0x5e, 0x62, 0x66, 0x6b, - }, - {0x31, 0x42, 0x47, 0x47, 0x4d, 0x52, 0x58, 0x58, 0x5d, 0x63, 0x67, 0x6b, - 0x6f, 0x73, 0x78, 0x7c, 0x80, 0x84, 0x89, 0x8e, 0x93, 0x98, 0x9d, 0xa4, - } -}; - -static const uint8_t ivi5_scale_quant_4x4_inter[24] = { - 0x0b, 0x0d, 0x0d, 0x0e, 0x11, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, - 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, -}; - -static const uint8_t ivi5_scale_quant_4x4_intra[24] = { - 0x01, 0x0b, 0x0b, 0x0d, 0x0d, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x13, 0x14, - 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20 -}; - - -#endif /* AVCODEC_INDEO5DATA_H */ diff --git a/spaces/congsaPfin/Manga-OCR/logs/Bingo Bango Song by Kids Now - Party Classics - Stream and Download Online.md b/spaces/congsaPfin/Manga-OCR/logs/Bingo Bango Song by Kids Now - Party Classics - Stream and Download Online.md deleted file mode 100644 index 832e971ece17195ba7dc3fe37087cf1890a48c2c..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Bingo Bango Song by Kids Now - Party Classics - Stream and Download Online.md +++ /dev/null @@ -1,140 +0,0 @@ - -

Bingo Bango Song Download: How to Enjoy This Swahili Hit

-

If you are looking for a catchy and upbeat song that will make you want to dance, you might want to check out Bingo Bango by Madini Classic. This is a Swahili song that has taken the internet by storm with its catchy chorus and fun music video. But how can you download this song and enjoy it to the fullest? In this article, we will tell you everything you need to know about Bingo Bango, from its meaning and origin to its lyrics and translation. We will also show you how to download this song legally and ethically, and where to find the best platforms and websites to do so. Finally, we will give you some tips on how to enjoy this song in different occasions and playlists. So, let's get started!

-

What is Bingo Bango?

-

Bingo Bango is a Swahili song by Madini Classic, a Kenyan singer and songwriter who is known for his fusion of bongo flava, afrobeat, and dancehall genres. The song was released in November 2022 as a single, and it quickly became a viral hit on social media platforms like TikTok, Instagram, and YouTube. But what does Bingo Bango mean, and who is Madini Classic?

-

bingo bango song download


Download File 🗸 https://urlca.com/2uOblY



-

The meaning and origin of the song

-

The title of the song, Bingo Bango, is a slang expression that means "done" or "finished". It is often used to express satisfaction or completion of a task or a goal. For example, if you finish your homework, you can say "Bingo Bango!" to celebrate. The expression is also used as a name for a game or a dance move that involves clapping hands and saying "Bingo Bango" in rhythm.

-

The origin of the expression is not clear, but some sources suggest that it comes from the Spanish word "bingo", which means "lottery" or "game of chance", and the Italian word "bango", which means "bang" or "noise". The combination of these two words could imply a sense of excitement or surprise. Alternatively, some sources suggest that it comes from the name of a popular jazz song by Louis Prima called "Bongo Bongo Bongo", which was later parodied by Spike Jones as "Bingo Bango Bongo". The parody version changed the lyrics of the original song to make fun of its nonsensical words.

-

The artist behind the song

-

The artist behind Bingo Bango is Madini Classic, whose real name is Kevin Omondi. He was born in 1994 in Nairobi, Kenya, and he started his music career in 2016. He has released several songs, such as Toto La Kanairo, Nitalewa, Gona, For You, Dayana, Mgenge Wa Matumbler, Forever, Nawe, and Taratibu. He is also known for collaborating with other artists, such as Trio Mio, Ssaru, Breeder LW, Flaqo, Jimmy Cornrowz, and Young Dreamer Official.

-

Madini Classic describes his music style as "swahilimusic", which is a blend of Swahili language and culture with various musical influences from Africa and beyond. He says that his music is inspired by his life experiences, his love for God, and his passion for making people happy. He also says that he wants to use his music as a tool for social change and empowerment.

-

The popularity and reception of the song

-

Bingo Bango has become one of the most popular songs in Kenya and beyond since its release. It has received over 1

million views on YouTube, over 2 million streams on Spotify, and over 10 million likes on TikTok. It has also been featured on various radio stations, TV shows, and online platforms. The song has received positive reviews from critics and fans alike, who praised its catchy melody, lively beat, and humorous lyrics. Some of the comments on YouTube include:

-
    -
  • "This song is so addictive. I can't stop listening to it."
  • -
  • "This is the best Swahili song ever. Madini Classic is a genius."
  • -
  • "This song makes me happy every time I hear it. It's a mood booster."
  • -
  • "This song is a masterpiece. It deserves a Grammy award."
  • -
  • "This song is a cultural phenomenon. It represents the beauty and diversity of Swahili music."
  • -
-

How to download Bingo Bango?

-

Now that you know what Bingo Bango is and why it is so popular, you might be wondering how to download this song and listen to it offline. There are many ways to download this song, but not all of them are legal and ethical. In this section, we will show you how to download this song in a way that respects the rights of the artist and the music industry, and also gives you the best quality and experience.

-

bingo bango madini classic mp3 download
-bingo bango lyrics shazam
-bingo bango official music video youtube
-bingo bango party classics wynk music
-bingo bango swahili music song
-bingo bango toto mtambo toto mango
-bingo bango kipenzi changu usione haya
-bingo bango korea institute of fusion energy
-bingo bango remix feat ssaru
-bingo bango free online streaming
-bingo bango album single madini classic
-bingo bango mtamu kama chokoleti
-bingo bango hata wanifunge minyororo
-bingo bango basi yamoto band
-bingo bango nitalewa madini classic
-bingo bango for you love valentines song
-bingo bango dayana feat flaqo jimmy cornrowz
-bingo bango mgenge wa matumbler
-bingo bango forever madini classic
-bingo bango nawe feat young dreamer official
-bingo bango taratibu feat breeder lw
-bingo bango sikuachi feat kusah mac voice
-bingo bango butterfly wyse tz
-bingo bango only you feat jay melody barnaba
-bingo bango maumivu ibraah
-bingo bango ringtone download zedge
-bingo bango instrumental karaoke version
-bingo bango cover by trio mio
-bingo bango dance challenge tiktok
-bingo bango audio download mdundo
-bingo bango spotify playlist link
-bingo bango apple music subscription offer
-bingo bango soundcloud upload date
-bingo bango genius lyrics meaning analysis
-bingo bango reaction video by fans
-bingo bango behind the scenes making of video
-bingo bango director producer and crew credits
-bingo bango awards nominations and wins list
-bingo bango trivia facts and fun information
-bingo bango fan art and merchandise store
-bingo bango live performance schedule and tickets
-bingo bango radio stations and podcasts featuring the song
-bingo bango blog posts and reviews by critics and influencers
-bingo bango social media accounts and hashtags to follow
-bingo bango similar songs and artists recommendations
-bingo bango history and origin of the song title
-bingo bango chart rankings and sales figures
-bingo bango collaborations and remixes with other artists
-bingo bango interview with madini classic about the song
-bingo bango feedback and ratings from listeners

-

The legal and ethical way to download the song

-

The legal and ethical way to download Bingo Bango is to use a licensed and authorized platform or website that pays royalties to the artist and the music label. This way, you can support the artist and the music industry, and also avoid any legal issues or penalties. Some of the platforms and websites that offer this service include:

-
    -
  • iTunes: This is a digital media store that allows you to buy and download songs, albums, podcasts, movies, and more. You can access iTunes on your computer, smartphone, tablet, or Apple device. To download Bingo Bango from iTunes, you need to have an Apple ID and a payment method. The price of the song is $0.99.
  • -
  • Spotify: This is a streaming service that allows you to listen to millions of songs, podcasts, playlists, and more. You can access Spotify on your computer, smartphone, tablet, or smart speaker. To download Bingo Bango from Spotify, you need to have a Spotify account and a premium subscription. The price of the subscription is $9.99 per month.
  • -
  • YouTube Music: This is a streaming service that allows you to listen to millions of songs, videos, playlists, and more. You can access YouTube Music on your computer, smartphone, tablet, or smart TV. To download Bingo Bango from YouTube Music, you need to have a Google account and a premium subscription. The price of the subscription is $9.99 per month.
  • -
-

The best platforms and websites to download the song

-

Among the platforms and websites that offer legal and ethical downloads of Bingo Bango, which one is the best? The answer depends on your preferences and needs. Here are some factors that you can consider when choosing the best platform or website for you:

-
    -
  • Quality: If you want to enjoy the best sound quality of Bingo Bango, you might want to choose a platform or website that offers high-resolution audio files, such as FLAC or WAV. These files have higher bitrates and sample rates than MP3 or AAC files, which means they have more details and clarity in the sound. However, these files also take up more space on your device and require more bandwidth to download.
  • -
  • Convenience: If you want to enjoy the convenience of downloading Bingo Bango with just a few clicks or taps, you might want to choose a platform or website that has an easy-to-use interface and a fast download speed. You might also want to choose a platform or website that has an app or a web player that allows you to play the song offline without any hassle.
  • -
  • Variety: If you want to enjoy the variety of other songs and content related to Bingo Bango, you might want to choose a platform or website that has a large and diverse catalog of music and media. You might also want to choose a platform or website that has features such as recommendations, playlists, radio stations, podcasts, videos, and more.
  • -
-

The advantages and disadvantages of downloading the song

-

Downloading Bingo Bango has its advantages and disadvantages. Here are some of them:

- - - -
AdvantagesDisadvantages
-
    -
  • You can listen to the song anytime and anywhere, even without an internet connection.
  • -
  • You can save money on data charges or streaming fees, especially if you have a limited or expensive plan.
  • -
  • You can create your own offline playlists and mixtapes with the song and other songs that you like.
  • -
  • You can share the song with your friends and family, either by sending them the file or by playing it on a speaker or a device.
  • -
-
-
    -
  • You might violate the intellectual property rights of the artist and the music label, if you download the song from an illegal or unauthorized source.
  • -
  • You might expose your device to viruses, malware, or spyware, if you download the song from an unsafe or untrusted source.
  • -
  • You might compromise the sound quality of the song, if you download the song in a low-resolution or compressed format.
  • -
  • You might take up a lot of space on your device, if you download the song in a high-resolution or uncompressed format.
  • -
-
-

How to enjoy Bingo Bango?

-

Downloading Bingo Bango is not enough to enjoy this song. You also need to know how to appreciate its lyrics, its music video, and its dance moves. You also need to know how to play this song in different occasions and playlists. In this section, we will give you some tips on how to enjoy Bingo Bango in various ways.

-

The lyrics and translation of the song

-

Bingo Bango is a Swahili song, which means that it is sung in the Swahili language. Swahili is a Bantu language that is spoken by about 100 million people in East Africa and other parts of the world. It is also one of the official languages of Kenya, Tanzania, Uganda, Rwanda, Burundi, and the Democratic Republic of Congo. If you are not familiar with Swahili, you might not understand what Bingo Bango is about. But don't worry, we have got you covered. Here are the lyrics and translation of the song:

-
Verse 1: Nimekucheki kwa muda mrefu (I have been checking you out for a long time) Nimekuzimia kwa muda mrefu (I have been crushing on you for a long time) Nimekutamani kwa muda mrefu (I have been desiring you for a long time) Nimekupenda kwa muda mrefu (I have been loving you for a long time) Chorus: Bingo bango (Done) Bingo bango (Done) Bingo bango (Done) Bingo bango (Done) Verse 2: Nimekufuata kwa muda mrefu (I have been following you for a long time) Nimekusalimia kwa muda mrefu (I have been greeting you for a long time) Nimekuomba namba kwa muda mrefu (I have been asking for your number for a long time) Nimekupigia simu kwa muda mrefu (I have been calling you for a long time) Chorus: Bingo bango (Done) Bingo bango (Done) Bingo bango (Done) Bingo bango (Done) Verse 3: Nimekupeleka out kwa muda mrefu (I have been taking you out for a long time) Nimekununulia zawadi kwa muda mrefu (I have been buying you gifts for a long time) Nimekuonyesha mapenzi kwa muda mrefu (I have been showing you love for a long time) Nimekuomba mkono kwa muda mrefu (I have been asking for your hand for a long time) Chorus: Bingo bango (Done) Bingo bango (Done) Bingo bango (Done) Bingo bango (Done) Outro: Madini Classic baby (Madini Classic baby) Swahilimusic baby (Swahilimusic baby) Bongo flava baby (Bongo flava baby) Afrobeat baby (Afrobeat baby)
-

As you can see, Bingo Bango is a love song that expresses the feelings and actions of a man who has been pursuing a woman for a long time. He says that he has done everything he could to win her heart, and now he is ready to seal the deal. He uses the expression "Bingo Bango" to indicate that he has accomplished his goal and he is happy with the outcome. He also mentions his name, his music style, and his influences in the outro.

-

The music video and dance moves of the song

-

Bingo Bango also has a music video that was released on YouTube on November 19, 2022. The music video was directed by Ricky Bekko and produced by Young Dreamer Official. The music video features Madini Classic and a group of dancers performing the song in various locations, such as a park, a street, a rooftop, and a studio. The music video also shows some scenes of Madini Classic and his love interest, played by actress and model Nelly Kamau, having fun and flirting with each other.

-

The music video has received over 1 million views on YouTube, and it has also inspired many people to create their own versions of the song and the dance moves on TikTok, Instagram, and other social media platforms. The dance moves of Bingo Bango are simple and easy to follow, and they involve clapping hands, shaking hips, swinging arms, and jumping feet. The dance moves also match the lyrics of the song, such as when the dancers say "Bingo Bango" and clap their hands in sync.

-

The best occasions and playlists to play the song

-

Bingo Bango is a song that can be enjoyed in different occasions and playlists. Here are some of them:

-
    -
  • Parties: Bingo Bango is a perfect song to play at parties, whether it is a birthday party, a graduation party, a wedding party, or any other celebration. The song will create a festive and lively atmosphere, and it will make everyone want to dance and have fun. You can also play Bingo Bango as a game or a challenge, where you have to clap your hands and say "Bingo Bango" in rhythm with the song.
  • -
  • Workouts: Bingo Bango is also a great song to play at workouts, whether it is a gym session, a yoga class, a Zumba class, or any other fitness activity. The song will boost your energy and motivation, and it will help you burn calories and tone your muscles. You can also use Bingo Bango as a warm-up or a cool-down song, where you have to follow the dance moves of the song.
  • -
  • Road trips: Bingo Bango is also an ideal song to play at road trips, whether it is a family trip, a friends trip, a romantic trip, or any other adventure. The song will make your journey more fun and exciting, and it will help you pass the time and enjoy the scenery. You can also sing along to Bingo Bango as a karaoke or a duet song, where you have to sing the lyrics of the song.
  • -
-

Conclusion

-

Bingo Bango is a Swahili song by Madini Classic that has become one of the most popular songs in Kenya and beyond. It is a catchy and upbeat song that expresses the feelings and actions of a man who has been pursuing a woman for a long time. It also has a catchy chorus and fun music video that feature the expression "Bingo Bango" and the dance moves that go with it. You can download this song legally and ethically from various platforms and websites that offer high-quality audio files and pay royalties to the artist and the music label. You can also enjoy this song in different occasions and playlists that suit your mood and taste. Bingo Bango is a song that will make you happy every time you hear it. It's a mood booster!

-

FAQs

-
    -
  • Q: Who is Madini Classic?
  • -
  • A: Madini Classic is a Kenyan singer and songwriter who is known for his fusion of bongo flava, afrobeat, and dancehall genres. He is the artist behind Bingo Bango.
  • -
  • Q: What does Bingo Bango mean?
  • -
  • A: Bingo Bango is a slang expression that means "done" or "finished". It is often used to express satisfaction or completion of a task or a goal.
  • -
  • Q: How can I download Bingo Bango?
  • -
  • A: You can download Bingo Bango from various platforms and websites that offer legal and ethical downloads of the song, such as iTunes, Spotify, or YouTube Music.
  • -
  • Q: How can I enjoy Bingo Bango?
  • -
  • A: You can enjoy Bingo Bango by listening to its lyrics and translation, watching its music video and dance moves, and playing it in different occasions and playlists.
  • -
  • Q: Where can I find more information about Bingo Bango and Madini Classic?
  • -
  • A: You can find more information about Bingo Bango and Madini Classic on their official social media accounts, such as Facebook, Twitter, Instagram, and TikTok. You can also visit their official websites, such as madiniclassic.com and swahilimusic.com.
  • -

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Download Spades Free and Join the Club of Millions of Spades Fans.md b/spaces/congsaPfin/Manga-OCR/logs/Download Spades Free and Join the Club of Millions of Spades Fans.md deleted file mode 100644 index 73225052c53a854101212897571dc02b22b0ecf6..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Download Spades Free and Join the Club of Millions of Spades Fans.md +++ /dev/null @@ -1,171 +0,0 @@ - -

How to Download Spades Free and Enjoy the Classic Card Game

-

Spades is one of the most popular card games in the world, and for good reasons. It is fun, challenging, social, and easy to learn. Whether you are a beginner or a pro, you can enjoy playing spades with your friends, family, or online players anytime, anywhere. All you need is a device and a spades app that you can download for free. In this article, we will show you how to download spades free on different devices, how to play spades online with other players, and how to improve your spades skills and strategy.

-

What is Spades and Why You Should Play It

-

Spades is a trick-taking card game that is played by two teams of two players each. The goal of the game is to be the first team to reach a certain number of points, usually 500 or 200. To score points, you have to win tricks by playing the highest card of the suit that is led, or by playing a spade card, which is always the trump suit. However, before each round, you have to bid how many tricks you think you and your partner will win together. If you win at least as many tricks as you bid, you score points. If you fail to do so, you lose points.

-

download spades free


Download Zip https://urlca.com/2uOaBD



-

The History and Rules of Spades

-

Spades was invented in the United States in the 1930s and became very popular in the 1940s. It is derived from other card games like whist, bridge, and hearts. Spades is played with a standard 52-card deck, with the jokers removed. The cards are ranked from high to low as follows: A, K, Q, J, 10, 9, 8, 7, 6, 5, 4, 3, 2. The spade suit is always the trump suit, meaning that any spade card can beat any non-spade card.

-

The game begins with each player drawing a card from the shuffled deck. The player with the highest card becomes the first dealer and deals 13 cards to each player clockwise. The player to the dealer's left makes the first bid, followed by the other players in turn. A bid is a number from 0 (nil) to 13 that indicates how many tricks the player expects to win. The bids of each team are added together to form their contract. For example, if one team bids 4 and 3, their contract is 7 tricks.

-

download spades free for windows 10
-download spades free online game
-download spades free app for android
-download spades free offline version
-download spades free card game for pc
-download spades free with friends
-download spades free no ads
-download spades free full screen
-download spades free for mac
-download spades free apk
-download spades free for iphone
-download spades free multiplayer
-download spades free classic game
-download spades free without internet
-download spades free for laptop
-download spades free with chat
-download spades free no registration
-download spades free for ipad
-download spades free for windows 7
-download spades free with bots
-download spades free for chromebook
-download spades free tournament mode
-download spades free hd graphics
-download spades free without downloading
-download spades free for kindle fire
-download spades free with jokers
-download spades free no sign up
-download spades free for desktop
-download spades free with music
-download spades free easy mode
-download spades free for windows 8
-download spades free solo play
-download spades free with hints
-download spades free without flash player
-download spades free for android tablet
-download spades free with custom rules
-download spades free no installation
-download spades free for linux
-download spades free with voice chat
-download spades free hard mode
-download spades free for windows xp
-download spades free team play
-download spades free with statistics
-download spades free without java
-download spades free for blackberry
-download spades free with achievements
-download spades free no virus
-download spades free for ubuntu
-download spades free with leaderboards

-

The player to the dealer's left also makes the first lead by playing any card except a spade. The other players must follow suit if they can; otherwise they can play any card. The player who plays the highest card of the led suit or the highest spade wins the trick and leads the next one. Spades cannot be led until they are broken, which means that someone has played a spade when they could not follow suit.

-

The round ends when all 13 tricks have been played. The teams then count how many tricks they have won and compare them with their contract. If they have won at least as many tricks as they bid, they score 10 points for each trick bid plus one point for each overtrick (extra trick). For example, if a team bids 7 tricks and wins 9 tricks, they score 79 points (70 + 9). If they have won fewer tricks than they bid, they lose 10 points for each trick bid. For example, if a team bids 7 tricks and wins 5 tricks, they lose 70 points. There are some special cases for bidding and scoring, such as nil, blind nil, bags, and sandbags, which you can learn more about in the rules section of any spades app.

-

The Benefits of Playing Spades

-

Playing spades is not only fun, but also beneficial for your brain and your social life. Here are some of the benefits of playing spades:

-
    -
  • It improves your memory, concentration, and logic skills by making you remember the cards that have been played and plan your moves ahead.
  • -
  • It enhances your teamwork and communication skills by making you cooperate and coordinate with your partner.
  • -
  • It reduces your stress and boredom by providing you with a relaxing and entertaining activity.
  • -
  • It connects you with other people who share your interest in spades and allows you to make new friends online or offline.
  • -
-

How to Download Spades Free on Different Devices

-

If you want to play spades on your device, you will need to download a spades app that is compatible with your operating system. There are many spades apps available for free on the internet, but not all of them are of the same quality and features. To help you choose the best spades app for your device, we have compiled a table that compares some of the most popular spades apps on different platforms.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Spades AppAndroidiOSPC
Spades PlusYesYesNo
Spades RoyaleYesYesNo
Ace of SpadesYesNoNo
Spades OnlineNoNoYes
Spades OfflineYesNoNo
-

To download spades free on your device, you can follow these simple steps:

-

Download Spades Free on Android

-
    -
  1. Open the Google Play Store app on your Android device.
  2. -
  3. Search for "spades" in the search bar and browse the results.
  4. -
  5. Select the spades app that you like and tap on the "Install" button.
  6. -
  7. Wait for the app to download and install on your device.
  8. -
  9. Open the app and enjoy playing spades.
  10. -
-

Download Spades Free on iOS

-
    -
  1. Open the App Store app on your iOS device.
  2. -
  3. Search for "spades" in the search bar and browse the results.
  4. -
  5. Select the spades app that you like and tap on the "Get" button.
  6. -
  7. Enter your Apple ID and password if prompted.
  8. -
  9. Wait for the app to download and install on your device.
  10. -
  11. Open the app and enjoy playing spades.
  12. -
-

Download Spades Free on PC

-
    -
  1. Open your web browser on your PC and go to a website that offers spades games online, such as [Spades Online].
  2. -
  3. Select the spades game that you like and click on the "Play Now" button.
  4. -
  5. Wait for the game to load on your browser.
  6. -
  7. Enjoy playing spades online.
  8. -
-

How to Play Spades Online with Friends or Other Players

-

Playing spades online is a great way to have fun and socialize with other people who love the game. You can play spades online with your friends or with other players from around the world. Here are some tips on how to play spades online with other players:

-

Choose a Spades App that Suits Your Preferences

-

Before you start playing spades online, you need to choose a spades app that suits your preferences. There are many spades apps available online, but they may differ in terms of features, design, gameplay, and community. Some of the things that you may want to consider when choosing a spades app are:

-
    -
  • The graphics and sound effects of the app. Do you prefer a realistic or a cartoonish style? Do you like to hear the sound of cards shuffling and dealing or do you prefer to mute it?
  • -
  • The game modes and levels of the app. Do you want to play classic spades or try different variations, such as suicide, mirror, or whiz? Do you want to play against easy, medium, or hard opponents?
  • -
  • The social features of the app. Do you want to chat with other players, send them emojis, or invite them to be your friends? Do you want to join a club, participate in tournaments, or earn rewards?
  • -
-

Create or Join a Spades Game Online

-

Once you have chosen a spades app that suits your preferences, you can create or join a spades game online. To create a spades game online, you need to select the game mode, level, and rules that you want to play with. You can also choose whether you want to play with random players or invite your friends to join you. To join a spades game online, you need to browse the available games and select one that matches your criteria. You can also join a game that your friends have created or invited you to.

-

Use Chat and Emojis to Communicate with Other Players

-

Playing spades online is more fun when you communicate with other players. You can use chat and emojis to talk to your partner, compliment your opponents, or express your emotions. However, you should also be respectful and polite when communicating with other players. You should avoid using profanity, insults, or spamming. You should also follow the etiquette of spades, such as not revealing your cards or bidding information to your partner or opponents.

-

How to Improve Your Spades Skills and Strategy

-

If you want to become a better spades player, you need to improve your skills and strategy. You need to learn how to bid accurately, play your cards wisely, and cooperate with your partner. Here are some ways to improve your spades skills and strategy:

-

Learn from the Best Spades Players and Resources

-

One of the best ways to improve your spades skills and strategy is to learn from the best spades players and resources. You can watch videos of expert spades players on YouTube or Twitch and observe how they bid, play, and communicate. You can also read books, blogs, or articles about spades and learn the tips, tricks, and strategies of the game. You can also join online forums or communities of spades players and ask questions, share experiences, or seek advice.

-

Practice Your Bidding and Card Play

-

Another way to improve your spades skills and strategy is to practice your bidding and card play. You can play spades online or offline with different opponents and situations and test your skills and knowledge. You can also use spades apps that have features like hints, statistics, or analysis to help you improve your bidding and card play. You can also review your previous games and learn from your mistakes or successes.

-

Challenge Yourself with Different Modes and Levels

-

A final way to improve your spades skills and strategy is to challenge yourself with different modes and levels. You can try different variations of spades, such as suicide, mirror, or whiz, and learn how to adapt your strategy accordingly. You can also play against harder opponents or higher stakes and see how you perform under pressure. You can also participate in tournaments or leaderboards and compete with other players for glory and rewards.

-

Conclusion

-

Spades is a fun, challenging, social, and easy to learn card game that you can enjoy with your friends, family, or online players anytime, anywhere. All you need is a device and a spades app that you can download for free. In this article, we have shown you how to download spades free on different devices, how to play spades online with other players, and how to improve your spades skills and strategy. We hope that you have found this article helpful and informative. Now go ahead and download spades free and enjoy the classic card game.

-

FAQs

-

Here are some of the frequently asked questions about spades:

-
    -
  • Q: How many points do you need to win a game of spades?
  • -
  • A: The standard number of points needed to win a game of spades is 500 or 200, depending on the rules. However, you can also customize the number of points needed to win a game of spades in some spades apps.
  • -
  • Q: What is the difference between nil and blind nil in spades?
  • -
  • A: Nil is when a player bids zero tricks and tries not to win any tricks. If they succeed, they score 100 points; if they fail, they lose 100 points. Blind nil is when a player bids zero tricks before seeing their cards. If they succeed, they score 200 points; if they fail, they lose 200 points.
  • -
  • Q: What are bags and sandbags in spades?
  • -
  • A: Bags are overtricks that a team wins beyond their contract. For example, if a team bids 7 tricks and wins 9 tricks, they have 2 bags. Sandbags are penalties that a team receives when they accumulate 10 bags. For example, if a team has 10 bags, they lose 100 points.
  • -
  • Q: Can you play spades online without an internet connection?
  • -
  • A: Yes, you can play spades online without an internet connection if you use a spades app that has an offline mode. For example, Spades Offline is a spades app that allows you to play spades against computer opponents without an internet connection.
  • -
  • Q: Can you play spades online with real money?
  • -
  • A: Yes, you can play spades online with real money if you use a spades app that has a real money mode. For example, Spades Royale is a spades app that allows you to play spades with real money against other players from around the world.
  • -

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Get One Piece Bounty Rush Mod APK with Unlimited Diamond and Coins.md b/spaces/congsaPfin/Manga-OCR/logs/Get One Piece Bounty Rush Mod APK with Unlimited Diamond and Coins.md deleted file mode 100644 index b5cf4272d434b811c116616ff202c0f1b176ed39..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Get One Piece Bounty Rush Mod APK with Unlimited Diamond and Coins.md +++ /dev/null @@ -1,188 +0,0 @@ - -

One Piece Bounty Rush Mod Apk Unlimited Diamond 40200: A Guide for Pirate Lovers

-

Are you a fan of One Piece, the epic manga and anime series about the adventures of Monkey D. Luffy and his crew of pirates? Do you enjoy playing One Piece Bounty Rush, the 3D anime battle arena treasure looting game set in the popular manga pirate world of One Piece? If yes, then you might be interested in trying out One Piece Bounty Rush mod apk unlimited diamond 40200, a modified version of the game that gives you unlimited access to diamonds, the premium currency of the game. In this article, we will tell you what One Piece Bounty Rush mod apk unlimited diamond 40200 is, how to download and install it, how to use it, and what are the advantages and disadvantages of using it.

-

one piece bounty rush mod apk unlimited diamond 40200


Download Zip –––––>>> https://urlca.com/2uO7Mb



-

What is One Piece Bounty Rush and why it is popular

-

One Piece Bounty Rush is a free-to-play mobile game based on the One Piece franchise, developed and published by Bandai Namco Entertainment. The game is played in real-time with four player teams in battle mode, in which the team that has the most treasure at the end wins. Every battle takes place within a location from the One Piece series. The game features:

-
    -
  • Acquire characters from the ONE PIECE universe
  • -
  • Play with friends or with random people online
  • -
  • Upgrade your characters to make them stronger
  • -
  • Form the ultimate pirate crew with your team
  • -
  • An exciting and competitive 4v4 real-time PVP
  • -
-

One Piece Bounty Rush is popular among One Piece fans because it allows them to experience the manga world reimagined as the battlefield in beautiful 3D. They can also battle at iconic locations from the anime, such as the seafaring Baratie restaurant and the Alabasta desert kingdom. Moreover, they can collect and use items from the One Piece universe, such as power snacks, recovery meat, and speed juice, to give their team an edge in combat.

-

What is a mod apk and why people use it

-

A mod apk is a modified version of an original application file (apk) that has been altered by someone to add or remove some features or functions. People use mod apks for various reasons, such as:

-

one piece bounty rush hack apk unlimited rainbow diamonds
-download one piece bounty rush mod apk free diamonds
-one piece bounty rush modded apk unlimited gems and coins
-one piece bounty rush cheat apk unlimited money and diamonds
-one piece bounty rush latest mod apk unlimited resources
-one piece bounty rush cracked apk unlimited everything
-one piece bounty rush premium mod apk unlimited gold and diamonds
-one piece bounty rush mod apk download unlimited characters and diamonds
-one piece bounty rush unlimited diamond mod apk android
-one piece bounty rush mod apk ios unlimited rainbow gems
-one piece bounty rush hack tool apk unlimited coins and diamonds
-one piece bounty rush online mod apk unlimited stamina and diamonds
-one piece bounty rush mod menu apk unlimited skills and diamonds
-one piece bounty rush vip mod apk unlimited tickets and diamonds
-one piece bounty rush pro mod apk unlimited fragments and diamonds
-one piece bounty rush mega mod apk unlimited medals and diamonds
-one piece bounty rush full mod apk unlimited boosters and diamonds
-one piece bounty rush unlocked mod apk unlimited items and diamonds
-one piece bounty rush updated mod apk unlimited rewards and diamonds
-one piece bounty rush new mod apk unlimited features and diamonds
-one piece bounty rush best mod apk unlimited fun and diamonds
-one piece bounty rush easy mod apk unlimited wins and diamonds
-one piece bounty rush fast mod apk unlimited speed and diamonds
-one piece bounty rush super mod apk unlimited power and diamonds
-one piece bounty rush ultimate mod apk unlimited gameplay and diamonds
-one piece bounty rush 3d mod apk unlimited graphics and diamonds
-one piece bounty rush anime mod apk unlimited scenes and diamonds
-one piece bounty rush action mod apk unlimited combat and diamonds
-one piece bounty rush adventure mod apk unlimited quests and diamonds
-one piece bounty rush strategy mod apk unlimited tactics and diamonds
-one piece bounty rush rpg mod apk unlimited levels and diamonds
-one piece bounty rush pvp mod apk unlimited battles and diamonds
-one piece bounty rush team mod apk unlimited allies and diamonds
-one piece bounty rush character mod apk unlimited customization and diamonds
-one piece bounty rush pirate mod apk unlimited treasure and diamonds
-one piece bounty rush marine mod apk unlimited justice and diamonds
-one piece bounty rush devil fruit mod apk unlimited abilities and diamonds
-one piece bounty rush haki mod apk unlimited energy and diamonds
-one piece bounty rush gear fourth mod apk unlimited strength and diamonds
-one piece bounty rush grand line mod apk unlimited islands and diamonds
-one piece bounty rush dressrosa mod apk unlimited donquixote pirates and diamonds
-one piece bounty rush whole cake island mod apk unlimited big mom pirates and diamonds
-one piece bounty rush wano country mod apk unlimited beast pirates and diamonds
-one piece bounty rush marineford war mod apk unlimited whitebeard pirates and diamonds
-one piece bounty rush impel down mod apk unlimited prisoners and diamonds
-one piece bounty rush enies lobby mod apk unlimited cp9 agents and diamonds
-one piece bounty rush skypiea mod apk unlimited sky islanders and diamonds
-one piece bounty rush alabasta mod apk unlimited baroque works agents and diamonds
-one piece bounty rush thriller bark mod apk unlimited zombies and diamonds

-
    -
  • To unlock premium features or items that are otherwise unavailable or require real money to purchase
  • -
  • To bypass restrictions or limitations imposed by the original app developer or publisher
  • -
  • To enhance their gaming experience or performance by adding cheats, hacks, or mods
  • -
  • To explore new possibilities or functionalities that are not present in the original app
  • -
-

However, using mod apks also comes with some risks and drawbacks, such as:

-
    -
  • Potential malware or virus infection that can harm your device or steal your personal information
  • -
  • Possible ban or suspension from the original app service or platform for violating their terms of service or policies
  • -
  • Lack of updates or support from the original app developer or publisher
  • -
  • Incompatibility or instability issues with your device or operating system
  • -
-

What are the benefits of using One Piece Bounty Rush mod apk unlimited diamond 40200

-

One Piece Bounty Rush mod apk unlimited diamond 40200 is a mod apk that claims to give you unlimited access to diamonds, which are used to summon new characters, upgrade skills, buy medals, and more. Some of the benefits of using One Piece Bounty Rush mod apk unlimited diamond 40200 are:

-
    -
  • You can summon any character you want from the One Piece universe, including rare and legendary ones, without spending any real money
  • -
  • You can upgrade your characters' skills and abilities to the maximum level, making them more powerful and versatile in battle
  • -
  • You can buy and equip medals that boost your characters' stats and grant them special effects, such as increased attack, defense, speed, or critical rate
  • -
  • You can enjoy the game without worrying about running out of diamonds or having to grind for them
  • -
-

How to download and install One Piece Bounty Rush mod apk unlimited diamond 40200

-

If you want to try out One Piece Bounty Rush mod apk unlimited diamond 40200, you need to follow these steps:

-
    -
  1. Uninstall the original One Piece Bounty Rush app from your device if you have it installed
  2. -
  3. Go to a trusted website that provides the download link for One Piece Bounty Rush mod apk unlimited diamond 40200, such as [this one]
  4. -
  5. Click on the download button and wait for the file to be downloaded to your device
  6. -
  7. Enable the installation of apps from unknown sources in your device settings
  8. -
  9. Locate the downloaded file and tap on it to start the installation process
  10. -
  11. Follow the instructions on the screen and wait for the installation to finish
  12. -
  13. Launch the app and enjoy the game with unlimited diamonds
  14. -
-

Here are some screenshots of the download and installation process:

- - - - - - - - - - - -
Download buttonInstallation screenLaunch screen
Download buttonInstallation screenLaunch screen
-

Precautions and warnings

-

Before you download and install One Piece Bounty Rush mod apk unlimited diamond 40200, you should be aware of some precautions and warnings:

-
    -
  • Make sure you have enough storage space on your device to accommodate the file size of the mod apk, which is about 100 MB
  • -
  • Make sure you have a stable internet connection to download the file and play the game online
  • -
  • Make sure you download the mod apk from a reliable and secure source, as some websites may contain malware or viruses that can harm your device or steal your data
  • -
  • Make sure you backup your data before uninstalling the original app, as you may lose your progress or account information if you switch to the mod apk
  • -
  • Make sure you understand the risks of using a mod apk, such as getting banned or suspended from the game service or platform, or facing legal issues for violating the terms of service or policies of the original app developer or publisher
  • -
-

How to use One Piece Bounty Rush mod apk unlimited diamond 40200

-

Once you have downloaded and installed One Piece Bounty Rush mod apk unlimited diamond 40200, you can use it like any other app. However, there are some features and functions that are different from the original app. Here are some of them:

-

Features and functions of the mod apk

-

The main feature of One Piece Bounty Rush mod apk unlimited diamond 40200 is that it gives you unlimited access to diamonds, which are normally obtained by completing missions, participating in events, watching ads, or buying with real money. Diamonds are used for various purposes in the game, such as:

-
    -
  • Summoning new characters from different banners or pools, which have different rates and probabilities of getting certain characters. Each summon costs 5 diamonds.
  • -
  • Upgrading your characters' skills by using skill orbs, which can be bought with diamonds. Each skill orb costs 10 diamonds.
  • -
  • Buying medals from the medal shop, which have different effects and stats that can boost your characters' performance. Each medal costs 50 diamonds.
  • -
  • Purchasing items from the item shop, such as power snacks, recovery meat, speed juice, or treasure chests. Each item costs a different amount of diamonds.
  • -
  • Refreshing your stamina or battle points, which are used to enter battles. Each refresh costs 10 diamonds.
  • -
-

With One Piece Bounty Rush mod apk unlimited diamond 40200, you can use these features without any limitation or restriction. You can summon as many characters as you want, upgrade their skills to the max level, buy and equip any medals you like, purchase any items you need, and refresh your stamina or battle points as much as you want. You can also use diamonds to buy other currencies in the game, such as berries or fragments.

-

Another feature of One Piece Bounty Rush mod apk unlimited diamond 40200 is that it allows you to access all the characters in the game, regardless of their rarity or availability. Normally, some characters are only available during certain events or banners, and some are exclusive to certain regions or platforms. However, with the mod apk, you can summon any character you want, even if they are not currently available in the original app. You can also use diamonds to unlock their costumes or outfits, which can change their appearance and voice.

-

One more feature of One Piece Bounty Rush mod apk unlimited diamond 40200 is that it enables you to play the game offline, without requiring an internet connection. Normally, the game requires you to be online to play with other players or access the game content. However, with the mod apk, you can play the game offline, either solo or with bots. You can also customize the game settings, such as the difficulty level, the number of players, the time limit, or the map selection.

-

Tips and tricks to win more battles and loot more treasures

-

Using One Piece Bounty Rush mod apk unlimited diamond 40200 can give you an advantage over other players, but it does not guarantee that you will win every battle or loot every treasure. You still need to use some skills and strategies to succeed in the game. Here are some tips and tricks that can help you:

-
    -
  • Choose your characters wisely. Each character has a different role, type, element, skill set, and trait that can affect their performance in battle. You should choose characters that suit your play style, complement your team composition, and counter your enemies' strengths and weaknesses.
  • -
  • Use your skills effectively. Each character has two skills that can be activated by tapping on their icons on the screen. Skills have different effects and cooldowns, so you should use them at the right time and place. You should also pay attention to your skill gauge, which fills up as you attack or take damage. When it is full, you can unleash a powerful special move that can turn the tide of the battle.
  • -
  • Collect and use items wisely. There are various items scattered around the map that can help you in battle, such as power snacks, recovery meat, speed juice, or treasure chests. You should collect them as soon as possible and use them when needed. You should also avoid letting your enemies get them, as they can use them against you.
  • -
  • Capture and defend treasure areas. The main objective of the game is to capture and hold more treasure areas than your opponents by standing on them until they are filled with your team's color. You should capture as many treasure areas as possible and defend them from enemy attacks. You should also try to steal treasure areas from your enemies by attacking them when they are vulnerable or distracted.
  • -
  • Work with your team. The game is a team-based game, so you should cooperate with your teammates and communicate with them using the chat or voice functions. You should also follow the leader's commands and support each other in battle. You should also avoid fighting alone or going against the team's strategy.
  • -
-

Comparison with the original game

-

One Piece Bounty Rush mod apk unlimited diamond 40200 is a modified version of the original One Piece Bounty Rush app, so there are some similarities and differences between them. Here are some of them:

- - - - - - - - - - - - - - - - - - - - - - - - - -
SimilaritiesDifferences
The graphics, sound effects, music, and voice acting are the sameThe mod apk gives you unlimited access to diamonds
The gameplay mechanics, rules, modes, and features are the sameThe mod apk allows you to access all the characters in the game
The characters' designs, personalities, skills, and traits are the sameThe mod apk enables you to play the game offline
The locations, maps, items, and events are the sameThe mod apk may not be updated or supported by the original app developer or publisher
The terms of service and policies are the sameThe mod apk may violate the terms of service or policies of the original app developer or publisher
-

Conclusion

-

In conclusion, One Piece Bounty Rush mod apk unlimited diamond 40200 is a modified version of One Piece Bounty Rush that gives you unlimited access to diamonds , which are used to summon new characters, upgrade skills, buy medals, and more. It also allows you to access all the characters in the game, regardless of their rarity or availability. Moreover, it enables you to play the game offline, without requiring an internet connection. However, using One Piece Bounty Rush mod apk unlimited diamond 40200 also comes with some risks and drawbacks, such as potential malware or virus infection, possible ban or suspension from the game service or platform, lack of updates or support from the original app developer or publisher, and incompatibility or instability issues with your device or operating system. Therefore, you should use One Piece Bounty Rush mod apk unlimited diamond 40200 at your own discretion and responsibility. We hope this article has been helpful and informative for you. If you have any questions or feedback, please feel free to contact us. Thank you for reading and happy gaming!

-

FAQs

-

Here are some frequently asked questions about One Piece Bounty Rush mod apk unlimited diamond 40200:

-
    -
  1. Q: Is One Piece Bounty Rush mod apk unlimited diamond 40200 safe to use?
  2. -
  3. A: One Piece Bounty Rush mod apk unlimited diamond 40200 is not an official app from Bandai Namco Entertainment, so it may not be safe to use. It may contain malware or viruses that can harm your device or steal your data. It may also violate the terms of service or policies of the original app developer or publisher, which can result in a ban or suspension from the game service or platform. Therefore, you should use One Piece Bounty Rush mod apk unlimited diamond 40200 at your own risk and discretion.
  4. -
  5. Q: How can I get One Piece Bounty Rush mod apk unlimited diamond 40200?
  6. -
  7. A: You can get One Piece Bounty Rush mod apk unlimited diamond 40200 by following the steps mentioned in this article. You need to uninstall the original app, download the mod apk file from a trusted website, enable the installation of apps from unknown sources, install the mod apk file, and launch the app.
  8. -
  9. Q: What are the advantages of using One Piece Bounty Rush mod apk unlimited diamond 40200?
  10. -
  11. A: The advantages of using One Piece Bounty Rush mod apk unlimited diamond 40200 are that it gives you unlimited access to diamonds, which are used to summon new characters, upgrade skills, buy medals, and more. It also allows you to access all the characters in the game, regardless of their rarity or availability. Moreover, it enables you to play the game offline, without requiring an internet connection.
  12. -
  13. Q: What are the disadvantages of using One Piece Bounty Rush mod apk unlimited diamond 40200?
  14. -
  15. A: The disadvantages of using One Piece Bounty Rush mod apk unlimited diamond 40200 are that it may not be safe to use, as it may contain malware or viruses that can harm your device or steal your data. It may also violate the terms of service or policies of the original app developer or publisher, which can result in a ban or suspension from the game service or platform. Furthermore, it may not be updated or supported by the original app developer or publisher, and it may have compatibility or stability issues with your device or operating system.
  16. -
  17. Q: Can I use One Piece Bounty Rush mod apk unlimited diamond 40200 with my existing account?
  18. -
  19. A: You can use One Piece Bounty Rush mod apk unlimited diamond 40200 with your existing account, but you should backup your data before uninstalling the original app, as you may lose your progress or account information if you switch to the mod apk. You should also be careful not to log in with your account on multiple devices at the same time, as this may trigger a security alert and lead to a ban or suspension from the game service or platform.
  20. -

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/contluForse/HuggingGPT/assets/Capture One Pro 7 Crack Serial Codes [WORK].md b/spaces/contluForse/HuggingGPT/assets/Capture One Pro 7 Crack Serial Codes [WORK].md deleted file mode 100644 index fb5544286f75451698123950c4e4ecf327da7925..0000000000000000000000000000000000000000 --- a/spaces/contluForse/HuggingGPT/assets/Capture One Pro 7 Crack Serial Codes [WORK].md +++ /dev/null @@ -1,6 +0,0 @@ -

capture one pro 7 crack serial codes


Download Filehttps://ssurll.com/2uzvFa



- -Capture One Pro Crack has all the best image editing tools that helps you to compatibility for Panasonic LX Mark II and Leica D-LUX 7. 1fdad05405
-
-
-

diff --git a/spaces/contluForse/HuggingGPT/assets/Crochet 30 Beautiful Crochet Patterns For Beginners With Step-By-Step Instructions (Croche Guide).md b/spaces/contluForse/HuggingGPT/assets/Crochet 30 Beautiful Crochet Patterns For Beginners With Step-By-Step Instructions (Croche Guide).md deleted file mode 100644 index 9d589fb82ef614721271e16b61e1cb88e0f3035c..0000000000000000000000000000000000000000 --- a/spaces/contluForse/HuggingGPT/assets/Crochet 30 Beautiful Crochet Patterns For Beginners With Step-By-Step Instructions (Croche Guide).md +++ /dev/null @@ -1,26 +0,0 @@ - -

Do you want to learn how to crochet? Are you a beginner looking for easy crochet patterns? If so, you have come to the right place! In this blog post, we will share 25 free and easy crochet patterns that are perfect for beginners. These patterns are simple and easy to follow, and they range in difficulty level from beginner to intermediate. So whether you are a newbie crocheter or someone who is just looking for some new and easy patterns, we have got you covered!

-

The first thing a beginner should crochet is a simple scarf or another small rectangular project. These projects are a great way to practice your crocheting skills and try out new stitches and techniques.

-

Crochet: 30 Beautiful Crochet Patterns For Beginners: All Of My Crochet Projects In One Book (Croche


Download ○○○ https://ssurll.com/2uzxlz



-

Crochet coasters are one of the smallest projects on this list, so they're perfect for total beginners who are just learning how to crochet. This tutorial will teach you how to make crochet coasters in two styles: square and round.

-

I am new to crocheting and i am going crazy over it i even i want to make it a business, now there are patterns i am trying out every day like the cable stitch wow its bit hard for now but i will get there.Right now i am trying to make a bag for my project my fingers are crossed.

-

Hi8! I'm a newbie to crocheting & I love a lot of the beginners patterns especially the fingerless gloves! But I'm going to start my first project with the cute wash cloth pattern! Wish me luck I'm praying i catch on to crocheting I'm so excited

-

That is a beautiful blanket! I too crochet anytime, anywhere, but my favourite time is probably on a cold dark winter evening after all the chores are done and I can just relax and forget about everything else.
Nicola
NicolaKnits.com

-

I recommend anyone who is new to crochet to give this easy, chevron blanket pattern a try. While this is our most popular chevron pattern, we have other free blanket patterns using it too. This pattern is full of simple, single crochet stitches throughout and is the perfect beginner project.

-

I really enjoy this pattern, it is very simple. My grandmother taught me how to crochet a few weeks back, so I have been doing a lot of beginner projects. The blanket I am making using this pattern is by far my favorite one so far.

-

-

Designed by Lucy Croft, this design was originally published in installments in Simply Crochet magazine (2018-2019). Beginner friendly patterns to learn 12 crochet stitches and how to put the blanket together.

-

An instruction book from 1846 describes Shepherd or single crochet as what in current British usage is either called single crochet or slip-stitch crochet, with U.S. American terminology always using the latter (reserving single crochet for use as noted above).[12] It similarly equates "Double" and "French crochet".[13]

-

Notwithstanding the categorical assertion of a purely British origin, there is solid evidence of a connection between French tambour embroidery and crochet. French tambour embroidery was illustrated in detail in 1763 in Diderot's Encyclopedia. The tip of the needle shown there is indistinguishable from that of a present-day inline crochet hook and the chain stitch separated from a cloth support is a fundamental element of the latter technique. The 1823 Penélopé instructions unequivocally state that the tambour tool was used for crochet and the first of the 1840s instruction books uses the terms tambour and crochet as synonyms.[14] This equivalence is retained in the 4th edition of that work, 1847.[15]

-

The strong Victorian colours disappeared, though, and new publications called for white or pale threads, except for fancy purses, which were often crocheted of brightly colored silk and elaborately beaded. After World War I, far fewer crochet patterns were published, and most of them were simplified versions of the early 20th-century patterns.[citation needed] After World War II, from the late 1940s until the early 1960s, there was a resurgence in interest in home crafts, particularly in the United States, with many new and imaginative crochet designs published for colorful doilies, potholders, and other home items, along with updates of earlier publications. These patterns called for thicker threads and yarns than in earlier patterns and included variegated colors. The craft remained primarily a homemaker's art until the late 1960s and early 1970s, when the new generation picked up on crochet and popularized granny squares, a motif worked in the round and incorporating bright colors.

-

Although crochet underwent a subsequent decline in popularity, the early 21st century has seen a revival of interest in handcrafts and DIY, as well as improvement of the quality and varieties of yarn. As well as books and classes, there are YouTube tutorials and tiktok videos to help people who may need a clearer explanation to learn how to crochet.[20]

-

Crochet has experienced a revival on the catwalk as well. Christopher Kane's Fall 2011 Ready-to-Wear collection[21] makes intensive use of the granny square, one of the most basic of crochet motifs. In addition, crochet has been utilized many times by designers on the reality show Project Runway.[citation needed] Websites such as Etsy and Ravelry have made it easier for individual hobbyists to sell and distribute their patterns or projects across the internet.

-

Basic materials required for crochet are a hook and some type of material that will be crocheted, most commonly yarn or thread. Yarn, one of the most commonly used materials for crocheting, has varying weights which need to be taken into consideration when following patterns. Acrylic can also be used when crocheting, as it is synthetic and an alternative for wool. Additional tools are convenient for making related accessories. Examples of such tools include cardboard cutouts, which can be used to make tassels, fringe, and many other items; a pom-pom circle, used to make pom-poms; a tape measure and a gauge measure, both used for measuring crocheted work and counting stitches; a row counter; and occasionally plastic rings, which are used for special projects.In recent years, yarn selections have moved beyond synthetic and plant and animal-based fibers to include bamboo, qiviut, hemp, and banana stalks, to name a few. Many advanced crocheters have also incorporated recycled materials into their work in an effort to "go green" and experiment with new textures by using items such as plastic bags, old t-shirts or sheets, VCR or Cassette tape, and ribbon.

-

In the English-speaking crochet world, basic stitches have different names that vary by country. The differences are usually referred to as UK/US or British/American. Crochet is traditionally worked off a written pattern in which stitches and placement are communicated using textual abbreviations.[24] To help counter confusion when reading patterns, a diagramming system using a standard international notation has come into use (illustration, left). In the United States, crochet terminology and sizing guidelines, as well as standards for yarn and hook labeling, are primarily regulated by the Craft Yarn Council.[25]

-

Round or cylindrical patterns are simple to produce with a regular crochet hook, but cylindrical knitting requires either a set of circular needles or three to five special double-ended needles. Many crocheted items are composed of individual motifs which are then joined, either by sewing or crocheting, whereas knitting is usually composed of one fabric, such as entrelac.

-

There are a small number of architects currently interested in the subject of crochet as it relates to architecture. The following publications, explorations and thesis projects can be used as a resource to see how crochet is being used within the capacity of architecture.

-

"Love your patterns own so many of them, consistently well written and easy to follow, book is beautiful and i am happy to pay more as well worth it. Keep designing and we will keep buying."
- Maree B.

-

Hi question, pretty new to crochet .. still learning to reading patterns. *Sc twice in next st, sc in next st. Repeat from * 5 times. (18)
Do you mean 5 more times meaning there would be 6? If I repeat what is in the ** I would end up with more then 18?!? I confused?? TIA

-

Do you see any that strike a chord or really inspire you? Save them to your Pinterest board. Over time you can create various Pinterest boards dedicated to crochet e.g. Crochet Tutorials, Crochet blankets, Crochet hats, pink crochet projects, etc. You will most likely refer back to these pins for months or years in the future!

aaccfb2cb3
-
-
\ No newline at end of file diff --git a/spaces/contluForse/HuggingGPT/assets/Dell Portable Bios And Diags Rev A34 How to Reset Service Tag and Troubleshoot Hardware Issues.md b/spaces/contluForse/HuggingGPT/assets/Dell Portable Bios And Diags Rev A34 How to Reset Service Tag and Troubleshoot Hardware Issues.md deleted file mode 100644 index e1d09feee300f638e4c7b7d29d6f31ac0d19ce27..0000000000000000000000000000000000000000 --- a/spaces/contluForse/HuggingGPT/assets/Dell Portable Bios And Diags Rev A34 How to Reset Service Tag and Troubleshoot Hardware Issues.md +++ /dev/null @@ -1,6 +0,0 @@ -

Dell Portable Bios And Diags Rev A34 geburtstaggedichte k


Download Ziphttps://ssurll.com/2uzyWK



-
- aaccfb2cb3
-
-
-

diff --git a/spaces/contluForse/HuggingGPT/assets/ESET NOD32 Antivirus 4.0.314 FULL licencia hasta 2050 utorrent Protect your PC with the latest version of ESET.md b/spaces/contluForse/HuggingGPT/assets/ESET NOD32 Antivirus 4.0.314 FULL licencia hasta 2050 utorrent Protect your PC with the latest version of ESET.md deleted file mode 100644 index bf71995f530ecec6abbd74024634e5c3f9241270..0000000000000000000000000000000000000000 --- a/spaces/contluForse/HuggingGPT/assets/ESET NOD32 Antivirus 4.0.314 FULL licencia hasta 2050 utorrent Protect your PC with the latest version of ESET.md +++ /dev/null @@ -1,6 +0,0 @@ -

ESET NOD32 Antivirus 4.0.314 FULL licencia hasta 2050 utorrent


Download 🗸 https://ssurll.com/2uzxcK



- - aaccfb2cb3
-
-
-

diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/evaluation/fast_eval_api.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/evaluation/fast_eval_api.py deleted file mode 100644 index 75458b1cf8c26500da9b6e60cb6224a3c26d6dd2..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/evaluation/fast_eval_api.py +++ /dev/null @@ -1,121 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import copy -import logging -import numpy as np -import time -from pycocotools.cocoeval import COCOeval - -from annotator.oneformer.detectron2 import _C - -logger = logging.getLogger(__name__) - - -class COCOeval_opt(COCOeval): - """ - This is a slightly modified version of the original COCO API, where the functions evaluateImg() - and accumulate() are implemented in C++ to speedup evaluation - """ - - def evaluate(self): - """ - Run per image evaluation on given images and store results in self.evalImgs_cpp, a - datastructure that isn't readable from Python but is used by a c++ implementation of - accumulate(). Unlike the original COCO PythonAPI, we don't populate the datastructure - self.evalImgs because this datastructure is a computational bottleneck. - :return: None - """ - tic = time.time() - - p = self.params - # add backward compatibility if useSegm is specified in params - if p.useSegm is not None: - p.iouType = "segm" if p.useSegm == 1 else "bbox" - logger.info("Evaluate annotation type *{}*".format(p.iouType)) - p.imgIds = list(np.unique(p.imgIds)) - if p.useCats: - p.catIds = list(np.unique(p.catIds)) - p.maxDets = sorted(p.maxDets) - self.params = p - - self._prepare() # bottleneck - - # loop through images, area range, max detection number - catIds = p.catIds if p.useCats else [-1] - - if p.iouType == "segm" or p.iouType == "bbox": - computeIoU = self.computeIoU - elif p.iouType == "keypoints": - computeIoU = self.computeOks - self.ious = { - (imgId, catId): computeIoU(imgId, catId) for imgId in p.imgIds for catId in catIds - } # bottleneck - - maxDet = p.maxDets[-1] - - # <<<< Beginning of code differences with original COCO API - def convert_instances_to_cpp(instances, is_det=False): - # Convert annotations for a list of instances in an image to a format that's fast - # to access in C++ - instances_cpp = [] - for instance in instances: - instance_cpp = _C.InstanceAnnotation( - int(instance["id"]), - instance["score"] if is_det else instance.get("score", 0.0), - instance["area"], - bool(instance.get("iscrowd", 0)), - bool(instance.get("ignore", 0)), - ) - instances_cpp.append(instance_cpp) - return instances_cpp - - # Convert GT annotations, detections, and IOUs to a format that's fast to access in C++ - ground_truth_instances = [ - [convert_instances_to_cpp(self._gts[imgId, catId]) for catId in p.catIds] - for imgId in p.imgIds - ] - detected_instances = [ - [convert_instances_to_cpp(self._dts[imgId, catId], is_det=True) for catId in p.catIds] - for imgId in p.imgIds - ] - ious = [[self.ious[imgId, catId] for catId in catIds] for imgId in p.imgIds] - - if not p.useCats: - # For each image, flatten per-category lists into a single list - ground_truth_instances = [[[o for c in i for o in c]] for i in ground_truth_instances] - detected_instances = [[[o for c in i for o in c]] for i in detected_instances] - - # Call C++ implementation of self.evaluateImgs() - self._evalImgs_cpp = _C.COCOevalEvaluateImages( - p.areaRng, maxDet, p.iouThrs, ious, ground_truth_instances, detected_instances - ) - self._evalImgs = None - - self._paramsEval = copy.deepcopy(self.params) - toc = time.time() - logger.info("COCOeval_opt.evaluate() finished in {:0.2f} seconds.".format(toc - tic)) - # >>>> End of code differences with original COCO API - - def accumulate(self): - """ - Accumulate per image evaluation results and store the result in self.eval. Does not - support changing parameter settings from those used by self.evaluate() - """ - logger.info("Accumulating evaluation results...") - tic = time.time() - assert hasattr( - self, "_evalImgs_cpp" - ), "evaluate() must be called before accmulate() is called." - - self.eval = _C.COCOevalAccumulate(self._paramsEval, self._evalImgs_cpp) - - # recall is num_iou_thresholds X num_categories X num_area_ranges X num_max_detections - self.eval["recall"] = np.array(self.eval["recall"]).reshape( - self.eval["counts"][:1] + self.eval["counts"][2:] - ) - - # precision and scores are num_iou_thresholds X num_recall_thresholds X num_categories X - # num_area_ranges X num_max_detections - self.eval["precision"] = np.array(self.eval["precision"]).reshape(self.eval["counts"]) - self.eval["scores"] = np.array(self.eval["scores"]).reshape(self.eval["counts"]) - toc = time.time() - logger.info("COCOeval_opt.accumulate() finished in {:0.2f} seconds.".format(toc - tic)) diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/modeling/meta_arch/rcnn.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/modeling/meta_arch/rcnn.py deleted file mode 100644 index 7cacf065ed2803686f80c8e6f562ebfeb5d584d5..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/modeling/meta_arch/rcnn.py +++ /dev/null @@ -1,341 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import logging -import numpy as np -from typing import Dict, List, Optional, Tuple -import torch -from torch import nn - -from annotator.oneformer.detectron2.config import configurable -from annotator.oneformer.detectron2.data.detection_utils import convert_image_to_rgb -from annotator.oneformer.detectron2.layers import move_device_like -from annotator.oneformer.detectron2.structures import ImageList, Instances -from annotator.oneformer.detectron2.utils.events import get_event_storage -from annotator.oneformer.detectron2.utils.logger import log_first_n - -from ..backbone import Backbone, build_backbone -from ..postprocessing import detector_postprocess -from ..proposal_generator import build_proposal_generator -from ..roi_heads import build_roi_heads -from .build import META_ARCH_REGISTRY - -__all__ = ["GeneralizedRCNN", "ProposalNetwork"] - - -@META_ARCH_REGISTRY.register() -class GeneralizedRCNN(nn.Module): - """ - Generalized R-CNN. Any models that contains the following three components: - 1. Per-image feature extraction (aka backbone) - 2. Region proposal generation - 3. Per-region feature extraction and prediction - """ - - @configurable - def __init__( - self, - *, - backbone: Backbone, - proposal_generator: nn.Module, - roi_heads: nn.Module, - pixel_mean: Tuple[float], - pixel_std: Tuple[float], - input_format: Optional[str] = None, - vis_period: int = 0, - ): - """ - Args: - backbone: a backbone module, must follow detectron2's backbone interface - proposal_generator: a module that generates proposals using backbone features - roi_heads: a ROI head that performs per-region computation - pixel_mean, pixel_std: list or tuple with #channels element, representing - the per-channel mean and std to be used to normalize the input image - input_format: describe the meaning of channels of input. Needed by visualization - vis_period: the period to run visualization. Set to 0 to disable. - """ - super().__init__() - self.backbone = backbone - self.proposal_generator = proposal_generator - self.roi_heads = roi_heads - - self.input_format = input_format - self.vis_period = vis_period - if vis_period > 0: - assert input_format is not None, "input_format is required for visualization!" - - self.register_buffer("pixel_mean", torch.tensor(pixel_mean).view(-1, 1, 1), False) - self.register_buffer("pixel_std", torch.tensor(pixel_std).view(-1, 1, 1), False) - assert ( - self.pixel_mean.shape == self.pixel_std.shape - ), f"{self.pixel_mean} and {self.pixel_std} have different shapes!" - - @classmethod - def from_config(cls, cfg): - backbone = build_backbone(cfg) - return { - "backbone": backbone, - "proposal_generator": build_proposal_generator(cfg, backbone.output_shape()), - "roi_heads": build_roi_heads(cfg, backbone.output_shape()), - "input_format": cfg.INPUT.FORMAT, - "vis_period": cfg.VIS_PERIOD, - "pixel_mean": cfg.MODEL.PIXEL_MEAN, - "pixel_std": cfg.MODEL.PIXEL_STD, - } - - @property - def device(self): - return self.pixel_mean.device - - def _move_to_current_device(self, x): - return move_device_like(x, self.pixel_mean) - - def visualize_training(self, batched_inputs, proposals): - """ - A function used to visualize images and proposals. It shows ground truth - bounding boxes on the original image and up to 20 top-scoring predicted - object proposals on the original image. Users can implement different - visualization functions for different models. - - Args: - batched_inputs (list): a list that contains input to the model. - proposals (list): a list that contains predicted proposals. Both - batched_inputs and proposals should have the same length. - """ - from annotator.oneformer.detectron2.utils.visualizer import Visualizer - - storage = get_event_storage() - max_vis_prop = 20 - - for input, prop in zip(batched_inputs, proposals): - img = input["image"] - img = convert_image_to_rgb(img.permute(1, 2, 0), self.input_format) - v_gt = Visualizer(img, None) - v_gt = v_gt.overlay_instances(boxes=input["instances"].gt_boxes) - anno_img = v_gt.get_image() - box_size = min(len(prop.proposal_boxes), max_vis_prop) - v_pred = Visualizer(img, None) - v_pred = v_pred.overlay_instances( - boxes=prop.proposal_boxes[0:box_size].tensor.cpu().numpy() - ) - prop_img = v_pred.get_image() - vis_img = np.concatenate((anno_img, prop_img), axis=1) - vis_img = vis_img.transpose(2, 0, 1) - vis_name = "Left: GT bounding boxes; Right: Predicted proposals" - storage.put_image(vis_name, vis_img) - break # only visualize one image in a batch - - def forward(self, batched_inputs: List[Dict[str, torch.Tensor]]): - """ - Args: - batched_inputs: a list, batched outputs of :class:`DatasetMapper` . - Each item in the list contains the inputs for one image. - For now, each item in the list is a dict that contains: - - * image: Tensor, image in (C, H, W) format. - * instances (optional): groundtruth :class:`Instances` - * proposals (optional): :class:`Instances`, precomputed proposals. - - Other information that's included in the original dicts, such as: - - * "height", "width" (int): the output resolution of the model, used in inference. - See :meth:`postprocess` for details. - - Returns: - list[dict]: - Each dict is the output for one input image. - The dict contains one key "instances" whose value is a :class:`Instances`. - The :class:`Instances` object has the following keys: - "pred_boxes", "pred_classes", "scores", "pred_masks", "pred_keypoints" - """ - if not self.training: - return self.inference(batched_inputs) - - images = self.preprocess_image(batched_inputs) - if "instances" in batched_inputs[0]: - gt_instances = [x["instances"].to(self.device) for x in batched_inputs] - else: - gt_instances = None - - features = self.backbone(images.tensor) - - if self.proposal_generator is not None: - proposals, proposal_losses = self.proposal_generator(images, features, gt_instances) - else: - assert "proposals" in batched_inputs[0] - proposals = [x["proposals"].to(self.device) for x in batched_inputs] - proposal_losses = {} - - _, detector_losses = self.roi_heads(images, features, proposals, gt_instances) - if self.vis_period > 0: - storage = get_event_storage() - if storage.iter % self.vis_period == 0: - self.visualize_training(batched_inputs, proposals) - - losses = {} - losses.update(detector_losses) - losses.update(proposal_losses) - return losses - - def inference( - self, - batched_inputs: List[Dict[str, torch.Tensor]], - detected_instances: Optional[List[Instances]] = None, - do_postprocess: bool = True, - ): - """ - Run inference on the given inputs. - - Args: - batched_inputs (list[dict]): same as in :meth:`forward` - detected_instances (None or list[Instances]): if not None, it - contains an `Instances` object per image. The `Instances` - object contains "pred_boxes" and "pred_classes" which are - known boxes in the image. - The inference will then skip the detection of bounding boxes, - and only predict other per-ROI outputs. - do_postprocess (bool): whether to apply post-processing on the outputs. - - Returns: - When do_postprocess=True, same as in :meth:`forward`. - Otherwise, a list[Instances] containing raw network outputs. - """ - assert not self.training - - images = self.preprocess_image(batched_inputs) - features = self.backbone(images.tensor) - - if detected_instances is None: - if self.proposal_generator is not None: - proposals, _ = self.proposal_generator(images, features, None) - else: - assert "proposals" in batched_inputs[0] - proposals = [x["proposals"].to(self.device) for x in batched_inputs] - - results, _ = self.roi_heads(images, features, proposals, None) - else: - detected_instances = [x.to(self.device) for x in detected_instances] - results = self.roi_heads.forward_with_given_boxes(features, detected_instances) - - if do_postprocess: - assert not torch.jit.is_scripting(), "Scripting is not supported for postprocess." - return GeneralizedRCNN._postprocess(results, batched_inputs, images.image_sizes) - return results - - def preprocess_image(self, batched_inputs: List[Dict[str, torch.Tensor]]): - """ - Normalize, pad and batch the input images. - """ - images = [self._move_to_current_device(x["image"]) for x in batched_inputs] - images = [(x - self.pixel_mean) / self.pixel_std for x in images] - images = ImageList.from_tensors( - images, - self.backbone.size_divisibility, - padding_constraints=self.backbone.padding_constraints, - ) - return images - - @staticmethod - def _postprocess(instances, batched_inputs: List[Dict[str, torch.Tensor]], image_sizes): - """ - Rescale the output instances to the target size. - """ - # note: private function; subject to changes - processed_results = [] - for results_per_image, input_per_image, image_size in zip( - instances, batched_inputs, image_sizes - ): - height = input_per_image.get("height", image_size[0]) - width = input_per_image.get("width", image_size[1]) - r = detector_postprocess(results_per_image, height, width) - processed_results.append({"instances": r}) - return processed_results - - -@META_ARCH_REGISTRY.register() -class ProposalNetwork(nn.Module): - """ - A meta architecture that only predicts object proposals. - """ - - @configurable - def __init__( - self, - *, - backbone: Backbone, - proposal_generator: nn.Module, - pixel_mean: Tuple[float], - pixel_std: Tuple[float], - ): - """ - Args: - backbone: a backbone module, must follow detectron2's backbone interface - proposal_generator: a module that generates proposals using backbone features - pixel_mean, pixel_std: list or tuple with #channels element, representing - the per-channel mean and std to be used to normalize the input image - """ - super().__init__() - self.backbone = backbone - self.proposal_generator = proposal_generator - self.register_buffer("pixel_mean", torch.tensor(pixel_mean).view(-1, 1, 1), False) - self.register_buffer("pixel_std", torch.tensor(pixel_std).view(-1, 1, 1), False) - - @classmethod - def from_config(cls, cfg): - backbone = build_backbone(cfg) - return { - "backbone": backbone, - "proposal_generator": build_proposal_generator(cfg, backbone.output_shape()), - "pixel_mean": cfg.MODEL.PIXEL_MEAN, - "pixel_std": cfg.MODEL.PIXEL_STD, - } - - @property - def device(self): - return self.pixel_mean.device - - def _move_to_current_device(self, x): - return move_device_like(x, self.pixel_mean) - - def forward(self, batched_inputs): - """ - Args: - Same as in :class:`GeneralizedRCNN.forward` - - Returns: - list[dict]: - Each dict is the output for one input image. - The dict contains one key "proposals" whose value is a - :class:`Instances` with keys "proposal_boxes" and "objectness_logits". - """ - images = [self._move_to_current_device(x["image"]) for x in batched_inputs] - images = [(x - self.pixel_mean) / self.pixel_std for x in images] - images = ImageList.from_tensors( - images, - self.backbone.size_divisibility, - padding_constraints=self.backbone.padding_constraints, - ) - features = self.backbone(images.tensor) - - if "instances" in batched_inputs[0]: - gt_instances = [x["instances"].to(self.device) for x in batched_inputs] - elif "targets" in batched_inputs[0]: - log_first_n( - logging.WARN, "'targets' in the model inputs is now renamed to 'instances'!", n=10 - ) - gt_instances = [x["targets"].to(self.device) for x in batched_inputs] - else: - gt_instances = None - proposals, proposal_losses = self.proposal_generator(images, features, gt_instances) - # In training, the proposals are not useful at all but we generate them anyway. - # This makes RPN-only models about 5% slower. - if self.training: - return proposal_losses - - processed_results = [] - for results_per_image, input_per_image, image_size in zip( - proposals, batched_inputs, images.image_sizes - ): - height = input_per_image.get("height", image_size[0]) - width = input_per_image.get("width", image_size[1]) - r = detector_postprocess(results_per_image, height, width) - processed_results.append({"proposals": r}) - return processed_results diff --git a/spaces/crashedice/signify/signify/core.py b/spaces/crashedice/signify/signify/core.py deleted file mode 100644 index 6552cc5da9d5ec82c8562804039b51283739ae48..0000000000000000000000000000000000000000 --- a/spaces/crashedice/signify/signify/core.py +++ /dev/null @@ -1,7 +0,0 @@ -# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_core.ipynb. - -# %% auto 0 -__all__ = ['foo'] - -# %% ../nbs/00_core.ipynb 3 -def foo(): pass diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/PIL/PdfParser.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/PIL/PdfParser.py deleted file mode 100644 index dc1012f54d3d0d683e96fed41ee7ace492904e71..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/PIL/PdfParser.py +++ /dev/null @@ -1,996 +0,0 @@ -import calendar -import codecs -import collections -import mmap -import os -import re -import time -import zlib - - -# see 7.9.2.2 Text String Type on page 86 and D.3 PDFDocEncoding Character Set -# on page 656 -def encode_text(s): - return codecs.BOM_UTF16_BE + s.encode("utf_16_be") - - -PDFDocEncoding = { - 0x16: "\u0017", - 0x18: "\u02D8", - 0x19: "\u02C7", - 0x1A: "\u02C6", - 0x1B: "\u02D9", - 0x1C: "\u02DD", - 0x1D: "\u02DB", - 0x1E: "\u02DA", - 0x1F: "\u02DC", - 0x80: "\u2022", - 0x81: "\u2020", - 0x82: "\u2021", - 0x83: "\u2026", - 0x84: "\u2014", - 0x85: "\u2013", - 0x86: "\u0192", - 0x87: "\u2044", - 0x88: "\u2039", - 0x89: "\u203A", - 0x8A: "\u2212", - 0x8B: "\u2030", - 0x8C: "\u201E", - 0x8D: "\u201C", - 0x8E: "\u201D", - 0x8F: "\u2018", - 0x90: "\u2019", - 0x91: "\u201A", - 0x92: "\u2122", - 0x93: "\uFB01", - 0x94: "\uFB02", - 0x95: "\u0141", - 0x96: "\u0152", - 0x97: "\u0160", - 0x98: "\u0178", - 0x99: "\u017D", - 0x9A: "\u0131", - 0x9B: "\u0142", - 0x9C: "\u0153", - 0x9D: "\u0161", - 0x9E: "\u017E", - 0xA0: "\u20AC", -} - - -def decode_text(b): - if b[: len(codecs.BOM_UTF16_BE)] == codecs.BOM_UTF16_BE: - return b[len(codecs.BOM_UTF16_BE) :].decode("utf_16_be") - else: - return "".join(PDFDocEncoding.get(byte, chr(byte)) for byte in b) - - -class PdfFormatError(RuntimeError): - """An error that probably indicates a syntactic or semantic error in the - PDF file structure""" - - pass - - -def check_format_condition(condition, error_message): - if not condition: - raise PdfFormatError(error_message) - - -class IndirectReference( - collections.namedtuple("IndirectReferenceTuple", ["object_id", "generation"]) -): - def __str__(self): - return "%s %s R" % self - - def __bytes__(self): - return self.__str__().encode("us-ascii") - - def __eq__(self, other): - return ( - other.__class__ is self.__class__ - and other.object_id == self.object_id - and other.generation == self.generation - ) - - def __ne__(self, other): - return not (self == other) - - def __hash__(self): - return hash((self.object_id, self.generation)) - - -class IndirectObjectDef(IndirectReference): - def __str__(self): - return "%s %s obj" % self - - -class XrefTable: - def __init__(self): - self.existing_entries = {} # object ID => (offset, generation) - self.new_entries = {} # object ID => (offset, generation) - self.deleted_entries = {0: 65536} # object ID => generation - self.reading_finished = False - - def __setitem__(self, key, value): - if self.reading_finished: - self.new_entries[key] = value - else: - self.existing_entries[key] = value - if key in self.deleted_entries: - del self.deleted_entries[key] - - def __getitem__(self, key): - try: - return self.new_entries[key] - except KeyError: - return self.existing_entries[key] - - def __delitem__(self, key): - if key in self.new_entries: - generation = self.new_entries[key][1] + 1 - del self.new_entries[key] - self.deleted_entries[key] = generation - elif key in self.existing_entries: - generation = self.existing_entries[key][1] + 1 - self.deleted_entries[key] = generation - elif key in self.deleted_entries: - generation = self.deleted_entries[key] - else: - msg = ( - "object ID " + str(key) + " cannot be deleted because it doesn't exist" - ) - raise IndexError(msg) - - def __contains__(self, key): - return key in self.existing_entries or key in self.new_entries - - def __len__(self): - return len( - set(self.existing_entries.keys()) - | set(self.new_entries.keys()) - | set(self.deleted_entries.keys()) - ) - - def keys(self): - return ( - set(self.existing_entries.keys()) - set(self.deleted_entries.keys()) - ) | set(self.new_entries.keys()) - - def write(self, f): - keys = sorted(set(self.new_entries.keys()) | set(self.deleted_entries.keys())) - deleted_keys = sorted(set(self.deleted_entries.keys())) - startxref = f.tell() - f.write(b"xref\n") - while keys: - # find a contiguous sequence of object IDs - prev = None - for index, key in enumerate(keys): - if prev is None or prev + 1 == key: - prev = key - else: - contiguous_keys = keys[:index] - keys = keys[index:] - break - else: - contiguous_keys = keys - keys = None - f.write(b"%d %d\n" % (contiguous_keys[0], len(contiguous_keys))) - for object_id in contiguous_keys: - if object_id in self.new_entries: - f.write(b"%010d %05d n \n" % self.new_entries[object_id]) - else: - this_deleted_object_id = deleted_keys.pop(0) - check_format_condition( - object_id == this_deleted_object_id, - f"expected the next deleted object ID to be {object_id}, " - f"instead found {this_deleted_object_id}", - ) - try: - next_in_linked_list = deleted_keys[0] - except IndexError: - next_in_linked_list = 0 - f.write( - b"%010d %05d f \n" - % (next_in_linked_list, self.deleted_entries[object_id]) - ) - return startxref - - -class PdfName: - def __init__(self, name): - if isinstance(name, PdfName): - self.name = name.name - elif isinstance(name, bytes): - self.name = name - else: - self.name = name.encode("us-ascii") - - def name_as_str(self): - return self.name.decode("us-ascii") - - def __eq__(self, other): - return ( - isinstance(other, PdfName) and other.name == self.name - ) or other == self.name - - def __hash__(self): - return hash(self.name) - - def __repr__(self): - return f"PdfName({repr(self.name)})" - - @classmethod - def from_pdf_stream(cls, data): - return cls(PdfParser.interpret_name(data)) - - allowed_chars = set(range(33, 127)) - {ord(c) for c in "#%/()<>[]{}"} - - def __bytes__(self): - result = bytearray(b"/") - for b in self.name: - if b in self.allowed_chars: - result.append(b) - else: - result.extend(b"#%02X" % b) - return bytes(result) - - -class PdfArray(list): - def __bytes__(self): - return b"[ " + b" ".join(pdf_repr(x) for x in self) + b" ]" - - -class PdfDict(collections.UserDict): - def __setattr__(self, key, value): - if key == "data": - collections.UserDict.__setattr__(self, key, value) - else: - self[key.encode("us-ascii")] = value - - def __getattr__(self, key): - try: - value = self[key.encode("us-ascii")] - except KeyError as e: - raise AttributeError(key) from e - if isinstance(value, bytes): - value = decode_text(value) - if key.endswith("Date"): - if value.startswith("D:"): - value = value[2:] - - relationship = "Z" - if len(value) > 17: - relationship = value[14] - offset = int(value[15:17]) * 60 - if len(value) > 20: - offset += int(value[18:20]) - - format = "%Y%m%d%H%M%S"[: len(value) - 2] - value = time.strptime(value[: len(format) + 2], format) - if relationship in ["+", "-"]: - offset *= 60 - if relationship == "+": - offset *= -1 - value = time.gmtime(calendar.timegm(value) + offset) - return value - - def __bytes__(self): - out = bytearray(b"<<") - for key, value in self.items(): - if value is None: - continue - value = pdf_repr(value) - out.extend(b"\n") - out.extend(bytes(PdfName(key))) - out.extend(b" ") - out.extend(value) - out.extend(b"\n>>") - return bytes(out) - - -class PdfBinary: - def __init__(self, data): - self.data = data - - def __bytes__(self): - return b"<%s>" % b"".join(b"%02X" % b for b in self.data) - - -class PdfStream: - def __init__(self, dictionary, buf): - self.dictionary = dictionary - self.buf = buf - - def decode(self): - try: - filter = self.dictionary.Filter - except AttributeError: - return self.buf - if filter == b"FlateDecode": - try: - expected_length = self.dictionary.DL - except AttributeError: - expected_length = self.dictionary.Length - return zlib.decompress(self.buf, bufsize=int(expected_length)) - else: - msg = f"stream filter {repr(self.dictionary.Filter)} unknown/unsupported" - raise NotImplementedError(msg) - - -def pdf_repr(x): - if x is True: - return b"true" - elif x is False: - return b"false" - elif x is None: - return b"null" - elif isinstance(x, (PdfName, PdfDict, PdfArray, PdfBinary)): - return bytes(x) - elif isinstance(x, (int, float)): - return str(x).encode("us-ascii") - elif isinstance(x, time.struct_time): - return b"(D:" + time.strftime("%Y%m%d%H%M%SZ", x).encode("us-ascii") + b")" - elif isinstance(x, dict): - return bytes(PdfDict(x)) - elif isinstance(x, list): - return bytes(PdfArray(x)) - elif isinstance(x, str): - return pdf_repr(encode_text(x)) - elif isinstance(x, bytes): - # XXX escape more chars? handle binary garbage - x = x.replace(b"\\", b"\\\\") - x = x.replace(b"(", b"\\(") - x = x.replace(b")", b"\\)") - return b"(" + x + b")" - else: - return bytes(x) - - -class PdfParser: - """Based on - https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf - Supports PDF up to 1.4 - """ - - def __init__(self, filename=None, f=None, buf=None, start_offset=0, mode="rb"): - if buf and f: - msg = "specify buf or f or filename, but not both buf and f" - raise RuntimeError(msg) - self.filename = filename - self.buf = buf - self.f = f - self.start_offset = start_offset - self.should_close_buf = False - self.should_close_file = False - if filename is not None and f is None: - self.f = f = open(filename, mode) - self.should_close_file = True - if f is not None: - self.buf = buf = self.get_buf_from_file(f) - self.should_close_buf = True - if not filename and hasattr(f, "name"): - self.filename = f.name - self.cached_objects = {} - if buf: - self.read_pdf_info() - else: - self.file_size_total = self.file_size_this = 0 - self.root = PdfDict() - self.root_ref = None - self.info = PdfDict() - self.info_ref = None - self.page_tree_root = {} - self.pages = [] - self.orig_pages = [] - self.pages_ref = None - self.last_xref_section_offset = None - self.trailer_dict = {} - self.xref_table = XrefTable() - self.xref_table.reading_finished = True - if f: - self.seek_end() - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, traceback): - self.close() - return False # do not suppress exceptions - - def start_writing(self): - self.close_buf() - self.seek_end() - - def close_buf(self): - try: - self.buf.close() - except AttributeError: - pass - self.buf = None - - def close(self): - if self.should_close_buf: - self.close_buf() - if self.f is not None and self.should_close_file: - self.f.close() - self.f = None - - def seek_end(self): - self.f.seek(0, os.SEEK_END) - - def write_header(self): - self.f.write(b"%PDF-1.4\n") - - def write_comment(self, s): - self.f.write(f"% {s}\n".encode()) - - def write_catalog(self): - self.del_root() - self.root_ref = self.next_object_id(self.f.tell()) - self.pages_ref = self.next_object_id(0) - self.rewrite_pages() - self.write_obj(self.root_ref, Type=PdfName(b"Catalog"), Pages=self.pages_ref) - self.write_obj( - self.pages_ref, - Type=PdfName(b"Pages"), - Count=len(self.pages), - Kids=self.pages, - ) - return self.root_ref - - def rewrite_pages(self): - pages_tree_nodes_to_delete = [] - for i, page_ref in enumerate(self.orig_pages): - page_info = self.cached_objects[page_ref] - del self.xref_table[page_ref.object_id] - pages_tree_nodes_to_delete.append(page_info[PdfName(b"Parent")]) - if page_ref not in self.pages: - # the page has been deleted - continue - # make dict keys into strings for passing to write_page - stringified_page_info = {} - for key, value in page_info.items(): - # key should be a PdfName - stringified_page_info[key.name_as_str()] = value - stringified_page_info["Parent"] = self.pages_ref - new_page_ref = self.write_page(None, **stringified_page_info) - for j, cur_page_ref in enumerate(self.pages): - if cur_page_ref == page_ref: - # replace the page reference with the new one - self.pages[j] = new_page_ref - # delete redundant Pages tree nodes from xref table - for pages_tree_node_ref in pages_tree_nodes_to_delete: - while pages_tree_node_ref: - pages_tree_node = self.cached_objects[pages_tree_node_ref] - if pages_tree_node_ref.object_id in self.xref_table: - del self.xref_table[pages_tree_node_ref.object_id] - pages_tree_node_ref = pages_tree_node.get(b"Parent", None) - self.orig_pages = [] - - def write_xref_and_trailer(self, new_root_ref=None): - if new_root_ref: - self.del_root() - self.root_ref = new_root_ref - if self.info: - self.info_ref = self.write_obj(None, self.info) - start_xref = self.xref_table.write(self.f) - num_entries = len(self.xref_table) - trailer_dict = {b"Root": self.root_ref, b"Size": num_entries} - if self.last_xref_section_offset is not None: - trailer_dict[b"Prev"] = self.last_xref_section_offset - if self.info: - trailer_dict[b"Info"] = self.info_ref - self.last_xref_section_offset = start_xref - self.f.write( - b"trailer\n" - + bytes(PdfDict(trailer_dict)) - + b"\nstartxref\n%d\n%%%%EOF" % start_xref - ) - - def write_page(self, ref, *objs, **dict_obj): - if isinstance(ref, int): - ref = self.pages[ref] - if "Type" not in dict_obj: - dict_obj["Type"] = PdfName(b"Page") - if "Parent" not in dict_obj: - dict_obj["Parent"] = self.pages_ref - return self.write_obj(ref, *objs, **dict_obj) - - def write_obj(self, ref, *objs, **dict_obj): - f = self.f - if ref is None: - ref = self.next_object_id(f.tell()) - else: - self.xref_table[ref.object_id] = (f.tell(), ref.generation) - f.write(bytes(IndirectObjectDef(*ref))) - stream = dict_obj.pop("stream", None) - if stream is not None: - dict_obj["Length"] = len(stream) - if dict_obj: - f.write(pdf_repr(dict_obj)) - for obj in objs: - f.write(pdf_repr(obj)) - if stream is not None: - f.write(b"stream\n") - f.write(stream) - f.write(b"\nendstream\n") - f.write(b"endobj\n") - return ref - - def del_root(self): - if self.root_ref is None: - return - del self.xref_table[self.root_ref.object_id] - del self.xref_table[self.root[b"Pages"].object_id] - - @staticmethod - def get_buf_from_file(f): - if hasattr(f, "getbuffer"): - return f.getbuffer() - elif hasattr(f, "getvalue"): - return f.getvalue() - else: - try: - return mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) - except ValueError: # cannot mmap an empty file - return b"" - - def read_pdf_info(self): - self.file_size_total = len(self.buf) - self.file_size_this = self.file_size_total - self.start_offset - self.read_trailer() - self.root_ref = self.trailer_dict[b"Root"] - self.info_ref = self.trailer_dict.get(b"Info", None) - self.root = PdfDict(self.read_indirect(self.root_ref)) - if self.info_ref is None: - self.info = PdfDict() - else: - self.info = PdfDict(self.read_indirect(self.info_ref)) - check_format_condition(b"Type" in self.root, "/Type missing in Root") - check_format_condition( - self.root[b"Type"] == b"Catalog", "/Type in Root is not /Catalog" - ) - check_format_condition(b"Pages" in self.root, "/Pages missing in Root") - check_format_condition( - isinstance(self.root[b"Pages"], IndirectReference), - "/Pages in Root is not an indirect reference", - ) - self.pages_ref = self.root[b"Pages"] - self.page_tree_root = self.read_indirect(self.pages_ref) - self.pages = self.linearize_page_tree(self.page_tree_root) - # save the original list of page references - # in case the user modifies, adds or deletes some pages - # and we need to rewrite the pages and their list - self.orig_pages = self.pages[:] - - def next_object_id(self, offset=None): - try: - # TODO: support reuse of deleted objects - reference = IndirectReference(max(self.xref_table.keys()) + 1, 0) - except ValueError: - reference = IndirectReference(1, 0) - if offset is not None: - self.xref_table[reference.object_id] = (offset, 0) - return reference - - delimiter = rb"[][()<>{}/%]" - delimiter_or_ws = rb"[][()<>{}/%\000\011\012\014\015\040]" - whitespace = rb"[\000\011\012\014\015\040]" - whitespace_or_hex = rb"[\000\011\012\014\015\0400-9a-fA-F]" - whitespace_optional = whitespace + b"*" - whitespace_mandatory = whitespace + b"+" - # No "\012" aka "\n" or "\015" aka "\r": - whitespace_optional_no_nl = rb"[\000\011\014\040]*" - newline_only = rb"[\r\n]+" - newline = whitespace_optional_no_nl + newline_only + whitespace_optional_no_nl - re_trailer_end = re.compile( - whitespace_mandatory - + rb"trailer" - + whitespace_optional - + rb"<<(.*>>)" - + newline - + rb"startxref" - + newline - + rb"([0-9]+)" - + newline - + rb"%%EOF" - + whitespace_optional - + rb"$", - re.DOTALL, - ) - re_trailer_prev = re.compile( - whitespace_optional - + rb"trailer" - + whitespace_optional - + rb"<<(.*?>>)" - + newline - + rb"startxref" - + newline - + rb"([0-9]+)" - + newline - + rb"%%EOF" - + whitespace_optional, - re.DOTALL, - ) - - def read_trailer(self): - search_start_offset = len(self.buf) - 16384 - if search_start_offset < self.start_offset: - search_start_offset = self.start_offset - m = self.re_trailer_end.search(self.buf, search_start_offset) - check_format_condition(m, "trailer end not found") - # make sure we found the LAST trailer - last_match = m - while m: - last_match = m - m = self.re_trailer_end.search(self.buf, m.start() + 16) - if not m: - m = last_match - trailer_data = m.group(1) - self.last_xref_section_offset = int(m.group(2)) - self.trailer_dict = self.interpret_trailer(trailer_data) - self.xref_table = XrefTable() - self.read_xref_table(xref_section_offset=self.last_xref_section_offset) - if b"Prev" in self.trailer_dict: - self.read_prev_trailer(self.trailer_dict[b"Prev"]) - - def read_prev_trailer(self, xref_section_offset): - trailer_offset = self.read_xref_table(xref_section_offset=xref_section_offset) - m = self.re_trailer_prev.search( - self.buf[trailer_offset : trailer_offset + 16384] - ) - check_format_condition(m, "previous trailer not found") - trailer_data = m.group(1) - check_format_condition( - int(m.group(2)) == xref_section_offset, - "xref section offset in previous trailer doesn't match what was expected", - ) - trailer_dict = self.interpret_trailer(trailer_data) - if b"Prev" in trailer_dict: - self.read_prev_trailer(trailer_dict[b"Prev"]) - - re_whitespace_optional = re.compile(whitespace_optional) - re_name = re.compile( - whitespace_optional - + rb"/([!-$&'*-.0-;=?-Z\\^-z|~]+)(?=" - + delimiter_or_ws - + rb")" - ) - re_dict_start = re.compile(whitespace_optional + rb"<<") - re_dict_end = re.compile(whitespace_optional + rb">>" + whitespace_optional) - - @classmethod - def interpret_trailer(cls, trailer_data): - trailer = {} - offset = 0 - while True: - m = cls.re_name.match(trailer_data, offset) - if not m: - m = cls.re_dict_end.match(trailer_data, offset) - check_format_condition( - m and m.end() == len(trailer_data), - "name not found in trailer, remaining data: " - + repr(trailer_data[offset:]), - ) - break - key = cls.interpret_name(m.group(1)) - value, offset = cls.get_value(trailer_data, m.end()) - trailer[key] = value - check_format_condition( - b"Size" in trailer and isinstance(trailer[b"Size"], int), - "/Size not in trailer or not an integer", - ) - check_format_condition( - b"Root" in trailer and isinstance(trailer[b"Root"], IndirectReference), - "/Root not in trailer or not an indirect reference", - ) - return trailer - - re_hashes_in_name = re.compile(rb"([^#]*)(#([0-9a-fA-F]{2}))?") - - @classmethod - def interpret_name(cls, raw, as_text=False): - name = b"" - for m in cls.re_hashes_in_name.finditer(raw): - if m.group(3): - name += m.group(1) + bytearray.fromhex(m.group(3).decode("us-ascii")) - else: - name += m.group(1) - if as_text: - return name.decode("utf-8") - else: - return bytes(name) - - re_null = re.compile(whitespace_optional + rb"null(?=" + delimiter_or_ws + rb")") - re_true = re.compile(whitespace_optional + rb"true(?=" + delimiter_or_ws + rb")") - re_false = re.compile(whitespace_optional + rb"false(?=" + delimiter_or_ws + rb")") - re_int = re.compile( - whitespace_optional + rb"([-+]?[0-9]+)(?=" + delimiter_or_ws + rb")" - ) - re_real = re.compile( - whitespace_optional - + rb"([-+]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+))(?=" - + delimiter_or_ws - + rb")" - ) - re_array_start = re.compile(whitespace_optional + rb"\[") - re_array_end = re.compile(whitespace_optional + rb"]") - re_string_hex = re.compile( - whitespace_optional + rb"<(" + whitespace_or_hex + rb"*)>" - ) - re_string_lit = re.compile(whitespace_optional + rb"\(") - re_indirect_reference = re.compile( - whitespace_optional - + rb"([-+]?[0-9]+)" - + whitespace_mandatory - + rb"([-+]?[0-9]+)" - + whitespace_mandatory - + rb"R(?=" - + delimiter_or_ws - + rb")" - ) - re_indirect_def_start = re.compile( - whitespace_optional - + rb"([-+]?[0-9]+)" - + whitespace_mandatory - + rb"([-+]?[0-9]+)" - + whitespace_mandatory - + rb"obj(?=" - + delimiter_or_ws - + rb")" - ) - re_indirect_def_end = re.compile( - whitespace_optional + rb"endobj(?=" + delimiter_or_ws + rb")" - ) - re_comment = re.compile( - rb"(" + whitespace_optional + rb"%[^\r\n]*" + newline + rb")*" - ) - re_stream_start = re.compile(whitespace_optional + rb"stream\r?\n") - re_stream_end = re.compile( - whitespace_optional + rb"endstream(?=" + delimiter_or_ws + rb")" - ) - - @classmethod - def get_value(cls, data, offset, expect_indirect=None, max_nesting=-1): - if max_nesting == 0: - return None, None - m = cls.re_comment.match(data, offset) - if m: - offset = m.end() - m = cls.re_indirect_def_start.match(data, offset) - if m: - check_format_condition( - int(m.group(1)) > 0, - "indirect object definition: object ID must be greater than 0", - ) - check_format_condition( - int(m.group(2)) >= 0, - "indirect object definition: generation must be non-negative", - ) - check_format_condition( - expect_indirect is None - or expect_indirect - == IndirectReference(int(m.group(1)), int(m.group(2))), - "indirect object definition different than expected", - ) - object, offset = cls.get_value(data, m.end(), max_nesting=max_nesting - 1) - if offset is None: - return object, None - m = cls.re_indirect_def_end.match(data, offset) - check_format_condition(m, "indirect object definition end not found") - return object, m.end() - check_format_condition( - not expect_indirect, "indirect object definition not found" - ) - m = cls.re_indirect_reference.match(data, offset) - if m: - check_format_condition( - int(m.group(1)) > 0, - "indirect object reference: object ID must be greater than 0", - ) - check_format_condition( - int(m.group(2)) >= 0, - "indirect object reference: generation must be non-negative", - ) - return IndirectReference(int(m.group(1)), int(m.group(2))), m.end() - m = cls.re_dict_start.match(data, offset) - if m: - offset = m.end() - result = {} - m = cls.re_dict_end.match(data, offset) - while not m: - key, offset = cls.get_value(data, offset, max_nesting=max_nesting - 1) - if offset is None: - return result, None - value, offset = cls.get_value(data, offset, max_nesting=max_nesting - 1) - result[key] = value - if offset is None: - return result, None - m = cls.re_dict_end.match(data, offset) - offset = m.end() - m = cls.re_stream_start.match(data, offset) - if m: - try: - stream_len = int(result[b"Length"]) - except (TypeError, KeyError, ValueError) as e: - msg = "bad or missing Length in stream dict (%r)" % result.get( - b"Length", None - ) - raise PdfFormatError(msg) from e - stream_data = data[m.end() : m.end() + stream_len] - m = cls.re_stream_end.match(data, m.end() + stream_len) - check_format_condition(m, "stream end not found") - offset = m.end() - result = PdfStream(PdfDict(result), stream_data) - else: - result = PdfDict(result) - return result, offset - m = cls.re_array_start.match(data, offset) - if m: - offset = m.end() - result = [] - m = cls.re_array_end.match(data, offset) - while not m: - value, offset = cls.get_value(data, offset, max_nesting=max_nesting - 1) - result.append(value) - if offset is None: - return result, None - m = cls.re_array_end.match(data, offset) - return result, m.end() - m = cls.re_null.match(data, offset) - if m: - return None, m.end() - m = cls.re_true.match(data, offset) - if m: - return True, m.end() - m = cls.re_false.match(data, offset) - if m: - return False, m.end() - m = cls.re_name.match(data, offset) - if m: - return PdfName(cls.interpret_name(m.group(1))), m.end() - m = cls.re_int.match(data, offset) - if m: - return int(m.group(1)), m.end() - m = cls.re_real.match(data, offset) - if m: - # XXX Decimal instead of float??? - return float(m.group(1)), m.end() - m = cls.re_string_hex.match(data, offset) - if m: - # filter out whitespace - hex_string = bytearray( - b for b in m.group(1) if b in b"0123456789abcdefABCDEF" - ) - if len(hex_string) % 2 == 1: - # append a 0 if the length is not even - yes, at the end - hex_string.append(ord(b"0")) - return bytearray.fromhex(hex_string.decode("us-ascii")), m.end() - m = cls.re_string_lit.match(data, offset) - if m: - return cls.get_literal_string(data, m.end()) - # return None, offset # fallback (only for debugging) - msg = "unrecognized object: " + repr(data[offset : offset + 32]) - raise PdfFormatError(msg) - - re_lit_str_token = re.compile( - rb"(\\[nrtbf()\\])|(\\[0-9]{1,3})|(\\(\r\n|\r|\n))|(\r\n|\r|\n)|(\()|(\))" - ) - escaped_chars = { - b"n": b"\n", - b"r": b"\r", - b"t": b"\t", - b"b": b"\b", - b"f": b"\f", - b"(": b"(", - b")": b")", - b"\\": b"\\", - ord(b"n"): b"\n", - ord(b"r"): b"\r", - ord(b"t"): b"\t", - ord(b"b"): b"\b", - ord(b"f"): b"\f", - ord(b"("): b"(", - ord(b")"): b")", - ord(b"\\"): b"\\", - } - - @classmethod - def get_literal_string(cls, data, offset): - nesting_depth = 0 - result = bytearray() - for m in cls.re_lit_str_token.finditer(data, offset): - result.extend(data[offset : m.start()]) - if m.group(1): - result.extend(cls.escaped_chars[m.group(1)[1]]) - elif m.group(2): - result.append(int(m.group(2)[1:], 8)) - elif m.group(3): - pass - elif m.group(5): - result.extend(b"\n") - elif m.group(6): - result.extend(b"(") - nesting_depth += 1 - elif m.group(7): - if nesting_depth == 0: - return bytes(result), m.end() - result.extend(b")") - nesting_depth -= 1 - offset = m.end() - msg = "unfinished literal string" - raise PdfFormatError(msg) - - re_xref_section_start = re.compile(whitespace_optional + rb"xref" + newline) - re_xref_subsection_start = re.compile( - whitespace_optional - + rb"([0-9]+)" - + whitespace_mandatory - + rb"([0-9]+)" - + whitespace_optional - + newline_only - ) - re_xref_entry = re.compile(rb"([0-9]{10}) ([0-9]{5}) ([fn])( \r| \n|\r\n)") - - def read_xref_table(self, xref_section_offset): - subsection_found = False - m = self.re_xref_section_start.match( - self.buf, xref_section_offset + self.start_offset - ) - check_format_condition(m, "xref section start not found") - offset = m.end() - while True: - m = self.re_xref_subsection_start.match(self.buf, offset) - if not m: - check_format_condition( - subsection_found, "xref subsection start not found" - ) - break - subsection_found = True - offset = m.end() - first_object = int(m.group(1)) - num_objects = int(m.group(2)) - for i in range(first_object, first_object + num_objects): - m = self.re_xref_entry.match(self.buf, offset) - check_format_condition(m, "xref entry not found") - offset = m.end() - is_free = m.group(3) == b"f" - if not is_free: - generation = int(m.group(2)) - new_entry = (int(m.group(1)), generation) - if i not in self.xref_table: - self.xref_table[i] = new_entry - return offset - - def read_indirect(self, ref, max_nesting=-1): - offset, generation = self.xref_table[ref[0]] - check_format_condition( - generation == ref[1], - f"expected to find generation {ref[1]} for object ID {ref[0]} in xref " - f"table, instead found generation {generation} at offset {offset}", - ) - value = self.get_value( - self.buf, - offset + self.start_offset, - expect_indirect=IndirectReference(*ref), - max_nesting=max_nesting, - )[0] - self.cached_objects[ref] = value - return value - - def linearize_page_tree(self, node=None): - if node is None: - node = self.page_tree_root - check_format_condition( - node[b"Type"] == b"Pages", "/Type of page tree node is not /Pages" - ) - pages = [] - for kid in node[b"Kids"]: - kid_object = self.read_indirect(kid) - if kid_object[b"Type"] == b"Page": - pages.append(kid) - else: - pages.extend(self.linearize_page_tree(node=kid_object)) - return pages diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/dateutil/parser/_parser.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/dateutil/parser/_parser.py deleted file mode 100644 index 37d1663b2f72447800d9a553929e3de932244289..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/dateutil/parser/_parser.py +++ /dev/null @@ -1,1613 +0,0 @@ -# -*- coding: utf-8 -*- -""" -This module offers a generic date/time string parser which is able to parse -most known formats to represent a date and/or time. - -This module attempts to be forgiving with regards to unlikely input formats, -returning a datetime object even for dates which are ambiguous. If an element -of a date/time stamp is omitted, the following rules are applied: - -- If AM or PM is left unspecified, a 24-hour clock is assumed, however, an hour - on a 12-hour clock (``0 <= hour <= 12``) *must* be specified if AM or PM is - specified. -- If a time zone is omitted, a timezone-naive datetime is returned. - -If any other elements are missing, they are taken from the -:class:`datetime.datetime` object passed to the parameter ``default``. If this -results in a day number exceeding the valid number of days per month, the -value falls back to the end of the month. - -Additional resources about date/time string formats can be found below: - -- `A summary of the international standard date and time notation - `_ -- `W3C Date and Time Formats `_ -- `Time Formats (Planetary Rings Node) `_ -- `CPAN ParseDate module - `_ -- `Java SimpleDateFormat Class - `_ -""" -from __future__ import unicode_literals - -import datetime -import re -import string -import time -import warnings - -from calendar import monthrange -from io import StringIO - -import six -from six import integer_types, text_type - -from decimal import Decimal - -from warnings import warn - -from .. import relativedelta -from .. import tz - -__all__ = ["parse", "parserinfo", "ParserError"] - - -# TODO: pandas.core.tools.datetimes imports this explicitly. Might be worth -# making public and/or figuring out if there is something we can -# take off their plate. -class _timelex(object): - # Fractional seconds are sometimes split by a comma - _split_decimal = re.compile("([.,])") - - def __init__(self, instream): - if isinstance(instream, (bytes, bytearray)): - instream = instream.decode() - - if isinstance(instream, text_type): - instream = StringIO(instream) - elif getattr(instream, 'read', None) is None: - raise TypeError('Parser must be a string or character stream, not ' - '{itype}'.format(itype=instream.__class__.__name__)) - - self.instream = instream - self.charstack = [] - self.tokenstack = [] - self.eof = False - - def get_token(self): - """ - This function breaks the time string into lexical units (tokens), which - can be parsed by the parser. Lexical units are demarcated by changes in - the character set, so any continuous string of letters is considered - one unit, any continuous string of numbers is considered one unit. - - The main complication arises from the fact that dots ('.') can be used - both as separators (e.g. "Sep.20.2009") or decimal points (e.g. - "4:30:21.447"). As such, it is necessary to read the full context of - any dot-separated strings before breaking it into tokens; as such, this - function maintains a "token stack", for when the ambiguous context - demands that multiple tokens be parsed at once. - """ - if self.tokenstack: - return self.tokenstack.pop(0) - - seenletters = False - token = None - state = None - - while not self.eof: - # We only realize that we've reached the end of a token when we - # find a character that's not part of the current token - since - # that character may be part of the next token, it's stored in the - # charstack. - if self.charstack: - nextchar = self.charstack.pop(0) - else: - nextchar = self.instream.read(1) - while nextchar == '\x00': - nextchar = self.instream.read(1) - - if not nextchar: - self.eof = True - break - elif not state: - # First character of the token - determines if we're starting - # to parse a word, a number or something else. - token = nextchar - if self.isword(nextchar): - state = 'a' - elif self.isnum(nextchar): - state = '0' - elif self.isspace(nextchar): - token = ' ' - break # emit token - else: - break # emit token - elif state == 'a': - # If we've already started reading a word, we keep reading - # letters until we find something that's not part of a word. - seenletters = True - if self.isword(nextchar): - token += nextchar - elif nextchar == '.': - token += nextchar - state = 'a.' - else: - self.charstack.append(nextchar) - break # emit token - elif state == '0': - # If we've already started reading a number, we keep reading - # numbers until we find something that doesn't fit. - if self.isnum(nextchar): - token += nextchar - elif nextchar == '.' or (nextchar == ',' and len(token) >= 2): - token += nextchar - state = '0.' - else: - self.charstack.append(nextchar) - break # emit token - elif state == 'a.': - # If we've seen some letters and a dot separator, continue - # parsing, and the tokens will be broken up later. - seenletters = True - if nextchar == '.' or self.isword(nextchar): - token += nextchar - elif self.isnum(nextchar) and token[-1] == '.': - token += nextchar - state = '0.' - else: - self.charstack.append(nextchar) - break # emit token - elif state == '0.': - # If we've seen at least one dot separator, keep going, we'll - # break up the tokens later. - if nextchar == '.' or self.isnum(nextchar): - token += nextchar - elif self.isword(nextchar) and token[-1] == '.': - token += nextchar - state = 'a.' - else: - self.charstack.append(nextchar) - break # emit token - - if (state in ('a.', '0.') and (seenletters or token.count('.') > 1 or - token[-1] in '.,')): - l = self._split_decimal.split(token) - token = l[0] - for tok in l[1:]: - if tok: - self.tokenstack.append(tok) - - if state == '0.' and token.count('.') == 0: - token = token.replace(',', '.') - - return token - - def __iter__(self): - return self - - def __next__(self): - token = self.get_token() - if token is None: - raise StopIteration - - return token - - def next(self): - return self.__next__() # Python 2.x support - - @classmethod - def split(cls, s): - return list(cls(s)) - - @classmethod - def isword(cls, nextchar): - """ Whether or not the next character is part of a word """ - return nextchar.isalpha() - - @classmethod - def isnum(cls, nextchar): - """ Whether the next character is part of a number """ - return nextchar.isdigit() - - @classmethod - def isspace(cls, nextchar): - """ Whether the next character is whitespace """ - return nextchar.isspace() - - -class _resultbase(object): - - def __init__(self): - for attr in self.__slots__: - setattr(self, attr, None) - - def _repr(self, classname): - l = [] - for attr in self.__slots__: - value = getattr(self, attr) - if value is not None: - l.append("%s=%s" % (attr, repr(value))) - return "%s(%s)" % (classname, ", ".join(l)) - - def __len__(self): - return (sum(getattr(self, attr) is not None - for attr in self.__slots__)) - - def __repr__(self): - return self._repr(self.__class__.__name__) - - -class parserinfo(object): - """ - Class which handles what inputs are accepted. Subclass this to customize - the language and acceptable values for each parameter. - - :param dayfirst: - Whether to interpret the first value in an ambiguous 3-integer date - (e.g. 01/05/09) as the day (``True``) or month (``False``). If - ``yearfirst`` is set to ``True``, this distinguishes between YDM - and YMD. Default is ``False``. - - :param yearfirst: - Whether to interpret the first value in an ambiguous 3-integer date - (e.g. 01/05/09) as the year. If ``True``, the first number is taken - to be the year, otherwise the last number is taken to be the year. - Default is ``False``. - """ - - # m from a.m/p.m, t from ISO T separator - JUMP = [" ", ".", ",", ";", "-", "/", "'", - "at", "on", "and", "ad", "m", "t", "of", - "st", "nd", "rd", "th"] - - WEEKDAYS = [("Mon", "Monday"), - ("Tue", "Tuesday"), # TODO: "Tues" - ("Wed", "Wednesday"), - ("Thu", "Thursday"), # TODO: "Thurs" - ("Fri", "Friday"), - ("Sat", "Saturday"), - ("Sun", "Sunday")] - MONTHS = [("Jan", "January"), - ("Feb", "February"), # TODO: "Febr" - ("Mar", "March"), - ("Apr", "April"), - ("May", "May"), - ("Jun", "June"), - ("Jul", "July"), - ("Aug", "August"), - ("Sep", "Sept", "September"), - ("Oct", "October"), - ("Nov", "November"), - ("Dec", "December")] - HMS = [("h", "hour", "hours"), - ("m", "minute", "minutes"), - ("s", "second", "seconds")] - AMPM = [("am", "a"), - ("pm", "p")] - UTCZONE = ["UTC", "GMT", "Z", "z"] - PERTAIN = ["of"] - TZOFFSET = {} - # TODO: ERA = ["AD", "BC", "CE", "BCE", "Stardate", - # "Anno Domini", "Year of Our Lord"] - - def __init__(self, dayfirst=False, yearfirst=False): - self._jump = self._convert(self.JUMP) - self._weekdays = self._convert(self.WEEKDAYS) - self._months = self._convert(self.MONTHS) - self._hms = self._convert(self.HMS) - self._ampm = self._convert(self.AMPM) - self._utczone = self._convert(self.UTCZONE) - self._pertain = self._convert(self.PERTAIN) - - self.dayfirst = dayfirst - self.yearfirst = yearfirst - - self._year = time.localtime().tm_year - self._century = self._year // 100 * 100 - - def _convert(self, lst): - dct = {} - for i, v in enumerate(lst): - if isinstance(v, tuple): - for v in v: - dct[v.lower()] = i - else: - dct[v.lower()] = i - return dct - - def jump(self, name): - return name.lower() in self._jump - - def weekday(self, name): - try: - return self._weekdays[name.lower()] - except KeyError: - pass - return None - - def month(self, name): - try: - return self._months[name.lower()] + 1 - except KeyError: - pass - return None - - def hms(self, name): - try: - return self._hms[name.lower()] - except KeyError: - return None - - def ampm(self, name): - try: - return self._ampm[name.lower()] - except KeyError: - return None - - def pertain(self, name): - return name.lower() in self._pertain - - def utczone(self, name): - return name.lower() in self._utczone - - def tzoffset(self, name): - if name in self._utczone: - return 0 - - return self.TZOFFSET.get(name) - - def convertyear(self, year, century_specified=False): - """ - Converts two-digit years to year within [-50, 49] - range of self._year (current local time) - """ - - # Function contract is that the year is always positive - assert year >= 0 - - if year < 100 and not century_specified: - # assume current century to start - year += self._century - - if year >= self._year + 50: # if too far in future - year -= 100 - elif year < self._year - 50: # if too far in past - year += 100 - - return year - - def validate(self, res): - # move to info - if res.year is not None: - res.year = self.convertyear(res.year, res.century_specified) - - if ((res.tzoffset == 0 and not res.tzname) or - (res.tzname == 'Z' or res.tzname == 'z')): - res.tzname = "UTC" - res.tzoffset = 0 - elif res.tzoffset != 0 and res.tzname and self.utczone(res.tzname): - res.tzoffset = 0 - return True - - -class _ymd(list): - def __init__(self, *args, **kwargs): - super(self.__class__, self).__init__(*args, **kwargs) - self.century_specified = False - self.dstridx = None - self.mstridx = None - self.ystridx = None - - @property - def has_year(self): - return self.ystridx is not None - - @property - def has_month(self): - return self.mstridx is not None - - @property - def has_day(self): - return self.dstridx is not None - - def could_be_day(self, value): - if self.has_day: - return False - elif not self.has_month: - return 1 <= value <= 31 - elif not self.has_year: - # Be permissive, assume leap year - month = self[self.mstridx] - return 1 <= value <= monthrange(2000, month)[1] - else: - month = self[self.mstridx] - year = self[self.ystridx] - return 1 <= value <= monthrange(year, month)[1] - - def append(self, val, label=None): - if hasattr(val, '__len__'): - if val.isdigit() and len(val) > 2: - self.century_specified = True - if label not in [None, 'Y']: # pragma: no cover - raise ValueError(label) - label = 'Y' - elif val > 100: - self.century_specified = True - if label not in [None, 'Y']: # pragma: no cover - raise ValueError(label) - label = 'Y' - - super(self.__class__, self).append(int(val)) - - if label == 'M': - if self.has_month: - raise ValueError('Month is already set') - self.mstridx = len(self) - 1 - elif label == 'D': - if self.has_day: - raise ValueError('Day is already set') - self.dstridx = len(self) - 1 - elif label == 'Y': - if self.has_year: - raise ValueError('Year is already set') - self.ystridx = len(self) - 1 - - def _resolve_from_stridxs(self, strids): - """ - Try to resolve the identities of year/month/day elements using - ystridx, mstridx, and dstridx, if enough of these are specified. - """ - if len(self) == 3 and len(strids) == 2: - # we can back out the remaining stridx value - missing = [x for x in range(3) if x not in strids.values()] - key = [x for x in ['y', 'm', 'd'] if x not in strids] - assert len(missing) == len(key) == 1 - key = key[0] - val = missing[0] - strids[key] = val - - assert len(self) == len(strids) # otherwise this should not be called - out = {key: self[strids[key]] for key in strids} - return (out.get('y'), out.get('m'), out.get('d')) - - def resolve_ymd(self, yearfirst, dayfirst): - len_ymd = len(self) - year, month, day = (None, None, None) - - strids = (('y', self.ystridx), - ('m', self.mstridx), - ('d', self.dstridx)) - - strids = {key: val for key, val in strids if val is not None} - if (len(self) == len(strids) > 0 or - (len(self) == 3 and len(strids) == 2)): - return self._resolve_from_stridxs(strids) - - mstridx = self.mstridx - - if len_ymd > 3: - raise ValueError("More than three YMD values") - elif len_ymd == 1 or (mstridx is not None and len_ymd == 2): - # One member, or two members with a month string - if mstridx is not None: - month = self[mstridx] - # since mstridx is 0 or 1, self[mstridx-1] always - # looks up the other element - other = self[mstridx - 1] - else: - other = self[0] - - if len_ymd > 1 or mstridx is None: - if other > 31: - year = other - else: - day = other - - elif len_ymd == 2: - # Two members with numbers - if self[0] > 31: - # 99-01 - year, month = self - elif self[1] > 31: - # 01-99 - month, year = self - elif dayfirst and self[1] <= 12: - # 13-01 - day, month = self - else: - # 01-13 - month, day = self - - elif len_ymd == 3: - # Three members - if mstridx == 0: - if self[1] > 31: - # Apr-2003-25 - month, year, day = self - else: - month, day, year = self - elif mstridx == 1: - if self[0] > 31 or (yearfirst and self[2] <= 31): - # 99-Jan-01 - year, month, day = self - else: - # 01-Jan-01 - # Give precedence to day-first, since - # two-digit years is usually hand-written. - day, month, year = self - - elif mstridx == 2: - # WTF!? - if self[1] > 31: - # 01-99-Jan - day, year, month = self - else: - # 99-01-Jan - year, day, month = self - - else: - if (self[0] > 31 or - self.ystridx == 0 or - (yearfirst and self[1] <= 12 and self[2] <= 31)): - # 99-01-01 - if dayfirst and self[2] <= 12: - year, day, month = self - else: - year, month, day = self - elif self[0] > 12 or (dayfirst and self[1] <= 12): - # 13-01-01 - day, month, year = self - else: - # 01-13-01 - month, day, year = self - - return year, month, day - - -class parser(object): - def __init__(self, info=None): - self.info = info or parserinfo() - - def parse(self, timestr, default=None, - ignoretz=False, tzinfos=None, **kwargs): - """ - Parse the date/time string into a :class:`datetime.datetime` object. - - :param timestr: - Any date/time string using the supported formats. - - :param default: - The default datetime object, if this is a datetime object and not - ``None``, elements specified in ``timestr`` replace elements in the - default object. - - :param ignoretz: - If set ``True``, time zones in parsed strings are ignored and a - naive :class:`datetime.datetime` object is returned. - - :param tzinfos: - Additional time zone names / aliases which may be present in the - string. This argument maps time zone names (and optionally offsets - from those time zones) to time zones. This parameter can be a - dictionary with timezone aliases mapping time zone names to time - zones or a function taking two parameters (``tzname`` and - ``tzoffset``) and returning a time zone. - - The timezones to which the names are mapped can be an integer - offset from UTC in seconds or a :class:`tzinfo` object. - - .. doctest:: - :options: +NORMALIZE_WHITESPACE - - >>> from dateutil.parser import parse - >>> from dateutil.tz import gettz - >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")} - >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) - datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) - >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) - datetime.datetime(2012, 1, 19, 17, 21, - tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) - - This parameter is ignored if ``ignoretz`` is set. - - :param \\*\\*kwargs: - Keyword arguments as passed to ``_parse()``. - - :return: - Returns a :class:`datetime.datetime` object or, if the - ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the - first element being a :class:`datetime.datetime` object, the second - a tuple containing the fuzzy tokens. - - :raises ParserError: - Raised for invalid or unknown string format, if the provided - :class:`tzinfo` is not in a valid format, or if an invalid date - would be created. - - :raises TypeError: - Raised for non-string or character stream input. - - :raises OverflowError: - Raised if the parsed date exceeds the largest valid C integer on - your system. - """ - - if default is None: - default = datetime.datetime.now().replace(hour=0, minute=0, - second=0, microsecond=0) - - res, skipped_tokens = self._parse(timestr, **kwargs) - - if res is None: - raise ParserError("Unknown string format: %s", timestr) - - if len(res) == 0: - raise ParserError("String does not contain a date: %s", timestr) - - try: - ret = self._build_naive(res, default) - except ValueError as e: - six.raise_from(ParserError(str(e) + ": %s", timestr), e) - - if not ignoretz: - ret = self._build_tzaware(ret, res, tzinfos) - - if kwargs.get('fuzzy_with_tokens', False): - return ret, skipped_tokens - else: - return ret - - class _result(_resultbase): - __slots__ = ["year", "month", "day", "weekday", - "hour", "minute", "second", "microsecond", - "tzname", "tzoffset", "ampm","any_unused_tokens"] - - def _parse(self, timestr, dayfirst=None, yearfirst=None, fuzzy=False, - fuzzy_with_tokens=False): - """ - Private method which performs the heavy lifting of parsing, called from - ``parse()``, which passes on its ``kwargs`` to this function. - - :param timestr: - The string to parse. - - :param dayfirst: - Whether to interpret the first value in an ambiguous 3-integer date - (e.g. 01/05/09) as the day (``True``) or month (``False``). If - ``yearfirst`` is set to ``True``, this distinguishes between YDM - and YMD. If set to ``None``, this value is retrieved from the - current :class:`parserinfo` object (which itself defaults to - ``False``). - - :param yearfirst: - Whether to interpret the first value in an ambiguous 3-integer date - (e.g. 01/05/09) as the year. If ``True``, the first number is taken - to be the year, otherwise the last number is taken to be the year. - If this is set to ``None``, the value is retrieved from the current - :class:`parserinfo` object (which itself defaults to ``False``). - - :param fuzzy: - Whether to allow fuzzy parsing, allowing for string like "Today is - January 1, 2047 at 8:21:00AM". - - :param fuzzy_with_tokens: - If ``True``, ``fuzzy`` is automatically set to True, and the parser - will return a tuple where the first element is the parsed - :class:`datetime.datetime` datetimestamp and the second element is - a tuple containing the portions of the string which were ignored: - - .. doctest:: - - >>> from dateutil.parser import parse - >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) - (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) - - """ - if fuzzy_with_tokens: - fuzzy = True - - info = self.info - - if dayfirst is None: - dayfirst = info.dayfirst - - if yearfirst is None: - yearfirst = info.yearfirst - - res = self._result() - l = _timelex.split(timestr) # Splits the timestr into tokens - - skipped_idxs = [] - - # year/month/day list - ymd = _ymd() - - len_l = len(l) - i = 0 - try: - while i < len_l: - - # Check if it's a number - value_repr = l[i] - try: - value = float(value_repr) - except ValueError: - value = None - - if value is not None: - # Numeric token - i = self._parse_numeric_token(l, i, info, ymd, res, fuzzy) - - # Check weekday - elif info.weekday(l[i]) is not None: - value = info.weekday(l[i]) - res.weekday = value - - # Check month name - elif info.month(l[i]) is not None: - value = info.month(l[i]) - ymd.append(value, 'M') - - if i + 1 < len_l: - if l[i + 1] in ('-', '/'): - # Jan-01[-99] - sep = l[i + 1] - ymd.append(l[i + 2]) - - if i + 3 < len_l and l[i + 3] == sep: - # Jan-01-99 - ymd.append(l[i + 4]) - i += 2 - - i += 2 - - elif (i + 4 < len_l and l[i + 1] == l[i + 3] == ' ' and - info.pertain(l[i + 2])): - # Jan of 01 - # In this case, 01 is clearly year - if l[i + 4].isdigit(): - # Convert it here to become unambiguous - value = int(l[i + 4]) - year = str(info.convertyear(value)) - ymd.append(year, 'Y') - else: - # Wrong guess - pass - # TODO: not hit in tests - i += 4 - - # Check am/pm - elif info.ampm(l[i]) is not None: - value = info.ampm(l[i]) - val_is_ampm = self._ampm_valid(res.hour, res.ampm, fuzzy) - - if val_is_ampm: - res.hour = self._adjust_ampm(res.hour, value) - res.ampm = value - - elif fuzzy: - skipped_idxs.append(i) - - # Check for a timezone name - elif self._could_be_tzname(res.hour, res.tzname, res.tzoffset, l[i]): - res.tzname = l[i] - res.tzoffset = info.tzoffset(res.tzname) - - # Check for something like GMT+3, or BRST+3. Notice - # that it doesn't mean "I am 3 hours after GMT", but - # "my time +3 is GMT". If found, we reverse the - # logic so that timezone parsing code will get it - # right. - if i + 1 < len_l and l[i + 1] in ('+', '-'): - l[i + 1] = ('+', '-')[l[i + 1] == '+'] - res.tzoffset = None - if info.utczone(res.tzname): - # With something like GMT+3, the timezone - # is *not* GMT. - res.tzname = None - - # Check for a numbered timezone - elif res.hour is not None and l[i] in ('+', '-'): - signal = (-1, 1)[l[i] == '+'] - len_li = len(l[i + 1]) - - # TODO: check that l[i + 1] is integer? - if len_li == 4: - # -0300 - hour_offset = int(l[i + 1][:2]) - min_offset = int(l[i + 1][2:]) - elif i + 2 < len_l and l[i + 2] == ':': - # -03:00 - hour_offset = int(l[i + 1]) - min_offset = int(l[i + 3]) # TODO: Check that l[i+3] is minute-like? - i += 2 - elif len_li <= 2: - # -[0]3 - hour_offset = int(l[i + 1][:2]) - min_offset = 0 - else: - raise ValueError(timestr) - - res.tzoffset = signal * (hour_offset * 3600 + min_offset * 60) - - # Look for a timezone name between parenthesis - if (i + 5 < len_l and - info.jump(l[i + 2]) and l[i + 3] == '(' and - l[i + 5] == ')' and - 3 <= len(l[i + 4]) and - self._could_be_tzname(res.hour, res.tzname, - None, l[i + 4])): - # -0300 (BRST) - res.tzname = l[i + 4] - i += 4 - - i += 1 - - # Check jumps - elif not (info.jump(l[i]) or fuzzy): - raise ValueError(timestr) - - else: - skipped_idxs.append(i) - i += 1 - - # Process year/month/day - year, month, day = ymd.resolve_ymd(yearfirst, dayfirst) - - res.century_specified = ymd.century_specified - res.year = year - res.month = month - res.day = day - - except (IndexError, ValueError): - return None, None - - if not info.validate(res): - return None, None - - if fuzzy_with_tokens: - skipped_tokens = self._recombine_skipped(l, skipped_idxs) - return res, tuple(skipped_tokens) - else: - return res, None - - def _parse_numeric_token(self, tokens, idx, info, ymd, res, fuzzy): - # Token is a number - value_repr = tokens[idx] - try: - value = self._to_decimal(value_repr) - except Exception as e: - six.raise_from(ValueError('Unknown numeric token'), e) - - len_li = len(value_repr) - - len_l = len(tokens) - - if (len(ymd) == 3 and len_li in (2, 4) and - res.hour is None and - (idx + 1 >= len_l or - (tokens[idx + 1] != ':' and - info.hms(tokens[idx + 1]) is None))): - # 19990101T23[59] - s = tokens[idx] - res.hour = int(s[:2]) - - if len_li == 4: - res.minute = int(s[2:]) - - elif len_li == 6 or (len_li > 6 and tokens[idx].find('.') == 6): - # YYMMDD or HHMMSS[.ss] - s = tokens[idx] - - if not ymd and '.' not in tokens[idx]: - ymd.append(s[:2]) - ymd.append(s[2:4]) - ymd.append(s[4:]) - else: - # 19990101T235959[.59] - - # TODO: Check if res attributes already set. - res.hour = int(s[:2]) - res.minute = int(s[2:4]) - res.second, res.microsecond = self._parsems(s[4:]) - - elif len_li in (8, 12, 14): - # YYYYMMDD - s = tokens[idx] - ymd.append(s[:4], 'Y') - ymd.append(s[4:6]) - ymd.append(s[6:8]) - - if len_li > 8: - res.hour = int(s[8:10]) - res.minute = int(s[10:12]) - - if len_li > 12: - res.second = int(s[12:]) - - elif self._find_hms_idx(idx, tokens, info, allow_jump=True) is not None: - # HH[ ]h or MM[ ]m or SS[.ss][ ]s - hms_idx = self._find_hms_idx(idx, tokens, info, allow_jump=True) - (idx, hms) = self._parse_hms(idx, tokens, info, hms_idx) - if hms is not None: - # TODO: checking that hour/minute/second are not - # already set? - self._assign_hms(res, value_repr, hms) - - elif idx + 2 < len_l and tokens[idx + 1] == ':': - # HH:MM[:SS[.ss]] - res.hour = int(value) - value = self._to_decimal(tokens[idx + 2]) # TODO: try/except for this? - (res.minute, res.second) = self._parse_min_sec(value) - - if idx + 4 < len_l and tokens[idx + 3] == ':': - res.second, res.microsecond = self._parsems(tokens[idx + 4]) - - idx += 2 - - idx += 2 - - elif idx + 1 < len_l and tokens[idx + 1] in ('-', '/', '.'): - sep = tokens[idx + 1] - ymd.append(value_repr) - - if idx + 2 < len_l and not info.jump(tokens[idx + 2]): - if tokens[idx + 2].isdigit(): - # 01-01[-01] - ymd.append(tokens[idx + 2]) - else: - # 01-Jan[-01] - value = info.month(tokens[idx + 2]) - - if value is not None: - ymd.append(value, 'M') - else: - raise ValueError() - - if idx + 3 < len_l and tokens[idx + 3] == sep: - # We have three members - value = info.month(tokens[idx + 4]) - - if value is not None: - ymd.append(value, 'M') - else: - ymd.append(tokens[idx + 4]) - idx += 2 - - idx += 1 - idx += 1 - - elif idx + 1 >= len_l or info.jump(tokens[idx + 1]): - if idx + 2 < len_l and info.ampm(tokens[idx + 2]) is not None: - # 12 am - hour = int(value) - res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 2])) - idx += 1 - else: - # Year, month or day - ymd.append(value) - idx += 1 - - elif info.ampm(tokens[idx + 1]) is not None and (0 <= value < 24): - # 12am - hour = int(value) - res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 1])) - idx += 1 - - elif ymd.could_be_day(value): - ymd.append(value) - - elif not fuzzy: - raise ValueError() - - return idx - - def _find_hms_idx(self, idx, tokens, info, allow_jump): - len_l = len(tokens) - - if idx+1 < len_l and info.hms(tokens[idx+1]) is not None: - # There is an "h", "m", or "s" label following this token. We take - # assign the upcoming label to the current token. - # e.g. the "12" in 12h" - hms_idx = idx + 1 - - elif (allow_jump and idx+2 < len_l and tokens[idx+1] == ' ' and - info.hms(tokens[idx+2]) is not None): - # There is a space and then an "h", "m", or "s" label. - # e.g. the "12" in "12 h" - hms_idx = idx + 2 - - elif idx > 0 and info.hms(tokens[idx-1]) is not None: - # There is a "h", "m", or "s" preceding this token. Since neither - # of the previous cases was hit, there is no label following this - # token, so we use the previous label. - # e.g. the "04" in "12h04" - hms_idx = idx-1 - - elif (1 < idx == len_l-1 and tokens[idx-1] == ' ' and - info.hms(tokens[idx-2]) is not None): - # If we are looking at the final token, we allow for a - # backward-looking check to skip over a space. - # TODO: Are we sure this is the right condition here? - hms_idx = idx - 2 - - else: - hms_idx = None - - return hms_idx - - def _assign_hms(self, res, value_repr, hms): - # See GH issue #427, fixing float rounding - value = self._to_decimal(value_repr) - - if hms == 0: - # Hour - res.hour = int(value) - if value % 1: - res.minute = int(60*(value % 1)) - - elif hms == 1: - (res.minute, res.second) = self._parse_min_sec(value) - - elif hms == 2: - (res.second, res.microsecond) = self._parsems(value_repr) - - def _could_be_tzname(self, hour, tzname, tzoffset, token): - return (hour is not None and - tzname is None and - tzoffset is None and - len(token) <= 5 and - (all(x in string.ascii_uppercase for x in token) - or token in self.info.UTCZONE)) - - def _ampm_valid(self, hour, ampm, fuzzy): - """ - For fuzzy parsing, 'a' or 'am' (both valid English words) - may erroneously trigger the AM/PM flag. Deal with that - here. - """ - val_is_ampm = True - - # If there's already an AM/PM flag, this one isn't one. - if fuzzy and ampm is not None: - val_is_ampm = False - - # If AM/PM is found and hour is not, raise a ValueError - if hour is None: - if fuzzy: - val_is_ampm = False - else: - raise ValueError('No hour specified with AM or PM flag.') - elif not 0 <= hour <= 12: - # If AM/PM is found, it's a 12 hour clock, so raise - # an error for invalid range - if fuzzy: - val_is_ampm = False - else: - raise ValueError('Invalid hour specified for 12-hour clock.') - - return val_is_ampm - - def _adjust_ampm(self, hour, ampm): - if hour < 12 and ampm == 1: - hour += 12 - elif hour == 12 and ampm == 0: - hour = 0 - return hour - - def _parse_min_sec(self, value): - # TODO: Every usage of this function sets res.second to the return - # value. Are there any cases where second will be returned as None and - # we *don't* want to set res.second = None? - minute = int(value) - second = None - - sec_remainder = value % 1 - if sec_remainder: - second = int(60 * sec_remainder) - return (minute, second) - - def _parse_hms(self, idx, tokens, info, hms_idx): - # TODO: Is this going to admit a lot of false-positives for when we - # just happen to have digits and "h", "m" or "s" characters in non-date - # text? I guess hex hashes won't have that problem, but there's plenty - # of random junk out there. - if hms_idx is None: - hms = None - new_idx = idx - elif hms_idx > idx: - hms = info.hms(tokens[hms_idx]) - new_idx = hms_idx - else: - # Looking backwards, increment one. - hms = info.hms(tokens[hms_idx]) + 1 - new_idx = idx - - return (new_idx, hms) - - # ------------------------------------------------------------------ - # Handling for individual tokens. These are kept as methods instead - # of functions for the sake of customizability via subclassing. - - def _parsems(self, value): - """Parse a I[.F] seconds value into (seconds, microseconds).""" - if "." not in value: - return int(value), 0 - else: - i, f = value.split(".") - return int(i), int(f.ljust(6, "0")[:6]) - - def _to_decimal(self, val): - try: - decimal_value = Decimal(val) - # See GH 662, edge case, infinite value should not be converted - # via `_to_decimal` - if not decimal_value.is_finite(): - raise ValueError("Converted decimal value is infinite or NaN") - except Exception as e: - msg = "Could not convert %s to decimal" % val - six.raise_from(ValueError(msg), e) - else: - return decimal_value - - # ------------------------------------------------------------------ - # Post-Parsing construction of datetime output. These are kept as - # methods instead of functions for the sake of customizability via - # subclassing. - - def _build_tzinfo(self, tzinfos, tzname, tzoffset): - if callable(tzinfos): - tzdata = tzinfos(tzname, tzoffset) - else: - tzdata = tzinfos.get(tzname) - # handle case where tzinfo is paased an options that returns None - # eg tzinfos = {'BRST' : None} - if isinstance(tzdata, datetime.tzinfo) or tzdata is None: - tzinfo = tzdata - elif isinstance(tzdata, text_type): - tzinfo = tz.tzstr(tzdata) - elif isinstance(tzdata, integer_types): - tzinfo = tz.tzoffset(tzname, tzdata) - else: - raise TypeError("Offset must be tzinfo subclass, tz string, " - "or int offset.") - return tzinfo - - def _build_tzaware(self, naive, res, tzinfos): - if (callable(tzinfos) or (tzinfos and res.tzname in tzinfos)): - tzinfo = self._build_tzinfo(tzinfos, res.tzname, res.tzoffset) - aware = naive.replace(tzinfo=tzinfo) - aware = self._assign_tzname(aware, res.tzname) - - elif res.tzname and res.tzname in time.tzname: - aware = naive.replace(tzinfo=tz.tzlocal()) - - # Handle ambiguous local datetime - aware = self._assign_tzname(aware, res.tzname) - - # This is mostly relevant for winter GMT zones parsed in the UK - if (aware.tzname() != res.tzname and - res.tzname in self.info.UTCZONE): - aware = aware.replace(tzinfo=tz.UTC) - - elif res.tzoffset == 0: - aware = naive.replace(tzinfo=tz.UTC) - - elif res.tzoffset: - aware = naive.replace(tzinfo=tz.tzoffset(res.tzname, res.tzoffset)) - - elif not res.tzname and not res.tzoffset: - # i.e. no timezone information was found. - aware = naive - - elif res.tzname: - # tz-like string was parsed but we don't know what to do - # with it - warnings.warn("tzname {tzname} identified but not understood. " - "Pass `tzinfos` argument in order to correctly " - "return a timezone-aware datetime. In a future " - "version, this will raise an " - "exception.".format(tzname=res.tzname), - category=UnknownTimezoneWarning) - aware = naive - - return aware - - def _build_naive(self, res, default): - repl = {} - for attr in ("year", "month", "day", "hour", - "minute", "second", "microsecond"): - value = getattr(res, attr) - if value is not None: - repl[attr] = value - - if 'day' not in repl: - # If the default day exceeds the last day of the month, fall back - # to the end of the month. - cyear = default.year if res.year is None else res.year - cmonth = default.month if res.month is None else res.month - cday = default.day if res.day is None else res.day - - if cday > monthrange(cyear, cmonth)[1]: - repl['day'] = monthrange(cyear, cmonth)[1] - - naive = default.replace(**repl) - - if res.weekday is not None and not res.day: - naive = naive + relativedelta.relativedelta(weekday=res.weekday) - - return naive - - def _assign_tzname(self, dt, tzname): - if dt.tzname() != tzname: - new_dt = tz.enfold(dt, fold=1) - if new_dt.tzname() == tzname: - return new_dt - - return dt - - def _recombine_skipped(self, tokens, skipped_idxs): - """ - >>> tokens = ["foo", " ", "bar", " ", "19June2000", "baz"] - >>> skipped_idxs = [0, 1, 2, 5] - >>> _recombine_skipped(tokens, skipped_idxs) - ["foo bar", "baz"] - """ - skipped_tokens = [] - for i, idx in enumerate(sorted(skipped_idxs)): - if i > 0 and idx - 1 == skipped_idxs[i - 1]: - skipped_tokens[-1] = skipped_tokens[-1] + tokens[idx] - else: - skipped_tokens.append(tokens[idx]) - - return skipped_tokens - - -DEFAULTPARSER = parser() - - -def parse(timestr, parserinfo=None, **kwargs): - """ - - Parse a string in one of the supported formats, using the - ``parserinfo`` parameters. - - :param timestr: - A string containing a date/time stamp. - - :param parserinfo: - A :class:`parserinfo` object containing parameters for the parser. - If ``None``, the default arguments to the :class:`parserinfo` - constructor are used. - - The ``**kwargs`` parameter takes the following keyword arguments: - - :param default: - The default datetime object, if this is a datetime object and not - ``None``, elements specified in ``timestr`` replace elements in the - default object. - - :param ignoretz: - If set ``True``, time zones in parsed strings are ignored and a naive - :class:`datetime` object is returned. - - :param tzinfos: - Additional time zone names / aliases which may be present in the - string. This argument maps time zone names (and optionally offsets - from those time zones) to time zones. This parameter can be a - dictionary with timezone aliases mapping time zone names to time - zones or a function taking two parameters (``tzname`` and - ``tzoffset``) and returning a time zone. - - The timezones to which the names are mapped can be an integer - offset from UTC in seconds or a :class:`tzinfo` object. - - .. doctest:: - :options: +NORMALIZE_WHITESPACE - - >>> from dateutil.parser import parse - >>> from dateutil.tz import gettz - >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")} - >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) - datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) - >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) - datetime.datetime(2012, 1, 19, 17, 21, - tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) - - This parameter is ignored if ``ignoretz`` is set. - - :param dayfirst: - Whether to interpret the first value in an ambiguous 3-integer date - (e.g. 01/05/09) as the day (``True``) or month (``False``). If - ``yearfirst`` is set to ``True``, this distinguishes between YDM and - YMD. If set to ``None``, this value is retrieved from the current - :class:`parserinfo` object (which itself defaults to ``False``). - - :param yearfirst: - Whether to interpret the first value in an ambiguous 3-integer date - (e.g. 01/05/09) as the year. If ``True``, the first number is taken to - be the year, otherwise the last number is taken to be the year. If - this is set to ``None``, the value is retrieved from the current - :class:`parserinfo` object (which itself defaults to ``False``). - - :param fuzzy: - Whether to allow fuzzy parsing, allowing for string like "Today is - January 1, 2047 at 8:21:00AM". - - :param fuzzy_with_tokens: - If ``True``, ``fuzzy`` is automatically set to True, and the parser - will return a tuple where the first element is the parsed - :class:`datetime.datetime` datetimestamp and the second element is - a tuple containing the portions of the string which were ignored: - - .. doctest:: - - >>> from dateutil.parser import parse - >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) - (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) - - :return: - Returns a :class:`datetime.datetime` object or, if the - ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the - first element being a :class:`datetime.datetime` object, the second - a tuple containing the fuzzy tokens. - - :raises ParserError: - Raised for invalid or unknown string formats, if the provided - :class:`tzinfo` is not in a valid format, or if an invalid date would - be created. - - :raises OverflowError: - Raised if the parsed date exceeds the largest valid C integer on - your system. - """ - if parserinfo: - return parser(parserinfo).parse(timestr, **kwargs) - else: - return DEFAULTPARSER.parse(timestr, **kwargs) - - -class _tzparser(object): - - class _result(_resultbase): - - __slots__ = ["stdabbr", "stdoffset", "dstabbr", "dstoffset", - "start", "end"] - - class _attr(_resultbase): - __slots__ = ["month", "week", "weekday", - "yday", "jyday", "day", "time"] - - def __repr__(self): - return self._repr("") - - def __init__(self): - _resultbase.__init__(self) - self.start = self._attr() - self.end = self._attr() - - def parse(self, tzstr): - res = self._result() - l = [x for x in re.split(r'([,:.]|[a-zA-Z]+|[0-9]+)',tzstr) if x] - used_idxs = list() - try: - - len_l = len(l) - - i = 0 - while i < len_l: - # BRST+3[BRDT[+2]] - j = i - while j < len_l and not [x for x in l[j] - if x in "0123456789:,-+"]: - j += 1 - if j != i: - if not res.stdabbr: - offattr = "stdoffset" - res.stdabbr = "".join(l[i:j]) - else: - offattr = "dstoffset" - res.dstabbr = "".join(l[i:j]) - - for ii in range(j): - used_idxs.append(ii) - i = j - if (i < len_l and (l[i] in ('+', '-') or l[i][0] in - "0123456789")): - if l[i] in ('+', '-'): - # Yes, that's right. See the TZ variable - # documentation. - signal = (1, -1)[l[i] == '+'] - used_idxs.append(i) - i += 1 - else: - signal = -1 - len_li = len(l[i]) - if len_li == 4: - # -0300 - setattr(res, offattr, (int(l[i][:2]) * 3600 + - int(l[i][2:]) * 60) * signal) - elif i + 1 < len_l and l[i + 1] == ':': - # -03:00 - setattr(res, offattr, - (int(l[i]) * 3600 + - int(l[i + 2]) * 60) * signal) - used_idxs.append(i) - i += 2 - elif len_li <= 2: - # -[0]3 - setattr(res, offattr, - int(l[i][:2]) * 3600 * signal) - else: - return None - used_idxs.append(i) - i += 1 - if res.dstabbr: - break - else: - break - - - if i < len_l: - for j in range(i, len_l): - if l[j] == ';': - l[j] = ',' - - assert l[i] == ',' - - i += 1 - - if i >= len_l: - pass - elif (8 <= l.count(',') <= 9 and - not [y for x in l[i:] if x != ',' - for y in x if y not in "0123456789+-"]): - # GMT0BST,3,0,30,3600,10,0,26,7200[,3600] - for x in (res.start, res.end): - x.month = int(l[i]) - used_idxs.append(i) - i += 2 - if l[i] == '-': - value = int(l[i + 1]) * -1 - used_idxs.append(i) - i += 1 - else: - value = int(l[i]) - used_idxs.append(i) - i += 2 - if value: - x.week = value - x.weekday = (int(l[i]) - 1) % 7 - else: - x.day = int(l[i]) - used_idxs.append(i) - i += 2 - x.time = int(l[i]) - used_idxs.append(i) - i += 2 - if i < len_l: - if l[i] in ('-', '+'): - signal = (-1, 1)[l[i] == "+"] - used_idxs.append(i) - i += 1 - else: - signal = 1 - used_idxs.append(i) - res.dstoffset = (res.stdoffset + int(l[i]) * signal) - - # This was a made-up format that is not in normal use - warn(('Parsed time zone "%s"' % tzstr) + - 'is in a non-standard dateutil-specific format, which ' + - 'is now deprecated; support for parsing this format ' + - 'will be removed in future versions. It is recommended ' + - 'that you switch to a standard format like the GNU ' + - 'TZ variable format.', tz.DeprecatedTzFormatWarning) - elif (l.count(',') == 2 and l[i:].count('/') <= 2 and - not [y for x in l[i:] if x not in (',', '/', 'J', 'M', - '.', '-', ':') - for y in x if y not in "0123456789"]): - for x in (res.start, res.end): - if l[i] == 'J': - # non-leap year day (1 based) - used_idxs.append(i) - i += 1 - x.jyday = int(l[i]) - elif l[i] == 'M': - # month[-.]week[-.]weekday - used_idxs.append(i) - i += 1 - x.month = int(l[i]) - used_idxs.append(i) - i += 1 - assert l[i] in ('-', '.') - used_idxs.append(i) - i += 1 - x.week = int(l[i]) - if x.week == 5: - x.week = -1 - used_idxs.append(i) - i += 1 - assert l[i] in ('-', '.') - used_idxs.append(i) - i += 1 - x.weekday = (int(l[i]) - 1) % 7 - else: - # year day (zero based) - x.yday = int(l[i]) + 1 - - used_idxs.append(i) - i += 1 - - if i < len_l and l[i] == '/': - used_idxs.append(i) - i += 1 - # start time - len_li = len(l[i]) - if len_li == 4: - # -0300 - x.time = (int(l[i][:2]) * 3600 + - int(l[i][2:]) * 60) - elif i + 1 < len_l and l[i + 1] == ':': - # -03:00 - x.time = int(l[i]) * 3600 + int(l[i + 2]) * 60 - used_idxs.append(i) - i += 2 - if i + 1 < len_l and l[i + 1] == ':': - used_idxs.append(i) - i += 2 - x.time += int(l[i]) - elif len_li <= 2: - # -[0]3 - x.time = (int(l[i][:2]) * 3600) - else: - return None - used_idxs.append(i) - i += 1 - - assert i == len_l or l[i] == ',' - - i += 1 - - assert i >= len_l - - except (IndexError, ValueError, AssertionError): - return None - - unused_idxs = set(range(len_l)).difference(used_idxs) - res.any_unused_tokens = not {l[n] for n in unused_idxs}.issubset({",",":"}) - return res - - -DEFAULTTZPARSER = _tzparser() - - -def _parsetz(tzstr): - return DEFAULTTZPARSER.parse(tzstr) - - -class ParserError(ValueError): - """Exception subclass used for any failure to parse a datetime string. - - This is a subclass of :py:exc:`ValueError`, and should be raised any time - earlier versions of ``dateutil`` would have raised ``ValueError``. - - .. versionadded:: 2.8.1 - """ - def __str__(self): - try: - return self.args[0] % self.args[1:] - except (TypeError, IndexError): - return super(ParserError, self).__str__() - - def __repr__(self): - args = ", ".join("'%s'" % arg for arg in self.args) - return "%s(%s)" % (self.__class__.__name__, args) - - -class UnknownTimezoneWarning(RuntimeWarning): - """Raised when the parser finds a timezone it cannot parse into a tzinfo. - - .. versionadded:: 2.7.0 - """ -# vim:ts=4:sw=4:et diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/fontTools/cu2qu/ufo.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/fontTools/cu2qu/ufo.py deleted file mode 100644 index 10367cfecf8384e32eace3b9d0e01ab6c588c324..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/fontTools/cu2qu/ufo.py +++ /dev/null @@ -1,349 +0,0 @@ -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -"""Converts cubic bezier curves to quadratic splines. - -Conversion is performed such that the quadratic splines keep the same end-curve -tangents as the original cubics. The approach is iterative, increasing the -number of segments for a spline until the error gets below a bound. - -Respective curves from multiple fonts will be converted at once to ensure that -the resulting splines are interpolation-compatible. -""" - -import logging -from fontTools.pens.basePen import AbstractPen -from fontTools.pens.pointPen import PointToSegmentPen -from fontTools.pens.reverseContourPen import ReverseContourPen - -from . import curves_to_quadratic -from .errors import ( - UnequalZipLengthsError, - IncompatibleSegmentNumberError, - IncompatibleSegmentTypesError, - IncompatibleGlyphsError, - IncompatibleFontsError, -) - - -__all__ = ["fonts_to_quadratic", "font_to_quadratic"] - -# The default approximation error below is a relative value (1/1000 of the EM square). -# Later on, we convert it to absolute font units by multiplying it by a font's UPEM -# (see fonts_to_quadratic). -DEFAULT_MAX_ERR = 0.001 -CURVE_TYPE_LIB_KEY = "com.github.googlei18n.cu2qu.curve_type" - -logger = logging.getLogger(__name__) - - -_zip = zip - - -def zip(*args): - """Ensure each argument to zip has the same length. Also make sure a list is - returned for python 2/3 compatibility. - """ - - if len(set(len(a) for a in args)) != 1: - raise UnequalZipLengthsError(*args) - return list(_zip(*args)) - - -class GetSegmentsPen(AbstractPen): - """Pen to collect segments into lists of points for conversion. - - Curves always include their initial on-curve point, so some points are - duplicated between segments. - """ - - def __init__(self): - self._last_pt = None - self.segments = [] - - def _add_segment(self, tag, *args): - if tag in ["move", "line", "qcurve", "curve"]: - self._last_pt = args[-1] - self.segments.append((tag, args)) - - def moveTo(self, pt): - self._add_segment("move", pt) - - def lineTo(self, pt): - self._add_segment("line", pt) - - def qCurveTo(self, *points): - self._add_segment("qcurve", self._last_pt, *points) - - def curveTo(self, *points): - self._add_segment("curve", self._last_pt, *points) - - def closePath(self): - self._add_segment("close") - - def endPath(self): - self._add_segment("end") - - def addComponent(self, glyphName, transformation): - pass - - -def _get_segments(glyph): - """Get a glyph's segments as extracted by GetSegmentsPen.""" - - pen = GetSegmentsPen() - # glyph.draw(pen) - # We can't simply draw the glyph with the pen, but we must initialize the - # PointToSegmentPen explicitly with outputImpliedClosingLine=True. - # By default PointToSegmentPen does not outputImpliedClosingLine -- unless - # last and first point on closed contour are duplicated. Because we are - # converting multiple glyphs at the same time, we want to make sure - # this function returns the same number of segments, whether or not - # the last and first point overlap. - # https://github.com/googlefonts/fontmake/issues/572 - # https://github.com/fonttools/fonttools/pull/1720 - pointPen = PointToSegmentPen(pen, outputImpliedClosingLine=True) - glyph.drawPoints(pointPen) - return pen.segments - - -def _set_segments(glyph, segments, reverse_direction): - """Draw segments as extracted by GetSegmentsPen back to a glyph.""" - - glyph.clearContours() - pen = glyph.getPen() - if reverse_direction: - pen = ReverseContourPen(pen) - for tag, args in segments: - if tag == "move": - pen.moveTo(*args) - elif tag == "line": - pen.lineTo(*args) - elif tag == "curve": - pen.curveTo(*args[1:]) - elif tag == "qcurve": - pen.qCurveTo(*args[1:]) - elif tag == "close": - pen.closePath() - elif tag == "end": - pen.endPath() - else: - raise AssertionError('Unhandled segment type "%s"' % tag) - - -def _segments_to_quadratic(segments, max_err, stats, all_quadratic=True): - """Return quadratic approximations of cubic segments.""" - - assert all(s[0] == "curve" for s in segments), "Non-cubic given to convert" - - new_points = curves_to_quadratic([s[1] for s in segments], max_err, all_quadratic) - n = len(new_points[0]) - assert all(len(s) == n for s in new_points[1:]), "Converted incompatibly" - - spline_length = str(n - 2) - stats[spline_length] = stats.get(spline_length, 0) + 1 - - if all_quadratic or n == 3: - return [("qcurve", p) for p in new_points] - else: - return [("curve", p) for p in new_points] - - -def _glyphs_to_quadratic(glyphs, max_err, reverse_direction, stats, all_quadratic=True): - """Do the actual conversion of a set of compatible glyphs, after arguments - have been set up. - - Return True if the glyphs were modified, else return False. - """ - - try: - segments_by_location = zip(*[_get_segments(g) for g in glyphs]) - except UnequalZipLengthsError: - raise IncompatibleSegmentNumberError(glyphs) - if not any(segments_by_location): - return False - - # always modify input glyphs if reverse_direction is True - glyphs_modified = reverse_direction - - new_segments_by_location = [] - incompatible = {} - for i, segments in enumerate(segments_by_location): - tag = segments[0][0] - if not all(s[0] == tag for s in segments[1:]): - incompatible[i] = [s[0] for s in segments] - elif tag == "curve": - new_segments = _segments_to_quadratic( - segments, max_err, stats, all_quadratic - ) - if all_quadratic or new_segments != segments: - glyphs_modified = True - segments = new_segments - new_segments_by_location.append(segments) - - if glyphs_modified: - new_segments_by_glyph = zip(*new_segments_by_location) - for glyph, new_segments in zip(glyphs, new_segments_by_glyph): - _set_segments(glyph, new_segments, reverse_direction) - - if incompatible: - raise IncompatibleSegmentTypesError(glyphs, segments=incompatible) - return glyphs_modified - - -def glyphs_to_quadratic( - glyphs, max_err=None, reverse_direction=False, stats=None, all_quadratic=True -): - """Convert the curves of a set of compatible of glyphs to quadratic. - - All curves will be converted to quadratic at once, ensuring interpolation - compatibility. If this is not required, calling glyphs_to_quadratic with one - glyph at a time may yield slightly more optimized results. - - Return True if glyphs were modified, else return False. - - Raises IncompatibleGlyphsError if glyphs have non-interpolatable outlines. - """ - if stats is None: - stats = {} - - if not max_err: - # assume 1000 is the default UPEM - max_err = DEFAULT_MAX_ERR * 1000 - - if isinstance(max_err, (list, tuple)): - max_errors = max_err - else: - max_errors = [max_err] * len(glyphs) - assert len(max_errors) == len(glyphs) - - return _glyphs_to_quadratic( - glyphs, max_errors, reverse_direction, stats, all_quadratic - ) - - -def fonts_to_quadratic( - fonts, - max_err_em=None, - max_err=None, - reverse_direction=False, - stats=None, - dump_stats=False, - remember_curve_type=True, - all_quadratic=True, -): - """Convert the curves of a collection of fonts to quadratic. - - All curves will be converted to quadratic at once, ensuring interpolation - compatibility. If this is not required, calling fonts_to_quadratic with one - font at a time may yield slightly more optimized results. - - Return True if fonts were modified, else return False. - - By default, cu2qu stores the curve type in the fonts' lib, under a private - key "com.github.googlei18n.cu2qu.curve_type", and will not try to convert - them again if the curve type is already set to "quadratic". - Setting 'remember_curve_type' to False disables this optimization. - - Raises IncompatibleFontsError if same-named glyphs from different fonts - have non-interpolatable outlines. - """ - - if remember_curve_type: - curve_types = {f.lib.get(CURVE_TYPE_LIB_KEY, "cubic") for f in fonts} - if len(curve_types) == 1: - curve_type = next(iter(curve_types)) - if curve_type in ("quadratic", "mixed"): - logger.info("Curves already converted to quadratic") - return False - elif curve_type == "cubic": - pass # keep converting - else: - raise NotImplementedError(curve_type) - elif len(curve_types) > 1: - # going to crash later if they do differ - logger.warning("fonts may contain different curve types") - - if stats is None: - stats = {} - - if max_err_em and max_err: - raise TypeError("Only one of max_err and max_err_em can be specified.") - if not (max_err_em or max_err): - max_err_em = DEFAULT_MAX_ERR - - if isinstance(max_err, (list, tuple)): - assert len(max_err) == len(fonts) - max_errors = max_err - elif max_err: - max_errors = [max_err] * len(fonts) - - if isinstance(max_err_em, (list, tuple)): - assert len(fonts) == len(max_err_em) - max_errors = [f.info.unitsPerEm * e for f, e in zip(fonts, max_err_em)] - elif max_err_em: - max_errors = [f.info.unitsPerEm * max_err_em for f in fonts] - - modified = False - glyph_errors = {} - for name in set().union(*(f.keys() for f in fonts)): - glyphs = [] - cur_max_errors = [] - for font, error in zip(fonts, max_errors): - if name in font: - glyphs.append(font[name]) - cur_max_errors.append(error) - try: - modified |= _glyphs_to_quadratic( - glyphs, cur_max_errors, reverse_direction, stats, all_quadratic - ) - except IncompatibleGlyphsError as exc: - logger.error(exc) - glyph_errors[name] = exc - - if glyph_errors: - raise IncompatibleFontsError(glyph_errors) - - if modified and dump_stats: - spline_lengths = sorted(stats.keys()) - logger.info( - "New spline lengths: %s" - % (", ".join("%s: %d" % (l, stats[l]) for l in spline_lengths)) - ) - - if remember_curve_type: - for font in fonts: - curve_type = font.lib.get(CURVE_TYPE_LIB_KEY, "cubic") - new_curve_type = "quadratic" if all_quadratic else "mixed" - if curve_type != new_curve_type: - font.lib[CURVE_TYPE_LIB_KEY] = new_curve_type - modified = True - return modified - - -def glyph_to_quadratic(glyph, **kwargs): - """Convenience wrapper around glyphs_to_quadratic, for just one glyph. - Return True if the glyph was modified, else return False. - """ - - return glyphs_to_quadratic([glyph], **kwargs) - - -def font_to_quadratic(font, **kwargs): - """Convenience wrapper around fonts_to_quadratic, for just one font. - Return True if the font was modified, else return False. - """ - - return fonts_to_quadratic([font], **kwargs) diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/httpx/_transports/default.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/httpx/_transports/default.py deleted file mode 100644 index fca7de98d930a24b6ff5d5a12ce6787c7d5acdc7..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/httpx/_transports/default.py +++ /dev/null @@ -1,365 +0,0 @@ -""" -Custom transports, with nicely configured defaults. - -The following additional keyword arguments are currently supported by httpcore... - -* uds: str -* local_address: str -* retries: int - -Example usages... - -# Disable HTTP/2 on a single specific domain. -mounts = { - "all://": httpx.HTTPTransport(http2=True), - "all://*example.org": httpx.HTTPTransport() -} - -# Using advanced httpcore configuration, with connection retries. -transport = httpx.HTTPTransport(retries=1) -client = httpx.Client(transport=transport) - -# Using advanced httpcore configuration, with unix domain sockets. -transport = httpx.HTTPTransport(uds="socket.uds") -client = httpx.Client(transport=transport) -""" -import contextlib -import typing -from types import TracebackType - -import httpcore - -from .._config import DEFAULT_LIMITS, Limits, Proxy, create_ssl_context -from .._exceptions import ( - ConnectError, - ConnectTimeout, - LocalProtocolError, - NetworkError, - PoolTimeout, - ProtocolError, - ProxyError, - ReadError, - ReadTimeout, - RemoteProtocolError, - TimeoutException, - UnsupportedProtocol, - WriteError, - WriteTimeout, -) -from .._models import Request, Response -from .._types import AsyncByteStream, CertTypes, SyncByteStream, VerifyTypes -from .base import AsyncBaseTransport, BaseTransport - -T = typing.TypeVar("T", bound="HTTPTransport") -A = typing.TypeVar("A", bound="AsyncHTTPTransport") - - -@contextlib.contextmanager -def map_httpcore_exceptions() -> typing.Iterator[None]: - try: - yield - except Exception as exc: # noqa: PIE-786 - mapped_exc = None - - for from_exc, to_exc in HTTPCORE_EXC_MAP.items(): - if not isinstance(exc, from_exc): - continue - # We want to map to the most specific exception we can find. - # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to - # `httpx.ReadTimeout`, not just `httpx.TimeoutException`. - if mapped_exc is None or issubclass(to_exc, mapped_exc): - mapped_exc = to_exc - - if mapped_exc is None: # pragma: no cover - raise - - message = str(exc) - raise mapped_exc(message) from exc - - -HTTPCORE_EXC_MAP = { - httpcore.TimeoutException: TimeoutException, - httpcore.ConnectTimeout: ConnectTimeout, - httpcore.ReadTimeout: ReadTimeout, - httpcore.WriteTimeout: WriteTimeout, - httpcore.PoolTimeout: PoolTimeout, - httpcore.NetworkError: NetworkError, - httpcore.ConnectError: ConnectError, - httpcore.ReadError: ReadError, - httpcore.WriteError: WriteError, - httpcore.ProxyError: ProxyError, - httpcore.UnsupportedProtocol: UnsupportedProtocol, - httpcore.ProtocolError: ProtocolError, - httpcore.LocalProtocolError: LocalProtocolError, - httpcore.RemoteProtocolError: RemoteProtocolError, -} - - -class ResponseStream(SyncByteStream): - def __init__(self, httpcore_stream: typing.Iterable[bytes]): - self._httpcore_stream = httpcore_stream - - def __iter__(self) -> typing.Iterator[bytes]: - with map_httpcore_exceptions(): - for part in self._httpcore_stream: - yield part - - def close(self) -> None: - if hasattr(self._httpcore_stream, "close"): - self._httpcore_stream.close() - - -class HTTPTransport(BaseTransport): - def __init__( - self, - verify: VerifyTypes = True, - cert: typing.Optional[CertTypes] = None, - http1: bool = True, - http2: bool = False, - limits: Limits = DEFAULT_LIMITS, - trust_env: bool = True, - proxy: typing.Optional[Proxy] = None, - uds: typing.Optional[str] = None, - local_address: typing.Optional[str] = None, - retries: int = 0, - ) -> None: - ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env) - - if proxy is None: - self._pool = httpcore.ConnectionPool( - ssl_context=ssl_context, - max_connections=limits.max_connections, - max_keepalive_connections=limits.max_keepalive_connections, - keepalive_expiry=limits.keepalive_expiry, - http1=http1, - http2=http2, - uds=uds, - local_address=local_address, - retries=retries, - ) - elif proxy.url.scheme in ("http", "https"): - self._pool = httpcore.HTTPProxy( - proxy_url=httpcore.URL( - scheme=proxy.url.raw_scheme, - host=proxy.url.raw_host, - port=proxy.url.port, - target=proxy.url.raw_path, - ), - proxy_auth=proxy.raw_auth, - proxy_headers=proxy.headers.raw, - ssl_context=ssl_context, - max_connections=limits.max_connections, - max_keepalive_connections=limits.max_keepalive_connections, - keepalive_expiry=limits.keepalive_expiry, - http1=http1, - http2=http2, - ) - elif proxy.url.scheme == "socks5": - try: - import socksio # noqa - except ImportError: # pragma: no cover - raise ImportError( - "Using SOCKS proxy, but the 'socksio' package is not installed. " - "Make sure to install httpx using `pip install httpx[socks]`." - ) from None - - self._pool = httpcore.SOCKSProxy( - proxy_url=httpcore.URL( - scheme=proxy.url.raw_scheme, - host=proxy.url.raw_host, - port=proxy.url.port, - target=proxy.url.raw_path, - ), - proxy_auth=proxy.raw_auth, - ssl_context=ssl_context, - max_connections=limits.max_connections, - max_keepalive_connections=limits.max_keepalive_connections, - keepalive_expiry=limits.keepalive_expiry, - http1=http1, - http2=http2, - ) - else: # pragma: no cover - raise ValueError( - f"Proxy protocol must be either 'http', 'https', or 'socks5', but got {proxy.url.scheme!r}." - ) - - def __enter__(self: T) -> T: # Use generics for subclass support. - self._pool.__enter__() - return self - - def __exit__( - self, - exc_type: typing.Optional[typing.Type[BaseException]] = None, - exc_value: typing.Optional[BaseException] = None, - traceback: typing.Optional[TracebackType] = None, - ) -> None: - with map_httpcore_exceptions(): - self._pool.__exit__(exc_type, exc_value, traceback) - - def handle_request( - self, - request: Request, - ) -> Response: - assert isinstance(request.stream, SyncByteStream) - - req = httpcore.Request( - method=request.method, - url=httpcore.URL( - scheme=request.url.raw_scheme, - host=request.url.raw_host, - port=request.url.port, - target=request.url.raw_path, - ), - headers=request.headers.raw, - content=request.stream, - extensions=request.extensions, - ) - with map_httpcore_exceptions(): - resp = self._pool.handle_request(req) - - assert isinstance(resp.stream, typing.Iterable) - - return Response( - status_code=resp.status, - headers=resp.headers, - stream=ResponseStream(resp.stream), - extensions=resp.extensions, - ) - - def close(self) -> None: - self._pool.close() - - -class AsyncResponseStream(AsyncByteStream): - def __init__(self, httpcore_stream: typing.AsyncIterable[bytes]): - self._httpcore_stream = httpcore_stream - - async def __aiter__(self) -> typing.AsyncIterator[bytes]: - with map_httpcore_exceptions(): - async for part in self._httpcore_stream: - yield part - - async def aclose(self) -> None: - if hasattr(self._httpcore_stream, "aclose"): - await self._httpcore_stream.aclose() - - -class AsyncHTTPTransport(AsyncBaseTransport): - def __init__( - self, - verify: VerifyTypes = True, - cert: typing.Optional[CertTypes] = None, - http1: bool = True, - http2: bool = False, - limits: Limits = DEFAULT_LIMITS, - trust_env: bool = True, - proxy: typing.Optional[Proxy] = None, - uds: typing.Optional[str] = None, - local_address: typing.Optional[str] = None, - retries: int = 0, - ) -> None: - ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env) - - if proxy is None: - self._pool = httpcore.AsyncConnectionPool( - ssl_context=ssl_context, - max_connections=limits.max_connections, - max_keepalive_connections=limits.max_keepalive_connections, - keepalive_expiry=limits.keepalive_expiry, - http1=http1, - http2=http2, - uds=uds, - local_address=local_address, - retries=retries, - ) - elif proxy.url.scheme in ("http", "https"): - self._pool = httpcore.AsyncHTTPProxy( - proxy_url=httpcore.URL( - scheme=proxy.url.raw_scheme, - host=proxy.url.raw_host, - port=proxy.url.port, - target=proxy.url.raw_path, - ), - proxy_auth=proxy.raw_auth, - proxy_headers=proxy.headers.raw, - ssl_context=ssl_context, - max_connections=limits.max_connections, - max_keepalive_connections=limits.max_keepalive_connections, - keepalive_expiry=limits.keepalive_expiry, - http1=http1, - http2=http2, - ) - elif proxy.url.scheme == "socks5": - try: - import socksio # noqa - except ImportError: # pragma: no cover - raise ImportError( - "Using SOCKS proxy, but the 'socksio' package is not installed. " - "Make sure to install httpx using `pip install httpx[socks]`." - ) from None - - self._pool = httpcore.AsyncSOCKSProxy( - proxy_url=httpcore.URL( - scheme=proxy.url.raw_scheme, - host=proxy.url.raw_host, - port=proxy.url.port, - target=proxy.url.raw_path, - ), - proxy_auth=proxy.raw_auth, - ssl_context=ssl_context, - max_connections=limits.max_connections, - max_keepalive_connections=limits.max_keepalive_connections, - keepalive_expiry=limits.keepalive_expiry, - http1=http1, - http2=http2, - ) - else: # pragma: no cover - raise ValueError( - f"Proxy protocol must be either 'http', 'https', or 'socks5', but got {proxy.url.scheme!r}." - ) - - async def __aenter__(self: A) -> A: # Use generics for subclass support. - await self._pool.__aenter__() - return self - - async def __aexit__( - self, - exc_type: typing.Optional[typing.Type[BaseException]] = None, - exc_value: typing.Optional[BaseException] = None, - traceback: typing.Optional[TracebackType] = None, - ) -> None: - with map_httpcore_exceptions(): - await self._pool.__aexit__(exc_type, exc_value, traceback) - - async def handle_async_request( - self, - request: Request, - ) -> Response: - assert isinstance(request.stream, AsyncByteStream) - - req = httpcore.Request( - method=request.method, - url=httpcore.URL( - scheme=request.url.raw_scheme, - host=request.url.raw_host, - port=request.url.port, - target=request.url.raw_path, - ), - headers=request.headers.raw, - content=request.stream, - extensions=request.extensions, - ) - with map_httpcore_exceptions(): - resp = await self._pool.handle_async_request(req) - - assert isinstance(resp.stream, typing.AsyncIterable) - - return Response( - status_code=resp.status, - headers=resp.headers, - stream=AsyncResponseStream(resp.stream), - extensions=resp.extensions, - ) - - async def aclose(self) -> None: - await self._pool.aclose() diff --git a/spaces/declare-lab/tango/diffusers/examples/community/composable_stable_diffusion.py b/spaces/declare-lab/tango/diffusers/examples/community/composable_stable_diffusion.py deleted file mode 100644 index 35512395ace68fd0bf8c06573b0b9b056cd6d1a4..0000000000000000000000000000000000000000 --- a/spaces/declare-lab/tango/diffusers/examples/community/composable_stable_diffusion.py +++ /dev/null @@ -1,582 +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 inspect -from typing import Callable, List, Optional, Union - -import torch -from packaging import version -from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer - -from diffusers import DiffusionPipeline -from diffusers.configuration_utils import FrozenDict -from diffusers.models import AutoencoderKL, UNet2DConditionModel -from diffusers.schedulers import ( - DDIMScheduler, - DPMSolverMultistepScheduler, - EulerAncestralDiscreteScheduler, - EulerDiscreteScheduler, - LMSDiscreteScheduler, - PNDMScheduler, -) -from diffusers.utils import is_accelerate_available - -from ...utils import deprecate, logging -from . import StableDiffusionPipelineOutput -from .safety_checker import StableDiffusionSafetyChecker - - -logger = logging.get_logger(__name__) # pylint: disable=invalid-name - - -class ComposableStableDiffusionPipeline(DiffusionPipeline): - r""" - Pipeline for text-to-image generation using Stable Diffusion. - - This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the - library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.) - - Args: - vae ([`AutoencoderKL`]): - Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. - text_encoder ([`CLIPTextModel`]): - Frozen text-encoder. Stable Diffusion uses the text portion of - [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically - the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant. - tokenizer (`CLIPTokenizer`): - Tokenizer of class - [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer). - unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents. - scheduler ([`SchedulerMixin`]): - A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of - [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`]. - safety_checker ([`StableDiffusionSafetyChecker`]): - Classification module that estimates whether generated images could be considered offensive or harmful. - Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details. - feature_extractor ([`CLIPImageProcessor`]): - Model that extracts features from generated images to be used as inputs for the `safety_checker`. - """ - _optional_components = ["safety_checker", "feature_extractor"] - - def __init__( - self, - vae: AutoencoderKL, - text_encoder: CLIPTextModel, - tokenizer: CLIPTokenizer, - unet: UNet2DConditionModel, - scheduler: Union[ - DDIMScheduler, - PNDMScheduler, - LMSDiscreteScheduler, - EulerDiscreteScheduler, - EulerAncestralDiscreteScheduler, - DPMSolverMultistepScheduler, - ], - safety_checker: StableDiffusionSafetyChecker, - feature_extractor: CLIPImageProcessor, - requires_safety_checker: bool = True, - ): - super().__init__() - - if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1: - deprecation_message = ( - f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`" - f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " - "to update the config accordingly as leaving `steps_offset` might led to incorrect results" - " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," - " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" - " file" - ) - deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False) - new_config = dict(scheduler.config) - new_config["steps_offset"] = 1 - scheduler._internal_dict = FrozenDict(new_config) - - if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True: - deprecation_message = ( - f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`." - " `clip_sample` should be set to False in the configuration file. Please make sure to update the" - " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in" - " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very" - " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file" - ) - deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False) - new_config = dict(scheduler.config) - new_config["clip_sample"] = False - scheduler._internal_dict = FrozenDict(new_config) - - if safety_checker is None and requires_safety_checker: - logger.warning( - f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" - " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" - " results in services or applications open to the public. Both the diffusers team and Hugging Face" - " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" - " it only for use-cases that involve analyzing network behavior or auditing its results. For more" - " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." - ) - - if safety_checker is not None and feature_extractor is None: - raise ValueError( - "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety" - " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead." - ) - - is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse( - version.parse(unet.config._diffusers_version).base_version - ) < version.parse("0.9.0.dev0") - is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64 - if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64: - deprecation_message = ( - "The configuration file of the unet has set the default `sample_size` to smaller than" - " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the" - " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-" - " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5" - " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the" - " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`" - " in the config might lead to incorrect results in future versions. If you have downloaded this" - " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for" - " the `unet/config.json` file" - ) - deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False) - new_config = dict(unet.config) - new_config["sample_size"] = 64 - unet._internal_dict = FrozenDict(new_config) - - self.register_modules( - vae=vae, - text_encoder=text_encoder, - tokenizer=tokenizer, - unet=unet, - scheduler=scheduler, - safety_checker=safety_checker, - feature_extractor=feature_extractor, - ) - self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) - self.register_to_config(requires_safety_checker=requires_safety_checker) - - def enable_vae_slicing(self): - r""" - Enable sliced VAE decoding. - - When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several - steps. This is useful to save some memory and allow larger batch sizes. - """ - self.vae.enable_slicing() - - def disable_vae_slicing(self): - r""" - Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to - computing decoding in one step. - """ - self.vae.disable_slicing() - - def enable_sequential_cpu_offload(self, gpu_id=0): - r""" - Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet, - text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a - `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called. - """ - if is_accelerate_available(): - from accelerate import cpu_offload - else: - raise ImportError("Please install accelerate via `pip install accelerate`") - - device = torch.device(f"cuda:{gpu_id}") - - for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]: - if cpu_offloaded_model is not None: - cpu_offload(cpu_offloaded_model, device) - - if self.safety_checker is not None: - # TODO(Patrick) - there is currently a bug with cpu offload of nn.Parameter in accelerate - # fix by only offloading self.safety_checker for now - cpu_offload(self.safety_checker.vision_model, device) - - @property - def _execution_device(self): - r""" - Returns the device on which the pipeline's models will be executed. After calling - `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module - hooks. - """ - if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"): - return self.device - for module in self.unet.modules(): - if ( - hasattr(module, "_hf_hook") - and hasattr(module._hf_hook, "execution_device") - and module._hf_hook.execution_device is not None - ): - return torch.device(module._hf_hook.execution_device) - return self.device - - def _encode_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt): - r""" - Encodes the prompt into text encoder hidden states. - - Args: - prompt (`str` or `list(int)`): - 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]`): - The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored - if `guidance_scale` is less than `1`). - """ - batch_size = len(prompt) if isinstance(prompt, list) else 1 - - 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 - - text_embeddings = self.text_encoder( - text_input_ids.to(device), - attention_mask=attention_mask, - ) - text_embeddings = text_embeddings[0] - - # duplicate text embeddings for each generation per prompt, using mps friendly method - bs_embed, seq_len, _ = text_embeddings.shape - text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1) - text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1) - - # get unconditional embeddings for classifier free guidance - if do_classifier_free_guidance: - uncond_tokens: List[str] - if negative_prompt is None: - uncond_tokens = [""] * batch_size - elif type(prompt) is not type(negative_prompt): - raise TypeError( - f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" - f" {type(prompt)}." - ) - elif isinstance(negative_prompt, str): - uncond_tokens = [negative_prompt] - elif batch_size != len(negative_prompt): - raise ValueError( - f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" - f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" - " the batch size of `prompt`." - ) - else: - uncond_tokens = negative_prompt - - max_length = text_input_ids.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 - - uncond_embeddings = self.text_encoder( - uncond_input.input_ids.to(device), - attention_mask=attention_mask, - ) - uncond_embeddings = uncond_embeddings[0] - - # duplicate unconditional embeddings for each generation per prompt, using mps friendly method - seq_len = uncond_embeddings.shape[1] - uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1) - uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1) - - # For classifier free guidance, we need to do two forward passes. - # Here we concatenate the unconditional and text embeddings into a single batch - # to avoid doing two forward passes - text_embeddings = torch.cat([uncond_embeddings, text_embeddings]) - - return text_embeddings - - def run_safety_checker(self, image, device, dtype): - if self.safety_checker is not None: - safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device) - image, has_nsfw_concept = self.safety_checker( - images=image, clip_input=safety_checker_input.pixel_values.to(dtype) - ) - else: - has_nsfw_concept = None - return image, has_nsfw_concept - - def decode_latents(self, latents): - latents = 1 / 0.18215 * latents - image = self.vae.decode(latents).sample - image = (image / 2 + 0.5).clamp(0, 1) - # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 - image = image.cpu().permute(0, 2, 3, 1).float().numpy() - return image - - 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 - - def check_inputs(self, prompt, height, width, callback_steps): - if 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 height % 8 != 0 or width % 8 != 0: - raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.") - - if (callback_steps is None) or ( - callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0) - ): - raise ValueError( - f"`callback_steps` has to be a positive integer but is {callback_steps} of type" - f" {type(callback_steps)}." - ) - - def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None): - shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor) - if latents is None: - if device.type == "mps": - # randn does not work reproducibly on mps - latents = torch.randn(shape, generator=generator, device="cpu", dtype=dtype).to(device) - else: - latents = torch.randn(shape, generator=generator, device=device, dtype=dtype) - else: - if latents.shape != shape: - raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}") - latents = latents.to(device) - - # scale the initial noise by the standard deviation required by the scheduler - latents = latents * self.scheduler.init_noise_sigma - return latents - - @torch.no_grad() - def __call__( - self, - prompt: Union[str, List[str]], - height: Optional[int] = None, - width: Optional[int] = None, - num_inference_steps: int = 50, - guidance_scale: float = 7.5, - negative_prompt: Optional[Union[str, List[str]]] = None, - num_images_per_prompt: Optional[int] = 1, - eta: float = 0.0, - generator: Optional[torch.Generator] = None, - latents: Optional[torch.FloatTensor] = None, - output_type: Optional[str] = "pil", - return_dict: bool = True, - callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, - callback_steps: int = 1, - weights: Optional[str] = "", - ): - r""" - Function invoked when calling the pipeline for generation. - - Args: - prompt (`str` or `List[str]`): - The prompt or prompts to guide the image generation. - height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): - The height in pixels of the generated image. - width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): - The width in pixels of the generated image. - num_inference_steps (`int`, *optional*, defaults to 50): - The number of denoising steps. More denoising steps usually lead to a higher quality image at the - expense of slower inference. - guidance_scale (`float`, *optional*, defaults to 7.5): - Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). - `guidance_scale` is defined as `w` of equation 2. of [Imagen - Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > - 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, - usually at the expense of lower image quality. - negative_prompt (`str` or `List[str]`, *optional*): - The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored - if `guidance_scale` is less than `1`). - num_images_per_prompt (`int`, *optional*, defaults to 1): - The number of images to generate per prompt. - eta (`float`, *optional*, defaults to 0.0): - Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to - [`schedulers.DDIMScheduler`], will be ignored for others. - generator (`torch.Generator`, *optional*): - A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation - deterministic. - latents (`torch.FloatTensor`, *optional*): - Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image - generation. Can be used to tweak the same generation with different prompts. If not provided, a latents - tensor will ge generated by sampling using the supplied random `generator`. - output_type (`str`, *optional*, defaults to `"pil"`): - The output format of the generate image. Choose between - [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. - return_dict (`bool`, *optional*, defaults to `True`): - Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a - plain tuple. - callback (`Callable`, *optional*): - A function that will be called every `callback_steps` steps during inference. The function will be - called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. - callback_steps (`int`, *optional*, defaults to 1): - The frequency at which the `callback` function will be called. If not specified, the callback will be - called at every step. - - Returns: - [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: - [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple. - When returning a tuple, the first element is a list with the generated images, and the second element is a - list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" - (nsfw) content, according to the `safety_checker`. - """ - # 0. Default height and width to unet - height = height or self.unet.config.sample_size * self.vae_scale_factor - width = width or self.unet.config.sample_size * self.vae_scale_factor - - # 1. Check inputs. Raise error if not correct - self.check_inputs(prompt, height, width, callback_steps) - - # 2. Define call parameters - batch_size = 1 if isinstance(prompt, str) else len(prompt) - 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 - - if "|" in prompt: - prompt = [x.strip() for x in prompt.split("|")] - print(f"composing {prompt}...") - - if not weights: - # specify weights for prompts (excluding the unconditional score) - print("using equal positive weights (conjunction) for all prompts...") - weights = torch.tensor([guidance_scale] * len(prompt), device=self.device).reshape(-1, 1, 1, 1) - else: - # set prompt weight for each - num_prompts = len(prompt) if isinstance(prompt, list) else 1 - weights = [float(w.strip()) for w in weights.split("|")] - # guidance scale as the default - if len(weights) < num_prompts: - weights.append(guidance_scale) - else: - weights = weights[:num_prompts] - assert len(weights) == len(prompt), "weights specified are not equal to the number of prompts" - weights = torch.tensor(weights, device=self.device).reshape(-1, 1, 1, 1) - else: - weights = guidance_scale - - # 3. Encode input prompt - text_embeddings = self._encode_prompt( - prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt - ) - - # 4. Prepare timesteps - self.scheduler.set_timesteps(num_inference_steps, device=device) - timesteps = self.scheduler.timesteps - - # 5. Prepare latent variables - num_channels_latents = self.unet.in_channels - latents = self.prepare_latents( - batch_size * num_images_per_prompt, - num_channels_latents, - height, - width, - text_embeddings.dtype, - device, - generator, - latents, - ) - - # composable diffusion - if isinstance(prompt, list) and batch_size == 1: - # remove extra unconditional embedding - # N = one unconditional embed + conditional embeds - text_embeddings = text_embeddings[len(prompt) - 1 :] - - # 6. 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) - - # 7. 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) - - # predict the noise residual - noise_pred = [] - for j in range(text_embeddings.shape[0]): - noise_pred.append( - self.unet(latent_model_input[:1], t, encoder_hidden_states=text_embeddings[j : j + 1]).sample - ) - noise_pred = torch.cat(noise_pred, dim=0) - - # perform guidance - if do_classifier_free_guidance: - noise_pred_uncond, noise_pred_text = noise_pred[:1], noise_pred[1:] - noise_pred = noise_pred_uncond + (weights * (noise_pred_text - noise_pred_uncond)).sum( - dim=0, keepdims=True - ) - - # compute the previous noisy sample x_t -> x_t-1 - latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample - - # call the callback, if provided - if 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) - - # 8. Post-processing - image = self.decode_latents(latents) - - # 9. Run safety checker - image, has_nsfw_concept = self.run_safety_checker(image, device, text_embeddings.dtype) - - # 10. Convert to PIL - if output_type == "pil": - image = self.numpy_to_pil(image) - - if not return_dict: - return (image, has_nsfw_concept) - - return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept) diff --git a/spaces/deepghs/anime_object_detection/manbits.py b/spaces/deepghs/anime_object_detection/manbits.py deleted file mode 100644 index 87997d0056e07701dcfbed58f57c8270a0092576..0000000000000000000000000000000000000000 --- a/spaces/deepghs/anime_object_detection/manbits.py +++ /dev/null @@ -1,45 +0,0 @@ -from functools import lru_cache -from typing import List, Tuple - -from huggingface_hub import hf_hub_download -from imgutils.data import ImageTyping, load_image, rgb_encode - -from onnx_ import _open_onnx_model -from plot import detection_visualize -from yolo_ import _image_preprocess, _data_postprocess - -_MANBIT_MODELS = [ - 'manbits_detect_best_m.onnx', -] -_DEFAULT_MANBIT_MODEL = _MANBIT_MODELS[0] - - -@lru_cache() -def _open_manbits_detect_model(model_name): - return _open_onnx_model(hf_hub_download( - 'deepghs/imgutils-models', - f'manbits_detect/{model_name}' - )) - - -_LABELS = [ - 'EXPOSED_BELLY', 'EXPOSED_BREAST_F', 'EXPOSED_BREAST_M', - 'EXPOSED_BUTTOCKS', 'EXPOSED_GENITALIA_F', 'EXPOSED_GENITALIA_M' -] - - -def detect_manbits(image: ImageTyping, model_name: str, max_infer_size=640, - conf_threshold: float = 0.25, iou_threshold: float = 0.7) \ - -> List[Tuple[Tuple[int, int, int, int], str, float]]: - image = load_image(image, mode='RGB') - new_image, old_size, new_size = _image_preprocess(image, max_infer_size) - - data = rgb_encode(new_image)[None, ...] - output, = _open_manbits_detect_model(model_name).run(['output0'], {'images': data}) - return _data_postprocess(output[0], conf_threshold, iou_threshold, old_size, new_size, _LABELS) - - -def _gr_detect_manbits(image: ImageTyping, model_name: str, max_infer_size=640, - conf_threshold: float = 0.25, iou_threshold: float = 0.7): - ret = detect_manbits(image, model_name, max_infer_size, conf_threshold, iou_threshold) - return detection_visualize(image, ret, _LABELS) diff --git a/spaces/deeplearning/audioldm-text-to-audio-generation/audioldm/clap/open_clip/openai.py b/spaces/deeplearning/audioldm-text-to-audio-generation/audioldm/clap/open_clip/openai.py deleted file mode 100644 index 3f4eb8b55fe960e1792b3da804b60b3d8f70fe26..0000000000000000000000000000000000000000 --- a/spaces/deeplearning/audioldm-text-to-audio-generation/audioldm/clap/open_clip/openai.py +++ /dev/null @@ -1,156 +0,0 @@ -""" OpenAI pretrained model functions - -Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. -""" - -import os -import warnings -from typing import Union, List - -import torch - -from .model import build_model_from_openai_state_dict -from .pretrained import ( - get_pretrained_url, - list_pretrained_tag_models, - download_pretrained, -) - -__all__ = ["list_openai_models", "load_openai_model"] - - -def list_openai_models() -> List[str]: - """Returns the names of available CLIP models""" - return list_pretrained_tag_models("openai") - - -def load_openai_model( - name: str, - model_cfg, - device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", - jit=True, - cache_dir=os.path.expanduser("~/.cache/clip"), - enable_fusion: bool = False, - fusion_type: str = "None", -): - """Load a CLIP model, preserve its text pretrained part, and set in the CLAP model - - Parameters - ---------- - name : str - A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict - device : Union[str, torch.device] - The device to put the loaded model - jit : bool - Whether to load the optimized JIT model (default) or more hackable non-JIT model. - - Returns - ------- - model : torch.nn.Module - The CLAP model - preprocess : Callable[[PIL.Image], torch.Tensor] - A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input - """ - if get_pretrained_url(name, "openai"): - model_path = download_pretrained( - get_pretrained_url(name, "openai"), root=cache_dir - ) - elif os.path.isfile(name): - model_path = name - else: - raise RuntimeError( - f"Model {name} not found; available models = {list_openai_models()}" - ) - - try: - # loading JIT archive - model = torch.jit.load(model_path, map_location=device if jit else "cpu").eval() - state_dict = None - except RuntimeError: - # loading saved state dict - if jit: - warnings.warn( - f"File {model_path} is not a JIT archive. Loading as a state dict instead" - ) - jit = False - state_dict = torch.load(model_path, map_location="cpu") - - if not jit: - try: - model = build_model_from_openai_state_dict( - state_dict or model.state_dict(), model_cfg, enable_fusion, fusion_type - ).to(device) - except KeyError: - sd = {k[7:]: v for k, v in state_dict["state_dict"].items()} - model = build_model_from_openai_state_dict( - sd, model_cfg, enable_fusion, fusion_type - ).to(device) - - if str(device) == "cpu": - model.float() - return model - - # patch the device names - device_holder = torch.jit.trace( - lambda: torch.ones([]).to(torch.device(device)), example_inputs=[] - ) - device_node = [ - n - for n in device_holder.graph.findAllNodes("prim::Constant") - if "Device" in repr(n) - ][-1] - - def patch_device(module): - try: - graphs = [module.graph] if hasattr(module, "graph") else [] - except RuntimeError: - graphs = [] - - if hasattr(module, "forward1"): - graphs.append(module.forward1.graph) - - for graph in graphs: - for node in graph.findAllNodes("prim::Constant"): - if "value" in node.attributeNames() and str(node["value"]).startswith( - "cuda" - ): - node.copyAttributes(device_node) - - model.apply(patch_device) - patch_device(model.encode_audio) - patch_device(model.encode_text) - - # patch dtype to float32 on CPU - if str(device) == "cpu": - float_holder = torch.jit.trace( - lambda: torch.ones([]).float(), example_inputs=[] - ) - float_input = list(float_holder.graph.findNode("aten::to").inputs())[1] - float_node = float_input.node() - - def patch_float(module): - try: - graphs = [module.graph] if hasattr(module, "graph") else [] - except RuntimeError: - graphs = [] - - if hasattr(module, "forward1"): - graphs.append(module.forward1.graph) - - for graph in graphs: - for node in graph.findAllNodes("aten::to"): - inputs = list(node.inputs()) - for i in [ - 1, - 2, - ]: # dtype can be the second or third argument to aten::to() - if inputs[i].node()["value"] == 5: - inputs[i].node().copyAttributes(float_node) - - model.apply(patch_float) - patch_float(model.encode_audio) - patch_float(model.encode_text) - model.float() - - model.audio_branch.audio_length = model.audio_cfg.audio_length - return model diff --git a/spaces/dev-andres/Caracola-app/models/variables_globales.py b/spaces/dev-andres/Caracola-app/models/variables_globales.py deleted file mode 100644 index a0ea38e041476b2f7f1d1eafc29d72e1ff647c72..0000000000000000000000000000000000000000 --- a/spaces/dev-andres/Caracola-app/models/variables_globales.py +++ /dev/null @@ -1,150 +0,0 @@ -def numero(text): - """Convierte un texto de numero en numero entero (int) - - Parametros - ---------- - text: list - Serie de valores - - Regresa - --------- - dict_numeros: int - El número correspondiente - """ - global dict_numeros - # Como sabemos que siempre sera el primer elemento el valor despues - # de número (eg. cuatro or veintecinco) - numero_str = text[0] - return dict_numeros[numero_str] - -def flotante(text): - """Convierte un texto de numero en numero floatante (float) - - Parametros - ---------- - text: list - Serie de valores - - Regresa - --------- - dict_numeros: float - El número correspondiente en floatante (eg 3.4) - """ - global dict_numeros - text = " ".join(text) - before_keyword, keyword, after_keyword = text.partition('punto') - print(before_keyword) - print(after_keyword) - - # Obtenemos los dos numeros antes y despues del punto - before_num = before_keyword.strip().split(' ')[0] - after_num = after_keyword.strip().split(' ')[0] - - # Hacemos el mapeo uno -> 1 - num1_int = dict_numeros[before_num] - num2_int = dict_numeros[after_num] - - return float(str(num1_int) + '.' + str(num2_int)) - -def cadena(text): - """Convierte un texto de numero en string (str) - - Parametros - ---------- - text: list - Serie de valores - - Regresa - --------- - string: str - Una cadena con el contenido del texto - """ - numero_str = text[:] - return ' '.join(text) - -def lista(text): - """Convierte un texto de numero en string (str) - - Parametros - ---------- - text: list - Serie de valores - - Regresa - --------- - lista: list - Una lista vacia - """ - return [] - - - -diccionario_fonetico={'andrea':'a', - 'bravo':'b', - 'carlos':'c', - 'delta':'d', - 'eduardo':'e', - 'fernando':'f', - 'garcia':'g', - 'hotel':'h', - 'india':'i', - 'julieta':'j', - 'kilo':'k', - 'lima':'l', - 'miguel':'m', - 'noviembre':'n', - 'oscar':'o', - 'papa':'p', - 'queretaro':'q', - 'romero':'', - 'sierra':'s', - 'tango':'t', - 'uniforme':'u', - 'victor':'v', - 'wafle':'w', - 'equis':'x', - 'yarda':'y', - 'llarda':'y', - 'espacio':' '} - -# Separa en operadores comunes - -# si esto se lematiza puedes agarrar todas las frases de la forma suma, sumar, etc. -dict_operaciones={ - 'producto':'*','mas':'+','menos':'-','concatena':'+','entre':'/','modulo':'%' - } - -dict_numeros = { - 'cero':0, - 'uno': 1, - 'dos': 2, - 'tres': 3, - 'cuatro':4, - 'cinco': 5, - 'seis': 6, - 'siete': 7, - 'ocho': 8, - 'nueve': 9, - 'diez': 10, - 'once': 11, - 'doce': 12, - 'trece': 13, - 'catorce': 14, - 'quince': 15, - 'dieciseis': 16, - 'diecisiete': 17, - 'dieciocho': 18, - 'diecinueve': 19, - 'veinte': 20, - 'treinta': 30, - 'cuarenta': 40, - 'cicuenta': 50, -} - -# Diccionario de funciones -tipos_datos ={ - 'natural': numero, - 'flotante': flotante, - 'cadena': cadena, - 'lista': lista, -} \ No newline at end of file diff --git a/spaces/diacanFperku/AutoGPT/!!INSTALL!! Download Ecap V1014 Webcam 35.md b/spaces/diacanFperku/AutoGPT/!!INSTALL!! Download Ecap V1014 Webcam 35.md deleted file mode 100644 index 1ccf1fd29d41b8c9c192ece78f9c36a981e5ebe7..0000000000000000000000000000000000000000 --- a/spaces/diacanFperku/AutoGPT/!!INSTALL!! Download Ecap V1014 Webcam 35.md +++ /dev/null @@ -1,32 +0,0 @@ -
-

How to Download Ecap V1014 Webcam 35 Driver for Windows

-

If you have a webcam model Ecap V1014 Webcam 35 and you want to use it on your Windows PC, you need to download and install the correct driver for it. A driver is a software that allows your computer to communicate with your webcam and use its features. Without a driver, your webcam may not work properly or at all.

-

Download Ecap V1014 Webcam 35


Download ✦✦✦ https://gohhs.com/2uFTNE



-

In this article, we will show you how to download Ecap V1014 Webcam 35 driver for Windows from a reliable source and how to install it on your PC. Follow these steps:

-
    -
  1. Go to https://www.updatestar.com/en/topic/webcam%20ecap, a website that offers free webcam ecap software downloads.
  2. -
  3. Scroll down and find the section that says "webcam ecap Related searches". Click on the link that says "download webcam ecap-1.0.0.9". This is the latest version of the driver for Ecap V1014 Webcam 35.
  4. -
  5. You will be redirected to another page where you can download the driver file. Click on the green button that says "Download". Save the file to your computer.
  6. -
  7. Once the download is complete, locate the file on your computer and double-click on it to run it. Follow the instructions on the screen to install the driver.
  8. -
  9. After the installation is done, restart your computer and plug in your webcam. Your webcam should be detected by your PC and ready to use.
  10. -
-

Congratulations! You have successfully downloaded and installed Ecap V1014 Webcam 35 driver for Windows. Now you can enjoy using your webcam for video calls, online meetings, or recording videos.

- -

If you want to use Ecap V1014 Webcam 35 for video calls or online meetings, you need to have a compatible software that supports your webcam. Some of the popular software that you can use are Skype, Zoom, Microsoft Teams, Google Meet, and Facebook Messenger. You can download these software from their official websites or from the Windows Store.

-

To use Ecap V1014 Webcam 35 for video calls or online meetings, follow these steps:

-

-
    -
  1. Launch the software that you want to use and sign in with your account.
  2. -
  3. Go to the settings or preferences of the software and select your webcam as the video source. You may also need to select your microphone and speakers as the audio source and output.
  4. -
  5. Start a video call or join an online meeting with your contacts. You should be able to see yourself and others on the screen.
  6. -
-

If you want to use Ecap V1014 Webcam 35 for recording videos, you need to have a software that can capture and edit videos from your webcam. Some of the popular software that you can use are Windows Camera, OBS Studio, VLC Media Player, and Camtasia. You can download these software from their official websites or from the Windows Store.

-

To use Ecap V1014 Webcam 35 for recording videos, follow these steps:

-
    -
  1. Launch the software that you want to use and adjust the settings according to your preferences. You may need to select your webcam as the video source and choose the resolution, frame rate, quality, and format of the video.
  2. -
  3. Click on the record button to start capturing video from your webcam. You can also pause or stop the recording at any time.
  4. -
  5. Save the video file to your computer or edit it with the software if you want to add effects, transitions, captions, or music.
  6. -
-

We hope this article has helped you learn how to download Ecap V1014 Webcam 35 driver for Windows and how to use it for various purposes. If you have any questions or problems with your webcam, please contact the manufacturer or visit their website for more information.

d5da3c52bf
-
-
\ No newline at end of file diff --git a/spaces/diacanFperku/AutoGPT/Chhota Bheem And The Throne Of Bali Full !EXCLUSIVE! Movie Download Mp4 720p.md b/spaces/diacanFperku/AutoGPT/Chhota Bheem And The Throne Of Bali Full !EXCLUSIVE! Movie Download Mp4 720p.md deleted file mode 100644 index a7553bb3b66b3f3c58755a63fbc5a267d4f7d161..0000000000000000000000000000000000000000 --- a/spaces/diacanFperku/AutoGPT/Chhota Bheem And The Throne Of Bali Full !EXCLUSIVE! Movie Download Mp4 720p.md +++ /dev/null @@ -1,6 +0,0 @@ -

Chhota Bheem and the throne of Bali full movie download mp4 720p


Download Filehttps://gohhs.com/2uFTMV



-
-Download Chhota Bheem The Throne Of Bali Full Movie In Tamil play in 3GP MP4 FLV MP3 available in 240p, 360p, 720p, 1080p video formats Free Download ... 4d29de3e1b
-
-
-

diff --git a/spaces/diacanFperku/AutoGPT/Region Of Interest After Effects Cs4 Serial Number.md b/spaces/diacanFperku/AutoGPT/Region Of Interest After Effects Cs4 Serial Number.md deleted file mode 100644 index 2956fade3f2ff691353ef33622382d44512d6f45..0000000000000000000000000000000000000000 --- a/spaces/diacanFperku/AutoGPT/Region Of Interest After Effects Cs4 Serial Number.md +++ /dev/null @@ -1,10 +0,0 @@ -

region of interest after effects cs4 serial number


Download Ziphttps://gohhs.com/2uFVwX



-
-January 29, 2021 - Find solutions for serial number errors you may encounter when trying to... Applies to: Adobe After Effects CS5 Adobe After Effects CS5.5 Adobe ... Jump to: navigation. Search -Serial Number Errors - Serial number errors occur when trying to activate, update, or download software - which may result in an error message. -There are a large number of types of serial number errors, the most common of which are: -Error "The application failed to start because an unexpected error occurred while it was initializing" -"The software package was not found" error 8a78ff9644
-
-
-

diff --git a/spaces/digitalxingtong/Xingtong-Read-Dongmuchang-Bert-VITS2/utils.py b/spaces/digitalxingtong/Xingtong-Read-Dongmuchang-Bert-VITS2/utils.py deleted file mode 100644 index c6aa6cfc64c33e2eed33e9845239e831fc1c4a1a..0000000000000000000000000000000000000000 --- a/spaces/digitalxingtong/Xingtong-Read-Dongmuchang-Bert-VITS2/utils.py +++ /dev/null @@ -1,293 +0,0 @@ -import os -import glob -import sys -import argparse -import logging -import json -import subprocess -import numpy as np -from scipy.io.wavfile import read -import torch - -MATPLOTLIB_FLAG = False - -logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) -logger = logging - - -def load_checkpoint(checkpoint_path, model, optimizer=None, skip_optimizer=False): - assert os.path.isfile(checkpoint_path) - checkpoint_dict = torch.load(checkpoint_path, map_location='cpu') - iteration = checkpoint_dict['iteration'] - learning_rate = checkpoint_dict['learning_rate'] - if optimizer is not None and not skip_optimizer and checkpoint_dict['optimizer'] is not None: - optimizer.load_state_dict(checkpoint_dict['optimizer']) - elif optimizer is None and not skip_optimizer: - #else: #Disable this line if Infer ,and enable the line upper - new_opt_dict = optimizer.state_dict() - new_opt_dict_params = new_opt_dict['param_groups'][0]['params'] - new_opt_dict['param_groups'] = checkpoint_dict['optimizer']['param_groups'] - new_opt_dict['param_groups'][0]['params'] = new_opt_dict_params - optimizer.load_state_dict(new_opt_dict) - saved_state_dict = checkpoint_dict['model'] - if hasattr(model, 'module'): - state_dict = model.module.state_dict() - else: - state_dict = model.state_dict() - new_state_dict = {} - for k, v in state_dict.items(): - try: - #assert "emb_g" not in k - # print("load", k) - new_state_dict[k] = saved_state_dict[k] - assert saved_state_dict[k].shape == v.shape, (saved_state_dict[k].shape, v.shape) - except: - print("error, %s is not in the checkpoint" % k) - new_state_dict[k] = v - if hasattr(model, 'module'): - model.module.load_state_dict(new_state_dict, strict=False) - else: - model.load_state_dict(new_state_dict, strict=False) - print("load ") - logger.info("Loaded checkpoint '{}' (iteration {})".format( - checkpoint_path, iteration)) - return model, optimizer, learning_rate, iteration - - -def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path): - logger.info("Saving model and optimizer state at iteration {} to {}".format( - iteration, checkpoint_path)) - if hasattr(model, 'module'): - state_dict = model.module.state_dict() - else: - state_dict = model.state_dict() - torch.save({'model': state_dict, - 'iteration': iteration, - 'optimizer': optimizer.state_dict(), - 'learning_rate': learning_rate}, checkpoint_path) - - -def summarize(writer, global_step, scalars={}, histograms={}, images={}, audios={}, audio_sampling_rate=22050): - for k, v in scalars.items(): - writer.add_scalar(k, v, global_step) - for k, v in histograms.items(): - writer.add_histogram(k, v, global_step) - for k, v in images.items(): - writer.add_image(k, v, global_step, dataformats='HWC') - for k, v in audios.items(): - writer.add_audio(k, v, global_step, audio_sampling_rate) - - -def latest_checkpoint_path(dir_path, regex="G_*.pth"): - f_list = glob.glob(os.path.join(dir_path, regex)) - f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f)))) - x = f_list[-1] - print(x) - return x - - -def plot_spectrogram_to_numpy(spectrogram): - global MATPLOTLIB_FLAG - if not MATPLOTLIB_FLAG: - import matplotlib - matplotlib.use("Agg") - MATPLOTLIB_FLAG = True - mpl_logger = logging.getLogger('matplotlib') - mpl_logger.setLevel(logging.WARNING) - import matplotlib.pylab as plt - import numpy as np - - fig, ax = plt.subplots(figsize=(10, 2)) - im = ax.imshow(spectrogram, aspect="auto", origin="lower", - interpolation='none') - plt.colorbar(im, ax=ax) - plt.xlabel("Frames") - plt.ylabel("Channels") - plt.tight_layout() - - fig.canvas.draw() - data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') - data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) - plt.close() - return data - - -def plot_alignment_to_numpy(alignment, info=None): - global MATPLOTLIB_FLAG - if not MATPLOTLIB_FLAG: - import matplotlib - matplotlib.use("Agg") - MATPLOTLIB_FLAG = True - mpl_logger = logging.getLogger('matplotlib') - mpl_logger.setLevel(logging.WARNING) - import matplotlib.pylab as plt - import numpy as np - - fig, ax = plt.subplots(figsize=(6, 4)) - im = ax.imshow(alignment.transpose(), aspect='auto', origin='lower', - interpolation='none') - fig.colorbar(im, ax=ax) - xlabel = 'Decoder timestep' - if info is not None: - xlabel += '\n\n' + info - plt.xlabel(xlabel) - plt.ylabel('Encoder timestep') - plt.tight_layout() - - fig.canvas.draw() - data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') - data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) - plt.close() - return data - - -def load_wav_to_torch(full_path): - sampling_rate, data = read(full_path) - return torch.FloatTensor(data.astype(np.float32)), sampling_rate - - -def load_filepaths_and_text(filename, split="|"): - with open(filename, encoding='utf-8') as f: - filepaths_and_text = [line.strip().split(split) for line in f] - return filepaths_and_text - - -def get_hparams(init=True): - parser = argparse.ArgumentParser() - parser.add_argument('-c', '--config', type=str, default="./configs/base.json", - help='JSON file for configuration') - parser.add_argument('-m', '--model', type=str, default="./OUTPUT_MODEL", - help='Model name') - parser.add_argument('--cont', dest='cont', action="store_true", default=False, help="whether to continue training on the latest checkpoint") - - args = parser.parse_args() - model_dir = os.path.join("./logs", args.model) - - if not os.path.exists(model_dir): - os.makedirs(model_dir) - - config_path = args.config - config_save_path = os.path.join(model_dir, "config.json") - if init: - with open(config_path, "r") as f: - data = f.read() - with open(config_save_path, "w") as f: - f.write(data) - else: - with open(config_save_path, "r") as f: - data = f.read() - config = json.loads(data) - - hparams = HParams(**config) - hparams.model_dir = model_dir - hparams.cont = args.cont - return hparams - - -def clean_checkpoints(path_to_models='logs/44k/', n_ckpts_to_keep=2, sort_by_time=True): - """Freeing up space by deleting saved ckpts - - Arguments: - path_to_models -- Path to the model directory - n_ckpts_to_keep -- Number of ckpts to keep, excluding G_0.pth and D_0.pth - sort_by_time -- True -> chronologically delete ckpts - False -> lexicographically delete ckpts - """ - import re - ckpts_files = [f for f in os.listdir(path_to_models) if os.path.isfile(os.path.join(path_to_models, f))] - name_key = (lambda _f: int(re.compile('._(\d+)\.pth').match(_f).group(1))) - time_key = (lambda _f: os.path.getmtime(os.path.join(path_to_models, _f))) - sort_key = time_key if sort_by_time else name_key - x_sorted = lambda _x: sorted([f for f in ckpts_files if f.startswith(_x) and not f.endswith('_0.pth')], - key=sort_key) - to_del = [os.path.join(path_to_models, fn) for fn in - (x_sorted('G')[:-n_ckpts_to_keep] + x_sorted('D')[:-n_ckpts_to_keep])] - del_info = lambda fn: logger.info(f".. Free up space by deleting ckpt {fn}") - del_routine = lambda x: [os.remove(x), del_info(x)] - rs = [del_routine(fn) for fn in to_del] - -def get_hparams_from_dir(model_dir): - config_save_path = os.path.join(model_dir, "config.json") - with open(config_save_path, "r") as f: - data = f.read() - config = json.loads(data) - - hparams = HParams(**config) - hparams.model_dir = model_dir - return hparams - - -def get_hparams_from_file(config_path): - with open(config_path, "r") as f: - data = f.read() - config = json.loads(data) - - hparams = HParams(**config) - return hparams - - -def check_git_hash(model_dir): - source_dir = os.path.dirname(os.path.realpath(__file__)) - if not os.path.exists(os.path.join(source_dir, ".git")): - logger.warn("{} is not a git repository, therefore hash value comparison will be ignored.".format( - source_dir - )) - return - - cur_hash = subprocess.getoutput("git rev-parse HEAD") - - path = os.path.join(model_dir, "githash") - if os.path.exists(path): - saved_hash = open(path).read() - if saved_hash != cur_hash: - logger.warn("git hash values are different. {}(saved) != {}(current)".format( - saved_hash[:8], cur_hash[:8])) - else: - open(path, "w").write(cur_hash) - - -def get_logger(model_dir, filename="train.log"): - global logger - logger = logging.getLogger(os.path.basename(model_dir)) - logger.setLevel(logging.DEBUG) - - formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s") - if not os.path.exists(model_dir): - os.makedirs(model_dir) - h = logging.FileHandler(os.path.join(model_dir, filename)) - h.setLevel(logging.DEBUG) - h.setFormatter(formatter) - logger.addHandler(h) - return logger - - -class HParams(): - def __init__(self, **kwargs): - for k, v in kwargs.items(): - if type(v) == dict: - v = HParams(**v) - self[k] = v - - def keys(self): - return self.__dict__.keys() - - def items(self): - return self.__dict__.items() - - def values(self): - return self.__dict__.values() - - def __len__(self): - return len(self.__dict__) - - def __getitem__(self, key): - return getattr(self, key) - - def __setitem__(self, key, value): - return setattr(self, key, value) - - def __contains__(self, key): - return key in self.__dict__ - - def __repr__(self): - return self.__dict__.__repr__() diff --git a/spaces/dinhminh20521597/OCR_DEMO/configs/_base_/recog_models/seg.py b/spaces/dinhminh20521597/OCR_DEMO/configs/_base_/recog_models/seg.py deleted file mode 100644 index 291e547ff45de81ddd512bf04ce0af7957b89ae7..0000000000000000000000000000000000000000 --- a/spaces/dinhminh20521597/OCR_DEMO/configs/_base_/recog_models/seg.py +++ /dev/null @@ -1,21 +0,0 @@ -label_convertor = dict( - type='SegConvertor', dict_type='DICT36', with_unknown=True, lower=True) - -model = dict( - type='SegRecognizer', - backbone=dict( - type='ResNet31OCR', - layers=[1, 2, 5, 3], - channels=[32, 64, 128, 256, 512, 512], - out_indices=[0, 1, 2, 3], - stage4_pool_cfg=dict(kernel_size=2, stride=2), - last_stage_pool=True), - neck=dict( - type='FPNOCR', in_channels=[128, 256, 512, 512], out_channels=256), - head=dict( - type='SegHead', - in_channels=256, - upsample_param=dict(scale_factor=2.0, mode='nearest')), - loss=dict( - type='SegLoss', seg_downsample_ratio=1.0, seg_with_loss_weight=True), - label_convertor=label_convertor) diff --git a/spaces/dirge/voicevox/voicevox_engine/dev/synthesis_engine/mock.py b/spaces/dirge/voicevox/voicevox_engine/dev/synthesis_engine/mock.py deleted file mode 100644 index 3a1b47ac3ca86560a9cc4a379890a9c9609d1d4a..0000000000000000000000000000000000000000 --- a/spaces/dirge/voicevox/voicevox_engine/dev/synthesis_engine/mock.py +++ /dev/null @@ -1,136 +0,0 @@ -from logging import getLogger -from typing import Any, Dict, List, Optional - -import numpy as np -from pyopenjtalk import tts -from scipy.signal import resample - -from ...model import AccentPhrase, AudioQuery -from ...synthesis_engine import SynthesisEngineBase -from ...synthesis_engine.synthesis_engine import to_flatten_moras - - -class MockSynthesisEngine(SynthesisEngineBase): - """ - SynthesisEngine [Mock] - """ - - def __init__( - self, - speakers: str, - supported_devices: Optional[str] = None, - ): - """ - __init__ [Mock] - """ - super().__init__() - - self._speakers = speakers - self._supported_devices = supported_devices - self.default_sampling_rate = 24000 - - @property - def speakers(self) -> str: - return self._speakers - - @property - def supported_devices(self) -> Optional[str]: - return self._supported_devices - - def replace_phoneme_length( - self, accent_phrases: List[AccentPhrase], speaker_id: int - ) -> List[AccentPhrase]: - """ - replace_phoneme_length 入力accent_phrasesを変更せずにそのまま返します [Mock] - - Parameters - ---------- - accent_phrases : List[AccentPhrase] - フレーズ句のリスト - speaker_id : int - 話者 - - Returns - ------- - List[AccentPhrase] - フレーズ句のリスト(変更なし) - """ - return accent_phrases - - def replace_mora_pitch( - self, accent_phrases: List[AccentPhrase], speaker_id: int - ) -> List[AccentPhrase]: - """ - replace_mora_pitch 入力accent_phrasesを変更せずにそのまま返します [Mock] - - Parameters - ---------- - accent_phrases : List[AccentPhrase] - フレーズ句のリスト - speaker_id : int - 話者 - - Returns - ------- - List[AccentPhrase] - フレーズ句のリスト(変更なし) - """ - return accent_phrases - - def _synthesis_impl(self, query: AudioQuery, speaker_id: int) -> np.ndarray: - """ - synthesis voicevox coreを使わずに、音声合成する [Mock] - - Parameters - ---------- - query : AudioQuery - /audio_query APIで得たjson - speaker_id : int - 話者 - - Returns - ------- - wave [npt.NDArray[np.int16]] - 音声波形データをNumPy配列で返します - """ - # recall text in katakana - flatten_moras = to_flatten_moras(query.accent_phrases) - kana_text = "".join([mora.text for mora in flatten_moras]) - - wave = self.forward(kana_text) - - # volume - wave *= query.volumeScale - - return wave.astype("int16") - - def forward(self, text: str, **kwargs: Dict[str, Any]) -> np.ndarray: - """ - forward tts via pyopenjtalk.tts() - 参照→SynthesisEngine のdocstring [Mock] - - Parameters - ---------- - text : str - 入力文字列(例:読み上げたい文章をカタカナにした文字列、等) - - Returns - ------- - wave [npt.NDArray[np.int16]] - 音声波形データをNumPy配列で返します - - Note - ------- - ここで行う音声合成では、調声(ピッチ等)を反映しない - - # pyopenjtalk.tts()の出力仕様 - dtype=np.float64, 16 bit, mono 48000 Hz - - # resampleの説明 - 非モック実装(decode_forward)と合わせるために、出力を24kHzに変換した。 - """ - logger = getLogger("uvicorn") # FastAPI / Uvicorn 内からの利用のため - logger.info("[Mock] input text: %s" % text) - wave, sr = tts(text) - wave = resample(wave, 24000 * len(wave) // 48000) - return wave diff --git a/spaces/doevent/blip/data/flickr30k_dataset.py b/spaces/doevent/blip/data/flickr30k_dataset.py deleted file mode 100644 index 018ab387014ddaf554c4d3184cfc0e2ba8b2d487..0000000000000000000000000000000000000000 --- a/spaces/doevent/blip/data/flickr30k_dataset.py +++ /dev/null @@ -1,93 +0,0 @@ -import os -import json - -from torch.utils.data import Dataset -from torchvision.datasets.utils import download_url - -from PIL import Image - -from data.utils import pre_caption - -class flickr30k_train(Dataset): - def __init__(self, transform, image_root, ann_root, max_words=30, prompt=''): - ''' - image_root (string): Root directory of images (e.g. flickr30k/) - ann_root (string): directory to store the annotation file - ''' - url = 'https://storage.googleapis.com/sfr-vision-language-research/datasets/flickr30k_train.json' - filename = 'flickr30k_train.json' - - download_url(url,ann_root) - - self.annotation = json.load(open(os.path.join(ann_root,filename),'r')) - self.transform = transform - self.image_root = image_root - self.max_words = max_words - self.prompt = prompt - - self.img_ids = {} - n = 0 - for ann in self.annotation: - img_id = ann['image_id'] - if img_id not in self.img_ids.keys(): - self.img_ids[img_id] = n - n += 1 - - def __len__(self): - return len(self.annotation) - - def __getitem__(self, index): - - ann = self.annotation[index] - - image_path = os.path.join(self.image_root,ann['image']) - image = Image.open(image_path).convert('RGB') - image = self.transform(image) - - caption = self.prompt+pre_caption(ann['caption'], self.max_words) - - return image, caption, self.img_ids[ann['image_id']] - - -class flickr30k_retrieval_eval(Dataset): - def __init__(self, transform, image_root, ann_root, split, max_words=30): - ''' - image_root (string): Root directory of images (e.g. flickr30k/) - ann_root (string): directory to store the annotation file - split (string): val or test - ''' - urls = {'val':'https://storage.googleapis.com/sfr-vision-language-research/datasets/flickr30k_val.json', - 'test':'https://storage.googleapis.com/sfr-vision-language-research/datasets/flickr30k_test.json'} - filenames = {'val':'flickr30k_val.json','test':'flickr30k_test.json'} - - download_url(urls[split],ann_root) - - self.annotation = json.load(open(os.path.join(ann_root,filenames[split]),'r')) - self.transform = transform - self.image_root = image_root - - self.text = [] - self.image = [] - self.txt2img = {} - self.img2txt = {} - - txt_id = 0 - for img_id, ann in enumerate(self.annotation): - self.image.append(ann['image']) - self.img2txt[img_id] = [] - for i, caption in enumerate(ann['caption']): - self.text.append(pre_caption(caption,max_words)) - self.img2txt[img_id].append(txt_id) - self.txt2img[txt_id] = img_id - txt_id += 1 - - def __len__(self): - return len(self.annotation) - - def __getitem__(self, index): - - image_path = os.path.join(self.image_root, self.annotation[index]['image']) - image = Image.open(image_path).convert('RGB') - image = self.transform(image) - - return image, index \ No newline at end of file diff --git a/spaces/dorkai/singpt-2.0/README.md b/spaces/dorkai/singpt-2.0/README.md deleted file mode 100644 index 18d6e731c05a15211eb837baf14c858004b1a552..0000000000000000000000000000000000000000 --- a/spaces/dorkai/singpt-2.0/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: SinGPT-2.0 Web -emoji: ⚡ -colorFrom: yellow -colorTo: purple -sdk: gradio -sdk_version: 3.20.1 -app_file: run.py -pinned: true -license: mit -duplicated_from: Devops-hestabit/text-generation-webui-space ---- - -Check out this repo https://github.com/oobabooga/text-generation-webui \ No newline at end of file diff --git a/spaces/dorkai/text-generation-webui-main/modules/evaluate.py b/spaces/dorkai/text-generation-webui-main/modules/evaluate.py deleted file mode 100644 index adafa7137f8a676fee0595aa987dc37179561340..0000000000000000000000000000000000000000 --- a/spaces/dorkai/text-generation-webui-main/modules/evaluate.py +++ /dev/null @@ -1,144 +0,0 @@ -import datetime -import traceback -from pathlib import Path - -import pandas as pd -import torch -from datasets import load_dataset -from tqdm import tqdm - -from modules import shared -from modules.models import load_model, unload_model -from modules.text_generation import encode -from server import get_model_specific_settings, update_model_parameters - - -def load_past_evaluations(): - if Path('logs/evaluations.csv').exists(): - df = pd.read_csv(Path('logs/evaluations.csv'), dtype=str) - df['Perplexity'] = pd.to_numeric(df['Perplexity']) - return df - else: - return pd.DataFrame(columns=['Model', 'LoRAs', 'Dataset', 'Perplexity', 'stride', 'max_length', 'Date', 'Comment']) - - -past_evaluations = load_past_evaluations() - - -def save_past_evaluations(df): - global past_evaluations - past_evaluations = df - df.to_csv(Path('logs/evaluations.csv'), index=False) - - -def calculate_perplexity(models, input_dataset, stride, _max_length): - ''' - Based on: - https://huggingface.co/docs/transformers/perplexity#calculating-ppl-with-fixedlength-models - ''' - - global past_evaluations - cumulative_log = '' - cumulative_log += "Loading the input dataset...\n" - yield cumulative_log - - # Copied from https://github.com/qwopqwop200/GPTQ-for-LLaMa/blob/triton/utils/datautils.py - if input_dataset == 'wikitext': - data = load_dataset('wikitext', 'wikitext-2-raw-v1', split='test') - text = "\n\n".join(data['text']) - elif input_dataset == 'ptb': - data = load_dataset('ptb_text_only', 'penn_treebank', split='validation') - text = "\n\n".join(data['sentence']) - elif input_dataset == 'ptb_new': - data = load_dataset('ptb_text_only', 'penn_treebank', split='test') - text = " ".join(data['sentence']) - else: - with open(Path(f'training/datasets/{input_dataset}.txt'), 'r', encoding='utf-8') as f: - text = f.read() - - for model in models: - if is_in_past_evaluations(model, input_dataset, stride, _max_length): - cumulative_log += f"{model} has already been tested. Ignoring.\n" - yield cumulative_log - continue - - if model != 'current model': - try: - yield cumulative_log + f"Loading {model}...\n" - model_settings = get_model_specific_settings(model) - shared.settings.update(model_settings) # hijacking the interface defaults - update_model_parameters(model_settings) # hijacking the command-line arguments - shared.model_name = model - unload_model() - shared.model, shared.tokenizer = load_model(shared.model_name) - except: - cumulative_log += f"Failed to load {model}. Moving on.\n" - yield cumulative_log - continue - - cumulative_log += f"Processing {model}...\n" - yield cumulative_log + "Tokenizing the input dataset...\n" - encodings = encode(text, add_special_tokens=False) - seq_len = encodings.shape[1] - max_length = _max_length or shared.model.config.max_position_embeddings - nlls = [] - prev_end_loc = 0 - for begin_loc in tqdm(range(0, seq_len, stride)): - yield cumulative_log + f"Evaluating... {100*begin_loc/seq_len:.2f}%" - end_loc = min(begin_loc + max_length, seq_len) - trg_len = end_loc - prev_end_loc # may be different from stride on last loop - input_ids = encodings[:, begin_loc:end_loc] - target_ids = input_ids.clone() - target_ids[:, :-trg_len] = -100 - - with torch.no_grad(): - outputs = shared.model(input_ids, labels=target_ids) - - # loss is calculated using CrossEntropyLoss which averages over valid labels - # N.B. the model only calculates loss over trg_len - 1 labels, because it internally shifts the labels - # to the left by 1. - neg_log_likelihood = outputs.loss - - nlls.append(neg_log_likelihood) - - prev_end_loc = end_loc - if end_loc == seq_len: - break - - ppl = torch.exp(torch.stack(nlls).mean()) - add_entry_to_past_evaluations(float(ppl), shared.model_name, input_dataset, stride, _max_length) - save_past_evaluations(past_evaluations) - cumulative_log += f"Done. The perplexity is: {float(ppl)}\n\n" - yield cumulative_log - - -def add_entry_to_past_evaluations(perplexity, model, dataset, stride, max_length): - global past_evaluations - entry = { - 'Model': model, - 'LoRAs': ', '.join(shared.lora_names) or '-', - 'Dataset': dataset, - 'Perplexity': perplexity, - 'stride': str(stride), - 'max_length': str(max_length), - 'Date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), - 'Comment': '' - } - past_evaluations = pd.concat([past_evaluations, pd.DataFrame([entry])], ignore_index=True) - - -def is_in_past_evaluations(model, dataset, stride, max_length): - entries = past_evaluations[(past_evaluations['Model'] == model) & - (past_evaluations['Dataset'] == dataset) & - (past_evaluations['max_length'] == str(max_length)) & - (past_evaluations['stride'] == str(stride))] - - if entries.shape[0] > 0: - return True - else: - return False - - -def generate_markdown_table(): - sorted_df = past_evaluations.sort_values(by=['Dataset', 'stride', 'Perplexity', 'Date']) - return sorted_df diff --git a/spaces/dylanebert/gaussian-viewer/public/_app/immutable/nodes/2.f3e7c0be.js b/spaces/dylanebert/gaussian-viewer/public/_app/immutable/nodes/2.f3e7c0be.js deleted file mode 100644 index 5085c63c56f6e9d6f02db7034e3f8fff2635787c..0000000000000000000000000000000000000000 --- a/spaces/dylanebert/gaussian-viewer/public/_app/immutable/nodes/2.f3e7c0be.js +++ /dev/null @@ -1,3 +0,0 @@ -import{s as B,n as x,o as J,f as V,h as z}from"../chunks/scheduler.8b74b908.js";import{S as A,i as H,g as y,s as G,h as _,j as I,c as F,y as L,f as g,k as v,a as k,x as P}from"../chunks/index.c146e4e6.js";function K(f){let e,s;return{c(){e=y("video"),this.h()},l(t){e=_(t,"VIDEO",{id:!0,src:!0,class:!0}),I(e).forEach(g),this.h()},h(){v(e,"id","player"),z(e.src,s="")||v(e,"src",s),e.autoplay=!0,e.muted=!0,e.controls=!0,e.playsInline=!0,v(e,"class","svelte-129dyx6")},m(t,d){k(t,e,d)},d(t){t&&g(e)}}}function Q(f){let e,s="Loading...";return{c(){e=y("div"),e.textContent=s},l(t){e=_(t,"DIV",{"data-svelte-h":!0}),L(e)!=="svelte-194gxkm"&&(e.textContent=s)},m(t,d){k(t,e,d)},d(t){t&&g(e)}}}function U(f){let e,s,t,d=`paper | - code | - explanation`;function p(a,i){return a[0]?Q:K}let h=p(f),r=h(f);return{c(){e=y("main"),r.c(),s=G(),t=y("p"),t.innerHTML=d,this.h()},l(a){e=_(a,"MAIN",{class:!0});var i=I(e);r.l(i),s=F(i),t=_(i,"P",{"data-svelte-h":!0}),L(t)!=="svelte-1pku6pp"&&(t.innerHTML=d),i.forEach(g),this.h()},h(){v(e,"class","svelte-129dyx6")},m(a,i){k(a,e,i),r.m(e,null),P(e,s),P(e,t)},p(a,[i]){h!==(h=p(a))&&(r.d(1),r=h(a),r&&(r.c(),r.m(e,s)))},i:x,o:x,d(a){a&&g(e),r.d()}}}const w=3;async function W(f,e){const s=JSON.stringify(f);console.log("Sending ICE candidate: ",s),await fetch(`https://viewer.dylanebert.com/ice-candidate?session_id=${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:s})}function Z(f,e,s){let t,d,p,h,r=!0,a=!1,i=30,m=45,C=[0,.5,0],M=0,T=0;J(async()=>{const n=Math.random().toString(36).substring(2,15);await O(n);const o=document.querySelector("main");o.addEventListener("mousedown",()=>a=!0),o.addEventListener("mouseup",()=>a=!1),o.addEventListener("mousemove",R),o.addEventListener("touchstart",Y),o.addEventListener("touchmove",j),o.addEventListener("touchend",()=>a=!1),s(0,r=!1)}),V(()=>{t&&t.close()});async function O(n){console.log("Requesting ICE servers...");var c={iceServers:await fetch("https://viewer.dylanebert.com/ice-servers",{method:"GET",headers:{"Content-Type":"application/json"}}).then(l=>l.json())};console.log("Creating RTCPeerConnection with config: ",c),t=new RTCPeerConnection(c),t.addTransceiver("video",{direction:"recvonly"});let u=[];t.onicecandidate=async({candidate:l})=>{l&&u.push(l)},t.ontrack=l=>{console.log("Received track:",l),h=document.getElementById("player"),h.onerror=$=>{console.error("Error: ",$)},h.srcObject=l.streams[0]},d=t.createDataChannel("camera");const D={offerToReceiveAudio:!1,offerToReceiveVideo:!0},b=await t.createOffer(D);console.log("Created offer:",b),await t.setLocalDescription(b),s(0,r=!1),console.log("Sending offer SDP: ",b);const E=await fetch(`https://viewer.dylanebert.com/offer?session_id=${n}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sdp:t.localDescription.sdp,type:t.localDescription.type})}).then(l=>l.json());console.log("Received answer SDP: ",E),await t.setRemoteDescription(E),u.forEach(async l=>{await W(l,n)})}function X(n,o){p||(p=setTimeout(()=>{n(),p=null},o))}function Y(n){n.preventDefault(),a=!0;const o=n.touches[0];M=o.clientX,T=o.clientY}function j(n){if(n.preventDefault(),!a)return;const o=n.touches[0],c=o.clientX-M,u=o.clientY-T;M=o.clientX,T=o.clientY,S(c,u)}function R(n){if(!a)return;const o=n.movementX||n.mozMovementX||n.webkitMovementX||0,c=n.movementY||n.mozMovementY||n.webkitMovementY||0;S(o,c)}function S(n,o){m-=n*.5,i+=o*.5,i=Math.min(Math.max(i,0),70),m=(m+360)%360;const c=q(i,m),u=[-i,270-m,0];X(()=>{N(c,u)},1e3/30)}function q(n,o){const c=n*Math.PI/180,u=o*Math.PI/180;return[w*Math.cos(u)*Math.cos(c)+C[0],-w*Math.sin(c)+C[1],w*Math.sin(u)*Math.cos(c)+C[2]]}function N(n,o){const c={type:"camera_update",position:n,rotation:o};d.send(JSON.stringify(c))}return[r]}class ne extends A{constructor(e){super(),H(this,e,Z,U,B,{})}}export{ne as component}; diff --git a/spaces/egmaminta/indoor-scene-recognition-to-speech/README.md b/spaces/egmaminta/indoor-scene-recognition-to-speech/README.md deleted file mode 100644 index c53b0e96a717245f8083ff5db17ed4c1190d007a..0000000000000000000000000000000000000000 --- a/spaces/egmaminta/indoor-scene-recognition-to-speech/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Indoor Scene Recognition-to-Speech -emoji: 🏢 -colorFrom: blue -colorTo: red -sdk: gradio -sdk_version: 2.8.13 -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/ehristoforu/Stable-Diffusion-Protogen-x3.4-webui/README.md b/spaces/ehristoforu/Stable-Diffusion-Protogen-x3.4-webui/README.md deleted file mode 100644 index 90e6021e5563861694379c3eec805e110382f5e4..0000000000000000000000000000000000000000 --- a/spaces/ehristoforu/Stable-Diffusion-Protogen-x3.4-webui/README.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Stable Diffusion Protogen x3.4 Web UI -emoji: ⚛ -colorFrom: pink -colorTo: purple -sdk: docker -app_file: DockerApp.py -pinned: false -duplicated_from: darkstorm2150/Stable-Diffusion-Protogen-x3.4-webui ---- - -### ProtoGen Diffusion model merged by [darkstorm2150](https://twitter.com/Predogl) - -This model was merged on a large amount of data from large datasets new and trending on civitai.com - -You can enforce camera capture by using the prompt with "modelshoot style". - -It should also be very dreamboothable, being able to generate high fidelity faces with a little amount of steps. - -**[By using this model you agree to this license](https://huggingface.co/dreamlike-art/dreamlike-photoreal-2.0/blob/main/LICENSE.md), I the creator darkstorm2150 of this merge and Hugging Face is not liable for any content created by this Protogen Model.** - - - - - - - - - - - - - - -## Other.. - -## Stable Diffusion Web UI -[https://github.com/AUTOMATIC1111/stable-diffusion-webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui) - -## Documentation -[https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki) - -## Models License -https://huggingface.co/spaces/CompVis/stable-diffusion-license \ No newline at end of file diff --git a/spaces/emc348/faces-through-time/models/StyleCLIP/global_directions/dnnlib/tflib/network.py b/spaces/emc348/faces-through-time/models/StyleCLIP/global_directions/dnnlib/tflib/network.py deleted file mode 100644 index ff0c169eabdc579041dac0650fbc6da956646594..0000000000000000000000000000000000000000 --- a/spaces/emc348/faces-through-time/models/StyleCLIP/global_directions/dnnlib/tflib/network.py +++ /dev/null @@ -1,781 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# NVIDIA CORPORATION and its licensors retain all intellectual property -# and proprietary rights in and to this software, related documentation -# and any modifications thereto. Any use, reproduction, disclosure or -# distribution of this software and related documentation without an express -# license agreement from NVIDIA CORPORATION is strictly prohibited. - -"""Helper for managing networks.""" - -import types -import inspect -import re -import uuid -import sys -import copy -import numpy as np -import tensorflow as tf - -from collections import OrderedDict -from typing import Any, List, Tuple, Union, Callable - -from . import tfutil -from .. import util - -from .tfutil import TfExpression, TfExpressionEx - -# pylint: disable=protected-access -# pylint: disable=attribute-defined-outside-init -# pylint: disable=too-many-public-methods - -_import_handlers = [] # Custom import handlers for dealing with legacy data in pickle import. -_import_module_src = dict() # Source code for temporary modules created during pickle import. - - -def import_handler(handler_func): - """Function decorator for declaring custom import handlers.""" - _import_handlers.append(handler_func) - return handler_func - - -class Network: - """Generic network abstraction. - - Acts as a convenience wrapper for a parameterized network construction - function, providing several utility methods and convenient access to - the inputs/outputs/weights. - - Network objects can be safely pickled and unpickled for long-term - archival purposes. The pickling works reliably as long as the underlying - network construction function is defined in a standalone Python module - that has no side effects or application-specific imports. - - Args: - name: Network name. Used to select TensorFlow name and variable scopes. Defaults to build func name if None. - func_name: Fully qualified name of the underlying network construction function, or a top-level function object. - static_kwargs: Keyword arguments to be passed in to the network construction function. - """ - - def __init__(self, name: str = None, func_name: Any = None, **static_kwargs): - # Locate the user-specified build function. - assert isinstance(func_name, str) or util.is_top_level_function(func_name) - if util.is_top_level_function(func_name): - func_name = util.get_top_level_function_name(func_name) - module, func_name = util.get_module_from_obj_name(func_name) - func = util.get_obj_from_module(module, func_name) - - # Dig up source code for the module containing the build function. - module_src = _import_module_src.get(module, None) - if module_src is None: - module_src = inspect.getsource(module) - - # Initialize fields. - self._init_fields(name=(name or func_name), static_kwargs=static_kwargs, build_func=func, build_func_name=func_name, build_module_src=module_src) - - def _init_fields(self, name: str, static_kwargs: dict, build_func: Callable, build_func_name: str, build_module_src: str) -> None: - tfutil.assert_tf_initialized() - assert isinstance(name, str) - assert len(name) >= 1 - assert re.fullmatch(r"[A-Za-z0-9_.\\-]*", name) - assert isinstance(static_kwargs, dict) - assert util.is_pickleable(static_kwargs) - assert callable(build_func) - assert isinstance(build_func_name, str) - assert isinstance(build_module_src, str) - - # Choose TensorFlow name scope. - with tf.name_scope(None): - scope = tf.get_default_graph().unique_name(name, mark_as_used=True) - - # Query current TensorFlow device. - with tfutil.absolute_name_scope(scope), tf.control_dependencies(None): - device = tf.no_op(name="_QueryDevice").device - - # Immutable state. - self._name = name - self._scope = scope - self._device = device - self._static_kwargs = util.EasyDict(copy.deepcopy(static_kwargs)) - self._build_func = build_func - self._build_func_name = build_func_name - self._build_module_src = build_module_src - - # State before _init_graph(). - self._var_inits = dict() # var_name => initial_value, set to None by _init_graph() - self._all_inits_known = False # Do we know for sure that _var_inits covers all the variables? - self._components = None # subnet_name => Network, None if the components are not known yet - - # Initialized by _init_graph(). - self._input_templates = None - self._output_templates = None - self._own_vars = None - - # Cached values initialized the respective methods. - self._input_shapes = None - self._output_shapes = None - self._input_names = None - self._output_names = None - self._vars = None - self._trainables = None - self._var_global_to_local = None - self._run_cache = dict() - - def _init_graph(self) -> None: - assert self._var_inits is not None - assert self._input_templates is None - assert self._output_templates is None - assert self._own_vars is None - - # Initialize components. - if self._components is None: - self._components = util.EasyDict() - - # Choose build func kwargs. - build_kwargs = dict(self.static_kwargs) - build_kwargs["is_template_graph"] = True - build_kwargs["components"] = self._components - - # Override scope and device, and ignore surrounding control dependencies. - with tfutil.absolute_variable_scope(self.scope, reuse=False), tfutil.absolute_name_scope(self.scope), tf.device(self.device), tf.control_dependencies(None): - assert tf.get_variable_scope().name == self.scope - assert tf.get_default_graph().get_name_scope() == self.scope - - # Create input templates. - self._input_templates = [] - for param in inspect.signature(self._build_func).parameters.values(): - if param.kind == param.POSITIONAL_OR_KEYWORD and param.default is param.empty: - self._input_templates.append(tf.placeholder(tf.float32, name=param.name)) - - # Call build func. - out_expr = self._build_func(*self._input_templates, **build_kwargs) - - # Collect output templates and variables. - assert tfutil.is_tf_expression(out_expr) or isinstance(out_expr, tuple) - self._output_templates = [out_expr] if tfutil.is_tf_expression(out_expr) else list(out_expr) - self._own_vars = OrderedDict((var.name[len(self.scope) + 1:].split(":")[0], var) for var in tf.global_variables(self.scope + "/")) - - # Check for errors. - if len(self._input_templates) == 0: - raise ValueError("Network build func did not list any inputs.") - if len(self._output_templates) == 0: - raise ValueError("Network build func did not return any outputs.") - if any(not tfutil.is_tf_expression(t) for t in self._output_templates): - raise ValueError("Network outputs must be TensorFlow expressions.") - if any(t.shape.ndims is None for t in self._input_templates): - raise ValueError("Network input shapes not defined. Please call x.set_shape() for each input.") - if any(t.shape.ndims is None for t in self._output_templates): - raise ValueError("Network output shapes not defined. Please call x.set_shape() where applicable.") - if any(not isinstance(comp, Network) for comp in self._components.values()): - raise ValueError("Components of a Network must be Networks themselves.") - if len(self._components) != len(set(comp.name for comp in self._components.values())): - raise ValueError("Components of a Network must have unique names.") - - # Initialize variables. - if len(self._var_inits): - tfutil.set_vars({self._get_vars()[name]: value for name, value in self._var_inits.items() if name in self._get_vars()}) - remaining_inits = [var.initializer for name, var in self._own_vars.items() if name not in self._var_inits] - if self._all_inits_known: - assert len(remaining_inits) == 0 - else: - tfutil.run(remaining_inits) - self._var_inits = None - - @property - def name(self): - """User-specified name string.""" - return self._name - - @property - def scope(self): - """Unique TensorFlow scope containing template graph and variables, derived from the user-specified name.""" - return self._scope - - @property - def device(self): - """Name of the TensorFlow device that the weights of this network reside on. Determined by the current device at construction time.""" - return self._device - - @property - def static_kwargs(self): - """EasyDict of arguments passed to the user-supplied build func.""" - return copy.deepcopy(self._static_kwargs) - - @property - def components(self): - """EasyDict of sub-networks created by the build func.""" - return copy.copy(self._get_components()) - - def _get_components(self): - if self._components is None: - self._init_graph() - assert self._components is not None - return self._components - - @property - def input_shapes(self): - """List of input tensor shapes, including minibatch dimension.""" - if self._input_shapes is None: - self._input_shapes = [t.shape.as_list() for t in self.input_templates] - return copy.deepcopy(self._input_shapes) - - @property - def output_shapes(self): - """List of output tensor shapes, including minibatch dimension.""" - if self._output_shapes is None: - self._output_shapes = [t.shape.as_list() for t in self.output_templates] - return copy.deepcopy(self._output_shapes) - - @property - def input_shape(self): - """Short-hand for input_shapes[0].""" - return self.input_shapes[0] - - @property - def output_shape(self): - """Short-hand for output_shapes[0].""" - return self.output_shapes[0] - - @property - def num_inputs(self): - """Number of input tensors.""" - return len(self.input_shapes) - - @property - def num_outputs(self): - """Number of output tensors.""" - return len(self.output_shapes) - - @property - def input_names(self): - """Name string for each input.""" - if self._input_names is None: - self._input_names = [t.name.split("/")[-1].split(":")[0] for t in self.input_templates] - return copy.copy(self._input_names) - - @property - def output_names(self): - """Name string for each output.""" - if self._output_names is None: - self._output_names = [t.name.split("/")[-1].split(":")[0] for t in self.output_templates] - return copy.copy(self._output_names) - - @property - def input_templates(self): - """Input placeholders in the template graph.""" - if self._input_templates is None: - self._init_graph() - assert self._input_templates is not None - return copy.copy(self._input_templates) - - @property - def output_templates(self): - """Output tensors in the template graph.""" - if self._output_templates is None: - self._init_graph() - assert self._output_templates is not None - return copy.copy(self._output_templates) - - @property - def own_vars(self): - """Variables defined by this network (local_name => var), excluding sub-networks.""" - return copy.copy(self._get_own_vars()) - - def _get_own_vars(self): - if self._own_vars is None: - self._init_graph() - assert self._own_vars is not None - return self._own_vars - - @property - def vars(self): - """All variables (local_name => var).""" - return copy.copy(self._get_vars()) - - def _get_vars(self): - if self._vars is None: - self._vars = OrderedDict(self._get_own_vars()) - for comp in self._get_components().values(): - self._vars.update((comp.name + "/" + name, var) for name, var in comp._get_vars().items()) - return self._vars - - @property - def trainables(self): - """All trainable variables (local_name => var).""" - return copy.copy(self._get_trainables()) - - def _get_trainables(self): - if self._trainables is None: - self._trainables = OrderedDict((name, var) for name, var in self.vars.items() if var.trainable) - return self._trainables - - @property - def var_global_to_local(self): - """Mapping from variable global names to local names.""" - return copy.copy(self._get_var_global_to_local()) - - def _get_var_global_to_local(self): - if self._var_global_to_local is None: - self._var_global_to_local = OrderedDict((var.name.split(":")[0], name) for name, var in self.vars.items()) - return self._var_global_to_local - - def reset_own_vars(self) -> None: - """Re-initialize all variables of this network, excluding sub-networks.""" - if self._var_inits is None or self._components is None: - tfutil.run([var.initializer for var in self._get_own_vars().values()]) - else: - self._var_inits.clear() - self._all_inits_known = False - - def reset_vars(self) -> None: - """Re-initialize all variables of this network, including sub-networks.""" - if self._var_inits is None: - tfutil.run([var.initializer for var in self._get_vars().values()]) - else: - self._var_inits.clear() - self._all_inits_known = False - if self._components is not None: - for comp in self._components.values(): - comp.reset_vars() - - def reset_trainables(self) -> None: - """Re-initialize all trainable variables of this network, including sub-networks.""" - tfutil.run([var.initializer for var in self._get_trainables().values()]) - - def get_output_for(self, *in_expr: TfExpression, return_as_list: bool = False, **dynamic_kwargs) -> Union[TfExpression, List[TfExpression]]: - """Construct TensorFlow expression(s) for the output(s) of this network, given the input expression(s). - The graph is placed on the current TensorFlow device.""" - assert len(in_expr) == self.num_inputs - assert not all(expr is None for expr in in_expr) - self._get_vars() # ensure that all variables have been created - - # Choose build func kwargs. - build_kwargs = dict(self.static_kwargs) - build_kwargs.update(dynamic_kwargs) - build_kwargs["is_template_graph"] = False - build_kwargs["components"] = self._components - - # Build TensorFlow graph to evaluate the network. - with tfutil.absolute_variable_scope(self.scope, reuse=True), tf.name_scope(self.name): - assert tf.get_variable_scope().name == self.scope - valid_inputs = [expr for expr in in_expr if expr is not None] - final_inputs = [] - for expr, name, shape in zip(in_expr, self.input_names, self.input_shapes): - if expr is not None: - expr = tf.identity(expr, name=name) - else: - expr = tf.zeros([tf.shape(valid_inputs[0])[0]] + shape[1:], name=name) - final_inputs.append(expr) - out_expr = self._build_func(*final_inputs, **build_kwargs) - - # Propagate input shapes back to the user-specified expressions. - for expr, final in zip(in_expr, final_inputs): - if isinstance(expr, tf.Tensor): - expr.set_shape(final.shape) - - # Express outputs in the desired format. - assert tfutil.is_tf_expression(out_expr) or isinstance(out_expr, tuple) - if return_as_list: - out_expr = [out_expr] if tfutil.is_tf_expression(out_expr) else list(out_expr) - return out_expr - - def get_var_local_name(self, var_or_global_name: Union[TfExpression, str]) -> str: - """Get the local name of a given variable, without any surrounding name scopes.""" - assert tfutil.is_tf_expression(var_or_global_name) or isinstance(var_or_global_name, str) - global_name = var_or_global_name if isinstance(var_or_global_name, str) else var_or_global_name.name - return self._get_var_global_to_local()[global_name] - - def find_var(self, var_or_local_name: Union[TfExpression, str]) -> TfExpression: - """Find variable by local or global name.""" - assert tfutil.is_tf_expression(var_or_local_name) or isinstance(var_or_local_name, str) - return self._get_vars()[var_or_local_name] if isinstance(var_or_local_name, str) else var_or_local_name - - def get_var(self, var_or_local_name: Union[TfExpression, str]) -> np.ndarray: - """Get the value of a given variable as NumPy array. - Note: This method is very inefficient -- prefer to use tflib.run(list_of_vars) whenever possible.""" - return self.find_var(var_or_local_name).eval() - - def set_var(self, var_or_local_name: Union[TfExpression, str], new_value: Union[int, float, np.ndarray]) -> None: - """Set the value of a given variable based on the given NumPy array. - Note: This method is very inefficient -- prefer to use tflib.set_vars() whenever possible.""" - tfutil.set_vars({self.find_var(var_or_local_name): new_value}) - - def __getstate__(self) -> dict: - """Pickle export.""" - state = dict() - state["version"] = 5 - state["name"] = self.name - state["static_kwargs"] = dict(self.static_kwargs) - state["components"] = dict(self.components) - state["build_module_src"] = self._build_module_src - state["build_func_name"] = self._build_func_name - state["variables"] = list(zip(self._get_own_vars().keys(), tfutil.run(list(self._get_own_vars().values())))) - state["input_shapes"] = self.input_shapes - state["output_shapes"] = self.output_shapes - state["input_names"] = self.input_names - state["output_names"] = self.output_names - return state - - def __setstate__(self, state: dict) -> None: - """Pickle import.""" - - # Execute custom import handlers. - for handler in _import_handlers: - state = handler(state) - - # Get basic fields. - assert state["version"] in [2, 3, 4, 5] - name = state["name"] - static_kwargs = state["static_kwargs"] - build_module_src = state["build_module_src"] - build_func_name = state["build_func_name"] - - # Create temporary module from the imported source code. - module_name = "_tflib_network_import_" + uuid.uuid4().hex - module = types.ModuleType(module_name) - sys.modules[module_name] = module - _import_module_src[module] = build_module_src - exec(build_module_src, module.__dict__) # pylint: disable=exec-used - build_func = util.get_obj_from_module(module, build_func_name) - - # Initialize fields. - self._init_fields(name=name, static_kwargs=static_kwargs, build_func=build_func, build_func_name=build_func_name, build_module_src=build_module_src) - self._var_inits.update(copy.deepcopy(state["variables"])) - self._all_inits_known = True - self._components = util.EasyDict(state.get("components", {})) - self._input_shapes = copy.deepcopy(state.get("input_shapes", None)) - self._output_shapes = copy.deepcopy(state.get("output_shapes", None)) - self._input_names = copy.deepcopy(state.get("input_names", None)) - self._output_names = copy.deepcopy(state.get("output_names", None)) - - def clone(self, name: str = None, **new_static_kwargs) -> "Network": - """Create a clone of this network with its own copy of the variables.""" - static_kwargs = dict(self.static_kwargs) - static_kwargs.update(new_static_kwargs) - net = object.__new__(Network) - net._init_fields(name=(name or self.name), static_kwargs=static_kwargs, build_func=self._build_func, build_func_name=self._build_func_name, build_module_src=self._build_module_src) - net.copy_vars_from(self) - return net - - def copy_own_vars_from(self, src_net: "Network") -> None: - """Copy the values of all variables from the given network, excluding sub-networks.""" - - # Source has unknown variables or unknown components => init now. - if (src_net._var_inits is not None and not src_net._all_inits_known) or src_net._components is None: - src_net._get_vars() - - # Both networks are inited => copy directly. - if src_net._var_inits is None and self._var_inits is None: - names = [name for name in self._get_own_vars().keys() if name in src_net._get_own_vars()] - tfutil.set_vars(tfutil.run({self._get_vars()[name]: src_net._get_vars()[name] for name in names})) - return - - # Read from source. - if src_net._var_inits is None: - value_dict = tfutil.run(src_net._get_own_vars()) - else: - value_dict = src_net._var_inits - - # Write to destination. - if self._var_inits is None: - tfutil.set_vars({self._get_vars()[name]: value for name, value in value_dict.items() if name in self._get_vars()}) - else: - self._var_inits.update(value_dict) - - def copy_vars_from(self, src_net: "Network") -> None: - """Copy the values of all variables from the given network, including sub-networks.""" - - # Source has unknown variables or unknown components => init now. - if (src_net._var_inits is not None and not src_net._all_inits_known) or src_net._components is None: - src_net._get_vars() - - # Source is inited, but destination components have not been created yet => set as initial values. - if src_net._var_inits is None and self._components is None: - self._var_inits.update(tfutil.run(src_net._get_vars())) - return - - # Destination has unknown components => init now. - if self._components is None: - self._get_vars() - - # Both networks are inited => copy directly. - if src_net._var_inits is None and self._var_inits is None: - names = [name for name in self._get_vars().keys() if name in src_net._get_vars()] - tfutil.set_vars(tfutil.run({self._get_vars()[name]: src_net._get_vars()[name] for name in names})) - return - - # Copy recursively, component by component. - self.copy_own_vars_from(src_net) - for name, src_comp in src_net._components.items(): - if name in self._components: - self._components[name].copy_vars_from(src_comp) - - def copy_trainables_from(self, src_net: "Network") -> None: - """Copy the values of all trainable variables from the given network, including sub-networks.""" - names = [name for name in self._get_trainables().keys() if name in src_net._get_trainables()] - tfutil.set_vars(tfutil.run({self._get_vars()[name]: src_net._get_vars()[name] for name in names})) - - def convert(self, new_func_name: str, new_name: str = None, **new_static_kwargs) -> "Network": - """Create new network with the given parameters, and copy all variables from this network.""" - if new_name is None: - new_name = self.name - static_kwargs = dict(self.static_kwargs) - static_kwargs.update(new_static_kwargs) - net = Network(name=new_name, func_name=new_func_name, **static_kwargs) - net.copy_vars_from(self) - return net - - def setup_as_moving_average_of(self, src_net: "Network", beta: TfExpressionEx = 0.99, beta_nontrainable: TfExpressionEx = 0.0) -> tf.Operation: - """Construct a TensorFlow op that updates the variables of this network - to be slightly closer to those of the given network.""" - with tfutil.absolute_name_scope(self.scope + "/_MovingAvg"): - ops = [] - for name, var in self._get_vars().items(): - if name in src_net._get_vars(): - cur_beta = beta if var.trainable else beta_nontrainable - new_value = tfutil.lerp(src_net._get_vars()[name], var, cur_beta) - ops.append(var.assign(new_value)) - return tf.group(*ops) - - def run(self, - *in_arrays: Tuple[Union[np.ndarray, None], ...], - input_transform: dict = None, - output_transform: dict = None, - return_as_list: bool = False, - print_progress: bool = False, - minibatch_size: int = None, - num_gpus: int = 1, - assume_frozen: bool = False, - **dynamic_kwargs) -> Union[np.ndarray, Tuple[np.ndarray, ...], List[np.ndarray]]: - """Run this network for the given NumPy array(s), and return the output(s) as NumPy array(s). - - Args: - input_transform: A dict specifying a custom transformation to be applied to the input tensor(s) before evaluating the network. - The dict must contain a 'func' field that points to a top-level function. The function is called with the input - TensorFlow expression(s) as positional arguments. Any remaining fields of the dict will be passed in as kwargs. - output_transform: A dict specifying a custom transformation to be applied to the output tensor(s) after evaluating the network. - The dict must contain a 'func' field that points to a top-level function. The function is called with the output - TensorFlow expression(s) as positional arguments. Any remaining fields of the dict will be passed in as kwargs. - return_as_list: True = return a list of NumPy arrays, False = return a single NumPy array, or a tuple if there are multiple outputs. - print_progress: Print progress to the console? Useful for very large input arrays. - minibatch_size: Maximum minibatch size to use, None = disable batching. - num_gpus: Number of GPUs to use. - assume_frozen: Improve multi-GPU performance by assuming that the trainable parameters will remain changed between calls. - dynamic_kwargs: Additional keyword arguments to be passed into the network build function. - """ - assert len(in_arrays) == self.num_inputs - assert not all(arr is None for arr in in_arrays) - assert input_transform is None or util.is_top_level_function(input_transform["func"]) - assert output_transform is None or util.is_top_level_function(output_transform["func"]) - output_transform, dynamic_kwargs = _handle_legacy_output_transforms(output_transform, dynamic_kwargs) - num_items = in_arrays[0].shape[0] - if minibatch_size is None: - minibatch_size = num_items - - # Construct unique hash key from all arguments that affect the TensorFlow graph. - key = dict(input_transform=input_transform, output_transform=output_transform, num_gpus=num_gpus, assume_frozen=assume_frozen, dynamic_kwargs=dynamic_kwargs) - def unwind_key(obj): - if isinstance(obj, dict): - return [(key, unwind_key(value)) for key, value in sorted(obj.items())] - if callable(obj): - return util.get_top_level_function_name(obj) - return obj - key = repr(unwind_key(key)) - - # Build graph. - if key not in self._run_cache: - with tfutil.absolute_name_scope(self.scope + "/_Run"), tf.control_dependencies(None): - with tf.device("/cpu:0"): - in_expr = [tf.placeholder(tf.float32, name=name) for name in self.input_names] - in_split = list(zip(*[tf.split(x, num_gpus) for x in in_expr])) - - out_split = [] - for gpu in range(num_gpus): - with tf.device(self.device if num_gpus == 1 else "/gpu:%d" % gpu): - net_gpu = self.clone() if assume_frozen else self - in_gpu = in_split[gpu] - - if input_transform is not None: - in_kwargs = dict(input_transform) - in_gpu = in_kwargs.pop("func")(*in_gpu, **in_kwargs) - in_gpu = [in_gpu] if tfutil.is_tf_expression(in_gpu) else list(in_gpu) - - assert len(in_gpu) == self.num_inputs - out_gpu = net_gpu.get_output_for(*in_gpu, return_as_list=True, **dynamic_kwargs) - - if output_transform is not None: - out_kwargs = dict(output_transform) - out_gpu = out_kwargs.pop("func")(*out_gpu, **out_kwargs) - out_gpu = [out_gpu] if tfutil.is_tf_expression(out_gpu) else list(out_gpu) - - assert len(out_gpu) == self.num_outputs - out_split.append(out_gpu) - - with tf.device("/cpu:0"): - out_expr = [tf.concat(outputs, axis=0) for outputs in zip(*out_split)] - self._run_cache[key] = in_expr, out_expr - - # Run minibatches. - in_expr, out_expr = self._run_cache[key] - out_arrays = [np.empty([num_items] + expr.shape.as_list()[1:], expr.dtype.name) for expr in out_expr] - - for mb_begin in range(0, num_items, minibatch_size): - if print_progress: - print("\r%d / %d" % (mb_begin, num_items), end="") - - mb_end = min(mb_begin + minibatch_size, num_items) - mb_num = mb_end - mb_begin - mb_in = [src[mb_begin : mb_end] if src is not None else np.zeros([mb_num] + shape[1:]) for src, shape in zip(in_arrays, self.input_shapes)] - mb_out = tf.get_default_session().run(out_expr, dict(zip(in_expr, mb_in))) - - for dst, src in zip(out_arrays, mb_out): - dst[mb_begin: mb_end] = src - - # Done. - if print_progress: - print("\r%d / %d" % (num_items, num_items)) - - if not return_as_list: - out_arrays = out_arrays[0] if len(out_arrays) == 1 else tuple(out_arrays) - return out_arrays - - def list_ops(self) -> List[TfExpression]: - _ = self.output_templates # ensure that the template graph has been created - include_prefix = self.scope + "/" - exclude_prefix = include_prefix + "_" - ops = tf.get_default_graph().get_operations() - ops = [op for op in ops if op.name.startswith(include_prefix)] - ops = [op for op in ops if not op.name.startswith(exclude_prefix)] - return ops - - def list_layers(self) -> List[Tuple[str, TfExpression, List[TfExpression]]]: - """Returns a list of (layer_name, output_expr, trainable_vars) tuples corresponding to - individual layers of the network. Mainly intended to be used for reporting.""" - layers = [] - - def recurse(scope, parent_ops, parent_vars, level): - if len(parent_ops) == 0 and len(parent_vars) == 0: - return - - # Ignore specific patterns. - if any(p in scope for p in ["/Shape", "/strided_slice", "/Cast", "/concat", "/Assign"]): - return - - # Filter ops and vars by scope. - global_prefix = scope + "/" - local_prefix = global_prefix[len(self.scope) + 1:] - cur_ops = [op for op in parent_ops if op.name.startswith(global_prefix) or op.name == global_prefix[:-1]] - cur_vars = [(name, var) for name, var in parent_vars if name.startswith(local_prefix) or name == local_prefix[:-1]] - if not cur_ops and not cur_vars: - return - - # Filter out all ops related to variables. - for var in [op for op in cur_ops if op.type.startswith("Variable")]: - var_prefix = var.name + "/" - cur_ops = [op for op in cur_ops if not op.name.startswith(var_prefix)] - - # Scope does not contain ops as immediate children => recurse deeper. - contains_direct_ops = any("/" not in op.name[len(global_prefix):] and op.type not in ["Identity", "Cast", "Transpose"] for op in cur_ops) - if (level == 0 or not contains_direct_ops) and (len(cur_ops) != 0 or len(cur_vars) != 0): - visited = set() - for rel_name in [op.name[len(global_prefix):] for op in cur_ops] + [name[len(local_prefix):] for name, _var in cur_vars]: - token = rel_name.split("/")[0] - if token not in visited: - recurse(global_prefix + token, cur_ops, cur_vars, level + 1) - visited.add(token) - return - - # Report layer. - layer_name = scope[len(self.scope) + 1:] - layer_output = cur_ops[-1].outputs[0] if cur_ops else cur_vars[-1][1] - layer_trainables = [var for _name, var in cur_vars if var.trainable] - layers.append((layer_name, layer_output, layer_trainables)) - - recurse(self.scope, self.list_ops(), list(self._get_vars().items()), 0) - return layers - - def print_layers(self, title: str = None, hide_layers_with_no_params: bool = False) -> None: - """Print a summary table of the network structure.""" - rows = [[title if title is not None else self.name, "Params", "OutputShape", "WeightShape"]] - rows += [["---"] * 4] - total_params = 0 - - for layer_name, layer_output, layer_trainables in self.list_layers(): - num_params = sum(int(np.prod(var.shape.as_list())) for var in layer_trainables) - weights = [var for var in layer_trainables if var.name.endswith("/weight:0")] - weights.sort(key=lambda x: len(x.name)) - if len(weights) == 0 and len(layer_trainables) == 1: - weights = layer_trainables - total_params += num_params - - if not hide_layers_with_no_params or num_params != 0: - num_params_str = str(num_params) if num_params > 0 else "-" - output_shape_str = str(layer_output.shape) - weight_shape_str = str(weights[0].shape) if len(weights) >= 1 else "-" - rows += [[layer_name, num_params_str, output_shape_str, weight_shape_str]] - - rows += [["---"] * 4] - rows += [["Total", str(total_params), "", ""]] - - widths = [max(len(cell) for cell in column) for column in zip(*rows)] - print() - for row in rows: - print(" ".join(cell + " " * (width - len(cell)) for cell, width in zip(row, widths))) - print() - - def setup_weight_histograms(self, title: str = None) -> None: - """Construct summary ops to include histograms of all trainable parameters in TensorBoard.""" - if title is None: - title = self.name - - with tf.name_scope(None), tf.device(None), tf.control_dependencies(None): - for local_name, var in self._get_trainables().items(): - if "/" in local_name: - p = local_name.split("/") - name = title + "_" + p[-1] + "/" + "_".join(p[:-1]) - else: - name = title + "_toplevel/" + local_name - - tf.summary.histogram(name, var) - -#---------------------------------------------------------------------------- -# Backwards-compatible emulation of legacy output transformation in Network.run(). - -_print_legacy_warning = True - -def _handle_legacy_output_transforms(output_transform, dynamic_kwargs): - global _print_legacy_warning - legacy_kwargs = ["out_mul", "out_add", "out_shrink", "out_dtype"] - if not any(kwarg in dynamic_kwargs for kwarg in legacy_kwargs): - return output_transform, dynamic_kwargs - - if _print_legacy_warning: - _print_legacy_warning = False - print() - print("WARNING: Old-style output transformations in Network.run() are deprecated.") - print("Consider using 'output_transform=dict(func=tflib.convert_images_to_uint8)'") - print("instead of 'out_mul=127.5, out_add=127.5, out_dtype=np.uint8'.") - print() - assert output_transform is None - - new_kwargs = dict(dynamic_kwargs) - new_transform = {kwarg: new_kwargs.pop(kwarg) for kwarg in legacy_kwargs if kwarg in dynamic_kwargs} - new_transform["func"] = _legacy_output_transform_func - return new_transform, new_kwargs - -def _legacy_output_transform_func(*expr, out_mul=1.0, out_add=0.0, out_shrink=1, out_dtype=None): - if out_mul != 1.0: - expr = [x * out_mul for x in expr] - - if out_add != 0.0: - expr = [x + out_add for x in expr] - - if out_shrink > 1: - ksize = [1, 1, out_shrink, out_shrink] - expr = [tf.nn.avg_pool(x, ksize=ksize, strides=ksize, padding="VALID", data_format="NCHW") for x in expr] - - if out_dtype is not None: - if tf.as_dtype(out_dtype).is_integer: - expr = [tf.round(x) for x in expr] - expr = [tf.saturate_cast(x, out_dtype) for x in expr] - return expr diff --git a/spaces/emc348/faces-through-time/torch_utils/ops/upfirdn2d.h b/spaces/emc348/faces-through-time/torch_utils/ops/upfirdn2d.h deleted file mode 100644 index c9e2032bcac9d2abde7a75eea4d812da348afadd..0000000000000000000000000000000000000000 --- a/spaces/emc348/faces-through-time/torch_utils/ops/upfirdn2d.h +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -// -// NVIDIA CORPORATION and its licensors retain all intellectual property -// and proprietary rights in and to this software, related documentation -// and any modifications thereto. Any use, reproduction, disclosure or -// distribution of this software and related documentation without an express -// license agreement from NVIDIA CORPORATION is strictly prohibited. - -#include - -//------------------------------------------------------------------------ -// CUDA kernel parameters. - -struct upfirdn2d_kernel_params -{ - const void* x; - const float* f; - void* y; - - int2 up; - int2 down; - int2 pad0; - int flip; - float gain; - - int4 inSize; // [width, height, channel, batch] - int4 inStride; - int2 filterSize; // [width, height] - int2 filterStride; - int4 outSize; // [width, height, channel, batch] - int4 outStride; - int sizeMinor; - int sizeMajor; - - int loopMinor; - int loopMajor; - int loopX; - int launchMinor; - int launchMajor; -}; - -//------------------------------------------------------------------------ -// CUDA kernel specialization. - -struct upfirdn2d_kernel_spec -{ - void* kernel; - int tileOutW; - int tileOutH; - int loopMinor; - int loopX; -}; - -//------------------------------------------------------------------------ -// CUDA kernel selection. - -template upfirdn2d_kernel_spec choose_upfirdn2d_kernel(const upfirdn2d_kernel_params& p); - -//------------------------------------------------------------------------ diff --git a/spaces/evi0mo/vits-fastapi-server/transforms.py b/spaces/evi0mo/vits-fastapi-server/transforms.py deleted file mode 100644 index 4793d67ca5a5630e0ffe0f9fb29445c949e64dae..0000000000000000000000000000000000000000 --- a/spaces/evi0mo/vits-fastapi-server/transforms.py +++ /dev/null @@ -1,193 +0,0 @@ -import torch -from torch.nn import functional as F - -import numpy as np - - -DEFAULT_MIN_BIN_WIDTH = 1e-3 -DEFAULT_MIN_BIN_HEIGHT = 1e-3 -DEFAULT_MIN_DERIVATIVE = 1e-3 - - -def piecewise_rational_quadratic_transform(inputs, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=False, - tails=None, - tail_bound=1., - min_bin_width=DEFAULT_MIN_BIN_WIDTH, - min_bin_height=DEFAULT_MIN_BIN_HEIGHT, - min_derivative=DEFAULT_MIN_DERIVATIVE): - - if tails is None: - spline_fn = rational_quadratic_spline - spline_kwargs = {} - else: - spline_fn = unconstrained_rational_quadratic_spline - spline_kwargs = { - 'tails': tails, - 'tail_bound': tail_bound - } - - outputs, logabsdet = spline_fn( - inputs=inputs, - unnormalized_widths=unnormalized_widths, - unnormalized_heights=unnormalized_heights, - unnormalized_derivatives=unnormalized_derivatives, - inverse=inverse, - min_bin_width=min_bin_width, - min_bin_height=min_bin_height, - min_derivative=min_derivative, - **spline_kwargs - ) - return outputs, logabsdet - - -def searchsorted(bin_locations, inputs, eps=1e-6): - bin_locations[..., -1] += eps - return torch.sum( - inputs[..., None] >= bin_locations, - dim=-1 - ) - 1 - - -def unconstrained_rational_quadratic_spline(inputs, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=False, - tails='linear', - tail_bound=1., - min_bin_width=DEFAULT_MIN_BIN_WIDTH, - min_bin_height=DEFAULT_MIN_BIN_HEIGHT, - min_derivative=DEFAULT_MIN_DERIVATIVE): - inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound) - outside_interval_mask = ~inside_interval_mask - - outputs = torch.zeros_like(inputs) - logabsdet = torch.zeros_like(inputs) - - if tails == 'linear': - unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1)) - constant = np.log(np.exp(1 - min_derivative) - 1) - unnormalized_derivatives[..., 0] = constant - unnormalized_derivatives[..., -1] = constant - - outputs[outside_interval_mask] = inputs[outside_interval_mask] - logabsdet[outside_interval_mask] = 0 - else: - raise RuntimeError('{} tails are not implemented.'.format(tails)) - - outputs[inside_interval_mask], logabsdet[inside_interval_mask] = rational_quadratic_spline( - inputs=inputs[inside_interval_mask], - unnormalized_widths=unnormalized_widths[inside_interval_mask, :], - unnormalized_heights=unnormalized_heights[inside_interval_mask, :], - unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :], - inverse=inverse, - left=-tail_bound, right=tail_bound, bottom=-tail_bound, top=tail_bound, - min_bin_width=min_bin_width, - min_bin_height=min_bin_height, - min_derivative=min_derivative - ) - - return outputs, logabsdet - -def rational_quadratic_spline(inputs, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=False, - left=0., right=1., bottom=0., top=1., - min_bin_width=DEFAULT_MIN_BIN_WIDTH, - min_bin_height=DEFAULT_MIN_BIN_HEIGHT, - min_derivative=DEFAULT_MIN_DERIVATIVE): - if torch.min(inputs) < left or torch.max(inputs) > right: - raise ValueError('Input to a transform is not within its domain') - - num_bins = unnormalized_widths.shape[-1] - - if min_bin_width * num_bins > 1.0: - raise ValueError('Minimal bin width too large for the number of bins') - if min_bin_height * num_bins > 1.0: - raise ValueError('Minimal bin height too large for the number of bins') - - widths = F.softmax(unnormalized_widths, dim=-1) - widths = min_bin_width + (1 - min_bin_width * num_bins) * widths - cumwidths = torch.cumsum(widths, dim=-1) - cumwidths = F.pad(cumwidths, pad=(1, 0), mode='constant', value=0.0) - cumwidths = (right - left) * cumwidths + left - cumwidths[..., 0] = left - cumwidths[..., -1] = right - widths = cumwidths[..., 1:] - cumwidths[..., :-1] - - derivatives = min_derivative + F.softplus(unnormalized_derivatives) - - heights = F.softmax(unnormalized_heights, dim=-1) - heights = min_bin_height + (1 - min_bin_height * num_bins) * heights - cumheights = torch.cumsum(heights, dim=-1) - cumheights = F.pad(cumheights, pad=(1, 0), mode='constant', value=0.0) - cumheights = (top - bottom) * cumheights + bottom - cumheights[..., 0] = bottom - cumheights[..., -1] = top - heights = cumheights[..., 1:] - cumheights[..., :-1] - - if inverse: - bin_idx = searchsorted(cumheights, inputs)[..., None] - else: - bin_idx = searchsorted(cumwidths, inputs)[..., None] - - input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0] - input_bin_widths = widths.gather(-1, bin_idx)[..., 0] - - input_cumheights = cumheights.gather(-1, bin_idx)[..., 0] - delta = heights / widths - input_delta = delta.gather(-1, bin_idx)[..., 0] - - input_derivatives = derivatives.gather(-1, bin_idx)[..., 0] - input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0] - - input_heights = heights.gather(-1, bin_idx)[..., 0] - - if inverse: - a = (((inputs - input_cumheights) * (input_derivatives - + input_derivatives_plus_one - - 2 * input_delta) - + input_heights * (input_delta - input_derivatives))) - b = (input_heights * input_derivatives - - (inputs - input_cumheights) * (input_derivatives - + input_derivatives_plus_one - - 2 * input_delta)) - c = - input_delta * (inputs - input_cumheights) - - discriminant = b.pow(2) - 4 * a * c - assert (discriminant >= 0).all() - - root = (2 * c) / (-b - torch.sqrt(discriminant)) - outputs = root * input_bin_widths + input_cumwidths - - theta_one_minus_theta = root * (1 - root) - denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta) - * theta_one_minus_theta) - derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * root.pow(2) - + 2 * input_delta * theta_one_minus_theta - + input_derivatives * (1 - root).pow(2)) - logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator) - - return outputs, -logabsdet - else: - theta = (inputs - input_cumwidths) / input_bin_widths - theta_one_minus_theta = theta * (1 - theta) - - numerator = input_heights * (input_delta * theta.pow(2) - + input_derivatives * theta_one_minus_theta) - denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta) - * theta_one_minus_theta) - outputs = input_cumheights + numerator / denominator - - derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * theta.pow(2) - + 2 * input_delta * theta_one_minus_theta - + input_derivatives * (1 - theta).pow(2)) - logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator) - - return outputs, logabsdet diff --git a/spaces/f2api/gpt-academic/docs/README_FR.md b/spaces/f2api/gpt-academic/docs/README_FR.md deleted file mode 100644 index 3d96849740374357056fba1d0370167e9182fe71..0000000000000000000000000000000000000000 --- a/spaces/f2api/gpt-academic/docs/README_FR.md +++ /dev/null @@ -1,323 +0,0 @@ -> **Note** -> -> Ce fichier README est généré automatiquement par le plugin de traduction markdown de ce projet et n'est peut - être pas correct à 100%. -> -> During installation, please strictly select the versions **specified** in requirements.txt. -> -> `pip install -r requirements.txt` -> - -# Optimisation académique GPT (GPT Academic) - -**Si vous aimez ce projet, veuillez lui donner une étoile. Si vous avez trouvé des raccourcis académiques ou des plugins fonctionnels plus utiles, n'hésitez pas à ouvrir une demande ou une pull request. -Pour traduire ce projet dans une langue arbitraire avec GPT, lisez et exécutez [`multi_language.py`](multi_language.py) (expérimental). - -> **Note** -> -> 1. Veuillez noter que seuls les plugins de fonctions (boutons) **en rouge** prennent en charge la lecture de fichiers. Certains plugins se trouvent dans le **menu déroulant** de la zone de plugins. De plus, nous accueillons et traitons les nouvelles pull requests pour les plugins avec **la plus haute priorité**! -> -> 2. Les fonctions de chaque fichier de ce projet sont expliquées en détail dans l'auto-analyse [`self_analysis.md`](https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A). Avec l'itération des versions, vous pouvez également cliquer sur les plugins de fonctions pertinents et appeler GPT pour régénérer le rapport d'auto-analyse du projet à tout moment. Les FAQ sont résumées dans [le wiki](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98). [Méthode d'installation](#installation). -> -> 3. Ce projet est compatible avec et encourage l'utilisation de grands modèles de langage nationaux tels que chatglm, RWKV, Pangu, etc. La coexistence de plusieurs clés API est prise en charge et peut être remplie dans le fichier de configuration, tel que `API_KEY="openai-key1,openai-key2,api2d-key3"`. Lorsque vous souhaitez remplacer temporairement `API_KEY`, saisissez temporairement `API_KEY` dans la zone de saisie, puis appuyez sur Entrée pour soumettre et activer. - -
- -Functionnalité | Description ---- | --- -Révision en un clic | prend en charge la révision en un clic et la recherche d'erreurs de syntaxe dans les articles -Traduction chinois-anglais en un clic | Traduction chinois-anglais en un clic -Explication de code en un clic | Affichage, explication, génération et ajout de commentaires de code -[Raccourcis personnalisés](https://www.bilibili.com/video/BV14s4y1E7jN) | prend en charge les raccourcis personnalisés -Conception modulaire | prend en charge de puissants plugins de fonction personnalisée, les plugins prennent en charge la [mise à jour à chaud](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%87%BD%E6%95%B0%E6%8F%92%E4%BB%B6%E6%8C%87%E5%8D%97) -[Autoscanner](https://www.bilibili.com/video/BV1cj411A7VW) | [Plug-in de fonction] [Compréhension instantanée](https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A) du code source de ce projet -[Analyse de programme](https://www.bilibili.com/video/BV1cj411A7VW) | [Plug-in de fonction] Analyse en un clic de la structure d'autres projets Python / C / C ++ / Java / Lua / ... -Lecture d'articles, [traduction](https://www.bilibili.com/video/BV1KT411x7Wn) d'articles | [Plug-in de fonction] Compréhension instantanée de l'article latex / pdf complet et génération de résumés -[Traduction](https://www.bilibili.com/video/BV1nk4y1Y7Js/) et [révision](https://www.bilibili.com/video/BV1FT411H7c5/) complets en latex | [Plug-in de fonction] traduction ou révision en un clic d'articles en latex -Génération de commentaires en masse | [Plug-in de fonction] Génération en un clic de commentaires de fonction en masse -Traduction [chinois-anglais](https://www.bilibili.com/video/BV1yo4y157jV/) en Markdown | [Plug-in de fonction] avez-vous vu la [README](https://github.com/binary-husky/chatgpt_academic/blob/master/docs/README_EN.md) pour les 5 langues ci-dessus? -Génération de rapports d'analyse de chat | [Plug-in de fonction] Génère automatiquement un rapport de résumé après l'exécution -[Traduction intégrale en pdf](https://www.bilibili.com/video/BV1KT411x7Wn) | [Plug-in de fonction] Extraction de titre et de résumé de l'article pdf + traduction intégrale (multi-thread) -[Aide à arxiv](https://www.bilibili.com/video/BV1LM4y1279X) | [Plug-in de fonction] Entrer l'url de l'article arxiv pour traduire et télécharger le résumé en un clic -[Aide à la recherche Google Scholar](https://www.bilibili.com/video/BV19L411U7ia) | [Plug-in de fonction] Donnez l'URL de la page de recherche Google Scholar, laissez GPT vous aider à [écrire des ouvrages connexes](https://www.bilibili.com/video/BV1GP411U7Az/) -Aggrégation d'informations en ligne et GPT | [Plug-in de fonction] Permet à GPT de [récupérer des informations en ligne](https://www.bilibili.com/video/BV1om4y127ck), puis de répondre aux questions, afin que les informations ne soient jamais obsolètes -Affichage d'équations / images / tableaux | Fournit un affichage simultané de [la forme tex et de la forme rendue](https://user-images.githubusercontent.com/96192199/230598842-1d7fcddd-815d-40ee-af60-baf488a199df.png), prend en charge les formules mathématiques et la coloration syntaxique du code -Prise en charge des plugins à plusieurs threads | prend en charge l'appel multithread de chatgpt, un clic pour traiter [un grand nombre d'articles](https://www.bilibili.com/video/BV1FT411H7c5/) ou de programmes -Thème gradio sombre en option de démarrage | Ajoutez```/?__theme=dark``` à la fin de l'URL du navigateur pour basculer vers le thème sombre -[Prise en charge de plusieurs modèles LLM](https://www.bilibili.com/video/BV1wT411p7yf), [API2D](https://api2d.com/) | Sera probablement très agréable d'être servi simultanément par GPT3.5, GPT4, [ChatGLM de Tsinghua](https://github.com/THUDM/ChatGLM-6B), [MOSS de Fudan](https://github.com/OpenLMLab/MOSS) -Plus de modèles LLM, déploiement de [huggingface](https://huggingface.co/spaces/qingxu98/gpt-academic) | Ajout prise en charge de l'interface Newbing (nouvelle bing), introduction du support de [Jittorllms de Tsinghua](https://github.com/Jittor/JittorLLMs), [LLaMA](https://github.com/facebookresearch/llama), [RWKV](https://github.com/BlinkDL/ChatRWKV) et [Panguα](https://openi.org.cn/pangu/) -Plus de nouvelles fonctionnalités (génération d'images, etc.) ... | Voir la fin de ce document pour plus de détails ... - -
- - -- Nouvelle interface (modifier l'option LAYOUT de `config.py` pour passer d'une disposition ``gauche-droite`` à une disposition ``haut-bas``) -
- -
- Tous les boutons sont générés dynamiquement en lisant functional.py et peuvent être facilement personnalisés pour ajouter des fonctionnalités personnalisées, ce qui facilite l'utilisation du presse-papiers. -
- -
- -- Correction d'erreurs/lissage du texte. -
- -
- -- Si la sortie contient des équations, elles sont affichées à la fois sous forme de tex et sous forme rendue pour faciliter la lecture et la copie. -
- -
- -- Pas envie de lire les codes de ce projet? Tout le projet est directement exposé par ChatGPT. -
- -
- -- Appel à une variété de modèles de langage de grande envergure (ChatGLM + OpenAI-GPT3.5 + [API2D] (https://api2d.com/)-GPT4). -
- -
- ---- -# Installation -## Installation-Method 1: running directly (Windows, Linux or MacOS) - -1. Télécharger le projet -```sh -git clone https://github.com/binary-husky/chatgpt_academic.git -cd chatgpt_academic -``` - -2. Configuration de la clé API - -Dans `config.py`, configurez la clé API et d'autres paramètres. Consultez [Special network environment settings] (https://github.com/binary-husky/gpt_academic/issues/1). - -(P.S. Lorsque le programme est exécuté, il vérifie en premier s'il existe un fichier de configuration privé nommé `config_private.py` et remplace les paramètres portant le même nom dans `config.py` par les paramètres correspondants dans `config_private.py`. Par conséquent, si vous comprenez la logique de lecture de nos configurations, nous vous recommandons vivement de créer un nouveau fichier de configuration nommé `config_private.py` à côté de `config.py` et de transférer (copier) les configurations de `config.py`. `config_private.py` n'est pas contrôlé par Git et peut garantir la sécurité de vos informations privées. P.S. Le projet prend également en charge la configuration de la plupart des options via "variables d'environnement", le format d'écriture des variables d'environnement est référencé dans le fichier `docker-compose`. Priorité de lecture: "variables d'environnement" > `config_private.py` > `config.py`) - - -3. Installer les dépendances -```sh -# (Option I: python users instalation) (Python version 3.9 or higher, the newer the better). Note: use official pip source or ali pip source. To temporarily change the source: python -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/ -python -m pip install -r requirements.txt - -# (Option II: non-python users instalation) Use Anaconda, the steps are similar (https://www.bilibili.com/video/BV1rc411W7Dr): -conda create -n gptac_venv python=3.11 # Create anaconda env -conda activate gptac_venv # Activate anaconda env -python -m pip install -r requirements.txt # Same step as pip instalation -``` - -
Cliquez ici pour afficher le texte si vous souhaitez prendre en charge THU ChatGLM/FDU MOSS en tant que backend. -

- -【Optional】 Si vous souhaitez prendre en charge THU ChatGLM/FDU MOSS en tant que backend, des dépendances supplémentaires doivent être installées (prérequis: compétent en Python + utilisez Pytorch + configuration suffisante de l'ordinateur): -```sh -# 【Optional Step I】 Support THU ChatGLM. Remarque sur THU ChatGLM: Si vous rencontrez l'erreur "Appel à ChatGLM échoué, les paramètres ChatGLM ne peuvent pas être chargés normalement", reportez-vous à ce qui suit: 1: La version par défaut installée est torch+cpu, si vous souhaitez utiliser cuda, vous devez désinstaller torch et réinstaller torch+cuda; 2: Si le modèle ne peut pas être chargé en raison d'une configuration insuffisante de l'ordinateur local, vous pouvez modifier la précision du modèle dans request_llm/bridge_chatglm.py, modifier AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) par AutoTokenizer.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True) -python -m pip install -r request_llm/requirements_chatglm.txt - -# 【Optional Step II】 Support FDU MOSS -python -m pip install -r request_llm/requirements_moss.txt -git clone https://github.com/OpenLMLab/MOSS.git request_llm/moss # Note: When running this line of code, you must be in the project root path. - -# 【Optional Step III】Make sure the AVAIL_LLM_MODELS in the config.py configuration file contains the desired model. Currently, all models supported are as follows (the jittorllms series currently only supports the docker scheme): -AVAIL_LLM_MODELS = ["gpt-3.5-turbo", "api2d-gpt-3.5-turbo", "gpt-4", "api2d-gpt-4", "chatglm", "newbing", "moss"] # + ["jittorllms_rwkv", "jittorllms_pangualpha", "jittorllms_llama"] -``` - -

-
- - - -4. Exécution -```sh -python main.py -```5. Plugin de fonction de test -``` -- Fonction de modèle de plugin de test (requiert que GPT réponde à ce qui s'est passé dans l'histoire aujourd'hui), vous pouvez utiliser cette fonction comme modèle pour mettre en œuvre des fonctionnalités plus complexes. - Cliquez sur "[Démo de modèle de plugin de fonction] Aujourd'hui dans l'histoire" -``` - -## Installation - Méthode 2: Utilisation de Docker - -1. ChatGPT uniquement (recommandé pour la plupart des gens) - -``` sh -git clone https://github.com/binary-husky/chatgpt_academic.git # Télécharger le projet -cd chatgpt_academic # Accéder au chemin -nano config.py # Editez config.py avec n'importe quel éditeur de texte en configurant "Proxy", "API_KEY" et "WEB_PORT" (p. ex. 50923) -docker build -t gpt-academic . # Installer - -# (Dernière étape - choix1) Dans un environnement Linux, l'utilisation de `--net=host` est plus facile et rapide -docker run --rm -it --net=host gpt-academic -# (Dernière étape - choix 2) Dans un environnement macOS/Windows, seule l'option -p permet d'exposer le port du récipient (p.ex. 50923) au port de l'hôte. -docker run --rm -it -e WEB_PORT=50923 -p 50923:50923 gpt-academic -``` - -2. ChatGPT + ChatGLM + MOSS (il faut connaître Docker) - -``` sh -# Modifiez docker-compose.yml, supprimez la solution 1 et la solution 3, conservez la solution 2. Modifiez la configuration de la solution 2 dans docker-compose.yml en suivant les commentaires. -docker-compose up -``` - -3. ChatGPT + LLAMA + PanGu + RWKV (il faut connaître Docker) -``` sh -# Modifiez docker-compose.yml, supprimez la solution 1 et la solution 2, conservez la solution 3. Modifiez la configuration de la solution 3 dans docker-compose.yml en suivant les commentaires. -docker-compose up -``` - - -## Installation - Méthode 3: Autres méthodes de déploiement - -1. Comment utiliser une URL de proxy inversé / Microsoft Azure Cloud API -Configurez simplement API_URL_REDIRECT selon les instructions de config.py. - -2. Déploiement distant sur un serveur cloud (connaissance et expérience des serveurs cloud requises) -Veuillez consulter [Wiki de déploiement-1] (https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BA%91%E6%9C%8D%E5%8A%A1%E5%99%A8%E8%BF%9C%E7%A8%8B%E9%83%A8%E7%BD%B2%E6%8C%87%E5%8D%97). - -3. Utilisation de WSL2 (sous-système Windows pour Linux) -Veuillez consulter [Wiki de déploiement-2] (https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BD%BF%E7%94%A8WSL2%EF%BC%88Windows-Subsystem-for-Linux-%E5%AD%90%E7%B3%BB%E7%BB%9F%EF%BC%89%E9%83%A8%E7%BD%B2). - -4. Comment exécuter sous un sous-répertoire (tel que `http://localhost/subpath`) -Veuillez consulter les [instructions d'exécution de FastAPI] (docs/WithFastapi.md). - -5. Utilisation de docker-compose -Veuillez lire docker-compose.yml, puis suivre les instructions fournies. - -# Utilisation avancée -## Personnalisation de nouveaux boutons pratiques / Plugins de fonctions personnalisées - -1. Personnalisation de nouveaux boutons pratiques (raccourcis académiques) -Ouvrez core_functional.py avec n'importe quel éditeur de texte, ajoutez une entrée comme suit, puis redémarrez le programme. (Si le bouton a été ajouté avec succès et est visible, le préfixe et le suffixe prennent en charge les modifications à chaud et ne nécessitent pas le redémarrage du programme pour prendre effet.) -Par exemple -``` -"Super coller sens": { - # Préfixe, sera ajouté avant votre entrée. Par exemple, pour décrire votre demande, telle que traduire, expliquer du code, faire la mise en forme, etc. - "Prefix": "Veuillez traduire le contenu suivant en chinois, puis expliquer chaque terme proprement nommé qui y apparaît avec un tableau markdown:\n\n", - - # Suffixe, sera ajouté après votre entrée. Par exemple, en utilisant le préfixe, vous pouvez entourer votre contenu d'entrée de guillemets. - "Suffix": "", -}, -``` -
- -
- -2. Plugins de fonctions personnalisées - -Écrivez des plugins de fonctions puissants pour effectuer toutes les tâches que vous souhaitez ou que vous ne pouvez pas imaginer. -Les plugins de ce projet ont une difficulté de programmation et de débogage très faible. Si vous avez des connaissances de base en Python, vous pouvez simuler la fonctionnalité de votre propre plugin en suivant le modèle que nous avons fourni. -Veuillez consulter le [Guide du plugin de fonction] (https://github.com/binary-husky/chatgpt_academic/wiki/%E5%87%BD%E6%95%B0%E6%8F%92%E4%BB%B6%E6%8C%87%E5%8D%97) pour plus de détails. - ---- -# Latest Update - -## Nouvelles fonctionnalités en cours de déploiement. - -1. Fonction de sauvegarde de la conversation. -Appelez simplement "Enregistrer la conversation actuelle" dans la zone de plugin de fonction pour enregistrer la conversation actuelle en tant que fichier html lisible et récupérable. De plus, dans la zone de plugin de fonction (menu déroulant), appelez "Charger une archive de l'historique de la conversation" pour restaurer la conversation précédente. Astuce : cliquer directement sur "Charger une archive de l'historique de la conversation" sans spécifier de fichier permet de consulter le cache d'archive html précédent. Cliquez sur "Supprimer tous les enregistrements locaux de l'historique de la conversation" pour supprimer le cache d'archive html. - -
- -
- - - -2. Générer un rapport. La plupart des plugins génèrent un rapport de travail après l'exécution. -
- - - -
- -3. Conception de fonctionnalités modulaires avec une interface simple mais capable d'une fonctionnalité puissante. -
- - -
- -4. C'est un projet open source qui peut "se traduire de lui-même". -
- -
- -5. Traduire d'autres projets open source n'est pas un problème. -
- -
- -
- -
- -6. Fonction de décoration de live2d (désactivée par défaut, nécessite une modification de config.py). -
- -
- -7. Prise en charge du modèle de langue MOSS. -
- -
- -8. Génération d'images OpenAI. -
- -
- -9. Analyse et synthèse vocales OpenAI. -
- -
- -10. Correction de la totalité des erreurs de Latex. -
- -
- - -## Versions : -- version 3.5 (À faire) : appel de toutes les fonctions de plugin de ce projet en langage naturel (priorité élevée) -- version 3.4 (À faire) : amélioration du support multi-thread de chatglm en local -- version 3.3 : Fonctionnalité intégrée d'informations d'internet -- version 3.2 : La fonction du plugin de fonction prend désormais en charge des interfaces de paramètres plus nombreuses (fonction de sauvegarde, décodage de n'importe quel langage de code + interrogation simultanée de n'importe quelle combinaison de LLM) -- version 3.1 : Prise en charge de l'interrogation simultanée de plusieurs modèles GPT ! Support api2d, équilibrage de charge multi-clé api. -- version 3.0 : Prise en charge de chatglm et autres LLM de petite taille. -- version 2.6 : Refonte de la structure des plugins, amélioration de l'interactivité, ajout de plus de plugins. -- version 2.5 : Auto-mise à jour, résolution des problèmes de texte trop long et de dépassement de jetons lors de la compilation du projet global. -- version 2.4 : (1) Nouvelle fonction de traduction de texte intégral PDF ; (2) Nouvelle fonction de permutation de position de la zone d'entrée ; (3) Nouvelle option de mise en page verticale ; (4) Amélioration des fonctions multi-thread de plug-in. -- version 2.3 : Amélioration de l'interactivité multithread. -- version 2.2 : Les plugins de fonctions peuvent désormais être rechargés à chaud. -- version 2.1 : Disposition pliable -- version 2.0 : Introduction de plugins de fonctions modulaires -- version 1.0 : Fonctionnalités de base - -gpt_academic développeur QQ groupe-2:610599535 - -- Problèmes connus - - Certains plugins de traduction de navigateur perturbent le fonctionnement de l'interface frontend de ce logiciel - - Des versions gradio trop hautes ou trop basses provoquent de nombreuses anomalies - -## Référence et apprentissage - -``` -De nombreux autres excellents projets ont été référencés dans le code, notamment : - -# Projet 1 : ChatGLM-6B de Tsinghua : -https://github.com/THUDM/ChatGLM-6B - -# Projet 2 : JittorLLMs de Tsinghua : -https://github.com/Jittor/JittorLLMs - -# Projet 3 : Edge-GPT : -https://github.com/acheong08/EdgeGPT - -# Projet 4 : ChuanhuChatGPT : -https://github.com/GaiZhenbiao/ChuanhuChatGPT - -# Projet 5 : ChatPaper : -https://github.com/kaixindelele/ChatPaper - -# Plus : -https://github.com/gradio-app/gradio -https://github.com/fghrsh/live2d_demo -``` \ No newline at end of file diff --git a/spaces/falterWliame/Face_Mask_Detection/Cisco Air P121ag A K9 Windows 7 Driver.md b/spaces/falterWliame/Face_Mask_Detection/Cisco Air P121ag A K9 Windows 7 Driver.md deleted file mode 100644 index 8b6673320300f344e41555efbd38bc3e96146b70..0000000000000000000000000000000000000000 --- a/spaces/falterWliame/Face_Mask_Detection/Cisco Air P121ag A K9 Windows 7 Driver.md +++ /dev/null @@ -1,9 +0,0 @@ -
-

to mount the driver package using the “mount” option in windows, right-click the driver package file, and then click “mount”. then navigate to the location where you saved the driver package file, and then click “mount”.

-

Cisco Air P121ag A K9 Windows 7 Driver


Download Filehttps://urlca.com/2uDd4g



-

the following steps uninstall the vulnerable device driver.

  1. verify that the cisco air p121ag a k9 device is connected to the network.
  2. click start, click search, type uninstall and press enter.
  3. click on the entry for the device driver, click the remove button.
  4. click yes when the confirmation box pops up.
  5. remove any redundant device drivers that are no longer used.
-

the embedded microsoft windows device driver for the cisco air p121ag a k9 device is vulnerable to a remote code execution vulnerability (cve-2013-0556). a successful exploit of this vulnerability could allow an unauthenticated, remote attacker to execute arbitrary code with the privileges of the local user.

-

the cisco air p121ag a k9 device is a unified wi-fi base station that works in conjunction with the cisco smart wi-fi services available on the cisco air network operating system (anos) to provide high-speed, secure wi-fi for enterprise, home, and mobile customers. this vulnerable device is only supported on windows 7 operating system. the cisco air p121ag a k9 device is sold separately, and is not included with the cisco anos services or any other cisco product. it is sold as a standalone product. the cisco air p121ag a k9 device is supported on windows 7, windows server 2008, windows server 2008 r2, windows server 2012, windows 8 and windows 8.1.

-

899543212b
-
-
\ No newline at end of file diff --git a/spaces/falterWliame/Face_Mask_Detection/Dos2usb License Key.rar.md b/spaces/falterWliame/Face_Mask_Detection/Dos2usb License Key.rar.md deleted file mode 100644 index f9c2e7ef6925e411c2b46de296ec3f14fe2f3b7b..0000000000000000000000000000000000000000 --- a/spaces/falterWliame/Face_Mask_Detection/Dos2usb License Key.rar.md +++ /dev/null @@ -1,11 +0,0 @@ - -

this software is not free software. all of the serial keys and crack keys are owned by our company. you must buy a license key from our company. if you are unable to download the licensed program, please contact us.

-

dos2usb license key.rar


Download Zip >>>>> https://urlca.com/2uDccN



-

dos2usb captures ms-dos print jobs from lpt1-lpt9 and prn ports simultaneously and redirect it to correspondingly selected printers (gdi printers, pdf prnters, network printers, ip printers, rdp printers, any kind of virtual prnters etc.) moreover it provides full screen dos prompts also, so that ms-dos applications get advantage of fullscreen in newer windows os.

-

dos2usb dos2usb dos2usb license key dos2usb download dos2usb crack dos2usb review dos2usb licence key dos2usb 1.59.84 dos2usb keygen dos2usb serial dos2usb. save adobe premiere pro cc 2015 project as zip dos2usb licence key windows 7 orjinal yapma program. 222 x full version software torrent key 64bit pc rar.

-

dos2usb serial key license is the only solution that works 100% in every environment, and can be used by any user. just pay a small fee of £1.50 and get your dos2usb serial key license. dos2usb license key.rar

-

dos2usb is a remarkable dos utility which captures ms-dos print jobs from lpt1-lpt9 and prn ports simultaneously and redirects them to correspondingly selected printers (gdi printers, pdf prnters, network printers, ip printers, rdp printers, any kind of virtual printers etc.) moreover it provides full screen dos prompts also, so that ms-dos applications get advantage of fullscreen in newer windows os.

-

-

dos2usb it is a remarkable dos utility which captures ms-dos print jobs from lpt1-lpt9 and prn ports simultaneously and redirects them to correspondingly selected printers (gdi printers, pdf prnters, network printers, ip printers, rdp printers, any kind of virtual printers etc.) moreover it provides full screen dos prompts also, so that ms-dos applications get advantage of fullscreen in newer windows os.

899543212b
-
-
\ No newline at end of file diff --git a/spaces/falterWliame/Face_Mask_Detection/Optimum K Software Crack 16 _HOT_.md b/spaces/falterWliame/Face_Mask_Detection/Optimum K Software Crack 16 _HOT_.md deleted file mode 100644 index 3f206568bc49612bd22bc2eb5fbf71fa77ce625b..0000000000000000000000000000000000000000 --- a/spaces/falterWliame/Face_Mask_Detection/Optimum K Software Crack 16 _HOT_.md +++ /dev/null @@ -1,8 +0,0 @@ -
-

we have already seen that a linear crack can be modeled by using the classical damage model. a linear crack is a line in the material that can be modeled by two faces. when one face is fixed, the crack has only one dimension. this type of crack is used to model a crack in a plate that is perpendicular to the surface. the crack is modeled as a crack in a plate that is parallel to the surface.

-

the crack growth algorithm calculates the optimum path from which the crack growth can be simulated. the use of this model and the information gathered throughout the simulation are used to quantify the cracks growth in optimum conditions. for further details on the parameterization of the damage model and the result of the performance analysis of a structure, the reader is referred to reference 13 .

-

optimum k software crack 16


Download →→→ https://urlca.com/2uDdIF



-

although many of the database and models for this problem are based on laboratory experiments, we have also implemented a stochastic model, in particular, a markov chain that is stochastic in nature. the model is based on the following hypotheses: (1) the crack propagation direction is the same for all cracks of a given specimen. (2) the crack propagation direction is distributed randomly. (3) the probability of the crack propagation is independent of the orientation of the specimen. these hypotheses are based on the crack propagation behavior in real-world scenarios, where the crack propagation direction is usually random and the probability of the crack propagation is independent of the orientation of the specimen.

-

the markov chain is constructed as follows. the time t represents the current step of the markov chain. let t(t) denote the set of possible crack propagation directions at step t. let. suppose the set of possible crack propagation directions at the current step is t(t). then, with probability, the crack propagation direction will be in the set of possible crack propagation directions at the next step, t(t+1). let p(t) represent the probability of the crack propagation at the current step. then, for each element in the set of possible crack propagation directions at the current step, the probability of the crack propagation is:

899543212b
-
-
\ No newline at end of file diff --git a/spaces/fatiXbelha/sd/CPU-x Dasher z Battery life The Best App for Real-Time CPU Frequency and Network Speed Monitoring.md b/spaces/fatiXbelha/sd/CPU-x Dasher z Battery life The Best App for Real-Time CPU Frequency and Network Speed Monitoring.md deleted file mode 100644 index bdc94f0d4d7e7a58f4f686cba6db53fb7fadea2f..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/CPU-x Dasher z Battery life The Best App for Real-Time CPU Frequency and Network Speed Monitoring.md +++ /dev/null @@ -1,127 +0,0 @@ -
-

CPU-x Dasher z Battery Life APK: A Comprehensive Review

-

If you are looking for a mobile app that can help you query your phone's hardware and system information, monitor your network speed and traffic, view your phone's screen and camera details, check your memory and storage usage, and use a health widget that displays steps, distance, and calories data from the "health" app, then you might want to try CPU-x Dasher z Battery Life APK. This app is a tool that can provide you with accurate real-time CPU frequency calculation, user-friendly interface, simple interaction, and support for iPhone13 series and iPad Mini 6 models. In this article, we will review CPU-x Dasher z Battery Life APK in detail and compare it with other similar apps. We will also answer some frequently asked questions about this app.

-

What is CPU-x Dasher z Battery Life APK?

-

CPU-x Dasher z Battery Life APK is a mobile app that allows users to query their phone's hardware and system information. It provides accurate real-time CPU frequency calculation, network speed and traffic monitoring, and storage usage information. The app also allows users to view their phone's screen and camera details, as well as network and carrier support. The app has a user-friendly interface with simple interaction and supports iPhone13 series and iPad Mini 6 models.

-

cpu-x dasher z battery life apk


Download File ○○○ https://urllie.com/2uNyxJ



-

Features and Benefits of CPU-x Dasher z Battery Life APK

-

Some of the features and benefits of CPU-x Dasher z Battery Life APK are:

-
    -
  • Accurate CPU real-time frequency calculation with low system resource usage
  • -
  • View system hardware information, operating system information
  • -
  • View network and carrier support
  • -
  • Real-time network speed and traffic monitoring, WiFi hotspot information
  • -
  • View phone screen details
  • -
  • View camera details
  • -
  • Check memory and storage usage information
  • -
  • Health widget that displays steps, distance, and calories data from the "health" app
  • -
  • User-friendly interface with simple interaction
  • -
  • Supports iPhone13 series and iPad Mini 6 models
  • -
-

How to Download and Install CPU-x Dasher z Battery Life APK

-

To download and install CPU-x Dasher z Battery Life APK on your phone, you need to follow these steps:

-

cpu-x dasher z battery life app download
-cpu-x dasher z battery life ios review
-cpu-x dasher z battery life software features
-cpu-x dasher z battery life apk free
-cpu-x dasher z battery life for android
-cpu-x dasher z battery life app store
-cpu-x dasher z battery life software pricing
-cpu-x dasher z battery life apk latest version
-cpu-x dasher z battery life for iphone
-cpu-x dasher z battery life app advice
-cpu-x dasher z battery life software details
-cpu-x dasher z battery life apk mod
-cpu-x dasher z battery life for ipad
-cpu-x dasher z battery life app cnet
-cpu-x dasher z battery life software alternatives
-cpu-x dasher z battery life apk download for pc
-cpu-x dasher z battery life for mac
-cpu-x dasher z battery life app nowgaming
-cpu-x dasher z battery life software support
-cpu-x dasher z battery life apk mirror
-cpu-x dasher z battery life for windows
-cpu-x dasher z battery life app justuseapp
-cpu-x dasher z battery life software troubleshooting
-cpu-x dasher z battery life apk pure
-cpu-x dasher z battery life for linux
-cpu-x dasher z battery life app rating
-cpu-x dasher z battery life software contact
-cpu-x dasher z battery life apk uptodown
-cpu-x dasher z battery life for pc
-cpu-x dasher z battery life app screenshots
-cpu-x dasher z battery life software delete/cancel
-cpu-x dasher z battery life apk old version
-cpu-x dasher z battery life for chromebook
-cpu-x dasher z battery life app description
-cpu-x dasher z battery life software company name
-cpu-x dasher z battery life apk online
-cpu-x dasher z battery life for web browser
-cpu-x dasher z battery life app overview
-cpu-x dasher z battery life software update history
-cpu-x dasher z battery life apk cracked

-
    -
  1. Go to the official website of CPU-x Dasher z Battery Life APK or click on this link
  2. -
  3. Tap on the "Download" button and wait for the download to complete
  4. -
  5. Open the downloaded file and tap on "Install"
  6. -
  7. Allow the app to access your device settings and permissions
  8. -
  9. Launch the app and enjoy its features
  10. -
-

How to Use CPU-x Dasher z Battery Life APK

-

CPU-x Dasher z Battery Life APK is easy to use. You just need to launch the app and tap on the icons that correspond to the information you want to query or monitor. Here are some tips on how to use CPU-x Dasher z Battery Life APK for different purposes:

-

How to Check Your Phone's Hardware and System Information

-

To check your phone's hardware and system information, you can tap on the "CPU" icon on the main screen of the app. You will see a list of information such as CPU model, cores, frequency, architecture, cache, instruction set, and temperature. You can also see the system information such as device model, name, serial number, operating system, version, build number, kernel version, uptime, and battery level. You can swipe left or right to switch between different categories of information.

-

How to Monitor Your Network Speed and Traffic

-

To monitor your network speed and traffic, you can tap on the "Network" icon on the main screen of the app. You will see a graph that shows the upload and download speed of your network in real-time. You can also see the network type, IP address, MAC address, DNS server, gateway, subnet mask, and proxy settings. You can also see the WiFi hotspot information such as SSID, BSSID, channel, frequency, signal strength, security type, and password. You can swipe left or right to switch between different categories of information.

-

How to View Your Phone's Screen and Camera Details

-

To view your phone's screen and camera details, you can tap on the "Screen" icon on the main screen of the app. You will see a list of information such as screen size, resolution, density, refresh rate, brightness, contrast ratio, color gamut, HDR support, and notch size. You can also see the camera details such as camera model, resolution, focal length, aperture, ISO, shutter speed, flash mode, zoom level, and video recording quality. You can swipe left or right to switch between different categories of information.

-

How to Check Your Memory and Storage Usage

-

To check your memory and storage usage, you can tap on the "Memory" icon on the main screen of the app. You will see a pie chart that shows the percentage of memory and storage used and available on your phone. You can also see the total memory and storage capacity of your phone. You can tap on the "Clean" button to free up some memory and storage space by deleting unnecessary files and cache data.

-

How to Use the Health Widget

-

To use the health widget, you need to enable it from the settings menu of the app. You can then see a small widget on the main screen of the app that displays steps, distance, and calories data from the "health" app. You can tap on the widget to open the "health" app and view more details about your health data.

-

Pros and Cons of CPU-x Dasher z Battery Life APK

-

CPU-x Dasher z Battery Life APK is a useful app that can help you query your phone's hardware and system information, monitor your network speed and traffic, view your phone's screen and camera details, check your memory and storage usage, and use a health widget that displays steps, distance, and calories data from the "health" app. However, like any other app, it also has some pros and cons that you should consider before downloading and installing it. Here are some of the pros and cons of CPU-x Dasher z Battery Life APK:

-

Pros

-
    -
  • It provides accurate real-time CPU frequency calculation with low system resource usage
  • -
  • It allows users to view various hardware and system information in one app
  • -
  • It supports iPhone13 series and iPad Mini 6 models
  • -
  • It has a user-friendly interface with simple interaction
  • -
  • It has a health widget that displays steps, distance, and calories data from the "health" app
  • -
-

Cons

-
    -
  • It requires access to device settings and permissions that some users might not feel comfortable with
  • -
  • It might not be compatible with some older or newer models of phones or tablets
  • -
  • It might have some bugs or errors that need to be fixed or updated
  • -
  • It might drain the battery faster than normal due to constant monitoring and calculation
  • -
  • It might not provide all the information that users need or want
  • -
-

Comparison Table of CPU-x Dasher z Battery Life APK and Other Similar Apps

-

To help you decide whether CPU-x Dasher z Battery Life APK is the best app for you, we have created a comparison table that shows how it compares with other similar apps in terms of features, ratings, reviews, and price. Here is the comparison table:

- - - - - - - -
App NameFeaturesRatingsReviewsPrice
CPU-x Dasher z Battery Life APKCPU frequency calculation, hardware and system information, network speed and traffic monitoring, screen and camera details, memory and storage usage, health widget4.5/5 stars"Great app for checking phone performance and battery life"Free
CPU-Z - Hardware Info & System MonitorCPU frequency calculation, hardware and system information, network speed and traffic monitoring, screen and camera details, memory and storage usage4.3/5 stars"Good app but needs more updates and improvements"$0.99
CPU Monitor - Temperature & Usage StatsCPU frequency calculation, hardware and system information, network speed and traffic monitoring, memory and storage usage, battery temperature and health status4.1/5 stars"Useful app but sometimes inaccurate or slow"$1.99
CPU X - Device & System Info & Network MonitorCPU frequency calculation, hardware and system information, network speed and traffic monitoring, screen and camera details, memory and storage usage, battery temperature and health status, device benchmarking3.9/5 stars"Nice app but too many ads and permissions"$2.99
CPU Identifier - Hardware Info & System MonitorCPU frequency calculation, hardware and system information, network speed and traffic monitoring, screen and camera details, memory and storage usage, device benchmarking, sensor data3.7/5 stars"Decent app but not very user-friendly or reliable"$3.99
-

Conclusion

-

CPU-x Dasher z Battery Life APK is a mobile app that can help you query your phone's hardware and system information, monitor your network speed and traffic, view your phone's screen and camera details, check your memory and storage usage, and use a health widget that displays steps, distance, and calories data from the "health" app. It has a user-friendly interface with simple interaction and supports iPhone13 series and iPad Mini 6 models. It also provides accurate real-time CPU frequency calculation with low system resource usage. However, it also has some drawbacks such as requiring access to device settings and permissions, being incompatible with some models of phones or tablets, having some bugs or errors, draining the battery faster than normal, and not providing all the information that users need or want. Therefore, you should weigh the pros and cons of CPU-x Dasher z Battery Life APK before downloading and installing it on your phone. You can also compare it with other similar apps in terms of features, ratings, reviews, and price to find the best app for you.

-

FAQs

-

Here are some frequently asked questions about CPU-x Dasher z Battery Life APK:

-
    -
  1. What is the difference between CPU-x Dasher z Battery Life APK and CPU-Z - Hardware Info & System Monitor?
  2. -

    CPU-x Dasher z Battery Life APK and CPU-Z - Hardware Info & System Monitor are both mobile apps that allow users to query their phone's hardware and system information, monitor their network speed and traffic, view their phone's screen and camera details, and check their memory and storage usage. However, CPU-x Dasher z Battery Life APK has some additional features such as a health widget that displays steps, distance, and calories data from the "health" app, support for iPhone13 series and iPad Mini 6 models, and a free price. CPU-Z - Hardware Info & System Monitor has a $0.99 price tag and does not have a health widget or support for iPhone13 series and iPad Mini 6 models.

    -
  3. How can I update CPU-x Dasher z Battery Life APK to the latest version?
  4. -

    To update CPU-x Dasher z Battery Life APK to the latest version, you can go to the official website of CPU-x Dasher z Battery Life APK or click on this link and tap on the "Download" button. You can then install the updated version of the app on your phone by following the same steps as mentioned above.

    -
  5. Is CPU-x Dasher z Battery Life APK safe to use?
  6. -

    CPU-x Dasher z Battery Life APK is safe to use as long as you download it from the official website or a trusted source. However, you should be aware that the app requires access to your device settings and permissions such as location, camera, microphone, photos, media, files, network connections, WiFi connections, Bluetooth connections, device ID, call information, etc. You should only grant these permissions if you trust the app and its developers. You should also scan the app for viruses or malware before installing it on your phone.

    -
  7. Can I use CPU-x Dasher z Battery Life APK on my Android phone or tablet?
  8. -

    No, you cannot use CPU-x Dasher z Battery Life APK on your Android phone or tablet. The app is only compatible with iOS devices such as iPhones and iPads. If you want to use a similar app on your Android device, you can try one of the other apps mentioned in the comparison table above.

    -
  9. How can I contact the developers of CPU-x Dasher z Battery Life APK?
  10. -

    If you have any questions, feedback, suggestions, or complaints about CPU-x Dasher z Battery Life APK, you can contact the developers of the app by sending an email to cpu.x.dasher.z.battery.life.apk@gmail.com. You can also visit their Facebook page or Twitter account for more information.

    -

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/fatiXbelha/sd/Download Kick The Buddy 3D APK for Android - The Ultimate Stress Relief Game.md b/spaces/fatiXbelha/sd/Download Kick The Buddy 3D APK for Android - The Ultimate Stress Relief Game.md deleted file mode 100644 index 1b6ea8c741541082f8c6a70f68c84ff682633bac..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Download Kick The Buddy 3D APK for Android - The Ultimate Stress Relief Game.md +++ /dev/null @@ -1,126 +0,0 @@ - -

Kick the Buddy 3D: A Fun and Stress-Relieving Game

-

Do you ever feel angry, frustrated, or bored and want to vent your emotions in a safe and harmless way? If so, you might want to try Kick the Buddy 3D, a casual and action-packed game that lets you unleash your creativity and imagination on a ragdoll named Buddy. In this game, you can use a variety of weapons, items, and tools to destroy, torture, or play with Buddy in different environments and levels. Whether you want to shoot him with a gun, explode him with a bomb, freeze him with an ice cream, or dress him up with funny costumes, you can do it all in Kick the Buddy 3D. This game is not only a great way to relieve stress, but also a fun and entertaining game that will make you laugh and smile. In this article, we will tell you more about Kick the Buddy 3D, how to play it, why you should play it, where to download it, and what are some alternatives to it.

-

kick the buddy 3d download


DOWNLOADhttps://urllie.com/2uNCiA



-

What is Kick the Buddy 3D?

-

A brief introduction to the game and its features

-

Kick the Buddy 3D is a casual and single-player game developed by Playgendary for Android and iOS devices. It is a sequel to the popular game Kick the Buddy, which was released in 2011. The game features a ragdoll character named Buddy, who is your target and companion in the game. You can interact with him in various ways, such as hitting, throwing, burning, shooting, smashing, freezing, or using the power of the gods. You can also customize his appearance with different outfits and accessories. The game offers a wide range of weapons and items to use, such as knives, guns, rockets, lasers, flamethrowers, tanks, atomic bombs, and more. You can also choose from different environments and levels to play in, such as a kitchen, a garage, a forest, a desert, a city, and more. Each environment has its own unique features and challenges.

-

How to play Kick the Buddy 3D?

-

The basic gameplay and controls

-

The gameplay of Kick the Buddy 3D is simple and intuitive. You just need to tap on the screen to select a weapon or item from the menu at the bottom. Then you can drag or swipe on the screen to use it on Buddy. You can also tap on Buddy to grab him and move him around. You can also pinch or zoom on the screen to change the perspective. The game does not have any rules or objectives. You can play as long as you want and do whatever you want with Buddy. You can also pause or resume the game at any time.

-

The different weapons and items to use

-

The game offers a huge variety of weapons and items to use on Buddy. You can find them in different categories on the menu at the bottom of the screen. Some of them are free to use, while others require coins or gems to unlock. You can earn coins by playing the game or watching ads. You can also buy coins or gems with real money if you want. Here are some examples of weapons and items that you can use:

-
    -
  • Firearms: Pistols, rifles, shotguns, machine guns, snipers, bazookas, etc.
  • -
  • Explosives: Gren

    ades, mines, dynamites, fireworks, atomic bombs, etc.

  • -
  • Cold weapons: Knives, swords, axes, hammers, spears, etc.
  • -
  • Tools: Drills, saws, scissors, needles, nails, etc.
  • -
  • Food: Fruits, vegetables, cakes, ice creams, pizzas, etc.
  • -
  • Animals: Dogs, cats, snakes, spiders, sharks, dinosaurs, etc.
  • -
  • Sports: Balls, bats, rackets, golf clubs, bowling pins, etc.
  • -
  • Machines: Cars, trucks, motorcycles, tanks, helicopters, planes, etc.
  • -
  • Magic: Lightning, fireballs, tornadoes, earthquakes, etc.
  • -
  • Gods: Zeus, Thor, Poseidon, Hades, etc.
  • -
  • Miscellaneous: Balloons, pillows, guitars, gunslingers, pirates, ninjas, etc.
  • -
-

The various environments and levels to explore

-

The game also offers a wide range of environments and levels to play in. You can find them in different categories on the menu at the top of the screen. Some of them are free to play, while others require coins or gems to unlock. You can also buy coins or gems with real money if you want. Here are some examples of environments and levels that you can play:

-
    -
  • Kitchen: A place where you can use kitchen utensils and food to mess with Buddy.
  • -
  • Garage: A place where you can use tools and machines to damage Buddy.
  • -
  • Forest: A place where you can use nature and animals to torment Buddy.
  • -
  • Desert: A place where you can use heat and sand to torture Buddy.
  • -
  • City: A place where you can use urban elements and vehicles to destroy Buddy.
  • -
  • Laboratory: A place where you can use science and experiments to test Buddy.
  • -
  • Museum: A place where you can use history and art to play with Buddy.
  • -
  • Circus: A place where you can use fun and humor to make Buddy laugh or cry.
  • -
  • Hell: A place where you can use fire and demons to make Buddy suffer.
  • -
  • Heaven: A place where you can use light and angels to make Buddy happy or sad.
  • -
-

Why play Kick the Buddy 3D?

-

The benefits of playing a stress-relieving game

-

Kick the Buddy 3D is not just a game for fun. It is also a game for stress relief. According to some studies , playing violent video games can help reduce stress and aggression by providing a safe and harmless outlet for negative emotions. Playing Kick the Buddy 3D can help you cope with anger, frustration, boredom, anxiety, or depression by letting you vent your feelings on a virtual doll that does not feel any pain or harm. You can also express your creativity and imagination by using different weapons and items on Buddy. Playing Kick the Buddy 3D can also improve your mood and mental health by making you laugh and smile at the funny and absurd situations that happen in the game.

-

The fun and humor of the game

-

Kick the Buddy 3D is also a game for entertainment. It is a game that will make you laugh and smile at the hilarious and ridiculous things that you can do with Buddy. You can enjoy the witty and sarcastic comments that Buddy makes as you interact with him. You can also appreciate the humorous and cartoonish animations and sound effects that accompany your actions. You can also have fun by customizing Buddy's appearance with different outfits and accessories. You can make him look like a superhero, a pirate, a ninja, or anything you want. You can also share your screenshots and videos of your gameplay with your friends and family on social media.

-

The amazing 3D graphics and sound effects

-

Kick the Buddy 3D is also a game for visual and auditory pleasure. It is a game that will impress you with its stunning and realistic 3D graphics and sound effects. You can admire the detailed and colorful design of Buddy, the weapons, the items, and the environments. You can also enjoy the immersive and dynamic sound effects that match your actions and the situations. You can also adjust the graphics and sound settings to suit your preferences and device performance.

-

Where to download Kick the Buddy 3D?

-

The availability of the game on different platforms

-

Kick the Buddy 3D is available for Android and iOS devices. You can download it from the Google Play Store or the App Store for free. The game requires an internet connection to play and access some features. The game also contains ads and in-app purchases that you can disable or enable according to your choice.

-

kick the buddy 3d apk free download
-kick the buddy 3d online game
-kick the buddy 3d mod apk unlimited money
-kick the buddy 3d playgendary
-kick the buddy 3d pc download
-kick the buddy 3d gameforge
-kick the buddy 3d model free
-kick the buddy 3d cheats and hacks
-kick the buddy 3d latest version
-kick the buddy 3d android game
-kick the buddy 3d html5 game
-kick the buddy 3d weapons list
-kick the buddy 3d review and rating
-kick the buddy 3d gameplay video
-kick the buddy 3d tips and tricks
-kick the buddy 3d for ios devices
-kick the buddy 3d unblocked games
-kick the buddy 3d no ads option
-kick the buddy 3d offline mode
-kick the buddy 3d new levels and features
-kick the buddy 3d how to play guide
-kick the buddy 3d best weapons to use
-kick the buddy 3d fun and stress relief game
-kick the buddy 3d update and patch notes
-kick the buddy 3d support and feedback
-kick the buddy 3d alternatives and similar games
-kick the buddy 3d download size and requirements
-kick the buddy 3d free coins and gems generator
-kick the buddy 3d install and setup instructions
-kick the buddy 3d bugs and issues report
-kick the buddy 3d fan art and wallpapers
-kick the buddy 3d memes and jokes collection
-kick the buddy 3d wiki and information page
-kick the buddy 3d forum and community group
-kick the buddy 3d gift codes and redeem coupons
-kick the buddy 3d soundtrack and music download
-kick the buddy 3d easter eggs and secrets revealed
-kick the buddy 3d comparison with previous versions
-kick the buddy 3d frequently asked questions (FAQ)
-kick the buddy 3d developer contact and social media links

-

The download links and instructions

-

To download Kick the Buddy 3D, you can follow these simple steps:

-
    -
  1. Go to the Google Play Store or the App Store on your device.
  2. -
  3. Search for Kick the Buddy 3D or use these links: Google Play Store or App Store.
  4. -
  5. Tap on the Install or Get button to start downloading the game.
  6. -
  7. Wait for the download to finish and then open the game.
  8. -
  9. Enjoy playing Kick the Buddy 3D!
  10. -
-

What are some alternatives to Kick the Buddy 3D?

-

A list of similar games with brief descriptions

-

If you like Kick the Buddy 3D, you might also like these similar games that offer fun and stress relief:

-
    -
  • Kick the Buddy: The original game that started it all. It has similar gameplay and features as Kick the Buddy 3D, but with 2D graphics and sound effects.
  • -
  • Buddy Toss: A game that lets you toss Buddy into the air and see how far he can go. You can also upgrade your power and unlock new costumes for Buddy.
  • -
  • Buddyman: Kick: A game that features a superhero version of Buddy, who can withstand more damage and use more weapons. You can also collect coins and gems to buy new items and outfits.
  • -
  • Beat the Boss: A game that lets you take revenge on your annoying boss by using various weapons and items. You can also customize your boss's appearance and voice.
  • -
  • Dude Theft Wars: A game that lets you explore an open world full of chaos and fun. You can use guns, cars, bikes, planes, tanks, and more to cause mayhem and destruction.
  • -
-

Conclusion

-

Kick the Buddy 3D is a fun and stress-relieving game that lets you unleash your creativity and imagination on a ragdoll named Buddy. You can use a variety of weapons, items, and tools to destroy, torture, or play with Buddy in different environments and levels. You can also customize his appearance with different outfits and accessories. The game is not only a great way to relieve stress, but also a fun and entertaining game that will make you laugh and smile. The game has amazing 3D graphics and sound effects that will enhance your gaming experience. You can download Kick the Buddy 3D from the Google Play Store or the App Store for free. You can also try some alternatives to Kick the Buddy 3D if you want more fun and stress relief.

-

Frequently Asked Questions

-

Here are some common questions that people have about Kick the Buddy 3D:

-
    -
  1. Is Kick the Buddy 3D suitable for children?
  2. -

    Kick the Buddy 3D is rated 12+ on the Google Play Store and 9+ on the App Store for violence, blood, gore, profanity, crude humor, etc. Therefore, it is not suitable for young children who might be disturbed or influenced by these elements. Parents should supervise their children's gameplay or use parental controls to restrict their access to this game.

    -
  3. How do I get more coins or gems in Kick the Buddy 3D?
  4. -

    You can get more coins or gems in Kick the Buddy 3D by playing the game or watching ads. You can also buy coins or gems with real money if you want. You can use coins or gems to unlock new weapons, items, environments, and levels in the game.

    -
  5. How do I remove ads or in-app purchases in Kick the Buddy 3D?
  6. -

    You can remove ads or in-app purchases in Kick the Buddy 3D by paying a one-time fee of $2.99. You can do this by tapping on the No Ads or No In-App Purchases buttons on the menu at the top of the screen. You can also restore your purchase if you change your device or reinstall the game.

    -
  7. How do I contact the developer of Kick the Buddy 3D?
  8. -

    You can contact the developer of Kick the Buddy 3D by sending an email to support@playgendary.com. You can also visit their website at https://playgendary.com/ or follow them on Facebook, Twitter, Instagram, or YouTube for more updates and information.

    -
  9. How do I rate or review Kick the Buddy 3D?
  10. -

    You can rate or review Kick the Buddy 3D by going to the Google Play Store or the App Store on your device. You can also leave your feedback or suggestions on their social media pages or email them to support@playgendary.com.

    -

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/fatiXbelha/sd/Explore the Holiday Island of Fuerteventura with Tourist Bus Simulator.md b/spaces/fatiXbelha/sd/Explore the Holiday Island of Fuerteventura with Tourist Bus Simulator.md deleted file mode 100644 index 68245e7bba18fca42aee567471b1c8a8781c1144..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Explore the Holiday Island of Fuerteventura with Tourist Bus Simulator.md +++ /dev/null @@ -1,92 +0,0 @@ -
-

Tourist Bus Simulator Free Download: How to Start Your Own Bus Company on Fuerteventura

-

Have you ever dreamed of driving a bus and running your own transportation business? If so, you might want to check out Tourist Bus Simulator, a realistic and immersive simulation game that lets you create your own bus empire on the popular holiday island Fuerteventura. In this article, we will show you how to download and install Tourist Bus Simulator for free on your PC, how to play the game, and some tips and tricks to help you succeed in your bus career.

-

tourist bus simulator free download


Download File ===> https://urllie.com/2uNyI9



-

What is Tourist Bus Simulator?

-

Tourist Bus Simulator is a bus simulator game developed by TML-Studios and published by Aerosoft for Microsoft Windows. The game is powered by Unreal Engine 4 and was initially available on 6 December 2018 worldwide.

-

The game is set in Fuerteventura of the Canary Islands, featuring a total of twenty recreated cities, beaches and locations such as the Fuerteventura Airport. The main licensed vehicle in the game that offers to the player is MAN Lion's Coach, as well as other off-road and service vehicles.

-

Thanks to the economy system in the new Tourist Bus Simulator, you will be able to found your own bus company on Fuerteventura. Your offer comprises scheduled routes, hotel shuttles or sightseeing tours. Furthermore, you also have to manage your fleet, including vehicle care and maintenance, and employee planning. If you are successful, you can continuously expand your fleet.

-

How to Download and Install Tourist Bus Simulator

-

To download and install Tourist Bus Simulator for free on your PC, you will need to follow these steps:

-

How to play tourist bus simulator on PC with LDPlayer emulator
-Tourist bus simulator driving game for Android devices
-Tourist bus simulator free download full version for Windows
-Tourist bus simulator Fuerteventura map and routes guide
-Tourist bus simulator system requirements and performance tips
-Tourist bus simulator mods and customizations
-Tourist bus simulator review and gameplay videos
-Tourist bus simulator cheats and hacks
-Tourist bus simulator online multiplayer mode
-Tourist bus simulator best buses and designs
-Tourist bus simulator tips and tricks for beginners
-Tourist bus simulator comparison with other bus simulation games
-Tourist bus simulator features and updates
-Tourist bus simulator FAQs and troubleshooting
-Tourist bus simulator feedback and suggestions
-Tourist bus simulator free trial and demo version
-Tourist bus simulator coupon codes and discounts
-Tourist bus simulator alternatives and similar games
-Tourist bus simulator community and forums
-Tourist bus simulator news and events

-
    -
  1. Go to GameTrex, a website that offers free downloads of PC games.
  2. -
  3. Click on the green "Download" button under the title "Tourist Bus Simulator Free Download".
  4. -
  5. Choose a mirror link from the list and click on it. You will be redirected to a file hosting site where you can download the game files.
  6. -
  7. Extract the downloaded files using WinRAR or 7-Zip.
  8. -
  9. Run the setup file and follow the instructions to install the game.
  10. -
  11. Copy the crack files from the CODEX folder and paste them into the game installation folder.
  12. -
  13. Launch the game from the desktop shortcut or the .exe file in the game folder.
  14. -
  15. Enjoy playing Tourist Bus Simulator for free!
  16. -
-

Note: Tourist Bus Simulator has not been cracked yet for Steam users. If you want to play the game on Steam, you will need to purchase it from Steam Store.

-

How to Play Tourist Bus Simulator

-

To play Tourist Bus Simulator, you will need to learn how to operate your bus and how to run your business. Here are some basics of the gameplay:

-
    -
  • You can choose between different bus designs and sizes to suit each task. You can also customize your buses with different colors and decals.
  • -
  • You can drive your bus manually or use automatic transmission. You will need to follow traffic rules, signals, speed limits, and road signs. You will also need to use - You can drive your bus manually or use automatic transmission. You will need to follow traffic rules, signals, speed limits, and road signs. You will also need to use indicators, headlights, wipers, horn, and other features of your bus. You can also switch between different camera views, such as cockpit, exterior, or free camera.
  • -
  • You can choose between different game modes, such as free play, campaign, or multiplayer. In free play mode, you can explore the island and drive any bus you want. In campaign mode, you will start with a small bus company and grow it by completing various tasks and missions. In multiplayer mode, you can join other players online and cooperate or compete with them.
  • -
  • You can earn money by transporting passengers, delivering goods, or completing special orders. You can use the money to buy new buses, upgrade your garage, hire employees, or expand your routes. You can also take loans from the bank if you need more funds.
  • -
  • You can manage your company by using the office menu. Here you can see your income and expenses, your fleet and employees, your routes and customers, and your reputation and achievements. You can also adjust the settings of your company, such as the ticket prices, the wages, the maintenance costs, and the marketing strategies.
  • -
  • You can interact with your passengers, employees, and customers by using the dialogue system. You can greet them, ask them questions, give them instructions, or respond to their requests. You can also use the radio or the phone to communicate with other drivers or clients.
  • -
-

Tips and Tricks for Tourist Bus Simulator

-

Tourist Bus Simulator is a complex and challenging game that requires skill and strategy. Here are some tips and tricks to help you master the game:

-
    -
  • Plan your routes carefully. You should consider the distance, the traffic, the weather, the fuel consumption, and the passenger demand of each route. You should also avoid overlapping routes or creating gaps in your service.
  • -
  • Keep your buses in good condition. You should regularly check the status of your buses and perform maintenance tasks such as refueling, washing, repairing, or servicing. You should also avoid damaging your buses by driving carefully and avoiding collisions or accidents.
  • -
  • Train your employees well. You should hire qualified drivers and mechanics for your company and assign them to suitable tasks. You should also pay them fairly and motivate them with bonuses or promotions. You should also monitor their performance and feedback and fire them if they are incompetent or dishonest.
  • -
  • Satisfy your customers well. You should provide a comfortable and safe ride for your passengers and deliver a high-quality service for your clients. You should also listen to their complaints or suggestions and improve your service accordingly. You should also offer discounts or loyalty programs to attract more customers.
  • -
  • Compete with other companies well. You should research the market and find out the strengths and weaknesses of your competitors. You should also try to outperform them by offering better prices, services, or routes. You should also cooperate with them if possible and form alliances or partnerships.
  • -
-

Conclusion

-

Tourist Bus Simulator is a fun and realistic game that lets you experience the life of a bus driver and a bus entrepreneur on Fuerteventura. You can download and install Tourist Bus Simulator for free on your PC by following our guide above. You can also play Tourist Bus Simulator by following our summary of the gameplay above. And you can succeed in Tourist Bus Simulator by following our tips and tricks above.

-

If you are looking for a game that combines driving simulation with business management, Tourist Bus Simulator is the game for you. So what are you waiting for? Download Tourist Bus Simulator today and start your own bus company on Fuerteventura!

-

FAQs

-

Q: What are the system requirements for Tourist Bus Simulator?

-

A: The minimum system requirements for Tourist Bus Simulator are:

-
    -
  • OS: Windows 7 / 8 / 8.1 / 10 (64 bit)
  • -
  • Processor: Intel Core i5 Processor or similar with at least 2.6 GHz
  • -
  • Memory: 6 GB RAM
  • -
  • Graphics: Nvidia GeForce GTX 560 or similar AMD Radeon (no support for onboard cards)
  • -
  • DirectX: Version 11
  • -
  • Storage: 25 GB available space
  • -
-

Q: How many buses are there in Tourist Bus Simulator?

-

A: There are six buses in Tourist Bus Simulator:

-
    -
  • MAN Lion's Coach
  • -
  • MAN Lion's Coach C
  • -
  • - MAN Lion's Coach L
  • -
  • MAN Lion's Intercity
  • -
  • MAN Lion's City A47
  • -
  • MAN Lion's City A21
  • -
-

Q: How can I update Tourist Bus Simulator?

-

A: You can update Tourist Bus Simulator by using the Aerosoft Updater, a tool that allows you to download and install the latest patches and updates for the game. You can find the Aerosoft Updater in the game installation folder or download it from Aerosoft Support.

-

Q: How can I get more content for Tourist Bus Simulator?

-

A: You can get more content for Tourist Bus Simulator by purchasing DLCs (downloadable content) that add new features, vehicles, or locations to the game. You can find the available DLCs for Tourist Bus Simulator on Steam Store or Aerosoft Shop.

-

Q: How can I contact the developers of Tourist Bus Simulator?

-

A: You can contact the developers of Tourist Bus Simulator by visiting their official website TML-Studios or their social media pages on Facebook, Twitter, or YouTube. You can also join their community forums on TML-Studios Forum or Steam Community Hub.

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/fclong/summary/fengshen/examples/clue1.1/predict2submit.sh b/spaces/fclong/summary/fengshen/examples/clue1.1/predict2submit.sh deleted file mode 100644 index 9da7445929bef2c2e3829d0827b26fd5ba8d2d0f..0000000000000000000000000000000000000000 --- a/spaces/fclong/summary/fengshen/examples/clue1.1/predict2submit.sh +++ /dev/null @@ -1,16 +0,0 @@ - -PRED_DATA_PATH=./predict -SUBMIT_DATA_PATH=./submit - -SCRIPT_PATH=./predict2submit - -python $SCRIPT_PATH/afqmc_submit.py --data_path=$PRED_DATA_PATH/afqmc-M4_predict.json --save_path=$SUBMIT_DATA_PATH/afqmc_predict.json -python $SCRIPT_PATH/c3_submit.py --data_path=$PRED_DATA_PATH/c3_predict.json --save_path=$SUBMIT_DATA_PATH/c311_predict.json -python $SCRIPT_PATH/chid_submit.py --data_path=$PRED_DATA_PATH/chid_predict.json --save_path=$SUBMIT_DATA_PATH/chid11_predict.json -python $SCRIPT_PATH/csl_submit.py --data_path=$PRED_DATA_PATH/csl_predict.json --save_path=$SUBMIT_DATA_PATH/csl_predict.json -python $SCRIPT_PATH/iflytek_submit.py --data_path=$PRED_DATA_PATH/iflytek_predict.json --save_path=$SUBMIT_DATA_PATH/iflytek_predict.json -python $SCRIPT_PATH/ocnli_submit.py --data_path=$PRED_DATA_PATH/ocnli_predict.json --save_path=$SUBMIT_DATA_PATH/ocnli_50k_predict.json -python $SCRIPT_PATH/tnews_submit.py --data_path=$PRED_DATA_PATH/tnews_predict.json --save_path=$SUBMIT_DATA_PATH/tnews11_predict.json -python $SCRIPT_PATH/wsc_submit.py --data_path=$PRED_DATA_PATH/wsc_predict.json --save_path=$SUBMIT_DATA_PATH/cluewsc11_predict.json - -python $SCRIPT_PATH/cmrc2018_submit.py --data_path=$PRED_DATA_PATH/cmrc2018_predict.json --save_path=$SUBMIT_DATA_PATH/cmrc2018_predict.json diff --git a/spaces/feng2022/Time-TravelRephotography/Time_TravelRephotography/model.py b/spaces/feng2022/Time-TravelRephotography/Time_TravelRephotography/model.py deleted file mode 100644 index 67aec32b7857fba2767c30ce31667c7dbd19091d..0000000000000000000000000000000000000000 --- a/spaces/feng2022/Time-TravelRephotography/Time_TravelRephotography/model.py +++ /dev/null @@ -1,697 +0,0 @@ -import math -import random -import functools -import operator -import numpy as np - -import torch -from torch import nn -from torch.nn import functional as F -from torch.autograd import Function - -from op import FusedLeakyReLU, fused_leaky_relu, upfirdn2d - - -class PixelNorm(nn.Module): - def __init__(self): - super().__init__() - - def forward(self, input): - return input * torch.rsqrt(torch.mean(input ** 2, dim=1, keepdim=True) + 1e-8) - - -def make_kernel(k): - k = torch.tensor(k, dtype=torch.float32) - - if k.ndim == 1: - k = k[None, :] * k[:, None] - - k /= k.sum() - - return k - - -class Upsample(nn.Module): - def __init__(self, kernel, factor=2): - super().__init__() - - self.factor = factor - kernel = make_kernel(kernel) * (factor ** 2) - self.register_buffer('kernel', kernel) - - p = kernel.shape[0] - factor - - pad0 = (p + 1) // 2 + factor - 1 - pad1 = p // 2 - - self.pad = (pad0, pad1) - - def forward(self, input): - out = upfirdn2d(input, self.kernel, up=self.factor, down=1, pad=self.pad) - - return out - - -class Downsample(nn.Module): - def __init__(self, kernel, factor=2): - super().__init__() - - self.factor = factor - kernel = make_kernel(kernel) - self.register_buffer('kernel', kernel) - - p = kernel.shape[0] - factor - - pad0 = (p + 1) // 2 - pad1 = p // 2 - - self.pad = (pad0, pad1) - - def forward(self, input): - out = upfirdn2d(input, self.kernel, up=1, down=self.factor, pad=self.pad) - - return out - - -class Blur(nn.Module): - def __init__(self, kernel, pad, upsample_factor=1): - super().__init__() - - kernel = make_kernel(kernel) - - if upsample_factor > 1: - kernel = kernel * (upsample_factor ** 2) - - self.register_buffer('kernel', kernel) - - self.pad = pad - - def forward(self, input): - out = upfirdn2d(input, self.kernel, pad=self.pad) - - return out - - -class EqualConv2d(nn.Module): - def __init__( - self, in_channel, out_channel, kernel_size, stride=1, padding=0, bias=True - ): - super().__init__() - - self.weight = nn.Parameter( - torch.randn(out_channel, in_channel, kernel_size, kernel_size) - ) - self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2) - - self.stride = stride - self.padding = padding - - if bias: - self.bias = nn.Parameter(torch.zeros(out_channel)) - - else: - self.bias = None - - def forward(self, input): - out = F.conv2d( - input, - self.weight * self.scale, - bias=self.bias, - stride=self.stride, - padding=self.padding, - ) - - return out - - def __repr__(self): - return ( - f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]},' - f' {self.weight.shape[2]}, stride={self.stride}, padding={self.padding})' - ) - - -class EqualLinear(nn.Module): - def __init__( - self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1, activation=None - ): - super().__init__() - - self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul)) - - if bias: - self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init)) - - else: - self.bias = None - - self.activation = activation - - self.scale = (1 / math.sqrt(in_dim)) * lr_mul - self.lr_mul = lr_mul - - def forward(self, input): - if self.activation: - out = F.linear(input, self.weight * self.scale) - out = fused_leaky_relu(out, self.bias * self.lr_mul) - - else: - out = F.linear( - input, self.weight * self.scale, bias=self.bias * self.lr_mul - ) - - return out - - def __repr__(self): - return ( - f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})' - ) - - -class ScaledLeakyReLU(nn.Module): - def __init__(self, negative_slope=0.2): - super().__init__() - - self.negative_slope = negative_slope - - def forward(self, input): - out = F.leaky_relu(input, negative_slope=self.negative_slope) - - return out * math.sqrt(2) - - -class ModulatedConv2d(nn.Module): - def __init__( - self, - in_channel, - out_channel, - kernel_size, - style_dim, - demodulate=True, - upsample=False, - downsample=False, - blur_kernel=[1, 3, 3, 1], - ): - super().__init__() - - self.eps = 1e-8 - self.kernel_size = kernel_size - self.in_channel = in_channel - self.out_channel = out_channel - self.upsample = upsample - self.downsample = downsample - - if upsample: - factor = 2 - p = (len(blur_kernel) - factor) - (kernel_size - 1) - pad0 = (p + 1) // 2 + factor - 1 - pad1 = p // 2 + 1 - - self.blur = Blur(blur_kernel, pad=(pad0, pad1), upsample_factor=factor) - - if downsample: - factor = 2 - p = (len(blur_kernel) - factor) + (kernel_size - 1) - pad0 = (p + 1) // 2 - pad1 = p // 2 - - self.blur = Blur(blur_kernel, pad=(pad0, pad1)) - - fan_in = in_channel * kernel_size ** 2 - self.scale = 1 / math.sqrt(fan_in) - self.padding = kernel_size // 2 - - self.weight = nn.Parameter( - torch.randn(1, out_channel, in_channel, kernel_size, kernel_size) - ) - - self.modulation = EqualLinear(style_dim, in_channel, bias_init=1) - - self.demodulate = demodulate - - def __repr__(self): - return ( - f'{self.__class__.__name__}({self.in_channel}, {self.out_channel}, {self.kernel_size}, ' - f'upsample={self.upsample}, downsample={self.downsample})' - ) - - def forward(self, input, style): - batch, in_channel, height, width = input.shape - - style = self.modulation(style).view(batch, 1, in_channel, 1, 1) - weight = self.scale * self.weight * style - - if self.demodulate: - demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + 1e-8) - weight = weight * demod.view(batch, self.out_channel, 1, 1, 1) - - weight = weight.view( - batch * self.out_channel, in_channel, self.kernel_size, self.kernel_size - ) - - if self.upsample: - input = input.view(1, batch * in_channel, height, width) - weight = weight.view( - batch, self.out_channel, in_channel, self.kernel_size, self.kernel_size - ) - weight = weight.transpose(1, 2).reshape( - batch * in_channel, self.out_channel, self.kernel_size, self.kernel_size - ) - out = F.conv_transpose2d(input, weight, padding=0, stride=2, groups=batch) - _, _, height, width = out.shape - out = out.view(batch, self.out_channel, height, width) - out = self.blur(out) - - elif self.downsample: - input = self.blur(input) - _, _, height, width = input.shape - input = input.view(1, batch * in_channel, height, width) - out = F.conv2d(input, weight, padding=0, stride=2, groups=batch) - _, _, height, width = out.shape - out = out.view(batch, self.out_channel, height, width) - - else: - input = input.view(1, batch * in_channel, height, width) - out = F.conv2d(input, weight, padding=self.padding, groups=batch) - _, _, height, width = out.shape - out = out.view(batch, self.out_channel, height, width) - - return out - - -class NoiseInjection(nn.Module): - def __init__(self): - super().__init__() - - self.weight = nn.Parameter(torch.zeros(1)) - - def forward(self, image, noise=None): - if noise is None: - batch, _, height, width = image.shape - noise = image.new_empty(batch, 1, height, width).normal_() - - return image + self.weight * noise - - -class ConstantInput(nn.Module): - def __init__(self, channel, size=4): - super().__init__() - - self.input = nn.Parameter(torch.randn(1, channel, size, size)) - - def forward(self, input): - batch = input.shape[0] - out = self.input.repeat(batch, 1, 1, 1) - - return out - - -class StyledConv(nn.Module): - def __init__( - self, - in_channel, - out_channel, - kernel_size, - style_dim, - upsample=False, - blur_kernel=[1, 3, 3, 1], - demodulate=True, - ): - super().__init__() - - self.conv = ModulatedConv2d( - in_channel, - out_channel, - kernel_size, - style_dim, - upsample=upsample, - blur_kernel=blur_kernel, - demodulate=demodulate, - ) - - self.noise = NoiseInjection() - # self.bias = nn.Parameter(torch.zeros(1, out_channel, 1, 1)) - # self.activate = ScaledLeakyReLU(0.2) - self.activate = FusedLeakyReLU(out_channel) - - def forward(self, input, style, noise=None): - out = self.conv(input, style) - out = self.noise(out, noise=noise) - # out = out + self.bias - out = self.activate(out) - - return out - - -class ToRGB(nn.Module): - def __init__(self, in_channel, style_dim, upsample=True, blur_kernel=[1, 3, 3, 1]): - super().__init__() - - if upsample: - self.upsample = Upsample(blur_kernel) - - self.conv = ModulatedConv2d(in_channel, 3, 1, style_dim, demodulate=False) - self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1)) - - def forward(self, input, style, skip=None): - out = self.conv(input, style) - style_modulated = out - out = out + self.bias - - if skip is not None: - skip = self.upsample(skip) - - out = out + skip - - return out, style_modulated - - -class Generator(nn.Module): - def __init__( - self, - size, - style_dim, - n_mlp, - channel_multiplier=2, - blur_kernel=[1, 3, 3, 1], - lr_mlp=0.01, - ): - super().__init__() - - self.size = size - - self.style_dim = style_dim - - layers = [PixelNorm()] - - for i in range(n_mlp): - layers.append( - EqualLinear( - style_dim, style_dim, lr_mul=lr_mlp, activation='fused_lrelu' - ) - ) - - self.style = nn.Sequential(*layers) - - self.channels = { - 4: 512, - 8: 512, - 16: 512, - 32: 512, - 64: 256 * channel_multiplier, - 128: 128 * channel_multiplier, - 256: 64 * channel_multiplier, - 512: 32 * channel_multiplier, - 1024: 16 * channel_multiplier, - } - - self.input = ConstantInput(self.channels[4]) - self.conv1 = StyledConv( - self.channels[4], self.channels[4], 3, style_dim, blur_kernel=blur_kernel - ) - self.to_rgb1 = ToRGB(self.channels[4], style_dim, upsample=False) - - self.log_size = int(math.log(size, 2)) - self.num_layers = (self.log_size - 2) * 2 + 1 - - self.convs = nn.ModuleList() - self.upsamples = nn.ModuleList() - self.to_rgbs = nn.ModuleList() - self.noises = nn.Module() - - in_channel = self.channels[4] - - for layer_idx in range(self.num_layers): - res = (layer_idx + 5) // 2 - shape = [1, 1, 2 ** res, 2 ** res] - self.noises.register_buffer(f'noise_{layer_idx}', torch.randn(*shape)) - - for i in range(3, self.log_size + 1): - out_channel = self.channels[2 ** i] - - self.convs.append( - StyledConv( - in_channel, - out_channel, - 3, - style_dim, - upsample=True, - blur_kernel=blur_kernel, - ) - ) - - self.convs.append( - StyledConv( - out_channel, out_channel, 3, style_dim, blur_kernel=blur_kernel - ) - ) - - self.to_rgbs.append(ToRGB(out_channel, style_dim)) - - in_channel = out_channel - - self.n_latent = self.log_size * 2 - 2 - - @property - def device(self): - # TODO if multi-gpu is expected, could use the following more expensive version - #device, = list(set(p.device for p in self.parameters())) - return next(self.parameters()).device - - @staticmethod - def get_latent_size(size): - log_size = int(math.log(size, 2)) - return log_size * 2 - 2 - - @staticmethod - def make_noise_by_size(size: int, device: torch.device): - log_size = int(math.log(size, 2)) - noises = [torch.randn(1, 1, 2 ** 2, 2 ** 2, device=device)] - - for i in range(3, log_size + 1): - for _ in range(2): - noises.append(torch.randn(1, 1, 2 ** i, 2 ** i, device=device)) - - return noises - - - def make_noise(self): - return self.make_noise_by_size(self.size, self.input.input.device) - - def mean_latent(self, n_latent): - latent_in = torch.randn( - n_latent, self.style_dim, device=self.input.input.device - ) - latent = self.style(latent_in).mean(0, keepdim=True) - - return latent - - def get_latent(self, input): - return self.style(input) - - def forward( - self, - styles, - return_latents=False, - inject_index=None, - truncation=1, - truncation_latent=None, - input_is_latent=False, - noise=None, - randomize_noise=True, - ): - if not input_is_latent: - styles = [self.style(s) for s in styles] - - if noise is None: - if randomize_noise: - noise = [None] * self.num_layers - else: - noise = [ - getattr(self.noises, f'noise_{i}') for i in range(self.num_layers) - ] - - if truncation < 1: - style_t = [] - - for style in styles: - style_t.append( - truncation_latent + truncation * (style - truncation_latent) - ) - - styles = style_t - - if len(styles) < 2: - inject_index = self.n_latent - - if styles[0].ndim < 3: - latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1) - - else: - latent = styles[0] - - else: - if inject_index is None: - inject_index = random.randint(1, self.n_latent - 1) - - latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1) - latent2 = styles[1].unsqueeze(1).repeat(1, self.n_latent - inject_index, 1) - - latent = torch.cat([latent, latent2], 1) - - out = self.input(latent) - out = self.conv1(out, latent[:, 0], noise=noise[0]) - - skip, rgb_mod = self.to_rgb1(out, latent[:, 1]) - - - rgbs = [rgb_mod] # all but the last skip - i = 1 - for conv1, conv2, noise1, noise2, to_rgb in zip( - self.convs[::2], self.convs[1::2], noise[1::2], noise[2::2], self.to_rgbs - ): - out = conv1(out, latent[:, i], noise=noise1) - out = conv2(out, latent[:, i + 1], noise=noise2) - skip, rgb_mod = to_rgb(out, latent[:, i + 2], skip) - rgbs.append(rgb_mod) - - i += 2 - - image = skip - - if return_latents: - return image, latent, rgbs - - else: - return image, None, rgbs - - -class ConvLayer(nn.Sequential): - def __init__( - self, - in_channel, - out_channel, - kernel_size, - downsample=False, - blur_kernel=[1, 3, 3, 1], - bias=True, - activate=True, - ): - layers = [] - - if downsample: - factor = 2 - p = (len(blur_kernel) - factor) + (kernel_size - 1) - pad0 = (p + 1) // 2 - pad1 = p // 2 - - layers.append(Blur(blur_kernel, pad=(pad0, pad1))) - - stride = 2 - self.padding = 0 - - else: - stride = 1 - self.padding = kernel_size // 2 - - layers.append( - EqualConv2d( - in_channel, - out_channel, - kernel_size, - padding=self.padding, - stride=stride, - bias=bias and not activate, - ) - ) - - if activate: - if bias: - layers.append(FusedLeakyReLU(out_channel)) - - else: - layers.append(ScaledLeakyReLU(0.2)) - - super().__init__(*layers) - - -class ResBlock(nn.Module): - def __init__(self, in_channel, out_channel, blur_kernel=[1, 3, 3, 1]): - super().__init__() - - self.conv1 = ConvLayer(in_channel, in_channel, 3) - self.conv2 = ConvLayer(in_channel, out_channel, 3, downsample=True) - - self.skip = ConvLayer( - in_channel, out_channel, 1, downsample=True, activate=False, bias=False - ) - - def forward(self, input): - out = self.conv1(input) - out = self.conv2(out) - - skip = self.skip(input) - out = (out + skip) / math.sqrt(2) - - return out - - -class Discriminator(nn.Module): - def __init__(self, size, channel_multiplier=2, blur_kernel=[1, 3, 3, 1]): - super().__init__() - - channels = { - 4: 512, - 8: 512, - 16: 512, - 32: 512, - 64: 256 * channel_multiplier, - 128: 128 * channel_multiplier, - 256: 64 * channel_multiplier, - 512: 32 * channel_multiplier, - 1024: 16 * channel_multiplier, - } - - convs = [ConvLayer(3, channels[size], 1)] - - log_size = int(math.log(size, 2)) - - in_channel = channels[size] - - for i in range(log_size, 2, -1): - out_channel = channels[2 ** (i - 1)] - - convs.append(ResBlock(in_channel, out_channel, blur_kernel)) - - in_channel = out_channel - - self.convs = nn.Sequential(*convs) - - self.stddev_group = 4 - self.stddev_feat = 1 - - self.final_conv = ConvLayer(in_channel + 1, channels[4], 3) - self.final_linear = nn.Sequential( - EqualLinear(channels[4] * 4 * 4, channels[4], activation='fused_lrelu'), - EqualLinear(channels[4], 1), - ) - - def forward(self, input): - out = self.convs(input) - - batch, channel, height, width = out.shape - group = min(batch, self.stddev_group) - stddev = out.view( - group, -1, self.stddev_feat, channel // self.stddev_feat, height, width - ) - stddev = torch.sqrt(stddev.var(0, unbiased=False) + 1e-8) - stddev = stddev.mean([2, 3, 4], keepdims=True).squeeze(2) - stddev = stddev.repeat(group, 1, height, width) - out = torch.cat([out, stddev], 1) - - out = self.final_conv(out) - - out = out.view(batch, -1) - out = self.final_linear(out) - - return out - diff --git a/spaces/fengmuxi/ChatGpt-Web/app/polyfill.ts b/spaces/fengmuxi/ChatGpt-Web/app/polyfill.ts deleted file mode 100644 index 517f06e7c9338f6589714fe478824e7ae7ea8b44..0000000000000000000000000000000000000000 --- a/spaces/fengmuxi/ChatGpt-Web/app/polyfill.ts +++ /dev/null @@ -1,27 +0,0 @@ -declare global { - interface Array { - at(index: number): T | undefined; - } -} - -if (!Array.prototype.at) { - Array.prototype.at = function (index: number) { - // Get the length of the array - const length = this.length; - - // Convert negative index to a positive index - if (index < 0) { - index = length + index; - } - - // Return undefined if the index is out of range - if (index < 0 || index >= length) { - return undefined; - } - - // Use Array.prototype.slice method to get value at the specified index - return Array.prototype.slice.call(this, index, index + 1)[0]; - }; -} - -export {}; diff --git a/spaces/feregVcuzo/sanity-test-midi/Lounge Lizard Ep 4 _TOP_ Keygen Mac Os.md b/spaces/feregVcuzo/sanity-test-midi/Lounge Lizard Ep 4 _TOP_ Keygen Mac Os.md deleted file mode 100644 index 7daec37d0f77afdeb32b1fad9adeacc9aeb4a331..0000000000000000000000000000000000000000 --- a/spaces/feregVcuzo/sanity-test-midi/Lounge Lizard Ep 4 _TOP_ Keygen Mac Os.md +++ /dev/null @@ -1,86 +0,0 @@ -## lounge lizard ep 4 keygen mac os - - - - - - ![Lounge Lizard Ep 4 _TOP_ Keygen Mac Os](https://cdn.shopify.com/s/files/1/0016/5173/6636/products/LoungeLizardPacks_1200x1200.png?v\u003d1646918920) - - - - - -**Click Here > [https://apconhanstraf.blogspot.com/?c=2tyqdO](https://apconhanstraf.blogspot.com/?c=2tyqdO)** - - - - - - - - - - - - - -# Lounge Lizard EP-4: A Vintage Electric Piano Plug-in for Mac OS - - - -If you are looking for a plug-in that can deliver authentic vintage electric piano sounds, you might want to check out Lounge Lizard EP-4 by Applied Acoustics Systems. Lounge Lizard EP-4 is a plug-in that models the physical components of real electric pianos, such as the hammer, tone, tine, pickup, and cabinet. You can customize your own electric piano sounds by tweaking these parameters, or choose from over 240 presets that cover classic sounds from legends like Stevie Wonder, Herbie Hancock, and Ray Charles, as well as custom sounds and effects. - - - -Lounge Lizard EP-4 also features a new streamlined interface, a new equalizer and compressor module, a new multi-effect processor, and native 64-bit operation on Mac OS X and Windows. It supports VST, Audio Unit, RTAS, AAX Native, NKS, and standalone formats. You can use it with any DAW or host application that supports these formats. - - - -Lounge Lizard EP-4 is available now for $199 from the Applied Acoustics Systems website[^1^]. You can also download a free trial version to test it out before buying. If you already own Lounge Lizard EP-1, EP-2, EP-3, or Session, you can upgrade to EP-4 starting at $39. - - - -Lounge Lizard EP-4 is a plug-in that will make your electric piano tracks sound more realistic and expressive. Whether you want to recreate the classic sounds of the past or explore new sonic possibilities, Lounge Lizard EP-4 is a plug-in worth trying. - - - -Lounge Lizard EP-4 has received positive reviews from users and critics alike, who praise its realistic sound, flexible editing, and low CPU usage. Some of the features that make Lounge Lizard EP-4 stand out are: - - - -- Standalone operation for quick jams and experimentations - -- Real-time control over any parameters via your MIDI controller knobs, faders, and switches - -- MIDI clock, tap, and host tempo synchronization for effects and modulations - -- Relaxed editing with unlimited undo/redo capability - -- Sound manipulation at the source core - -- Presets load in a flash - -- Super smooth dynamics—no velocity layers! - -- Small memory footprint—less than 256 MB of RAM per instance - -- Installs in less than a minute - - - -Lounge Lizard EP-4 is compatible with Mac OS X 10.7 or later and Windows 7 32/64-bit or later. It supports VST, Audio Unit, RTAS, AAX Native, NKS, and standalone formats. You can use it with any DAW or host application that supports these formats, such as Logic Pro, Cubase, Pro Tools, Ableton Live, GarageBand, and more. - - - -If you want to hear some audio demos of Lounge Lizard EP-4, you can visit the Applied Acoustics Systems website[^3^] or watch some YouTube videos[^2^]. You can also download a free trial version to test it out before buying. - - - -Lounge Lizard EP-4 is a plug-in that will make your electric piano tracks sound more realistic and expressive. Whether you want to recreate the classic sounds of the past or explore new sonic possibilities, Lounge Lizard EP-4 is a plug-in worth trying. - - dfd1c89656 - - - - - diff --git a/spaces/feregVcuzo/sanity-test-midi/checkpoint/Download Solar Smash APK and Enjoy the Best Planet Destruction Simulator for Android.md b/spaces/feregVcuzo/sanity-test-midi/checkpoint/Download Solar Smash APK and Enjoy the Best Planet Destruction Simulator for Android.md deleted file mode 100644 index 2eeff85eb236f80e4cc11a005dcd446352c7b141..0000000000000000000000000000000000000000 --- a/spaces/feregVcuzo/sanity-test-midi/checkpoint/Download Solar Smash APK and Enjoy the Best Planet Destruction Simulator for Android.md +++ /dev/null @@ -1,90 +0,0 @@ -
-

How to Download Solar Smash APK Android

-

Do you want to unleash your inner destructive power and have fun destroying planets with different weapons? If yes, then you should try Solar Smash, a planet destruction simulator game that is available for Android devices. In this article, we will tell you what Solar Smash is, why you should download Solar Smash APK Android, and how to download Solar Smash APK Android.

-

What is Solar Smash?

-

Solar Smash is a game developed by Paradyme Games that allows the player to use a variety of different weapons to destroy the planet. These include nuclear missiles, lasers, and asteroids. The game has realistic graphics and physics that make the destruction more satisfying and immersive. You can also customize your planet with different colors and textures, or choose from preset planets like Earth, Mars, or Saturn.

-

download solar smash apk android


Download File ---> https://gohhs.com/2uPvuI



-

Features of Solar Smash

-

Planet destruction simulator

-

The main feature of Solar Smash is that it is a planet destruction simulator. You can choose from different modes to destroy your planet, such as sandbox mode, where you can freely experiment with different weapons and scenarios; or challenge mode, where you have to complete certain objectives within a time limit.

-

Variety of weapons

-

Solar Smash also offers a variety of weapons to destroy your planet. You can use nuclear missiles that create huge explosions and mushroom clouds; lasers that cut through the planet's surface; asteroids that crash into the planet and cause massive craters; or even black holes that suck everything in their vicinity.

-

Flashing lights warning

-

One thing to note about Solar Smash is that it contains flashing lights that may make it unsuitable for people with photosensitive epilepsy or other photosensitive conditions. If you are sensitive to flashing lights, you should play this game with caution or avoid it altogether.

-

Why Download Solar Smash APK Android?

-

Solar Smash is available on Google Play Store, but you may wonder why you should download Solar Smash APK Android instead. APK stands for Android Package Kit, and it is a file format that contains all the elements of an Android app. By downloading Solar Smash APK Android, you can enjoy some benefits and risks that are not available on the official app store.

Benefits of APK files

-

Free to download

-

One of the benefits of APK files is that they are free to download. You do not need to pay any fees or subscriptions to access the app. This can save you some money and allow you to try the app before buying it.

-

Easy to install

-

Another benefit of APK files is that they are easy to install. You do not need to go through the hassle of creating an account, logging in, or verifying your device. You just need to enable unknown sources on your settings, find a reliable APK source, and download and install the file.

-

Compatible with different devices

-

A third benefit of APK files is that they are compatible with different devices. You do not need to worry about the compatibility of your device with the app. You can use APK files on any Android device, regardless of the model, brand, or operating system version.

-

download solar smash game apk for android
-solar smash planet destruction simulator apk download
-how to install solar smash apk on android device
-solar smash mod apk unlimited money and weapons
-solar smash latest version apk free download
-download solar smash 2.1.1 apk for android
-solar smash apk download without ads
-solar smash offline mode apk download
-solar smash apk + obb data download
-solar smash 3d graphics and sound effects apk download
-download solar smash apk from apkcombo.com
-solar smash apk download for android phone or tablet
-solar smash best weapons and features apk download
-solar smash apk download from mob.org
-solar smash realistic physics and animations apk download
-download solar smash apk for android 5.1 and up
-solar smash tips and tricks apk download
-solar smash space images credits apk download
-solar smash apk download for android tv
-solar smash fun and addictive gameplay apk download
-download solar smash apk from google play store
-solar smash online multiplayer mode apk download
-solar smash custom planets and scenarios apk download
-solar smash no root required apk download
-solar smash safe and secure apk download
-download solar smash apk from uptodown.com
-solar smash low battery consumption apk download
-solar smash different difficulty levels apk download
-solar smash easy and intuitive controls apk download
-solar smash fast and smooth performance apk download
-download solar smash apk from apkpure.com
-solar smash new updates and bug fixes apk download
-solar smash user reviews and ratings apk download
-solar smash screenshots and videos apk download
-solar smash support and feedback apk download

-

Risks of APK files

-

Malware infection

-

One of the risks of APK files is that they may contain malware or viruses that can harm your device or steal your data. You do not have the guarantee of security or quality that the official app store provides. You have to be careful about the source of the APK file and scan it with an antivirus before installing it.

-

Legal issues

-

Another risk of APK files is that they may violate the intellectual property rights of the app developers or publishers. You may be infringing on their copyrights or trademarks by downloading or using their app without their permission. You may face legal consequences or penalties if you are caught.

-

Performance issues

-

A third risk of APK files is that they may cause performance issues on your device or app. You may experience bugs, crashes, glitches, or errors that affect your user experience. You may also miss out on updates, features, or support that the official app store offers.

-

How to Download Solar Smash APK Android?

-

Steps to download Solar Smash APK Android

-

If you want to download Solar Smash APK Android, you need to follow these steps:

-

Step 1: Enable unknown sources

-

The first step is to enable unknown sources on your device settings. This will allow you to install apps from sources other than the official app store. To do this, go to Settings > Security > Unknown Sources and toggle it on.

-

Step 2: Find a reliable APK source

-

The second step is to find a reliable APK source that offers Solar Smash APK Android. You can search online for websites or blogs that provide links to download Solar Smash APK Android. Make sure to check the reviews, ratings, and comments of other users to verify the credibility and safety of the source.

-

Step 3: Download and install Solar Smash APK Android

-

The third step is to download and install Solar Smash APK Android on your device. To do this, click on the link provided by the source and wait for the download to finish. Then, open the file manager and locate the downloaded file. Tap on it and follow the instructions to install it.

-

Conclusion

-

Solar Smash is a fun and addictive game that lets you destroy planets with different weapons. You can download Solar Smash APK Android to enjoy some benefits and risks that are not available on the official app store. However, you need to be careful about the source of the APK file and scan it with an antivirus before installing it. We hope this article helped you learn how to download Solar Smash APK Android.

-

Frequently Asked Questions

-

Here are some frequently asked questions about Solar Smash APK Android:

-
    -
  1. Is Solar Smash free?
  2. -

    Yes, Solar Smash is free to play. However, it may contain ads or in-app purchases that require real money.

    -
  3. Is Solar Smash safe?
  4. -

    Solar Smash is safe if you download it from a reliable source and scan it with an antivirus before installing it. However, it may contain flashing lights that may trigger photosensitive epilepsy or other photosensitive conditions.

    -
  5. Is Solar Smash offline?
  6. -

    Solar Smash does not require an internet connection to play. You can play it offline anytime and anywhere.

    -
  7. < b>Is Solar Smash realistic?
  8. -

    Solar Smash is not realistic in terms of the physics and effects of the weapons. It is a game that is meant to be fun and entertaining, not educational or scientific.

    -
  9. How to update Solar Smash APK Android?
  10. -

    To update Solar Smash APK Android, you need to download the latest version of the APK file from the same source and install it over the existing app. You may also need to enable unknown sources again if you have disabled it.

    -

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/fffffu/bing/src/components/ui/codeblock.tsx b/spaces/fffffu/bing/src/components/ui/codeblock.tsx deleted file mode 100644 index aabda4e3b59f4e36b6ab79feb19d8d18b70e881b..0000000000000000000000000000000000000000 --- a/spaces/fffffu/bing/src/components/ui/codeblock.tsx +++ /dev/null @@ -1,142 +0,0 @@ -'use client' - -import { FC, memo } from 'react' -import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter' -import { coldarkDark } from 'react-syntax-highlighter/dist/cjs/styles/prism' - -import { useCopyToClipboard } from '@/lib/hooks/use-copy-to-clipboard' -import { IconCheck, IconCopy, IconDownload } from '@/components/ui/icons' -import { Button } from '@/components/ui/button' - -interface Props { - language: string - value: string -} - -interface languageMap { - [key: string]: string | undefined -} - -export const programmingLanguages: languageMap = { - javascript: '.js', - python: '.py', - java: '.java', - c: '.c', - cpp: '.cpp', - 'c++': '.cpp', - 'c#': '.cs', - ruby: '.rb', - php: '.php', - swift: '.swift', - 'objective-c': '.m', - kotlin: '.kt', - typescript: '.ts', - go: '.go', - perl: '.pl', - rust: '.rs', - scala: '.scala', - haskell: '.hs', - lua: '.lua', - shell: '.sh', - sql: '.sql', - html: '.html', - css: '.css' - // add more file extensions here, make sure the key is same as language prop in CodeBlock.tsx component -} - -export const generateRandomString = (length: number, lowercase = false) => { - const chars = 'ABCDEFGHJKLMNPQRSTUVWXY3456789' // excluding similar looking characters like Z, 2, I, 1, O, 0 - let result = '' - for (let i = 0; i < length; i++) { - result += chars.charAt(Math.floor(Math.random() * chars.length)) - } - return lowercase ? result.toLowerCase() : result -} - -const CodeBlock: FC = memo(({ language, value }) => { - const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 2000 }) - - const downloadAsFile = () => { - if (typeof window === 'undefined') { - return - } - const fileExtension = programmingLanguages[language] || '.file' - const suggestedFileName = `file-${generateRandomString( - 3, - true - )}${fileExtension}` - const fileName = window.prompt('Enter file name' || '', suggestedFileName) - - if (!fileName) { - // User pressed cancel on prompt. - return - } - - const blob = new Blob([value], { type: 'text/plain' }) - const url = URL.createObjectURL(blob) - const link = document.createElement('a') - link.download = fileName - link.href = url - link.style.display = 'none' - document.body.appendChild(link) - link.click() - document.body.removeChild(link) - URL.revokeObjectURL(url) - } - - const onCopy = () => { - if (isCopied) return - copyToClipboard(value) - } - - return ( -
-
- {language} -
- - -
-
- - {value} - -
- ) -}) -CodeBlock.displayName = 'CodeBlock' - -export { CodeBlock } diff --git a/spaces/fffiloni/Music_Source_Separation/scripts/0_download_datasets/maestro.sh b/spaces/fffiloni/Music_Source_Separation/scripts/0_download_datasets/maestro.sh deleted file mode 100644 index be7f5a78d642cb46a954c1175196b479a2e9f95d..0000000000000000000000000000000000000000 --- a/spaces/fffiloni/Music_Source_Separation/scripts/0_download_datasets/maestro.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/bash - -echo "The dataset link is at https://magenta.tensorflow.org/datasets/maestro" - -# The downloaded MAESTRO dataset looks like: -# ./datasets/maestro -# ├── 2004 (264 files) -# │ └── ... -# ├── 2006 (230 files) -# │ └── ... -# ├── 2008 (294 files) -# │ └── ... -# ├── 2009 (250 files) -# │ └── ... -# ├── 2011 (326 files) -# │ └── ... -# ├── 2013 (254 files) -# │ └── ... -# ├── 2014 (210 files) -# │ └── ... -# ├── 2015 (258 files) -# │ └── ... -# ├── 2017 (280 files) -# │ └── ... -# ├── 2018 (198 files) -# │ └── ... -# ├── LICENSE -# ├── maestro-v2.0.0.csv -# ├── maestro-v2.0.0.json -# └── README \ No newline at end of file diff --git a/spaces/fffiloni/SplitTrack2MusicGen/audiocraft/models/builders.py b/spaces/fffiloni/SplitTrack2MusicGen/audiocraft/models/builders.py deleted file mode 100644 index 77ee5f96fea2e3c9e475fe961bc1a5ee473ed8eb..0000000000000000000000000000000000000000 --- a/spaces/fffiloni/SplitTrack2MusicGen/audiocraft/models/builders.py +++ /dev/null @@ -1,218 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -""" -All the functions to build the relevant models and modules -from the Hydra config. -""" - -import typing as tp -import warnings - -import audiocraft -import omegaconf -import torch - -from .encodec import CompressionModel, EncodecModel, FlattenedCompressionModel # noqa -from .lm import LMModel -from ..modules.codebooks_patterns import ( - CodebooksPatternProvider, - DelayedPatternProvider, - ParallelPatternProvider, - UnrolledPatternProvider, - VALLEPattern, - MusicLMPattern, -) -from ..modules.conditioners import ( - BaseConditioner, - ConditioningProvider, - LUTConditioner, - T5Conditioner, - ConditionFuser, - ChromaStemConditioner, -) -from .. import quantization as qt -from ..utils.utils import dict_from_config - - -def get_quantizer(quantizer: str, cfg: omegaconf.DictConfig, dimension: int) -> qt.BaseQuantizer: - klass = { - 'no_quant': qt.DummyQuantizer, - 'rvq': qt.ResidualVectorQuantizer - }[quantizer] - kwargs = dict_from_config(getattr(cfg, quantizer)) - if quantizer != 'no_quant': - kwargs['dimension'] = dimension - return klass(**kwargs) - - -def get_encodec_autoencoder(encoder_name: str, cfg: omegaconf.DictConfig): - if encoder_name == 'seanet': - kwargs = dict_from_config(getattr(cfg, 'seanet')) - encoder_override_kwargs = kwargs.pop('encoder') - decoder_override_kwargs = kwargs.pop('decoder') - encoder_kwargs = {**kwargs, **encoder_override_kwargs} - decoder_kwargs = {**kwargs, **decoder_override_kwargs} - encoder = audiocraft.modules.SEANetEncoder(**encoder_kwargs) - decoder = audiocraft.modules.SEANetDecoder(**decoder_kwargs) - return encoder, decoder - else: - raise KeyError(f'Unexpected compression model {cfg.compression_model}') - - -def get_compression_model(cfg: omegaconf.DictConfig) -> CompressionModel: - """Instantiate a compression model. - """ - if cfg.compression_model == 'encodec': - kwargs = dict_from_config(getattr(cfg, 'encodec')) - encoder_name = kwargs.pop('autoencoder') - quantizer_name = kwargs.pop('quantizer') - encoder, decoder = get_encodec_autoencoder(encoder_name, cfg) - quantizer = get_quantizer(quantizer_name, cfg, encoder.dimension) - frame_rate = kwargs['sample_rate'] // encoder.hop_length - renormalize = kwargs.pop('renormalize', None) - renorm = kwargs.pop('renorm') - if renormalize is None: - renormalize = renorm is not None - warnings.warn("You are using a deprecated EnCodec model. Please migrate to new renormalization.") - return EncodecModel(encoder, decoder, quantizer, - frame_rate=frame_rate, renormalize=renormalize, **kwargs).to(cfg.device) - else: - raise KeyError(f'Unexpected compression model {cfg.compression_model}') - - -def get_lm_model(cfg: omegaconf.DictConfig) -> LMModel: - """Instantiate a transformer LM. - """ - if cfg.lm_model == 'transformer_lm': - kwargs = dict_from_config(getattr(cfg, 'transformer_lm')) - n_q = kwargs['n_q'] - q_modeling = kwargs.pop('q_modeling', None) - codebooks_pattern_cfg = getattr(cfg, 'codebooks_pattern') - attribute_dropout = dict_from_config(getattr(cfg, 'attribute_dropout')) - cls_free_guidance = dict_from_config(getattr(cfg, 'classifier_free_guidance')) - cfg_prob, cfg_coef = cls_free_guidance["training_dropout"], cls_free_guidance["inference_coef"] - fuser = get_condition_fuser(cfg) - condition_provider = get_conditioner_provider(kwargs["dim"], cfg).to(cfg.device) - if len(fuser.fuse2cond['cross']) > 0: # enforce cross-att programatically - kwargs['cross_attention'] = True - if codebooks_pattern_cfg.modeling is None: - assert q_modeling is not None, \ - 'LM model should either have a codebook pattern defined or transformer_lm.q_modeling' - codebooks_pattern_cfg = omegaconf.OmegaConf.create( - {'modeling': q_modeling, 'delay': {'delays': list(range(n_q))}} - ) - pattern_provider = get_codebooks_pattern_provider(n_q, codebooks_pattern_cfg) - return LMModel( - pattern_provider=pattern_provider, - condition_provider=condition_provider, - fuser=fuser, - cfg_dropout=cfg_prob, - cfg_coef=cfg_coef, - attribute_dropout=attribute_dropout, - dtype=getattr(torch, cfg.dtype), - device=cfg.device, - **kwargs - ).to(cfg.device) - else: - raise KeyError(f'Unexpected LM model {cfg.lm_model}') - - -def get_conditioner_provider(output_dim: int, cfg: omegaconf.DictConfig) -> ConditioningProvider: - """Instantiate a conditioning model. - """ - device = cfg.device - duration = cfg.dataset.segment_duration - cfg = getattr(cfg, "conditioners") - cfg = omegaconf.OmegaConf.create({}) if cfg is None else cfg - conditioners: tp.Dict[str, BaseConditioner] = {} - with omegaconf.open_dict(cfg): - condition_provider_args = cfg.pop('args', {}) - for cond, cond_cfg in cfg.items(): - model_type = cond_cfg["model"] - model_args = cond_cfg[model_type] - if model_type == "t5": - conditioners[str(cond)] = T5Conditioner(output_dim=output_dim, device=device, **model_args) - elif model_type == "lut": - conditioners[str(cond)] = LUTConditioner(output_dim=output_dim, **model_args) - elif model_type == "chroma_stem": - model_args.pop('cache_path', None) - conditioners[str(cond)] = ChromaStemConditioner( - output_dim=output_dim, - duration=duration, - device=device, - **model_args - ) - else: - raise ValueError(f"unrecognized conditioning model: {model_type}") - conditioner = ConditioningProvider(conditioners, device=device, **condition_provider_args) - return conditioner - - -def get_condition_fuser(cfg: omegaconf.DictConfig) -> ConditionFuser: - """Instantiate a condition fuser object. - """ - fuser_cfg = getattr(cfg, "fuser") - fuser_methods = ["sum", "cross", "prepend", "input_interpolate"] - fuse2cond = {k: fuser_cfg[k] for k in fuser_methods} - kwargs = {k: v for k, v in fuser_cfg.items() if k not in fuser_methods} - fuser = ConditionFuser(fuse2cond=fuse2cond, **kwargs) - return fuser - - -def get_codebooks_pattern_provider(n_q: int, cfg: omegaconf.DictConfig) -> CodebooksPatternProvider: - """Instantiate a codebooks pattern provider object. - """ - pattern_providers = { - 'parallel': ParallelPatternProvider, - 'delay': DelayedPatternProvider, - 'unroll': UnrolledPatternProvider, - 'valle': VALLEPattern, - 'musiclm': MusicLMPattern, - } - name = cfg.modeling - kwargs = dict_from_config(cfg.get(name)) if hasattr(cfg, name) else {} - klass = pattern_providers[name] - return klass(n_q, **kwargs) - - -def get_debug_compression_model(device='cpu'): - """Instantiate a debug compression model to be used for unit tests. - """ - seanet_kwargs = { - 'n_filters': 4, - 'n_residual_layers': 1, - 'dimension': 32, - 'ratios': [10, 8, 16] # 25 Hz at 32kHz - } - encoder = audiocraft.modules.SEANetEncoder(**seanet_kwargs) - decoder = audiocraft.modules.SEANetDecoder(**seanet_kwargs) - quantizer = qt.ResidualVectorQuantizer(dimension=32, bins=400, n_q=4) - init_x = torch.randn(8, 32, 128) - quantizer(init_x, 1) # initialize kmeans etc. - compression_model = EncodecModel( - encoder, decoder, quantizer, - frame_rate=25, sample_rate=32000, channels=1).to(device) - return compression_model.eval() - - -def get_debug_lm_model(device='cpu'): - """Instantiate a debug LM to be used for unit tests. - """ - pattern = DelayedPatternProvider(n_q=4) - dim = 16 - providers = { - 'description': LUTConditioner(n_bins=128, dim=dim, output_dim=dim, tokenizer="whitespace"), - } - condition_provider = ConditioningProvider(providers) - fuser = ConditionFuser( - {'cross': ['description'], 'prepend': [], - 'sum': [], 'input_interpolate': []}) - lm = LMModel( - pattern, condition_provider, fuser, - n_q=4, card=400, dim=dim, num_heads=4, custom=True, num_layers=2, - cross_attention=True, causal=True) - return lm.to(device).eval() diff --git a/spaces/fffiloni/lama-video-watermark-remover/bin/paper_runfiles/predict_inner_features.sh b/spaces/fffiloni/lama-video-watermark-remover/bin/paper_runfiles/predict_inner_features.sh deleted file mode 100644 index 864c1a0fca8b93b2a193656e45ff55f6a051eb8c..0000000000000000000000000000000000000000 --- a/spaces/fffiloni/lama-video-watermark-remover/bin/paper_runfiles/predict_inner_features.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env bash - -# paths to data are valid for mml7 - -source "$(dirname $0)/env.sh" - -"$BINDIR/predict_inner_features.py" \ - -cn default_inner_features_ffc \ - model.path="/data/inpainting/paper_data/final_models/ours/r.suvorov_2021-03-05_17-34-05_train_ablv2_work_ffc075_resume_epoch39" \ - indir="/data/inpainting/paper_data/inner_features_vis/input/" \ - outdir="/data/inpainting/paper_data/inner_features_vis/output/ffc" \ - dataset.img_suffix=.png - - -"$BINDIR/predict_inner_features.py" \ - -cn default_inner_features_work \ - model.path="/data/inpainting/paper_data/final_models/ours/r.suvorov_2021-03-05_17-08-35_train_ablv2_work_resume_epoch37" \ - indir="/data/inpainting/paper_data/inner_features_vis/input/" \ - outdir="/data/inpainting/paper_data/inner_features_vis/output/work" \ - dataset.img_suffix=.png diff --git a/spaces/flax-community/image-captioning/app.py b/spaces/flax-community/image-captioning/app.py deleted file mode 100644 index 3d7f400e8a89f3837916358e0bf3b1525c4e39f2..0000000000000000000000000000000000000000 --- a/spaces/flax-community/image-captioning/app.py +++ /dev/null @@ -1,97 +0,0 @@ -import streamlit as st -import requests -import io - - -# Designing the interface -st.title("🖼️ Image Captioning Demo 📝") -st.write("[Yih-Dar SHIEH](https://huggingface.co/ydshieh)") - -st.sidebar.markdown( - """ - An image captioning model by combining ViT model with GPT2 model. - The encoder (ViT) and decoder (GPT2) are combined using Hugging Face transformers' [Vision-To-Text Encoder-Decoder - framework](https://huggingface.co/transformers/master/model_doc/visionencoderdecoder.html). - The pretrained weights of both models are loaded, with a set of randomly initialized cross-attention weights. - The model is trained on the COCO 2017 dataset for about 6900 steps (batch_size=256). - [Follow-up work of [Huggingface JAX/Flax event](https://discuss.huggingface.co/t/open-to-the-community-community-week-using-jax-flax-for-nlp-cv/).]\n - """ -) - -with st.spinner('Loading and compiling ViT-GPT2 model ...'): - from model import * - -random_image_id = get_random_image_id() - -st.sidebar.title("Select a sample image") -sample_image_id = st.sidebar.selectbox( - "Please choose a sample image", - sample_image_ids -) - -if st.sidebar.button("Random COCO 2017 (val) images"): - random_image_id = get_random_image_id() - sample_image_id = "None" - -bytes_data = None -with st.sidebar.form("file-uploader-form", clear_on_submit=True): - uploaded_file = st.file_uploader("Choose a file") - submitted = st.form_submit_button("Upload") - if submitted and uploaded_file is not None: - bytes_data = io.BytesIO(uploaded_file.getvalue()) - -if (bytes_data is None) and submitted: - - st.write("No file is selected to upload") - -else: - - image_id = random_image_id - if sample_image_id != "None": - assert type(sample_image_id) == int - image_id = sample_image_id - - sample_name = f"COCO_val2017_{str(image_id).zfill(12)}.jpg" - sample_path = os.path.join(sample_dir, sample_name) - - if bytes_data is not None: - image = Image.open(bytes_data) - elif os.path.isfile(sample_path): - image = Image.open(sample_path) - else: - url = f"http://images.cocodataset.org/val2017/{str(image_id).zfill(12)}.jpg" - image = Image.open(requests.get(url, stream=True).raw) - - width, height = image.size - resized = image.resize(size=(width, height)) - if height > 384: - width = int(width / height * 384) - height = 384 - resized = resized.resize(size=(width, height)) - width, height = resized.size - if width > 512: - width = 512 - height = int(height / width * 512) - resized = resized.resize(size=(width, height)) - - if bytes_data is None: - st.markdown(f"[{str(image_id).zfill(12)}.jpg](http://images.cocodataset.org/val2017/{str(image_id).zfill(12)}.jpg)") - show = st.image(resized) - show.image(resized, '\n\nSelected Image') - resized.close() - - # For newline - st.sidebar.write('\n') - - with st.spinner('Generating image caption ...'): - - caption = predict(image) - - caption_en = caption - st.header(f'Predicted caption:\n\n') - st.subheader(caption_en) - - st.sidebar.header("ViT-GPT2 predicts: ") - st.sidebar.write(f"{caption}") - - image.close() diff --git a/spaces/freddyaboulton/gradio_pdf/src/backend/gradio_pdf/pdf.py b/spaces/freddyaboulton/gradio_pdf/src/backend/gradio_pdf/pdf.py deleted file mode 100644 index 3020f2d4f2198f3d0dcd0b4feaeb6d75c3ab7018..0000000000000000000000000000000000000000 --- a/spaces/freddyaboulton/gradio_pdf/src/backend/gradio_pdf/pdf.py +++ /dev/null @@ -1,50 +0,0 @@ -from __future__ import annotations -from typing import Any, Callable - -from gradio.components.base import Component -from gradio.data_classes import FileData -from gradio import processing_utils - -class PDF(Component): - - EVENTS = ["change", "upload"] - - data_model = FileData - - def __init__(self, value: Any = None, *, - height: int | None = None, - label: str | None = None, info: str | None = None, - show_label: bool | None = None, - container: bool = True, - scale: int | None = None, - min_width: int | None = None, - interactive: bool | None = None, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - render: bool = True, - load_fn: Callable[..., Any] | None = None, - every: float | None = None): - super().__init__(value, label=label, info=info, - show_label=show_label, container=container, - scale=scale, min_width=min_width, - interactive=interactive, visible=visible, - elem_id=elem_id, elem_classes=elem_classes, - render=render, load_fn=load_fn, every=every) - self.height = height - - def preprocess(self, payload: FileData) -> str: - return payload.path - - def postprocess(self, value: str | None) -> FileData: - if not value: - return None - return FileData(path=value) - - def example_inputs(self): - return "https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/fw9.pdf" - - def as_example(self, input_data: str | None) -> str | None: - if input_data is None: - return None - return processing_utils.move_resource_to_block_cache(input_data, self) diff --git a/spaces/georgefen/Face-Landmark-ControlNet/annotator/hed/__init__.py b/spaces/georgefen/Face-Landmark-ControlNet/annotator/hed/__init__.py deleted file mode 100644 index 56532c374df5c26f9ec53e2ac0dd924f4534bbdd..0000000000000000000000000000000000000000 --- a/spaces/georgefen/Face-Landmark-ControlNet/annotator/hed/__init__.py +++ /dev/null @@ -1,132 +0,0 @@ -import numpy as np -import cv2 -import os -import torch -from einops import rearrange -from annotator.util import annotator_ckpts_path - - -class Network(torch.nn.Module): - def __init__(self, model_path): - super().__init__() - - self.netVggOne = torch.nn.Sequential( - torch.nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False), - torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False) - ) - - self.netVggTwo = torch.nn.Sequential( - torch.nn.MaxPool2d(kernel_size=2, stride=2), - torch.nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False), - torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False) - ) - - self.netVggThr = torch.nn.Sequential( - torch.nn.MaxPool2d(kernel_size=2, stride=2), - torch.nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False), - torch.nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False), - torch.nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False) - ) - - self.netVggFou = torch.nn.Sequential( - torch.nn.MaxPool2d(kernel_size=2, stride=2), - torch.nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False), - torch.nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False), - torch.nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False) - ) - - self.netVggFiv = torch.nn.Sequential( - torch.nn.MaxPool2d(kernel_size=2, stride=2), - torch.nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False), - torch.nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False), - torch.nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False) - ) - - self.netScoreOne = torch.nn.Conv2d(in_channels=64, out_channels=1, kernel_size=1, stride=1, padding=0) - self.netScoreTwo = torch.nn.Conv2d(in_channels=128, out_channels=1, kernel_size=1, stride=1, padding=0) - self.netScoreThr = torch.nn.Conv2d(in_channels=256, out_channels=1, kernel_size=1, stride=1, padding=0) - self.netScoreFou = torch.nn.Conv2d(in_channels=512, out_channels=1, kernel_size=1, stride=1, padding=0) - self.netScoreFiv = torch.nn.Conv2d(in_channels=512, out_channels=1, kernel_size=1, stride=1, padding=0) - - self.netCombine = torch.nn.Sequential( - torch.nn.Conv2d(in_channels=5, out_channels=1, kernel_size=1, stride=1, padding=0), - torch.nn.Sigmoid() - ) - - self.load_state_dict({strKey.replace('module', 'net'): tenWeight for strKey, tenWeight in torch.load(model_path).items()}) - - def forward(self, tenInput): - tenInput = tenInput * 255.0 - tenInput = tenInput - torch.tensor(data=[104.00698793, 116.66876762, 122.67891434], dtype=tenInput.dtype, device=tenInput.device).view(1, 3, 1, 1) - - tenVggOne = self.netVggOne(tenInput) - tenVggTwo = self.netVggTwo(tenVggOne) - tenVggThr = self.netVggThr(tenVggTwo) - tenVggFou = self.netVggFou(tenVggThr) - tenVggFiv = self.netVggFiv(tenVggFou) - - tenScoreOne = self.netScoreOne(tenVggOne) - tenScoreTwo = self.netScoreTwo(tenVggTwo) - tenScoreThr = self.netScoreThr(tenVggThr) - tenScoreFou = self.netScoreFou(tenVggFou) - tenScoreFiv = self.netScoreFiv(tenVggFiv) - - tenScoreOne = torch.nn.functional.interpolate(input=tenScoreOne, size=(tenInput.shape[2], tenInput.shape[3]), mode='bilinear', align_corners=False) - tenScoreTwo = torch.nn.functional.interpolate(input=tenScoreTwo, size=(tenInput.shape[2], tenInput.shape[3]), mode='bilinear', align_corners=False) - tenScoreThr = torch.nn.functional.interpolate(input=tenScoreThr, size=(tenInput.shape[2], tenInput.shape[3]), mode='bilinear', align_corners=False) - tenScoreFou = torch.nn.functional.interpolate(input=tenScoreFou, size=(tenInput.shape[2], tenInput.shape[3]), mode='bilinear', align_corners=False) - tenScoreFiv = torch.nn.functional.interpolate(input=tenScoreFiv, size=(tenInput.shape[2], tenInput.shape[3]), mode='bilinear', align_corners=False) - - return self.netCombine(torch.cat([ tenScoreOne, tenScoreTwo, tenScoreThr, tenScoreFou, tenScoreFiv ], 1)) - - -class HEDdetector: - def __init__(self): - remote_model_path = "https://huggingface.co/lllyasviel/ControlNet/resolve/main/annotator/ckpts/network-bsds500.pth" - modelpath = os.path.join(annotator_ckpts_path, "network-bsds500.pth") - if not os.path.exists(modelpath): - from basicsr.utils.download_util import load_file_from_url - load_file_from_url(remote_model_path, model_dir=annotator_ckpts_path) - self.netNetwork = Network(modelpath).cuda().eval() - - def __call__(self, input_image): - assert input_image.ndim == 3 - input_image = input_image[:, :, ::-1].copy() - with torch.no_grad(): - image_hed = torch.from_numpy(input_image).float().cuda() - image_hed = image_hed / 255.0 - image_hed = rearrange(image_hed, 'h w c -> 1 c h w') - edge = self.netNetwork(image_hed)[0] - edge = (edge.cpu().numpy() * 255.0).clip(0, 255).astype(np.uint8) - return edge[0] - - -def nms(x, t, s): - x = cv2.GaussianBlur(x.astype(np.float32), (0, 0), s) - - f1 = np.array([[0, 0, 0], [1, 1, 1], [0, 0, 0]], dtype=np.uint8) - f2 = np.array([[0, 1, 0], [0, 1, 0], [0, 1, 0]], dtype=np.uint8) - f3 = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=np.uint8) - f4 = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]], dtype=np.uint8) - - y = np.zeros_like(x) - - for f in [f1, f2, f3, f4]: - np.putmask(y, cv2.dilate(x, kernel=f) == x, x) - - z = np.zeros_like(y, dtype=np.uint8) - z[y > t] = 255 - return z diff --git a/spaces/georgefen/Face-Landmark-ControlNet/ldm/modules/midas/utils.py b/spaces/georgefen/Face-Landmark-ControlNet/ldm/modules/midas/utils.py deleted file mode 100644 index 9a9d3b5b66370fa98da9e067ba53ead848ea9a59..0000000000000000000000000000000000000000 --- a/spaces/georgefen/Face-Landmark-ControlNet/ldm/modules/midas/utils.py +++ /dev/null @@ -1,189 +0,0 @@ -"""Utils for monoDepth.""" -import sys -import re -import numpy as np -import cv2 -import torch - - -def read_pfm(path): - """Read pfm file. - - Args: - path (str): path to file - - Returns: - tuple: (data, scale) - """ - with open(path, "rb") as file: - - color = None - width = None - height = None - scale = None - endian = None - - header = file.readline().rstrip() - if header.decode("ascii") == "PF": - color = True - elif header.decode("ascii") == "Pf": - color = False - else: - raise Exception("Not a PFM file: " + path) - - dim_match = re.match(r"^(\d+)\s(\d+)\s$", file.readline().decode("ascii")) - if dim_match: - width, height = list(map(int, dim_match.groups())) - else: - raise Exception("Malformed PFM header.") - - scale = float(file.readline().decode("ascii").rstrip()) - if scale < 0: - # little-endian - endian = "<" - scale = -scale - else: - # big-endian - endian = ">" - - data = np.fromfile(file, endian + "f") - shape = (height, width, 3) if color else (height, width) - - data = np.reshape(data, shape) - data = np.flipud(data) - - return data, scale - - -def write_pfm(path, image, scale=1): - """Write pfm file. - - Args: - path (str): pathto file - image (array): data - scale (int, optional): Scale. Defaults to 1. - """ - - with open(path, "wb") as file: - color = None - - if image.dtype.name != "float32": - raise Exception("Image dtype must be float32.") - - image = np.flipud(image) - - if len(image.shape) == 3 and image.shape[2] == 3: # color image - color = True - elif ( - len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1 - ): # greyscale - color = False - else: - raise Exception("Image must have H x W x 3, H x W x 1 or H x W dimensions.") - - file.write("PF\n" if color else "Pf\n".encode()) - file.write("%d %d\n".encode() % (image.shape[1], image.shape[0])) - - endian = image.dtype.byteorder - - if endian == "<" or endian == "=" and sys.byteorder == "little": - scale = -scale - - file.write("%f\n".encode() % scale) - - image.tofile(file) - - -def read_image(path): - """Read image and output RGB image (0-1). - - Args: - path (str): path to file - - Returns: - array: RGB image (0-1) - """ - img = cv2.imread(path) - - if img.ndim == 2: - img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) - - img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) / 255.0 - - return img - - -def resize_image(img): - """Resize image and make it fit for network. - - Args: - img (array): image - - Returns: - tensor: data ready for network - """ - height_orig = img.shape[0] - width_orig = img.shape[1] - - if width_orig > height_orig: - scale = width_orig / 384 - else: - scale = height_orig / 384 - - height = (np.ceil(height_orig / scale / 32) * 32).astype(int) - width = (np.ceil(width_orig / scale / 32) * 32).astype(int) - - img_resized = cv2.resize(img, (width, height), interpolation=cv2.INTER_AREA) - - img_resized = ( - torch.from_numpy(np.transpose(img_resized, (2, 0, 1))).contiguous().float() - ) - img_resized = img_resized.unsqueeze(0) - - return img_resized - - -def resize_depth(depth, width, height): - """Resize depth map and bring to CPU (numpy). - - Args: - depth (tensor): depth - width (int): image width - height (int): image height - - Returns: - array: processed depth - """ - depth = torch.squeeze(depth[0, :, :, :]).to("cpu") - - depth_resized = cv2.resize( - depth.numpy(), (width, height), interpolation=cv2.INTER_CUBIC - ) - - return depth_resized - -def write_depth(path, depth, bits=1): - """Write depth map to pfm and png file. - - Args: - path (str): filepath without extension - depth (array): depth - """ - write_pfm(path + ".pfm", depth.astype(np.float32)) - - depth_min = depth.min() - depth_max = depth.max() - - max_val = (2**(8*bits))-1 - - if depth_max - depth_min > np.finfo("float").eps: - out = max_val * (depth - depth_min) / (depth_max - depth_min) - else: - out = np.zeros(depth.shape, dtype=depth.type) - - if bits == 1: - cv2.imwrite(path + ".png", out.astype("uint8")) - elif bits == 2: - cv2.imwrite(path + ".png", out.astype("uint16")) - - return diff --git a/spaces/gradio/HuBERT/examples/speech_recognition/tasks/__init__.py b/spaces/gradio/HuBERT/examples/speech_recognition/tasks/__init__.py deleted file mode 100644 index 7ac3b8dc69639c92cc129294356e9012745e3fb2..0000000000000000000000000000000000000000 --- a/spaces/gradio/HuBERT/examples/speech_recognition/tasks/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -import importlib -import os - - -for file in sorted(os.listdir(os.path.dirname(__file__))): - if file.endswith(".py") and not file.startswith("_"): - task_name = file[: file.find(".py")] - importlib.import_module("examples.speech_recognition.tasks." + task_name) diff --git a/spaces/gradio/HuBERT/fairseq/data/encoders/sentencepiece_bpe.py b/spaces/gradio/HuBERT/fairseq/data/encoders/sentencepiece_bpe.py deleted file mode 100644 index a76d46a2014e81eff72b19f6c13084a855fcd477..0000000000000000000000000000000000000000 --- a/spaces/gradio/HuBERT/fairseq/data/encoders/sentencepiece_bpe.py +++ /dev/null @@ -1,48 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -from dataclasses import dataclass, field - -from fairseq import file_utils -from fairseq.data.encoders import register_bpe -from fairseq.dataclass import FairseqDataclass - - -@dataclass -class SentencepieceConfig(FairseqDataclass): - sentencepiece_model: str = field( - default="???", metadata={"help": "path to sentencepiece model"} - ) - - -@register_bpe("sentencepiece", dataclass=SentencepieceConfig) -class SentencepieceBPE(object): - def __init__(self, cfg): - sentencepiece_model = file_utils.cached_path(cfg.sentencepiece_model) - try: - import sentencepiece as spm - - self.sp = spm.SentencePieceProcessor() - self.sp.Load(sentencepiece_model) - except ImportError: - raise ImportError( - "Please install sentencepiece with: pip install sentencepiece" - ) - - def encode(self, x: str) -> str: - return " ".join(self.sp.EncodeAsPieces(x)) - - def decode(self, x: str) -> str: - return x.replace(" ", "").replace("\u2581", " ").strip() - - def is_beginning_of_word(self, x: str) -> bool: - if x in ["", "", "", ""]: - # special elements are always considered beginnings - # HACK: this logic is already present in fairseq/tasks/masked_lm.py - # but these special tokens are also contained in the sentencepiece - # vocabulary which causes duplicate special tokens. This hack makes - # sure that they are all taken into account. - return True - return x.startswith("\u2581") diff --git a/spaces/gradio/HuBERT/fairseq/modules/gelu.py b/spaces/gradio/HuBERT/fairseq/modules/gelu.py deleted file mode 100644 index a2f1ecff4a3ae3de3eb7d327b9163c46b18a15ed..0000000000000000000000000000000000000000 --- a/spaces/gradio/HuBERT/fairseq/modules/gelu.py +++ /dev/null @@ -1,25 +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. -""" -See "Gaussian Error Linear Units (GELUs)" by Dan Hendrycks and Kevin Gimpel with -the corresponding GitHub repo: https://github.com/hendrycks/GELUs -""" - -import math - -import torch -import torch.nn as nn - - -def gelu_accurate(x): - if not hasattr(gelu_accurate, "_a"): - gelu_accurate._a = math.sqrt(2 / math.pi) - return ( - 0.5 * x * (1 + torch.tanh(gelu_accurate._a * (x + 0.044715 * torch.pow(x, 3)))) - ) - - -def gelu(x: torch.Tensor) -> torch.Tensor: - return torch.nn.functional.gelu(x.float()).type_as(x) diff --git a/spaces/gyugnsu/DragGan-Inversion/PTI/models/StyleCLIP/models/stylegan2/op/__init__.py b/spaces/gyugnsu/DragGan-Inversion/PTI/models/StyleCLIP/models/stylegan2/op/__init__.py deleted file mode 100644 index d0918d92285955855be89f00096b888ee5597ce3..0000000000000000000000000000000000000000 --- a/spaces/gyugnsu/DragGan-Inversion/PTI/models/StyleCLIP/models/stylegan2/op/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from .fused_act import FusedLeakyReLU, fused_leaky_relu -from .upfirdn2d import upfirdn2d diff --git a/spaces/h2oai/wave-tour/examples/plot_path_smooth.py b/spaces/h2oai/wave-tour/examples/plot_path_smooth.py deleted file mode 100644 index fe34c35e79cd91259b07757f8c1b27fa0c5b855f..0000000000000000000000000000000000000000 --- a/spaces/h2oai/wave-tour/examples/plot_path_smooth.py +++ /dev/null @@ -1,26 +0,0 @@ -# Plot / Path / Smooth -# Make a path #plot with a smooth curve. -# --- -from h2o_wave import site, data, ui - -page = site['/demo'] - -page.add('example', ui.plot_card( - box='1 1 4 5', - title='Path, smooth', - data=data('price performance', 10, rows=[ - (0.1, 0.6), - (0.2, 0.5), - (0.3, 0.3), - (0.4, 0.2), - (0.4, 0.5), - (0.2, 0.2), - (0.8, 0.5), - (0.3, 0.3), - (0.2, 0.4), - (0.1, 0.0), - ]), - plot=ui.plot([ui.mark(type='path', x='=price', y='=performance', curve='smooth')]) -)) - -page.save() diff --git a/spaces/hasibzunair/fifa-tryon-demo/Self-Correction-Human-Parsing-for-ACGPN/mhp_extension/detectron2/detectron2/modeling/backbone/backbone.py b/spaces/hasibzunair/fifa-tryon-demo/Self-Correction-Human-Parsing-for-ACGPN/mhp_extension/detectron2/detectron2/modeling/backbone/backbone.py deleted file mode 100644 index 66dee4a6565e6c45ed17d0880fcc37eac8f75c3a..0000000000000000000000000000000000000000 --- a/spaces/hasibzunair/fifa-tryon-demo/Self-Correction-Human-Parsing-for-ACGPN/mhp_extension/detectron2/detectron2/modeling/backbone/backbone.py +++ /dev/null @@ -1,53 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved -from abc import ABCMeta, abstractmethod -import torch.nn as nn - -from detectron2.layers import ShapeSpec - -__all__ = ["Backbone"] - - -class Backbone(nn.Module, metaclass=ABCMeta): - """ - Abstract base class for network backbones. - """ - - def __init__(self): - """ - The `__init__` method of any subclass can specify its own set of arguments. - """ - super().__init__() - - @abstractmethod - def forward(self): - """ - Subclasses must override this method, but adhere to the same return type. - - Returns: - dict[str->Tensor]: mapping from feature name (e.g., "res2") to tensor - """ - pass - - @property - def size_divisibility(self): - """ - Some backbones require the input height and width to be divisible by a - specific integer. This is typically true for encoder / decoder type networks - with lateral connection (e.g., FPN) for which feature maps need to match - dimension in the "bottom up" and "top down" paths. Set to 0 if no specific - input size divisibility is required. - """ - return 0 - - def output_shape(self): - """ - Returns: - dict[str->ShapeSpec] - """ - # this is a backward-compatible default - return { - name: ShapeSpec( - channels=self._out_feature_channels[name], stride=self._out_feature_strides[name] - ) - for name in self._out_features - } diff --git a/spaces/hekbobo/bingo/src/components/ui/textarea.tsx b/spaces/hekbobo/bingo/src/components/ui/textarea.tsx deleted file mode 100644 index e25af722c7a5dc1121a9ab58d6716952f9f76081..0000000000000000000000000000000000000000 --- a/spaces/hekbobo/bingo/src/components/ui/textarea.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import * as React from 'react' - -import { cn } from '@/lib/utils' - -export interface TextareaProps - extends React.TextareaHTMLAttributes {} - -const Textarea = React.forwardRef( - ({ className, ...props }, ref) => { - return ( - - - -
-
- Advanced Options -
- - -
- - - - 4 - - - - 0.3 - - - - - 0.5 - - - - - 0.8 - - - - - 0.0 - - - - - 0.8 - - - - - 0.1 - - - - - 0.2 - - - - - - - -
-
- - -
-
- - -
-
- - - -
- - -
-
- -
-
-
-
- - - -
-
- -
- - - - -
-
- - - - \ No newline at end of file diff --git a/spaces/lemon7/White-box-Cartoonization/README.md b/spaces/lemon7/White-box-Cartoonization/README.md deleted file mode 100644 index 9860239cf42c94e385faaaa75a85311e010d64f7..0000000000000000000000000000000000000000 --- a/spaces/lemon7/White-box-Cartoonization/README.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -python_version: 3.7 -title: White Box Cartoonization -emoji: 📚 -colorFrom: purple -colorTo: green -sdk: gradio -sdk_version: 2.9.4 -app_file: app.py -pinned: false -license: apache-2.0 -duplicated_from: hylee/White-box-Cartoonization ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference diff --git a/spaces/lewisliuX123/wechatgpt3/bot/baidu/baidu_unit_bot.py b/spaces/lewisliuX123/wechatgpt3/bot/baidu/baidu_unit_bot.py deleted file mode 100644 index a84ac57c9b7843a00e689b662807c9ec4710d6af..0000000000000000000000000000000000000000 --- a/spaces/lewisliuX123/wechatgpt3/bot/baidu/baidu_unit_bot.py +++ /dev/null @@ -1,26 +0,0 @@ -# encoding:utf-8 - -import requests -from bot.bot import Bot - - -# Baidu Unit对话接口 (可用, 但能力较弱) -class BaiduUnitBot(Bot): - def reply(self, query, context=None): - token = self.get_token() - url = 'https://aip.baidubce.com/rpc/2.0/unit/service/v3/chat?access_token=' + token - post_data = "{\"version\":\"3.0\",\"service_id\":\"S73177\",\"session_id\":\"\",\"log_id\":\"7758521\",\"skill_ids\":[\"1221886\"],\"request\":{\"terminal_id\":\"88888\",\"query\":\"" + query + "\", \"hyper_params\": {\"chat_custom_bot_profile\": 1}}}" - print(post_data) - headers = {'content-type': 'application/x-www-form-urlencoded'} - response = requests.post(url, data=post_data.encode(), headers=headers) - if response: - return response.json()['result']['context']['SYS_PRESUMED_HIST'][1] - - def get_token(self): - access_key = 'YOUR_ACCESS_KEY' - secret_key = 'YOUR_SECRET_KEY' - host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + access_key + '&client_secret=' + secret_key - response = requests.get(host) - if response: - print(response.json()) - return response.json()['access_token'] diff --git a/spaces/lfolle/DeepNAPSI/entrypoint.py b/spaces/lfolle/DeepNAPSI/entrypoint.py deleted file mode 100644 index 57edc3b4950541599d2a802097e18608ae323260..0000000000000000000000000000000000000000 --- a/spaces/lfolle/DeepNAPSI/entrypoint.py +++ /dev/null @@ -1,14 +0,0 @@ -import os -import sys -import shutil -import subprocess -from huggingface_hub import Repository - -# Bug got fixed lately -# hooks_path = ".git/hooks/" -# if os.path.exists(hooks_path): -# shutil.rmtree(hooks_path) -Repository("repos/hand-ki-model", f"https://oauth2:{os.getenv('HANDKIGIT5')}@git5.cs.fau.de/folle/hand-ki-model.git", use_auth_token=os.getenv("")) - -subprocess.check_call([sys.executable, "-m", "pip", "install", "repos/hand-ki-model/"]) -import app \ No newline at end of file diff --git a/spaces/light22/Real-CUGAN/README.md b/spaces/light22/Real-CUGAN/README.md deleted file mode 100644 index d673114edadba73e80f33a3c71bc0dbee8758cc8..0000000000000000000000000000000000000000 --- a/spaces/light22/Real-CUGAN/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Real CUGAN -emoji: 🐢 -colorFrom: gray -colorTo: green -sdk: gradio -sdk_version: 3.6 -app_file: app.py -pinned: false -license: gpl-3.0 -duplicated_from: DianXian/Real-CUGAN ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Avast Antitrack Premium Free NEW!.md b/spaces/lincquiQcaudo/Top-20-Diffusion/Avast Antitrack Premium Free NEW!.md deleted file mode 100644 index 101d31233bf94b478dc7b3c809ad0ac7cd00958b..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Avast Antitrack Premium Free NEW!.md +++ /dev/null @@ -1,6 +0,0 @@ -

avast antitrack premium free


Download Zip ····· https://bytlly.com/2uGw6e



- -Avast Antitrack Premium Key is a sponsor observing avoidance module that keeps your unique mark covered up. Avast Anti-Track Premium 19.4.2370 Crack + ... 4d29de3e1b
-
-
-

diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/CRACK Kolor Autopano Giga 4.4.2 _TOP_.md b/spaces/lincquiQcaudo/Top-20-Diffusion/CRACK Kolor Autopano Giga 4.4.2 _TOP_.md deleted file mode 100644 index 75db7104a864145695070b14dc448af8943ddac2..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/CRACK Kolor Autopano Giga 4.4.2 _TOP_.md +++ /dev/null @@ -1,6 +0,0 @@ -

CRACK Kolor Autopano Giga 4.4.2


Download File --->>> https://bytlly.com/2uGvIt



-
-Autopano Pro 4.4.2 Pro crack Review with License Key. ... Autopano ... motion estimation, Giga color modification engine that is entirely new. ... Wirecast Pro ... 1fdad05405
-
-
-

diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/HD Online Player (spectre 2015 Dual Audio 720p Brripgo).md b/spaces/lincquiQcaudo/Top-20-Diffusion/HD Online Player (spectre 2015 Dual Audio 720p Brripgo).md deleted file mode 100644 index 5e6baf167dde8677f440a6d5bd26758658240b7b..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/HD Online Player (spectre 2015 Dual Audio 720p Brripgo).md +++ /dev/null @@ -1,22 +0,0 @@ -
-

How to Watch Spectre (2015) in HD Online with Dual Audio

-

If you are a fan of James Bond movies, you might be interested in watching Spectre (2015), the twenty-fourth film in the series. Spectre is a spy thriller that follows Bond as he uncovers the existence of a sinister organisation named SPECTRE, led by his arch-enemy Ernst Stavro Blofeld. The film stars Daniel Craig as Bond, Christoph Waltz as Blofeld, Léa Seydoux as Madeleine Swann, Ben Whishaw as Q, Naomie Harris as Moneypenny, Dave Bautista as Hinx, Monica Bellucci as Lucia Sciarra, and Ralph Fiennes as M.

-

But how can you watch Spectre (2015) in HD online with dual audio? Dual audio means that you can choose between two languages for the audio track, such as English and Hindi. This can be useful if you want to enjoy the movie in your native language or learn a new one. Here are some tips on how to watch Spectre (2015) in HD online with dual audio:

-

HD Online Player (spectre 2015 dual audio 720p brripgo)


Download File ••• https://bytlly.com/2uGy34



-
    -
  • Find a reliable online player that supports dual audio. There are many online players that claim to offer HD quality and dual audio, but not all of them are trustworthy or safe. Some may contain malware, viruses, or ads that can harm your device or compromise your privacy. To avoid these risks, you should look for an online player that has a good reputation, positive reviews, and secure encryption. One example of such an online player is HD Online Player (spectre 2015 dual audio 720p brripgo), which you can find by searching on Bing.
  • -
  • Select the movie and the audio track. Once you have found a reliable online player, you can search for Spectre (2015) on its website or app. You should see a list of available sources for the movie, each with different qualities and formats. Choose the one that has HD quality and dual audio options. Then, select the audio track that you prefer from the menu. You can switch between the languages anytime during the playback.
  • -
  • Enjoy the movie. After selecting the movie and the audio track, you can start watching Spectre (2015) in HD online with dual audio. You can adjust the volume, brightness, subtitles, and other settings according to your preference. You can also pause, rewind, fast-forward, or skip scenes as you wish. Make sure you have a stable internet connection and a compatible device for the best viewing experience.
  • -
-

Watching Spectre (2015) in HD online with dual audio can be a fun and convenient way to enjoy this James Bond movie. However, you should always be careful about the online players that you use and respect the copyright laws of your country. If you want to watch more movies like Spectre (2015) in HD online with dual audio, you can check out other sources on Bing.

- -

What makes Spectre (2015) a great James Bond movie? Spectre (2015) is the fourth and final film to feature Daniel Craig as James Bond, and the second one to be directed by Sam Mendes. The film has received mixed reviews from critics and fans, but it has also been praised for its action sequences, cast performances, musical score, and cinematography. Here are some of the reasons why Spectre (2015) is a great James Bond movie:

-
    -
  • It connects the previous films in the series. Spectre (2015) is the culmination of the story arc that began with Casino Royale (2006), continued with Quantum of Solace (2008) and Skyfall (2012), and ended with Spectre (2015). The film reveals that all the villains that Bond faced in the previous films were part of SPECTRE, a global criminal organisation that has been manipulating world events for decades. The film also reveals that Blofeld is Bond's foster brother and the mastermind behind SPECTRE. The film ties up many loose ends and gives closure to Bond's character development.
  • -
  • It pays homage to the classic Bond films. Spectre (2015) is full of references and nods to the classic Bond films, especially those featuring Sean Connery and Roger Moore. For example, the film features a car chase in Rome with an Aston Martin DB10 and a Jaguar C-X75, a fight scene on a train with Hinx, a henchman with metal thumbs, a torture scene with Blofeld using a drill, a visit to Q's workshop with many gadgets, a ski chase in Austria with a plane, a desert base in Morocco with a meteorite crater, and a climax in London with a helicopter. The film also brings back some iconic elements of the Bond franchise, such as the gun barrel sequence, the white cat, the Nehru jacket, and the scarred face of Blofeld.
  • -
  • It explores the themes of surveillance and identity. Spectre (2015) is set in a contemporary world where technology and surveillance are ubiquitous and powerful. The film questions the role and relevance of spies and secret agents in such a world, where information and data can be easily accessed and manipulated by anyone. The film also explores the themes of identity and legacy, as Bond struggles to find his place and purpose in a changing world, while also confronting his past and his family ties. The film challenges Bond's loyalty to MI6 and his sense of duty, as he goes rogue to pursue SPECTRE and Blofeld.
  • -
-

Spectre (2015) is a great James Bond movie that offers a thrilling and satisfying conclusion to Daniel Craig's era as 007. The film combines action, adventure, romance, humor, and drama in a stylish and spectacular way. If you haven't watched Spectre (2015) yet, you can watch it in HD online with dual audio using HD Online Player (spectre 2015 dual audio 720p brripgo).

-

d5da3c52bf
-
-
\ No newline at end of file diff --git a/spaces/lizhen30/LangChainGo/data/pure-bash-bible.md b/spaces/lizhen30/LangChainGo/data/pure-bash-bible.md deleted file mode 100644 index 4b1d011d0b5d29ca9d90216eb3607b03d5f90d5a..0000000000000000000000000000000000000000 --- a/spaces/lizhen30/LangChainGo/data/pure-bash-bible.md +++ /dev/null @@ -1,2200 +0,0 @@ -

NEW: pure sh bible (📖 A collection of pure POSIX sh alternatives to external processes).

- -
- -

-

pure bash bible

A collection of pure bash alternatives to external -processes.

- -

- -

- -
- - - - - -The goal of this book is to document commonly-known and lesser-known methods of doing various tasks using only built-in `bash` features. Using the snippets from this bible can help remove unneeded dependencies from scripts and in most cases make them faster. I came across these tips and discovered a few while developing [neofetch](https://github.com/dylanaraps/neofetch), [pxltrm](https://github.com/dylanaraps/pxltrm) and other smaller projects. - -The snippets below are linted using `shellcheck` and tests have been written where applicable. Want to contribute? Read the [CONTRIBUTING.md](https://github.com/dylanaraps/pure-bash-bible/blob/master/CONTRIBUTING.md). It outlines how the unit tests work and what is required when adding snippets to the bible. - -See something incorrectly described, buggy or outright wrong? Open an issue or send a pull request. If the bible is missing something, open an issue and a solution will be found. - -
-

This book is also available to purchase on leanpub. https://leanpub.com/bash

-

Or you can buy me a coffee. - -

- -
- -# Table of Contents - - - -* [FOREWORD](#foreword) -* [STRINGS](#strings) - * [Trim leading and trailing white-space from string](#trim-leading-and-trailing-white-space-from-string) - * [Trim all white-space from string and truncate spaces](#trim-all-white-space-from-string-and-truncate-spaces) - * [Use regex on a string](#use-regex-on-a-string) - * [Split a string on a delimiter](#split-a-string-on-a-delimiter) - * [Change a string to lowercase](#change-a-string-to-lowercase) - * [Change a string to uppercase](#change-a-string-to-uppercase) - * [Reverse a string case](#reverse-a-string-case) - * [Trim quotes from a string](#trim-quotes-from-a-string) - * [Strip all instances of pattern from string](#strip-all-instances-of-pattern-from-string) - * [Strip first occurrence of pattern from string](#strip-first-occurrence-of-pattern-from-string) - * [Strip pattern from start of string](#strip-pattern-from-start-of-string) - * [Strip pattern from end of string](#strip-pattern-from-end-of-string) - * [Percent-encode a string](#percent-encode-a-string) - * [Decode a percent-encoded string](#decode-a-percent-encoded-string) - * [Check if string contains a sub-string](#check-if-string-contains-a-sub-string) - * [Check if string starts with sub-string](#check-if-string-starts-with-sub-string) - * [Check if string ends with sub-string](#check-if-string-ends-with-sub-string) -* [ARRAYS](#arrays) - * [Reverse an array](#reverse-an-array) - * [Remove duplicate array elements](#remove-duplicate-array-elements) - * [Random array element](#random-array-element) - * [Cycle through an array](#cycle-through-an-array) - * [Toggle between two values](#toggle-between-two-values) -* [LOOPS](#loops) - * [Loop over a range of numbers](#loop-over-a-range-of-numbers) - * [Loop over a variable range of numbers](#loop-over-a-variable-range-of-numbers) - * [Loop over an array](#loop-over-an-array) - * [Loop over an array with an index](#loop-over-an-array-with-an-index) - * [Loop over the contents of a file](#loop-over-the-contents-of-a-file) - * [Loop over files and directories](#loop-over-files-and-directories) -* [FILE HANDLING](#file-handling) - * [Read a file to a string](#read-a-file-to-a-string) - * [Read a file to an array (*by line*)](#read-a-file-to-an-array-by-line) - * [Get the first N lines of a file](#get-the-first-n-lines-of-a-file) - * [Get the last N lines of a file](#get-the-last-n-lines-of-a-file) - * [Get the number of lines in a file](#get-the-number-of-lines-in-a-file) - * [Count files or directories in directory](#count-files-or-directories-in-directory) - * [Create an empty file](#create-an-empty-file) - * [Extract lines between two markers](#extract-lines-between-two-markers) -* [FILE PATHS](#file-paths) - * [Get the directory name of a file path](#get-the-directory-name-of-a-file-path) - * [Get the base-name of a file path](#get-the-base-name-of-a-file-path) -* [VARIABLES](#variables) - * [Assign and access a variable using a variable](#assign-and-access-a-variable-using-a-variable) - * [Name a variable based on another variable](#name-a-variable-based-on-another-variable) -* [ESCAPE SEQUENCES](#escape-sequences) - * [Text Colors](#text-colors) - * [Text Attributes](#text-attributes) - * [Cursor Movement](#cursor-movement) - * [Erasing Text](#erasing-text) -* [PARAMETER EXPANSION](#parameter-expansion) - * [Indirection](#indirection) - * [Replacement](#replacement) - * [Length](#length) - * [Expansion](#expansion) - * [Case Modification](#case-modification) - * [Default Value](#default-value) -* [BRACE EXPANSION](#brace-expansion) - * [Ranges](#ranges) - * [String Lists](#string-lists) -* [CONDITIONAL EXPRESSIONS](#conditional-expressions) - * [File Conditionals](#file-conditionals) - * [File Comparisons](#file-comparisons) - * [Variable Conditionals](#variable-conditionals) - * [Variable Comparisons](#variable-comparisons) -* [ARITHMETIC OPERATORS](#arithmetic-operators) - * [Assignment](#assignment) - * [Arithmetic](#arithmetic) - * [Bitwise](#bitwise) - * [Logical](#logical) - * [Miscellaneous](#miscellaneous) -* [ARITHMETIC](#arithmetic-1) - * [Simpler syntax to set variables](#simpler-syntax-to-set-variables) - * [Ternary Tests](#ternary-tests) -* [TRAPS](#traps) - * [Do something on script exit](#do-something-on-script-exit) - * [Ignore terminal interrupt (CTRL+C, SIGINT)](#ignore-terminal-interrupt-ctrlc-sigint) - * [React to window resize](#react-to-window-resize) - * [Do something before every command](#do-something-before-every-command) - * [Do something when a shell function or a sourced file finishes executing](#do-something-when-a-shell-function-or-a-sourced-file-finishes-executing) -* [PERFORMANCE](#performance) - * [Disable Unicode](#disable-unicode) -* [OBSOLETE SYNTAX](#obsolete-syntax) - * [Shebang](#shebang) - * [Command Substitution](#command-substitution) - * [Function Declaration](#function-declaration) -* [INTERNAL VARIABLES](#internal-variables) - * [Get the location to the `bash` binary](#get-the-location-to-the-bash-binary) - * [Get the version of the current running `bash` process](#get-the-version-of-the-current-running-bash-process) - * [Open the user's preferred text editor](#open-the-users-preferred-text-editor) - * [Get the name of the current function](#get-the-name-of-the-current-function) - * [Get the host-name of the system](#get-the-host-name-of-the-system) - * [Get the architecture of the Operating System](#get-the-architecture-of-the-operating-system) - * [Get the name of the Operating System / Kernel](#get-the-name-of-the-operating-system--kernel) - * [Get the current working directory](#get-the-current-working-directory) - * [Get the number of seconds the script has been running](#get-the-number-of-seconds-the-script-has-been-running) - * [Get a pseudorandom integer](#get-a-pseudorandom-integer) -* [INFORMATION ABOUT THE TERMINAL](#information-about-the-terminal) - * [Get the terminal size in lines and columns (*from a script*)](#get-the-terminal-size-in-lines-and-columns-from-a-script) - * [Get the terminal size in pixels](#get-the-terminal-size-in-pixels) - * [Get the current cursor position](#get-the-current-cursor-position) -* [CONVERSION](#conversion) - * [Convert a hex color to RGB](#convert-a-hex-color-to-rgb) - * [Convert an RGB color to hex](#convert-an-rgb-color-to-hex) -* [CODE GOLF](#code-golf) - * [Shorter `for` loop syntax](#shorter-for-loop-syntax) - * [Shorter infinite loops](#shorter-infinite-loops) - * [Shorter function declaration](#shorter-function-declaration) - * [Shorter `if` syntax](#shorter-if-syntax) - * [Simpler `case` statement to set variable](#simpler-case-statement-to-set-variable) -* [OTHER](#other) - * [Use `read` as an alternative to the `sleep` command](#use-read-as-an-alternative-to-the-sleep-command) - * [Check if a program is in the user's PATH](#check-if-a-program-is-in-the-users-path) - * [Get the current date using `strftime`](#get-the-current-date-using-strftime) - * [Get the username of the current user](#get-the-username-of-the-current-user) - * [Generate a UUID V4](#generate-a-uuid-v4) - * [Progress bars](#progress-bars) - * [Get the list of functions in a script](#get-the-list-of-functions-in-a-script) - * [Bypass shell aliases](#bypass-shell-aliases) - * [Bypass shell functions](#bypass-shell-functions) - * [Run a command in the background](#run-a-command-in-the-background) - * [Capture function return without command substitution](#capture-the-return-value-of-a-function-without-command-substitution) -* [AFTERWORD](#afterword) - - - -
- - -# FOREWORD - -A collection of pure `bash` alternatives to external processes and programs. The `bash` scripting language is more powerful than people realise and most tasks can be accomplished without depending on external programs. - -Calling an external process in `bash` is expensive and excessive use will cause a noticeable slowdown. Scripts and programs written using built-in methods (*where applicable*) will be faster, require fewer dependencies and afford a better understanding of the language itself. - -The contents of this book provide a reference for solving problems encountered when writing programs and scripts in `bash`. Examples are in function formats showcasing how to incorporate these solutions into code. - - - - -# STRINGS - -## Trim leading and trailing white-space from string - -This is an alternative to `sed`, `awk`, `perl` and other tools. The -function below works by finding all leading and trailing white-space and -removing it from the start and end of the string. The `:` built-in is used in place of a temporary variable. - -**Example Function:** - -```sh -trim_string() { - # Usage: trim_string " example string " - : "${1#"${1%%[![:space:]]*}"}" - : "${_%"${_##*[![:space:]]}"}" - printf '%s\n' "$_" -} -``` - -**Example Usage:** - -```shell -$ trim_string " Hello, World " -Hello, World - -$ name=" John Black " -$ trim_string "$name" -John Black -``` - - -## Trim all white-space from string and truncate spaces - -This is an alternative to `sed`, `awk`, `perl` and other tools. The -function below works by abusing word splitting to create a new string -without leading/trailing white-space and with truncated spaces. - -**Example Function:** - -```sh -# shellcheck disable=SC2086,SC2048 -trim_all() { - # Usage: trim_all " example string " - set -f - set -- $* - printf '%s\n' "$*" - set +f -} -``` - -**Example Usage:** - -```shell -$ trim_all " Hello, World " -Hello, World - -$ name=" John Black is my name. " -$ trim_all "$name" -John Black is my name. -``` - -## Use regex on a string - -The result of `bash`'s regex matching can be used to replace `sed` for a -large number of use-cases. - -**CAVEAT**: This is one of the few platform dependent `bash` features. -`bash` will use whatever regex engine is installed on the user's system. -Stick to POSIX regex features if aiming for compatibility. - -**CAVEAT**: This example only prints the first matching group. When using -multiple capture groups some modification is needed. - -**Example Function:** - -```sh -regex() { - # Usage: regex "string" "regex" - [[ $1 =~ $2 ]] && printf '%s\n' "${BASH_REMATCH[1]}" -} -``` - -**Example Usage:** - -```shell -$ # Trim leading white-space. -$ regex ' hello' '^\s*(.*)' -hello - -$ # Validate a hex color. -$ regex "#FFFFFF" '^(#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))$' -#FFFFFF - -$ # Validate a hex color (invalid). -$ regex "red" '^(#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))$' -# no output (invalid) -``` - -**Example Usage in script:** - -```shell -is_hex_color() { - if [[ $1 =~ ^(#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))$ ]]; then - printf '%s\n' "${BASH_REMATCH[1]}" - else - printf '%s\n' "error: $1 is an invalid color." - return 1 - fi -} - -read -r color -is_hex_color "$color" || color="#FFFFFF" - -# Do stuff. -``` - - -## Split a string on a delimiter - -**CAVEAT:** Requires `bash` 4+ - -This is an alternative to `cut`, `awk` and other tools. - -**Example Function:** - -```sh -split() { - # Usage: split "string" "delimiter" - IFS=$'\n' read -d "" -ra arr <<< "${1//$2/$'\n'}" - printf '%s\n' "${arr[@]}" -} -``` - -**Example Usage:** - -```shell -$ split "apples,oranges,pears,grapes" "," -apples -oranges -pears -grapes - -$ split "1, 2, 3, 4, 5" ", " -1 -2 -3 -4 -5 - -# Multi char delimiters work too! -$ split "hello---world---my---name---is---john" "---" -hello -world -my -name -is -john -``` - -## Change a string to lowercase - -**CAVEAT:** Requires `bash` 4+ - -**Example Function:** - -```sh -lower() { - # Usage: lower "string" - printf '%s\n' "${1,,}" -} -``` - -**Example Usage:** - -```shell -$ lower "HELLO" -hello - -$ lower "HeLlO" -hello - -$ lower "hello" -hello -``` - -## Change a string to uppercase - -**CAVEAT:** Requires `bash` 4+ - -**Example Function:** - -```sh -upper() { - # Usage: upper "string" - printf '%s\n' "${1^^}" -} -``` - -**Example Usage:** - -```shell -$ upper "hello" -HELLO - -$ upper "HeLlO" -HELLO - -$ upper "HELLO" -HELLO -``` - -## Reverse a string case - -**CAVEAT:** Requires `bash` 4+ - -**Example Function:** - -```sh -reverse_case() { - # Usage: reverse_case "string" - printf '%s\n' "${1~~}" -} -``` - -**Example Usage:** - -```shell -$ reverse_case "hello" -HELLO - -$ reverse_case "HeLlO" -hElLo - -$ reverse_case "HELLO" -hello -``` - -## Trim quotes from a string - -**Example Function:** - -```sh -trim_quotes() { - # Usage: trim_quotes "string" - : "${1//\'}" - printf '%s\n' "${_//\"}" -} -``` - -**Example Usage:** - -```shell -$ var="'Hello', \"World\"" -$ trim_quotes "$var" -Hello, World -``` - -## Strip all instances of pattern from string - -**Example Function:** - -```sh -strip_all() { - # Usage: strip_all "string" "pattern" - printf '%s\n' "${1//$2}" -} -``` - -**Example Usage:** - -```shell -$ strip_all "The Quick Brown Fox" "[aeiou]" -Th Qck Brwn Fx - -$ strip_all "The Quick Brown Fox" "[[:space:]]" -TheQuickBrownFox - -$ strip_all "The Quick Brown Fox" "Quick " -The Brown Fox -``` - -## Strip first occurrence of pattern from string - -**Example Function:** - -```sh -strip() { - # Usage: strip "string" "pattern" - printf '%s\n' "${1/$2}" -} -``` - -**Example Usage:** - -```shell -$ strip "The Quick Brown Fox" "[aeiou]" -Th Quick Brown Fox - -$ strip "The Quick Brown Fox" "[[:space:]]" -TheQuick Brown Fox -``` - -## Strip pattern from start of string - -**Example Function:** - -```sh -lstrip() { - # Usage: lstrip "string" "pattern" - printf '%s\n' "${1##$2}" -} -``` - -**Example Usage:** - -```shell -$ lstrip "The Quick Brown Fox" "The " -Quick Brown Fox -``` - -## Strip pattern from end of string - -**Example Function:** - -```sh -rstrip() { - # Usage: rstrip "string" "pattern" - printf '%s\n' "${1%%$2}" -} -``` - -**Example Usage:** - -```shell -$ rstrip "The Quick Brown Fox" " Fox" -The Quick Brown -``` - -## Percent-encode a string - -**Example Function:** - -```sh -urlencode() { - # Usage: urlencode "string" - local LC_ALL=C - for (( i = 0; i < ${#1}; i++ )); do - : "${1:i:1}" - case "$_" in - [a-zA-Z0-9.~_-]) - printf '%s' "$_" - ;; - - *) - printf '%%%02X' "'$_" - ;; - esac - done - printf '\n' -} -``` - -**Example Usage:** - -```shell -$ urlencode "https://github.com/dylanaraps/pure-bash-bible" -https%3A%2F%2Fgithub.com%2Fdylanaraps%2Fpure-bash-bible -``` - -## Decode a percent-encoded string - -**Example Function:** - -```sh -urldecode() { - # Usage: urldecode "string" - : "${1//+/ }" - printf '%b\n' "${_//%/\\x}" -} -``` - -**Example Usage:** - -```shell -$ urldecode "https%3A%2F%2Fgithub.com%2Fdylanaraps%2Fpure-bash-bible" -https://github.com/dylanaraps/pure-bash-bible -``` - -## Check if string contains a sub-string - -**Using a test:** - -```shell -if [[ $var == *sub_string* ]]; then - printf '%s\n' "sub_string is in var." -fi - -# Inverse (substring not in string). -if [[ $var != *sub_string* ]]; then - printf '%s\n' "sub_string is not in var." -fi - -# This works for arrays too! -if [[ ${arr[*]} == *sub_string* ]]; then - printf '%s\n' "sub_string is in array." -fi -``` - -**Using a case statement:** - -```shell -case "$var" in - *sub_string*) - # Do stuff - ;; - - *sub_string2*) - # Do more stuff - ;; - - *) - # Else - ;; -esac -``` - -## Check if string starts with sub-string - -```shell -if [[ $var == sub_string* ]]; then - printf '%s\n' "var starts with sub_string." -fi - -# Inverse (var does not start with sub_string). -if [[ $var != sub_string* ]]; then - printf '%s\n' "var does not start with sub_string." -fi -``` - -## Check if string ends with sub-string - -```shell -if [[ $var == *sub_string ]]; then - printf '%s\n' "var ends with sub_string." -fi - -# Inverse (var does not end with sub_string). -if [[ $var != *sub_string ]]; then - printf '%s\n' "var does not end with sub_string." -fi -``` - - - - -# ARRAYS - -## Reverse an array - -Enabling `extdebug` allows access to the `BASH_ARGV` array which stores -the current function’s arguments in reverse. - -**CAVEAT**: Requires `shopt -s compat44` in `bash` 5.0+. - -**Example Function:** - -```sh -reverse_array() { - # Usage: reverse_array "array" - shopt -s extdebug - f()(printf '%s\n' "${BASH_ARGV[@]}"); f "$@" - shopt -u extdebug -} -``` - -**Example Usage:** - -```shell -$ reverse_array 1 2 3 4 5 -5 -4 -3 -2 -1 - -$ arr=(red blue green) -$ reverse_array "${arr[@]}" -green -blue -red -``` - -## Remove duplicate array elements - -Create a temporary associative array. When setting associative array -values and a duplicate assignment occurs, bash overwrites the key. This -allows us to effectively remove array duplicates. - -**CAVEAT:** Requires `bash` 4+ - -**CAVEAT:** List order may not stay the same. - -**Example Function:** - -```sh -remove_array_dups() { - # Usage: remove_array_dups "array" - declare -A tmp_array - - for i in "$@"; do - [[ $i ]] && IFS=" " tmp_array["${i:- }"]=1 - done - - printf '%s\n' "${!tmp_array[@]}" -} -``` - -**Example Usage:** - -```shell -$ remove_array_dups 1 1 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5 -1 -2 -3 -4 -5 - -$ arr=(red red green blue blue) -$ remove_array_dups "${arr[@]}" -red -green -blue -``` - -## Random array element - -**Example Function:** - -```sh -random_array_element() { - # Usage: random_array_element "array" - local arr=("$@") - printf '%s\n' "${arr[RANDOM % $#]}" -} -``` - -**Example Usage:** - -```shell -$ array=(red green blue yellow brown) -$ random_array_element "${array[@]}" -yellow - -# Multiple arguments can also be passed. -$ random_array_element 1 2 3 4 5 6 7 -3 -``` - -## Cycle through an array - -Each time the `printf` is called, the next array element is printed. When -the print hits the last array element it starts from the first element -again. - -```sh -arr=(a b c d) - -cycle() { - printf '%s ' "${arr[${i:=0}]}" - ((i=i>=${#arr[@]}-1?0:++i)) -} -``` - - -## Toggle between two values - -This works the same as above, this is just a different use case. - -```sh -arr=(true false) - -cycle() { - printf '%s ' "${arr[${i:=0}]}" - ((i=i>=${#arr[@]}-1?0:++i)) -} -``` - - - - -# LOOPS - -## Loop over a range of numbers - -Alternative to `seq`. - -```shell -# Loop from 0-100 (no variable support). -for i in {0..100}; do - printf '%s\n' "$i" -done -``` - -## Loop over a variable range of numbers - -Alternative to `seq`. - -```shell -# Loop from 0-VAR. -VAR=50 -for ((i=0;i<=VAR;i++)); do - printf '%s\n' "$i" -done -``` - -## Loop over an array - -```shell -arr=(apples oranges tomatoes) - -# Just elements. -for element in "${arr[@]}"; do - printf '%s\n' "$element" -done -``` - -## Loop over an array with an index - -```shell -arr=(apples oranges tomatoes) - -# Elements and index. -for i in "${!arr[@]}"; do - printf '%s\n' "${arr[i]}" -done - -# Alternative method. -for ((i=0;i<${#arr[@]};i++)); do - printf '%s\n' "${arr[i]}" -done -``` - -## Loop over the contents of a file - -```shell -while read -r line; do - printf '%s\n' "$line" -done < "file" -``` - -## Loop over files and directories - -Don’t use `ls`. - -```shell -# Greedy example. -for file in *; do - printf '%s\n' "$file" -done - -# PNG files in dir. -for file in ~/Pictures/*.png; do - printf '%s\n' "$file" -done - -# Iterate over directories. -for dir in ~/Downloads/*/; do - printf '%s\n' "$dir" -done - -# Brace Expansion. -for file in /path/to/parentdir/{file1,file2,subdir/file3}; do - printf '%s\n' "$file" -done - -# Iterate recursively. -shopt -s globstar -for file in ~/Pictures/**/*; do - printf '%s\n' "$file" -done -shopt -u globstar -``` - - - - -# FILE HANDLING - -**CAVEAT:** `bash` does not handle binary data properly in versions `< 4.4`. - -## Read a file to a string - -Alternative to the `cat` command. - -```shell -file_data="$(<"file")" -``` - -## Read a file to an array (*by line*) - -Alternative to the `cat` command. - -```shell -# Bash <4 (discarding empty lines). -IFS=$'\n' read -d "" -ra file_data < "file" - -# Bash <4 (preserving empty lines). -while read -r line; do - file_data+=("$line") -done < "file" - -# Bash 4+ -mapfile -t file_data < "file" -``` - -## Get the first N lines of a file - -Alternative to the `head` command. - -**CAVEAT:** Requires `bash` 4+ - -**Example Function:** - -```sh -head() { - # Usage: head "n" "file" - mapfile -tn "$1" line < "$2" - printf '%s\n' "${line[@]}" -} -``` - -**Example Usage:** - -```shell -$ head 2 ~/.bashrc -# Prompt -PS1='➜ ' - -$ head 1 ~/.bashrc -# Prompt -``` - -## Get the last N lines of a file - -Alternative to the `tail` command. - -**CAVEAT:** Requires `bash` 4+ - -**Example Function:** - -```sh -tail() { - # Usage: tail "n" "file" - mapfile -tn 0 line < "$2" - printf '%s\n' "${line[@]: -$1}" -} -``` - -**Example Usage:** - -```shell -$ tail 2 ~/.bashrc -# Enable tmux. -# [[ -z "$TMUX" ]] && exec tmux - -$ tail 1 ~/.bashrc -# [[ -z "$TMUX" ]] && exec tmux -``` - -## Get the number of lines in a file - -Alternative to `wc -l`. - -**Example Function (bash 4):** - -```sh -lines() { - # Usage: lines "file" - mapfile -tn 0 lines < "$1" - printf '%s\n' "${#lines[@]}" -} -``` - -**Example Function (bash 3):** - -This method uses less memory than the `mapfile` method and works in `bash` 3 but it is slower for bigger files. - -```sh -lines_loop() { - # Usage: lines_loop "file" - count=0 - while IFS= read -r _; do - ((count++)) - done < "$1" - printf '%s\n' "$count" -} -``` - -**Example Usage:** - -```shell -$ lines ~/.bashrc -48 - -$ lines_loop ~/.bashrc -48 -``` - -## Count files or directories in directory - -This works by passing the output of the glob to the function and then counting the number of arguments. - -**Example Function:** - -```sh -count() { - # Usage: count /path/to/dir/* - # count /path/to/dir/*/ - printf '%s\n' "$#" -} -``` - -**Example Usage:** - -```shell -# Count all files in dir. -$ count ~/Downloads/* -232 - -# Count all dirs in dir. -$ count ~/Downloads/*/ -45 - -# Count all jpg files in dir. -$ count ~/Pictures/*.jpg -64 -``` - -## Create an empty file - -Alternative to `touch`. - -```shell -# Shortest. ->file - -# Longer alternatives: -:>file -echo -n >file -printf '' >file -``` - -## Extract lines between two markers - -**Example Function:** - -```sh -extract() { - # Usage: extract file "opening marker" "closing marker" - while IFS=$'\n' read -r line; do - [[ $extract && $line != "$3" ]] && - printf '%s\n' "$line" - - [[ $line == "$2" ]] && extract=1 - [[ $line == "$3" ]] && extract= - done < "$1" -} -``` - -**Example Usage:** - -```shell -# Extract code blocks from MarkDown file. -$ extract ~/projects/pure-bash/README.md '```sh' '```' -# Output here... -``` - - - - -# FILE PATHS - -## Get the directory name of a file path - -Alternative to the `dirname` command. - -**Example Function:** - -```sh -dirname() { - # Usage: dirname "path" - local tmp=${1:-.} - - [[ $tmp != *[!/]* ]] && { - printf '/\n' - return - } - - tmp=${tmp%%"${tmp##*[!/]}"} - - [[ $tmp != */* ]] && { - printf '.\n' - return - } - - tmp=${tmp%/*} - tmp=${tmp%%"${tmp##*[!/]}"} - - printf '%s\n' "${tmp:-/}" -} -``` - -**Example Usage:** - -```shell -$ dirname ~/Pictures/Wallpapers/1.jpg -/home/black/Pictures/Wallpapers - -$ dirname ~/Pictures/Downloads/ -/home/black/Pictures -``` - -## Get the base-name of a file path - -Alternative to the `basename` command. - -**Example Function:** - -```sh -basename() { - # Usage: basename "path" ["suffix"] - local tmp - - tmp=${1%"${1##*[!/]}"} - tmp=${tmp##*/} - tmp=${tmp%"${2/"$tmp"}"} - - printf '%s\n' "${tmp:-/}" -} -``` - -**Example Usage:** - -```shell -$ basename ~/Pictures/Wallpapers/1.jpg -1.jpg - -$ basename ~/Pictures/Wallpapers/1.jpg .jpg -1 - -$ basename ~/Pictures/Downloads/ -Downloads -``` - - - - -# VARIABLES - -## Assign and access a variable using a variable - -```shell -$ hello_world="value" - -# Create the variable name. -$ var="world" -$ ref="hello_$var" - -# Print the value of the variable name stored in 'hello_$var'. -$ printf '%s\n' "${!ref}" -value -``` - -Alternatively, on `bash` 4.3+: - -```shell -$ hello_world="value" -$ var="world" - -# Declare a nameref. -$ declare -n ref=hello_$var - -$ printf '%s\n' "$ref" -value -``` - -## Name a variable based on another variable - -```shell -$ var="world" -$ declare "hello_$var=value" -$ printf '%s\n' "$hello_world" -value -``` - - - - -# ESCAPE SEQUENCES - -Contrary to popular belief, there is no issue in utilizing raw escape sequences. Using `tput` abstracts the same ANSI sequences as if printed manually. Worse still, `tput` is not actually portable. There are a number of `tput` variants each with different commands and syntaxes (*try `tput setaf 3` on a FreeBSD system*). Raw sequences are fine. - -## Text Colors - -**NOTE:** Sequences requiring RGB values only work in True-Color Terminal Emulators. - -| Sequence | What does it do? | Value | -| -------- | ---------------- | ----- | -| `\e[38;5;m` | Set text foreground color. | `0-255` -| `\e[48;5;m` | Set text background color. | `0-255` -| `\e[38;2;;;m` | Set text foreground color to RGB color. | `R`, `G`, `B` -| `\e[48;2;;;m` | Set text background color to RGB color. | `R`, `G`, `B` - -## Text Attributes - -**NOTE:** Prepend 2 to any code below to turn it's effect off -(examples: 21=bold text off, 22=faint text off, 23=italic text off). - -| Sequence | What does it do? | -| -------- | ---------------- | -| `\e[m` | Reset text formatting and colors. | -| `\e[1m` | Bold text. | -| `\e[2m` | Faint text. | -| `\e[3m` | Italic text. | -| `\e[4m` | Underline text. | -| `\e[5m` | Blinking text. | -| `\e[7m` | Highlighted text. | -| `\e[8m` | Hidden text. | -| `\e[9m` | Strike-through text. | - - -## Cursor Movement - -| Sequence | What does it do? | Value | -| -------- | ---------------- | ----- | -| `\e[;H` | Move cursor to absolute position. | `line`, `column` -| `\e[H` | Move cursor to home position (`0,0`). | -| `\e[A` | Move cursor up N lines. | `num` -| `\e[B` | Move cursor down N lines. | `num` -| `\e[C` | Move cursor right N columns. | `num` -| `\e[D` | Move cursor left N columns. | `num` -| `\e[s` | Save cursor position. | -| `\e[u` | Restore cursor position. | - - -## Erasing Text - -| Sequence | What does it do? | -| -------- | ---------------- | -| `\e[K` | Erase from cursor position to end of line. -| `\e[1K` | Erase from cursor position to start of line. -| `\e[2K` | Erase the entire current line. -| `\e[J` | Erase from the current line to the bottom of the screen. -| `\e[1J` | Erase from the current line to the top of the screen. -| `\e[2J` | Clear the screen. -| `\e[2J\e[H` | Clear the screen and move cursor to `0,0`. - - - - - -# PARAMETER EXPANSION - -## Indirection - -| Parameter | What does it do? | -| --------- | ---------------- | -| `${!VAR}` | Access a variable based on the value of `VAR`. -| `${!VAR*}` | Expand to `IFS` separated list of variable names starting with `VAR`. | -| `${!VAR@}` | Expand to `IFS` separated list of variable names starting with `VAR`. If double-quoted, each variable name expands to a separate word. | - - -## Replacement - -| Parameter | What does it do? | -| --------- | ---------------- | -| `${VAR#PATTERN}` | Remove shortest match of pattern from start of string. | -| `${VAR##PATTERN}` | Remove longest match of pattern from start of string. | -| `${VAR%PATTERN}` | Remove shortest match of pattern from end of string. | -| `${VAR%%PATTERN}` | Remove longest match of pattern from end of string. | -| `${VAR/PATTERN/REPLACE}` | Replace first match with string. -| `${VAR//PATTERN/REPLACE}` | Replace all matches with string. -| `${VAR/PATTERN}` | Remove first match. -| `${VAR//PATTERN}` | Remove all matches. - -## Length - -| Parameter | What does it do? | -| --------- | ---------------- | -| `${#VAR}` | Length of var in characters. -| `${#ARR[@]}` | Length of array in elements. - -## Expansion - -| Parameter | What does it do? | -| --------- | ---------------- | -| `${VAR:OFFSET}` | Remove first `N` chars from variable. -| `${VAR:OFFSET:LENGTH}` | Get substring from `N` character to `N` character.
(`${VAR:10:10}`: Get sub-string from char `10` to char `20`) -| `${VAR:: OFFSET}` | Get first `N` chars from variable. -| `${VAR:: -OFFSET}` | Remove last `N` chars from variable. -| `${VAR: -OFFSET}` | Get last `N` chars from variable. -| `${VAR:OFFSET:-OFFSET}` | Cut first `N` chars and last `N` chars. | `bash 4.2+` | - -## Case Modification - -| Parameter | What does it do? | CAVEAT | -| --------- | ---------------- | ------ | -| `${VAR^}` | Uppercase first character. | `bash 4+` | -| `${VAR^^}` | Uppercase all characters. | `bash 4+` | -| `${VAR,}` | Lowercase first character. | `bash 4+` | -| `${VAR,,}` | Lowercase all characters. | `bash 4+` | -| `${VAR~}` | Reverse case of first character. | `bash 4+` | -| `${VAR~~}` | Reverse case of all characters. | `bash 4+` | - - -## Default Value - -| Parameter | What does it do? | -| --------- | ---------------- | -| `${VAR:-STRING}` | If `VAR` is empty or unset, use `STRING` as its value. -| `${VAR-STRING}` | If `VAR` is unset, use `STRING` as its value. -| `${VAR:=STRING}` | If `VAR` is empty or unset, set the value of `VAR` to `STRING`. -| `${VAR=STRING}` | If `VAR` is unset, set the value of `VAR` to `STRING`. -| `${VAR:+STRING}` | If `VAR` is not empty, use `STRING` as its value. -| `${VAR+STRING}` | If `VAR` is set, use `STRING` as its value. -| `${VAR:?STRING}` | Display an error if empty or unset. -| `${VAR?STRING}` | Display an error if unset. - - - - - -# BRACE EXPANSION - -## Ranges - -```shell -# Syntax: {..} - -# Print numbers 1-100. -echo {1..100} - -# Print range of floats. -echo 1.{1..9} - -# Print chars a-z. -echo {a..z} -echo {A..Z} - -# Nesting. -echo {A..Z}{0..9} - -# Print zero-padded numbers. -# CAVEAT: bash 4+ -echo {01..100} - -# Change increment amount. -# Syntax: {....} -# CAVEAT: bash 4+ -echo {1..10..2} # Increment by 2. -``` - -## String Lists - -```shell -echo {apples,oranges,pears,grapes} - -# Example Usage: -# Remove dirs Movies, Music and ISOS from ~/Downloads/. -rm -rf ~/Downloads/{Movies,Music,ISOS} -``` - - - - - - -# CONDITIONAL EXPRESSIONS - -## File Conditionals - -| Expression | Value | What does it do? | -| ---------- | ------ | ---------------- | -| `-a` | `file` | If file exists. -| `-b` | `file` | If file exists and is a block special file. -| `-c` | `file` | If file exists and is a character special file. -| `-d` | `file` | If file exists and is a directory. -| `-e` | `file` | If file exists. -| `-f` | `file` | If file exists and is a regular file. -| `-g` | `file` | If file exists and its set-group-id bit is set. -| `-h` | `file` | If file exists and is a symbolic link. -| `-k` | `file` | If file exists and its sticky-bit is set -| `-p` | `file` | If file exists and is a named pipe (*FIFO*). -| `-r` | `file` | If file exists and is readable. -| `-s` | `file` | If file exists and its size is greater than zero. -| `-t` | `fd` | If file descriptor is open and refers to a terminal. -| `-u` | `file` | If file exists and its set-user-id bit is set. -| `-w` | `file` | If file exists and is writable. -| `-x` | `file` | If file exists and is executable. -| `-G` | `file` | If file exists and is owned by the effective group ID. -| `-L` | `file` | If file exists and is a symbolic link. -| `-N` | `file` | If file exists and has been modified since last read. -| `-O` | `file` | If file exists and is owned by the effective user ID. -| `-S` | `file` | If file exists and is a socket. - -## File Comparisons - -| Expression | What does it do? | -| ---------- | ---------------- | -| `file -ef file2` | If both files refer to the same inode and device numbers. -| `file -nt file2` | If `file` is newer than `file2` (*uses modification time*) or `file` exists and `file2` does not. -| `file -ot file2` | If `file` is older than `file2` (*uses modification time*) or `file2` exists and `file` does not. - -## Variable Conditionals - -| Expression | Value | What does it do? | -| ---------- | ----- | ---------------- | -| `-o` | `opt` | If shell option is enabled. -| `-v` | `var` | If variable has a value assigned. -| `-R` | `var` | If variable is a name reference. -| `-z` | `var` | If the length of string is zero. -| `-n` | `var` | If the length of string is non-zero. - -## Variable Comparisons - -| Expression | What does it do? | -| ---------- | ---------------- | -| `var = var2` | Equal to. -| `var == var2` | Equal to (*synonym for `=`*). -| `var != var2` | Not equal to. -| `var < var2` | Less than (*in ASCII alphabetical order.*) -| `var > var2` | Greater than (*in ASCII alphabetical order.*) - - - - - -# ARITHMETIC OPERATORS - -## Assignment - -| Operators | What does it do? | -| --------- | ---------------- | -| `=` | Initialize or change the value of a variable. - -## Arithmetic - -| Operators | What does it do? | -| --------- | ---------------- | -| `+` | Addition -| `-` | Subtraction -| `*` | Multiplication -| `/` | Division -| `**` | Exponentiation -| `%` | Modulo -| `+=` | Plus-Equal (*Increment a variable.*) -| `-=` | Minus-Equal (*Decrement a variable.*) -| `*=` | Times-Equal (*Multiply a variable.*) -| `/=` | Slash-Equal (*Divide a variable.*) -| `%=` | Mod-Equal (*Remainder of dividing a variable.*) - -## Bitwise - -| Operators | What does it do? | -| --------- | ---------------- | -| `<<` | Bitwise Left Shift -| `<<=` | Left-Shift-Equal -| `>>` | Bitwise Right Shift -| `>>=` | Right-Shift-Equal -| `&` | Bitwise AND -| `&=` | Bitwise AND-Equal -| `\|` | Bitwise OR -| `\|=` | Bitwise OR-Equal -| `~` | Bitwise NOT -| `^` | Bitwise XOR -| `^=` | Bitwise XOR-Equal - -## Logical - -| Operators | What does it do? | -| --------- | ---------------- | -| `!` | NOT -| `&&` | AND -| `\|\|` | OR - -## Miscellaneous - -| Operators | What does it do? | Example | -| --------- | ---------------- | ------- | -| `,` | Comma Separator | `((a=1,b=2,c=3))` - - - - - -# ARITHMETIC - -## Simpler syntax to set variables - -```shell -# Simple math -((var=1+2)) - -# Decrement/Increment variable -((var++)) -((var--)) -((var+=1)) -((var-=1)) - -# Using variables -((var=var2*arr[2])) -``` - -## Ternary Tests - -```shell -# Set the value of var to var2 if var2 is greater than var. -# var: variable to set. -# var2>var: Condition to test. -# ?var2: If the test succeeds. -# :var: If the test fails. -((var=var2>var?var2:var)) -``` - - - - -# TRAPS - -Traps allow a script to execute code on various signals. In [pxltrm](https://github.com/dylanaraps/pxltrm) (*a pixel art editor written in bash*) traps are used to redraw the user interface on window resize. Another use case is cleaning up temporary files on script exit. - -Traps should be added near the start of scripts so any early errors are also caught. - -**NOTE:** For a full list of signals, see `trap -l`. - - -## Do something on script exit - -```shell -# Clear screen on script exit. -trap 'printf \\e[2J\\e[H\\e[m' EXIT -``` - -## Ignore terminal interrupt (CTRL+C, SIGINT) - -```shell -trap '' INT -``` - -## React to window resize - -```shell -# Call a function on window resize. -trap 'code_here' SIGWINCH -``` - -## Do something before every command - -```shell -trap 'code_here' DEBUG -``` - -## Do something when a shell function or a sourced file finishes executing - -```shell -trap 'code_here' RETURN -``` - - - - -# PERFORMANCE - -## Disable Unicode - -If unicode is not required, it can be disabled for a performance increase. Results may vary however there have been noticeable improvements in [neofetch](https://github.com/dylanaraps/neofetch) and other programs. - -```shell -# Disable unicode. -LC_ALL=C -LANG=C -``` - - - - -# OBSOLETE SYNTAX - -## Shebang - -Use `#!/usr/bin/env bash` instead of `#!/bin/bash`. - -- The former searches the user's `PATH` to find the `bash` binary. -- The latter assumes it is always installed to `/bin/` which can cause issues. - -**NOTE**: There are times when one may have a good reason for using `#!/bin/bash` or another direct path to the binary. - - -```shell -# Right: - - #!/usr/bin/env bash - -# Less right: - - #!/bin/bash -``` - -## Command Substitution - -Use `$()` instead of `` ` ` ``. - -```shell -# Right. -var="$(command)" - -# Wrong. -var=`command` - -# $() can easily be nested whereas `` cannot. -var="$(command "$(command)")" -``` - -## Function Declaration - -Do not use the `function` keyword, it reduces compatibility with older versions of `bash`. - -```shell -# Right. -do_something() { - # ... -} - -# Wrong. -function do_something() { - # ... -} -``` - - - - -# INTERNAL VARIABLES - -## Get the location to the `bash` binary - -```shell -"$BASH" -``` - -## Get the version of the current running `bash` process - -```shell -# As a string. -"$BASH_VERSION" - -# As an array. -"${BASH_VERSINFO[@]}" -``` - -## Open the user's preferred text editor - -```shell -"$EDITOR" "$file" - -# NOTE: This variable may be empty, set a fallback value. -"${EDITOR:-vi}" "$file" -``` - -## Get the name of the current function - -```shell -# Current function. -"${FUNCNAME[0]}" - -# Parent function. -"${FUNCNAME[1]}" - -# So on and so forth. -"${FUNCNAME[2]}" -"${FUNCNAME[3]}" - -# All functions including parents. -"${FUNCNAME[@]}" -``` - -## Get the host-name of the system - -```shell -"$HOSTNAME" - -# NOTE: This variable may be empty. -# Optionally set a fallback to the hostname command. -"${HOSTNAME:-$(hostname)}" -``` - -## Get the architecture of the Operating System - -```shell -"$HOSTTYPE" -``` - -## Get the name of the Operating System / Kernel - -This can be used to add conditional support for different Operating -Systems without needing to call `uname`. - -```shell -"$OSTYPE" -``` - -## Get the current working directory - -This is an alternative to the `pwd` built-in. - -```shell -"$PWD" -``` - -## Get the number of seconds the script has been running - -```shell -"$SECONDS" -``` - -## Get a pseudorandom integer - -Each time `$RANDOM` is used, a different integer between `0` and `32767` is returned. This variable should not be used for anything related to security (*this includes encryption keys etc*). - - -```shell -"$RANDOM" -``` - - - - -# INFORMATION ABOUT THE TERMINAL - -## Get the terminal size in lines and columns (*from a script*) - -This is handy when writing scripts in pure bash and `stty`/`tput` can’t be -called. - -**Example Function:** - -```sh -get_term_size() { - # Usage: get_term_size - - # (:;:) is a micro sleep to ensure the variables are - # exported immediately. - shopt -s checkwinsize; (:;:) - printf '%s\n' "$LINES $COLUMNS" -} -``` - -**Example Usage:** - -```shell -# Output: LINES COLUMNS -$ get_term_size -15 55 -``` - -## Get the terminal size in pixels - -**CAVEAT**: This does not work in some terminal emulators. - -**Example Function:** - -```sh -get_window_size() { - # Usage: get_window_size - printf '%b' "${TMUX:+\\ePtmux;\\e}\\e[14t${TMUX:+\\e\\\\}" - IFS=';t' read -d t -t 0.05 -sra term_size - printf '%s\n' "${term_size[1]}x${term_size[2]}" -} -``` - -**Example Usage:** - -```shell -# Output: WIDTHxHEIGHT -$ get_window_size -1200x800 - -# Output (fail): -$ get_window_size -x -``` - -## Get the current cursor position - -This is useful when creating a TUI in pure bash. - -**Example Function:** - -```sh -get_cursor_pos() { - # Usage: get_cursor_pos - IFS='[;' read -p $'\e[6n' -d R -rs _ y x _ - printf '%s\n' "$x $y" -} -``` - -**Example Usage:** - -```shell -# Output: X Y -$ get_cursor_pos -1 8 -``` - - - - -# CONVERSION - -## Convert a hex color to RGB - -**Example Function:** - -```sh -hex_to_rgb() { - # Usage: hex_to_rgb "#FFFFFF" - # hex_to_rgb "000000" - : "${1/\#}" - ((r=16#${_:0:2},g=16#${_:2:2},b=16#${_:4:2})) - printf '%s\n' "$r $g $b" -} -``` - -**Example Usage:** - -```shell -$ hex_to_rgb "#FFFFFF" -255 255 255 -``` - - -## Convert an RGB color to hex - -**Example Function:** - -```sh -rgb_to_hex() { - # Usage: rgb_to_hex "r" "g" "b" - printf '#%02x%02x%02x\n' "$1" "$2" "$3" -} -``` - -**Example Usage:** - -```shell -$ rgb_to_hex "255" "255" "255" -#FFFFFF -``` - - -# CODE GOLF - -## Shorter `for` loop syntax - -```shell -# Tiny C Style. -for((;i++<10;)){ echo "$i";} - -# Undocumented method. -for i in {1..10};{ echo "$i";} - -# Expansion. -for i in {1..10}; do echo "$i"; done - -# C Style. -for((i=0;i<=10;i++)); do echo "$i"; done -``` - -## Shorter infinite loops - -```shell -# Normal method -while :; do echo hi; done - -# Shorter -for((;;)){ echo hi;} -``` - -## Shorter function declaration - -```shell -# Normal method -f(){ echo hi;} - -# Using a subshell -f()(echo hi) - -# Using arithmetic -# This can be used to assign integer values. -# Example: f a=1 -# f a++ -f()(($1)) - -# Using tests, loops etc. -# NOTE: ‘while’, ‘until’, ‘case’, ‘(())’, ‘[[]]’ can also be used. -f()if true; then echo "$1"; fi -f()for i in "$@"; do echo "$i"; done -``` - -## Shorter `if` syntax - -```shell -# One line -# Note: The 3rd statement may run when the 1st is true -[[ $var == hello ]] && echo hi || echo bye -[[ $var == hello ]] && { echo hi; echo there; } || echo bye - -# Multi line (no else, single statement) -# Note: The exit status may not be the same as with an if statement -[[ $var == hello ]] && - echo hi - -# Multi line (no else) -[[ $var == hello ]] && { - echo hi - # ... -} -``` - -## Simpler `case` statement to set variable - -The `:` built-in can be used to avoid repeating `variable=` in a case statement. The `$_` variable stores the last argument of the last command. `:` always succeeds so it can be used to store the variable value. - -```shell -# Modified snippet from Neofetch. -case "$OSTYPE" in - "darwin"*) - : "MacOS" - ;; - - "linux"*) - : "Linux" - ;; - - *"bsd"* | "dragonfly" | "bitrig") - : "BSD" - ;; - - "cygwin" | "msys" | "win32") - : "Windows" - ;; - - *) - printf '%s\n' "Unknown OS detected, aborting..." >&2 - exit 1 - ;; -esac - -# Finally, set the variable. -os="$_" -``` - - - - -# OTHER - -## Use `read` as an alternative to the `sleep` command - -Surprisingly, `sleep` is an external command and not a `bash` built-in. - -**CAVEAT:** Requires `bash` 4+ - -**Example Function:** - -```sh -read_sleep() { - # Usage: read_sleep 1 - # read_sleep 0.2 - read -rt "$1" <> <(:) || : -} -``` - -**Example Usage:** - -```shell -read_sleep 1 -read_sleep 0.1 -read_sleep 30 -``` - -For performance-critical situations, where it is not economic to open and close an excessive number of file descriptors, the allocation of a file descriptor may be done only once for all invocations of `read`: - -(See the generic original implementation at https://blog.dhampir.no/content/sleeping-without-a-subprocess-in-bash-and-how-to-sleep-forever) - -```shell -exec {sleep_fd}<> <(:) -while some_quick_test; do - # equivalent of sleep 0.001 - read -t 0.001 -u $sleep_fd -done -``` - -## Check if a program is in the user's PATH - -```shell -# There are 3 ways to do this and either one can be used. -type -p executable_name &>/dev/null -hash executable_name &>/dev/null -command -v executable_name &>/dev/null - -# As a test. -if type -p executable_name &>/dev/null; then - # Program is in PATH. -fi - -# Inverse. -if ! type -p executable_name &>/dev/null; then - # Program is not in PATH. -fi - -# Example (Exit early if program is not installed). -if ! type -p convert &>/dev/null; then - printf '%s\n' "error: convert is not installed, exiting..." - exit 1 -fi -``` - -## Get the current date using `strftime` - -Bash’s `printf` has a built-in method of getting the date which can be used in place of the `date` command. - -**CAVEAT:** Requires `bash` 4+ - -**Example Function:** - -```sh -date() { - # Usage: date "format" - # See: 'man strftime' for format. - printf "%($1)T\\n" "-1" -} -``` - -**Example Usage:** - -```shell -# Using above function. -$ date "%a %d %b - %l:%M %p" -Fri 15 Jun - 10:00 AM - -# Using printf directly. -$ printf '%(%a %d %b - %l:%M %p)T\n' "-1" -Fri 15 Jun - 10:00 AM - -# Assigning a variable using printf. -$ printf -v date '%(%a %d %b - %l:%M %p)T\n' '-1' -$ printf '%s\n' "$date" -Fri 15 Jun - 10:00 AM -``` - -## Get the username of the current user - -**CAVEAT:** Requires `bash` 4.4+ - -```shell -$ : \\u -# Expand the parameter as if it were a prompt string. -$ printf '%s\n' "${_@P}" -black -``` - -## Generate a UUID V4 - -**CAVEAT**: The generated value is not cryptographically secure. - -**Example Function:** - -```sh -uuid() { - # Usage: uuid - C="89ab" - - for ((N=0;N<16;++N)); do - B="$((RANDOM%256))" - - case "$N" in - 6) printf '4%x' "$((B%16))" ;; - 8) printf '%c%x' "${C:$RANDOM%${#C}:1}" "$((B%16))" ;; - - 3|5|7|9) - printf '%02x-' "$B" - ;; - - *) - printf '%02x' "$B" - ;; - esac - done - - printf '\n' -} -``` - -**Example Usage:** - -```shell -$ uuid -d5b6c731-1310-4c24-9fe3-55d556d44374 -``` - -## Progress bars - -This is a simple way of drawing progress bars without needing a for loop -in the function itself. - -**Example Function:** - -```sh -bar() { - # Usage: bar 1 10 - # ^----- Elapsed Percentage (0-100). - # ^-- Total length in chars. - ((elapsed=$1*$2/100)) - - # Create the bar with spaces. - printf -v prog "%${elapsed}s" - printf -v total "%$(($2-elapsed))s" - - printf '%s\r' "[${prog// /-}${total}]" -} -``` - -**Example Usage:** - -```shell -for ((i=0;i<=100;i++)); do - # Pure bash micro sleeps (for the example). - (:;:) && (:;:) && (:;:) && (:;:) && (:;:) - - # Print the bar. - bar "$i" "10" -done - -printf '\n' -``` - -## Get the list of functions in a script - -```sh -get_functions() { - # Usage: get_functions - IFS=$'\n' read -d "" -ra functions < <(declare -F) - printf '%s\n' "${functions[@]//declare -f }" -} -``` - -## Bypass shell aliases - -```shell -# alias -ls - -# command -# shellcheck disable=SC1001 -\ls -``` - -## Bypass shell functions - -```shell -# function -ls - -# command -command ls -``` - -## Run a command in the background - -This will run the given command and keep it running, even after the terminal or SSH connection is terminated. All output is ignored. - -```sh -bkr() { - (nohup "$@" &>/dev/null &) -} - -bkr ./some_script.sh # some_script.sh is now running in the background -``` - -## Capture the return value of a function without command substitution - -**CAVEAT:** Requires `bash` 4+ - -This uses local namerefs to avoid using `var=$(some_func)` style command substitution for function output capture. - -```sh -to_upper() { - local -n ptr=${1} - - ptr=${ptr^^} -} - -foo="bar" -to_upper foo -printf "%s\n" "${foo}" # BAR -``` - - - -# AFTERWORD - -Thanks for reading! If this bible helped you in any way and you'd like to give back, consider donating. Donations give me the time to make this the best resource possible. Can't donate? That's OK, star the repo and share it with your friends! - - - - -Rock on. 🤘 diff --git a/spaces/llamaindex/text2image_prompt_assistant/app.py b/spaces/llamaindex/text2image_prompt_assistant/app.py deleted file mode 100644 index 36d144cb9e339a48e60f723fe4b8f78410df2524..0000000000000000000000000000000000000000 --- a/spaces/llamaindex/text2image_prompt_assistant/app.py +++ /dev/null @@ -1,43 +0,0 @@ -import streamlit as st -from prompt_assistant import Text2ImagePromptAssistant - -st.title('LlamaIndex Text2ImagePromptAssistant') - -st.markdown('This is a tool for HF agents, that assists with writing text-to-image prompts with the power of [LlamaIndex](https://gpt-index.readthedocs.io/en/latest/index.html). By indexing 10K random prompts from [DiffusionDB](https://huggingface.co/datasets/poloclub/diffusiondb), LlamaIndex is able to suggest text-to-image prompts that will hopefully lead to more beautiful results. With a HF Agent, the agent will call the prompt assistant tool before generating an image from text.') - -st.markdown('Example usage is below:') - -st.markdown(""" -```python -from transformers import load_tool - -prompt_assistant = load_tool( - "llamaindex/text2image_prompt_assistant", - openai_api_key="your_api_key", - model_name='text-davinci-003', - temperature=0.3, # increase or decrease this to control variation - verbose=True -) - -agent = OpenAiAgent(model="text-davinci-003", api_key="your_api_key") -agent.run("Draw me a picture a river and some trees.") -``` -""" -) - -st.subheader("Try out the tool below!") -st.markdown("Note that the first run may be slow as it downloads files needed inference. Furthermore, the text-2-image model itself will be running on CPU. After the first run, it should be faster!") - -api_key = st.text_input('OpenAI API key') - -model_name = st.selectbox('Model Name', options=['text-davinci-003', 'gpt-3.5-turbo', 'gpt-4']) - -temperature = st.slider('Temperature', min_value=0.0, max_value=1.0, step=0.05, value=0.3) - -initial_input = st.text_input('Initial text-to-image prompt', placeholder='Draw me an image of a happy dog.') - -if st.button('Generate optimized image'): - with st.spinner('Running...'): - tool = Text2ImagePromptAssistant(openai_api_key=api_key, model_name=model_name, temperature=temperature) - response = tool(initial_input) - st.image(response) diff --git a/spaces/longlian/llm-grounded-diffusion/models/attention_processor.py b/spaces/longlian/llm-grounded-diffusion/models/attention_processor.py deleted file mode 100644 index ed86bf62f0c61c14e2857974093b2d043393b21b..0000000000000000000000000000000000000000 --- a/spaces/longlian/llm-grounded-diffusion/models/attention_processor.py +++ /dev/null @@ -1,508 +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 warnings -from typing import Callable, Optional, Union - -import torch -import torch.nn.functional as F -from torch import nn - -from diffusers.utils import deprecate, logging, maybe_allow_in_graph - -logger = logging.get_logger(__name__) # pylint: disable=invalid-name - -@maybe_allow_in_graph -class Attention(nn.Module): - r""" - A cross attention layer. - - Parameters: - query_dim (`int`): The number of channels in the query. - cross_attention_dim (`int`, *optional*): - The number of channels in the encoder_hidden_states. If not given, defaults to `query_dim`. - heads (`int`, *optional*, defaults to 8): The number of heads to use for multi-head attention. - dim_head (`int`, *optional*, defaults to 64): The number of channels in each head. - dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. - bias (`bool`, *optional*, defaults to False): - Set to `True` for the query, key, and value linear layers to contain a bias parameter. - """ - - def __init__( - self, - query_dim: int, - cross_attention_dim: Optional[int] = None, - heads: int = 8, - dim_head: int = 64, - dropout: float = 0.0, - bias=False, - upcast_attention: bool = False, - upcast_softmax: bool = False, - cross_attention_norm: Optional[str] = None, - cross_attention_norm_num_groups: int = 32, - added_kv_proj_dim: Optional[int] = None, - norm_num_groups: Optional[int] = None, - spatial_norm_dim: Optional[int] = None, - out_bias: bool = True, - scale_qk: bool = True, - only_cross_attention: bool = False, - eps: float = 1e-5, - rescale_output_factor: float = 1.0, - residual_connection: bool = False, - _from_deprecated_attn_block=False, - processor: Optional["AttnProcessor"] = None, - ): - super().__init__() - inner_dim = dim_head * heads - cross_attention_dim = cross_attention_dim if cross_attention_dim is not None else query_dim - self.upcast_attention = upcast_attention - self.upcast_softmax = upcast_softmax - self.rescale_output_factor = rescale_output_factor - self.residual_connection = residual_connection - - # we make use of this private variable to know whether this class is loaded - # with an deprecated state dict so that we can convert it on the fly - self._from_deprecated_attn_block = _from_deprecated_attn_block - - self.scale_qk = scale_qk - self.scale = dim_head**-0.5 if self.scale_qk else 1.0 - - self.heads = heads - # for slice_size > 0 the attention score computation - # is split across the batch axis to save memory - # You can set slice_size with `set_attention_slice` - self.sliceable_head_dim = heads - - self.added_kv_proj_dim = added_kv_proj_dim - self.only_cross_attention = only_cross_attention - - if self.added_kv_proj_dim is None and self.only_cross_attention: - raise ValueError( - "`only_cross_attention` can only be set to True if `added_kv_proj_dim` is not None. Make sure to set either `only_cross_attention=False` or define `added_kv_proj_dim`." - ) - - if norm_num_groups is not None: - self.group_norm = nn.GroupNorm(num_channels=query_dim, num_groups=norm_num_groups, eps=eps, affine=True) - else: - self.group_norm = None - - if spatial_norm_dim is not None: - self.spatial_norm = SpatialNorm(f_channels=query_dim, zq_channels=spatial_norm_dim) - else: - self.spatial_norm = None - - if cross_attention_norm is None: - self.norm_cross = None - elif cross_attention_norm == "layer_norm": - self.norm_cross = nn.LayerNorm(cross_attention_dim) - elif cross_attention_norm == "group_norm": - if self.added_kv_proj_dim is not None: - # The given `encoder_hidden_states` are initially of shape - # (batch_size, seq_len, added_kv_proj_dim) before being projected - # to (batch_size, seq_len, cross_attention_dim). The norm is applied - # before the projection, so we need to use `added_kv_proj_dim` as - # the number of channels for the group norm. - norm_cross_num_channels = added_kv_proj_dim - else: - norm_cross_num_channels = cross_attention_dim - - self.norm_cross = nn.GroupNorm( - num_channels=norm_cross_num_channels, num_groups=cross_attention_norm_num_groups, eps=1e-5, affine=True - ) - else: - raise ValueError( - f"unknown cross_attention_norm: {cross_attention_norm}. Should be None, 'layer_norm' or 'group_norm'" - ) - - self.to_q = nn.Linear(query_dim, inner_dim, bias=bias) - - if not self.only_cross_attention: - # only relevant for the `AddedKVProcessor` classes - self.to_k = nn.Linear(cross_attention_dim, inner_dim, bias=bias) - self.to_v = nn.Linear(cross_attention_dim, inner_dim, bias=bias) - else: - self.to_k = None - self.to_v = None - - if self.added_kv_proj_dim is not None: - self.add_k_proj = nn.Linear(added_kv_proj_dim, inner_dim) - self.add_v_proj = nn.Linear(added_kv_proj_dim, inner_dim) - - self.to_out = nn.ModuleList([]) - self.to_out.append(nn.Linear(inner_dim, query_dim, bias=out_bias)) - self.to_out.append(nn.Dropout(dropout)) - - # set attention processor - # We use the AttnProcessor2_0 by default when torch 2.x is used which uses - # torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention - # but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1 - if processor is None: - # processor = ( - # AttnProcessor2_0() if hasattr(F, "scaled_dot_product_attention") and self.scale_qk else AttnProcessor() - # ) - # Note: efficient attention is not used. We can use efficient attention to speed up. - processor = AttnProcessor() - self.set_processor(processor) - - def set_processor(self, processor: "AttnProcessor"): - # if current processor is in `self._modules` and if passed `processor` is not, we need to - # pop `processor` from `self._modules` - if ( - hasattr(self, "processor") - and isinstance(self.processor, torch.nn.Module) - and not isinstance(processor, torch.nn.Module) - ): - logger.info(f"You are removing possibly trained weights of {self.processor} with {processor}") - self._modules.pop("processor") - - self.processor = processor - - def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None, return_attntion_probs=False, **cross_attention_kwargs): - # The `Attention` class can call different attention processors / attention functions - # here we simply pass along all tensors to the selected processor class - # For standard processors that are defined here, `**cross_attention_kwargs` is empty - return self.processor( - self, - hidden_states, - encoder_hidden_states=encoder_hidden_states, - attention_mask=attention_mask, - return_attntion_probs=return_attntion_probs, - **cross_attention_kwargs, - ) - - def batch_to_head_dim(self, tensor): - head_size = self.heads - batch_size, seq_len, dim = tensor.shape - tensor = tensor.reshape(batch_size // head_size, head_size, seq_len, dim) - tensor = tensor.permute(0, 2, 1, 3).reshape(batch_size // head_size, seq_len, dim * head_size) - return tensor - - def head_to_batch_dim(self, tensor, out_dim=3): - head_size = self.heads - batch_size, seq_len, dim = tensor.shape - tensor = tensor.reshape(batch_size, seq_len, head_size, dim // head_size) - tensor = tensor.permute(0, 2, 1, 3) - - if out_dim == 3: - tensor = tensor.reshape(batch_size * head_size, seq_len, dim // head_size) - - return tensor - - def get_attention_scores(self, query, key, attention_mask=None): - dtype = query.dtype - if self.upcast_attention: - query = query.float() - key = key.float() - - if attention_mask is None: - baddbmm_input = torch.empty( - query.shape[0], query.shape[1], key.shape[1], dtype=query.dtype, device=query.device - ) - beta = 0 - else: - baddbmm_input = attention_mask - beta = 1 - - attention_scores = torch.baddbmm( - baddbmm_input, - query, - key.transpose(-1, -2), - beta=beta, - alpha=self.scale, - ) - del baddbmm_input - - if self.upcast_softmax: - attention_scores = attention_scores.float() - - attention_probs = attention_scores.softmax(dim=-1) - del attention_scores - - attention_probs = attention_probs.to(dtype) - - return attention_probs - - def prepare_attention_mask(self, attention_mask, target_length, batch_size=None, out_dim=3): - if batch_size is None: - deprecate( - "batch_size=None", - "0.0.15", - ( - "Not passing the `batch_size` parameter to `prepare_attention_mask` can lead to incorrect" - " attention mask preparation and is deprecated behavior. Please make sure to pass `batch_size` to" - " `prepare_attention_mask` when preparing the attention_mask." - ), - ) - batch_size = 1 - - head_size = self.heads - if attention_mask is None: - return attention_mask - - current_length: int = attention_mask.shape[-1] - if current_length != target_length: - if attention_mask.device.type == "mps": - # HACK: MPS: Does not support padding by greater than dimension of input tensor. - # Instead, we can manually construct the padding tensor. - padding_shape = (attention_mask.shape[0], attention_mask.shape[1], target_length) - padding = torch.zeros(padding_shape, dtype=attention_mask.dtype, device=attention_mask.device) - attention_mask = torch.cat([attention_mask, padding], dim=2) - else: - # TODO: for pipelines such as stable-diffusion, padding cross-attn mask: - # we want to instead pad by (0, remaining_length), where remaining_length is: - # remaining_length: int = target_length - current_length - # TODO: re-enable tests/models/test_models_unet_2d_condition.py#test_model_xattn_padding - attention_mask = F.pad(attention_mask, (0, target_length), value=0.0) - - if out_dim == 3: - if attention_mask.shape[0] < batch_size * head_size: - attention_mask = attention_mask.repeat_interleave(head_size, dim=0) - elif out_dim == 4: - attention_mask = attention_mask.unsqueeze(1) - attention_mask = attention_mask.repeat_interleave(head_size, dim=1) - - return attention_mask - - def norm_encoder_hidden_states(self, encoder_hidden_states): - assert self.norm_cross is not None, "self.norm_cross must be defined to call self.norm_encoder_hidden_states" - - if isinstance(self.norm_cross, nn.LayerNorm): - encoder_hidden_states = self.norm_cross(encoder_hidden_states) - elif isinstance(self.norm_cross, nn.GroupNorm): - # Group norm norms along the channels dimension and expects - # input to be in the shape of (N, C, *). In this case, we want - # to norm along the hidden dimension, so we need to move - # (batch_size, sequence_length, hidden_size) -> - # (batch_size, hidden_size, sequence_length) - encoder_hidden_states = encoder_hidden_states.transpose(1, 2) - encoder_hidden_states = self.norm_cross(encoder_hidden_states) - encoder_hidden_states = encoder_hidden_states.transpose(1, 2) - else: - assert False - - return encoder_hidden_states - - -class AttnProcessor: - r""" - Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). - """ - - def __init__(self): - if not hasattr(F, "scaled_dot_product_attention"): - raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.") - - def __call_fast__( - self, - attn: Attention, - hidden_states, - encoder_hidden_states=None, - attention_mask=None, - temb=None, - ): - residual = hidden_states - - if attn.spatial_norm is not None: - hidden_states = attn.spatial_norm(hidden_states, temb) - - input_ndim = hidden_states.ndim - - if input_ndim == 4: - batch_size, channel, height, width = hidden_states.shape - hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2) - - batch_size, sequence_length, _ = ( - hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape - ) - inner_dim = hidden_states.shape[-1] - - if attention_mask is not None: - attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) - # scaled_dot_product_attention expects attention_mask shape to be - # (batch, heads, source_length, target_length) - attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1]) - - if attn.group_norm is not None: - hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2) - - query = attn.to_q(hidden_states) - - if encoder_hidden_states is None: - encoder_hidden_states = hidden_states - elif attn.norm_cross: - encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states) - - key = attn.to_k(encoder_hidden_states) - value = attn.to_v(encoder_hidden_states) - - head_dim = inner_dim // attn.heads - query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) - key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) - value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) - - # the output of sdp = (batch, num_heads, seq_len, head_dim) - # TODO: add support for attn.scale when we move to Torch 2.1 - hidden_states = F.scaled_dot_product_attention( - query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False - ) - - hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) - hidden_states = hidden_states.to(query.dtype) - - # linear proj - hidden_states = attn.to_out[0](hidden_states) - # dropout - hidden_states = attn.to_out[1](hidden_states) - - if input_ndim == 4: - hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width) - - if attn.residual_connection: - hidden_states = hidden_states + residual - - hidden_states = hidden_states / attn.rescale_output_factor - - return hidden_states - - def __call__( - self, - attn: Attention, - hidden_states, - encoder_hidden_states=None, - attention_mask=None, - temb=None, - return_attntion_probs=False, - attn_key=None, - attn_process_fn=None, - return_cond_ca_only=False, - return_token_ca_only=None, - offload_cross_attn_to_cpu=False, - save_attn_to_dict=None, - save_keys=None, - enable_flash_attn=True, - ): - """ - attn_key: current key (a tuple of hierarchy index (up/mid/down, stage id, block id, sub-block id), sub block id should always be 0 in SD UNet) - save_attn_to_dict: pass in a dict to save to dict - """ - cross_attn = encoder_hidden_states is not None - - if (not cross_attn) or ( - (attn_process_fn is None) - and not (save_attn_to_dict is not None and (save_keys is None or (tuple(attn_key) in save_keys))) - and not return_attntion_probs): - with torch.backends.cuda.sdp_kernel(enable_flash=enable_flash_attn, enable_math=True, enable_mem_efficient=enable_flash_attn): - return self.__call_fast__(attn, hidden_states, encoder_hidden_states, attention_mask, temb) - - residual = hidden_states - - if attn.spatial_norm is not None: - hidden_states = attn.spatial_norm(hidden_states, temb) - - input_ndim = hidden_states.ndim - - if input_ndim == 4: - batch_size, channel, height, width = hidden_states.shape - hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2) - - batch_size, sequence_length, _ = ( - hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape - ) - attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) - - if attn.group_norm is not None: - hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2) - - query = attn.to_q(hidden_states) - - if encoder_hidden_states is None: - encoder_hidden_states = hidden_states - elif attn.norm_cross: - encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states) - - key = attn.to_k(encoder_hidden_states) - value = attn.to_v(encoder_hidden_states) - - query = attn.head_to_batch_dim(query) - key = attn.head_to_batch_dim(key) - value = attn.head_to_batch_dim(value) - - attention_probs = attn.get_attention_scores(query, key, attention_mask) - # Currently only process cross-attention - if attn_process_fn is not None and cross_attn: - attention_probs_before_process = attention_probs.clone() - attention_probs = attn_process_fn(attention_probs, query, key, value, attn_key=attn_key, cross_attn=cross_attn, batch_size=batch_size, heads=attn.heads) - else: - attention_probs_before_process = attention_probs - hidden_states = torch.bmm(attention_probs, value) - hidden_states = attn.batch_to_head_dim(hidden_states) - - # linear proj - hidden_states = attn.to_out[0](hidden_states) - # dropout - hidden_states = attn.to_out[1](hidden_states) - - if input_ndim == 4: - hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width) - - if attn.residual_connection: - hidden_states = hidden_states + residual - - hidden_states = hidden_states / attn.rescale_output_factor - - if return_attntion_probs or save_attn_to_dict is not None: - # Recover batch dimension: (batch_size, heads, flattened_2d, text_tokens) - attention_probs_unflattened = attention_probs_before_process.unflatten(dim=0, sizes=(batch_size, attn.heads)) - if return_token_ca_only is not None: - # (batch size, n heads, 2d dimension, num text tokens) - if isinstance(return_token_ca_only, int): - # return_token_ca_only: an integer - attention_probs_unflattened = attention_probs_unflattened[:, :, :, return_token_ca_only:return_token_ca_only+1] - else: - # return_token_ca_only: A 1d index tensor - attention_probs_unflattened = attention_probs_unflattened[:, :, :, return_token_ca_only] - if return_cond_ca_only: - assert batch_size % 2 == 0, f"Samples are not in pairs: {batch_size} samples" - attention_probs_unflattened = attention_probs_unflattened[batch_size // 2:] - if offload_cross_attn_to_cpu: - attention_probs_unflattened = attention_probs_unflattened.cpu() - if save_attn_to_dict is not None and (save_keys is None or (tuple(attn_key) in save_keys)): - save_attn_to_dict[tuple(attn_key)] = attention_probs_unflattened - if return_attntion_probs: - return hidden_states, attention_probs_unflattened - return hidden_states - -# For typing -AttentionProcessor = AttnProcessor - -class SpatialNorm(nn.Module): - """ - Spatially conditioned normalization as defined in https://arxiv.org/abs/2209.09002 - """ - - def __init__( - self, - f_channels, - zq_channels, - ): - super().__init__() - self.norm_layer = nn.GroupNorm(num_channels=f_channels, num_groups=32, eps=1e-6, affine=True) - self.conv_y = nn.Conv2d(zq_channels, f_channels, kernel_size=1, stride=1, padding=0) - self.conv_b = nn.Conv2d(zq_channels, f_channels, kernel_size=1, stride=1, padding=0) - - def forward(self, f, zq): - f_size = f.shape[-2:] - zq = F.interpolate(zq, size=f_size, mode="nearest") - norm_f = self.norm_layer(f) - new_f = norm_f * self.conv_y(zq) + self.conv_b(zq) - return new_f diff --git a/spaces/ltgoslo/ssa-perin/mtool/codec/treex.py b/spaces/ltgoslo/ssa-perin/mtool/codec/treex.py deleted file mode 100644 index 800035677886bf877447c5d44074d453f8aeac03..0000000000000000000000000000000000000000 --- a/spaces/ltgoslo/ssa-perin/mtool/codec/treex.py +++ /dev/null @@ -1,191 +0,0 @@ -from operator import itemgetter; -import os.path; -import re; -import xml.etree.ElementTree as ET; - -from graph import Graph; - -def walk(id, node, parent, nodes, edges, ns): - i = node.get("id"); - o = node.findtext(ns + "ord"); - if i is None or o is None and parent is not None: - raise Exception("treex.walk(): " - "missing ‘id’ or ‘ord’ values while decoding tree #{}; exit." - "".format(id)); - nodes.append((i, int(o) if o is not None else 0, node)); - - if edges is not None: - functor = node.findtext(ns + "functor"); - if parent is not None and functor is not None: - edges.append((parent, i, functor)); - - children = node.find(ns + "children"); - if children is not None: - for child in children: - if child.tag == ns + "LM": - walk(id, child, i, nodes, edges, ns); - if children.find(ns + "LM") is None: - walk(id, children, i, nodes, edges, ns); - -def read(fp, text = None): - ns = "{http://ufal.mff.cuni.cz/pdt/pml/}"; - - # - # _fix_me_ - # factor out the anchor()ing code into a reusable form. (oe; 4-apr-20) - # - n = None; - i = 0; - - def skip(): - nonlocal i; - while i < n and graph.input[i] in {" ", "\t"}: - i += 1; - - def scan(candidates): - for candidate in candidates: - if graph.input.startswith(candidate, i): - return len(candidate); - - def anchor(form): - nonlocal i; - skip(); - m = None; - if graph.input.startswith(form, i): - m = len(form); - else: - for old, new in {("‘", "`"), ("’", "'")}: - form = form.replace(old, new); - if graph.input.startswith(form, i): - m = len(form); - break; - if not m: - m = scan({"“", "\"", "``"}) or scan({"‘", "`"}) \ - or scan({"”", "\"", "''"}) or scan({"’", "'"}) \ - or scan({"—", "—", "---", "--"}) \ - or scan({"…", "...", ". . ."}); - if m: - anchor = {"from": i, "to": i + m}; - i += m; - skip(); - return anchor; - else: - raise Exception("{}: failed to anchor |{}| in |{}| ({})" - "".format(graph.id, form, graph.input, i)); - - tree = ET.parse(fp).getroot(); - bundles = tree.find(ns + "bundles"); - for item in bundles.findall(ns + "LM"): - id = item.get("id"); - graph = Graph(id, flavor = 0, framework = "ptg"); - surface = list(); nodes = list(); edges = list(); - for zone in item.iter(ns + "zone"): - if zone.get("language") == "en": - sentence = zone.findtext(ns + "sentence"); - trees = zone.find(ns + "trees"); - if trees is not None: - atree = trees.find(ns + "a_tree"); - ttree = trees.find(ns + "t_tree"); - root = atree.find(ns + "children"); - top = ttree.find(ns + "children"); -# print(id, sentence, atree, ttree, root, top); - if root is None or top is None: - raise Exception("treex.read(): " - "missing ‘a_tree’ or ‘t_tree’ values while decoding tree #{}; exit." - "".format(id)); - walk(id, root, None, surface, None, ns); - walk(id, top, None, nodes, edges, ns); - # - # determine character-based anchors for all .surface. (analytical) tokens - # - anchoring = dict(); - if sentence is not None: - graph.add_input(sentence); - n = len(graph.input); - i = 0; - for node in sorted(surface, key = itemgetter(1)): - anchoring[node[0]] = anchor(node[2].findtext(ns + "form")); - - # - # now process tectogrammatical nodes in surface order (as indicated in the - # annotations): map to consecutive numerical identifiers; retrieve anchors - # from corresponding analytical nodes; and create actual (new) graph nodes. - # - mapping = {}; - to = 0; - for node in sorted(nodes, key = itemgetter(1)): - mapping[node[0]] = i = len(mapping); - properties = dict(); - - a = node[2].find(ns + "a"); - if a is not None: - anchors = list(); - for lex in a: - if len(lex) == 0: - anchors.append(anchoring[lex.text]); - else: - for lm in lex.findall(ns + "LM"): - anchors.append(anchoring[lm.text]); - anchors = sorted(anchors, key = itemgetter("to")); - to = anchors[-1]["to"]; - else: - # - # _fix_me_ - # discuss anchoring of generated nodes: currently, for uniformity, we - # anchor them to an empty string immediately after the final character - # of the preceding non-generated node. but this arguably introduces a - # vacuous piece of information, unless one were to argue that it rather - # is an encoding of the node status for generated nodes? (oe; 4-apr-20) - # - anchors = [{"from": to, "to": to}]; - - # - # the node label comes from the tectogrammatical lemma - # - lemma = node[2].findtext(ns + "t_lemma"); - - frame = node[2].findtext(ns + "val_frame.rf"); - # - # where present (mostly on verbs), extract the valency frame identifier - # _fix_me_ - # for compatibility with earlier PSD releases, strip prefix that seems to - # identify the valency dictionary. (oe; 4-apr-20) - # - if frame is not None: - if "#" in frame: - properties["frame"] = frame[frame.index("#") + 1:]; - else: - properties["frame"] = frame; - - # - # selectively expose grammatemes as node-local properties, but ignore - # (vanilla but very high-frequent) default values - # - grammatemes = node[2].find(ns + "gram"); - if grammatemes is not None: - for property, default in [("tense", {"nil"}), ("negation", {"neg0"})]: - match = grammatemes.findtext(ns + property); - if match is not None and match not in default: - properties[property] = match; - - graph.add_node(id = i, label = lemma, anchors = anchors, - properties = properties.keys(), - values = properties.values(), - top = node[0] == top.get("id")); - - # - # similarly, record all edges, now using mapped identifiers - # - for source, target, label in edges: - graph.add_edge(mapping[source], mapping[target], label); - - # - # in a second pass (so that all internal identifiers are mapped already), - # create edges reflecting coreference annotations. - # - for node in nodes: - coref = node[2].findtext(ns + "coref_gram.rf"); - if coref is not None: - graph.add_edge(mapping[node[0]], mapping[coref], "coref_gram"); - - yield graph, None; diff --git a/spaces/luxuedong/lxd/src/components/ui/textarea.tsx b/spaces/luxuedong/lxd/src/components/ui/textarea.tsx deleted file mode 100644 index e25af722c7a5dc1121a9ab58d6716952f9f76081..0000000000000000000000000000000000000000 --- a/spaces/luxuedong/lxd/src/components/ui/textarea.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import * as React from 'react' - -import { cn } from '@/lib/utils' - -export interface TextareaProps - extends React.TextareaHTMLAttributes {} - -const Textarea = React.forwardRef( - ({ className, ...props }, ref) => { - return ( -