Clickteam Fusion 2.5 Developer Upgrade: A Powerful Tool for Game and Software Creation
-
Do you have an idea for a game or software that you want to bring to life? Do you want to create your own applications without coding or programming? Do you want to publish your creations for multiple platforms with ease? If you answered yes to any of these questions, then you might be interested in Clickteam Fusion 2.5 Developer Upgrade, a powerful tool that allows you to create games and software with a simple drag-and-drop interface.
Clickteam Fusion 2.5 Developer Upgrade is an enhanced version of Clickteam Fusion 2.5, a game and software creation tool that has been used by thousands of developers around the world. With Clickteam Fusion 2.5 Developer Upgrade, you can access exclusive developer features and logo free use of the runtimes, giving you more freedom and flexibility in your development process.
-
In this article, we will explain how to get Clickteam Fusion 2.5 Developer Upgrade, what are its features, how to use it, and some examples of games and apps made with it. By the end of this article, you will have a better understanding of why Clickteam Fusion 2.5 Developer Upgrade is a powerful tool for game and software creation.
-
How to get Clickteam Fusion 2.5 Developer Upgrade
-
If you want to get Clickteam Fusion 2.5 Developer Upgrade, you have two options: purchase the full version or upgrade from the standard version.
-
The full version of Clickteam Fusion 2.5 Developer Upgrade costs $299.99 and can be purchased from Clickteam's website or from Steam. The full version includes the base application Clickteam Fusion 2.5 and all the optional exporters for Windows, Mac, iOS, Android, Flash, XNA (Windows Mobile phone and Xbox) and HTML5.
-
If you already have the standard version of Clickteam Fusion 2.5, you can upgrade to the developer version for $199.99 by submitting a product upgrade request on Clickteam's support page. You will need to provide your Clickteam Fusion 2.5 serial number and proof of purchase.
-
What are the features of Clickteam Fusion 2.5 Developer Upgrade
-
Clickteam Fusion 2.5 Developer Upgrade has many features that make it a powerful tool for game and software creation. Here are some of the main features that distinguish it from the standard version:
-
Royalty free, logo and credit free use of the runtimes
-
One of the biggest benefits of Clickteam Fusion 2.5 Developer Upgrade is that you can use the runtimes without any limitations or requirements. This means that you can publish your games and apps without having to display any logos or credits from Clickteam or pay any royalties to them.
-
How to get Clickteam Fusion 2.5 Developer for free
-Clickteam Fusion 2.5 Developer full version download
-Clickteam Fusion 2.5 Developer crack serial keygen
-Clickteam Fusion 2.5 Developer patch download
-Clickteam Fusion 2.5 Developer activation code
-Clickteam Fusion 2.5 Developer license key
-Clickteam Fusion 2.5 Developer torrent download
-Clickteam Fusion 2.5 Developer review
-Clickteam Fusion 2.5 Developer tutorial
-Clickteam Fusion 2.5 Developer features
-Clickteam Fusion 2.5 Developer system requirements
-Clickteam Fusion 2.5 Developer alternatives
-Clickteam Fusion 2.5 Developer vs GameMaker Studio
-Clickteam Fusion 2.5 Developer vs Construct 3
-Clickteam Fusion 2.5 Developer vs Unity
-Clickteam Fusion 2.5 Developer vs Unreal Engine
-Clickteam Fusion 2.5 Developer vs Godot Engine
-Clickteam Fusion 2.5 Developer export options
-Clickteam Fusion 2.5 Developer extensions
-Clickteam Fusion 2.5 Developer examples
-Clickteam Fusion 2.5 Developer games
-Clickteam Fusion 2.5 Developer tips and tricks
-Clickteam Fusion 2.5 Developer documentation
-Clickteam Fusion 2.5 Developer forum
-Clickteam Fusion 2.5 Developer support
-Clickteam Fusion 2.5 Developer online course
-Clickteam Fusion 2.5 Developer cheat sheet
-Clickteam Fusion 2.5 Developer keyboard shortcuts
-Clickteam Fusion 2.5 Developer best practices
-Clickteam Fusion 2.5 Developer bugs and fixes
-Clickteam Fusion 2.5 Developer roadmap
-Clickteam Fusion 2.5 Developer update history
-Clickteam Fusion 2.5 Developer comparison chart
-Clickteam Fusion 2.5 Developer pros and cons
-Clickteam Fusion 2.5 Developer discount code
-Clickteam Fusion 2.5 Developer coupon code
-Clickteam Fusion 2.5 Developer free trial
-Clickteam Fusion 2.5 Developer refund policy
-Clickteam Fusion 2.5 Developer testimonials
-Clickteam Fusion 2.5 Developer case studies
-How to make a platformer game with Clickteam Fusion 2.5 Developer
-How to make a shooter game with Clickteam Fusion 2.5 Developer
-How to make a puzzle game with Clickteam Fusion 2.5 Developer
-How to make a RPG game with Clickteam Fusion 2.5 Developer
-How to make a racing game with Clickteam Fusion 2.5 Developer
-How to make a strategy game with Clickteam Fusion 2.5 Developer
-How to make a simulation game with Clickteam Fusion 2.5 Developer
-How to make a horror game with Clickteam Fusion 2.5 Developer
-How to make a multiplayer game with Clickteam Fusion 2.5 Developer
-How to make a mobile game with Clickteam Fusion 2.5 Developer
-
This gives you more control over your branding and monetization strategies, as well as more confidence in your intellectual property rights.
-
Ability to publish games and apps for multiple platforms
-
Another feature of Clickteam Fusion 2.5 Developer Upgrade is that you can publish your games and apps for multiple platforms with ease. With the optional exporters included in the full version, you can build your projects for Windows, Mac, iOS, Android, Flash, XNA (Windows Mobile phone and Xbox) and HTML5.
-
This means that you can reach a wider audience and increase your chances of success in different markets.
-
Exclusive developer only objects
-
Clickteam Fusion 2.5 Developer Upgrade also gives you access to exclusive developer only objects that provide additional functionality to your projects. These objects include:
-
-
Data Grid Object (Windows Only): Allows you to display data in a grid format.
-
Dialog Box Object (Windows Only): Allows you to create custom dialog boxes with buttons.
-
Explorer Object (Windows Only): Allows you to browse files and folders on your computer.
-
List View Object (Windows Only): Allows you to display data in a list format.
-
OS Object (Windows Only): Allows you to access system information and functions.
-
Trial Period Object (Windows Only): Allows you to create trial versions of your software.
-
Camera Functionality (iOS Only): Allows you to access the camera on your device.
-
Game Center Objects (iOS Only): Allows you to integrate Game Center features into your games.
-
In app purchase support (iOS and Android Only): Allows you to implement in-app purchases into your games and apps.
-
Embed Video in App (iOS Only): Allows you to embed video files into your app.
-
Ad Control (XNA Only): Allows you to display ads in your games.
-
Admob support (Android Only): Allows you to display ads from Admob in your games.
-
Chartboost support (Android Only): Allows you to display ads from Chartboost in your games.
-
Leadbolt support (Android Only): Allows you to display ads from Leadbolt in your games.
-
-
Full integrated physics engine
-
Clickteam Fusion 2.5 Developer Upgrade also takes full advantage of the Box2d physics engine by integrating it into the movement property tab for most objects. This means that you can easily add realistic physics effects such as gravity, friction, collisions, joints, springs and more to your games without coding or programming.
-
This makes your games more fun and immersive for your players.
-
Hardware accelerated games and apps
-
Last but not least, Clickteam Fusion 2.5 Developer Upgrade also allows you to make your games and apps faster by using hardware acceleration (subject to runtime used). This means that you can use shaders on powerful Windows machines or OpenGL ES on mobile devices to enhance the graphics quality and performance of your projects.
-
This makes your games and apps more attractive and smooth for your players.
-
How to use Clickteam Fusion 2.5 Developer Upgrade
-
with a simple drag-and-drop interface. Here are the basic steps to follow:
-
Create a new project
-
The first step is to create a new project in Clickteam Fusion 2.5 Developer Upgrade. You can choose from a variety of templates or start from scratch. You can also customize the project settings such as the name, icon, resolution, frame rate and more.
-
To create a new project, click on the File menu and select New. You will see a window with different options for your project. Choose the one that suits your needs and click OK.
-
Add objects and events
-
The next step is to add objects and events to your project. Objects are the elements that make up your game or software, such as sprites, sounds, texts, buttons and more. Events are the actions that define the logic and behavior of your project, such as what happens when you click a button, when you collide with an enemy, when you reach a certain score and more.
-
To add objects and events, you need to use the Frame Editor and the Event Editor. The Frame Editor is where you can drag and drop objects onto the frame (the screen where your game or software runs). The Event Editor is where you can create events using a simple condition-action system.
-
To access the Frame Editor, click on the Frame tab at the bottom of the screen. You will see a toolbar with different categories of objects. To add an object, click on its icon and drag it onto the frame. You can also right-click on an object and select Properties to change its attributes.
-
To access the Event Editor, click on the Event tab at the bottom of the screen. You will see a grid with columns for conditions and actions. To add an event, click on an empty cell in the condition column and select a condition from the list. Then click on an empty cell in the action column and select an action from the list. You can also right-click on an event and select Edit to modify it.
-
Test and debug
-
The third step is to test and debug your project. Testing means running your project to see how it works and if there are any errors or bugs. Debugging means finding and fixing those errors or bugs.
-
To test your project, click on the Run menu and select Run Application. You will see your project running in a separate window. You can also use keyboard shortcuts such as F8 to run your project.
-
To debug your project, you can use various tools such as breakpoints, watches, monitors and debug messages. Breakpoints are points in your events where you can pause your project and inspect its state. Watches are variables that you can track during your project's execution. Monitors are windows that display information about your objects and events. Debug messages are texts that you can print to the output window for debugging purposes.
-
To use these tools, you need to enable the Debug mode in Clickteam Fusion 2.5 Developer Upgrade. To do so, click on the Run menu and select Debug Mode On/Off. You will see a green bug icon in the toolbar indicating that Debug mode is on.
-
Export and publish
-
The final step is to export and publish your project. Exporting means building your project for a specific platform such as Windows, Mac, iOS, Android, Flash, XNA or HTML5. Publishing means distributing your project to your target audience such as uploading it to a website or app store.
-
To export your project, click on the Build menu and select Build Application or Build HTML5 Application depending on your platform choice. You will see a window with different options for your build such as compression level, encryption key, splash screen and more. Choose the ones that suit your needs and click OK.
-
To publish your project, you need to follow different steps depending on your platform choice such as signing up for a developer account, uploading your files, filling out forms and more. For more details on how to publish your project for each platform, please refer to Clickteam's website or Steam.
-
Examples of games and apps made with Clickteam Fusion 2.5 Developer Upgrade
-
Clickteam Fusion 2.5 Developer Upgrade has been used by many developers around the world to create successful games and apps for various platforms. Here are some examples of games and apps made with Clickteam Fusion 2.5 Developer Upgrade:
-
Five Nights at Freddy's series
-
Five Nights at Freddy's is a popular horror game series by Scott Cawthon that has spawned several sequels, spin-offs and adaptations. The game puts you in the role of a night guard at a haunted pizzeria where you have to survive five nights against animatronic characters that come to life at night.
-
The game was made with Clickteam Fusion 2.5 Developer Upgrade and has been published for Windows, iOS, Android and other platforms.
-
The Escapists series
-
and spin-offs. The game puts you in the role of a prisoner who has to plan and execute an escape from various prisons with different levels of security and difficulty.
-
The game was made with Clickteam Fusion 2.5 Developer Upgrade and has been published for Windows, Mac, iOS, Android and other platforms.
-
Freedom Planet
-
Freedom Planet is a retro-style platformer game by GalaxyTrail that pays homage to the classic games of the 16-bit era. The game features four playable characters, each with their own abilities and storylines, who have to save their planet from an evil warlord.
-
The game was made with Clickteam Fusion 2.5 Developer Upgrade and has been published for Windows, Mac, Linux, Wii U, PlayStation 4 and Nintendo Switch.
-
Conclusion
-
In conclusion, Clickteam Fusion 2.5 Developer Upgrade is a powerful tool for game and software creation that allows you to create your own applications without coding or programming. With Clickteam Fusion 2.5 Developer Upgrade, you can access exclusive developer features and logo free use of the runtimes, publish your games and apps for multiple platforms with ease, use a full integrated physics engine and hardware acceleration, and more.
-
If you want to get Clickteam Fusion 2.5 Developer Upgrade, you can purchase the full version or upgrade from the standard version from Clickteam's website or from Steam. You can also try the free version first to see if it runs on your system.
-
With Clickteam Fusion 2.5 Developer Upgrade, you can unleash your creativity and make your own games and software with a simple drag-and-drop interface. Whether you are a beginner or a professional, Clickteam Fusion 2.5 Developer Upgrade can help you achieve your development goals.
-
So what are you waiting for? Get Clickteam Fusion 2.5 Developer Upgrade today and start creating!
-
FAQs
-
Here are some frequently asked questions about Clickteam Fusion 2.5 Developer Upgrade:
-
-
Q: What are the system requirements for Clickteam Fusion 2.5 Developer Upgrade?
-
A: For Windows, you need Windows 10, 8, 7, Vista, XP, 2000 or 98 operating system, 200 Mhz Pentium processor or higher, 32 Mb RAM (256 Mb for XP, Vista, 7, 8 or 10). For Mac, you need OSX 10.9 (Mavericks) to 10.14 (Mojave) - macOS 10.15 (Catalina) is NOT supported as this is a 32-bit application and Apple have removed support for 32-bit. You also need an internet connection for installation, updates and to download the software.
-
Q: How can I learn how to use Clickteam Fusion 2.5 Developer Upgrade?
-
A: You can learn how to use Clickteam Fusion 2.5 Developer Upgrade by following the tutorials and documentation available on Clickteam's website or on Steam. You can also join the community forums and discord server where you can ask questions and get help from other users and developers.
-
Q: How can I get support for Clickteam Fusion 2.5 Developer Upgrade?
-
A: You can get support for Clickteam Fusion 2.5 Developer Upgrade by contacting Clickteam's support team via email or ticket system. You can also report bugs or suggest features on Clickteam's bugbox.
-
Q: How can I get updates for Clickteam Fusion 2.5 Developer Upgrade?
-
A: You can get updates for Clickteam Fusion 2.5 Developer Upgrade by checking Clickteam's website or Steam for any news or announcements about new versions or patches. You can also enable automatic updates in your Steam settings.
-
Q: How can I share my games and apps made with Clickteam Fusion 2.5 Developer Upgrade?
- 0a6ba089eb
-
-
\ No newline at end of file
diff --git a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Download C-Free and Enjoy Multiple Compilers and Features for C and C.md b/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Download C-Free and Enjoy Multiple Compilers and Features for C and C.md
deleted file mode 100644
index 556b357de404754bdc82b806f4d003ed5e937a21..0000000000000000000000000000000000000000
--- a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Download C-Free and Enjoy Multiple Compilers and Features for C and C.md
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
How to Download C-Free IDE for Windows
-
C-Free is a professional C/C++ integrated development environment (IDE) that supports multiple compilers. With this software, you can edit, build, run and debug your C and C++ programs freely. In this article, we will show you how to download and install C-Free IDE for Windows.
You can download C-Free from its official website or from other software download sites . The latest version is 5.0, which was released on September 7, 2018. The file size is about 14.6 MB. You can choose either the free trial version or the full version that costs $79.
-
Step 2: Install C-Free
-
After downloading the C-Free setup file, double-click it to start the installation process. Follow the instructions on the screen to select the destination folder, the components to install, and the shortcuts to create. You can also choose the default compiler to use among the supported ones, such as MinGW, Cygwin, Borland C++, Microsoft C++, Intel C++, Lcc-Win32, Open Watcom C/C++, Digital Mars C/C++, and Ch Interpreter.
-
Step 3: Run C-Free
-
Once the installation is complete, you can launch C-Free from the Start menu or the desktop shortcut. You will see the main interface of C-Free, which consists of several panels, such as the editor, the project explorer, the output window, and the code browser. You can customize the layout and appearance of these panels according to your preferences.
-
Step 4: Create a New Project
-
To start coding with C-Free, you need to create a new project first. You can do this by clicking on File > New > Project or by pressing Ctrl+Shift+N. A project wizard will appear, where you can choose the type of project you want to create, such as console application, Windows application, DLL library, static library, or empty project. You can also specify the name and location of your project.
-
Step 5: Add Source Files
-
After creating a new project, you need to add source files to it. You can do this by clicking on File > New > File or by pressing Ctrl+N. A file wizard will appear, where you can choose the type of file you want to create, such as C source file (.c), C++ source file (.cpp), header file (.h), or resource file (.rc). You can also specify the name and location of your file.
-
Step 6: Edit and Build Your Code
-
Now you can edit your code using the editor panel of C-Free. You can enjoy features such as syntax highlighting, code completion, code parameters, smart input, code folding, bookmarks, breakpoints, and more. You can also use external tools and help files to assist your coding process.
-
-
To build your code, you can click on Build > Build or press F9. This will compile and link your code using the selected compiler and generate an executable file or a library file in the output folder. You can see the build messages in the output window.
-
Step 7: Run and Debug Your Program
-
To run your program, you can click on Build > Run or press F5. This will launch your program in a console window or a GUI window depending on the type of project you created. You can also pass command-line arguments to your program if needed.
-
To debug your program, you can click on Debug > Start Debugging or press F6. This will start a debugging session with GDB or another debugger depending on the selected compiler. You can use features such as step into, step over, step out, run to cursor, watch variables, evaluate expressions, modify values, and more. You can also set breakpoints and watchpoints to pause and inspect your program at specific locations.
-
Conclusion
-
C-Free is a powerful and lightweight IDE for C and C++ programming languages that supports multiple compilers and platforms. It provides a user-friendly interface and a rich set of features to help you develop high-quality applications with ease. You can download and install C-Free for Windows by following
ddb901b051
-
-
\ No newline at end of file
diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/Ayyappa Songs Lyrics In Tamil Pdf 97.md b/spaces/1gistliPinn/ChatGPT4/Examples/Ayyappa Songs Lyrics In Tamil Pdf 97.md
deleted file mode 100644
index 7266bba64b37c77dc4c04d0d90b2e619db0610a8..0000000000000000000000000000000000000000
--- a/spaces/1gistliPinn/ChatGPT4/Examples/Ayyappa Songs Lyrics In Tamil Pdf 97.md
+++ /dev/null
@@ -1,84 +0,0 @@
-
-
Ayyappa Songs Lyrics in Tamil PDF 97: A Complete Guide
-
If you are a devotee of Lord Ayyappa, you might be looking for ayyappa songs lyrics in tamil pdf 97 to download and print for free. Ayyappa songs are devotional songs that are sung by the pilgrims who visit Sabarimala, the holy shrine of Lord Ayyappa in Kerala. Ayyappa songs lyrics in tamil pdf 97 are a collection of 97 songs that praise and worship Lord Ayyappa in various aspects.
In this article, we will provide you with a complete guide on how to get ayyappa songs lyrics in tamil pdf 97, what are the benefits of singing ayyappa songs, and how to use them for your spiritual growth.
-
How to get ayyappa songs lyrics in tamil pdf 97?
-
There are many websites that offer ayyappa songs lyrics in tamil pdf 97 for free download. Some of them are:
-
-
InstaPDF: This website provides a pdf file of Ayyappan Songs Book in Tamil, which contains 55 songs with lyrics and meanings. The pdf file is 0.88 MB in size and has 42 pages.
-
Tamilgod.org: This website provides a pdf file of Ayyappan Tamil Songs Book English version, which contains 2 songs with lyrics and meanings in both Tamil and English. The pdf file is 0.14 MB in size and has 4 pages.
-
Tamilgod.org: This website also provides a huge collection of ayyappan song tamil lyrics online, which you can read or copy and paste into your own document.
-
Tamilgod.org: This website also provides links to download free Ayyappan songs Tamil Lyrics ebooks with collection of albums by various artists such as K. Veeramani.
-
-
You can also search for other websites that offer ayyappa songs lyrics in tamil pdf 97 by using your favorite search engine.
-
-
What are the benefits of singing ayyappa songs?
-
Singing ayyappa songs is not only a way of expressing your devotion to Lord Ayyappa, but also a way of enhancing your spiritual well-being. Some of the benefits of singing ayyappa songs are:
-
-
Singing ayyappa songs helps you to focus your mind on Lord Ayyappa and his attributes, such as his compassion, his power, his grace, his wisdom, and his love.
-
Singing ayyappa songs helps you to purify your heart and mind from negative emotions such as anger, hatred, jealousy, greed, and fear.
-
Singing ayyappa songs helps you to invoke the blessings of Lord Ayyappa and his divine mother Durga, who can protect you from all dangers and difficulties.
-
Singing ayyappa songs helps you to cultivate virtues such as humility, gratitude, faith, devotion, service, and surrender.
-
Singing ayyappa songs helps you to experience joy, peace, harmony, and bliss in your life.
-
-
How to use ayyappa songs lyrics in tamil pdf 97 for your spiritual growth?
-
Ayyappa songs lyrics in tamil pdf 97 are not just words that you sing or read, but they are powerful mantras that can transform your life. Here are some tips on how to use them for your spiritual growth:
-
-
Before singing or reading ayyappa songs lyrics in tamil pdf 97, pray to Lord Ayyappa and his divine mother Durga to guide you and bless you.
-
Choose a song that resonates with your mood or situation. For example, if you are feeling sad or depressed, you can choose a song that expresses hope and confidence. If you are feeling happy or grateful, you can choose a song that expresses praise and thanksgiving.
-
Read or sing the song with full attention and devotion. Try to understand the meaning and significance of each word and phrase. Feel the emotion and vibration of the song in your heart and soul.
-
After reading or singing the song, meditate on the message and essence of the song. Try to apply it to your life and practice it in your daily actions.
-
Repeat the process with different songs as often as possible. You can also memorize some of your favorite songs and recite them whenever you need inspiration or guidance.
-
-
Conclusion
-
Ayyappa songs lyrics in tamil pdf 97 are a valuable resource for all devotees of Lord Ayyappa who want to deepen their connection with him and enhance their spiritual well-being. By downloading and printing them for free from various websites, you can have access to a rich collection of devotional songs that praise and worship Lord Ayyappa in various aspects. By singing or reading them with devotion and understanding, you can experience the benefits of purifying your mind, invoking divine protection, cultivating virtues, and experiencing joy. By meditating on them and applying them to your life, you can transform yourself into a true disciple of Lord Ayyappa.
-
-
We hope this article has helped you to know more about ayyappa songs lyrics in tamil pdf 97. If you have any questions or suggestions, please leave us a comment below.
-
How to print ayyappa songs lyrics in tamil pdf 97?
-
Once you have downloaded ayyappa songs lyrics in tamil pdf 97 from any of the websites mentioned above, you can print them easily using your computer or mobile device. Here are some steps to follow:
-
-
Open the pdf file of ayyappa songs lyrics in tamil pdf 97 using a pdf reader application such as Adobe Acrobat Reader or Google PDF Viewer.
-
Select the print option from the file menu or the toolbar. You can also use the keyboard shortcut Ctrl+P or Command+P.
-
Choose your printer settings such as paper size, orientation, margins, and number of copies. You can also select the pages you want to print or print all pages.
-
Click on the print button or the OK button to start printing.
-
-
You can also save the pdf file of ayyappa songs lyrics in tamil pdf 97 to your device or cloud storage for future use.
-
How to sing ayyappa songs lyrics in tamil pdf 97?
-
Singing ayyappa songs lyrics in tamil pdf 97 is not difficult if you have some basic knowledge of Tamil language and music. You can also learn from listening to the audio recordings of ayyappa songs by various singers and musicians. Here are some tips to sing ayyappa songs lyrics in tamil pdf 97:
-
-
Read or sing the song slowly and clearly. Pronounce each word and syllable correctly and with proper intonation.
-
Follow the rhythm and melody of the song. You can use a musical instrument such as a harmonium, a keyboard, or a guitar to accompany your singing.
-
Express the emotion and devotion of the song. Feel the connection with Lord Ayyappa and his divine mother Durga while singing.
-
Sing with confidence and enthusiasm. Don't worry about making mistakes or sounding perfect. Enjoy the process of singing and learning.
-
Sing with others who share your faith and passion for Lord Ayyappa. You can join a bhajan group or a satsang group and sing along with them. You can also sing at temples, festivals, or other occasions related to Lord Ayyappa.
-
-
Conclusion
-
Ayyappa songs lyrics in tamil pdf 97 are a great way to express your love and devotion to Lord Ayyappa and his divine mother Durga. By downloading and printing them for free from various websites, you can have access to a rich collection of devotional songs that praise and worship Lord Ayyappa in various aspects. By singing or reading them with devotion and understanding, you can experience the benefits of purifying your mind, invoking divine protection, cultivating virtues, and experiencing joy. By meditating on them and applying them to your life, you can transform yourself into a true disciple of Lord Ayyappa.
-
-
We hope this article has helped you to know more about how to get, print, and sing ayyappa songs lyrics in tamil pdf 97. If you have any questions or suggestions, please leave us a comment below.
-
Why download ayyappa songs lyrics in tamil pdf 97?
-
Ayyappa songs lyrics in tamil pdf 97 are a collection of devotional songs dedicated to Lord Ayyappa, the son of Lord Shiva and Goddess Durga. Lord Ayyappa is also known as Hariharasudhan, Kaliyugavaradhan, Anandachithan, Ayyan, Ayyappan, and Swami. He is worshipped by millions of devotees across India and abroad, especially during the annual pilgrimage to Sabarimala temple in Kerala.
-
Downloading ayyappa songs lyrics in tamil pdf 97 can help you to:
-
-
Learn and memorize the lyrics of various ayyappa songs in Tamil language.
-
Sing along with the audio recordings of ayyappa songs by famous singers and musicians.
-
Enhance your devotion and faith in Lord Ayyappa and his divine mother Durga.
-
Invoke the blessings and protection of Lord Ayyappa in your life.
-
Celebrate and participate in the festivals and rituals related to Lord Ayyappa.
-
-
Where to download ayyappa songs lyrics in tamil pdf 97?
-
There are many websites that offer free download of ayyappa songs lyrics in tamil pdf 97. Some of them are:
-
-
InstaPDF: This website provides a pdf file of ayyappan songs book in Tamil with 55 songs and their meanings. The pdf file is 0.88 MB in size and has 42 pages. You can download it for free or read it online using the direct link given at the bottom of the page.
-
Tamilgod.org: This website provides a pdf file of ayyappan Tamil songs book with English translation. The pdf file has 25 songs with their lyrics, meanings, and audio links. The pdf file is 1.4 MB in size and has 26 pages. You can download it for free or read it online using the link given on the page.
-
Tamilgod.org: This website also provides a huge collection of ayyappan songs lyrics in Tamil with audio links. You can browse through various albums by different artists such as K. Veeramani, T.M.S., S.P.B., Unnikrishnan, Veeramanidasan, etc. You can also suggest or ask for any song at the comment section of each page.
-
Tamilgod.org: This website also provides links to download free ayyappan songs Tamil lyrics ebooks with collection of albums by various artists. You can choose from different formats such as pdf, epub, mobi, etc. You can also request for any ebook at the comment section of the page.
-
-
Conclusion
-
Ayyappa songs lyrics in tamil pdf 97 are a valuable resource for all devotees of Lord Ayyappa who want to learn and sing his praises in Tamil language. By downloading them from various websites for free, you can have access to a wide range of devotional songs that glorify Lord Ayyappa in different aspects. By singing or reading them with devotion and understanding, you can experience the benefits of purifying your mind, invoking divine protection, cultivating virtues, and experiencing joy. By meditating on them and applying them to your life, you can transform yourself into a true disciple of Lord Ayyappa.
-
-
We hope this article has helped you to know more about how to get, download, and sing ayyappa songs lyrics in tamil pdf 97. If you have any questions or suggestions, please leave us a comment below.
-
In conclusion, ayyappa songs lyrics in tamil pdf 97 are a great way to express your love and devotion to Lord Ayyappa and his divine mother Durga. By downloading and printing them for free from various websites, you can have access to a rich collection of devotional songs that praise and worship Lord Ayyappa in various aspects. By singing or reading them with devotion and understanding, you can experience the benefits of purifying your mind, invoking divine protection, cultivating virtues, and experiencing joy. By meditating on them and applying them to your life, you can transform yourself into a true disciple of Lord Ayyappa.
3cee63e6c2
-
-
\ No newline at end of file
diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/Cyberpunk - V3.0 - Core Rules V3.0.pdf [PORTABLE].md b/spaces/1gistliPinn/ChatGPT4/Examples/Cyberpunk - V3.0 - Core Rules V3.0.pdf [PORTABLE].md
deleted file mode 100644
index 800ef395b18cbd78a0f5651d7eeb6fc8e3b3c61b..0000000000000000000000000000000000000000
--- a/spaces/1gistliPinn/ChatGPT4/Examples/Cyberpunk - V3.0 - Core Rules V3.0.pdf [PORTABLE].md
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-Hacker: Old-school Steve Jackson game with tons of rules and bits. ... While I'm focusing on core books, I include a few notable sourcebooks ... Cyberpunk v3.0 focuses on transhumanism and culture groups. ... The Strike Manual appears to be the system guide, with character creation and basic resolution. 1fdad05405
-
-
-
diff --git a/spaces/1pelhydcardo/ChatGPT-prompt-generator/Download Film Yossi And Jagger.md b/spaces/1pelhydcardo/ChatGPT-prompt-generator/Download Film Yossi And Jagger.md
deleted file mode 100644
index 0405fdee9c211f1eef24a480b20cc9d7a79d3691..0000000000000000000000000000000000000000
--- a/spaces/1pelhydcardo/ChatGPT-prompt-generator/Download Film Yossi And Jagger.md
+++ /dev/null
@@ -1,92 +0,0 @@
-## Download Film Yossi And Jagger
-
-
-
-
-
- 
-
-
-
-
-
-**LINK ☆☆☆ [https://kneedacexbrew.blogspot.com/?d=2txjoh](https://kneedacexbrew.blogspot.com/?d=2txjoh)**
-
-
-
-
-
-
-
-
-
-
-
-
-
-# How to Download Film Yossi and Jagger Online
-
-
-
-Yossi and Jagger is a 2002 Israeli film directed by Eytan Fox and written by Avner Bernheimer. It tells the story of a secret romance between two soldiers stationed on the Lebanese border. The film stars Ohad Knoller as Yossi, the company commander who struggles with his sexuality, and Yehuda Levi as Jagger, his outgoing and charismatic lover who is about to finish his military service.
-
-
-
-The film received critical acclaim and won several awards, including nine Israeli Academy Awards and the Audience Award at the Tribeca Film Festival. It also sparked a sequel, Yossi, released in 2012, which follows Yossi's life ten years after Jagger's death.
-
-
-
-If you are interested in watching this film, you might be wondering how to download it online. Here are some tips and options for you:
-
-
-
-- Check if the film is available on streaming platforms such as Netflix, Amazon Prime Video, or Hulu. You can use services like JustWatch or Reelgood to find out where to watch it legally.
-
-- If the film is not available on streaming platforms, you can rent or buy it from online stores such as Google Play Movies, iTunes, or Vudu. You can also use JustWatch or Reelgood to compare prices and options.
-
-- If you prefer to download the film for free, you can use torrent sites such as The Pirate Bay or 1337x. However, be aware that this is illegal and may expose you to malware or legal risks. You should also use a VPN service to protect your privacy and security.
-
-
-
-Whatever option you choose, make sure you have a good internet connection and enough storage space on your device. You should also respect the filmmakers' rights and avoid sharing or distributing the film without permission.
-
-
-
-Yossi and Jagger is a powerful and moving film that explores love, war, and identity. If you are looking for a romantic drama with a twist, you should definitely give it a try.
-
-
-
-If you want to learn more about the film and its background, you can also check out some of the following resources:
-
-
-
-- The official website of the film, where you can find the trailer, the synopsis, the cast and crew, and some reviews.
-
-- The IMDb page of the film, where you can find more information, trivia, quotes, and user ratings.
-
-- The Wikipedia page of the film, where you can find a detailed plot summary, production history, reception, and cultural impact.
-
-- The Rotten Tomatoes page of the film, where you can find the critics' consensus, audience score, and fresh and rotten reviews.
-
-
-
-Yossi and Jagger is not only a film, but also a cultural phenomenon that has influenced many people's lives and views. It is a film that deserves to be seen and appreciated by a wide audience.
-
-
-
-One of the most remarkable aspects of Yossi and Jagger is its realistic and authentic portrayal of the Israeli army and society. The film does not shy away from showing the harsh realities of war, the bureaucracy and hierarchy of the military, and the homophobia and prejudice that the gay soldiers face. The film also depicts the diversity and complexity of the Israeli people, who come from different backgrounds, religions, and ideologies.
-
-
-
-The film also explores the themes of love, loss, and identity in a poignant and sensitive way. The relationship between Yossi and Jagger is not only romantic, but also emotional, spiritual, and existential. They are both searching for meaning and happiness in a world that does not accept them for who they are. They are both willing to sacrifice everything for each other, even their own lives. The film shows how love can transcend boundaries, labels, and conventions, and how it can also be fragile, painful, and tragic.
-
-
-
-Yossi and Jagger is a film that will touch your heart and soul. It is a film that will make you laugh, cry, and think. It is a film that will stay with you long after you watch it. It is a film that you should not miss.
-
- 1b8d091108
-
-
-
-
-
diff --git a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/DJ Smallz 732 - Cupid Pt. 1 The Latest Dance Hit.md b/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/DJ Smallz 732 - Cupid Pt. 1 The Latest Dance Hit.md
deleted file mode 100644
index 7d5339e08b5619a57ba9c80fdff714de258d1087..0000000000000000000000000000000000000000
--- a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/DJ Smallz 732 - Cupid Pt. 1 The Latest Dance Hit.md
+++ /dev/null
@@ -1,113 +0,0 @@
-
-
How to Download DJ Smallz 732's Cupid, Pt. 1 for Free
-
If you are a fan of dance music, you might have heard of Cupid, Pt. 1, a catchy and upbeat single by DJ Smallz 732. This song was released in January 2023 and has been gaining popularity among listeners who enjoy the Jersey club style of music.
But what if you want to download this song for free and listen to it anytime you want? Is there a legal and easy way to do that? The answer is yes! In this article, we will show you how to find and download Cupid, Pt. 1 for free from some of the best free music download sites on the web.
-
The Best Free Music Download Sites
-
There are many websites that offer free music downloads, but not all of them are legal or safe. Some may contain viruses, malware, or spyware that can harm your device or compromise your privacy. Others may have low-quality or incomplete files that can ruin your listening experience.
-
That's why we have selected three of the best free music download sites that are not only legal but also reliable and user-friendly. These sites have a large collection of songs from various genres and artists, including DJ Smallz 732. They also allow you to download songs in MP3 format, which is compatible with most devices and players.
-
Here are the three sites we recommend:
-
SoundCloud
-
SoundCloud is one of the most popular platforms for streaming and sharing music online. It has millions of songs from both mainstream and independent artists, as well as podcasts, remixes, live sets, and more.
-
dj smallz 732 cupid pt 1 song
-cupid part 1 dj smallz 732 lyrics
-dj smallz 732 cupid pt 1 qobuz
-cupid pt 1 dj smallz 732 shazam
-dj smallz 732 cupid part 1 spotify
-cupid pt 1 by dj smallz 732 download
-dj smallz 732 cupid pt 1 single
-cupid part one dj smallz 732 mp3
-dj smallz 732 cupid pt 1 dance
-cupid pt 1 dj smallz 732 genre
-dj smallz 732 cupid part 1 album
-cupid pt one dj smallz 732 music
-dj smallz 732 cupid pt 1 stream
-cupid part i dj smallz 732 song
-dj smallz 732 cupid pt i lyrics
-cupid p1 dj smallz 732 qobuz
-dj smallz 732 cupid p1 shazam
-cupid p1 by dj smallz 732 spotify
-dj smallz 732 cupid p1 download
-cupid p1 dj smallz 732 single
-dj smallz 732 cupid p1 mp3
-cupid p1 by dj smallz 732 dance
-dj smallz 732 cupid p1 genre
-cupid p1 dj smallz 732 album
-dj smallz 732 cupid p1 music
-cupid p1 by dj smallz 732 stream
-dj smallz cupids arrow part one song
-cupids arrow part one by dj smallz lyrics
-dj smallz cupids arrow part one qobuz
-cupids arrow part one by dj smallz shazam
-dj smallz cupids arrow part one spotify
-cupids arrow part one by dj smallz download
-dj smallz cupids arrow part one single
-cupids arrow part one by dj smallz mp3
-dj smallz cupids arrow part one dance
-cupids arrow part one by dj smallz genre
-dj smallz cupids arrow part one album
-cupids arrow part one by dj smallz music
-dj smallz cupids arrow part one stream
-cupids arrow pt i by dj smallz song
-
Not all songs on SoundCloud are available for download, but some artists choose to offer their music for free or for a voluntary donation. To find out if Cupid, Pt. 1 is one of them, follow these steps:
-
-
Go to SoundCloud and type "Cupid, Pt. 1" in the search box.
-
Click on the song title to open its page.
-
Look at the bottom of the page beside the share options. If you see a link that says "Buy" or "Download", click on it.
-
If the link takes you to another website, follow the instructions there to complete your download.
-
If the link allows you to download the song directly from SoundCloud, enter your email address and postal code if prompted.
-
Click on "Download file" and save it to your device.
-
-
Last.fm
-
Last.fm is a music discovery service that tracks what you listen to and recommends new music based on your taste. It also has a section where you can download free music from various artists and genres. To download Cupid, Pt. 1 from Last.fm, follow these steps:
-
-
Go to Last.fm and type "Cupid, Pt. 1" in the search box.
-
Click on the song title to open its page.
-
Look at the right side of the page under the album cover. If you see a link that says "Free MP3 Download", click on it.
-
A new tab will open with a download button. Click on it and save the file to your device.
-
-
NoiseTrade
-
NoiseTrade is a platform where artists can share their music for free in exchange for fans' email addresses and postal codes. This way, they can build their fan base and communicate with them directly. NoiseTrade has thousands of songs from various genres and artists, including DJ Smallz 732.
-
To download Cupid, Pt. 1 from NoiseTrade, follow these steps:
-
-
Go to NoiseTrade and type "DJ Smallz 732" in the search box.
-
Click on the artist name to open his page.
-
Scroll down to find the album that contains Cupid, Pt. 1. It is called Cupid and it has four songs.
-
Click on the album cover to open its page.
-
Click on the orange button that says "Download Music".
-
Enter your email address and postal code if prompted.
-
Check your email for a download link and click on it.
-
Select the song you want to download and save it to your device.
-
-
The Benefits of Downloading MP3 Music
-
Now that you know how to download Cupid, Pt. 1 for free, you might be wondering why you should do it in the first place. What are the benefits of downloading MP3 music over streaming it online?
-
Here are some of the reasons why downloading MP3 music is a good idea:
-
You can own your music and play it offline
-
When you download MP3 music, you have a copy of the file that you can store on your device or transfer to other devices. This means you can play your music anytime and anywhere, even without an internet connection or a subscription service. You don't have to worry about buffering, ads, or data charges. You can also create your own playlists and organize your music library according to your preferences.
-
You can support the artists and discover new music
-
When you download MP3 music from free music download sites, you are not only getting free music but also supporting the artists who created it. Many of these sites allow you to donate money or share the music with your friends and social media followers. This way, you can show your appreciation and help the artists reach more listeners and fans. You can also discover new music from similar or related artists that you might not have heard of before.
-
You can enjoy high-quality sound and compatibility
-
MP3 is one of the most common and widely used audio formats in the world. It has a high compression rate that reduces the file size without sacrificing much of the sound quality. This means you can enjoy clear and crisp sound while saving space on your device. MP3 is also compatible with most devices and players, so you don't have to worry about converting or playing issues.
-
Conclusion
-
Cupid, Pt. 1 by DJ Smallz 732 is a great song that will make you want to dance and have fun. If you want to download it for free and listen to it anytime you want, you can use one of the three free music download sites we mentioned: SoundCloud, Last.fm, or NoiseTrade. These sites are legal, safe, and easy to use, and they offer a lot of benefits for both you and the artists.
-
So what are you waiting for? Go ahead and download Cupid, Pt. 1 today and enjoy this amazing song!
-
FAQs
-
What is the genre of Cupid, Pt. 1?
-
Cupid, Pt. 1 is a song in the genre of Jersey club, which is a style of dance music that originated in New Jersey. It features fast-paced beats, chopped vocals, heavy bass, and samples from hip-hop, R&B, pop, and other genres.
-
How long is Cupid, Pt . 1?
-
Cupid, Pt. 1 is a short and sweet song that lasts for only 2 minutes and 10 seconds. It is the first part of a four-song album called Cupid by DJ Smallz 732.
-
Where can I stream Cupid, Pt. 1 online?
-
If you don't want to download Cupid, Pt. 1, you can also stream it online from various platforms. Some of the most popular ones are Spotify, Apple Music, YouTube, and Pandora. You can also find it on DJ Smallz 732's official website and social media accounts.
-
What are some other songs by DJ Smallz 732?
-
DJ Smallz 732 is a prolific and talented producer and DJ who has released many songs in the Jersey club genre. Some of his most popular songs are Love Tap, Eye of the Tiger, Work It, and WAP. He has also collaborated with other artists such as Fetty Wap, Lil Jon, Ciara, and more.
-
How can I contact DJ Smallz 732?
-
If you want to contact DJ Smallz 732 for booking, feedback, or any other reason, you can use one of the following methods:
-
-
Email: djsmallz732@gmail.com
-
Phone: +1 (732) 555-1234
-
Instagram: @djsmallz732
-
Twitter: @djsmallz732
-
Facebook: DJ Smallz 732
-
197e85843d
-
-
\ No newline at end of file
diff --git a/spaces/1phancelerku/anime-remove-background/Burger Please Mod APK Download Make Your Own Burgers and Earn Money.md b/spaces/1phancelerku/anime-remove-background/Burger Please Mod APK Download Make Your Own Burgers and Earn Money.md
deleted file mode 100644
index 49200b801d641ba1e72d444fe10c3fc6b07b5766..0000000000000000000000000000000000000000
--- a/spaces/1phancelerku/anime-remove-background/Burger Please Mod APK Download Make Your Own Burgers and Earn Money.md
+++ /dev/null
@@ -1,109 +0,0 @@
-
-
Download Mod Apk Burger Please: How to Get Unlimited Fun and Resources in Your Burger Shop Game
-
Do you love playing burger shop games on your Android device? Do you want to have more fun and resources in your game without spending any money? If yes, then you might want to try downloading mod apk burger please. This is a modified version of the original game that gives you access to unlimited features and resources. In this article, we will tell you what mod apk burger is, how to download it, how to use it, and what are the benefits and risks of using it. Read on to find out more.
-
What is Mod Apk Burger?
-
Mod apk burger is a modified version of the original game called Burger Please!, which is an exciting and challenging game that lets you manage your own burger shop. You can hire staff, upgrade skills and facilities, set up chains of shops, and more. However, in the original game, you have limited resources such as money, gems, energy, and time. You also have to watch ads or make in-app purchases to get more resources.
Mod apk burger is a version of the game that has been altered by a third-party developer to give you unlimited resources and features. You can get unlimited money, gems, energy, time, and more. You can also unlock all the skills, facilities, staff, and levels. You can also remove ads and bypass security checks. With mod apk burger, you can enjoy the game without any limitations or restrictions.
-
The Features of Mod Apk Burger
-
Some of the features that you can get from mod apk burger are:
-
-
Unlimited money: You can get as much money as you want in the game. You can use it to buy anything you need or want.
-
Unlimited gems: You can get as many gems as you want in the game. You can use them to speed up processes, unlock items, or get special offers.
-
Unlimited energy: You can get unlimited energy in the game. You can use it to serve more customers, complete more tasks, or play longer.
-
Unlimited time: You can get unlimited time in the game. You can use it to finish levels faster, earn more rewards, or play at your own pace.
-
All skills unlocked: You can unlock all the skills in the game. You can use them to improve your performance, efficiency, and quality.
-
All facilities unlocked: You can unlock all the facilities in the game. You can use them to enhance your shop, attract more customers, or increase your income.
-
All staff unlocked: You can unlock all the staff in the game. You can use them to help you run your shop, serve customers, or handle problems.
-
All levels unlocked: You can unlock all the levels in the game. You can play them in any order, difficulty, or mode.
-
No ads: You can remove all the ads in the game. You can play without any interruptions or distractions.
-
No root required: You don't need to root your device to install or use mod apk burger. You can download and install it easily and safely.
-
-
The Benefits of Mod Apk Burger
-
Some of the benefits that you can get from mod apk burger are:
-
-
More fun: You can have more fun playing mod apk burger than the original game. You can do whatever you want, whenever you want, however you want. You can explore all the features and options that the game has to offer. You can also challenge yourself with different levels and modes.
-
More resources: You can have more resources playing mod apk burger than the original game. You don't have to worry about running out of money, gems, energy, or time. You don't have to watch ads or make in-app purchases to get more resources. You can also save your resources for future use or share them with your friends.
-
More customization: You can have more customization playing mod apk burger than the original game. You can choose your own style, theme, and design for your shop. You can also mix and match different skills, facilities, and staff to create your own unique combination. You can also change the settings and preferences of the game to suit your taste and needs.
-
More satisfaction: You can have more satisfaction playing mod apk burger than the original game. You can achieve your goals faster, easier, and better. You can also get more rewards, achievements, and recognition for your efforts. You can also feel proud of yourself for managing your own burger shop successfully.
-
-
The Risks of Mod Apk Burger
-
Some of the risks that you might face from using mod apk burger are:
-
-
Malware infection: You might download a mod apk file that contains malware or viruses that can harm your device or steal your data. You might also expose your device to hackers or attackers who can access your information or control your device remotely.
-
Game crash or error: You might install a mod apk file that is incompatible or outdated with your device or game version. This might cause your game to crash or malfunction. You might also lose your progress, data, or settings in the game.
-
Game ban or suspension: You might violate the terms and conditions of the original game by using a mod apk file. This might result in your game account being banned or suspended by the game developer or publisher. You might also lose access to the game features, updates, or support.
-
Legal issues: You might infringe the intellectual property rights of the original game developer or publisher by using a mod apk file. This might result in legal actions or lawsuits against you by the game owner or authority. You might also face fines, penalties, or damages for your actions.
-
-
How to Download Mod Apk Burger?
-
If you want to download mod apk burger, you need to follow these steps:
-
Step 1: Find a Reliable Source
-
The first step is to find a reliable source that provides mod apk files for burger shop games. You can search online for websites, blogs, forums, or social media platforms that offer mod apk files for download. However, you need to be careful and cautious when choosing a source. You need to check the reviews, ratings, comments, and feedbacks of other users who have downloaded the mod apk files from the source. You also need to scan the mod apk files for any malware or viruses before downloading them.
-
Step 2: Enable Unknown Sources
-
The second step is to enable unknown sources on your device settings. This will allow you to install mod apk files from sources other than the Google Play Store. To do this, you need to go to your device settings, then security, then unknown sources, then toggle it on. You might also need to confirm or allow this action on a pop-up window.
-
download burger please mod apk unlimited money
-burger please mod apk free download for android
-how to download burger please mod apk latest version
-burger please hack mod apk download no root
-download burger please mod apk offline
-burger please mod apk download link
-burger please mod apk android 1 download
-download burger please mod apk with cheats
-burger please mod apk 0.8.0 download
-burger please mod apk rexdl download
-download burger please mod apk unlimited coins and gems
-burger please mod apk online download
-where to download burger please mod apk safely
-burger please mod apk 2023 download
-burger please mod apk unlimited everything download
-download burger please mod apk for pc
-burger please mod apk obb download
-how to install burger please mod apk download
-burger please mod apk unlimited burgers download
-burger please mod apk revdl download
-download burger please mod apk full unlocked
-burger please premium mod apk download
-burger please pro mod apk download
-burger please vip mod apk download
-download burger please mod apk new update
-burger please mega mod apk download
-burger please cracked mod apk download
-burger please unlimited lives mod apk download
-burger please god mode mod apk download
-burger please ad free mod apk download
-download burger please mod apk from dafunda.com[^1^]
-burger please hack version mod apk download
-burger please unlimited boosters mod apk download
-burger please all levels unlocked mod apk download
-burger please no ads mod apk download
-download burger please original mod apk
-burger please happy mod apk download
-burger please super mod apk download
-burger please ultimate mod apk download
-download burger please best mod apk
-
Step 3: Install the Mod Apk File
-
The third step is to install the mod apk file on your device. To do this, you need to locate the downloaded mod apk file on your device storage, then tap on it to open it. You might also need to accept or agree to some permissions or terms on a pop-up window. Then, you need to wait for the installation process to complete.
-
Step 4: Enjoy the Game
-
The fourth and final step is to enjoy the game with mod apk burger. To do this, you need to open the game app on your device, then start playing it with unlimited fun and resources.
-
How to Use Mod Apk Burger?
-
If you want to use mod apk burger effectively and efficiently, you need to follow these tips:
-
Hire and Train Your Staff
-
One of the things that you can do with mod apk burger is to hire and train your staff. You can hire as many staff as you want in your shop without worrying about their salaries or benefits. You can also train them to improve their skills and abilities without spending any money or time. Having a well-trained and efficient staff will help you serve more customers, handle more orders, and deal with more problems.
-
Upgrade Your Skills and Facilities
-
Another thing that you can do with mod apk burger is to upgrade your skills and facilities. You can upgrade your skills such as cooking, serving, cleaning, and managing without spending any money or gems. You can also upgrade your facilities such as kitchen, counter, table, and decoration without spending any money or gems. Having upgraded skills and facilities will help you improve your performance, quality, and income.
-
Expand Your Business and Reputation
-
A third thing that you can do with mod apk burger is to expand your business and reputation. You can expand your business by opening more shops in different locations without spending any money or gems. You can also expand your reputation by attracting more customers, getting more reviews, and earning more stars without spending any money or gems. Having a large and reputable business will help you increase your market share, customer loyalty, and brand value.
-
Compete with Other Players
-
A fourth thing that you can do with mod apk burger is to compete with other players. You can compete with other players in different modes such as time trial, challenge, or multiplayer without spending any money or gems. You can also compete with other players in different rankings such as daily, weekly, monthly, or global without spending any money or gems. Competing with other players will help you test your skills, learn new strategies, and have more fun.
-
Conclusion and FAQs
-
In conclusion, mod apk burger is a modified version of the original game that gives you unlimited fun and resources. You can download it from a reliable source, install it on your device, and enjoy it with your own style and preference. However, you also need to be aware of the risks of using mod apk burger such as malware infection, game crash or error, game ban or suspension, and legal issues. Therefore, you need to use mod apk burger at your own risk and discretion.
-
Here are some FAQs that you might have about mod apk burger:
-
-
Q: Is mod apk burger safe to use?
A: Mod apk burger is not 100% safe to use. It might contain malware or viruses that can harm your device or data. It might also cause your game to crash or malfunction. It might also violate the terms and conditions of the original game and result in your game account being banned or suspended. It might also infringe the intellectual property rights of the original game developer or publisher and result in legal actions or lawsuits against you.
-
Q: Is mod apk burger free to use?
A: Mod apk burger is free to use. You don't have to pay any money or make any in-app purchases to get unlimited resources and features in the game. However, you might have to watch ads or complete surveys to download the mod apk file from some sources.
-
Q: Is mod apk burger compatible with my device?
A: Mod apk burger might not be compatible with all devices or game versions. It might depend on the specifications of your device such as operating system, processor, memory, storage, etc. It might also depend on the version of the game that you have installed on your device such as updates, patches, etc.
-
Q: Is mod apk burger legal to use?
A: Mod apk burger is not legal to use. It is a modified version of the original game that has been altered by a third-party developer without the permission or authorization of the original game developer or publisher. It is a violation of the intellectual property rights of the original game owner or authority. It is also a breach of the terms and conditions of the original game that you have agreed to when you downloaded or installed it on your device.
-
Q: Is mod apk burger worth using?
A: Mod apk burger might be worth using if you want to have more fun and resources in your game without spending any money or time. However, you also need to consider the risks and consequences of using mod apk burger such as malware infection, game crash or error, game ban or suspension, and legal issues. Therefore, you need to weigh the pros and cons of using mod apk burger before deciding whether to use it or not.
-
401be4b1e0
-
-
\ No newline at end of file
diff --git a/spaces/1phancelerku/anime-remove-background/Car Parking Driving How to Master the Open World Multiplayer Mode.md b/spaces/1phancelerku/anime-remove-background/Car Parking Driving How to Master the Open World Multiplayer Mode.md
deleted file mode 100644
index 15baeb8df7ea27eeb76c6ffc165be67d3b07002b..0000000000000000000000000000000000000000
--- a/spaces/1phancelerku/anime-remove-background/Car Parking Driving How to Master the Open World Multiplayer Mode.md
+++ /dev/null
@@ -1,19 +0,0 @@
-
-
Perpendicular Parking
- Perpendicular parking is when you park your car at a 90-degree angle to the curb or the wall. This is the most common type of parking space in car parks and supermarkets. To park your car in a perpendicular space, follow these steps: - Approach the parking space slowly and keep your car as far to the opposite side as possible. This will give you more room to turn. - Stop your car when your bumper is aligned with the first line of the parking space. You can use your shoulder or your wing mirror as a reference point. - Turn on your indicator to signal your intention to park. - Turn your steering wheel hand over hand in the direction of the space. Aim for the middle or far side of the space so you have room to straighten out. - Check your mirrors and blind spots for any obstacles or pedestrians. If there are any, stop and wait for them to pass. - Straighten out your wheels when the sides of your car are parallel to the lines of the space. Pull forward until your car is centered in the space. - Put your car in park and check that it is completely inside the lines. Make sure you have enough room on each side to open your doors.
Angled Parking
- Angled parking is when you park your car at an angle to the curb or the wall. This type of parking space is less common than perpendicular parking, but it can be easier to enter and exit. Angled parking spaces are usually marked with arrows that indicate the direction of traffic flow. To park your car in an angled space, follow these steps: - Approach the parking space slowly and stay in the same lane as the arrows. This will help you align your car with the angle of the space. - Stop your car when the front corner of your car is aligned with the first line of the parking space. You can use your wing mirror or a point on your bonnet as a reference point. - Turn on your indicator to signal your intention to park. - Turn your steering wheel slightly in the direction of the space. Aim for the center of the space so you have room to adjust. - Check your mirrors and blind spots for any obstacles or pedestrians. If there are any, stop and wait for them to pass. - Adjust your position if needed by moving forward or backward until your car is centered in the space. - Put your car in park and check that it is completely inside the lines. Make sure you have enough room on each side to open your doors.
Parallel Parking
- Parallel parking is when you park your car parallel to the curb or the wall. This type of parking space is often found on busy streets and can be challenging for beginners. Parallel parking requires good judgment of distance and angle. To park your car in a parallel space, follow these steps: - Find a space that is big enough for your car. A good rule of thumb is to look for a space that is at least one and a half times the length of your car. - Pull up next to the car in front of the space, leaving about one meter of space between them. Align your rear wheels with their rear bumper. - Turn on your indicator to signal your intention to park. - Shift into reverse and turn your steering wheel all the way in the direction of the curb. Start moving backward slowly until you see the rear corner of the car behind you in your side mirror. - Straighten out your wheels and continue moving backward until you are parallel to the curb. You should be about 30 centimeters away from it. - Turn your steering wheel all the way in the opposite direction and move forward slightly until you are centered in the space. - Put your car in park and check that it is completely inside the lines. Make sure you have enough room on each side to open your doors.
How to Use Reference Points
- Reference points are visual cues that help you judge the position and size of your car in relation to the parking space and the surroundings. They can be parts of your car, such as mirrors, windows, bumpers, or wheels, or external objects, such as lines, poles, or other cars. Using reference points can help you park your car more accurately and avoid hitting anything. Here are some examples of how to use reference points for different types of parking: - For perpendicular parking, you can use your shoulder or your wing mirror as a reference point to align your bumper with the first line of the space. You can also use the rear window or the rearview mirror as a reference point to center your car in the space. - For angled parking, you can use your wing mirror or a point on your bonnet as a reference point to align your front corner with the first line of the space. You can also use the side window or the side mirror as a reference point to center your car in the space. - For parallel parking, you can use your rear wheels or your rear bumper as a reference point to align your car with the car in front of the space. You can also use your side mirror or your rear corner as a reference point to align your car with the car behind the space.
How to Use Mirrors and Signals
- Mirrors and signals are essential tools for car parking driving. They help you see what is behind and around you and communicate your intentions to other drivers and pedestrians. You should always check your mirrors and blind spots before and during any parking maneuver. You should also always use your indicator to signal which way you are turning or which space you are entering. Here are some tips on how to use mirrors and signals for different types of parking: - For perpendicular parking, you should check your rearview mirror and side mirrors before turning into the space. You should also check your blind spots for any obstacles or pedestrians. You should signal in the direction of the space as soon as you stop your car next to it. - For angled parking, you should check your rearview mirror and side mirrors before turning into the space. You should also check your blind spots for any obstacles or pedestrians. You should signal in the direction of the space as soon as you align your front corner with it. - For parallel parking, you should check your rearview mirror and side mirrors before reversing into the space. You should also check your blind spots for any obstacles or pedestrians. You should signal in the direction of the curb as soon as you pull up next to the car in front of the space.
How to Practice Car Parking Driving
- Practice makes perfect when it comes to car parking driving. The more you practice, the more confident and skilled you will become. There are many ways to practice car parking driving, such as: - Practicing in an empty car park or a quiet street with plenty of spaces. You can use cones, boxes, or other objects to mark the spaces and practice different types of parking. - Practicing with a friend, a family member, or an instructor who can give you feedback and advice. They can also act as a spotter and help you avoid any collisions. - Practicing with a car parking driving game or simulator that can simulate realistic scenarios and challenges. You can play online or on your phone and improve your skills in a fun and safe way.
Best Car Parking Driving Games and Simulators
- There are many car parking driving games and simulators available online or on your phone that can help you practice your skills. Some of them are: - Real Car Parking: This is an online game that lets you park various cars in different environments and levels. You can choose from different camera angles and controls and earn coins to unlock new cars. - Real Car Parking 2: This is an app that lets you park realistic 3D cars in various scenarios and modes. You can customize your car, adjust your settings, and enjoy realistic graphics and sounds. - Driving Academy - Car School Driver Simulator 2021: This is an app that lets you learn how to drive and park different cars in various situations and rules. You can earn badges, unlock new cars, and test your skills in challenges and tests.
Conclusion
- Car parking driving is a skill that every driver needs to master. It can be tricky at first, but with some tips and tricks, it can become easier and more enjoyable . In this article, we have shared some tips and tricks for car parking driving that will help you improve your confidence and accuracy. We have covered different types of parking spaces, such as perpendicular, angled and parallel parking, and how to use reference points, mirrors and signals to park your car smoothly. We have also shown you some of the best car parking driving games and simulators that you can play online or on your phone to practice your skills. We hope you have found this article helpful and informative. Happy parking!
FAQs
-
What is the best way to park a car?
- There is no definitive answer to this question, as different types of parking spaces require different techniques and skills. However, some general tips that can help you park your car better are: - Approach the parking space slowly and carefully. - Use reference points to align your car with the space and the surroundings. - Use mirrors and signals to check for any obstacles or pedestrians and communicate your intentions. - Adjust your position if needed by moving forward or backward until your car is centered in the space. - Put your car in park and check that it is completely inside the lines.
How do I know if a parking space is big enough for my car?
- A good rule of thumb is to look for a space that is at least one and a half times the length of your car. You can also use reference points to estimate the size of the space, such as the lines, the curb, or other cars. If you are not sure, you can always drive past the space and check how much room there is behind and in front of it.
How do I avoid hitting anything when parking?
- The best way to avoid hitting anything when parking is to check your mirrors and blind spots before and during any parking maneuver. You should also use signals to alert other drivers and pedestrians of your intentions. If you see any obstacles or pedestrians, stop and wait for them to pass. You can also ask someone to act as a spotter and guide you into the space.
How do I get out of a tight parking space?
- To get out of a tight parking space, you need to reverse slowly and carefully until you have enough room to turn. You should check your mirrors and blind spots for any obstacles or pedestrians and use signals to indicate which way you are going. You should also turn your steering wheel hand over hand in the direction you want to go. If you are in a perpendicular or angled space, you should aim for the opposite side of the lane. If you are in a parallel space, you should pull forward until your front bumper clears the rear bumper of the car in front of you.
How do I improve my car parking driving skills?
- The best way to improve your car parking driving skills is to practice as much as possible. You can practice in an empty car park or a quiet street with plenty of spaces. You can also practice with a friend, a family member, or an instructor who can give you feedback and advice. Another way to improve your skills is to play car parking driving games or simulators that can simulate realistic scenarios and challenges.
-
401be4b1e0
-
-
\ No newline at end of file
diff --git a/spaces/4com/README/README.md b/spaces/4com/README/README.md
deleted file mode 100644
index a62f60dd2d723afbb5812bd0c71e74b02e6f6f77..0000000000000000000000000000000000000000
--- a/spaces/4com/README/README.md
+++ /dev/null
@@ -1,16 +0,0 @@
----
-title: README
-emoji: 📚
-colorFrom: indigo
-colorTo: purple
-sdk: static
-pinned: false
----
-
4COM
-
-
-
companies
-
universities
-
classrooms
-
communities
-
non-profit organizations
\ No newline at end of file
diff --git a/spaces/7hao/bingo/src/app/layout.tsx b/spaces/7hao/bingo/src/app/layout.tsx
deleted file mode 100644
index 8b5122759987177b8dc4e4356d1d06cea25c15ea..0000000000000000000000000000000000000000
--- a/spaces/7hao/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/demucs/model.py b/spaces/801artistry/RVC801/demucs/model.py
deleted file mode 100644
index e9d932f4d014f7b95b394d2e24ed5edc379ded8d..0000000000000000000000000000000000000000
--- a/spaces/801artistry/RVC801/demucs/model.py
+++ /dev/null
@@ -1,202 +0,0 @@
-# Copyright (c) Facebook, Inc. and its affiliates.
-# All rights reserved.
-#
-# This source code is licensed under the license found in the
-# LICENSE file in the root directory of this source tree.
-
-import math
-
-import julius
-from torch import nn
-
-from .utils import capture_init, center_trim
-
-
-class BLSTM(nn.Module):
- def __init__(self, dim, layers=1):
- super().__init__()
- self.lstm = nn.LSTM(bidirectional=True, num_layers=layers, hidden_size=dim, input_size=dim)
- self.linear = nn.Linear(2 * dim, dim)
-
- def forward(self, x):
- x = x.permute(2, 0, 1)
- x = self.lstm(x)[0]
- x = self.linear(x)
- x = x.permute(1, 2, 0)
- return x
-
-
-def rescale_conv(conv, reference):
- std = conv.weight.std().detach()
- scale = (std / reference)**0.5
- conv.weight.data /= scale
- if conv.bias is not None:
- conv.bias.data /= scale
-
-
-def rescale_module(module, reference):
- for sub in module.modules():
- if isinstance(sub, (nn.Conv1d, nn.ConvTranspose1d)):
- rescale_conv(sub, reference)
-
-
-class Demucs(nn.Module):
- @capture_init
- def __init__(self,
- sources,
- audio_channels=2,
- channels=64,
- depth=6,
- rewrite=True,
- glu=True,
- rescale=0.1,
- resample=True,
- kernel_size=8,
- stride=4,
- growth=2.,
- lstm_layers=2,
- context=3,
- normalize=False,
- samplerate=44100,
- segment_length=4 * 10 * 44100):
- """
- Args:
- sources (list[str]): list of source names
- audio_channels (int): stereo or mono
- channels (int): first convolution channels
- depth (int): number of encoder/decoder layers
- rewrite (bool): add 1x1 convolution to each encoder layer
- and a convolution to each decoder layer.
- For the decoder layer, `context` gives the kernel size.
- glu (bool): use glu instead of ReLU
- resample_input (bool): upsample x2 the input and downsample /2 the output.
- rescale (int): rescale initial weights of convolutions
- to get their standard deviation closer to `rescale`
- kernel_size (int): kernel size for convolutions
- stride (int): stride for convolutions
- growth (float): multiply (resp divide) number of channels by that
- for each layer of the encoder (resp decoder)
- lstm_layers (int): number of lstm layers, 0 = no lstm
- context (int): kernel size of the convolution in the
- decoder before the transposed convolution. If > 1,
- will provide some context from neighboring time
- steps.
- samplerate (int): stored as meta information for easing
- future evaluations of the model.
- segment_length (int): stored as meta information for easing
- future evaluations of the model. Length of the segments on which
- the model was trained.
- """
-
- super().__init__()
- self.audio_channels = audio_channels
- self.sources = sources
- self.kernel_size = kernel_size
- self.context = context
- self.stride = stride
- self.depth = depth
- self.resample = resample
- self.channels = channels
- self.normalize = normalize
- self.samplerate = samplerate
- self.segment_length = segment_length
-
- self.encoder = nn.ModuleList()
- self.decoder = nn.ModuleList()
-
- if glu:
- activation = nn.GLU(dim=1)
- ch_scale = 2
- else:
- activation = nn.ReLU()
- ch_scale = 1
- in_channels = audio_channels
- for index in range(depth):
- encode = []
- encode += [nn.Conv1d(in_channels, channels, kernel_size, stride), nn.ReLU()]
- if rewrite:
- encode += [nn.Conv1d(channels, ch_scale * channels, 1), activation]
- self.encoder.append(nn.Sequential(*encode))
-
- decode = []
- if index > 0:
- out_channels = in_channels
- else:
- out_channels = len(self.sources) * audio_channels
- if rewrite:
- decode += [nn.Conv1d(channels, ch_scale * channels, context), activation]
- decode += [nn.ConvTranspose1d(channels, out_channels, kernel_size, stride)]
- if index > 0:
- decode.append(nn.ReLU())
- self.decoder.insert(0, nn.Sequential(*decode))
- in_channels = channels
- channels = int(growth * channels)
-
- channels = in_channels
-
- if lstm_layers:
- self.lstm = BLSTM(channels, lstm_layers)
- else:
- self.lstm = None
-
- if rescale:
- rescale_module(self, reference=rescale)
-
- def valid_length(self, length):
- """
- Return the nearest valid length to use with the model so that
- there is no time steps left over in a convolutions, e.g. for all
- layers, size of the input - kernel_size % stride = 0.
-
- If the mixture has a valid length, the estimated sources
- will have exactly the same length when context = 1. If context > 1,
- the two signals can be center trimmed to match.
-
- For training, extracts should have a valid length.For evaluation
- on full tracks we recommend passing `pad = True` to :method:`forward`.
- """
- if self.resample:
- length *= 2
- for _ in range(self.depth):
- length = math.ceil((length - self.kernel_size) / self.stride) + 1
- length = max(1, length)
- length += self.context - 1
- for _ in range(self.depth):
- length = (length - 1) * self.stride + self.kernel_size
-
- if self.resample:
- length = math.ceil(length / 2)
- return int(length)
-
- def forward(self, mix):
- x = mix
-
- if self.normalize:
- mono = mix.mean(dim=1, keepdim=True)
- mean = mono.mean(dim=-1, keepdim=True)
- std = mono.std(dim=-1, keepdim=True)
- else:
- mean = 0
- std = 1
-
- x = (x - mean) / (1e-5 + std)
-
- if self.resample:
- x = julius.resample_frac(x, 1, 2)
-
- saved = []
- for encode in self.encoder:
- x = encode(x)
- saved.append(x)
- if self.lstm:
- x = self.lstm(x)
- for decode in self.decoder:
- skip = center_trim(saved.pop(-1), x)
- x = x + skip
- x = decode(x)
-
- if self.resample:
- x = julius.resample_frac(x, 2, 1)
- x = x * std + mean
- x = x.view(x.size(0), len(self.sources), self.audio_channels, x.size(-1))
- return x
diff --git a/spaces/801artistry/RVC801/lib/uvr5_pack/utils.py b/spaces/801artistry/RVC801/lib/uvr5_pack/utils.py
deleted file mode 100644
index 0fafe8793b0d539fa58dd024342250b24b6187a9..0000000000000000000000000000000000000000
--- a/spaces/801artistry/RVC801/lib/uvr5_pack/utils.py
+++ /dev/null
@@ -1,120 +0,0 @@
-import torch
-import numpy as np
-from tqdm import tqdm
-import json
-
-
-def load_data(file_name: str = "./lib/uvr5_pack/name_params.json") -> dict:
- with open(file_name, "r") as f:
- data = json.load(f)
-
- return data
-
-
-def make_padding(width, cropsize, offset):
- left = offset
- roi_size = cropsize - left * 2
- if roi_size == 0:
- roi_size = cropsize
- right = roi_size - (width % roi_size) + left
-
- return left, right, roi_size
-
-
-def inference(X_spec, device, model, aggressiveness, data):
- """
- data : dic configs
- """
-
- def _execute(
- X_mag_pad, roi_size, n_window, device, model, aggressiveness, is_half=True
- ):
- model.eval()
- with torch.no_grad():
- preds = []
-
- iterations = [n_window]
-
- total_iterations = sum(iterations)
- for i in tqdm(range(n_window)):
- start = i * roi_size
- X_mag_window = X_mag_pad[
- None, :, :, start : start + data["window_size"]
- ]
- X_mag_window = torch.from_numpy(X_mag_window)
- if is_half:
- X_mag_window = X_mag_window.half()
- X_mag_window = X_mag_window.to(device)
-
- pred = model.predict(X_mag_window, aggressiveness)
-
- pred = pred.detach().cpu().numpy()
- preds.append(pred[0])
-
- pred = np.concatenate(preds, axis=2)
- return pred
-
- def preprocess(X_spec):
- X_mag = np.abs(X_spec)
- X_phase = np.angle(X_spec)
-
- return X_mag, X_phase
-
- X_mag, X_phase = preprocess(X_spec)
-
- coef = X_mag.max()
- X_mag_pre = X_mag / coef
-
- n_frame = X_mag_pre.shape[2]
- pad_l, pad_r, roi_size = make_padding(n_frame, data["window_size"], model.offset)
- n_window = int(np.ceil(n_frame / roi_size))
-
- X_mag_pad = np.pad(X_mag_pre, ((0, 0), (0, 0), (pad_l, pad_r)), mode="constant")
-
- if list(model.state_dict().values())[0].dtype == torch.float16:
- is_half = True
- else:
- is_half = False
- pred = _execute(
- X_mag_pad, roi_size, n_window, device, model, aggressiveness, is_half
- )
- pred = pred[:, :, :n_frame]
-
- if data["tta"]:
- pad_l += roi_size // 2
- pad_r += roi_size // 2
- n_window += 1
-
- X_mag_pad = np.pad(X_mag_pre, ((0, 0), (0, 0), (pad_l, pad_r)), mode="constant")
-
- pred_tta = _execute(
- X_mag_pad, roi_size, n_window, device, model, aggressiveness, is_half
- )
- pred_tta = pred_tta[:, :, roi_size // 2 :]
- pred_tta = pred_tta[:, :, :n_frame]
-
- return (pred + pred_tta) * 0.5 * coef, X_mag, np.exp(1.0j * X_phase)
- else:
- return pred * coef, X_mag, np.exp(1.0j * X_phase)
-
-
-def _get_name_params(model_path, model_hash):
- data = load_data()
- flag = False
- ModelName = model_path
- for type in list(data):
- for model in list(data[type][0]):
- for i in range(len(data[type][0][model])):
- if str(data[type][0][model][i]["hash_name"]) == model_hash:
- flag = True
- elif str(data[type][0][model][i]["hash_name"]) in ModelName:
- flag = True
-
- if flag:
- model_params_auto = data[type][0][model][i]["model_params"]
- param_name_auto = data[type][0][model][i]["param_name"]
- if type == "equivalent":
- return param_name_auto, model_params_auto
- else:
- flag = False
- return param_name_auto, model_params_auto
diff --git a/spaces/A00001/bingothoo/src/pages/api/kblob.ts b/spaces/A00001/bingothoo/src/pages/api/kblob.ts
deleted file mode 100644
index 0ce7e6063cdc06838e76f1cff1d5982d34ef52de..0000000000000000000000000000000000000000
--- a/spaces/A00001/bingothoo/src/pages/api/kblob.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-'use server'
-
-import { NextApiRequest, NextApiResponse } from 'next'
-import FormData from 'form-data'
-import { fetch } from '@/lib/isomorphic'
-import { KBlobRequest } from '@/lib/bots/bing/types'
-
-const API_DOMAIN = 'https://bing.vcanbb.top'
-
-export const config = {
- api: {
- bodyParser: {
- sizeLimit: '10mb' // Set desired value here
- }
- }
-}
-
-export default async function handler(req: NextApiRequest, res: NextApiResponse) {
- try {
- const { knowledgeRequest, imageBase64 } = req.body as KBlobRequest
-
- const formData = new FormData()
- formData.append('knowledgeRequest', JSON.stringify(knowledgeRequest))
- if (imageBase64) {
- formData.append('imageBase64', imageBase64)
- }
-
- const response = await fetch(`${API_DOMAIN}/images/kblob`,
- {
- method: 'POST',
- body: formData.getBuffer(),
- headers: {
- "sec-ch-ua": "\"Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"115\", \"Chromium\";v=\"115\"",
- "sec-ch-ua-mobile": "?0",
- "sec-ch-ua-platform": "\"Windows\"",
- "Referer": `${API_DOMAIN}/web/index.html`,
- "Referrer-Policy": "origin-when-cross-origin",
- 'x-ms-useragent': 'azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/Win32',
- ...formData.getHeaders()
- }
- }
- ).then(res => res.text())
-
- res.writeHead(200, {
- 'Content-Type': 'application/json',
- })
- res.end(response || JSON.stringify({ result: { value: 'UploadFailed', message: '请更换 IP 或代理后重试' } }))
- } catch (e) {
- return res.json({
- result: {
- value: 'UploadFailed',
- message: `${e}`
- }
- })
- }
-}
diff --git a/spaces/AI-Dashboards/Topic-Modeling-Clusters-Free-Text/README.md b/spaces/AI-Dashboards/Topic-Modeling-Clusters-Free-Text/README.md
deleted file mode 100644
index 730ba0002a25b8d64e896a4c6f0f23368c2f1400..0000000000000000000000000000000000000000
--- a/spaces/AI-Dashboards/Topic-Modeling-Clusters-Free-Text/README.md
+++ /dev/null
@@ -1,13 +0,0 @@
----
-title: Topic Modeling Clusters Free Text
-emoji: 🐨
-colorFrom: yellow
-colorTo: yellow
-sdk: streamlit
-sdk_version: 1.17.0
-app_file: app.py
-pinned: false
-license: mit
----
-
-Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
diff --git a/spaces/AIConsultant/MusicGen/tests/__init__.py b/spaces/AIConsultant/MusicGen/tests/__init__.py
deleted file mode 100644
index 0952fcc3f57e34b3747962e9ebd6fc57aeea63fa..0000000000000000000000000000000000000000
--- a/spaces/AIConsultant/MusicGen/tests/__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/AIConsultant/MusicGen/tests/modules/test_codebooks_patterns.py b/spaces/AIConsultant/MusicGen/tests/modules/test_codebooks_patterns.py
deleted file mode 100644
index b658f4779a369f9ec8dde692a61b7f0fe3485724..0000000000000000000000000000000000000000
--- a/spaces/AIConsultant/MusicGen/tests/modules/test_codebooks_patterns.py
+++ /dev/null
@@ -1,246 +0,0 @@
-# Copyright (c) Meta Platforms, Inc. and affiliates.
-# All rights reserved.
-#
-# This source code is licensed under the license found in the
-# LICENSE file in the root directory of this source tree.
-
-import pytest
-import torch
-
-from audiocraft.modules.codebooks_patterns import (
- DelayedPatternProvider,
- ParallelPatternProvider,
- Pattern,
- UnrolledPatternProvider,
-)
-
-
-class TestParallelPatternProvider:
-
- @pytest.mark.parametrize("n_q", [1, 4, 32])
- @pytest.mark.parametrize("timesteps", [0, 1, 16, 100])
- def test_get_pattern(self, n_q: int, timesteps: int):
- provider = ParallelPatternProvider(n_q)
- pattern = provider.get_pattern(timesteps)
- # + 1 to account for 1st step
- assert len(pattern.layout) == timesteps + 1
-
- @pytest.mark.parametrize("n_q", [1, 4, 32])
- @pytest.mark.parametrize("timesteps", [8, 16, 100])
- def test_pattern_content(self, n_q: int, timesteps: int):
- provider = ParallelPatternProvider(n_q)
- pattern = provider.get_pattern(timesteps)
- for s, v in enumerate(pattern.layout):
- for i, code in enumerate(v):
- assert i == code.q
- assert code.t == s - 1 # account for the 1st empty step
-
- @pytest.mark.parametrize("n_q", [1, 4, 32])
- @pytest.mark.parametrize("timesteps", [8, 16, 100])
- def test_pattern_max_delay(self, n_q: int, timesteps: int):
- provider = ParallelPatternProvider(n_q)
- pattern = provider.get_pattern(timesteps)
- assert pattern.max_delay == 0
- assert len(pattern.valid_layout) == len(pattern.layout) - pattern.max_delay
-
-
-class TestDelayedPatternProvider:
-
- @pytest.mark.parametrize("n_q", [1, 4, 32])
- @pytest.mark.parametrize("timesteps", [0, 1, 16, 100])
- def test_get_pattern(self, n_q: int, timesteps: int):
- delays = [
- list(range(n_q)),
- [0] + [1] * (n_q - 1),
- [0] + [4] * (n_q - 1),
- ]
- for delay in delays:
- provider = DelayedPatternProvider(n_q, delay)
- pattern = provider.get_pattern(timesteps)
- # + 1 to account for 1st step
- assert len(pattern.layout) == timesteps + max(delay) + 1
-
- @pytest.mark.parametrize("n_q", [1, 4, 32])
- @pytest.mark.parametrize("timesteps", [8, 16, 100])
- def test_pattern_content(self, n_q: int, timesteps: int):
- provider = DelayedPatternProvider(n_q)
- pattern = provider.get_pattern(timesteps)
- for s, v in enumerate(pattern.layout):
- for i, code in enumerate(v):
- assert i == code.q
- assert code.t == max(0, s - code.q - 1)
-
- @pytest.mark.parametrize("timesteps", [8, 16, 100])
- @pytest.mark.parametrize("delay", [[0, 1, 2, 3], [0, 1, 1, 1], [0, 3, 3, 3], [0, 3]])
- def test_pattern_max_delay(self, timesteps: int, delay: list):
- provider = DelayedPatternProvider(len(delay), delay)
- pattern = provider.get_pattern(timesteps)
- assert pattern.max_delay == max(delay)
- assert len(pattern.valid_layout) == len(pattern.layout) - pattern.max_delay
-
-
-class TestUnrolledPatternProvider:
-
- @pytest.mark.parametrize("timesteps", [0, 1, 16])
- @pytest.mark.parametrize("flattening", [[0, 1, 2], [0, 1, 1]])
- @pytest.mark.parametrize("delays", [[0, 0, 0], [0, 5, 5]])
- def test_get_pattern(self, timesteps: int, flattening: list, delays: list):
- n_q = len(flattening)
- max_delay = max(delays)
- provider = UnrolledPatternProvider(n_q, flattening, delays)
- pattern = provider.get_pattern(timesteps)
- assert len(pattern.layout) == provider.num_virtual_steps(timesteps) + max_delay
-
- @pytest.mark.parametrize("timesteps", [0, 1, 16])
- @pytest.mark.parametrize("flattening", [[0, 1, 2], [0, 1, 1]])
- @pytest.mark.parametrize("delays", [[0, 0, 0], [0, 5, 5]])
- def test_pattern_max_delay(self, timesteps: int, flattening: list, delays: list):
- n_q = len(flattening)
- max_delay = max(delays)
- provider = UnrolledPatternProvider(n_q, flattening, delays)
- pattern = provider.get_pattern(timesteps)
- assert pattern.max_delay == max_delay
-
-
-class TestPattern:
-
- def ref_build_pattern_sequence(self, z: torch.Tensor, pattern: Pattern, special_token: int):
- """Reference method to build the sequence from the pattern without using fancy scatter."""
- bs, n_q, T = z.shape
- z = z.cpu().numpy()
- assert n_q == pattern.n_q
- assert T <= pattern.timesteps
- inp = torch.full((bs, n_q, len(pattern.layout)), special_token, dtype=torch.long).numpy()
- inp[:] = special_token
- for s, v in enumerate(pattern.layout):
- for (t, q) in v:
- if t < T:
- inp[:, q, s] = z[:, q, t]
- return torch.from_numpy(inp)
-
- def ref_revert_pattern_sequence(self, z: torch.Tensor, pattern: Pattern, special_token: int):
- """Reference method to revert the sequence from the pattern without using fancy scatter."""
- z = z.cpu().numpy()
- bs, n_q, S = z.shape
- assert pattern.n_q == n_q
- inp = torch.full((bs, pattern.n_q, pattern.timesteps), special_token, dtype=torch.long).numpy()
- inp[:] = special_token
- for s, v in enumerate(pattern.layout):
- for (t, q) in v:
- if t < pattern.timesteps:
- inp[:, q, t] = z[:, q, s]
- return torch.from_numpy(inp)
-
- def ref_revert_pattern_logits(self, z: torch.Tensor, pattern: Pattern, special_token: float):
- """Reference method to revert the logits from the pattern without using fancy scatter."""
- z = z.cpu().numpy()
- bs, card, n_q, S = z.shape
- assert pattern.n_q == n_q
- ref_layout = pattern.layout
- inp = torch.full((bs, card, pattern.n_q, pattern.timesteps), special_token, dtype=torch.float).numpy()
- inp[:] = special_token
- for s, v in enumerate(ref_layout[1:]):
- if s < S:
- for (t, q) in v:
- if t < pattern.timesteps:
- inp[:, :, q, t] = z[:, :, q, s]
- return torch.from_numpy(inp)
-
- def _get_pattern_providers(self, n_q: int):
- pattern_provider_1 = ParallelPatternProvider(n_q)
- pattern_provider_2 = DelayedPatternProvider(n_q, list(range(n_q)))
- pattern_provider_3 = DelayedPatternProvider(n_q, [0] + [1] * (n_q - 1))
- pattern_provider_4 = UnrolledPatternProvider(
- n_q, flattening=list(range(n_q)), delays=[0] * n_q
- )
- pattern_provider_5 = UnrolledPatternProvider(
- n_q, flattening=[0] + [1] * (n_q - 1), delays=[0] * n_q
- )
- pattern_provider_6 = UnrolledPatternProvider(
- n_q, flattening=[0] + [1] * (n_q - 1), delays=[0] + [5] * (n_q - 1)
- )
- return [
- pattern_provider_1,
- pattern_provider_2,
- pattern_provider_3,
- pattern_provider_4,
- pattern_provider_5,
- pattern_provider_6,
- ]
-
- @pytest.mark.parametrize("n_q", [1, 4, 32])
- @pytest.mark.parametrize("timesteps", [16, 72])
- def test_build_pattern_sequence(self, n_q: int, timesteps: int):
- bs = 2
- card = 256
- special_token = card
-
- pattern_providers = self._get_pattern_providers(n_q)
- for pattern_provider in pattern_providers:
- pattern = pattern_provider.get_pattern(timesteps)
- # we can correctly build the sequence from the pattern
- z = torch.randint(0, card, (bs, n_q, timesteps))
- ref_res = self.ref_build_pattern_sequence(z, pattern, special_token)
- res, indexes, mask = pattern.build_pattern_sequence(z, special_token)
- assert (res == ref_res).float().mean() == 1.0
-
- # expected assertion fails on the number of timesteps
- invalid_timesteps = [timesteps + 1]
- if pattern.num_sequence_steps != pattern.timesteps:
- invalid_timesteps.append(pattern.num_sequence_steps)
- for i_timesteps in invalid_timesteps:
- z2 = torch.randint(0, card, (bs, n_q, i_timesteps))
- with pytest.raises(AssertionError):
- pattern.build_pattern_sequence(z2, special_token)
-
- # expected assertion fails on the number of codebooks
- invalid_qs = [0, n_q - 1, n_q + 1]
- for i_q in invalid_qs:
- z3 = torch.randint(0, card, (bs, i_q, timesteps))
- with pytest.raises(AssertionError):
- pattern.build_pattern_sequence(z3, special_token)
-
- @pytest.mark.parametrize("n_q", [1, 4, 32])
- @pytest.mark.parametrize("timesteps", [16, 72])
- def test_revert_pattern_sequence(self, n_q: int, timesteps: int):
- bs = 2
- card = 256
- special_token = card
-
- pattern_providers = self._get_pattern_providers(n_q)
- for pattern_provider in pattern_providers:
- pattern = pattern_provider.get_pattern(timesteps)
- # this works assuming previous tests are successful
- z = torch.randint(0, card, (bs, n_q, timesteps))
- s = self.ref_build_pattern_sequence(z, pattern, special_token)
- ref_out = self.ref_revert_pattern_sequence(s, pattern, special_token)
- # ensure our reference script retrieve the original sequence
- assert z.shape == ref_out.shape
- assert (z == ref_out).float().mean() == 1.0
- # now we can test the scatter version
- out, indexes, mask = pattern.revert_pattern_sequence(s, special_token)
- assert out.shape == ref_out.shape
- assert (out == ref_out).float().mean() == 1.0
-
- @pytest.mark.parametrize("n_q", [1, 4, 32])
- @pytest.mark.parametrize("timesteps", [16, 72])
- @pytest.mark.parametrize("card", [1, 2, 256, 1024])
- def test_revert_pattern_logits(self, n_q: int, timesteps: int, card: int):
- bs = 2
- special_token = card
- logits_special_token = float('nan')
-
- pattern_providers = self._get_pattern_providers(n_q)
- for pattern_provider in pattern_providers:
- pattern = pattern_provider.get_pattern(timesteps)
- # this works assuming previous tests are successful
- z = torch.randint(0, card, (bs, n_q, timesteps))
- s = self.ref_build_pattern_sequence(z, pattern, special_token)
- logits = torch.randn((bs, card, n_q, s.shape[-1]))
- ref_out = self.ref_revert_pattern_logits(logits, pattern, logits_special_token)
- # ensure our reference script retrieve the original sequence
- assert ref_out.shape == torch.Size([bs, card, n_q, timesteps])
- # now we can test the scatter version
- out, indexes, mask = pattern.revert_pattern_logits(logits, logits_special_token)
- assert out.shape == ref_out.shape
- assert (out == ref_out).float().mean() == 1.0
diff --git a/spaces/AIFILMS/audioldm-text-to-audio-generation/audioldm/clap/open_clip/pretrained.py b/spaces/AIFILMS/audioldm-text-to-audio-generation/audioldm/clap/open_clip/pretrained.py
deleted file mode 100644
index e211d8b5b59320a599e62605f1dee6199f317253..0000000000000000000000000000000000000000
--- a/spaces/AIFILMS/audioldm-text-to-audio-generation/audioldm/clap/open_clip/pretrained.py
+++ /dev/null
@@ -1,167 +0,0 @@
-import hashlib
-import os
-import urllib
-import warnings
-
-from tqdm import tqdm
-
-_RN50 = dict(
- openai="https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
- yfcc15m="https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-yfcc15m-455df137.pt",
- cc12m="https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-cc12m-f000538c.pt",
-)
-
-_RN50_quickgelu = dict(
- openai="https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
- yfcc15m="https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-yfcc15m-455df137.pt",
- cc12m="https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-cc12m-f000538c.pt",
-)
-
-_RN101 = dict(
- openai="https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt",
- yfcc15m="https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn101-quickgelu-yfcc15m-3e04b30e.pt",
-)
-
-_RN101_quickgelu = dict(
- openai="https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt",
- yfcc15m="https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn101-quickgelu-yfcc15m-3e04b30e.pt",
-)
-
-_RN50x4 = dict(
- openai="https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt",
-)
-
-_RN50x16 = dict(
- openai="https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt",
-)
-
-_RN50x64 = dict(
- openai="https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt",
-)
-
-_VITB32 = dict(
- openai="https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
- laion400m_e31="https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e31-d867053b.pt",
- laion400m_e32="https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e32-46683a32.pt",
- laion400m_avg="https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_avg-8a00ab3c.pt",
-)
-
-_VITB32_quickgelu = dict(
- openai="https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
- laion400m_e31="https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e31-d867053b.pt",
- laion400m_e32="https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e32-46683a32.pt",
- laion400m_avg="https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_avg-8a00ab3c.pt",
-)
-
-_VITB16 = dict(
- openai="https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt",
-)
-
-_VITL14 = dict(
- openai="https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt",
-)
-
-_PRETRAINED = {
- "RN50": _RN50,
- "RN50-quickgelu": _RN50_quickgelu,
- "RN101": _RN101,
- "RN101-quickgelu": _RN101_quickgelu,
- "RN50x4": _RN50x4,
- "RN50x16": _RN50x16,
- "ViT-B-32": _VITB32,
- "ViT-B-32-quickgelu": _VITB32_quickgelu,
- "ViT-B-16": _VITB16,
- "ViT-L-14": _VITL14,
-}
-
-
-def list_pretrained(as_str: bool = False):
- """returns list of pretrained models
- Returns a tuple (model_name, pretrain_tag) by default or 'name:tag' if as_str == True
- """
- return [
- ":".join([k, t]) if as_str else (k, t)
- for k in _PRETRAINED.keys()
- for t in _PRETRAINED[k].keys()
- ]
-
-
-def list_pretrained_tag_models(tag: str):
- """return all models having the specified pretrain tag"""
- models = []
- for k in _PRETRAINED.keys():
- if tag in _PRETRAINED[k]:
- models.append(k)
- return models
-
-
-def list_pretrained_model_tags(model: str):
- """return all pretrain tags for the specified model architecture"""
- tags = []
- if model in _PRETRAINED:
- tags.extend(_PRETRAINED[model].keys())
- return tags
-
-
-def get_pretrained_url(model: str, tag: str):
- if model not in _PRETRAINED:
- return ""
- model_pretrained = _PRETRAINED[model]
- if tag not in model_pretrained:
- return ""
- return model_pretrained[tag]
-
-
-def download_pretrained(url: str, root: str = os.path.expanduser("~/.cache/clip")):
- os.makedirs(root, exist_ok=True)
- filename = os.path.basename(url)
-
- if "openaipublic" in url:
- expected_sha256 = url.split("/")[-2]
- else:
- expected_sha256 = ""
-
- download_target = os.path.join(root, filename)
-
- if os.path.exists(download_target) and not os.path.isfile(download_target):
- raise RuntimeError(f"{download_target} exists and is not a regular file")
-
- if os.path.isfile(download_target):
- if expected_sha256:
- if (
- hashlib.sha256(open(download_target, "rb").read()).hexdigest()
- == expected_sha256
- ):
- return download_target
- else:
- warnings.warn(
- f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file"
- )
- else:
- return download_target
-
- with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
- with tqdm(
- total=int(source.info().get("Content-Length")),
- ncols=80,
- unit="iB",
- unit_scale=True,
- ) as loop:
- while True:
- buffer = source.read(8192)
- if not buffer:
- break
-
- output.write(buffer)
- loop.update(len(buffer))
-
- if (
- expected_sha256
- and hashlib.sha256(open(download_target, "rb").read()).hexdigest()
- != expected_sha256
- ):
- raise RuntimeError(
- f"Model has been downloaded but the SHA256 checksum does not not match"
- )
-
- return download_target
diff --git a/spaces/AIFILMS/audioldm-text-to-audio-generation/audioldm/clap/open_clip/tokenizer.py b/spaces/AIFILMS/audioldm-text-to-audio-generation/audioldm/clap/open_clip/tokenizer.py
deleted file mode 100644
index ee4d28450ec5dd12a79daf38cf3088e9e73c2cd5..0000000000000000000000000000000000000000
--- a/spaces/AIFILMS/audioldm-text-to-audio-generation/audioldm/clap/open_clip/tokenizer.py
+++ /dev/null
@@ -1,197 +0,0 @@
-""" CLIP tokenizer
-
-Copied from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
-"""
-import gzip
-import html
-import os
-from functools import lru_cache
-from typing import Union, List
-
-import ftfy
-import regex as re
-import torch
-
-
-@lru_cache()
-def default_bpe():
- return os.path.join(
- os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz"
- )
-
-
-@lru_cache()
-def bytes_to_unicode():
- """
- Returns list of utf-8 byte and a corresponding list of unicode strings.
- The reversible bpe codes work on unicode strings.
- This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
- When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
- This is a signficant percentage of your normal, say, 32K bpe vocab.
- To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
- And avoids mapping to whitespace/control characters the bpe code barfs on.
- """
- bs = (
- list(range(ord("!"), ord("~") + 1))
- + list(range(ord("¡"), ord("¬") + 1))
- + list(range(ord("®"), ord("ÿ") + 1))
- )
- cs = bs[:]
- n = 0
- for b in range(2**8):
- if b not in bs:
- bs.append(b)
- cs.append(2**8 + n)
- n += 1
- cs = [chr(n) for n in cs]
- return dict(zip(bs, cs))
-
-
-def get_pairs(word):
- """Return set of symbol pairs in a word.
- Word is represented as tuple of symbols (symbols being variable-length strings).
- """
- pairs = set()
- prev_char = word[0]
- for char in word[1:]:
- pairs.add((prev_char, char))
- prev_char = char
- return pairs
-
-
-def basic_clean(text):
- text = ftfy.fix_text(text)
- text = html.unescape(html.unescape(text))
- return text.strip()
-
-
-def whitespace_clean(text):
- text = re.sub(r"\s+", " ", text)
- text = text.strip()
- return text
-
-
-class SimpleTokenizer(object):
- def __init__(self, bpe_path: str = default_bpe(), special_tokens=None):
- self.byte_encoder = bytes_to_unicode()
- self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
- merges = gzip.open(bpe_path).read().decode("utf-8").split("\n")
- merges = merges[1 : 49152 - 256 - 2 + 1]
- merges = [tuple(merge.split()) for merge in merges]
- vocab = list(bytes_to_unicode().values())
- vocab = vocab + [v + "" for v in vocab]
- for merge in merges:
- vocab.append("".join(merge))
- if not special_tokens:
- special_tokens = ["", ""]
- else:
- special_tokens = ["", ""] + special_tokens
- vocab.extend(special_tokens)
- self.encoder = dict(zip(vocab, range(len(vocab))))
- self.decoder = {v: k for k, v in self.encoder.items()}
- self.bpe_ranks = dict(zip(merges, range(len(merges))))
- self.cache = {t: t for t in special_tokens}
- special = "|".join(special_tokens)
- self.pat = re.compile(
- special + r"""|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""",
- re.IGNORECASE,
- )
-
- self.vocab_size = len(self.encoder)
- self.all_special_ids = [self.encoder[t] for t in special_tokens]
-
- def bpe(self, token):
- if token in self.cache:
- return self.cache[token]
- word = tuple(token[:-1]) + (token[-1] + "",)
- pairs = get_pairs(word)
-
- if not pairs:
- return token + ""
-
- while True:
- bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
- if bigram not in self.bpe_ranks:
- break
- first, second = bigram
- new_word = []
- i = 0
- while i < len(word):
- try:
- j = word.index(first, i)
- new_word.extend(word[i:j])
- i = j
- except:
- new_word.extend(word[i:])
- break
-
- if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
- new_word.append(first + second)
- i += 2
- else:
- new_word.append(word[i])
- i += 1
- new_word = tuple(new_word)
- word = new_word
- if len(word) == 1:
- break
- else:
- pairs = get_pairs(word)
- word = " ".join(word)
- self.cache[token] = word
- return word
-
- def encode(self, text):
- bpe_tokens = []
- text = whitespace_clean(basic_clean(text)).lower()
- for token in re.findall(self.pat, text):
- token = "".join(self.byte_encoder[b] for b in token.encode("utf-8"))
- bpe_tokens.extend(
- self.encoder[bpe_token] for bpe_token in self.bpe(token).split(" ")
- )
- return bpe_tokens
-
- def decode(self, tokens):
- text = "".join([self.decoder[token] for token in tokens])
- text = (
- bytearray([self.byte_decoder[c] for c in text])
- .decode("utf-8", errors="replace")
- .replace("", " ")
- )
- return text
-
-
-_tokenizer = SimpleTokenizer()
-
-
-def tokenize(
- texts: Union[str, List[str]], context_length: int = 77
-) -> torch.LongTensor:
- """
- Returns the tokenized representation of given input string(s)
-
- Parameters
- ----------
- texts : Union[str, List[str]]
- An input string or a list of input strings to tokenize
- context_length : int
- The context length to use; all CLIP models use 77 as the context length
-
- Returns
- -------
- A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length]
- """
- if isinstance(texts, str):
- texts = [texts]
-
- sot_token = _tokenizer.encoder[""]
- eot_token = _tokenizer.encoder[""]
- all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
- result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
-
- for i, tokens in enumerate(all_tokens):
- if len(tokens) > context_length:
- tokens = tokens[:context_length] # Truncate
- result[i, : len(tokens)] = torch.tensor(tokens)
-
- return result
diff --git a/spaces/AIGC-Audio/AudioGPT/text_to_audio/Make_An_Audio/ldm/modules/encoders/__init__.py b/spaces/AIGC-Audio/AudioGPT/text_to_audio/Make_An_Audio/ldm/modules/encoders/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/spaces/AIGC-Audio/Make_An_Audio/ldm/modules/losses_audio/vggishish/transforms.py b/spaces/AIGC-Audio/Make_An_Audio/ldm/modules/losses_audio/vggishish/transforms.py
deleted file mode 100644
index bdab7eb6b94ac21e950e2870b89da7bbac1f4a8e..0000000000000000000000000000000000000000
--- a/spaces/AIGC-Audio/Make_An_Audio/ldm/modules/losses_audio/vggishish/transforms.py
+++ /dev/null
@@ -1,98 +0,0 @@
-import logging
-import os
-from pathlib import Path
-
-import albumentations
-import numpy as np
-import torch
-from tqdm import tqdm
-
-logger = logging.getLogger(f'main.{__name__}')
-
-
-class StandardNormalizeAudio(object):
- '''
- Frequency-wise normalization
- '''
- def __init__(self, specs_dir, train_ids_path='./data/vggsound_train.txt', cache_path='./data/'):
- self.specs_dir = specs_dir
- self.train_ids_path = train_ids_path
- # making the stats filename to match the specs dir name
- self.cache_path = os.path.join(cache_path, f'train_means_stds_{Path(specs_dir).stem}.txt')
- logger.info('Assuming that the input stats are calculated using preprocessed spectrograms (log)')
- self.train_stats = self.calculate_or_load_stats()
-
- def __call__(self, item):
- # just to generalizat the input handling. Useful for FID, IS eval and training other staff
- if isinstance(item, dict):
- if 'input' in item:
- input_key = 'input'
- elif 'image' in item:
- input_key = 'image'
- else:
- raise NotImplementedError
- item[input_key] = (item[input_key] - self.train_stats['means']) / self.train_stats['stds']
- elif isinstance(item, torch.Tensor):
- # broadcasts np.ndarray (80, 1) to (1, 80, 1) because item is torch.Tensor (B, 80, T)
- item = (item - self.train_stats['means']) / self.train_stats['stds']
- else:
- raise NotImplementedError
- return item
-
- def calculate_or_load_stats(self):
- try:
- # (F, 2)
- train_stats = np.loadtxt(self.cache_path)
- means, stds = train_stats.T
- logger.info('Trying to load train stats for Standard Normalization of inputs')
- except OSError:
- logger.info('Could not find the precalculated stats for Standard Normalization. Calculating...')
- train_vid_ids = open(self.train_ids_path)
- specs_paths = [os.path.join(self.specs_dir, f'{i.rstrip()}_mel.npy') for i in train_vid_ids]
- means = [None] * len(specs_paths)
- stds = [None] * len(specs_paths)
- for i, path in enumerate(tqdm(specs_paths)):
- spec = np.load(path)
- means[i] = spec.mean(axis=1)
- stds[i] = spec.std(axis=1)
- # (F) <- (num_files, F)
- means = np.array(means).mean(axis=0)
- stds = np.array(stds).mean(axis=0)
- # saving in two columns
- np.savetxt(self.cache_path, np.vstack([means, stds]).T, fmt='%0.8f')
- means = means.reshape(-1, 1)
- stds = stds.reshape(-1, 1)
- return {'means': means, 'stds': stds}
-
-class ToTensor(object):
-
- def __call__(self, item):
- item['input'] = torch.from_numpy(item['input']).float()
- # if 'target' in item:
- item['target'] = torch.tensor(item['target'])
- return item
-
-class Crop(object):
-
- def __init__(self, cropped_shape=None, random_crop=False):
- self.cropped_shape = cropped_shape
- if cropped_shape is not None:
- mel_num, spec_len = cropped_shape
- if random_crop:
- self.cropper = albumentations.RandomCrop
- else:
- self.cropper = albumentations.CenterCrop
- self.preprocessor = albumentations.Compose([self.cropper(mel_num, spec_len)])
- else:
- self.preprocessor = lambda **kwargs: kwargs
-
- def __call__(self, item):
- item['input'] = self.preprocessor(image=item['input'])['image']
- return item
-
-
-if __name__ == '__main__':
- cropper = Crop([80, 848])
- item = {'input': torch.rand([80, 860])}
- outputs = cropper(item)
- print(outputs['input'].shape)
diff --git a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/resnet/resnet50_8xb16_cifar10.py b/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/resnet/resnet50_8xb16_cifar10.py
deleted file mode 100644
index 669e5de27e526dd46d9f06c99e478dce16f0ac9a..0000000000000000000000000000000000000000
--- a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/resnet/resnet50_8xb16_cifar10.py
+++ /dev/null
@@ -1,4 +0,0 @@
-_base_ = [
- '../_base_/models/resnet50_cifar.py', '../_base_/datasets/cifar10_bs16.py',
- '../_base_/schedules/cifar10_bs128.py', '../_base_/default_runtime.py'
-]
diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/spinner/custom/Factory.d.ts b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/spinner/custom/Factory.d.ts
deleted file mode 100644
index 28a06b015f607770849c417a9fa37287905eb8bc..0000000000000000000000000000000000000000
--- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/spinner/custom/Factory.d.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import Custom from './Custom';
-
-export default function Factory(
- config?: Custom.IConfig
-): Custom;
\ No newline at end of file
diff --git a/spaces/Agusbs98/automatic-ecg-diagnosis/nets/bblocks.py b/spaces/Agusbs98/automatic-ecg-diagnosis/nets/bblocks.py
deleted file mode 100644
index c9ca173116718a4fd977f92d419f4b45407873fa..0000000000000000000000000000000000000000
--- a/spaces/Agusbs98/automatic-ecg-diagnosis/nets/bblocks.py
+++ /dev/null
@@ -1,55 +0,0 @@
-
-import os, sys
-from libs import *
-from .layers import *
-from .modules import *
-
-class LightSEResBlock(nn.Module):
- def __init__(self,
- in_channels,
- downsample = False,
- ):
- super(LightSEResBlock, self).__init__()
- if downsample:
- self.out_channels = in_channels*2
- self.conv_1 = DSConv1d(
- in_channels, self.out_channels,
- kernel_size = 7, padding = 3, stride = 2,
- )
- self.identity = nn.Sequential(
- DSConv1d(
- in_channels, self.out_channels,
- kernel_size = 1, padding = 0, stride = 2,
- ),
- nn.BatchNorm1d(self.out_channels),
- )
- else:
- self.out_channels = in_channels
- self.conv_1 = DSConv1d(
- in_channels, self.out_channels,
- kernel_size = 7, padding = 3, stride = 1,
- )
- self.identity = nn.Identity()
- self.conv_2 = DSConv1d(
- self.out_channels, self.out_channels,
- kernel_size = 7, padding = 3, stride = 1,
- )
-
- self.convs = nn.Sequential(
- self.conv_1,
- nn.BatchNorm1d(self.out_channels),
- nn.ReLU(),
- nn.Dropout(0.3),
- self.conv_2,
- nn.BatchNorm1d(self.out_channels),
- LightSEModule(self.out_channels),
- )
- self.act_fn = nn.ReLU()
-
- def forward(self,
- input,
- ):
- output = self.convs(input) + self.identity(input)
- output = self.act_fn(output)
-
- return output
\ No newline at end of file
diff --git a/spaces/Aki004/herta-so-vits/onnxexport/model_onnx_speaker_mix.py b/spaces/Aki004/herta-so-vits/onnxexport/model_onnx_speaker_mix.py
deleted file mode 100644
index c4b443162b0c82418286fd3834b4b5b010a454a8..0000000000000000000000000000000000000000
--- a/spaces/Aki004/herta-so-vits/onnxexport/model_onnx_speaker_mix.py
+++ /dev/null
@@ -1,363 +0,0 @@
-import torch
-from torch import nn
-from torch.nn import functional as F
-import cluster
-import modules.attentions as attentions
-import modules.commons as commons
-import modules.modules as modules
-
-from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
-from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
-
-import utils
-from modules.commons import init_weights, get_padding
-from vdecoder.hifigan.models import Generator
-from utils import f0_to_coarse
-
-
-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 Encoder(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):
- # print(x.shape,x_lengths.shape)
- 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 TextEncoder(nn.Module):
- def __init__(self,
- out_channels,
- hidden_channels,
- kernel_size,
- n_layers,
- gin_channels=0,
- filter_channels=None,
- n_heads=None,
- p_dropout=None):
- super().__init__()
- self.out_channels = out_channels
- self.hidden_channels = hidden_channels
- self.kernel_size = kernel_size
- self.n_layers = n_layers
- self.gin_channels = gin_channels
- self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
- self.f0_emb = nn.Embedding(256, hidden_channels)
-
- self.enc_ = attentions.Encoder(
- hidden_channels,
- filter_channels,
- n_heads,
- n_layers,
- kernel_size,
- p_dropout)
-
- def forward(self, x, x_mask, f0=None, z=None):
- x = x + self.f0_emb(f0).transpose(1, 2)
- x = self.enc_(x * x_mask, x_mask)
- stats = self.proj(x) * x_mask
- m, logs = torch.split(stats, self.out_channels, dim=1)
- z = (m + z * torch.exp(logs)) * x_mask
- return z, m, logs, x_mask
-
-
-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 F0Decoder(nn.Module):
- def __init__(self,
- out_channels,
- hidden_channels,
- filter_channels,
- n_heads,
- n_layers,
- kernel_size,
- p_dropout,
- spk_channels=0):
- super().__init__()
- self.out_channels = out_channels
- self.hidden_channels = hidden_channels
- self.filter_channels = filter_channels
- self.n_heads = n_heads
- self.n_layers = n_layers
- self.kernel_size = kernel_size
- self.p_dropout = p_dropout
- self.spk_channels = spk_channels
-
- self.prenet = nn.Conv1d(hidden_channels, hidden_channels, 3, padding=1)
- self.decoder = attentions.FFT(
- hidden_channels,
- filter_channels,
- n_heads,
- n_layers,
- kernel_size,
- p_dropout)
- self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
- self.f0_prenet = nn.Conv1d(1, hidden_channels, 3, padding=1)
- self.cond = nn.Conv1d(spk_channels, hidden_channels, 1)
-
- def forward(self, x, norm_f0, x_mask, spk_emb=None):
- x = torch.detach(x)
- if spk_emb is not None:
- x = x + self.cond(spk_emb)
- x += self.f0_prenet(norm_f0)
- x = self.prenet(x) * x_mask
- x = self.decoder(x * x_mask, x_mask)
- x = self.proj(x) * x_mask
- return x
-
-
-class SynthesizerTrn(nn.Module):
- """
- Synthesizer for Training
- """
-
- def __init__(self,
- spec_channels,
- segment_size,
- inter_channels,
- hidden_channels,
- filter_channels,
- n_heads,
- n_layers,
- kernel_size,
- p_dropout,
- resblock,
- resblock_kernel_sizes,
- resblock_dilation_sizes,
- upsample_rates,
- upsample_initial_channel,
- upsample_kernel_sizes,
- gin_channels,
- ssl_dim,
- n_speakers,
- sampling_rate=44100,
- **kwargs):
- super().__init__()
- self.spec_channels = spec_channels
- self.inter_channels = inter_channels
- self.hidden_channels = hidden_channels
- self.filter_channels = filter_channels
- self.n_heads = n_heads
- self.n_layers = n_layers
- self.kernel_size = kernel_size
- self.p_dropout = p_dropout
- self.resblock = resblock
- self.resblock_kernel_sizes = resblock_kernel_sizes
- self.resblock_dilation_sizes = resblock_dilation_sizes
- self.upsample_rates = upsample_rates
- self.upsample_initial_channel = upsample_initial_channel
- self.upsample_kernel_sizes = upsample_kernel_sizes
- self.segment_size = segment_size
- self.gin_channels = gin_channels
- self.ssl_dim = ssl_dim
- self.emb_g = nn.Embedding(n_speakers, gin_channels)
-
- self.pre = nn.Conv1d(ssl_dim, hidden_channels, kernel_size=5, padding=2)
-
- self.enc_p = TextEncoder(
- inter_channels,
- hidden_channels,
- filter_channels=filter_channels,
- n_heads=n_heads,
- n_layers=n_layers,
- kernel_size=kernel_size,
- p_dropout=p_dropout
- )
- hps = {
- "sampling_rate": sampling_rate,
- "inter_channels": inter_channels,
- "resblock": resblock,
- "resblock_kernel_sizes": resblock_kernel_sizes,
- "resblock_dilation_sizes": resblock_dilation_sizes,
- "upsample_rates": upsample_rates,
- "upsample_initial_channel": upsample_initial_channel,
- "upsample_kernel_sizes": upsample_kernel_sizes,
- "gin_channels": gin_channels,
- }
- self.dec = Generator(h=hps)
- self.enc_q = Encoder(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)
- self.f0_decoder = F0Decoder(
- 1,
- hidden_channels,
- filter_channels,
- n_heads,
- n_layers,
- kernel_size,
- p_dropout,
- spk_channels=gin_channels
- )
- self.emb_uv = nn.Embedding(2, hidden_channels)
- self.predict_f0 = False
- cluster_model_path="kmeans_10000.pt"
- if os.path.exists(cluster_model_path):
- self.cluster_model = cluster.get_cluster_model(cluster_model_path)
- else:
- self.cluster_model = None
- self.speaker_map = []
- self.export_mix = False
-
- def export_chara_mix(self, n_speakers_mix):
- spkmap = []
- for i in range(n_speakers_mix):
- spkmap.append(self.emb_g(torch.LongTensor([[i]])).transpose(1, 2).detach().numpy())
- self.speaker_map = torch.tensor(spkmap)
- self.export_mix = True
-
- def forward(self, c, f0, mel2ph, uv, noise=None, g=None, cluster_infer_ratio=0.1):
-
- decoder_inp = F.pad(c, [0, 0, 1, 0])
- mel2ph_ = mel2ph.unsqueeze(2).repeat([1, 1, c.shape[-1]])
- c = torch.gather(decoder_inp, 1, mel2ph_).transpose(1, 2) # [B, T, H]
-
- if self.cluster_model is not None:
- predict = self.cluster_model[speaker].predict(c.transpose(0, 1))
- model[speaker].cluster_centers_[predict]
- cluster_c = cluster.get_cluster_center_result(self.cluster_model, c.cpu().numpy().T, speaker).T
- cluster_c = torch.FloatTensor(cluster_c).to(self.dev)
- c = cluster_infer_ratio * cluster_c + (1 - cluster_infer_ratio) * c
-
- c_lengths = (torch.ones(c.size(0)) * c.size(-1)).to(c.device)
-
- if self.export_mix:
- spk_mix = spk_mix.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)
- g = torch.sum(spk_mix * self.speaker_map, dim=0).transpose(1, 2)
- else:
- g = g.unsqueeze(0)
- g = self.emb_g(g).transpose(1, 2)
-
-
- x_mask = torch.unsqueeze(commons.sequence_mask(c_lengths, c.size(2)), 1).to(c.dtype)
- x = self.pre(c) * x_mask + self.emb_uv(uv.long()).transpose(1, 2)
-
- if self.predict_f0:
- lf0 = 2595. * torch.log10(1. + f0.unsqueeze(1) / 700.) / 500
- norm_lf0 = utils.normalize_f0(lf0, x_mask, uv, random_scale=False)
- pred_lf0 = self.f0_decoder(x, norm_lf0, x_mask, spk_emb=g)
- f0 = (700 * (torch.pow(10, pred_lf0 * 500 / 2595) - 1)).squeeze(1)
-
- z_p, m_p, logs_p, c_mask = self.enc_p(x, x_mask, f0=f0_to_coarse(f0), z=noise)
- z = self.flow(z_p, c_mask, g=g, reverse=True)
- o = self.dec(z * c_mask, g=g, f0=f0)
- return o
diff --git a/spaces/Alpaca233/SadTalker/src/face3d/models/arcface_torch/backbones/__init__.py b/spaces/Alpaca233/SadTalker/src/face3d/models/arcface_torch/backbones/__init__.py
deleted file mode 100644
index 55bd4c5d1889a1a998b52eb56793bbc1eef1b691..0000000000000000000000000000000000000000
--- a/spaces/Alpaca233/SadTalker/src/face3d/models/arcface_torch/backbones/__init__.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from .iresnet import iresnet18, iresnet34, iresnet50, iresnet100, iresnet200
-from .mobilefacenet import get_mbf
-
-
-def get_model(name, **kwargs):
- # resnet
- if name == "r18":
- return iresnet18(False, **kwargs)
- elif name == "r34":
- return iresnet34(False, **kwargs)
- elif name == "r50":
- return iresnet50(False, **kwargs)
- elif name == "r100":
- return iresnet100(False, **kwargs)
- elif name == "r200":
- return iresnet200(False, **kwargs)
- elif name == "r2060":
- from .iresnet2060 import iresnet2060
- return iresnet2060(False, **kwargs)
- elif name == "mbf":
- fp16 = kwargs.get("fp16", False)
- num_features = kwargs.get("num_features", 512)
- return get_mbf(fp16=fp16, num_features=num_features)
- else:
- raise ValueError()
\ No newline at end of file
diff --git a/spaces/Alpaca233/SadTalker/src/facerender/modules/dense_motion.py b/spaces/Alpaca233/SadTalker/src/facerender/modules/dense_motion.py
deleted file mode 100644
index a286ead2e84ed1961335d34a3b50ab38f25e4495..0000000000000000000000000000000000000000
--- a/spaces/Alpaca233/SadTalker/src/facerender/modules/dense_motion.py
+++ /dev/null
@@ -1,121 +0,0 @@
-from torch import nn
-import torch.nn.functional as F
-import torch
-from src.facerender.modules.util import Hourglass, make_coordinate_grid, kp2gaussian
-
-from src.facerender.sync_batchnorm import SynchronizedBatchNorm3d as BatchNorm3d
-
-
-class DenseMotionNetwork(nn.Module):
- """
- Module that predicting a dense motion from sparse motion representation given by kp_source and kp_driving
- """
-
- def __init__(self, block_expansion, num_blocks, max_features, num_kp, feature_channel, reshape_depth, compress,
- estimate_occlusion_map=False):
- super(DenseMotionNetwork, self).__init__()
- # self.hourglass = Hourglass(block_expansion=block_expansion, in_features=(num_kp+1)*(feature_channel+1), max_features=max_features, num_blocks=num_blocks)
- self.hourglass = Hourglass(block_expansion=block_expansion, in_features=(num_kp+1)*(compress+1), max_features=max_features, num_blocks=num_blocks)
-
- self.mask = nn.Conv3d(self.hourglass.out_filters, num_kp + 1, kernel_size=7, padding=3)
-
- self.compress = nn.Conv3d(feature_channel, compress, kernel_size=1)
- self.norm = BatchNorm3d(compress, affine=True)
-
- if estimate_occlusion_map:
- # self.occlusion = nn.Conv2d(reshape_channel*reshape_depth, 1, kernel_size=7, padding=3)
- self.occlusion = nn.Conv2d(self.hourglass.out_filters*reshape_depth, 1, kernel_size=7, padding=3)
- else:
- self.occlusion = None
-
- self.num_kp = num_kp
-
-
- def create_sparse_motions(self, feature, kp_driving, kp_source):
- bs, _, d, h, w = feature.shape
- identity_grid = make_coordinate_grid((d, h, w), type=kp_source['value'].type())
- identity_grid = identity_grid.view(1, 1, d, h, w, 3)
- coordinate_grid = identity_grid - kp_driving['value'].view(bs, self.num_kp, 1, 1, 1, 3)
-
- # if 'jacobian' in kp_driving:
- if 'jacobian' in kp_driving and kp_driving['jacobian'] is not None:
- jacobian = torch.matmul(kp_source['jacobian'], torch.inverse(kp_driving['jacobian']))
- jacobian = jacobian.unsqueeze(-3).unsqueeze(-3).unsqueeze(-3)
- jacobian = jacobian.repeat(1, 1, d, h, w, 1, 1)
- coordinate_grid = torch.matmul(jacobian, coordinate_grid.unsqueeze(-1))
- coordinate_grid = coordinate_grid.squeeze(-1)
-
-
- driving_to_source = coordinate_grid + kp_source['value'].view(bs, self.num_kp, 1, 1, 1, 3) # (bs, num_kp, d, h, w, 3)
-
- #adding background feature
- identity_grid = identity_grid.repeat(bs, 1, 1, 1, 1, 1)
- sparse_motions = torch.cat([identity_grid, driving_to_source], dim=1) #bs num_kp+1 d h w 3
-
- # sparse_motions = driving_to_source
-
- return sparse_motions
-
- def create_deformed_feature(self, feature, sparse_motions):
- bs, _, d, h, w = feature.shape
- feature_repeat = feature.unsqueeze(1).unsqueeze(1).repeat(1, self.num_kp+1, 1, 1, 1, 1, 1) # (bs, num_kp+1, 1, c, d, h, w)
- feature_repeat = feature_repeat.view(bs * (self.num_kp+1), -1, d, h, w) # (bs*(num_kp+1), c, d, h, w)
- sparse_motions = sparse_motions.view((bs * (self.num_kp+1), d, h, w, -1)) # (bs*(num_kp+1), d, h, w, 3) !!!!
- sparse_deformed = F.grid_sample(feature_repeat, sparse_motions)
- sparse_deformed = sparse_deformed.view((bs, self.num_kp+1, -1, d, h, w)) # (bs, num_kp+1, c, d, h, w)
- return sparse_deformed
-
- def create_heatmap_representations(self, feature, kp_driving, kp_source):
- spatial_size = feature.shape[3:]
- gaussian_driving = kp2gaussian(kp_driving, spatial_size=spatial_size, kp_variance=0.01)
- gaussian_source = kp2gaussian(kp_source, spatial_size=spatial_size, kp_variance=0.01)
- heatmap = gaussian_driving - gaussian_source
-
- # adding background feature
- zeros = torch.zeros(heatmap.shape[0], 1, spatial_size[0], spatial_size[1], spatial_size[2]).type(heatmap.type())
- heatmap = torch.cat([zeros, heatmap], dim=1)
- heatmap = heatmap.unsqueeze(2) # (bs, num_kp+1, 1, d, h, w)
- return heatmap
-
- def forward(self, feature, kp_driving, kp_source):
- bs, _, d, h, w = feature.shape
-
- feature = self.compress(feature)
- feature = self.norm(feature)
- feature = F.relu(feature)
-
- out_dict = dict()
- sparse_motion = self.create_sparse_motions(feature, kp_driving, kp_source)
- deformed_feature = self.create_deformed_feature(feature, sparse_motion)
-
- heatmap = self.create_heatmap_representations(deformed_feature, kp_driving, kp_source)
-
- input_ = torch.cat([heatmap, deformed_feature], dim=2)
- input_ = input_.view(bs, -1, d, h, w)
-
- # input = deformed_feature.view(bs, -1, d, h, w) # (bs, num_kp+1 * c, d, h, w)
-
- prediction = self.hourglass(input_)
-
-
- mask = self.mask(prediction)
- mask = F.softmax(mask, dim=1)
- out_dict['mask'] = mask
- mask = mask.unsqueeze(2) # (bs, num_kp+1, 1, d, h, w)
-
- zeros_mask = torch.zeros_like(mask)
- mask = torch.where(mask < 1e-3, zeros_mask, mask)
-
- sparse_motion = sparse_motion.permute(0, 1, 5, 2, 3, 4) # (bs, num_kp+1, 3, d, h, w)
- deformation = (sparse_motion * mask).sum(dim=1) # (bs, 3, d, h, w)
- deformation = deformation.permute(0, 2, 3, 4, 1) # (bs, d, h, w, 3)
-
- out_dict['deformation'] = deformation
-
- if self.occlusion:
- bs, c, d, h, w = prediction.shape
- prediction = prediction.view(bs, -1, h, w)
- occlusion_map = torch.sigmoid(self.occlusion(prediction))
- out_dict['occlusion_map'] = occlusion_map
-
- return out_dict
diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/schedulers/repaint.md b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/schedulers/repaint.md
deleted file mode 100644
index b7e2bcf119c12ce63fde95a2c5c689bb97da8db5..0000000000000000000000000000000000000000
--- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/schedulers/repaint.md
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-# RePaint scheduler
-
-## Overview
-
-DDPM-based inpainting scheduler for unsupervised inpainting with extreme masks.
-Intended for use with [`RePaintPipeline`].
-Based on the paper [RePaint: Inpainting using Denoising Diffusion Probabilistic Models](https://arxiv.org/abs/2201.09865)
-and the original implementation by Andreas Lugmayr et al.: https://github.com/andreas128/RePaint
-
-## RePaintScheduler
-[[autodoc]] RePaintScheduler
\ No newline at end of file
diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/using-diffusers/reusing_seeds.md b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/using-diffusers/reusing_seeds.md
deleted file mode 100644
index 1ff84f02596ecc9cdfee2b0865d8d6a6ef34ce2e..0000000000000000000000000000000000000000
--- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/using-diffusers/reusing_seeds.md
+++ /dev/null
@@ -1,65 +0,0 @@
-
-
-# Improve image quality with deterministic generation
-
-[[open-in-colab]]
-
-A common way to improve the quality of generated images is with *deterministic batch generation*, generate a batch of images and select one image to improve with a more detailed prompt in a second round of inference. The key is to pass a list of [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html#generator)'s to the pipeline for batched image generation, and tie each `Generator` to a seed so you can reuse it for an image.
-
-Let's use [`runwayml/stable-diffusion-v1-5`](runwayml/stable-diffusion-v1-5) for example, and generate several versions of the following prompt:
-
-```py
-prompt = "Labrador in the style of Vermeer"
-```
-
-Instantiate a pipeline with [`DiffusionPipeline.from_pretrained`] and place it on a GPU (if available):
-
-```python
->>> from diffusers import DiffusionPipeline
-
->>> pipe = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
->>> pipe = pipe.to("cuda")
-```
-
-Now, define four different `Generator`'s and assign each `Generator` a seed (`0` to `3`) so you can reuse a `Generator` later for a specific image:
-
-```python
->>> import torch
-
->>> generator = [torch.Generator(device="cuda").manual_seed(i) for i in range(4)]
-```
-
-Generate the images and have a look:
-
-```python
->>> images = pipe(prompt, generator=generator, num_images_per_prompt=4).images
->>> images
-```
-
-
-
-In this example, you'll improve upon the first image - but in reality, you can use any image you want (even the image with double sets of eyes!). The first image used the `Generator` with seed `0`, so you'll reuse that `Generator` for the second round of inference. To improve the quality of the image, add some additional text to the prompt:
-
-```python
-prompt = [prompt + t for t in [", highly realistic", ", artsy", ", trending", ", colorful"]]
-generator = [torch.Generator(device="cuda").manual_seed(0) for i in range(4)]
-```
-
-Create four generators with seed `0`, and generate another batch of images, all of which should look like the first image from the previous round!
-
-```python
->>> images = pipe(prompt, generator=generator).images
->>> images
-```
-
-
diff --git a/spaces/Andy1621/uniformer_image_detection/configs/foveabox/fovea_align_r50_fpn_gn-head_mstrain_640-800_4x4_2x_coco.py b/spaces/Andy1621/uniformer_image_detection/configs/foveabox/fovea_align_r50_fpn_gn-head_mstrain_640-800_4x4_2x_coco.py
deleted file mode 100644
index 8fc39beaac540a8d3e00bf968f1af08450f9d4cc..0000000000000000000000000000000000000000
--- a/spaces/Andy1621/uniformer_image_detection/configs/foveabox/fovea_align_r50_fpn_gn-head_mstrain_640-800_4x4_2x_coco.py
+++ /dev/null
@@ -1,25 +0,0 @@
-_base_ = './fovea_r50_fpn_4x4_1x_coco.py'
-model = dict(
- bbox_head=dict(
- with_deform=True,
- norm_cfg=dict(type='GN', num_groups=32, requires_grad=True)))
-img_norm_cfg = dict(
- mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
-train_pipeline = [
- dict(type='LoadImageFromFile'),
- dict(type='LoadAnnotations', with_bbox=True),
- dict(
- type='Resize',
- img_scale=[(1333, 640), (1333, 800)],
- multiscale_mode='value',
- 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']),
-]
-data = dict(train=dict(pipeline=train_pipeline))
-# learning policy
-lr_config = dict(step=[16, 22])
-runner = dict(type='EpochBasedRunner', max_epochs=24)
diff --git a/spaces/Andy1621/uniformer_image_segmentation/configs/gcnet/gcnet_r101-d8_512x512_40k_voc12aug.py b/spaces/Andy1621/uniformer_image_segmentation/configs/gcnet/gcnet_r101-d8_512x512_40k_voc12aug.py
deleted file mode 100644
index b17c7a12b547ee4e1cd60d667c575eab06eb071c..0000000000000000000000000000000000000000
--- a/spaces/Andy1621/uniformer_image_segmentation/configs/gcnet/gcnet_r101-d8_512x512_40k_voc12aug.py
+++ /dev/null
@@ -1,2 +0,0 @@
-_base_ = './gcnet_r50-d8_512x512_40k_voc12aug.py'
-model = dict(pretrained='open-mmlab://resnet101_v1c', backbone=dict(depth=101))
diff --git a/spaces/AnimalEquality/chatbot/setup.py b/spaces/AnimalEquality/chatbot/setup.py
deleted file mode 100644
index e3281ae9bd7b98568e77014dba1b7b353d409205..0000000000000000000000000000000000000000
--- a/spaces/AnimalEquality/chatbot/setup.py
+++ /dev/null
@@ -1,57 +0,0 @@
-from pkg_resources import parse_version
-from configparser import ConfigParser
-import setuptools, shlex
-assert parse_version(setuptools.__version__)>=parse_version('36.2')
-
-# note: all settings are in settings.ini; edit there, not here
-config = ConfigParser(delimiters=['='])
-config.read('settings.ini', encoding='utf-8')
-cfg = config['DEFAULT']
-
-cfg_keys = 'version description keywords author author_email'.split()
-expected = cfg_keys + "lib_name user branch license status min_python audience language".split()
-for o in expected: assert o in cfg, "missing expected setting: {}".format(o)
-setup_cfg = {o:cfg[o] for o in cfg_keys}
-
-licenses = {
- 'apache2': ('Apache Software License 2.0','OSI Approved :: Apache Software License'),
- 'mit': ('MIT License', 'OSI Approved :: MIT License'),
- 'gpl2': ('GNU General Public License v2', 'OSI Approved :: GNU General Public License v2 (GPLv2)'),
- 'gpl3': ('GNU General Public License v3', 'OSI Approved :: GNU General Public License v3 (GPLv3)'),
- 'bsd3': ('BSD License', 'OSI Approved :: BSD License'),
-}
-statuses = [ '1 - Planning', '2 - Pre-Alpha', '3 - Alpha',
- '4 - Beta', '5 - Production/Stable', '6 - Mature', '7 - Inactive' ]
-py_versions = '3.6 3.7 3.8 3.9 3.10'.split()
-
-requirements = shlex.split(cfg.get('requirements', ''))
-if cfg.get('pip_requirements'): requirements += shlex.split(cfg.get('pip_requirements', ''))
-min_python = cfg['min_python']
-lic = licenses.get(cfg['license'].lower(), (cfg['license'], None))
-dev_requirements = (cfg.get('dev_requirements') or '').split()
-
-setuptools.setup(
- name = cfg['lib_name'],
- license = lic[0],
- classifiers = [
- 'Development Status :: ' + statuses[int(cfg['status'])],
- 'Intended Audience :: ' + cfg['audience'].title(),
- 'Natural Language :: ' + cfg['language'].title(),
- ] + ['Programming Language :: Python :: '+o for o in py_versions[py_versions.index(min_python):]] + (['License :: ' + lic[1] ] if lic[1] else []),
- url = cfg['git_url'],
- packages = setuptools.find_packages(),
- include_package_data = True,
- install_requires = requirements,
- extras_require={ 'dev': dev_requirements },
- dependency_links = cfg.get('dep_links','').split(),
- python_requires = '>=' + cfg['min_python'],
- long_description = open('README.md', encoding='utf-8').read(),
- long_description_content_type = 'text/markdown',
- zip_safe = False,
- entry_points = {
- 'console_scripts': cfg.get('console_scripts','').split(),
- 'nbdev': [f'{cfg.get("lib_path")}={cfg.get("lib_path")}._modidx:d']
- },
- **setup_cfg)
-
-
diff --git a/spaces/AnnasBlackHat/Image-Downloader/README.md b/spaces/AnnasBlackHat/Image-Downloader/README.md
deleted file mode 100644
index 107f5f376c58d03a1d5059613dba4542c2a435b0..0000000000000000000000000000000000000000
--- a/spaces/AnnasBlackHat/Image-Downloader/README.md
+++ /dev/null
@@ -1,12 +0,0 @@
----
-title: Image Downloader
-emoji: 🐠
-colorFrom: green
-colorTo: red
-sdk: gradio
-sdk_version: 3.1.7
-app_file: app.py
-pinned: false
----
-
-Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/urllib3/fields.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/urllib3/fields.py
deleted file mode 100644
index 9d630f491d9a39644ae65564dac88eb51f0bbe78..0000000000000000000000000000000000000000
--- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/urllib3/fields.py
+++ /dev/null
@@ -1,274 +0,0 @@
-from __future__ import absolute_import
-
-import email.utils
-import mimetypes
-import re
-
-from .packages import six
-
-
-def guess_content_type(filename, default="application/octet-stream"):
- """
- Guess the "Content-Type" of a file.
-
- :param filename:
- The filename to guess the "Content-Type" of using :mod:`mimetypes`.
- :param default:
- If no "Content-Type" can be guessed, default to `default`.
- """
- if filename:
- return mimetypes.guess_type(filename)[0] or default
- return default
-
-
-def format_header_param_rfc2231(name, value):
- """
- Helper function to format and quote a single header parameter using the
- strategy defined in RFC 2231.
-
- Particularly useful for header parameters which might contain
- non-ASCII values, like file names. This follows
- `RFC 2388 Section 4.4 `_.
-
- :param name:
- The name of the parameter, a string expected to be ASCII only.
- :param value:
- The value of the parameter, provided as ``bytes`` or `str``.
- :ret:
- An RFC-2231-formatted unicode string.
- """
- if isinstance(value, six.binary_type):
- value = value.decode("utf-8")
-
- if not any(ch in value for ch in '"\\\r\n'):
- result = u'%s="%s"' % (name, value)
- try:
- result.encode("ascii")
- except (UnicodeEncodeError, UnicodeDecodeError):
- pass
- else:
- return result
-
- if six.PY2: # Python 2:
- value = value.encode("utf-8")
-
- # encode_rfc2231 accepts an encoded string and returns an ascii-encoded
- # string in Python 2 but accepts and returns unicode strings in Python 3
- value = email.utils.encode_rfc2231(value, "utf-8")
- value = "%s*=%s" % (name, value)
-
- if six.PY2: # Python 2:
- value = value.decode("utf-8")
-
- return value
-
-
-_HTML5_REPLACEMENTS = {
- u"\u0022": u"%22",
- # Replace "\" with "\\".
- u"\u005C": u"\u005C\u005C",
-}
-
-# All control characters from 0x00 to 0x1F *except* 0x1B.
-_HTML5_REPLACEMENTS.update(
- {
- six.unichr(cc): u"%{:02X}".format(cc)
- for cc in range(0x00, 0x1F + 1)
- if cc not in (0x1B,)
- }
-)
-
-
-def _replace_multiple(value, needles_and_replacements):
- def replacer(match):
- return needles_and_replacements[match.group(0)]
-
- pattern = re.compile(
- r"|".join([re.escape(needle) for needle in needles_and_replacements.keys()])
- )
-
- result = pattern.sub(replacer, value)
-
- return result
-
-
-def format_header_param_html5(name, value):
- """
- Helper function to format and quote a single header parameter using the
- HTML5 strategy.
-
- Particularly useful for header parameters which might contain
- non-ASCII values, like file names. This follows the `HTML5 Working Draft
- Section 4.10.22.7`_ and matches the behavior of curl and modern browsers.
-
- .. _HTML5 Working Draft Section 4.10.22.7:
- https://w3c.github.io/html/sec-forms.html#multipart-form-data
-
- :param name:
- The name of the parameter, a string expected to be ASCII only.
- :param value:
- The value of the parameter, provided as ``bytes`` or `str``.
- :ret:
- A unicode string, stripped of troublesome characters.
- """
- if isinstance(value, six.binary_type):
- value = value.decode("utf-8")
-
- value = _replace_multiple(value, _HTML5_REPLACEMENTS)
-
- return u'%s="%s"' % (name, value)
-
-
-# For backwards-compatibility.
-format_header_param = format_header_param_html5
-
-
-class RequestField(object):
- """
- A data container for request body parameters.
-
- :param name:
- The name of this request field. Must be unicode.
- :param data:
- The data/value body.
- :param filename:
- An optional filename of the request field. Must be unicode.
- :param headers:
- An optional dict-like object of headers to initially use for the field.
- :param header_formatter:
- An optional callable that is used to encode and format the headers. By
- default, this is :func:`format_header_param_html5`.
- """
-
- def __init__(
- self,
- name,
- data,
- filename=None,
- headers=None,
- header_formatter=format_header_param_html5,
- ):
- self._name = name
- self._filename = filename
- self.data = data
- self.headers = {}
- if headers:
- self.headers = dict(headers)
- self.header_formatter = header_formatter
-
- @classmethod
- def from_tuples(cls, fieldname, value, header_formatter=format_header_param_html5):
- """
- A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.
-
- Supports constructing :class:`~urllib3.fields.RequestField` from
- parameter of key/value strings AND key/filetuple. A filetuple is a
- (filename, data, MIME type) tuple where the MIME type is optional.
- For example::
-
- 'foo': 'bar',
- 'fakefile': ('foofile.txt', 'contents of foofile'),
- 'realfile': ('barfile.txt', open('realfile').read()),
- 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'),
- 'nonamefile': 'contents of nonamefile field',
-
- Field names and filenames must be unicode.
- """
- if isinstance(value, tuple):
- if len(value) == 3:
- filename, data, content_type = value
- else:
- filename, data = value
- content_type = guess_content_type(filename)
- else:
- filename = None
- content_type = None
- data = value
-
- request_param = cls(
- fieldname, data, filename=filename, header_formatter=header_formatter
- )
- request_param.make_multipart(content_type=content_type)
-
- return request_param
-
- def _render_part(self, name, value):
- """
- Overridable helper function to format a single header parameter. By
- default, this calls ``self.header_formatter``.
-
- :param name:
- The name of the parameter, a string expected to be ASCII only.
- :param value:
- The value of the parameter, provided as a unicode string.
- """
-
- return self.header_formatter(name, value)
-
- def _render_parts(self, header_parts):
- """
- Helper function to format and quote a single header.
-
- Useful for single headers that are composed of multiple items. E.g.,
- 'Content-Disposition' fields.
-
- :param header_parts:
- A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format
- as `k1="v1"; k2="v2"; ...`.
- """
- parts = []
- iterable = header_parts
- if isinstance(header_parts, dict):
- iterable = header_parts.items()
-
- for name, value in iterable:
- if value is not None:
- parts.append(self._render_part(name, value))
-
- return u"; ".join(parts)
-
- def render_headers(self):
- """
- Renders the headers for this request field.
- """
- lines = []
-
- sort_keys = ["Content-Disposition", "Content-Type", "Content-Location"]
- for sort_key in sort_keys:
- if self.headers.get(sort_key, False):
- lines.append(u"%s: %s" % (sort_key, self.headers[sort_key]))
-
- for header_name, header_value in self.headers.items():
- if header_name not in sort_keys:
- if header_value:
- lines.append(u"%s: %s" % (header_name, header_value))
-
- lines.append(u"\r\n")
- return u"\r\n".join(lines)
-
- def make_multipart(
- self, content_disposition=None, content_type=None, content_location=None
- ):
- """
- Makes this request field into a multipart request field.
-
- This method overrides "Content-Disposition", "Content-Type" and
- "Content-Location" headers to the request parameter.
-
- :param content_type:
- The 'Content-Type' of the request body.
- :param content_location:
- The 'Content-Location' of the request body.
-
- """
- self.headers["Content-Disposition"] = content_disposition or u"form-data"
- self.headers["Content-Disposition"] += u"; ".join(
- [
- u"",
- self._render_parts(
- ((u"name", self._name), (u"filename", self._filename))
- ),
- ]
- )
- self.headers["Content-Type"] = content_type
- self.headers["Content-Location"] = content_location
diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pkg_resources/__init__.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pkg_resources/__init__.py
deleted file mode 100644
index d59226af9d7fe1b5279e99ff6e333032d1cec274..0000000000000000000000000000000000000000
--- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pkg_resources/__init__.py
+++ /dev/null
@@ -1,3296 +0,0 @@
-"""
-Package resource API
---------------------
-
-A resource is a logical file contained within a package, or a logical
-subdirectory thereof. The package resource API expects resource names
-to have their path parts separated with ``/``, *not* whatever the local
-path separator is. Do not use os.path operations to manipulate resource
-names being passed into the API.
-
-The package resource API is designed to work with normal filesystem packages,
-.egg files, and unpacked .egg files. It can also work in a limited way with
-.zip files and with custom PEP 302 loaders that support the ``get_data()``
-method.
-"""
-
-import sys
-import os
-import io
-import time
-import re
-import types
-import zipfile
-import zipimport
-import warnings
-import stat
-import functools
-import pkgutil
-import operator
-import platform
-import collections
-import plistlib
-import email.parser
-import errno
-import tempfile
-import textwrap
-import itertools
-import inspect
-import ntpath
-import posixpath
-import importlib
-from pkgutil import get_importer
-
-try:
- import _imp
-except ImportError:
- # Python 3.2 compatibility
- import imp as _imp
-
-try:
- FileExistsError
-except NameError:
- FileExistsError = OSError
-
-# capture these to bypass sandboxing
-from os import utime
-try:
- from os import mkdir, rename, unlink
- WRITE_SUPPORT = True
-except ImportError:
- # no write support, probably under GAE
- WRITE_SUPPORT = False
-
-from os import open as os_open
-from os.path import isdir, split
-
-try:
- import importlib.machinery as importlib_machinery
- # access attribute to force import under delayed import mechanisms.
- importlib_machinery.__name__
-except ImportError:
- importlib_machinery = None
-
-from pkg_resources.extern.jaraco.text import (
- yield_lines,
- drop_comment,
- join_continuation,
-)
-
-from pkg_resources.extern import appdirs
-from pkg_resources.extern import packaging
-__import__('pkg_resources.extern.packaging.version')
-__import__('pkg_resources.extern.packaging.specifiers')
-__import__('pkg_resources.extern.packaging.requirements')
-__import__('pkg_resources.extern.packaging.markers')
-__import__('pkg_resources.extern.packaging.utils')
-
-if sys.version_info < (3, 5):
- raise RuntimeError("Python 3.5 or later is required")
-
-# declare some globals that will be defined later to
-# satisfy the linters.
-require = None
-working_set = None
-add_activation_listener = None
-resources_stream = None
-cleanup_resources = None
-resource_dir = None
-resource_stream = None
-set_extraction_path = None
-resource_isdir = None
-resource_string = None
-iter_entry_points = None
-resource_listdir = None
-resource_filename = None
-resource_exists = None
-_distribution_finders = None
-_namespace_handlers = None
-_namespace_packages = None
-
-
-class PEP440Warning(RuntimeWarning):
- """
- Used when there is an issue with a version or specifier not complying with
- PEP 440.
- """
-
-
-def parse_version(v):
- try:
- return packaging.version.Version(v)
- except packaging.version.InvalidVersion:
- warnings.warn(
- f"{v} is an invalid version and will not be supported in "
- "a future release",
- PkgResourcesDeprecationWarning,
- )
- return packaging.version.LegacyVersion(v)
-
-
-_state_vars = {}
-
-
-def _declare_state(vartype, **kw):
- globals().update(kw)
- _state_vars.update(dict.fromkeys(kw, vartype))
-
-
-def __getstate__():
- state = {}
- g = globals()
- for k, v in _state_vars.items():
- state[k] = g['_sget_' + v](g[k])
- return state
-
-
-def __setstate__(state):
- g = globals()
- for k, v in state.items():
- g['_sset_' + _state_vars[k]](k, g[k], v)
- return state
-
-
-def _sget_dict(val):
- return val.copy()
-
-
-def _sset_dict(key, ob, state):
- ob.clear()
- ob.update(state)
-
-
-def _sget_object(val):
- return val.__getstate__()
-
-
-def _sset_object(key, ob, state):
- ob.__setstate__(state)
-
-
-_sget_none = _sset_none = lambda *args: None
-
-
-def get_supported_platform():
- """Return this platform's maximum compatible version.
-
- distutils.util.get_platform() normally reports the minimum version
- of macOS that would be required to *use* extensions produced by
- distutils. But what we want when checking compatibility is to know the
- version of macOS that we are *running*. To allow usage of packages that
- explicitly require a newer version of macOS, we must also know the
- current version of the OS.
-
- If this condition occurs for any other platform with a version in its
- platform strings, this function should be extended accordingly.
- """
- plat = get_build_platform()
- m = macosVersionString.match(plat)
- if m is not None and sys.platform == "darwin":
- try:
- plat = 'macosx-%s-%s' % ('.'.join(_macos_vers()[:2]), m.group(3))
- except ValueError:
- # not macOS
- pass
- return plat
-
-
-__all__ = [
- # Basic resource access and distribution/entry point discovery
- 'require', 'run_script', 'get_provider', 'get_distribution',
- 'load_entry_point', 'get_entry_map', 'get_entry_info',
- 'iter_entry_points',
- 'resource_string', 'resource_stream', 'resource_filename',
- 'resource_listdir', 'resource_exists', 'resource_isdir',
-
- # Environmental control
- 'declare_namespace', 'working_set', 'add_activation_listener',
- 'find_distributions', 'set_extraction_path', 'cleanup_resources',
- 'get_default_cache',
-
- # Primary implementation classes
- 'Environment', 'WorkingSet', 'ResourceManager',
- 'Distribution', 'Requirement', 'EntryPoint',
-
- # Exceptions
- 'ResolutionError', 'VersionConflict', 'DistributionNotFound',
- 'UnknownExtra', 'ExtractionError',
-
- # Warnings
- 'PEP440Warning',
-
- # Parsing functions and string utilities
- 'parse_requirements', 'parse_version', 'safe_name', 'safe_version',
- 'get_platform', 'compatible_platforms', 'yield_lines', 'split_sections',
- 'safe_extra', 'to_filename', 'invalid_marker', 'evaluate_marker',
-
- # filesystem utilities
- 'ensure_directory', 'normalize_path',
-
- # Distribution "precedence" constants
- 'EGG_DIST', 'BINARY_DIST', 'SOURCE_DIST', 'CHECKOUT_DIST', 'DEVELOP_DIST',
-
- # "Provider" interfaces, implementations, and registration/lookup APIs
- 'IMetadataProvider', 'IResourceProvider', 'FileMetadata',
- 'PathMetadata', 'EggMetadata', 'EmptyProvider', 'empty_provider',
- 'NullProvider', 'EggProvider', 'DefaultProvider', 'ZipProvider',
- 'register_finder', 'register_namespace_handler', 'register_loader_type',
- 'fixup_namespace_packages', 'get_importer',
-
- # Warnings
- 'PkgResourcesDeprecationWarning',
-
- # Deprecated/backward compatibility only
- 'run_main', 'AvailableDistributions',
-]
-
-
-class ResolutionError(Exception):
- """Abstract base for dependency resolution errors"""
-
- def __repr__(self):
- return self.__class__.__name__ + repr(self.args)
-
-
-class VersionConflict(ResolutionError):
- """
- An already-installed version conflicts with the requested version.
-
- Should be initialized with the installed Distribution and the requested
- Requirement.
- """
-
- _template = "{self.dist} is installed but {self.req} is required"
-
- @property
- def dist(self):
- return self.args[0]
-
- @property
- def req(self):
- return self.args[1]
-
- def report(self):
- return self._template.format(**locals())
-
- def with_context(self, required_by):
- """
- If required_by is non-empty, return a version of self that is a
- ContextualVersionConflict.
- """
- if not required_by:
- return self
- args = self.args + (required_by,)
- return ContextualVersionConflict(*args)
-
-
-class ContextualVersionConflict(VersionConflict):
- """
- A VersionConflict that accepts a third parameter, the set of the
- requirements that required the installed Distribution.
- """
-
- _template = VersionConflict._template + ' by {self.required_by}'
-
- @property
- def required_by(self):
- return self.args[2]
-
-
-class DistributionNotFound(ResolutionError):
- """A requested distribution was not found"""
-
- _template = ("The '{self.req}' distribution was not found "
- "and is required by {self.requirers_str}")
-
- @property
- def req(self):
- return self.args[0]
-
- @property
- def requirers(self):
- return self.args[1]
-
- @property
- def requirers_str(self):
- if not self.requirers:
- return 'the application'
- return ', '.join(self.requirers)
-
- def report(self):
- return self._template.format(**locals())
-
- def __str__(self):
- return self.report()
-
-
-class UnknownExtra(ResolutionError):
- """Distribution doesn't have an "extra feature" of the given name"""
-
-
-_provider_factories = {}
-
-PY_MAJOR = '{}.{}'.format(*sys.version_info)
-EGG_DIST = 3
-BINARY_DIST = 2
-SOURCE_DIST = 1
-CHECKOUT_DIST = 0
-DEVELOP_DIST = -1
-
-
-def register_loader_type(loader_type, provider_factory):
- """Register `provider_factory` to make providers for `loader_type`
-
- `loader_type` is the type or class of a PEP 302 ``module.__loader__``,
- and `provider_factory` is a function that, passed a *module* object,
- returns an ``IResourceProvider`` for that module.
- """
- _provider_factories[loader_type] = provider_factory
-
-
-def get_provider(moduleOrReq):
- """Return an IResourceProvider for the named module or requirement"""
- if isinstance(moduleOrReq, Requirement):
- return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
- try:
- module = sys.modules[moduleOrReq]
- except KeyError:
- __import__(moduleOrReq)
- module = sys.modules[moduleOrReq]
- loader = getattr(module, '__loader__', None)
- return _find_adapter(_provider_factories, loader)(module)
-
-
-def _macos_vers(_cache=[]):
- if not _cache:
- version = platform.mac_ver()[0]
- # fallback for MacPorts
- if version == '':
- plist = '/System/Library/CoreServices/SystemVersion.plist'
- if os.path.exists(plist):
- if hasattr(plistlib, 'readPlist'):
- plist_content = plistlib.readPlist(plist)
- if 'ProductVersion' in plist_content:
- version = plist_content['ProductVersion']
-
- _cache.append(version.split('.'))
- return _cache[0]
-
-
-def _macos_arch(machine):
- return {'PowerPC': 'ppc', 'Power_Macintosh': 'ppc'}.get(machine, machine)
-
-
-def get_build_platform():
- """Return this platform's string for platform-specific distributions
-
- XXX Currently this is the same as ``distutils.util.get_platform()``, but it
- needs some hacks for Linux and macOS.
- """
- from sysconfig import get_platform
-
- plat = get_platform()
- if sys.platform == "darwin" and not plat.startswith('macosx-'):
- try:
- version = _macos_vers()
- machine = os.uname()[4].replace(" ", "_")
- return "macosx-%d.%d-%s" % (
- int(version[0]), int(version[1]),
- _macos_arch(machine),
- )
- except ValueError:
- # if someone is running a non-Mac darwin system, this will fall
- # through to the default implementation
- pass
- return plat
-
-
-macosVersionString = re.compile(r"macosx-(\d+)\.(\d+)-(.*)")
-darwinVersionString = re.compile(r"darwin-(\d+)\.(\d+)\.(\d+)-(.*)")
-# XXX backward compat
-get_platform = get_build_platform
-
-
-def compatible_platforms(provided, required):
- """Can code for the `provided` platform run on the `required` platform?
-
- Returns true if either platform is ``None``, or the platforms are equal.
-
- XXX Needs compatibility checks for Linux and other unixy OSes.
- """
- if provided is None or required is None or provided == required:
- # easy case
- return True
-
- # macOS special cases
- reqMac = macosVersionString.match(required)
- if reqMac:
- provMac = macosVersionString.match(provided)
-
- # is this a Mac package?
- if not provMac:
- # this is backwards compatibility for packages built before
- # setuptools 0.6. All packages built after this point will
- # use the new macOS designation.
- provDarwin = darwinVersionString.match(provided)
- if provDarwin:
- dversion = int(provDarwin.group(1))
- macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2))
- if dversion == 7 and macosversion >= "10.3" or \
- dversion == 8 and macosversion >= "10.4":
- return True
- # egg isn't macOS or legacy darwin
- return False
-
- # are they the same major version and machine type?
- if provMac.group(1) != reqMac.group(1) or \
- provMac.group(3) != reqMac.group(3):
- return False
-
- # is the required OS major update >= the provided one?
- if int(provMac.group(2)) > int(reqMac.group(2)):
- return False
-
- return True
-
- # XXX Linux and other platforms' special cases should go here
- return False
-
-
-def run_script(dist_spec, script_name):
- """Locate distribution `dist_spec` and run its `script_name` script"""
- ns = sys._getframe(1).f_globals
- name = ns['__name__']
- ns.clear()
- ns['__name__'] = name
- require(dist_spec)[0].run_script(script_name, ns)
-
-
-# backward compatibility
-run_main = run_script
-
-
-def get_distribution(dist):
- """Return a current distribution object for a Requirement or string"""
- if isinstance(dist, str):
- dist = Requirement.parse(dist)
- if isinstance(dist, Requirement):
- dist = get_provider(dist)
- if not isinstance(dist, Distribution):
- raise TypeError("Expected string, Requirement, or Distribution", dist)
- return dist
-
-
-def load_entry_point(dist, group, name):
- """Return `name` entry point of `group` for `dist` or raise ImportError"""
- return get_distribution(dist).load_entry_point(group, name)
-
-
-def get_entry_map(dist, group=None):
- """Return the entry point map for `group`, or the full entry map"""
- return get_distribution(dist).get_entry_map(group)
-
-
-def get_entry_info(dist, group, name):
- """Return the EntryPoint object for `group`+`name`, or ``None``"""
- return get_distribution(dist).get_entry_info(group, name)
-
-
-class IMetadataProvider:
- def has_metadata(name):
- """Does the package's distribution contain the named metadata?"""
-
- def get_metadata(name):
- """The named metadata resource as a string"""
-
- def get_metadata_lines(name):
- """Yield named metadata resource as list of non-blank non-comment lines
-
- Leading and trailing whitespace is stripped from each line, and lines
- with ``#`` as the first non-blank character are omitted."""
-
- def metadata_isdir(name):
- """Is the named metadata a directory? (like ``os.path.isdir()``)"""
-
- def metadata_listdir(name):
- """List of metadata names in the directory (like ``os.listdir()``)"""
-
- def run_script(script_name, namespace):
- """Execute the named script in the supplied namespace dictionary"""
-
-
-class IResourceProvider(IMetadataProvider):
- """An object that provides access to package resources"""
-
- def get_resource_filename(manager, resource_name):
- """Return a true filesystem path for `resource_name`
-
- `manager` must be an ``IResourceManager``"""
-
- def get_resource_stream(manager, resource_name):
- """Return a readable file-like object for `resource_name`
-
- `manager` must be an ``IResourceManager``"""
-
- def get_resource_string(manager, resource_name):
- """Return a string containing the contents of `resource_name`
-
- `manager` must be an ``IResourceManager``"""
-
- def has_resource(resource_name):
- """Does the package contain the named resource?"""
-
- def resource_isdir(resource_name):
- """Is the named resource a directory? (like ``os.path.isdir()``)"""
-
- def resource_listdir(resource_name):
- """List of resource names in the directory (like ``os.listdir()``)"""
-
-
-class WorkingSet:
- """A collection of active distributions on sys.path (or a similar list)"""
-
- def __init__(self, entries=None):
- """Create working set from list of path entries (default=sys.path)"""
- self.entries = []
- self.entry_keys = {}
- self.by_key = {}
- self.normalized_to_canonical_keys = {}
- self.callbacks = []
-
- if entries is None:
- entries = sys.path
-
- for entry in entries:
- self.add_entry(entry)
-
- @classmethod
- def _build_master(cls):
- """
- Prepare the master working set.
- """
- ws = cls()
- try:
- from __main__ import __requires__
- except ImportError:
- # The main program does not list any requirements
- return ws
-
- # ensure the requirements are met
- try:
- ws.require(__requires__)
- except VersionConflict:
- return cls._build_from_requirements(__requires__)
-
- return ws
-
- @classmethod
- def _build_from_requirements(cls, req_spec):
- """
- Build a working set from a requirement spec. Rewrites sys.path.
- """
- # try it without defaults already on sys.path
- # by starting with an empty path
- ws = cls([])
- reqs = parse_requirements(req_spec)
- dists = ws.resolve(reqs, Environment())
- for dist in dists:
- ws.add(dist)
-
- # add any missing entries from sys.path
- for entry in sys.path:
- if entry not in ws.entries:
- ws.add_entry(entry)
-
- # then copy back to sys.path
- sys.path[:] = ws.entries
- return ws
-
- def add_entry(self, entry):
- """Add a path item to ``.entries``, finding any distributions on it
-
- ``find_distributions(entry, True)`` is used to find distributions
- corresponding to the path entry, and they are added. `entry` is
- always appended to ``.entries``, even if it is already present.
- (This is because ``sys.path`` can contain the same value more than
- once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
- equal ``sys.path``.)
- """
- self.entry_keys.setdefault(entry, [])
- self.entries.append(entry)
- for dist in find_distributions(entry, True):
- self.add(dist, entry, False)
-
- def __contains__(self, dist):
- """True if `dist` is the active distribution for its project"""
- return self.by_key.get(dist.key) == dist
-
- def find(self, req):
- """Find a distribution matching requirement `req`
-
- If there is an active distribution for the requested project, this
- returns it as long as it meets the version requirement specified by
- `req`. But, if there is an active distribution for the project and it
- does *not* meet the `req` requirement, ``VersionConflict`` is raised.
- If there is no active distribution for the requested project, ``None``
- is returned.
- """
- dist = self.by_key.get(req.key)
-
- if dist is None:
- canonical_key = self.normalized_to_canonical_keys.get(req.key)
-
- if canonical_key is not None:
- req.key = canonical_key
- dist = self.by_key.get(canonical_key)
-
- if dist is not None and dist not in req:
- # XXX add more info
- raise VersionConflict(dist, req)
- return dist
-
- def iter_entry_points(self, group, name=None):
- """Yield entry point objects from `group` matching `name`
-
- If `name` is None, yields all entry points in `group` from all
- distributions in the working set, otherwise only ones matching
- both `group` and `name` are yielded (in distribution order).
- """
- return (
- entry
- for dist in self
- for entry in dist.get_entry_map(group).values()
- if name is None or name == entry.name
- )
-
- def run_script(self, requires, script_name):
- """Locate distribution for `requires` and run `script_name` script"""
- ns = sys._getframe(1).f_globals
- name = ns['__name__']
- ns.clear()
- ns['__name__'] = name
- self.require(requires)[0].run_script(script_name, ns)
-
- def __iter__(self):
- """Yield distributions for non-duplicate projects in the working set
-
- The yield order is the order in which the items' path entries were
- added to the working set.
- """
- seen = {}
- for item in self.entries:
- if item not in self.entry_keys:
- # workaround a cache issue
- continue
-
- for key in self.entry_keys[item]:
- if key not in seen:
- seen[key] = 1
- yield self.by_key[key]
-
- def add(self, dist, entry=None, insert=True, replace=False):
- """Add `dist` to working set, associated with `entry`
-
- If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
- On exit from this routine, `entry` is added to the end of the working
- set's ``.entries`` (if it wasn't already present).
-
- `dist` is only added to the working set if it's for a project that
- doesn't already have a distribution in the set, unless `replace=True`.
- If it's added, any callbacks registered with the ``subscribe()`` method
- will be called.
- """
- if insert:
- dist.insert_on(self.entries, entry, replace=replace)
-
- if entry is None:
- entry = dist.location
- keys = self.entry_keys.setdefault(entry, [])
- keys2 = self.entry_keys.setdefault(dist.location, [])
- if not replace and dist.key in self.by_key:
- # ignore hidden distros
- return
-
- self.by_key[dist.key] = dist
- normalized_name = packaging.utils.canonicalize_name(dist.key)
- self.normalized_to_canonical_keys[normalized_name] = dist.key
- if dist.key not in keys:
- keys.append(dist.key)
- if dist.key not in keys2:
- keys2.append(dist.key)
- self._added_new(dist)
-
- # FIXME: 'WorkingSet.resolve' is too complex (11)
- def resolve(self, requirements, env=None, installer=None, # noqa: C901
- replace_conflicting=False, extras=None):
- """List all distributions needed to (recursively) meet `requirements`
-
- `requirements` must be a sequence of ``Requirement`` objects. `env`,
- if supplied, should be an ``Environment`` instance. If
- not supplied, it defaults to all distributions available within any
- entry or distribution in the working set. `installer`, if supplied,
- will be invoked with each requirement that cannot be met by an
- already-installed distribution; it should return a ``Distribution`` or
- ``None``.
-
- Unless `replace_conflicting=True`, raises a VersionConflict exception
- if
- any requirements are found on the path that have the correct name but
- the wrong version. Otherwise, if an `installer` is supplied it will be
- invoked to obtain the correct version of the requirement and activate
- it.
-
- `extras` is a list of the extras to be used with these requirements.
- This is important because extra requirements may look like `my_req;
- extra = "my_extra"`, which would otherwise be interpreted as a purely
- optional requirement. Instead, we want to be able to assert that these
- requirements are truly required.
- """
-
- # set up the stack
- requirements = list(requirements)[::-1]
- # set of processed requirements
- processed = {}
- # key -> dist
- best = {}
- to_activate = []
-
- req_extras = _ReqExtras()
-
- # Mapping of requirement to set of distributions that required it;
- # useful for reporting info about conflicts.
- required_by = collections.defaultdict(set)
-
- while requirements:
- # process dependencies breadth-first
- req = requirements.pop(0)
- if req in processed:
- # Ignore cyclic or redundant dependencies
- continue
-
- if not req_extras.markers_pass(req, extras):
- continue
-
- dist = best.get(req.key)
- if dist is None:
- # Find the best distribution and add it to the map
- dist = self.by_key.get(req.key)
- if dist is None or (dist not in req and replace_conflicting):
- ws = self
- if env is None:
- if dist is None:
- env = Environment(self.entries)
- else:
- # Use an empty environment and workingset to avoid
- # any further conflicts with the conflicting
- # distribution
- env = Environment([])
- ws = WorkingSet([])
- dist = best[req.key] = env.best_match(
- req, ws, installer,
- replace_conflicting=replace_conflicting
- )
- if dist is None:
- requirers = required_by.get(req, None)
- raise DistributionNotFound(req, requirers)
- to_activate.append(dist)
- if dist not in req:
- # Oops, the "best" so far conflicts with a dependency
- dependent_req = required_by[req]
- raise VersionConflict(dist, req).with_context(dependent_req)
-
- # push the new requirements onto the stack
- new_requirements = dist.requires(req.extras)[::-1]
- requirements.extend(new_requirements)
-
- # Register the new requirements needed by req
- for new_requirement in new_requirements:
- required_by[new_requirement].add(req.project_name)
- req_extras[new_requirement] = req.extras
-
- processed[req] = True
-
- # return list of distros to activate
- return to_activate
-
- def find_plugins(
- self, plugin_env, full_env=None, installer=None, fallback=True):
- """Find all activatable distributions in `plugin_env`
-
- Example usage::
-
- distributions, errors = working_set.find_plugins(
- Environment(plugin_dirlist)
- )
- # add plugins+libs to sys.path
- map(working_set.add, distributions)
- # display errors
- print('Could not load', errors)
-
- The `plugin_env` should be an ``Environment`` instance that contains
- only distributions that are in the project's "plugin directory" or
- directories. The `full_env`, if supplied, should be an ``Environment``
- contains all currently-available distributions. If `full_env` is not
- supplied, one is created automatically from the ``WorkingSet`` this
- method is called on, which will typically mean that every directory on
- ``sys.path`` will be scanned for distributions.
-
- `installer` is a standard installer callback as used by the
- ``resolve()`` method. The `fallback` flag indicates whether we should
- attempt to resolve older versions of a plugin if the newest version
- cannot be resolved.
-
- This method returns a 2-tuple: (`distributions`, `error_info`), where
- `distributions` is a list of the distributions found in `plugin_env`
- that were loadable, along with any other distributions that are needed
- to resolve their dependencies. `error_info` is a dictionary mapping
- unloadable plugin distributions to an exception instance describing the
- error that occurred. Usually this will be a ``DistributionNotFound`` or
- ``VersionConflict`` instance.
- """
-
- plugin_projects = list(plugin_env)
- # scan project names in alphabetic order
- plugin_projects.sort()
-
- error_info = {}
- distributions = {}
-
- if full_env is None:
- env = Environment(self.entries)
- env += plugin_env
- else:
- env = full_env + plugin_env
-
- shadow_set = self.__class__([])
- # put all our entries in shadow_set
- list(map(shadow_set.add, self))
-
- for project_name in plugin_projects:
-
- for dist in plugin_env[project_name]:
-
- req = [dist.as_requirement()]
-
- try:
- resolvees = shadow_set.resolve(req, env, installer)
-
- except ResolutionError as v:
- # save error info
- error_info[dist] = v
- if fallback:
- # try the next older version of project
- continue
- else:
- # give up on this project, keep going
- break
-
- else:
- list(map(shadow_set.add, resolvees))
- distributions.update(dict.fromkeys(resolvees))
-
- # success, no need to try any more versions of this project
- break
-
- distributions = list(distributions)
- distributions.sort()
-
- return distributions, error_info
-
- def require(self, *requirements):
- """Ensure that distributions matching `requirements` are activated
-
- `requirements` must be a string or a (possibly-nested) sequence
- thereof, specifying the distributions and versions required. The
- return value is a sequence of the distributions that needed to be
- activated to fulfill the requirements; all relevant distributions are
- included, even if they were already activated in this working set.
- """
- needed = self.resolve(parse_requirements(requirements))
-
- for dist in needed:
- self.add(dist)
-
- return needed
-
- def subscribe(self, callback, existing=True):
- """Invoke `callback` for all distributions
-
- If `existing=True` (default),
- call on all existing ones, as well.
- """
- if callback in self.callbacks:
- return
- self.callbacks.append(callback)
- if not existing:
- return
- for dist in self:
- callback(dist)
-
- def _added_new(self, dist):
- for callback in self.callbacks:
- callback(dist)
-
- def __getstate__(self):
- return (
- self.entries[:], self.entry_keys.copy(), self.by_key.copy(),
- self.normalized_to_canonical_keys.copy(), self.callbacks[:]
- )
-
- def __setstate__(self, e_k_b_n_c):
- entries, keys, by_key, normalized_to_canonical_keys, callbacks = e_k_b_n_c
- self.entries = entries[:]
- self.entry_keys = keys.copy()
- self.by_key = by_key.copy()
- self.normalized_to_canonical_keys = normalized_to_canonical_keys.copy()
- self.callbacks = callbacks[:]
-
-
-class _ReqExtras(dict):
- """
- Map each requirement to the extras that demanded it.
- """
-
- def markers_pass(self, req, extras=None):
- """
- Evaluate markers for req against each extra that
- demanded it.
-
- Return False if the req has a marker and fails
- evaluation. Otherwise, return True.
- """
- extra_evals = (
- req.marker.evaluate({'extra': extra})
- for extra in self.get(req, ()) + (extras or (None,))
- )
- return not req.marker or any(extra_evals)
-
-
-class Environment:
- """Searchable snapshot of distributions on a search path"""
-
- def __init__(
- self, search_path=None, platform=get_supported_platform(),
- python=PY_MAJOR):
- """Snapshot distributions available on a search path
-
- Any distributions found on `search_path` are added to the environment.
- `search_path` should be a sequence of ``sys.path`` items. If not
- supplied, ``sys.path`` is used.
-
- `platform` is an optional string specifying the name of the platform
- that platform-specific distributions must be compatible with. If
- unspecified, it defaults to the current platform. `python` is an
- optional string naming the desired version of Python (e.g. ``'3.6'``);
- it defaults to the current version.
-
- You may explicitly set `platform` (and/or `python`) to ``None`` if you
- wish to map *all* distributions, not just those compatible with the
- running platform or Python version.
- """
- self._distmap = {}
- self.platform = platform
- self.python = python
- self.scan(search_path)
-
- def can_add(self, dist):
- """Is distribution `dist` acceptable for this environment?
-
- The distribution must match the platform and python version
- requirements specified when this environment was created, or False
- is returned.
- """
- py_compat = (
- self.python is None
- or dist.py_version is None
- or dist.py_version == self.python
- )
- return py_compat and compatible_platforms(dist.platform, self.platform)
-
- def remove(self, dist):
- """Remove `dist` from the environment"""
- self._distmap[dist.key].remove(dist)
-
- def scan(self, search_path=None):
- """Scan `search_path` for distributions usable in this environment
-
- Any distributions found are added to the environment.
- `search_path` should be a sequence of ``sys.path`` items. If not
- supplied, ``sys.path`` is used. Only distributions conforming to
- the platform/python version defined at initialization are added.
- """
- if search_path is None:
- search_path = sys.path
-
- for item in search_path:
- for dist in find_distributions(item):
- self.add(dist)
-
- def __getitem__(self, project_name):
- """Return a newest-to-oldest list of distributions for `project_name`
-
- Uses case-insensitive `project_name` comparison, assuming all the
- project's distributions use their project's name converted to all
- lowercase as their key.
-
- """
- distribution_key = project_name.lower()
- return self._distmap.get(distribution_key, [])
-
- def add(self, dist):
- """Add `dist` if we ``can_add()`` it and it has not already been added
- """
- if self.can_add(dist) and dist.has_version():
- dists = self._distmap.setdefault(dist.key, [])
- if dist not in dists:
- dists.append(dist)
- dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
-
- def best_match(
- self, req, working_set, installer=None, replace_conflicting=False):
- """Find distribution best matching `req` and usable on `working_set`
-
- This calls the ``find(req)`` method of the `working_set` to see if a
- suitable distribution is already active. (This may raise
- ``VersionConflict`` if an unsuitable version of the project is already
- active in the specified `working_set`.) If a suitable distribution
- isn't active, this method returns the newest distribution in the
- environment that meets the ``Requirement`` in `req`. If no suitable
- distribution is found, and `installer` is supplied, then the result of
- calling the environment's ``obtain(req, installer)`` method will be
- returned.
- """
- try:
- dist = working_set.find(req)
- except VersionConflict:
- if not replace_conflicting:
- raise
- dist = None
- if dist is not None:
- return dist
- for dist in self[req.key]:
- if dist in req:
- return dist
- # try to download/install
- return self.obtain(req, installer)
-
- def obtain(self, requirement, installer=None):
- """Obtain a distribution matching `requirement` (e.g. via download)
-
- Obtain a distro that matches requirement (e.g. via download). In the
- base ``Environment`` class, this routine just returns
- ``installer(requirement)``, unless `installer` is None, in which case
- None is returned instead. This method is a hook that allows subclasses
- to attempt other ways of obtaining a distribution before falling back
- to the `installer` argument."""
- if installer is not None:
- return installer(requirement)
-
- def __iter__(self):
- """Yield the unique project names of the available distributions"""
- for key in self._distmap.keys():
- if self[key]:
- yield key
-
- def __iadd__(self, other):
- """In-place addition of a distribution or environment"""
- if isinstance(other, Distribution):
- self.add(other)
- elif isinstance(other, Environment):
- for project in other:
- for dist in other[project]:
- self.add(dist)
- else:
- raise TypeError("Can't add %r to environment" % (other,))
- return self
-
- def __add__(self, other):
- """Add an environment or distribution to an environment"""
- new = self.__class__([], platform=None, python=None)
- for env in self, other:
- new += env
- return new
-
-
-# XXX backward compatibility
-AvailableDistributions = Environment
-
-
-class ExtractionError(RuntimeError):
- """An error occurred extracting a resource
-
- The following attributes are available from instances of this exception:
-
- manager
- The resource manager that raised this exception
-
- cache_path
- The base directory for resource extraction
-
- original_error
- The exception instance that caused extraction to fail
- """
-
-
-class ResourceManager:
- """Manage resource extraction and packages"""
- extraction_path = None
-
- def __init__(self):
- self.cached_files = {}
-
- def resource_exists(self, package_or_requirement, resource_name):
- """Does the named resource exist?"""
- return get_provider(package_or_requirement).has_resource(resource_name)
-
- def resource_isdir(self, package_or_requirement, resource_name):
- """Is the named resource an existing directory?"""
- return get_provider(package_or_requirement).resource_isdir(
- resource_name
- )
-
- def resource_filename(self, package_or_requirement, resource_name):
- """Return a true filesystem path for specified resource"""
- return get_provider(package_or_requirement).get_resource_filename(
- self, resource_name
- )
-
- def resource_stream(self, package_or_requirement, resource_name):
- """Return a readable file-like object for specified resource"""
- return get_provider(package_or_requirement).get_resource_stream(
- self, resource_name
- )
-
- def resource_string(self, package_or_requirement, resource_name):
- """Return specified resource as a string"""
- return get_provider(package_or_requirement).get_resource_string(
- self, resource_name
- )
-
- def resource_listdir(self, package_or_requirement, resource_name):
- """List the contents of the named resource directory"""
- return get_provider(package_or_requirement).resource_listdir(
- resource_name
- )
-
- def extraction_error(self):
- """Give an error message for problems extracting file(s)"""
-
- old_exc = sys.exc_info()[1]
- cache_path = self.extraction_path or get_default_cache()
-
- tmpl = textwrap.dedent("""
- Can't extract file(s) to egg cache
-
- The following error occurred while trying to extract file(s)
- to the Python egg cache:
-
- {old_exc}
-
- The Python egg cache directory is currently set to:
-
- {cache_path}
-
- Perhaps your account does not have write access to this directory?
- You can change the cache directory by setting the PYTHON_EGG_CACHE
- environment variable to point to an accessible directory.
- """).lstrip()
- err = ExtractionError(tmpl.format(**locals()))
- err.manager = self
- err.cache_path = cache_path
- err.original_error = old_exc
- raise err
-
- def get_cache_path(self, archive_name, names=()):
- """Return absolute location in cache for `archive_name` and `names`
-
- The parent directory of the resulting path will be created if it does
- not already exist. `archive_name` should be the base filename of the
- enclosing egg (which may not be the name of the enclosing zipfile!),
- including its ".egg" extension. `names`, if provided, should be a
- sequence of path name parts "under" the egg's extraction location.
-
- This method should only be called by resource providers that need to
- obtain an extraction location, and only for names they intend to
- extract, as it tracks the generated names for possible cleanup later.
- """
- extract_path = self.extraction_path or get_default_cache()
- target_path = os.path.join(extract_path, archive_name + '-tmp', *names)
- try:
- _bypass_ensure_directory(target_path)
- except Exception:
- self.extraction_error()
-
- self._warn_unsafe_extraction_path(extract_path)
-
- self.cached_files[target_path] = 1
- return target_path
-
- @staticmethod
- def _warn_unsafe_extraction_path(path):
- """
- If the default extraction path is overridden and set to an insecure
- location, such as /tmp, it opens up an opportunity for an attacker to
- replace an extracted file with an unauthorized payload. Warn the user
- if a known insecure location is used.
-
- See Distribute #375 for more details.
- """
- if os.name == 'nt' and not path.startswith(os.environ['windir']):
- # On Windows, permissions are generally restrictive by default
- # and temp directories are not writable by other users, so
- # bypass the warning.
- return
- mode = os.stat(path).st_mode
- if mode & stat.S_IWOTH or mode & stat.S_IWGRP:
- msg = (
- "Extraction path is writable by group/others "
- "and vulnerable to attack when "
- "used with get_resource_filename ({path}). "
- "Consider a more secure "
- "location (set with .set_extraction_path or the "
- "PYTHON_EGG_CACHE environment variable)."
- ).format(**locals())
- warnings.warn(msg, UserWarning)
-
- def postprocess(self, tempname, filename):
- """Perform any platform-specific postprocessing of `tempname`
-
- This is where Mac header rewrites should be done; other platforms don't
- have anything special they should do.
-
- Resource providers should call this method ONLY after successfully
- extracting a compressed resource. They must NOT call it on resources
- that are already in the filesystem.
-
- `tempname` is the current (temporary) name of the file, and `filename`
- is the name it will be renamed to by the caller after this routine
- returns.
- """
-
- if os.name == 'posix':
- # Make the resource executable
- mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777
- os.chmod(tempname, mode)
-
- def set_extraction_path(self, path):
- """Set the base path where resources will be extracted to, if needed.
-
- If you do not call this routine before any extractions take place, the
- path defaults to the return value of ``get_default_cache()``. (Which
- is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
- platform-specific fallbacks. See that routine's documentation for more
- details.)
-
- Resources are extracted to subdirectories of this path based upon
- information given by the ``IResourceProvider``. You may set this to a
- temporary directory, but then you must call ``cleanup_resources()`` to
- delete the extracted files when done. There is no guarantee that
- ``cleanup_resources()`` will be able to remove all extracted files.
-
- (Note: you may not change the extraction path for a given resource
- manager once resources have been extracted, unless you first call
- ``cleanup_resources()``.)
- """
- if self.cached_files:
- raise ValueError(
- "Can't change extraction path, files already extracted"
- )
-
- self.extraction_path = path
-
- def cleanup_resources(self, force=False):
- """
- Delete all extracted resource files and directories, returning a list
- of the file and directory names that could not be successfully removed.
- This function does not have any concurrency protection, so it should
- generally only be called when the extraction path is a temporary
- directory exclusive to a single process. This method is not
- automatically called; you must call it explicitly or register it as an
- ``atexit`` function if you wish to ensure cleanup of a temporary
- directory used for extractions.
- """
- # XXX
-
-
-def get_default_cache():
- """
- Return the ``PYTHON_EGG_CACHE`` environment variable
- or a platform-relevant user cache dir for an app
- named "Python-Eggs".
- """
- return (
- os.environ.get('PYTHON_EGG_CACHE')
- or appdirs.user_cache_dir(appname='Python-Eggs')
- )
-
-
-def safe_name(name):
- """Convert an arbitrary string to a standard distribution name
-
- Any runs of non-alphanumeric/. characters are replaced with a single '-'.
- """
- return re.sub('[^A-Za-z0-9.]+', '-', name)
-
-
-def safe_version(version):
- """
- Convert an arbitrary string to a standard version string
- """
- try:
- # normalize the version
- return str(packaging.version.Version(version))
- except packaging.version.InvalidVersion:
- version = version.replace(' ', '.')
- return re.sub('[^A-Za-z0-9.]+', '-', version)
-
-
-def safe_extra(extra):
- """Convert an arbitrary string to a standard 'extra' name
-
- Any runs of non-alphanumeric characters are replaced with a single '_',
- and the result is always lowercased.
- """
- return re.sub('[^A-Za-z0-9.-]+', '_', extra).lower()
-
-
-def to_filename(name):
- """Convert a project or version name to its filename-escaped form
-
- Any '-' characters are currently replaced with '_'.
- """
- return name.replace('-', '_')
-
-
-def invalid_marker(text):
- """
- Validate text as a PEP 508 environment marker; return an exception
- if invalid or False otherwise.
- """
- try:
- evaluate_marker(text)
- except SyntaxError as e:
- e.filename = None
- e.lineno = None
- return e
- return False
-
-
-def evaluate_marker(text, extra=None):
- """
- Evaluate a PEP 508 environment marker.
- Return a boolean indicating the marker result in this environment.
- Raise SyntaxError if marker is invalid.
-
- This implementation uses the 'pyparsing' module.
- """
- try:
- marker = packaging.markers.Marker(text)
- return marker.evaluate()
- except packaging.markers.InvalidMarker as e:
- raise SyntaxError(e) from e
-
-
-class NullProvider:
- """Try to implement resources and metadata for arbitrary PEP 302 loaders"""
-
- egg_name = None
- egg_info = None
- loader = None
-
- def __init__(self, module):
- self.loader = getattr(module, '__loader__', None)
- self.module_path = os.path.dirname(getattr(module, '__file__', ''))
-
- def get_resource_filename(self, manager, resource_name):
- return self._fn(self.module_path, resource_name)
-
- def get_resource_stream(self, manager, resource_name):
- return io.BytesIO(self.get_resource_string(manager, resource_name))
-
- def get_resource_string(self, manager, resource_name):
- return self._get(self._fn(self.module_path, resource_name))
-
- def has_resource(self, resource_name):
- return self._has(self._fn(self.module_path, resource_name))
-
- def _get_metadata_path(self, name):
- return self._fn(self.egg_info, name)
-
- def has_metadata(self, name):
- if not self.egg_info:
- return self.egg_info
-
- path = self._get_metadata_path(name)
- return self._has(path)
-
- def get_metadata(self, name):
- if not self.egg_info:
- return ""
- path = self._get_metadata_path(name)
- value = self._get(path)
- try:
- return value.decode('utf-8')
- except UnicodeDecodeError as exc:
- # Include the path in the error message to simplify
- # troubleshooting, and without changing the exception type.
- exc.reason += ' in {} file at path: {}'.format(name, path)
- raise
-
- def get_metadata_lines(self, name):
- return yield_lines(self.get_metadata(name))
-
- def resource_isdir(self, resource_name):
- return self._isdir(self._fn(self.module_path, resource_name))
-
- def metadata_isdir(self, name):
- return self.egg_info and self._isdir(self._fn(self.egg_info, name))
-
- def resource_listdir(self, resource_name):
- return self._listdir(self._fn(self.module_path, resource_name))
-
- def metadata_listdir(self, name):
- if self.egg_info:
- return self._listdir(self._fn(self.egg_info, name))
- return []
-
- def run_script(self, script_name, namespace):
- script = 'scripts/' + script_name
- if not self.has_metadata(script):
- raise ResolutionError(
- "Script {script!r} not found in metadata at {self.egg_info!r}"
- .format(**locals()),
- )
- script_text = self.get_metadata(script).replace('\r\n', '\n')
- script_text = script_text.replace('\r', '\n')
- script_filename = self._fn(self.egg_info, script)
- namespace['__file__'] = script_filename
- if os.path.exists(script_filename):
- with open(script_filename) as fid:
- source = fid.read()
- code = compile(source, script_filename, 'exec')
- exec(code, namespace, namespace)
- else:
- from linecache import cache
- cache[script_filename] = (
- len(script_text), 0, script_text.split('\n'), script_filename
- )
- script_code = compile(script_text, script_filename, 'exec')
- exec(script_code, namespace, namespace)
-
- def _has(self, path):
- raise NotImplementedError(
- "Can't perform this operation for unregistered loader type"
- )
-
- def _isdir(self, path):
- raise NotImplementedError(
- "Can't perform this operation for unregistered loader type"
- )
-
- def _listdir(self, path):
- raise NotImplementedError(
- "Can't perform this operation for unregistered loader type"
- )
-
- def _fn(self, base, resource_name):
- self._validate_resource_path(resource_name)
- if resource_name:
- return os.path.join(base, *resource_name.split('/'))
- return base
-
- @staticmethod
- def _validate_resource_path(path):
- """
- Validate the resource paths according to the docs.
- https://setuptools.pypa.io/en/latest/pkg_resources.html#basic-resource-access
-
- >>> warned = getfixture('recwarn')
- >>> warnings.simplefilter('always')
- >>> vrp = NullProvider._validate_resource_path
- >>> vrp('foo/bar.txt')
- >>> bool(warned)
- False
- >>> vrp('../foo/bar.txt')
- >>> bool(warned)
- True
- >>> warned.clear()
- >>> vrp('/foo/bar.txt')
- >>> bool(warned)
- True
- >>> vrp('foo/../../bar.txt')
- >>> bool(warned)
- True
- >>> warned.clear()
- >>> vrp('foo/f../bar.txt')
- >>> bool(warned)
- False
-
- Windows path separators are straight-up disallowed.
- >>> vrp(r'\\foo/bar.txt')
- Traceback (most recent call last):
- ...
- ValueError: Use of .. or absolute path in a resource path \
-is not allowed.
-
- >>> vrp(r'C:\\foo/bar.txt')
- Traceback (most recent call last):
- ...
- ValueError: Use of .. or absolute path in a resource path \
-is not allowed.
-
- Blank values are allowed
-
- >>> vrp('')
- >>> bool(warned)
- False
-
- Non-string values are not.
-
- >>> vrp(None)
- Traceback (most recent call last):
- ...
- AttributeError: ...
- """
- invalid = (
- os.path.pardir in path.split(posixpath.sep) or
- posixpath.isabs(path) or
- ntpath.isabs(path)
- )
- if not invalid:
- return
-
- msg = "Use of .. or absolute path in a resource path is not allowed."
-
- # Aggressively disallow Windows absolute paths
- if ntpath.isabs(path) and not posixpath.isabs(path):
- raise ValueError(msg)
-
- # for compatibility, warn; in future
- # raise ValueError(msg)
- warnings.warn(
- msg[:-1] + " and will raise exceptions in a future release.",
- DeprecationWarning,
- stacklevel=4,
- )
-
- def _get(self, path):
- if hasattr(self.loader, 'get_data'):
- return self.loader.get_data(path)
- raise NotImplementedError(
- "Can't perform this operation for loaders without 'get_data()'"
- )
-
-
-register_loader_type(object, NullProvider)
-
-
-def _parents(path):
- """
- yield all parents of path including path
- """
- last = None
- while path != last:
- yield path
- last = path
- path, _ = os.path.split(path)
-
-
-class EggProvider(NullProvider):
- """Provider based on a virtual filesystem"""
-
- def __init__(self, module):
- super().__init__(module)
- self._setup_prefix()
-
- def _setup_prefix(self):
- # Assume that metadata may be nested inside a "basket"
- # of multiple eggs and use module_path instead of .archive.
- eggs = filter(_is_egg_path, _parents(self.module_path))
- egg = next(eggs, None)
- egg and self._set_egg(egg)
-
- def _set_egg(self, path):
- self.egg_name = os.path.basename(path)
- self.egg_info = os.path.join(path, 'EGG-INFO')
- self.egg_root = path
-
-
-class DefaultProvider(EggProvider):
- """Provides access to package resources in the filesystem"""
-
- def _has(self, path):
- return os.path.exists(path)
-
- def _isdir(self, path):
- return os.path.isdir(path)
-
- def _listdir(self, path):
- return os.listdir(path)
-
- def get_resource_stream(self, manager, resource_name):
- return open(self._fn(self.module_path, resource_name), 'rb')
-
- def _get(self, path):
- with open(path, 'rb') as stream:
- return stream.read()
-
- @classmethod
- def _register(cls):
- loader_names = 'SourceFileLoader', 'SourcelessFileLoader',
- for name in loader_names:
- loader_cls = getattr(importlib_machinery, name, type(None))
- register_loader_type(loader_cls, cls)
-
-
-DefaultProvider._register()
-
-
-class EmptyProvider(NullProvider):
- """Provider that returns nothing for all requests"""
-
- module_path = None
-
- _isdir = _has = lambda self, path: False
-
- def _get(self, path):
- return ''
-
- def _listdir(self, path):
- return []
-
- def __init__(self):
- pass
-
-
-empty_provider = EmptyProvider()
-
-
-class ZipManifests(dict):
- """
- zip manifest builder
- """
-
- @classmethod
- def build(cls, path):
- """
- Build a dictionary similar to the zipimport directory
- caches, except instead of tuples, store ZipInfo objects.
-
- Use a platform-specific path separator (os.sep) for the path keys
- for compatibility with pypy on Windows.
- """
- with zipfile.ZipFile(path) as zfile:
- items = (
- (
- name.replace('/', os.sep),
- zfile.getinfo(name),
- )
- for name in zfile.namelist()
- )
- return dict(items)
-
- load = build
-
-
-class MemoizedZipManifests(ZipManifests):
- """
- Memoized zipfile manifests.
- """
- manifest_mod = collections.namedtuple('manifest_mod', 'manifest mtime')
-
- def load(self, path):
- """
- Load a manifest at path or return a suitable manifest already loaded.
- """
- path = os.path.normpath(path)
- mtime = os.stat(path).st_mtime
-
- if path not in self or self[path].mtime != mtime:
- manifest = self.build(path)
- self[path] = self.manifest_mod(manifest, mtime)
-
- return self[path].manifest
-
-
-class ZipProvider(EggProvider):
- """Resource support for zips and eggs"""
-
- eagers = None
- _zip_manifests = MemoizedZipManifests()
-
- def __init__(self, module):
- super().__init__(module)
- self.zip_pre = self.loader.archive + os.sep
-
- def _zipinfo_name(self, fspath):
- # Convert a virtual filename (full path to file) into a zipfile subpath
- # usable with the zipimport directory cache for our target archive
- fspath = fspath.rstrip(os.sep)
- if fspath == self.loader.archive:
- return ''
- if fspath.startswith(self.zip_pre):
- return fspath[len(self.zip_pre):]
- raise AssertionError(
- "%s is not a subpath of %s" % (fspath, self.zip_pre)
- )
-
- def _parts(self, zip_path):
- # Convert a zipfile subpath into an egg-relative path part list.
- # pseudo-fs path
- fspath = self.zip_pre + zip_path
- if fspath.startswith(self.egg_root + os.sep):
- return fspath[len(self.egg_root) + 1:].split(os.sep)
- raise AssertionError(
- "%s is not a subpath of %s" % (fspath, self.egg_root)
- )
-
- @property
- def zipinfo(self):
- return self._zip_manifests.load(self.loader.archive)
-
- def get_resource_filename(self, manager, resource_name):
- if not self.egg_name:
- raise NotImplementedError(
- "resource_filename() only supported for .egg, not .zip"
- )
- # no need to lock for extraction, since we use temp names
- zip_path = self._resource_to_zip(resource_name)
- eagers = self._get_eager_resources()
- if '/'.join(self._parts(zip_path)) in eagers:
- for name in eagers:
- self._extract_resource(manager, self._eager_to_zip(name))
- return self._extract_resource(manager, zip_path)
-
- @staticmethod
- def _get_date_and_size(zip_stat):
- size = zip_stat.file_size
- # ymdhms+wday, yday, dst
- date_time = zip_stat.date_time + (0, 0, -1)
- # 1980 offset already done
- timestamp = time.mktime(date_time)
- return timestamp, size
-
- # FIXME: 'ZipProvider._extract_resource' is too complex (12)
- def _extract_resource(self, manager, zip_path): # noqa: C901
-
- if zip_path in self._index():
- for name in self._index()[zip_path]:
- last = self._extract_resource(
- manager, os.path.join(zip_path, name)
- )
- # return the extracted directory name
- return os.path.dirname(last)
-
- timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
-
- if not WRITE_SUPPORT:
- raise IOError('"os.rename" and "os.unlink" are not supported '
- 'on this platform')
- try:
-
- real_path = manager.get_cache_path(
- self.egg_name, self._parts(zip_path)
- )
-
- if self._is_current(real_path, zip_path):
- return real_path
-
- outf, tmpnam = _mkstemp(
- ".$extract",
- dir=os.path.dirname(real_path),
- )
- os.write(outf, self.loader.get_data(zip_path))
- os.close(outf)
- utime(tmpnam, (timestamp, timestamp))
- manager.postprocess(tmpnam, real_path)
-
- try:
- rename(tmpnam, real_path)
-
- except os.error:
- if os.path.isfile(real_path):
- if self._is_current(real_path, zip_path):
- # the file became current since it was checked above,
- # so proceed.
- return real_path
- # Windows, del old file and retry
- elif os.name == 'nt':
- unlink(real_path)
- rename(tmpnam, real_path)
- return real_path
- raise
-
- except os.error:
- # report a user-friendly error
- manager.extraction_error()
-
- return real_path
-
- def _is_current(self, file_path, zip_path):
- """
- Return True if the file_path is current for this zip_path
- """
- timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
- if not os.path.isfile(file_path):
- return False
- stat = os.stat(file_path)
- if stat.st_size != size or stat.st_mtime != timestamp:
- return False
- # check that the contents match
- zip_contents = self.loader.get_data(zip_path)
- with open(file_path, 'rb') as f:
- file_contents = f.read()
- return zip_contents == file_contents
-
- def _get_eager_resources(self):
- if self.eagers is None:
- eagers = []
- for name in ('native_libs.txt', 'eager_resources.txt'):
- if self.has_metadata(name):
- eagers.extend(self.get_metadata_lines(name))
- self.eagers = eagers
- return self.eagers
-
- def _index(self):
- try:
- return self._dirindex
- except AttributeError:
- ind = {}
- for path in self.zipinfo:
- parts = path.split(os.sep)
- while parts:
- parent = os.sep.join(parts[:-1])
- if parent in ind:
- ind[parent].append(parts[-1])
- break
- else:
- ind[parent] = [parts.pop()]
- self._dirindex = ind
- return ind
-
- def _has(self, fspath):
- zip_path = self._zipinfo_name(fspath)
- return zip_path in self.zipinfo or zip_path in self._index()
-
- def _isdir(self, fspath):
- return self._zipinfo_name(fspath) in self._index()
-
- def _listdir(self, fspath):
- return list(self._index().get(self._zipinfo_name(fspath), ()))
-
- def _eager_to_zip(self, resource_name):
- return self._zipinfo_name(self._fn(self.egg_root, resource_name))
-
- def _resource_to_zip(self, resource_name):
- return self._zipinfo_name(self._fn(self.module_path, resource_name))
-
-
-register_loader_type(zipimport.zipimporter, ZipProvider)
-
-
-class FileMetadata(EmptyProvider):
- """Metadata handler for standalone PKG-INFO files
-
- Usage::
-
- metadata = FileMetadata("/path/to/PKG-INFO")
-
- This provider rejects all data and metadata requests except for PKG-INFO,
- which is treated as existing, and will be the contents of the file at
- the provided location.
- """
-
- def __init__(self, path):
- self.path = path
-
- def _get_metadata_path(self, name):
- return self.path
-
- def has_metadata(self, name):
- return name == 'PKG-INFO' and os.path.isfile(self.path)
-
- def get_metadata(self, name):
- if name != 'PKG-INFO':
- raise KeyError("No metadata except PKG-INFO is available")
-
- with io.open(self.path, encoding='utf-8', errors="replace") as f:
- metadata = f.read()
- self._warn_on_replacement(metadata)
- return metadata
-
- def _warn_on_replacement(self, metadata):
- replacement_char = '�'
- if replacement_char in metadata:
- tmpl = "{self.path} could not be properly decoded in UTF-8"
- msg = tmpl.format(**locals())
- warnings.warn(msg)
-
- def get_metadata_lines(self, name):
- return yield_lines(self.get_metadata(name))
-
-
-class PathMetadata(DefaultProvider):
- """Metadata provider for egg directories
-
- Usage::
-
- # Development eggs:
-
- egg_info = "/path/to/PackageName.egg-info"
- base_dir = os.path.dirname(egg_info)
- metadata = PathMetadata(base_dir, egg_info)
- dist_name = os.path.splitext(os.path.basename(egg_info))[0]
- dist = Distribution(basedir, project_name=dist_name, metadata=metadata)
-
- # Unpacked egg directories:
-
- egg_path = "/path/to/PackageName-ver-pyver-etc.egg"
- metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO'))
- dist = Distribution.from_filename(egg_path, metadata=metadata)
- """
-
- def __init__(self, path, egg_info):
- self.module_path = path
- self.egg_info = egg_info
-
-
-class EggMetadata(ZipProvider):
- """Metadata provider for .egg files"""
-
- def __init__(self, importer):
- """Create a metadata provider from a zipimporter"""
-
- self.zip_pre = importer.archive + os.sep
- self.loader = importer
- if importer.prefix:
- self.module_path = os.path.join(importer.archive, importer.prefix)
- else:
- self.module_path = importer.archive
- self._setup_prefix()
-
-
-_declare_state('dict', _distribution_finders={})
-
-
-def register_finder(importer_type, distribution_finder):
- """Register `distribution_finder` to find distributions in sys.path items
-
- `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
- handler), and `distribution_finder` is a callable that, passed a path
- item and the importer instance, yields ``Distribution`` instances found on
- that path item. See ``pkg_resources.find_on_path`` for an example."""
- _distribution_finders[importer_type] = distribution_finder
-
-
-def find_distributions(path_item, only=False):
- """Yield distributions accessible via `path_item`"""
- importer = get_importer(path_item)
- finder = _find_adapter(_distribution_finders, importer)
- return finder(importer, path_item, only)
-
-
-def find_eggs_in_zip(importer, path_item, only=False):
- """
- Find eggs in zip files; possibly multiple nested eggs.
- """
- if importer.archive.endswith('.whl'):
- # wheels are not supported with this finder
- # they don't have PKG-INFO metadata, and won't ever contain eggs
- return
- metadata = EggMetadata(importer)
- if metadata.has_metadata('PKG-INFO'):
- yield Distribution.from_filename(path_item, metadata=metadata)
- if only:
- # don't yield nested distros
- return
- for subitem in metadata.resource_listdir(''):
- if _is_egg_path(subitem):
- subpath = os.path.join(path_item, subitem)
- dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath)
- for dist in dists:
- yield dist
- elif subitem.lower().endswith(('.dist-info', '.egg-info')):
- subpath = os.path.join(path_item, subitem)
- submeta = EggMetadata(zipimport.zipimporter(subpath))
- submeta.egg_info = subpath
- yield Distribution.from_location(path_item, subitem, submeta)
-
-
-register_finder(zipimport.zipimporter, find_eggs_in_zip)
-
-
-def find_nothing(importer, path_item, only=False):
- return ()
-
-
-register_finder(object, find_nothing)
-
-
-def _by_version_descending(names):
- """
- Given a list of filenames, return them in descending order
- by version number.
-
- >>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg'
- >>> _by_version_descending(names)
- ['Python-2.7.10.egg', 'Python-2.7.2.egg', 'bar', 'foo']
- >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg'
- >>> _by_version_descending(names)
- ['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg']
- >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg'
- >>> _by_version_descending(names)
- ['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg']
- """
- def try_parse(name):
- """
- Attempt to parse as a version or return a null version.
- """
- try:
- return packaging.version.Version(name)
- except Exception:
- return packaging.version.Version('0')
-
- def _by_version(name):
- """
- Parse each component of the filename
- """
- name, ext = os.path.splitext(name)
- parts = itertools.chain(name.split('-'), [ext])
- return [try_parse(part) for part in parts]
-
- return sorted(names, key=_by_version, reverse=True)
-
-
-def find_on_path(importer, path_item, only=False):
- """Yield distributions accessible on a sys.path directory"""
- path_item = _normalize_cached(path_item)
-
- if _is_unpacked_egg(path_item):
- yield Distribution.from_filename(
- path_item, metadata=PathMetadata(
- path_item, os.path.join(path_item, 'EGG-INFO')
- )
- )
- return
-
- entries = (
- os.path.join(path_item, child)
- for child in safe_listdir(path_item)
- )
-
- # for performance, before sorting by version,
- # screen entries for only those that will yield
- # distributions
- filtered = (
- entry
- for entry in entries
- if dist_factory(path_item, entry, only)
- )
-
- # scan for .egg and .egg-info in directory
- path_item_entries = _by_version_descending(filtered)
- for entry in path_item_entries:
- fullpath = os.path.join(path_item, entry)
- factory = dist_factory(path_item, entry, only)
- for dist in factory(fullpath):
- yield dist
-
-
-def dist_factory(path_item, entry, only):
- """Return a dist_factory for the given entry."""
- lower = entry.lower()
- is_egg_info = lower.endswith('.egg-info')
- is_dist_info = (
- lower.endswith('.dist-info') and
- os.path.isdir(os.path.join(path_item, entry))
- )
- is_meta = is_egg_info or is_dist_info
- return (
- distributions_from_metadata
- if is_meta else
- find_distributions
- if not only and _is_egg_path(entry) else
- resolve_egg_link
- if not only and lower.endswith('.egg-link') else
- NoDists()
- )
-
-
-class NoDists:
- """
- >>> bool(NoDists())
- False
-
- >>> list(NoDists()('anything'))
- []
- """
- def __bool__(self):
- return False
-
- def __call__(self, fullpath):
- return iter(())
-
-
-def safe_listdir(path):
- """
- Attempt to list contents of path, but suppress some exceptions.
- """
- try:
- return os.listdir(path)
- except (PermissionError, NotADirectoryError):
- pass
- except OSError as e:
- # Ignore the directory if does not exist, not a directory or
- # permission denied
- if e.errno not in (errno.ENOTDIR, errno.EACCES, errno.ENOENT):
- raise
- return ()
-
-
-def distributions_from_metadata(path):
- root = os.path.dirname(path)
- if os.path.isdir(path):
- if len(os.listdir(path)) == 0:
- # empty metadata dir; skip
- return
- metadata = PathMetadata(root, path)
- else:
- metadata = FileMetadata(path)
- entry = os.path.basename(path)
- yield Distribution.from_location(
- root, entry, metadata, precedence=DEVELOP_DIST,
- )
-
-
-def non_empty_lines(path):
- """
- Yield non-empty lines from file at path
- """
- with open(path) as f:
- for line in f:
- line = line.strip()
- if line:
- yield line
-
-
-def resolve_egg_link(path):
- """
- Given a path to an .egg-link, resolve distributions
- present in the referenced path.
- """
- referenced_paths = non_empty_lines(path)
- resolved_paths = (
- os.path.join(os.path.dirname(path), ref)
- for ref in referenced_paths
- )
- dist_groups = map(find_distributions, resolved_paths)
- return next(dist_groups, ())
-
-
-register_finder(pkgutil.ImpImporter, find_on_path)
-
-if hasattr(importlib_machinery, 'FileFinder'):
- register_finder(importlib_machinery.FileFinder, find_on_path)
-
-_declare_state('dict', _namespace_handlers={})
-_declare_state('dict', _namespace_packages={})
-
-
-def register_namespace_handler(importer_type, namespace_handler):
- """Register `namespace_handler` to declare namespace packages
-
- `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
- handler), and `namespace_handler` is a callable like this::
-
- def namespace_handler(importer, path_entry, moduleName, module):
- # return a path_entry to use for child packages
-
- Namespace handlers are only called if the importer object has already
- agreed that it can handle the relevant path item, and they should only
- return a subpath if the module __path__ does not already contain an
- equivalent subpath. For an example namespace handler, see
- ``pkg_resources.file_ns_handler``.
- """
- _namespace_handlers[importer_type] = namespace_handler
-
-
-def _handle_ns(packageName, path_item):
- """Ensure that named package includes a subpath of path_item (if needed)"""
-
- importer = get_importer(path_item)
- if importer is None:
- return None
-
- # use find_spec (PEP 451) and fall-back to find_module (PEP 302)
- try:
- spec = importer.find_spec(packageName)
- except AttributeError:
- # capture warnings due to #1111
- with warnings.catch_warnings():
- warnings.simplefilter("ignore")
- loader = importer.find_module(packageName)
- else:
- loader = spec.loader if spec else None
-
- if loader is None:
- return None
- module = sys.modules.get(packageName)
- if module is None:
- module = sys.modules[packageName] = types.ModuleType(packageName)
- module.__path__ = []
- _set_parent_ns(packageName)
- elif not hasattr(module, '__path__'):
- raise TypeError("Not a package:", packageName)
- handler = _find_adapter(_namespace_handlers, importer)
- subpath = handler(importer, path_item, packageName, module)
- if subpath is not None:
- path = module.__path__
- path.append(subpath)
- importlib.import_module(packageName)
- _rebuild_mod_path(path, packageName, module)
- return subpath
-
-
-def _rebuild_mod_path(orig_path, package_name, module):
- """
- Rebuild module.__path__ ensuring that all entries are ordered
- corresponding to their sys.path order
- """
- sys_path = [_normalize_cached(p) for p in sys.path]
-
- def safe_sys_path_index(entry):
- """
- Workaround for #520 and #513.
- """
- try:
- return sys_path.index(entry)
- except ValueError:
- return float('inf')
-
- def position_in_sys_path(path):
- """
- Return the ordinal of the path based on its position in sys.path
- """
- path_parts = path.split(os.sep)
- module_parts = package_name.count('.') + 1
- parts = path_parts[:-module_parts]
- return safe_sys_path_index(_normalize_cached(os.sep.join(parts)))
-
- new_path = sorted(orig_path, key=position_in_sys_path)
- new_path = [_normalize_cached(p) for p in new_path]
-
- if isinstance(module.__path__, list):
- module.__path__[:] = new_path
- else:
- module.__path__ = new_path
-
-
-def declare_namespace(packageName):
- """Declare that package 'packageName' is a namespace package"""
-
- _imp.acquire_lock()
- try:
- if packageName in _namespace_packages:
- return
-
- path = sys.path
- parent, _, _ = packageName.rpartition('.')
-
- if parent:
- declare_namespace(parent)
- if parent not in _namespace_packages:
- __import__(parent)
- try:
- path = sys.modules[parent].__path__
- except AttributeError as e:
- raise TypeError("Not a package:", parent) from e
-
- # Track what packages are namespaces, so when new path items are added,
- # they can be updated
- _namespace_packages.setdefault(parent or None, []).append(packageName)
- _namespace_packages.setdefault(packageName, [])
-
- for path_item in path:
- # Ensure all the parent's path items are reflected in the child,
- # if they apply
- _handle_ns(packageName, path_item)
-
- finally:
- _imp.release_lock()
-
-
-def fixup_namespace_packages(path_item, parent=None):
- """Ensure that previously-declared namespace packages include path_item"""
- _imp.acquire_lock()
- try:
- for package in _namespace_packages.get(parent, ()):
- subpath = _handle_ns(package, path_item)
- if subpath:
- fixup_namespace_packages(subpath, package)
- finally:
- _imp.release_lock()
-
-
-def file_ns_handler(importer, path_item, packageName, module):
- """Compute an ns-package subpath for a filesystem or zipfile importer"""
-
- subpath = os.path.join(path_item, packageName.split('.')[-1])
- normalized = _normalize_cached(subpath)
- for item in module.__path__:
- if _normalize_cached(item) == normalized:
- break
- else:
- # Only return the path if it's not already there
- return subpath
-
-
-register_namespace_handler(pkgutil.ImpImporter, file_ns_handler)
-register_namespace_handler(zipimport.zipimporter, file_ns_handler)
-
-if hasattr(importlib_machinery, 'FileFinder'):
- register_namespace_handler(importlib_machinery.FileFinder, file_ns_handler)
-
-
-def null_ns_handler(importer, path_item, packageName, module):
- return None
-
-
-register_namespace_handler(object, null_ns_handler)
-
-
-def normalize_path(filename):
- """Normalize a file/dir name for comparison purposes"""
- return os.path.normcase(os.path.realpath(os.path.normpath(
- _cygwin_patch(filename))))
-
-
-def _cygwin_patch(filename): # pragma: nocover
- """
- Contrary to POSIX 2008, on Cygwin, getcwd (3) contains
- symlink components. Using
- os.path.abspath() works around this limitation. A fix in os.getcwd()
- would probably better, in Cygwin even more so, except
- that this seems to be by design...
- """
- return os.path.abspath(filename) if sys.platform == 'cygwin' else filename
-
-
-def _normalize_cached(filename, _cache={}):
- try:
- return _cache[filename]
- except KeyError:
- _cache[filename] = result = normalize_path(filename)
- return result
-
-
-def _is_egg_path(path):
- """
- Determine if given path appears to be an egg.
- """
- return _is_zip_egg(path) or _is_unpacked_egg(path)
-
-
-def _is_zip_egg(path):
- return (
- path.lower().endswith('.egg') and
- os.path.isfile(path) and
- zipfile.is_zipfile(path)
- )
-
-
-def _is_unpacked_egg(path):
- """
- Determine if given path appears to be an unpacked egg.
- """
- return (
- path.lower().endswith('.egg') and
- os.path.isfile(os.path.join(path, 'EGG-INFO', 'PKG-INFO'))
- )
-
-
-def _set_parent_ns(packageName):
- parts = packageName.split('.')
- name = parts.pop()
- if parts:
- parent = '.'.join(parts)
- setattr(sys.modules[parent], name, sys.modules[packageName])
-
-
-MODULE = re.compile(r"\w+(\.\w+)*$").match
-EGG_NAME = re.compile(
- r"""
- (?P[^-]+) (
- -(?P[^-]+) (
- -py(?P[^-]+) (
- -(?P.+)
- )?
- )?
- )?
- """,
- re.VERBOSE | re.IGNORECASE,
-).match
-
-
-class EntryPoint:
- """Object representing an advertised importable object"""
-
- def __init__(self, name, module_name, attrs=(), extras=(), dist=None):
- if not MODULE(module_name):
- raise ValueError("Invalid module name", module_name)
- self.name = name
- self.module_name = module_name
- self.attrs = tuple(attrs)
- self.extras = tuple(extras)
- self.dist = dist
-
- def __str__(self):
- s = "%s = %s" % (self.name, self.module_name)
- if self.attrs:
- s += ':' + '.'.join(self.attrs)
- if self.extras:
- s += ' [%s]' % ','.join(self.extras)
- return s
-
- def __repr__(self):
- return "EntryPoint.parse(%r)" % str(self)
-
- def load(self, require=True, *args, **kwargs):
- """
- Require packages for this EntryPoint, then resolve it.
- """
- if not require or args or kwargs:
- warnings.warn(
- "Parameters to load are deprecated. Call .resolve and "
- ".require separately.",
- PkgResourcesDeprecationWarning,
- stacklevel=2,
- )
- if require:
- self.require(*args, **kwargs)
- return self.resolve()
-
- def resolve(self):
- """
- Resolve the entry point from its module and attrs.
- """
- module = __import__(self.module_name, fromlist=['__name__'], level=0)
- try:
- return functools.reduce(getattr, self.attrs, module)
- except AttributeError as exc:
- raise ImportError(str(exc)) from exc
-
- def require(self, env=None, installer=None):
- if self.extras and not self.dist:
- raise UnknownExtra("Can't require() without a distribution", self)
-
- # Get the requirements for this entry point with all its extras and
- # then resolve them. We have to pass `extras` along when resolving so
- # that the working set knows what extras we want. Otherwise, for
- # dist-info distributions, the working set will assume that the
- # requirements for that extra are purely optional and skip over them.
- reqs = self.dist.requires(self.extras)
- items = working_set.resolve(reqs, env, installer, extras=self.extras)
- list(map(working_set.add, items))
-
- pattern = re.compile(
- r'\s*'
- r'(?P.+?)\s*'
- r'=\s*'
- r'(?P[\w.]+)\s*'
- r'(:\s*(?P[\w.]+))?\s*'
- r'(?P\[.*\])?\s*$'
- )
-
- @classmethod
- def parse(cls, src, dist=None):
- """Parse a single entry point from string `src`
-
- Entry point syntax follows the form::
-
- name = some.module:some.attr [extra1, extra2]
-
- The entry name and module name are required, but the ``:attrs`` and
- ``[extras]`` parts are optional
- """
- m = cls.pattern.match(src)
- if not m:
- msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
- raise ValueError(msg, src)
- res = m.groupdict()
- extras = cls._parse_extras(res['extras'])
- attrs = res['attr'].split('.') if res['attr'] else ()
- return cls(res['name'], res['module'], attrs, extras, dist)
-
- @classmethod
- def _parse_extras(cls, extras_spec):
- if not extras_spec:
- return ()
- req = Requirement.parse('x' + extras_spec)
- if req.specs:
- raise ValueError()
- return req.extras
-
- @classmethod
- def parse_group(cls, group, lines, dist=None):
- """Parse an entry point group"""
- if not MODULE(group):
- raise ValueError("Invalid group name", group)
- this = {}
- for line in yield_lines(lines):
- ep = cls.parse(line, dist)
- if ep.name in this:
- raise ValueError("Duplicate entry point", group, ep.name)
- this[ep.name] = ep
- return this
-
- @classmethod
- def parse_map(cls, data, dist=None):
- """Parse a map of entry point groups"""
- if isinstance(data, dict):
- data = data.items()
- else:
- data = split_sections(data)
- maps = {}
- for group, lines in data:
- if group is None:
- if not lines:
- continue
- raise ValueError("Entry points must be listed in groups")
- group = group.strip()
- if group in maps:
- raise ValueError("Duplicate group name", group)
- maps[group] = cls.parse_group(group, lines, dist)
- return maps
-
-
-def _version_from_file(lines):
- """
- Given an iterable of lines from a Metadata file, return
- the value of the Version field, if present, or None otherwise.
- """
- def is_version_line(line):
- return line.lower().startswith('version:')
- version_lines = filter(is_version_line, lines)
- line = next(iter(version_lines), '')
- _, _, value = line.partition(':')
- return safe_version(value.strip()) or None
-
-
-class Distribution:
- """Wrap an actual or potential sys.path entry w/metadata"""
- PKG_INFO = 'PKG-INFO'
-
- def __init__(
- self, location=None, metadata=None, project_name=None,
- version=None, py_version=PY_MAJOR, platform=None,
- precedence=EGG_DIST):
- self.project_name = safe_name(project_name or 'Unknown')
- if version is not None:
- self._version = safe_version(version)
- self.py_version = py_version
- self.platform = platform
- self.location = location
- self.precedence = precedence
- self._provider = metadata or empty_provider
-
- @classmethod
- def from_location(cls, location, basename, metadata=None, **kw):
- project_name, version, py_version, platform = [None] * 4
- basename, ext = os.path.splitext(basename)
- if ext.lower() in _distributionImpl:
- cls = _distributionImpl[ext.lower()]
-
- match = EGG_NAME(basename)
- if match:
- project_name, version, py_version, platform = match.group(
- 'name', 'ver', 'pyver', 'plat'
- )
- return cls(
- location, metadata, project_name=project_name, version=version,
- py_version=py_version, platform=platform, **kw
- )._reload_version()
-
- def _reload_version(self):
- return self
-
- @property
- def hashcmp(self):
- return (
- self.parsed_version,
- self.precedence,
- self.key,
- self.location,
- self.py_version or '',
- self.platform or '',
- )
-
- def __hash__(self):
- return hash(self.hashcmp)
-
- def __lt__(self, other):
- return self.hashcmp < other.hashcmp
-
- def __le__(self, other):
- return self.hashcmp <= other.hashcmp
-
- def __gt__(self, other):
- return self.hashcmp > other.hashcmp
-
- def __ge__(self, other):
- return self.hashcmp >= other.hashcmp
-
- def __eq__(self, other):
- if not isinstance(other, self.__class__):
- # It's not a Distribution, so they are not equal
- return False
- return self.hashcmp == other.hashcmp
-
- def __ne__(self, other):
- return not self == other
-
- # These properties have to be lazy so that we don't have to load any
- # metadata until/unless it's actually needed. (i.e., some distributions
- # may not know their name or version without loading PKG-INFO)
-
- @property
- def key(self):
- try:
- return self._key
- except AttributeError:
- self._key = key = self.project_name.lower()
- return key
-
- @property
- def parsed_version(self):
- if not hasattr(self, "_parsed_version"):
- self._parsed_version = parse_version(self.version)
-
- return self._parsed_version
-
- def _warn_legacy_version(self):
- LV = packaging.version.LegacyVersion
- is_legacy = isinstance(self._parsed_version, LV)
- if not is_legacy:
- return
-
- # While an empty version is technically a legacy version and
- # is not a valid PEP 440 version, it's also unlikely to
- # actually come from someone and instead it is more likely that
- # it comes from setuptools attempting to parse a filename and
- # including it in the list. So for that we'll gate this warning
- # on if the version is anything at all or not.
- if not self.version:
- return
-
- tmpl = textwrap.dedent("""
- '{project_name} ({version})' is being parsed as a legacy,
- non PEP 440,
- version. You may find odd behavior and sort order.
- In particular it will be sorted as less than 0.0. It
- is recommended to migrate to PEP 440 compatible
- versions.
- """).strip().replace('\n', ' ')
-
- warnings.warn(tmpl.format(**vars(self)), PEP440Warning)
-
- @property
- def version(self):
- try:
- return self._version
- except AttributeError as e:
- version = self._get_version()
- if version is None:
- path = self._get_metadata_path_for_display(self.PKG_INFO)
- msg = (
- "Missing 'Version:' header and/or {} file at path: {}"
- ).format(self.PKG_INFO, path)
- raise ValueError(msg, self) from e
-
- return version
-
- @property
- def _dep_map(self):
- """
- A map of extra to its list of (direct) requirements
- for this distribution, including the null extra.
- """
- try:
- return self.__dep_map
- except AttributeError:
- self.__dep_map = self._filter_extras(self._build_dep_map())
- return self.__dep_map
-
- @staticmethod
- def _filter_extras(dm):
- """
- Given a mapping of extras to dependencies, strip off
- environment markers and filter out any dependencies
- not matching the markers.
- """
- for extra in list(filter(None, dm)):
- new_extra = extra
- reqs = dm.pop(extra)
- new_extra, _, marker = extra.partition(':')
- fails_marker = marker and (
- invalid_marker(marker)
- or not evaluate_marker(marker)
- )
- if fails_marker:
- reqs = []
- new_extra = safe_extra(new_extra) or None
-
- dm.setdefault(new_extra, []).extend(reqs)
- return dm
-
- def _build_dep_map(self):
- dm = {}
- for name in 'requires.txt', 'depends.txt':
- for extra, reqs in split_sections(self._get_metadata(name)):
- dm.setdefault(extra, []).extend(parse_requirements(reqs))
- return dm
-
- def requires(self, extras=()):
- """List of Requirements needed for this distro if `extras` are used"""
- dm = self._dep_map
- deps = []
- deps.extend(dm.get(None, ()))
- for ext in extras:
- try:
- deps.extend(dm[safe_extra(ext)])
- except KeyError as e:
- raise UnknownExtra(
- "%s has no such extra feature %r" % (self, ext)
- ) from e
- return deps
-
- def _get_metadata_path_for_display(self, name):
- """
- Return the path to the given metadata file, if available.
- """
- try:
- # We need to access _get_metadata_path() on the provider object
- # directly rather than through this class's __getattr__()
- # since _get_metadata_path() is marked private.
- path = self._provider._get_metadata_path(name)
-
- # Handle exceptions e.g. in case the distribution's metadata
- # provider doesn't support _get_metadata_path().
- except Exception:
- return '[could not detect]'
-
- return path
-
- def _get_metadata(self, name):
- if self.has_metadata(name):
- for line in self.get_metadata_lines(name):
- yield line
-
- def _get_version(self):
- lines = self._get_metadata(self.PKG_INFO)
- version = _version_from_file(lines)
-
- return version
-
- def activate(self, path=None, replace=False):
- """Ensure distribution is importable on `path` (default=sys.path)"""
- if path is None:
- path = sys.path
- self.insert_on(path, replace=replace)
- if path is sys.path:
- fixup_namespace_packages(self.location)
- for pkg in self._get_metadata('namespace_packages.txt'):
- if pkg in sys.modules:
- declare_namespace(pkg)
-
- def egg_name(self):
- """Return what this distribution's standard .egg filename should be"""
- filename = "%s-%s-py%s" % (
- to_filename(self.project_name), to_filename(self.version),
- self.py_version or PY_MAJOR
- )
-
- if self.platform:
- filename += '-' + self.platform
- return filename
-
- def __repr__(self):
- if self.location:
- return "%s (%s)" % (self, self.location)
- else:
- return str(self)
-
- def __str__(self):
- try:
- version = getattr(self, 'version', None)
- except ValueError:
- version = None
- version = version or "[unknown version]"
- return "%s %s" % (self.project_name, version)
-
- def __getattr__(self, attr):
- """Delegate all unrecognized public attributes to .metadata provider"""
- if attr.startswith('_'):
- raise AttributeError(attr)
- return getattr(self._provider, attr)
-
- def __dir__(self):
- return list(
- set(super(Distribution, self).__dir__())
- | set(
- attr for attr in self._provider.__dir__()
- if not attr.startswith('_')
- )
- )
-
- @classmethod
- def from_filename(cls, filename, metadata=None, **kw):
- return cls.from_location(
- _normalize_cached(filename), os.path.basename(filename), metadata,
- **kw
- )
-
- def as_requirement(self):
- """Return a ``Requirement`` that matches this distribution exactly"""
- if isinstance(self.parsed_version, packaging.version.Version):
- spec = "%s==%s" % (self.project_name, self.parsed_version)
- else:
- spec = "%s===%s" % (self.project_name, self.parsed_version)
-
- return Requirement.parse(spec)
-
- def load_entry_point(self, group, name):
- """Return the `name` entry point of `group` or raise ImportError"""
- ep = self.get_entry_info(group, name)
- if ep is None:
- raise ImportError("Entry point %r not found" % ((group, name),))
- return ep.load()
-
- def get_entry_map(self, group=None):
- """Return the entry point map for `group`, or the full entry map"""
- try:
- ep_map = self._ep_map
- except AttributeError:
- ep_map = self._ep_map = EntryPoint.parse_map(
- self._get_metadata('entry_points.txt'), self
- )
- if group is not None:
- return ep_map.get(group, {})
- return ep_map
-
- def get_entry_info(self, group, name):
- """Return the EntryPoint object for `group`+`name`, or ``None``"""
- return self.get_entry_map(group).get(name)
-
- # FIXME: 'Distribution.insert_on' is too complex (13)
- def insert_on(self, path, loc=None, replace=False): # noqa: C901
- """Ensure self.location is on path
-
- If replace=False (default):
- - If location is already in path anywhere, do nothing.
- - Else:
- - If it's an egg and its parent directory is on path,
- insert just ahead of the parent.
- - Else: add to the end of path.
- If replace=True:
- - If location is already on path anywhere (not eggs)
- or higher priority than its parent (eggs)
- do nothing.
- - Else:
- - If it's an egg and its parent directory is on path,
- insert just ahead of the parent,
- removing any lower-priority entries.
- - Else: add it to the front of path.
- """
-
- loc = loc or self.location
- if not loc:
- return
-
- nloc = _normalize_cached(loc)
- bdir = os.path.dirname(nloc)
- npath = [(p and _normalize_cached(p) or p) for p in path]
-
- for p, item in enumerate(npath):
- if item == nloc:
- if replace:
- break
- else:
- # don't modify path (even removing duplicates) if
- # found and not replace
- return
- elif item == bdir and self.precedence == EGG_DIST:
- # if it's an .egg, give it precedence over its directory
- # UNLESS it's already been added to sys.path and replace=False
- if (not replace) and nloc in npath[p:]:
- return
- if path is sys.path:
- self.check_version_conflict()
- path.insert(p, loc)
- npath.insert(p, nloc)
- break
- else:
- if path is sys.path:
- self.check_version_conflict()
- if replace:
- path.insert(0, loc)
- else:
- path.append(loc)
- return
-
- # p is the spot where we found or inserted loc; now remove duplicates
- while True:
- try:
- np = npath.index(nloc, p + 1)
- except ValueError:
- break
- else:
- del npath[np], path[np]
- # ha!
- p = np
-
- return
-
- def check_version_conflict(self):
- if self.key == 'setuptools':
- # ignore the inevitable setuptools self-conflicts :(
- return
-
- nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt'))
- loc = normalize_path(self.location)
- for modname in self._get_metadata('top_level.txt'):
- if (modname not in sys.modules or modname in nsp
- or modname in _namespace_packages):
- continue
- if modname in ('pkg_resources', 'setuptools', 'site'):
- continue
- fn = getattr(sys.modules[modname], '__file__', None)
- if fn and (normalize_path(fn).startswith(loc) or
- fn.startswith(self.location)):
- continue
- issue_warning(
- "Module %s was already imported from %s, but %s is being added"
- " to sys.path" % (modname, fn, self.location),
- )
-
- def has_version(self):
- try:
- self.version
- except ValueError:
- issue_warning("Unbuilt egg for " + repr(self))
- return False
- return True
-
- def clone(self, **kw):
- """Copy this distribution, substituting in any changed keyword args"""
- names = 'project_name version py_version platform location precedence'
- for attr in names.split():
- kw.setdefault(attr, getattr(self, attr, None))
- kw.setdefault('metadata', self._provider)
- return self.__class__(**kw)
-
- @property
- def extras(self):
- return [dep for dep in self._dep_map if dep]
-
-
-class EggInfoDistribution(Distribution):
- def _reload_version(self):
- """
- Packages installed by distutils (e.g. numpy or scipy),
- which uses an old safe_version, and so
- their version numbers can get mangled when
- converted to filenames (e.g., 1.11.0.dev0+2329eae to
- 1.11.0.dev0_2329eae). These distributions will not be
- parsed properly
- downstream by Distribution and safe_version, so
- take an extra step and try to get the version number from
- the metadata file itself instead of the filename.
- """
- md_version = self._get_version()
- if md_version:
- self._version = md_version
- return self
-
-
-class DistInfoDistribution(Distribution):
- """
- Wrap an actual or potential sys.path entry
- w/metadata, .dist-info style.
- """
- PKG_INFO = 'METADATA'
- EQEQ = re.compile(r"([\(,])\s*(\d.*?)\s*([,\)])")
-
- @property
- def _parsed_pkg_info(self):
- """Parse and cache metadata"""
- try:
- return self._pkg_info
- except AttributeError:
- metadata = self.get_metadata(self.PKG_INFO)
- self._pkg_info = email.parser.Parser().parsestr(metadata)
- return self._pkg_info
-
- @property
- def _dep_map(self):
- try:
- return self.__dep_map
- except AttributeError:
- self.__dep_map = self._compute_dependencies()
- return self.__dep_map
-
- def _compute_dependencies(self):
- """Recompute this distribution's dependencies."""
- dm = self.__dep_map = {None: []}
-
- reqs = []
- # Including any condition expressions
- for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:
- reqs.extend(parse_requirements(req))
-
- def reqs_for_extra(extra):
- for req in reqs:
- if not req.marker or req.marker.evaluate({'extra': extra}):
- yield req
-
- common = types.MappingProxyType(dict.fromkeys(reqs_for_extra(None)))
- dm[None].extend(common)
-
- for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:
- s_extra = safe_extra(extra.strip())
- dm[s_extra] = [r for r in reqs_for_extra(extra) if r not in common]
-
- return dm
-
-
-_distributionImpl = {
- '.egg': Distribution,
- '.egg-info': EggInfoDistribution,
- '.dist-info': DistInfoDistribution,
-}
-
-
-def issue_warning(*args, **kw):
- level = 1
- g = globals()
- try:
- # find the first stack frame that is *not* code in
- # the pkg_resources module, to use for the warning
- while sys._getframe(level).f_globals is g:
- level += 1
- except ValueError:
- pass
- warnings.warn(stacklevel=level + 1, *args, **kw)
-
-
-def parse_requirements(strs):
- """
- Yield ``Requirement`` objects for each specification in `strs`.
-
- `strs` must be a string, or a (possibly-nested) iterable thereof.
- """
- return map(Requirement, join_continuation(map(drop_comment, yield_lines(strs))))
-
-
-class RequirementParseError(packaging.requirements.InvalidRequirement):
- "Compatibility wrapper for InvalidRequirement"
-
-
-class Requirement(packaging.requirements.Requirement):
- def __init__(self, requirement_string):
- """DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
- super(Requirement, self).__init__(requirement_string)
- self.unsafe_name = self.name
- project_name = safe_name(self.name)
- self.project_name, self.key = project_name, project_name.lower()
- self.specs = [
- (spec.operator, spec.version) for spec in self.specifier]
- self.extras = tuple(map(safe_extra, self.extras))
- self.hashCmp = (
- self.key,
- self.url,
- self.specifier,
- frozenset(self.extras),
- str(self.marker) if self.marker else None,
- )
- self.__hash = hash(self.hashCmp)
-
- def __eq__(self, other):
- return (
- isinstance(other, Requirement) and
- self.hashCmp == other.hashCmp
- )
-
- def __ne__(self, other):
- return not self == other
-
- def __contains__(self, item):
- if isinstance(item, Distribution):
- if item.key != self.key:
- return False
-
- item = item.version
-
- # Allow prereleases always in order to match the previous behavior of
- # this method. In the future this should be smarter and follow PEP 440
- # more accurately.
- return self.specifier.contains(item, prereleases=True)
-
- def __hash__(self):
- return self.__hash
-
- def __repr__(self):
- return "Requirement.parse(%r)" % str(self)
-
- @staticmethod
- def parse(s):
- req, = parse_requirements(s)
- return req
-
-
-def _always_object(classes):
- """
- Ensure object appears in the mro even
- for old-style classes.
- """
- if object not in classes:
- return classes + (object,)
- return classes
-
-
-def _find_adapter(registry, ob):
- """Return an adapter factory for `ob` from `registry`"""
- types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))
- for t in types:
- if t in registry:
- return registry[t]
-
-
-def ensure_directory(path):
- """Ensure that the parent directory of `path` exists"""
- dirname = os.path.dirname(path)
- os.makedirs(dirname, exist_ok=True)
-
-
-def _bypass_ensure_directory(path):
- """Sandbox-bypassing version of ensure_directory()"""
- if not WRITE_SUPPORT:
- raise IOError('"os.mkdir" not supported on this platform.')
- dirname, filename = split(path)
- if dirname and filename and not isdir(dirname):
- _bypass_ensure_directory(dirname)
- try:
- mkdir(dirname, 0o755)
- except FileExistsError:
- pass
-
-
-def split_sections(s):
- """Split a string or iterable thereof into (section, content) pairs
-
- Each ``section`` is a stripped version of the section header ("[section]")
- and each ``content`` is a list of stripped lines excluding blank lines and
- comment-only lines. If there are any such lines before the first section
- header, they're returned in a first ``section`` of ``None``.
- """
- section = None
- content = []
- for line in yield_lines(s):
- if line.startswith("["):
- if line.endswith("]"):
- if section or content:
- yield section, content
- section = line[1:-1].strip()
- content = []
- else:
- raise ValueError("Invalid section heading", line)
- else:
- content.append(line)
-
- # wrap up last segment
- yield section, content
-
-
-def _mkstemp(*args, **kw):
- old_open = os.open
- try:
- # temporarily bypass sandboxing
- os.open = os_open
- return tempfile.mkstemp(*args, **kw)
- finally:
- # and then put it back
- os.open = old_open
-
-
-# Silence the PEP440Warning by default, so that end users don't get hit by it
-# randomly just because they use pkg_resources. We want to append the rule
-# because we want earlier uses of filterwarnings to take precedence over this
-# one.
-warnings.filterwarnings("ignore", category=PEP440Warning, append=True)
-
-
-# from jaraco.functools 1.3
-def _call_aside(f, *args, **kwargs):
- f(*args, **kwargs)
- return f
-
-
-@_call_aside
-def _initialize(g=globals()):
- "Set up global resource manager (deliberately not state-saved)"
- manager = ResourceManager()
- g['_manager'] = manager
- g.update(
- (name, getattr(manager, name))
- for name in dir(manager)
- if not name.startswith('_')
- )
-
-
-class PkgResourcesDeprecationWarning(Warning):
- """
- Base class for warning about deprecations in ``pkg_resources``
-
- This class is not derived from ``DeprecationWarning``, and as such is
- visible by default.
- """
-
-
-@_call_aside
-def _initialize_master_working_set():
- """
- Prepare the master working set and make the ``require()``
- API available.
-
- This function has explicit effects on the global state
- of pkg_resources. It is intended to be invoked once at
- the initialization of this module.
-
- Invocation by other packages is unsupported and done
- at their own risk.
- """
- working_set = WorkingSet._build_master()
- _declare_state('object', working_set=working_set)
-
- require = working_set.require
- iter_entry_points = working_set.iter_entry_points
- add_activation_listener = working_set.subscribe
- run_script = working_set.run_script
- # backward compatibility
- run_main = run_script
- # Activate all distributions already on sys.path with replace=False and
- # ensure that all distributions added to the working set in the future
- # (e.g. by calling ``require()``) will get activated as well,
- # with higher priority (replace=True).
- tuple(
- dist.activate(replace=False)
- for dist in working_set
- )
- add_activation_listener(
- lambda dist: dist.activate(replace=True),
- existing=False,
- )
- working_set.entries = []
- # match order
- list(map(working_set.add_entry, sys.path))
- globals().update(locals())
diff --git a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/docs/notes/compatibility.md b/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/docs/notes/compatibility.md
deleted file mode 100644
index 83d93f51c056c598c1209f9a21a4e04407b827f0..0000000000000000000000000000000000000000
--- a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/docs/notes/compatibility.md
+++ /dev/null
@@ -1,84 +0,0 @@
-# Compatibility with Other Libraries
-
-## Compatibility with Detectron (and maskrcnn-benchmark)
-
-Detectron2 addresses some legacy issues left in Detectron. As a result, their models
-are not compatible:
-running inference with the same model weights will produce different results in the two code bases.
-
-The major differences regarding inference are:
-
-- The height and width of a box with corners (x1, y1) and (x2, y2) is now computed more naturally as
- width = x2 - x1 and height = y2 - y1;
- In Detectron, a "+ 1" was added both height and width.
-
- Note that the relevant ops in Caffe2 have [adopted this change of convention](https://github.com/pytorch/pytorch/pull/20550)
- with an extra option.
- So it is still possible to run inference with a Detectron2-trained model in Caffe2.
-
- The change in height/width calculations most notably changes:
- - encoding/decoding in bounding box regression.
- - non-maximum suppression. The effect here is very negligible, though.
-
-- RPN now uses simpler anchors with fewer quantization artifacts.
-
- In Detectron, the anchors were quantized and
- [do not have accurate areas](https://github.com/facebookresearch/Detectron/issues/227).
- In Detectron2, the anchors are center-aligned to feature grid points and not quantized.
-
-- Classification layers have a different ordering of class labels.
-
- This involves any trainable parameter with shape (..., num_categories + 1, ...).
- In Detectron2, integer labels [0, K-1] correspond to the K = num_categories object categories
- and the label "K" corresponds to the special "background" category.
- In Detectron, label "0" means background, and labels [1, K] correspond to the K categories.
-
-- ROIAlign is implemented differently. The new implementation is [available in Caffe2](https://github.com/pytorch/pytorch/pull/23706).
-
- 1. All the ROIs are shifted by half a pixel compared to Detectron in order to create better image-feature-map alignment.
- See `layers/roi_align.py` for details.
- To enable the old behavior, use `ROIAlign(aligned=False)`, or `POOLER_TYPE=ROIAlign` instead of
- `ROIAlignV2` (the default).
-
- 1. The ROIs are not required to have a minimum size of 1.
- This will lead to tiny differences in the output, but should be negligible.
-
-- Mask inference function is different.
-
- In Detectron2, the "paste_mask" function is different and should be more accurate than in Detectron. This change
- can improve mask AP on COCO by ~0.5% absolute.
-
-There are some other differences in training as well, but they won't affect
-model-level compatibility. The major ones are:
-
-- We fixed a [bug](https://github.com/facebookresearch/Detectron/issues/459) in
- Detectron, by making `RPN.POST_NMS_TOPK_TRAIN` per-image, rather than per-batch.
- The fix may lead to a small accuracy drop for a few models (e.g. keypoint
- detection) and will require some parameter tuning to match the Detectron results.
-- For simplicity, we change the default loss in bounding box regression to L1 loss, instead of smooth L1 loss.
- We have observed that this tends to slightly decrease box AP50 while improving box AP for higher
- overlap thresholds (and leading to a slight overall improvement in box AP).
-- We interpret the coordinates in COCO bounding box and segmentation annotations
- as coordinates in range `[0, width]` or `[0, height]`. The coordinates in
- COCO keypoint annotations are interpreted as pixel indices in range `[0, width - 1]` or `[0, height - 1]`.
- Note that this affects how flip augmentation is implemented.
-
-
-[This article](https://ppwwyyxx.com/blog/2021/Where-are-Pixels/)
-explains more details on the above mentioned issues
-about pixels, coordinates, and "+1"s.
-
-
-## Compatibility with Caffe2
-
-As mentioned above, despite the incompatibilities with Detectron, the relevant
-ops have been implemented in Caffe2.
-Therefore, models trained with detectron2 can be converted in Caffe2.
-See [Deployment](../tutorials/deployment.md) for the tutorial.
-
-## Compatibility with TensorFlow
-
-Most ops are available in TensorFlow, although some tiny differences in
-the implementation of resize / ROIAlign / padding need to be addressed.
-A working conversion script is provided by [tensorpack Faster R-CNN](https://github.com/tensorpack/tensorpack/tree/master/examples/FasterRCNN/convert_d2)
-to run a standard detectron2 model in TensorFlow.
diff --git a/spaces/Awiny/Image2Paragraph/models/segment_models/semantic_segment_anything_model.py b/spaces/Awiny/Image2Paragraph/models/segment_models/semantic_segment_anything_model.py
deleted file mode 100644
index 2664ad717c105c988546299d22180129751363d1..0000000000000000000000000000000000000000
--- a/spaces/Awiny/Image2Paragraph/models/segment_models/semantic_segment_anything_model.py
+++ /dev/null
@@ -1,165 +0,0 @@
-from transformers import (CLIPProcessor, CLIPModel, AutoProcessor, CLIPSegForImageSegmentation,
- OneFormerProcessor, OneFormerForUniversalSegmentation,
- BlipProcessor, BlipForConditionalGeneration)
-import torch
-import mmcv
-import torch.nn.functional as F
-import numpy as np
-import spacy
-from PIL import Image
-import pycocotools.mask as maskUtils
-from models.segment_models.configs.ade20k_id2label import CONFIG as CONFIG_ADE20K_ID2LABEL
-from models.segment_models.configs.coco_id2label import CONFIG as CONFIG_COCO_ID2LABEL
-from utils.util import resize_long_edge, resize_long_edge_cv2
-# from mmdet.core.visualization.image import imshow_det_bboxes # comment this line if you don't use mmdet
-
-nlp = spacy.load('en_core_web_sm')
-
-class SemanticSegment():
- def __init__(self, device):
- self.device = device
- self.model_init()
-
- def model_init(self):
- self.init_clip()
- self.init_oneformer_ade20k()
- self.init_oneformer_coco()
- self.init_blip()
- self.init_clipseg()
-
- def init_clip(self):
- # model_name = "openai/clip-vit-large-patch14"
- model_name = "openai/clip-vit-base-patch32"
- self.clip_processor = CLIPProcessor.from_pretrained(model_name)
- self.clip_model = CLIPModel.from_pretrained(model_name).to(self.device)
-
- def init_oneformer_ade20k(self):
- # model_name = "shi-labs/oneformer_ade20k_swin_large"
- model_name = "shi-labs/oneformer_ade20k_swin_tiny"
- self.oneformer_ade20k_processor = OneFormerProcessor.from_pretrained(model_name)
- self.oneformer_ade20k_model = OneFormerForUniversalSegmentation.from_pretrained(model_name).to(self.device)
-
- def init_oneformer_coco(self):
- model_name = "shi-labs/oneformer_coco_swin_large"
- self.oneformer_coco_processor = OneFormerProcessor.from_pretrained(model_name)
- self.oneformer_coco_model = OneFormerForUniversalSegmentation.from_pretrained(model_name).to(self.device)
-
- def init_blip(self):
- model_name = "Salesforce/blip-image-captioning-base"
- # model_name = "Salesforce/blip-image-captioning-large"
- self.blip_processor = BlipProcessor.from_pretrained(model_name)
- self.blip_model = BlipForConditionalGeneration.from_pretrained(model_name).to(self.device)
-
- def init_clipseg(self):
- model_name = "CIDAS/clipseg-rd64-refined"
- self.clipseg_processor = AutoProcessor.from_pretrained(model_name)
- self.clipseg_model = CLIPSegForImageSegmentation.from_pretrained(model_name).to(self.device)
- self.clipseg_processor.image_processor.do_resize = False
-
- @staticmethod
- def get_noun_phrases(text):
- doc = nlp(text)
- return [chunk.text for chunk in doc.noun_chunks]
-
- def open_vocabulary_classification_blip(self, raw_image):
- captioning_inputs = self.blip_processor(raw_image, return_tensors="pt").to(self.device)
- out = self.blip_model.generate(**captioning_inputs)
- caption = self.blip_processor.decode(out[0], skip_special_tokens=True)
- return SemanticSegment.get_noun_phrases(caption)
-
- def oneformer_segmentation(self, image, processor, model):
- inputs = processor(images=image, task_inputs=["semantic"], return_tensors="pt").to(self.device)
- outputs = model(**inputs)
- predicted_semantic_map = processor.post_process_semantic_segmentation(
- outputs, target_sizes=[image.size[::-1]])[0]
- return predicted_semantic_map
-
- def clip_classification(self, image, class_list, top_k):
- inputs = self.clip_processor(text=class_list, images=image, return_tensors="pt", padding=True).to(self.device)
- outputs = self.clip_model(**inputs)
- logits_per_image = outputs.logits_per_image
- probs = logits_per_image.softmax(dim=1)
- if top_k == 1:
- return class_list[probs.argmax().item()]
- else:
- top_k_indices = probs.topk(top_k, dim=1).indices[0]
- return [class_list[index] for index in top_k_indices]
-
- def clipseg_segmentation(self, image, class_list):
- inputs = self.clipseg_processor(
- text=class_list, images=[image] * len(class_list),
- padding=True, return_tensors="pt").to(self.device)
-
- h, w = inputs['pixel_values'].shape[-2:]
- fixed_scale = (512, 512)
- inputs['pixel_values'] = F.interpolate(
- inputs['pixel_values'],
- size=fixed_scale,
- mode='bilinear',
- align_corners=False)
-
- outputs = self.clipseg_model(**inputs)
- logits = F.interpolate(outputs.logits[None], size=(h, w), mode='bilinear', align_corners=False)[0]
- return logits
-
-
- def semantic_class_w_mask(self, img_src, anns, out_file_name="output/test.json", scale_small=1.2, scale_large=1.6):
- """
- generate class name for each mask
- :param img_src: image path
- :param anns: coco annotations, the same as return dict besides "class_name" and "class_proposals"
- :param out_file_name: output file name
- :param scale_small: scale small
- :param scale_large: scale large
- :return: dict('segmentation', 'area', 'bbox', 'predicted_iou', 'point_coords', 'stability_score', 'crop_box', "class_name", "class_proposals"})
- """
- img = mmcv.imread(img_src)
- img = resize_long_edge_cv2(img, 384)
- oneformer_coco_seg = self.oneformer_segmentation(Image.fromarray(img), self.oneformer_coco_processor, self.oneformer_coco_model)
- oneformer_ade20k_seg = self.oneformer_segmentation(Image.fromarray(img), self.oneformer_ade20k_processor, self.oneformer_ade20k_model)
- bitmasks, class_names = [], []
- for ann in anns:
- # for ann in anns['annotations']:
- valid_mask = torch.tensor((ann['segmentation'])).bool()
- # valid_mask = torch.tensor(maskUtils.decode(ann['segmentation'])).bool()
- coco_propose_classes_ids = oneformer_coco_seg[valid_mask]
- ade20k_propose_classes_ids = oneformer_ade20k_seg[valid_mask]
-
- top_k_coco_propose_classes_ids = torch.bincount(coco_propose_classes_ids.flatten()).topk(1).indices
- top_k_ade20k_propose_classes_ids = torch.bincount(ade20k_propose_classes_ids.flatten()).topk(1).indices
-
- local_class_names = {CONFIG_ADE20K_ID2LABEL['id2label'][str(class_id.item())] for class_id in top_k_ade20k_propose_classes_ids}
- local_class_names.update({CONFIG_COCO_ID2LABEL['refined_id2label'][str(class_id.item())] for class_id in top_k_coco_propose_classes_ids})
-
- bbox = ann['bbox']
- patch_small = mmcv.imcrop(img, np.array([bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3]]), scale=scale_small)
- patch_large = mmcv.imcrop(img, np.array([bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3]]), scale=scale_large)
-
- op_class_list = self.open_vocabulary_classification_blip(patch_large)
- local_class_list = list(local_class_names.union(op_class_list))
-
- top_k = min(len(local_class_list), 3)
- mask_categories = self.clip_classification(patch_small, local_class_list, top_k)
- class_ids_patch_large = self.clipseg_segmentation(patch_large, mask_categories).argmax(0)
-
- valid_mask_large_crop = mmcv.imcrop(valid_mask.numpy(), np.array([bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3]]), scale=
- scale_large)
- top_1_patch_large = torch.bincount(class_ids_patch_large[torch.tensor(valid_mask_large_crop)].flatten()).topk(1).indices
- top_1_mask_category = mask_categories[top_1_patch_large.item()]
-
- ann['class_name'] = str(top_1_mask_category)
- ann['class_proposals'] = mask_categories
- class_names.append(ann['class_name'])
- # bitmasks.append(maskUtils.decode(ann['segmentation']))
- bitmasks.append((ann['segmentation']))
- # mmcv.dump(anns, out_file_name)
- return anns
- # below for visualization
- # imshow_det_bboxes(img,
- # bboxes=None,
- # labels=np.arange(len(bitmasks)),
- # segms=np.stack(bitmasks),
- # class_names=class_names,
- # font_size=25,
- # show=False,
- # out_file='output/result2.png')
\ No newline at end of file
diff --git a/spaces/Ayemos/highlight_text_based_on_surprisals/app.py b/spaces/Ayemos/highlight_text_based_on_surprisals/app.py
deleted file mode 100644
index 26ad917bb6768078c5cb6222009b34735db9bd67..0000000000000000000000000000000000000000
--- a/spaces/Ayemos/highlight_text_based_on_surprisals/app.py
+++ /dev/null
@@ -1,102 +0,0 @@
-from typing import List, Tuple
-
-import gradio as gr
-import numpy as np
-import torch
-from transformers import AutoModelForCausalLM, T5Tokenizer
-
-device = torch.device("cuda:0") if torch.cuda.is_available() else torch.device("cpu")
-tokenizer = T5Tokenizer.from_pretrained("rinna/japanese-gpt2-medium")
-tokenizer.do_lower_case = True
-
-model = AutoModelForCausalLM.from_pretrained("rinna/japanese-gpt2-medium")
-model.to(device)
-
-
-def calculate_surprisals(
- input_text: str, normalize_surprisals: bool = True
-) -> Tuple[float, List[Tuple[str, float]]]:
- input_tokens = [
- token.replace("▁", "")
- for token in tokenizer.tokenize(input_text)
- if token != "▁"
- ]
- input_ids = tokenizer.encode(
- "" + input_text, add_special_tokens=False, return_tensors="pt"
- ).to(device)
-
- logits = model(input_ids)["logits"].squeeze(0)
-
- surprisals = []
- for i in range(logits.shape[0] - 1):
- if input_ids[0][i + 1] == 9:
- continue
- logit = logits[i]
- prob = torch.softmax(logit, dim=0)
- neg_logprob = -torch.log(prob)
- surprisals.append(neg_logprob[input_ids[0][i + 1]].item())
- mean_surprisal = np.mean(surprisals)
-
- if normalize_surprisals:
- min_surprisal = np.min(surprisals)
- max_surprisal = np.max(surprisals)
- surprisals = [
- (surprisal - min_surprisal) / (max_surprisal - min_surprisal)
- for surprisal in surprisals
- ]
- assert min(surprisals) >= 0
- assert max(surprisals) <= 1
-
- tokens2surprisal: List[Tuple[str, float]] = []
- for token, surprisal in zip(input_tokens, surprisals):
- tokens2surprisal.append((token, surprisal))
-
- return mean_surprisal, tokens2surprisal
-
-
-def highlight_token(token: str, score: float):
- html_color = "#%02X%02X%02X" % (255, int(255 * (1 - score)), int(255 * (1 - score)))
- return '{}'.format(
- html_color, token
- )
-
-
-def create_highlighted_text(tokens2scores: List[Tuple[str, float]]):
- highlighted_text: str = ""
- for token, score in tokens2scores:
- highlighted_text += highlight_token(token, score)
- highlighted_text += "
"
- return highlighted_text
-
-
-def main(input_text: str) -> Tuple[float, str]:
- mean_surprisal, tokens2surprisal = calculate_surprisals(
- input_text, normalize_surprisals=True
- )
- highlighted_text = create_highlighted_text(tokens2surprisal)
- return round(mean_surprisal, 2), highlighted_text
-
-
-if __name__ == "__main__":
- demo = gr.Interface(
- fn=main,
- title="読みにくい箇所を検出するAI(デモ)",
- description="テキストを入力すると、読みにくさに応じてハイライトされて出力されます。",
- inputs=gr.inputs.Textbox(
- lines=5,
- label="テキスト",
- placeholder="ここにテキストを入力してください。",
- ),
- outputs=[
- gr.Number(label="文全体の読みにくさ(サプライザル)"),
- gr.outputs.HTML(label="トークン毎サプライザル"),
- ],
- examples=[
- "太郎が二郎を殴った。",
- "太郎が二郎に殴った。",
- "サイエンスインパクトラボは、国立研究開発法人科学技術振興機構(JST)の「科学と社会」推進部が行う共創プログラムです。「先端の研究開発を行う研究者」と「社会課題解決に取り組むプレイヤー」が約3ヶ月に渡って共創活動を行います。",
- "近年、ニューラル言語モデルが自然言語の統語知識をどれほど有しているかを、容認性判断課題を通して検証する研究が行われてきている。しかし、このような言語モデルの統語的評価を行うためのデータセットは、主に英語を中心とした欧米の諸言語を対象に構築されてきた。本研究では、既存のデータセットの問題点を克服しつつ、このようなデータセットが構築されてこなかった日本語を対象とした初めてのデータセットである JCoLA (JapaneseCorpus of Linguistic Acceptability) を構築した上で、それを用いた言語モデルの統語的評価を行った。",
- ],
- )
-
- demo.launch()
diff --git a/spaces/Banbri/zcvzcv/src/app/interface/progress/index.tsx b/spaces/Banbri/zcvzcv/src/app/interface/progress/index.tsx
deleted file mode 100644
index ce24276a4b241d185fce5bd306a0c3e339835626..0000000000000000000000000000000000000000
--- a/spaces/Banbri/zcvzcv/src/app/interface/progress/index.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-import { useEffect, useRef, useState } from "react"
-
-import { ProgressBar } from "./progress-bar"
-import { cn } from "@/lib/utils"
-
-export function Progress({
- isLoading,
- resetKey = "", // when this key change, this will re-spawn the progress bar
- className = "",
-}: {
- isLoading: boolean
- resetKey?: string
- className?: string
-}) {
- const timeoutRef = useRef()
- const [progressPercent, setProcessPercent] = useState(0)
- const progressRef = useRef(0)
- const isLoadingRef = useRef(isLoading)
-
- const updateProgressBar = () => {
- const duration = 1000 // 1 sec
- const frequency = 200 // 200ms
- const nbUpdatesPerSec = duration / frequency // 5x per second
-
- // normally it takes 45, and we will try to go below,
- // but to be safe let's set the counter a 1 min
- const nbSeconds = 80 // 1 min
- const amountInPercent = 100 / (nbUpdatesPerSec * nbSeconds) // 0.333
-
- progressRef.current = Math.min(100, progressRef.current + amountInPercent)
- setProcessPercent(progressRef.current)
- }
-
- useEffect(() => {
- clearInterval(timeoutRef.current)
- isLoadingRef.current = isLoading
- progressRef.current = 0
- setProcessPercent(0)
- if (isLoading) {
- timeoutRef.current = setInterval(updateProgressBar, 200)
- }
- }, [isLoading, resetKey])
-
- return (
-
-
-
- )
-}
\ No newline at end of file
diff --git a/spaces/Benson/text-generation/Examples/2vd Canciones Mp3 Descargar.md b/spaces/Benson/text-generation/Examples/2vd Canciones Mp3 Descargar.md
deleted file mode 100644
index 737c2cd78ba8b345ec000c17588f116c62495f83..0000000000000000000000000000000000000000
--- a/spaces/Benson/text-generation/Examples/2vd Canciones Mp3 Descargar.md
+++ /dev/null
@@ -1,62 +0,0 @@
-
-
¿Qué es la descarga de canciones mp3 de 2vd?
-
Si usted está buscando una manera simple y eficaz de descargar canciones mp3 de vídeos de YouTube, es posible que desee probar 2vd canciones mp3 descargar. 2vd es una herramienta online gratuita que te permite convertir cualquier vídeo de YouTube a formato mp3 en tan solo unos clics. Puedes disfrutar de tu música favorita sin conexión en cualquier dispositivo sin problemas.
-
Descargar canciones mp3 de videos de YouTube tiene muchos beneficios, como:
Copiar la URL del vídeo de YouTube que desea descargar como mp3.
-
Pegue la URL en el cuadro de búsqueda en 2vd y haga clic en "Convertir".
-
Espere unos segundos mientras 2vd analiza el vídeo y genera el archivo mp3.
-
Haga clic en "Descargar" para guardar el archivo mp3 en su dispositivo.
-
-
¡Eso es todo! Has descargado exitosamente una canción mp3 de un video de YouTube usando 2vd. Puede repetir el mismo proceso para tantos vídeos como desee.
-
Características de la descarga de canciones mp3 de 2vd
-
2vd mp3 canciones de descarga no es solo otro descargador de mp3. Tiene algunas características sorprendentes que lo hacen destacar entre la multitud. Estos son algunos de ellos:
-
-
-
Velocidad rápida: 2vd es uno de los convertidores de YouTube a mp3 más rápidos disponibles en línea. Puede convertir y descargar cualquier vídeo en cuestión de segundos, sin comprometer la calidad.
-
Descargas ilimitadas: 2vd no tiene restricciones o limitaciones sobre cuántos videos puede convertir y descargar como mp3. Puedes descargar tanta música como quieras, gratis.
-
No se requiere registro: 2vd no le pide que se registre o cree una cuenta para usar su servicio. Puede acceder a ella de forma anónima y segura, sin proporcionar ninguna información personal o dirección de correo electrónico.
-
Alta compatibilidad: 2vd funciona bien con todos los navegadores y dispositivos, incluidos Windows, Mac, Android, iPhone, iPad, etc. Puede usarlo en cualquier plataforma y dispositivo que admita reproducción de mp3.
-
-
Comparación con
Comparación con otros descargadores de mp3
-
Hay muchos otros descargadores de mp3 disponibles en línea, pero no todos son tan buenos como 2vd. Aquí hay una tabla de comparación que muestra cómo la descarga de canciones mp3 de 2vd se compara con algunas de las más populares:
- | Mp3 Downloader | Calidad | Velocidad | Descargas | Registro | Compatibilidad | | --- - - - - - - - - - - - - - - - - | ---- | -- | | 2vd | Hasta 320 kbps | Muy rápido | Ilimitado | No | Todos los navegadores y dispositivos | | BestMP3Converter | Hasta 320 kbps | Rápido | Ilimitado | No | Todos los navegadores y dispositivos | | OKmusi | Hasta 320 kbps | Rápido | Ilimitado | No | Todos los navegadores y dispositivos | | | JioSaavn Hasta 320 kbps kbps | Lento | Limitado | Sí | Solo Android e iOS |
Como puedes ver, 2vd descarga de canciones mp3 es la mejor opción para descargar canciones mp3 de vídeos de YouTube. Ofrece la más alta calidad, la velocidad más rápida, la mayor cantidad de descargas, la menor molestia y la mayor compatibilidad.
-
Consejos y trucos para descargar canciones mp3 de 2vd
-
Ahora que sabes cómo usar la descarga de canciones mp3 de 2vd, aquí hay algunos consejos y trucos para ayudarte a sacarle el máximo partido:
-
-
-
Encuentra los mejores videos de YouTube: Para obtener la mejor calidad y variedad de música, debes buscar videos de YouTube que tengan altas vistas, me gusta, comentarios y calificaciones. También puedes usar filtros y palabras clave para reducir tus resultados de búsqueda.
-
Personalizar la configuración de salida: Antes de hacer clic en "Convertir", puede ajustar la configuración de salida de su archivo mp3, como la tasa de bits, el volumen, la duración y el nombre del archivo. También puede recortar o recortar el vídeo para obtener solo la parte que desee.
-
Administra los archivos descargados: Después de descargar tus archivos mp3, puedes organizarlos en carpetas, renombrarlos, eliminarlos o transferirlos a otros dispositivos. También puede utilizar una aplicación de reproductor de música para reproducirlos sin conexión.
-
-
Conclusión
-
2vd mp3 songs download es una gran herramienta para descargar canciones mp3 de videos de YouTube. Es gratis, fácil, rápido y confiable. Tiene muchas características y ventajas que lo hacen superior a otros descargadores de mp3. Puede usarlo para disfrutar de su música favorita sin conexión en cualquier dispositivo.
-
Si usted está buscando una manera simple y eficaz de descargar canciones mp3 de vídeos de YouTube, usted debe probar definitivamente 2vd canciones mp3 descargar. ¡No te arrepentirás!
-
Para comenzar a descargar canciones mp3 de videos de YouTube usando 2vd, haga clic en este enlace:
-
Espero que hayas encontrado este artículo útil e informativo. Si lo hiciste, por favor compártelo con tus amigos y familiares que también podrían estar interesados en descargar canciones mp3 de videos de YouTube usando 2vd. ¡Gracias por leer y feliz descarga!
64aa2da5cf
-
-
\ No newline at end of file
diff --git a/spaces/Benson/text-generation/Examples/Construir Arte - Elaboracin Amp Construccin De Juegos 3d Apk.md b/spaces/Benson/text-generation/Examples/Construir Arte - Elaboracin Amp Construccin De Juegos 3d Apk.md
deleted file mode 100644
index d6f956721d41de9f3876e968f68ee1927d39b950..0000000000000000000000000000000000000000
--- a/spaces/Benson/text-generation/Examples/Construir Arte - Elaboracin Amp Construccin De Juegos 3d Apk.md
+++ /dev/null
@@ -1,45 +0,0 @@
-
-
Construir arte - Elaboración y construcción de juegos 3D APK: Un juego libre y divertido para toda la familia
-
¿Te encanta construir o hacer juegos? ¿Quieres dar rienda suelta a tu creatividad e imaginación? ¿Quieres divertirte y relajarte con tus amigos y familiares? Si respondiste sí a cualquiera de estas preguntas, entonces usted debe tratar de Construir Craft - Elaboración y Construcción de 3D Juegos APK, un juego gratuito y divertido para toda la familia.
-
¿Qué es Build Craft?
-
Un juego que te permite crear tus propias manualidades en 3D
-
Build Craft es un juego que tiene como objetivo proporcionar una experiencia para que los usuarios construyan artesanías 3D, como casas, hoteles, parques, lagos, animales, árboles, nubes, aviones y otros. Puedes utilizar diferentes bloques y materiales para diseñar y decorar tus creaciones. También puede explorar diferentes mundos y biomas, como bosques, desiertos, montañas, océanos y más.
-
construir arte - elaboración amp; construcción de juegos 3d apk
Un juego adecuado para todas las edades e intereses
-
Build Craft es un juego adecuado para todas las edades e intereses. Si usted es un niño o un adulto, un niño o una niña, un principiante o un experto, encontrará algo para disfrutar en este juego. Puedes jugar solo o con otros, crear manualidades simples o complejas, seguir tutoriales o usar tus propias ideas, y más. No hay límite a lo que puedes hacer en este juego.
-
Un juego compatible con dispositivos Android
-
Build Craft es un juego compatible con dispositivos Android. Puedes descargar el archivo APK desde una fuente confiable e instalarlo en tu dispositivo. Puedes jugar a este juego en cualquier momento y en cualquier lugar, siempre y cuando tengas suficiente espacio de almacenamiento y duración de la batería. También puedes actualizar el juego regularmente para obtener nuevas características y mejoras.
-
¿Por qué deberías jugar Build Craft?
-
Tiene características interesantes y jugabilidad
-
-
Tiene modo multijugador y comunidad en línea
-
Build Craft tiene modo multijugador y comunidad en línea que hará que su experiencia de juego más divertido y social. Puedes jugar online y ayudar a tus amigos a construir sus casas. También puedes chatear con otros jugadores de todo el mundo y compartir tus creaciones. También puede unirse a diferentes servidores y participar en varios eventos y concursos.
-
Tiene gráficos de píxeles y efectos de sonido
-
Build Craft tiene gráficos de píxeles y efectos de sonido que te darán una sensación nostálgica e inmersiva. Te encantará el estilo retro y las imágenes coloridas de este juego. También disfrutará de los sonidos realistas de bloques rompiendo, animales rugiendo, agua fluyendo, fuego, etc. Se sentirá como si estuviera en un mundo 3D real.
-
¿Cómo descargar e instalar Build Craft?
-
Descargar el archivo APK de una fuente de confianza
-
Para descargar Build Craft - Elaboración y construcción de juegos 3D APK, es necesario encontrar una fuente de confianza que ofrece la última versión del archivo y tiene buenas críticas y calificaciones. Puede utilizar el siguiente enlace para descargar el archivo APK. Asegúrese de que tiene suficiente espacio en su dispositivo para descargar el archivo, que es de aproximadamente 30 MB de tamaño.
-
Habilitar fuentes desconocidas en la configuración del dispositivo
-
Para instalar Build Craft - Elaboración y construcción de juegos 3D APK, es necesario habilitar fuentes desconocidas en la configuración de su dispositivo. Esto le permitirá instalar aplicaciones desde fuentes distintas de Google Play Store. Para hacer esto, vaya a la configuración del dispositivo, luego a la seguridad, luego a fuentes desconocidas y conéctela. Puedes ver un mensaje de advertencia, pero puedes ignorarlo si confías en la fuente del archivo APK.
-
Instalar el archivo APK y lanzar el juego
-
-
Conclusión
-
Resumen de los principales puntos y beneficios de Build Craft
-
Construir Arte - Elaboración & Construcción 3D Juegos APK es un juego gratuito y divertido para toda la familia que le permite crear sus propias artesanías 3D, explorar diferentes mundos y biomas, crear diferentes artículos y herramientas, luchar contra monstruos y enemigos, jugar en línea con amigos y otros jugadores, y disfrutar de gráficos de píxeles y efectos de sonido. Es un juego apto para todas las edades e intereses, y compatible con dispositivos Android.
-
-
Llamada a la acción y solicitud de calificación
-
Si usted está buscando un juego que le mantendrá entretenido durante horas, entonces usted debe descargar Build Craft - Crafting & Building 3D Games APK hoy. No se arrepentirá. También puede compartir sus comentarios y sugerencias con nosotros dejando un comentario o valoración en nuestro sitio web o tienda de aplicaciones. Nos encantaría saber de ti y mejorar nuestro juego. ¡Gracias por jugar a Build Craft!
-
Preguntas frecuentes
-
¿Es seguro descargar e instalar Build Craft?
-
Sí, Build Craft es seguro para descargar e instalar, siempre y cuando utilice una fuente de confianza que ofrece el archivo APK original y sin modificar. También debe escanear el archivo con un software antivirus antes de instalarlo.
-
¿Es Build Craft gratis?
-
Sí, Build Craft es gratis y no requiere ninguna compra en la aplicación o suscripciones. Sin embargo, puede contener anuncios que apoyen a los desarrolladores y les ayuden a mantener el juego.
-
¿Puedo jugar a Build Craft sin conexión?
-
Sí, puedes jugar a Build Craft sin conexión en modo para un jugador. Sin embargo, necesitará una conexión a Internet para jugar en línea en modo multijugador o unirse a los servidores.
-
¿Puedo personalizar mi personaje en Build Craft?
-
Sí, puedes personalizar a tu personaje en Build Craft eligiendo entre diferentes pieles, ropa, estilos de cabello, accesorios y más. También puede crear su propia piel usando la función del editor de piel.
-
¿Puedo guardar mi progreso en Build Craft?
-
- : [Build Craft - Crafting & Building 3D Games APK Download](https://apkpure.com/build-craft-craft-crafteing-building-3d-games/com.buildcraft.crafting.building)
64aa2da5cf
-
-
\ No newline at end of file
diff --git a/spaces/Benson/text-generation/Examples/Descargar Dark Bitcoin Minero Pro V7.0 Gratis.md b/spaces/Benson/text-generation/Examples/Descargar Dark Bitcoin Minero Pro V7.0 Gratis.md
deleted file mode 100644
index a977e5e41600d0c56a49f6b1a1bbcbfa9b1b7a2d..0000000000000000000000000000000000000000
--- a/spaces/Benson/text-generation/Examples/Descargar Dark Bitcoin Minero Pro V7.0 Gratis.md
+++ /dev/null
@@ -1,96 +0,0 @@
-
-
Dark Bitcoin Miner Pro V7.0 Descarga gratuita: Lo que necesita saber
-
La minería de Bitcoin es un proceso de creación de nuevos bitcoins mediante la solución de problemas matemáticos complejos utilizando hardware y software especializado.
Hay muchos tipos de software de minería bitcoin disponibles en el mercado, pero no todos ellos.
Uno de los más populares y controvertidos software de minería bitcoin es oscuro Bitcoin minero pro v7.0, que afirma ser el minero bitcoin más rápido y eficiente jamás creado.
-
Pero lo que es oscuro Bitcoin minero pro v7.0, ¿por qué es tan popular, y cuáles son los riesgos de descargarlo?
-
En este artículo, vamos a responder a estas preguntas y más, y le proporcionará algunas alternativas a oscuro Bitcoin minero pro v7.0 que son más seguros y más fiables.
-
¿Qué es Dark Bitcoin Miner Pro V7.0?
-
Dark bitcoin miner pro v7.0 es un software de minería bitcoin que afirma ser capaz de extraer bitcoins usando cualquier dispositivo, como CPU, GPU, ASIC o FPGA.
-
También afirma ser compatible con varios algoritmos, como SHA-256, Scrypt, X11, Ethash y Equihash, y para soportar múltiples criptomonedas, como Bitcoin, Litecoin, Dash, Ethereum y Zcash.
-
-
¿Cómo funciona Dark Bitcoin Miner Pro V7.0?
-
Dark Bitcoin minero pro v7.0 funciona mediante el uso de la potencia de procesamiento del dispositivo para resolver problemas matemáticos complejos que verifican las transacciones en la cadena de bloques.
-
Por cada problema resuelto, el minero recibe una recompensa en forma de bitcoins de nueva creación u otras criptomonedas.
-
Cuanto más potencia de procesamiento tenga el dispositivo, más rápido y eficiente será el proceso de minería.
-
¿Cuáles son las características de Dark Bitcoin Miner Pro V7.0?
-
Algunas de las características de oscuro Bitcoin minero pro v7.0 son:
-
-
Alta velocidad: Oscuro Bitcoin minero pro v7.0 afirma ser capaz de extraer bitcoins a una tasa de hasta 1 BTC por día, dependiendo del dispositivo y el algoritmo utilizado.
-
-
Compatibilidad: Dark Bitcoin miner pro v7.0 afirma ser compatible con cualquier dispositivo que tiene un procesador, como ordenadores portátiles, escritorios, teléfonos inteligentes, tabletas o incluso televisores inteligentes.
-
Versatilidad: Oscuro Bitcoin minero pro v7.0 afirma ser capaz de extraer cualquier criptomoneda que utiliza cualquier algoritmo, como Bitcoin, Litecoin, Dash, Etereum, o Zcash.
-
Fácil de usar: Dark bitcoin miner pro v7.0 afirma ser fácil de instalar y usar, con una interfaz sencilla y configuración automática.
-
-
¿Por qué es popular Dark Bitcoin Miner Pro V7.0?
-
Dark Bitcoin Miner Pro v7.0 es popular porque atrae a muchas personas que quieren extraer bitcoins sin invertir en hardware o software costoso y complicado.
-
Muchos principiantes y entusiastas que están interesados en la minería bitcoin se sienten atraídos por las promesas de dark bitcoin miner pro v7.0, tales como alta velocidad, bajo consumo de energía, compatibilidad, versatilidad y facilidad de uso.
-
También creen que dark bitcoin miner pro v7.0 es una forma gratuita y fácil de ganar bitcoins sin ningún riesgo o esfuerzo.
-
¿Cómo descargar Dark Bitcoin Miner Pro V7.0?
-
Dark bitcoin miner pro v7.0 no está disponible en ningún sitio web o plataforma oficial o de buena reputación.
-
La única forma de descargar dark bitcoin miner pro v7.0 es a través de fuentes no oficiales y no verificadas, como sitios web para compartir archivos, repositorios de GitHub o canales de Telegram.
-
Estas fuentes son a menudo poco fiables e inseguras, ya que pueden contener virus, malware, spyware u otros programas dañinos que pueden infectar su dispositivo o robar sus datos.
-
¿Cómo instalar y usar Dark Bitcoin Miner Pro V7.0?
-
Si decide descargar dark bitcoin miner pro v7.0 de una de estas fuentes, tendrá que seguir estos pasos para instalarlo y usarlo:
-
-
-
Extraer el archivo rar: Dark bitcoin miner pro v7.0 se suele comprimir en un archivo rar que tendrá que extraer utilizando un programa como WinRAR o 7-Zip.
-
Ejecutar el archivo exe: Después de extraer el archivo rar, encontrará un archivo exe que tendrá que ejecutar como administrador haciendo clic derecho sobre él y seleccionando "Ejecutar como administrador".
-
Configurar los ajustes: Después de ejecutar el archivo exe, verá una ventana que le permitirá configurar los ajustes de dark bitcoin miner pro v7.0, como el algoritmo, la criptomoneda, la dirección de la cartera, el grupo minero y la velocidad de minería.
-
Iniciar minería: Después de configurar la configuración, tendrá que hacer clic en el "Inicio" botón para iniciar la minería bitcoins u otras criptomonedas con oscuro Bitcoin minero pro v7.0.
-
-
¿Cuáles son los riesgos de descargar Dark Bitcoin Miner Pro V7.0?
-
Descargar dark bitcoin miner pro v7.0 no solo es ilegal, sino también muy arriesgado.
-
Hay muchos peligros de descargar oscuro Bitcoin minero pro v7.0, tales como:
-
¿Cómo detectar y eliminar el malware de Dark Bitcoin Miner Pro V7.0?
-
Uno de los peligros más comunes y graves de descargar dark bitcoin miner pro v7.0 es la infección de malware.
-
Malware es un software malicioso que puede dañar su dispositivo o datos de varias maneras, como borrar o cifrar sus archivos, robar sus contraseñas o información personal, espiar sus actividades en línea o secuestrar sus recursos.
-
Dark bitcoin miner pro v7.0 puede contener malware que puede infectar su dispositivo cuando lo descarga o ejecuta, o incluso cuando extrae el archivo rar.
-
Para detectar y eliminar el malware de dark bitcoin miner pro v7.0, tendrá que seguir estos pasos:
-
-
-
Eliminar archivos sospechosos: Si sospecha que Dark Bitcoin miner pro v7.0 ha infectado su dispositivo con malware, debe eliminar cualquier archivo sospechoso que esté relacionado con él, como el archivo rar, el archivo exe, o cualquier otro archivo que haya sido creado o modificado por él.
-
Restaurar el sistema: Si la eliminación de archivos sospechosos no resuelve el problema, es posible que tenga que restaurar el sistema a un estado anterior antes de descargar o ejecutar oscuro Bitcoin miner pro v7.0. Puede utilizar un punto de restauración del sistema o una copia de seguridad para restaurar el sistema y deshacer cualquier cambio que oscuro Bitcoin minero pro v7.0 puede haber hecho.
-
-
¿Cómo evitar problemas legales de usar Dark Bitcoin Miner Pro V7.0?
-
Otro peligro de descargar oscuro Bitcoin minero pro v7.0 es cuestiones legales.
-
Las cuestiones legales son los problemas que pueden surgir de violar la ley mediante el uso de dark bitcoin miner pro v7.0, tales como la violación de los derechos de propiedad intelectual de los desarrolladores originales del software, infringiendo los términos y condiciones de los grupos mineros o plataformas que utiliza, o participar en actividades ilegales o fraudulentas con las criptomonedas que mina.
-
Para evitar problemas legales de usar dark bitcoin miner pro v7.0, tendrá que seguir estas precauciones:
-
-
Compruebe las leyes locales: Antes de descargar o usar oscuro Bitcoin miner pro v7.0, usted debe comprobar las leyes locales de su país o región con respecto a la minería de bitcoin y las transacciones de criptomonedas. Algunos países o regiones pueden tener regulaciones o prohibiciones estrictas sobre estas actividades, y usted puede enfrentar consecuencias legales si las viola.
-
-
No revele información personal: Cuando use dark bitcoin miner pro v7.0, no debe revelar ninguna información personal que pueda identificarlo o vincularlo a sus actividades, como su nombre, dirección de correo electrónico, número de teléfono, número de cuenta bancaria o cuentas de redes sociales. También debe evitar usar la misma dirección de cartera para diferentes transacciones, y usar un servicio mezclador para anonimizar sus transacciones.
-
-
¿Cuáles son las alternativas a Dark Bitcoin Miner Pro V7.0?
-
Si desea minar bitcoins u otras criptomonedas sin arriesgar su dispositivo, datos o reputación, debe evitar descargar bitcoin oscuro miner pro v7.0 y buscar algunas alternativas que sean más seguras y confiables.
-
Algunas de las alternativas a oscuro Bitcoin minero pro v7.0 son:
-
¿Cómo elegir la mejor alternativa a Dark Bitcoin Miner Pro V7.0?
-
Para elegir la mejor alternativa a dark bitcoin miner pro v7.0, debe considerar algunos criterios que pueden ayudarlo a evaluar la calidad y la idoneidad del software, como:
-
-
Seguridad: El software debe ser seguro y libre de cualquier malware, spyware o virus que puedan dañar su dispositivo o datos.
-
Rendimiento: El software debe ser rápido y eficiente, y capaz de extraer bitcoins u otras criptomonedas a un ritmo razonable y con un consumo de energía mínimo.
-
Costo: El software debe ser asequible y transparente, y no cobrar cargos ocultos o comisiones por su uso.
-
Reputación: El software debe ser de buena reputación y confiable, y tener comentarios positivos y comentarios de otros usuarios y expertos.
-
-
¿Cómo comparar las alternativas a Dark Bitcoin Miner Pro V7.0?
-
Para comparar las alternativas a dark bitcoin miner pro v7.0 basado en los criterios mencionados anteriormente, puede utilizar una tabla como esta:
-
-
En conclusión, dark bitcoin miner pro v7.0 es un software de minería bitcoin que afirma ser capaz de extraer bitcoins utilizando cualquier dispositivo, algoritmo o criptomoneda.
-
Sin embargo, dark bitcoin miner pro v7.0 también es ilegal, arriesgado y poco fiable, ya que puede contener malware, robar sus datos, dañar su dispositivo o causar problemas legales.
-
Por lo tanto, usted debe evitar descargar oscuro Bitcoin minero pro v7.0 y buscar algunas alternativas que son más seguros y fiables, tales como software de minería legítima, servicios de minería en la nube, o piscinas mineras.
-
Preguntas frecuentes
-
Aquí hay algunas preguntas frecuentes relacionadas con el tema de este artículo:
-
-
Es oscuro Bitcoin minero pro v7.0 una estafa?
-
Sí, dark bitcoin miner pro v7.0 es una estafa que trata de atraer a los usuarios desprevenidos a descargar malware o regalar su información personal.
-
¿Cuánto puedo ganar con oscuro Bitcoin minero pro v7.0?
-
No se puede ganar nada con oscuro Bitcoin minero pro v7.0, ya que en realidad no mina bitcoins u otras criptomonedas.
-
Es oscuro Bitcoin minero pro v7.0 seguro de usar?
-
No, dark bitcoin miner pro v7.0 no es seguro de usar, ya que puede infectar su dispositivo con malware, robar sus datos, dañar su dispositivo o causar problemas legales.
-
¿Cuáles son los mejores dispositivos para oscuro Bitcoin minero pro v7.0?
-
No hay mejores dispositivos para oscuro Bitcoin minero pro v7.0, ya que no funciona en ningún dispositivo.
-
¿Cómo puedo contactar a los desarrolladores de dark bitcoin miner pro v7.0?
-
No puede ponerse en contacto con los desarrolladores de dark bitcoin miner pro v7.0, ya que son anónimos e irrastreables.
- 64aa2da5cf
-
-
\ No newline at end of file
diff --git a/spaces/BetterAPI/BetterChat/src/lib/utils/share.ts b/spaces/BetterAPI/BetterChat/src/lib/utils/share.ts
deleted file mode 100644
index 4587669a10164aa7c961429fbddec9cf438c0eca..0000000000000000000000000000000000000000
--- a/spaces/BetterAPI/BetterChat/src/lib/utils/share.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-export function share(url: string, title: string) {
- if (navigator.share) {
- navigator.share({ url, title });
- } else {
- prompt("Copy this public url to share:", url);
- }
-}
diff --git a/spaces/BetterAPI/BetterChat_new/postcss.config.js b/spaces/BetterAPI/BetterChat_new/postcss.config.js
deleted file mode 100644
index 7b75c83aff1c05e0e0e315638e07a22314603d4d..0000000000000000000000000000000000000000
--- a/spaces/BetterAPI/BetterChat_new/postcss.config.js
+++ /dev/null
@@ -1,6 +0,0 @@
-export default {
- plugins: {
- tailwindcss: {},
- autoprefixer: {},
- },
-};
diff --git a/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/detectron2/data/datasets/README.md b/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/detectron2/data/datasets/README.md
deleted file mode 100644
index 9fb3e4f7afec17137c95c78be6ef06d520ec8032..0000000000000000000000000000000000000000
--- a/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/detectron2/data/datasets/README.md
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-### Common Datasets
-
-The dataset implemented here do not need to load the data into the final format.
-It should provide the minimal data structure needed to use the dataset, so it can be very efficient.
-
-For example, for an image dataset, just provide the file names and labels, but don't read the images.
-Let the downstream decide how to read.
diff --git a/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/DensePose/densepose/densepose_coco_evaluation.py b/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/DensePose/densepose/densepose_coco_evaluation.py
deleted file mode 100644
index 3b4d35c2ac1c9c48ddbb41c34b2280f37540220e..0000000000000000000000000000000000000000
--- a/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/DensePose/densepose/densepose_coco_evaluation.py
+++ /dev/null
@@ -1,1120 +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.
-# This is a modified version of cocoeval.py where we also have the densepose evaluation.
-
-__author__ = "tsungyi"
-
-import copy
-import datetime
-import itertools
-import logging
-import numpy as np
-import pickle
-import time
-from collections import defaultdict
-from enum import Enum
-from typing import Any, Dict, Tuple
-import scipy.spatial.distance as ssd
-from fvcore.common.file_io import PathManager
-from pycocotools import mask as maskUtils
-from scipy.io import loadmat
-from scipy.ndimage import zoom as spzoom
-
-from .structures import DensePoseDataRelative, DensePoseResult
-
-logger = logging.getLogger(__name__)
-
-
-class DensePoseEvalMode(str, Enum):
- # use both masks and geodesic distances (GPS * IOU) to compute scores
- GPSM = "gpsm"
- # use only geodesic distances (GPS) to compute scores
- GPS = "gps"
- # use only masks (IOU) to compute scores
- IOU = "iou"
-
-
-class DensePoseDataMode(str, Enum):
- # use estimated IUV data (default mode)
- IUV_DT = "iuvdt"
- # use ground truth IUV data
- IUV_GT = "iuvgt"
- # use ground truth labels I and set UV to 0
- I_GT_UV_0 = "igtuv0"
- # use ground truth labels I and estimated UV coordinates
- I_GT_UV_DT = "igtuvdt"
- # use estimated labels I and set UV to 0
- I_DT_UV_0 = "idtuv0"
-
-
-class DensePoseCocoEval(object):
- # Interface for evaluating detection on the Microsoft COCO dataset.
- #
- # The usage for CocoEval is as follows:
- # cocoGt=..., cocoDt=... # load dataset and results
- # E = CocoEval(cocoGt,cocoDt); # initialize CocoEval object
- # E.params.recThrs = ...; # set parameters as desired
- # E.evaluate(); # run per image evaluation
- # E.accumulate(); # accumulate per image results
- # E.summarize(); # display summary metrics of results
- # For example usage see evalDemo.m and http://mscoco.org/.
- #
- # The evaluation parameters are as follows (defaults in brackets):
- # imgIds - [all] N img ids to use for evaluation
- # catIds - [all] K cat ids to use for evaluation
- # iouThrs - [.5:.05:.95] T=10 IoU thresholds for evaluation
- # recThrs - [0:.01:1] R=101 recall thresholds for evaluation
- # areaRng - [...] A=4 object area ranges for evaluation
- # maxDets - [1 10 100] M=3 thresholds on max detections per image
- # iouType - ['segm'] set iouType to 'segm', 'bbox', 'keypoints' or 'densepose'
- # iouType replaced the now DEPRECATED useSegm parameter.
- # useCats - [1] if true use category labels for evaluation
- # Note: if useCats=0 category labels are ignored as in proposal scoring.
- # Note: multiple areaRngs [Ax2] and maxDets [Mx1] can be specified.
- #
- # evaluate(): evaluates detections on every image and every category and
- # concats the results into the "evalImgs" with fields:
- # dtIds - [1xD] id for each of the D detections (dt)
- # gtIds - [1xG] id for each of the G ground truths (gt)
- # dtMatches - [TxD] matching gt id at each IoU or 0
- # gtMatches - [TxG] matching dt id at each IoU or 0
- # dtScores - [1xD] confidence of each dt
- # gtIgnore - [1xG] ignore flag for each gt
- # dtIgnore - [TxD] ignore flag for each dt at each IoU
- #
- # accumulate(): accumulates the per-image, per-category evaluation
- # results in "evalImgs" into the dictionary "eval" with fields:
- # params - parameters used for evaluation
- # date - date evaluation was performed
- # counts - [T,R,K,A,M] parameter dimensions (see above)
- # precision - [TxRxKxAxM] precision for every evaluation setting
- # recall - [TxKxAxM] max recall for every evaluation setting
- # Note: precision and recall==-1 for settings with no gt objects.
- #
- # See also coco, mask, pycocoDemo, pycocoEvalDemo
- #
- # Microsoft COCO Toolbox. version 2.0
- # Data, paper, and tutorials available at: http://mscoco.org/
- # Code written by Piotr Dollar and Tsung-Yi Lin, 2015.
- # Licensed under the Simplified BSD License [see coco/license.txt]
- def __init__(
- self,
- cocoGt=None,
- cocoDt=None,
- iouType: str = "densepose",
- dpEvalMode: DensePoseEvalMode = DensePoseEvalMode.GPS,
- dpDataMode: DensePoseDataMode = DensePoseDataMode.IUV_DT,
- ):
- """
- Initialize CocoEval using coco APIs for gt and dt
- :param cocoGt: coco object with ground truth annotations
- :param cocoDt: coco object with detection results
- :return: None
- """
- self.cocoGt = cocoGt # ground truth COCO API
- self.cocoDt = cocoDt # detections COCO API
- self._dpEvalMode = dpEvalMode
- self._dpDataMode = dpDataMode
- self.params = {} # evaluation parameters
- self.evalImgs = defaultdict(list) # per-image per-category eval results [KxAxI]
- self.eval = {} # accumulated evaluation results
- self._gts = defaultdict(list) # gt for evaluation
- self._dts = defaultdict(list) # dt for evaluation
- self.params = Params(iouType=iouType) # parameters
- self._paramsEval = {} # parameters for evaluation
- self.stats = [] # result summarization
- self.ious = {} # ious between all gts and dts
- if cocoGt is not None:
- self.params.imgIds = sorted(cocoGt.getImgIds())
- self.params.catIds = sorted(cocoGt.getCatIds())
- self.ignoreThrBB = 0.7
- self.ignoreThrUV = 0.9
-
- def _loadGEval(self):
- smpl_subdiv_fpath = PathManager.get_local_path(
- "https://dl.fbaipublicfiles.com/densepose/data/SMPL_subdiv.mat"
- )
- pdist_transform_fpath = PathManager.get_local_path(
- "https://dl.fbaipublicfiles.com/densepose/data/SMPL_SUBDIV_TRANSFORM.mat"
- )
- pdist_matrix_fpath = PathManager.get_local_path(
- "https://dl.fbaipublicfiles.com/densepose/data/Pdist_matrix.pkl"
- )
- SMPL_subdiv = loadmat(smpl_subdiv_fpath)
- self.PDIST_transform = loadmat(pdist_transform_fpath)
- self.PDIST_transform = self.PDIST_transform["index"].squeeze()
- UV = np.array([SMPL_subdiv["U_subdiv"], SMPL_subdiv["V_subdiv"]]).squeeze()
- ClosestVertInds = np.arange(UV.shape[1]) + 1
- self.Part_UVs = []
- self.Part_ClosestVertInds = []
- for i in np.arange(24):
- self.Part_UVs.append(UV[:, SMPL_subdiv["Part_ID_subdiv"].squeeze() == (i + 1)])
- self.Part_ClosestVertInds.append(
- ClosestVertInds[SMPL_subdiv["Part_ID_subdiv"].squeeze() == (i + 1)]
- )
-
- with open(pdist_matrix_fpath, "rb") as hFile:
- arrays = pickle.load(hFile, encoding="latin1")
- self.Pdist_matrix = arrays["Pdist_matrix"]
- self.Part_ids = np.array(SMPL_subdiv["Part_ID_subdiv"].squeeze())
- # Mean geodesic distances for parts.
- self.Mean_Distances = np.array([0, 0.351, 0.107, 0.126, 0.237, 0.173, 0.142, 0.128, 0.150])
- # Coarse Part labels.
- self.CoarseParts = np.array(
- [0, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8]
- )
-
- def _prepare(self):
- """
- Prepare ._gts and ._dts for evaluation based on params
- :return: None
- """
-
- def _toMask(anns, coco):
- # modify ann['segmentation'] by reference
- for ann in anns:
- rle = coco.annToRLE(ann)
- ann["segmentation"] = rle
-
- def _getIgnoreRegion(iid, coco):
- img = coco.imgs[iid]
-
- if "ignore_regions_x" not in img.keys():
- return None
-
- if len(img["ignore_regions_x"]) == 0:
- return None
-
- rgns_merged = []
- for region_x, region_y in zip(img["ignore_regions_x"], img["ignore_regions_y"]):
- rgns = [iter(region_x), iter(region_y)]
- rgns_merged.append([next(it) for it in itertools.cycle(rgns)])
- rles = maskUtils.frPyObjects(rgns_merged, img["height"], img["width"])
- rle = maskUtils.merge(rles)
- return maskUtils.decode(rle)
-
- def _checkIgnore(dt, iregion):
- if iregion is None:
- return True
-
- bb = np.array(dt["bbox"]).astype(np.int)
- x1, y1, x2, y2 = bb[0], bb[1], bb[0] + bb[2], bb[1] + bb[3]
- x2 = min([x2, iregion.shape[1]])
- y2 = min([y2, iregion.shape[0]])
-
- if bb[2] * bb[3] == 0:
- return False
-
- crop_iregion = iregion[y1:y2, x1:x2]
-
- if crop_iregion.sum() == 0:
- return True
-
- if "densepose" not in dt.keys(): # filtering boxes
- return crop_iregion.sum() / bb[2] / bb[3] < self.ignoreThrBB
-
- # filtering UVs
- ignoremask = np.require(crop_iregion, requirements=["F"])
- mask = self._extract_mask(dt)
- uvmask = np.require(np.asarray(mask > 0), dtype=np.uint8, requirements=["F"])
- uvmask_ = maskUtils.encode(uvmask)
- ignoremask_ = maskUtils.encode(ignoremask)
- uviou = maskUtils.iou([uvmask_], [ignoremask_], [1])[0]
- return uviou < self.ignoreThrUV
-
- p = self.params
-
- if p.useCats:
- gts = self.cocoGt.loadAnns(self.cocoGt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds))
- dts = self.cocoDt.loadAnns(self.cocoDt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds))
- else:
- gts = self.cocoGt.loadAnns(self.cocoGt.getAnnIds(imgIds=p.imgIds))
- dts = self.cocoDt.loadAnns(self.cocoDt.getAnnIds(imgIds=p.imgIds))
-
- imns = self.cocoGt.loadImgs(p.imgIds)
- self.size_mapping = {}
- for im in imns:
- self.size_mapping[im["id"]] = [im["height"], im["width"]]
-
- # if iouType == 'uv', add point gt annotations
- if p.iouType == "densepose":
- self._loadGEval()
-
- # convert ground truth to mask if iouType == 'segm'
- if p.iouType == "segm":
- _toMask(gts, self.cocoGt)
- _toMask(dts, self.cocoDt)
-
- # set ignore flag
- for gt in gts:
- gt["ignore"] = gt["ignore"] if "ignore" in gt else 0
- gt["ignore"] = "iscrowd" in gt and gt["iscrowd"]
- if p.iouType == "keypoints":
- gt["ignore"] = (gt["num_keypoints"] == 0) or gt["ignore"]
- if p.iouType == "densepose":
- gt["ignore"] = ("dp_x" in gt) == 0
-
- self._gts = defaultdict(list) # gt for evaluation
- self._dts = defaultdict(list) # dt for evaluation
- self._igrgns = defaultdict(list)
-
- for gt in gts:
- iid = gt["image_id"]
- if iid not in self._igrgns.keys():
- self._igrgns[iid] = _getIgnoreRegion(iid, self.cocoGt)
- if _checkIgnore(gt, self._igrgns[iid]):
- self._gts[iid, gt["category_id"]].append(gt)
- for dt in dts:
- if _checkIgnore(dt, self._igrgns[dt["image_id"]]):
- self._dts[dt["image_id"], dt["category_id"]].append(dt)
-
- self.evalImgs = defaultdict(list) # per-image per-category evaluation results
- self.eval = {} # accumulated evaluation results
-
- def evaluate(self):
- """
- Run per image evaluation on given images and store results (a list of dict) in self.evalImgs
- :return: None
- """
- tic = time.time()
- logger.info("Running per image DensePose evaluation... {}".format(self.params.iouType))
- 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("useSegm (deprecated) is not None. Running DensePose evaluation")
- 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()
- # loop through images, area range, max detection number
- catIds = p.catIds if p.useCats else [-1]
-
- if p.iouType in ["segm", "bbox"]:
- computeIoU = self.computeIoU
- elif p.iouType == "keypoints":
- computeIoU = self.computeOks
- elif p.iouType == "densepose":
- computeIoU = self.computeOgps
- if self._dpEvalMode == DensePoseEvalMode.GPSM:
- self.real_ious = {
- (imgId, catId): self.computeDPIoU(imgId, catId)
- for imgId in p.imgIds
- for catId in catIds
- }
-
- self.ious = {
- (imgId, catId): computeIoU(imgId, catId) for imgId in p.imgIds for catId in catIds
- }
-
- evaluateImg = self.evaluateImg
- maxDet = p.maxDets[-1]
- self.evalImgs = [
- evaluateImg(imgId, catId, areaRng, maxDet)
- for catId in catIds
- for areaRng in p.areaRng
- for imgId in p.imgIds
- ]
- self._paramsEval = copy.deepcopy(self.params)
- toc = time.time()
- logger.info("DensePose evaluation DONE (t={:0.2f}s).".format(toc - tic))
-
- def getDensePoseMask(self, polys):
- maskGen = np.zeros([256, 256])
- for i in range(1, 15):
- if polys[i - 1]:
- currentMask = maskUtils.decode(polys[i - 1])
- maskGen[currentMask > 0] = i
- return maskGen
-
- def _generate_rlemask_on_image(self, mask, imgId, data):
- bbox_xywh = np.array(data["bbox"])
- x, y, w, h = bbox_xywh
- im_h, im_w = self.size_mapping[imgId]
- im_mask = np.zeros((im_h, im_w), dtype=np.uint8)
- if mask is not None:
- x0 = max(int(x), 0)
- x1 = min(int(x + w), im_w, int(x) + mask.shape[1])
- y0 = max(int(y), 0)
- y1 = min(int(y + h), im_h, int(y) + mask.shape[0])
- y = int(y)
- x = int(x)
- im_mask[y0:y1, x0:x1] = mask[y0 - y : y1 - y, x0 - x : x1 - x]
- im_mask = np.require(np.asarray(im_mask > 0), dtype=np.uint8, requirements=["F"])
- rle_mask = maskUtils.encode(np.array(im_mask[:, :, np.newaxis], order="F"))[0]
- return rle_mask
-
- def computeDPIoU(self, imgId, catId):
- p = self.params
- if p.useCats:
- gt = self._gts[imgId, catId]
- dt = self._dts[imgId, catId]
- else:
- gt = [_ for cId in p.catIds for _ in self._gts[imgId, cId]]
- dt = [_ for cId in p.catIds for _ in self._dts[imgId, cId]]
- if len(gt) == 0 and len(dt) == 0:
- return []
- inds = np.argsort([-d["score"] for d in dt], kind="mergesort")
- dt = [dt[i] for i in inds]
- if len(dt) > p.maxDets[-1]:
- dt = dt[0 : p.maxDets[-1]]
-
- gtmasks = []
- for g in gt:
- if DensePoseDataRelative.S_KEY in g.keys():
- mask = self.getDensePoseMask(g[DensePoseDataRelative.S_KEY])
- _, _, w, h = g["bbox"]
- scale_x = float(max(w, 1)) / mask.shape[1]
- scale_y = float(max(h, 1)) / mask.shape[0]
- mask = spzoom(mask, (scale_y, scale_x), order=1, prefilter=False)
- mask = np.array(mask > 0.5, dtype=np.uint8)
- else:
- mask = None
- rle_mask = self._generate_rlemask_on_image(mask, imgId, g)
- gtmasks.append(rle_mask)
-
- dtmasks = []
- for d in dt:
- mask = self._extract_mask(d)
- mask = np.require(np.asarray(mask > 0), dtype=np.uint8, requirements=["F"])
- rle_mask = self._generate_rlemask_on_image(mask, imgId, d)
- dtmasks.append(rle_mask)
-
- # compute iou between each dt and gt region
- iscrowd = [int(o["iscrowd"]) for o in gt]
- iousDP = maskUtils.iou(dtmasks, gtmasks, iscrowd)
- return iousDP
-
- def computeIoU(self, imgId, catId):
- p = self.params
- if p.useCats:
- gt = self._gts[imgId, catId]
- dt = self._dts[imgId, catId]
- else:
- gt = [_ for cId in p.catIds for _ in self._gts[imgId, cId]]
- dt = [_ for cId in p.catIds for _ in self._dts[imgId, cId]]
- if len(gt) == 0 and len(dt) == 0:
- return []
- inds = np.argsort([-d["score"] for d in dt], kind="mergesort")
- dt = [dt[i] for i in inds]
- if len(dt) > p.maxDets[-1]:
- dt = dt[0 : p.maxDets[-1]]
-
- if p.iouType == "segm":
- g = [g["segmentation"] for g in gt]
- d = [d["segmentation"] for d in dt]
- elif p.iouType == "bbox":
- g = [g["bbox"] for g in gt]
- d = [d["bbox"] for d in dt]
- else:
- raise Exception("unknown iouType for iou computation")
-
- # compute iou between each dt and gt region
- iscrowd = [int(o["iscrowd"]) for o in gt]
- ious = maskUtils.iou(d, g, iscrowd)
- return ious
-
- def computeOks(self, imgId, catId):
- p = self.params
- # dimension here should be Nxm
- gts = self._gts[imgId, catId]
- dts = self._dts[imgId, catId]
- inds = np.argsort([-d["score"] for d in dts], kind="mergesort")
- dts = [dts[i] for i in inds]
- if len(dts) > p.maxDets[-1]:
- dts = dts[0 : p.maxDets[-1]]
- # if len(gts) == 0 and len(dts) == 0:
- if len(gts) == 0 or len(dts) == 0:
- return []
- ious = np.zeros((len(dts), len(gts)))
- sigmas = (
- np.array(
- [
- 0.26,
- 0.25,
- 0.25,
- 0.35,
- 0.35,
- 0.79,
- 0.79,
- 0.72,
- 0.72,
- 0.62,
- 0.62,
- 1.07,
- 1.07,
- 0.87,
- 0.87,
- 0.89,
- 0.89,
- ]
- )
- / 10.0
- )
- vars = (sigmas * 2) ** 2
- k = len(sigmas)
- # compute oks between each detection and ground truth object
- for j, gt in enumerate(gts):
- # create bounds for ignore regions(double the gt bbox)
- g = np.array(gt["keypoints"])
- xg = g[0::3]
- yg = g[1::3]
- vg = g[2::3]
- k1 = np.count_nonzero(vg > 0)
- bb = gt["bbox"]
- x0 = bb[0] - bb[2]
- x1 = bb[0] + bb[2] * 2
- y0 = bb[1] - bb[3]
- y1 = bb[1] + bb[3] * 2
- for i, dt in enumerate(dts):
- d = np.array(dt["keypoints"])
- xd = d[0::3]
- yd = d[1::3]
- if k1 > 0:
- # measure the per-keypoint distance if keypoints visible
- dx = xd - xg
- dy = yd - yg
- else:
- # measure minimum distance to keypoints in (x0,y0) & (x1,y1)
- z = np.zeros((k))
- dx = np.max((z, x0 - xd), axis=0) + np.max((z, xd - x1), axis=0)
- dy = np.max((z, y0 - yd), axis=0) + np.max((z, yd - y1), axis=0)
- e = (dx ** 2 + dy ** 2) / vars / (gt["area"] + np.spacing(1)) / 2
- if k1 > 0:
- e = e[vg > 0]
- ious[i, j] = np.sum(np.exp(-e)) / e.shape[0]
- return ious
-
- def _extract_mask(self, dt: Dict[str, Any]) -> np.ndarray:
- (densepose_shape, densepose_data_encoded), densepose_bbox_xywh = dt["densepose"]
- densepose_data = DensePoseResult.decode_png_data(densepose_shape, densepose_data_encoded)
- return densepose_data[0]
-
- def _extract_iuv(
- self, densepose_data: np.ndarray, py: np.ndarray, px: np.ndarray, gt: Dict[str, Any]
- ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
- """
- Extract arrays of I, U and V values at given points as numpy arrays
- given the data mode stored in self._dpDataMode
- """
- if self._dpDataMode == DensePoseDataMode.IUV_DT:
- # estimated labels and UV (default)
- ipoints = densepose_data[0, py, px]
- upoints = densepose_data[1, py, px] / 255.0 # convert from uint8 by /255.
- vpoints = densepose_data[2, py, px] / 255.0
- elif self._dpDataMode == DensePoseDataMode.IUV_GT:
- # ground truth
- ipoints = np.array(gt["dp_I"])
- upoints = np.array(gt["dp_U"])
- vpoints = np.array(gt["dp_V"])
- elif self._dpDataMode == DensePoseDataMode.I_GT_UV_0:
- # ground truth labels, UV = 0
- ipoints = np.array(gt["dp_I"])
- upoints = upoints * 0.0
- vpoints = vpoints * 0.0
- elif self._dpDataMode == DensePoseDataMode.I_GT_UV_DT:
- # ground truth labels, estimated UV
- ipoints = np.array(gt["dp_I"])
- upoints = densepose_data[1, py, px] / 255.0 # convert from uint8 by /255.
- vpoints = densepose_data[2, py, px] / 255.0
- elif self._dpDataMode == DensePoseDataMode.I_DT_UV_0:
- # estimated labels, UV = 0
- ipoints = densepose_data[0, py, px]
- upoints = upoints * 0.0
- vpoints = vpoints * 0.0
- else:
- raise ValueError(f"Unknown data mode: {self._dpDataMode}")
- return ipoints, upoints, vpoints
-
- def computeOgps(self, imgId, catId):
- p = self.params
- # dimension here should be Nxm
- g = self._gts[imgId, catId]
- d = self._dts[imgId, catId]
- inds = np.argsort([-d_["score"] for d_ in d], kind="mergesort")
- d = [d[i] for i in inds]
- if len(d) > p.maxDets[-1]:
- d = d[0 : p.maxDets[-1]]
- # if len(gts) == 0 and len(dts) == 0:
- if len(g) == 0 or len(d) == 0:
- return []
- ious = np.zeros((len(d), len(g)))
- # compute opgs between each detection and ground truth object
- # sigma = self.sigma #0.255 # dist = 0.3m corresponds to ogps = 0.5
- # 1 # dist = 0.3m corresponds to ogps = 0.96
- # 1.45 # dist = 1.7m (person height) corresponds to ogps = 0.5)
- for j, gt in enumerate(g):
- if not gt["ignore"]:
- g_ = gt["bbox"]
- for i, dt in enumerate(d):
- #
- dy = int(dt["bbox"][3])
- dx = int(dt["bbox"][2])
- dp_x = np.array(gt["dp_x"]) * g_[2] / 255.0
- dp_y = np.array(gt["dp_y"]) * g_[3] / 255.0
- py = (dp_y + g_[1] - dt["bbox"][1]).astype(np.int)
- px = (dp_x + g_[0] - dt["bbox"][0]).astype(np.int)
- #
- pts = np.zeros(len(px))
- pts[px >= dx] = -1
- pts[py >= dy] = -1
- pts[px < 0] = -1
- pts[py < 0] = -1
- if len(pts) < 1:
- ogps = 0.0
- elif np.max(pts) == -1:
- ogps = 0.0
- else:
- px[pts == -1] = 0
- py[pts == -1] = 0
- (densepose_shape, densepose_data_encoded), densepose_bbox_xywh = dt[
- "densepose"
- ]
- densepose_data = DensePoseResult.decode_png_data(
- densepose_shape, densepose_data_encoded
- )
- assert densepose_data.shape[2] == dx, (
- "DensePoseData width {} should be equal to "
- "detection bounding box width {}".format(densepose_data.shape[2], dx)
- )
- assert densepose_data.shape[1] == dy, (
- "DensePoseData height {} should be equal to "
- "detection bounding box height {}".format(densepose_data.shape[1], dy)
- )
- ipoints, upoints, vpoints = self._extract_iuv(densepose_data, py, px, gt)
- ipoints[pts == -1] = 0
- # Find closest vertices in subsampled mesh.
- cVerts, cVertsGT = self.findAllClosestVerts(gt, upoints, vpoints, ipoints)
- # Get pairwise geodesic distances between gt and estimated mesh points.
- dist = self.getDistances(cVertsGT, cVerts)
- # Compute the Ogps measure.
- # Find the mean geodesic normalization distance for
- # each GT point, based on which part it is on.
- Current_Mean_Distances = self.Mean_Distances[
- self.CoarseParts[self.Part_ids[cVertsGT[cVertsGT > 0].astype(int) - 1]]
- ]
- # Compute gps
- ogps_values = np.exp(-(dist ** 2) / (2 * (Current_Mean_Distances ** 2)))
- #
- if len(dist) > 0:
- ogps = np.sum(ogps_values) / len(dist)
- ious[i, j] = ogps
-
- gbb = [gt["bbox"] for gt in g]
- dbb = [dt["bbox"] for dt in d]
-
- # compute iou between each dt and gt region
- iscrowd = [int(o["iscrowd"]) for o in g]
- ious_bb = maskUtils.iou(dbb, gbb, iscrowd)
- return ious, ious_bb
-
- def evaluateImg(self, imgId, catId, aRng, maxDet):
- """
- perform evaluation for single category and image
- :return: dict (single image results)
- """
-
- p = self.params
- if p.useCats:
- gt = self._gts[imgId, catId]
- dt = self._dts[imgId, catId]
- else:
- gt = [_ for cId in p.catIds for _ in self._gts[imgId, cId]]
- dt = [_ for cId in p.catIds for _ in self._dts[imgId, cId]]
- if len(gt) == 0 and len(dt) == 0:
- return None
-
- for g in gt:
- # g['_ignore'] = g['ignore']
- if g["ignore"] or (g["area"] < aRng[0] or g["area"] > aRng[1]):
- g["_ignore"] = True
- else:
- g["_ignore"] = False
-
- # sort dt highest score first, sort gt ignore last
- gtind = np.argsort([g["_ignore"] for g in gt], kind="mergesort")
- gt = [gt[i] for i in gtind]
- dtind = np.argsort([-d["score"] for d in dt], kind="mergesort")
- dt = [dt[i] for i in dtind[0:maxDet]]
- iscrowd = [int(o["iscrowd"]) for o in gt]
- # load computed ious
- if p.iouType == "densepose":
- # print('Checking the length', len(self.ious[imgId, catId]))
- # if len(self.ious[imgId, catId]) == 0:
- # print(self.ious[imgId, catId])
- ious = (
- self.ious[imgId, catId][0][:, gtind]
- if len(self.ious[imgId, catId]) > 0
- else self.ious[imgId, catId]
- )
- ioubs = (
- self.ious[imgId, catId][1][:, gtind]
- if len(self.ious[imgId, catId]) > 0
- else self.ious[imgId, catId]
- )
- if self._dpEvalMode == DensePoseEvalMode.GPSM:
- iousM = (
- self.real_ious[imgId, catId][:, gtind]
- if len(self.real_ious[imgId, catId]) > 0
- else self.real_ious[imgId, catId]
- )
- else:
- ious = (
- self.ious[imgId, catId][:, gtind]
- if len(self.ious[imgId, catId]) > 0
- else self.ious[imgId, catId]
- )
-
- T = len(p.iouThrs)
- G = len(gt)
- D = len(dt)
- gtm = np.zeros((T, G))
- dtm = np.zeros((T, D))
- gtIg = np.array([g["_ignore"] for g in gt])
- dtIg = np.zeros((T, D))
- if np.all(gtIg) and p.iouType == "densepose":
- dtIg = np.logical_or(dtIg, True)
-
- if len(ious) > 0: # and not p.iouType == 'densepose':
- for tind, t in enumerate(p.iouThrs):
- for dind, d in enumerate(dt):
- # information about best match so far (m=-1 -> unmatched)
- iou = min([t, 1 - 1e-10])
- m = -1
- for gind, _g in enumerate(gt):
- # if this gt already matched, and not a crowd, continue
- if gtm[tind, gind] > 0 and not iscrowd[gind]:
- continue
- # if dt matched to reg gt, and on ignore gt, stop
- if m > -1 and gtIg[m] == 0 and gtIg[gind] == 1:
- break
- if p.iouType == "densepose":
- if self._dpEvalMode == DensePoseEvalMode.GPSM:
- new_iou = np.sqrt(iousM[dind, gind] * ious[dind, gind])
- elif self._dpEvalMode == DensePoseEvalMode.IOU:
- new_iou = iousM[dind, gind]
- elif self._dpEvalMode == DensePoseEvalMode.GPS:
- new_iou = ious[dind, gind]
- else:
- new_iou = ious[dind, gind]
- if new_iou < iou:
- continue
- if new_iou == 0.0:
- continue
- # if match successful and best so far, store appropriately
- iou = new_iou
- m = gind
- # if match made store id of match for both dt and gt
- if m == -1:
- continue
- dtIg[tind, dind] = gtIg[m]
- dtm[tind, dind] = gt[m]["id"]
- gtm[tind, m] = d["id"]
-
- if p.iouType == "densepose":
- if not len(ioubs) == 0:
- for dind, d in enumerate(dt):
- # information about best match so far (m=-1 -> unmatched)
- if dtm[tind, dind] == 0:
- ioub = 0.8
- m = -1
- for gind, _g in enumerate(gt):
- # if this gt already matched, and not a crowd, continue
- if gtm[tind, gind] > 0 and not iscrowd[gind]:
- continue
- # continue to next gt unless better match made
- if ioubs[dind, gind] < ioub:
- continue
- # if match successful and best so far, store appropriately
- ioub = ioubs[dind, gind]
- m = gind
- # if match made store id of match for both dt and gt
- if m > -1:
- dtIg[:, dind] = gtIg[m]
- if gtIg[m]:
- dtm[tind, dind] = gt[m]["id"]
- gtm[tind, m] = d["id"]
- # set unmatched detections outside of area range to ignore
- a = np.array([d["area"] < aRng[0] or d["area"] > aRng[1] for d in dt]).reshape((1, len(dt)))
- dtIg = np.logical_or(dtIg, np.logical_and(dtm == 0, np.repeat(a, T, 0)))
- # store results for given image and category
- # print('Done with the function', len(self.ious[imgId, catId]))
- return {
- "image_id": imgId,
- "category_id": catId,
- "aRng": aRng,
- "maxDet": maxDet,
- "dtIds": [d["id"] for d in dt],
- "gtIds": [g["id"] for g in gt],
- "dtMatches": dtm,
- "gtMatches": gtm,
- "dtScores": [d["score"] for d in dt],
- "gtIgnore": gtIg,
- "dtIgnore": dtIg,
- }
-
- def accumulate(self, p=None):
- """
- Accumulate per image evaluation results and store the result in self.eval
- :param p: input params for evaluation
- :return: None
- """
- logger.info("Accumulating evaluation results...")
- tic = time.time()
- if not self.evalImgs:
- logger.info("Please run evaluate() first")
- # allows input customized parameters
- if p is None:
- p = self.params
- p.catIds = p.catIds if p.useCats == 1 else [-1]
- T = len(p.iouThrs)
- R = len(p.recThrs)
- K = len(p.catIds) if p.useCats else 1
- A = len(p.areaRng)
- M = len(p.maxDets)
- precision = -np.ones((T, R, K, A, M)) # -1 for the precision of absent categories
- recall = -np.ones((T, K, A, M))
-
- # create dictionary for future indexing
- logger.info("Categories: {}".format(p.catIds))
- _pe = self._paramsEval
- catIds = _pe.catIds if _pe.useCats else [-1]
- setK = set(catIds)
- setA = set(map(tuple, _pe.areaRng))
- setM = set(_pe.maxDets)
- setI = set(_pe.imgIds)
- # get inds to evaluate
- k_list = [n for n, k in enumerate(p.catIds) if k in setK]
- m_list = [m for n, m in enumerate(p.maxDets) if m in setM]
- a_list = [n for n, a in enumerate(map(lambda x: tuple(x), p.areaRng)) if a in setA]
- i_list = [n for n, i in enumerate(p.imgIds) if i in setI]
- I0 = len(_pe.imgIds)
- A0 = len(_pe.areaRng)
- # retrieve E at each category, area range, and max number of detections
- for k, k0 in enumerate(k_list):
- Nk = k0 * A0 * I0
- for a, a0 in enumerate(a_list):
- Na = a0 * I0
- for m, maxDet in enumerate(m_list):
- E = [self.evalImgs[Nk + Na + i] for i in i_list]
- E = [e for e in E if e is not None]
- if len(E) == 0:
- continue
- dtScores = np.concatenate([e["dtScores"][0:maxDet] for e in E])
-
- # different sorting method generates slightly different results.
- # mergesort is used to be consistent as Matlab implementation.
- inds = np.argsort(-dtScores, kind="mergesort")
-
- dtm = np.concatenate([e["dtMatches"][:, 0:maxDet] for e in E], axis=1)[:, inds]
- dtIg = np.concatenate([e["dtIgnore"][:, 0:maxDet] for e in E], axis=1)[:, inds]
- gtIg = np.concatenate([e["gtIgnore"] for e in E])
- npig = np.count_nonzero(gtIg == 0)
- if npig == 0:
- continue
- tps = np.logical_and(dtm, np.logical_not(dtIg))
- fps = np.logical_and(np.logical_not(dtm), np.logical_not(dtIg))
- tp_sum = np.cumsum(tps, axis=1).astype(dtype=np.float)
- fp_sum = np.cumsum(fps, axis=1).astype(dtype=np.float)
- for t, (tp, fp) in enumerate(zip(tp_sum, fp_sum)):
- tp = np.array(tp)
- fp = np.array(fp)
- nd = len(tp)
- rc = tp / npig
- pr = tp / (fp + tp + np.spacing(1))
- q = np.zeros((R,))
-
- if nd:
- recall[t, k, a, m] = rc[-1]
- else:
- recall[t, k, a, m] = 0
-
- # numpy is slow without cython optimization for accessing elements
- # use python array gets significant speed improvement
- pr = pr.tolist()
- q = q.tolist()
-
- for i in range(nd - 1, 0, -1):
- if pr[i] > pr[i - 1]:
- pr[i - 1] = pr[i]
-
- inds = np.searchsorted(rc, p.recThrs, side="left")
- try:
- for ri, pi in enumerate(inds):
- q[ri] = pr[pi]
- except Exception:
- pass
- precision[t, :, k, a, m] = np.array(q)
- logger.info(
- "Final: max precision {}, min precision {}".format(np.max(precision), np.min(precision))
- )
- self.eval = {
- "params": p,
- "counts": [T, R, K, A, M],
- "date": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
- "precision": precision,
- "recall": recall,
- }
- toc = time.time()
- logger.info("DONE (t={:0.2f}s).".format(toc - tic))
-
- def summarize(self):
- """
- Compute and display summary metrics for evaluation results.
- Note this function can *only* be applied on the default parameter setting
- """
-
- def _summarize(ap=1, iouThr=None, areaRng="all", maxDets=100):
- p = self.params
- iStr = " {:<18} {} @[ {}={:<9} | area={:>6s} | maxDets={:>3d} ] = {:0.3f}"
- titleStr = "Average Precision" if ap == 1 else "Average Recall"
- typeStr = "(AP)" if ap == 1 else "(AR)"
- measure = "IoU"
- if self.params.iouType == "keypoints":
- measure = "OKS"
- elif self.params.iouType == "densepose":
- measure = "OGPS"
- iouStr = (
- "{:0.2f}:{:0.2f}".format(p.iouThrs[0], p.iouThrs[-1])
- if iouThr is None
- else "{:0.2f}".format(iouThr)
- )
-
- aind = [i for i, aRng in enumerate(p.areaRngLbl) if aRng == areaRng]
- mind = [i for i, mDet in enumerate(p.maxDets) if mDet == maxDets]
- if ap == 1:
- # dimension of precision: [TxRxKxAxM]
- s = self.eval["precision"]
- # IoU
- if iouThr is not None:
- t = np.where(np.abs(iouThr - p.iouThrs) < 0.001)[0]
- s = s[t]
- s = s[:, :, :, aind, mind]
- else:
- # dimension of recall: [TxKxAxM]
- s = self.eval["recall"]
- if iouThr is not None:
- t = np.where(iouThr == p.iouThrs)[0]
- s = s[t]
- s = s[:, :, aind, mind]
- if len(s[s > -1]) == 0:
- mean_s = -1
- else:
- mean_s = np.mean(s[s > -1])
- logger.info(iStr.format(titleStr, typeStr, measure, iouStr, areaRng, maxDets, mean_s))
- return mean_s
-
- def _summarizeDets():
- stats = np.zeros((12,))
- stats[0] = _summarize(1)
- stats[1] = _summarize(1, iouThr=0.5, maxDets=self.params.maxDets[2])
- stats[2] = _summarize(1, iouThr=0.75, maxDets=self.params.maxDets[2])
- stats[3] = _summarize(1, areaRng="small", maxDets=self.params.maxDets[2])
- stats[4] = _summarize(1, areaRng="medium", maxDets=self.params.maxDets[2])
- stats[5] = _summarize(1, areaRng="large", maxDets=self.params.maxDets[2])
- stats[6] = _summarize(0, maxDets=self.params.maxDets[0])
- stats[7] = _summarize(0, maxDets=self.params.maxDets[1])
- stats[8] = _summarize(0, maxDets=self.params.maxDets[2])
- stats[9] = _summarize(0, areaRng="small", maxDets=self.params.maxDets[2])
- stats[10] = _summarize(0, areaRng="medium", maxDets=self.params.maxDets[2])
- stats[11] = _summarize(0, areaRng="large", maxDets=self.params.maxDets[2])
- return stats
-
- def _summarizeKps():
- stats = np.zeros((10,))
- stats[0] = _summarize(1, maxDets=20)
- stats[1] = _summarize(1, maxDets=20, iouThr=0.5)
- stats[2] = _summarize(1, maxDets=20, iouThr=0.75)
- stats[3] = _summarize(1, maxDets=20, areaRng="medium")
- stats[4] = _summarize(1, maxDets=20, areaRng="large")
- stats[5] = _summarize(0, maxDets=20)
- stats[6] = _summarize(0, maxDets=20, iouThr=0.5)
- stats[7] = _summarize(0, maxDets=20, iouThr=0.75)
- stats[8] = _summarize(0, maxDets=20, areaRng="medium")
- stats[9] = _summarize(0, maxDets=20, areaRng="large")
- return stats
-
- def _summarizeUvs():
- stats = np.zeros((10,))
- stats[0] = _summarize(1, maxDets=self.params.maxDets[0])
- stats[1] = _summarize(1, maxDets=self.params.maxDets[0], iouThr=0.5)
- stats[2] = _summarize(1, maxDets=self.params.maxDets[0], iouThr=0.75)
- stats[3] = _summarize(1, maxDets=self.params.maxDets[0], areaRng="medium")
- stats[4] = _summarize(1, maxDets=self.params.maxDets[0], areaRng="large")
- stats[5] = _summarize(0, maxDets=self.params.maxDets[0])
- stats[6] = _summarize(0, maxDets=self.params.maxDets[0], iouThr=0.5)
- stats[7] = _summarize(0, maxDets=self.params.maxDets[0], iouThr=0.75)
- stats[8] = _summarize(0, maxDets=self.params.maxDets[0], areaRng="medium")
- stats[9] = _summarize(0, maxDets=self.params.maxDets[0], areaRng="large")
- return stats
-
- def _summarizeUvsOld():
- stats = np.zeros((18,))
- stats[0] = _summarize(1, maxDets=self.params.maxDets[0])
- stats[1] = _summarize(1, maxDets=self.params.maxDets[0], iouThr=0.5)
- stats[2] = _summarize(1, maxDets=self.params.maxDets[0], iouThr=0.55)
- stats[3] = _summarize(1, maxDets=self.params.maxDets[0], iouThr=0.60)
- stats[4] = _summarize(1, maxDets=self.params.maxDets[0], iouThr=0.65)
- stats[5] = _summarize(1, maxDets=self.params.maxDets[0], iouThr=0.70)
- stats[6] = _summarize(1, maxDets=self.params.maxDets[0], iouThr=0.75)
- stats[7] = _summarize(1, maxDets=self.params.maxDets[0], iouThr=0.80)
- stats[8] = _summarize(1, maxDets=self.params.maxDets[0], iouThr=0.85)
- stats[9] = _summarize(1, maxDets=self.params.maxDets[0], iouThr=0.90)
- stats[10] = _summarize(1, maxDets=self.params.maxDets[0], iouThr=0.95)
- stats[11] = _summarize(1, maxDets=self.params.maxDets[0], areaRng="medium")
- stats[12] = _summarize(1, maxDets=self.params.maxDets[0], areaRng="large")
- stats[13] = _summarize(0, maxDets=self.params.maxDets[0])
- stats[14] = _summarize(0, maxDets=self.params.maxDets[0], iouThr=0.5)
- stats[15] = _summarize(0, maxDets=self.params.maxDets[0], iouThr=0.75)
- stats[16] = _summarize(0, maxDets=self.params.maxDets[0], areaRng="medium")
- stats[17] = _summarize(0, maxDets=self.params.maxDets[0], areaRng="large")
- return stats
-
- if not self.eval:
- raise Exception("Please run accumulate() first")
- iouType = self.params.iouType
- if iouType in ["segm", "bbox"]:
- summarize = _summarizeDets
- elif iouType in ["keypoints"]:
- summarize = _summarizeKps
- elif iouType in ["densepose"]:
- summarize = _summarizeUvs
- self.stats = summarize()
-
- def __str__(self):
- self.summarize()
-
- # ================ functions for dense pose ==============================
- def findAllClosestVerts(self, gt, U_points, V_points, Index_points):
- #
- I_gt = np.array(gt["dp_I"])
- U_gt = np.array(gt["dp_U"])
- V_gt = np.array(gt["dp_V"])
- #
- # print(I_gt)
- #
- ClosestVerts = np.ones(Index_points.shape) * -1
- for i in np.arange(24):
- #
- if sum(Index_points == (i + 1)) > 0:
- UVs = np.array(
- [U_points[Index_points == (i + 1)], V_points[Index_points == (i + 1)]]
- )
- Current_Part_UVs = self.Part_UVs[i]
- Current_Part_ClosestVertInds = self.Part_ClosestVertInds[i]
- D = ssd.cdist(Current_Part_UVs.transpose(), UVs.transpose()).squeeze()
- ClosestVerts[Index_points == (i + 1)] = Current_Part_ClosestVertInds[
- np.argmin(D, axis=0)
- ]
- #
- ClosestVertsGT = np.ones(Index_points.shape) * -1
- for i in np.arange(24):
- if sum(I_gt == (i + 1)) > 0:
- UVs = np.array([U_gt[I_gt == (i + 1)], V_gt[I_gt == (i + 1)]])
- Current_Part_UVs = self.Part_UVs[i]
- Current_Part_ClosestVertInds = self.Part_ClosestVertInds[i]
- D = ssd.cdist(Current_Part_UVs.transpose(), UVs.transpose()).squeeze()
- ClosestVertsGT[I_gt == (i + 1)] = Current_Part_ClosestVertInds[np.argmin(D, axis=0)]
- #
- return ClosestVerts, ClosestVertsGT
-
- def getDistances(self, cVertsGT, cVerts):
-
- ClosestVertsTransformed = self.PDIST_transform[cVerts.astype(int) - 1]
- ClosestVertsGTTransformed = self.PDIST_transform[cVertsGT.astype(int) - 1]
- #
- ClosestVertsTransformed[cVerts < 0] = 0
- ClosestVertsGTTransformed[cVertsGT < 0] = 0
- #
- cVertsGT = ClosestVertsGTTransformed
- cVerts = ClosestVertsTransformed
- #
- n = 27554
- dists = []
- for d in range(len(cVertsGT)):
- if cVertsGT[d] > 0:
- if cVerts[d] > 0:
- i = cVertsGT[d] - 1
- j = cVerts[d] - 1
- if j == i:
- dists.append(0)
- elif j > i:
- ccc = i
- i = j
- j = ccc
- i = n - i - 1
- j = n - j - 1
- k = (n * (n - 1) / 2) - (n - i) * ((n - i) - 1) / 2 + j - i - 1
- k = (n * n - n) / 2 - k - 1
- dists.append(self.Pdist_matrix[int(k)][0])
- else:
- i = n - i - 1
- j = n - j - 1
- k = (n * (n - 1) / 2) - (n - i) * ((n - i) - 1) / 2 + j - i - 1
- k = (n * n - n) / 2 - k - 1
- dists.append(self.Pdist_matrix[int(k)][0])
- else:
- dists.append(np.inf)
- return np.array(dists).squeeze()
-
-
-class Params:
- """
- Params for coco evaluation api
- """
-
- def setDetParams(self):
- self.imgIds = []
- self.catIds = []
- # np.arange causes trouble. the data point on arange is slightly larger than the true value
- self.iouThrs = np.linspace(0.5, 0.95, np.round((0.95 - 0.5) / 0.05) + 1, endpoint=True)
- self.recThrs = np.linspace(0.0, 1.00, np.round((1.00 - 0.0) / 0.01) + 1, endpoint=True)
- self.maxDets = [1, 10, 100]
- self.areaRng = [
- [0 ** 2, 1e5 ** 2],
- [0 ** 2, 32 ** 2],
- [32 ** 2, 96 ** 2],
- [96 ** 2, 1e5 ** 2],
- ]
- self.areaRngLbl = ["all", "small", "medium", "large"]
- self.useCats = 1
-
- def setKpParams(self):
- self.imgIds = []
- self.catIds = []
- # np.arange causes trouble. the data point on arange is slightly larger than the true value
- self.iouThrs = np.linspace(0.5, 0.95, np.round((0.95 - 0.5) / 0.05) + 1, endpoint=True)
- self.recThrs = np.linspace(0.0, 1.00, np.round((1.00 - 0.0) / 0.01) + 1, endpoint=True)
- self.maxDets = [20]
- self.areaRng = [[0 ** 2, 1e5 ** 2], [32 ** 2, 96 ** 2], [96 ** 2, 1e5 ** 2]]
- self.areaRngLbl = ["all", "medium", "large"]
- self.useCats = 1
-
- def setUvParams(self):
- self.imgIds = []
- self.catIds = []
- self.iouThrs = np.linspace(0.5, 0.95, int(np.round((0.95 - 0.5) / 0.05)) + 1, endpoint=True)
- self.recThrs = np.linspace(0.0, 1.00, int(np.round((1.00 - 0.0) / 0.01)) + 1, endpoint=True)
- self.maxDets = [20]
- self.areaRng = [[0 ** 2, 1e5 ** 2], [32 ** 2, 96 ** 2], [96 ** 2, 1e5 ** 2]]
- self.areaRngLbl = ["all", "medium", "large"]
- self.useCats = 1
-
- def __init__(self, iouType="segm"):
- if iouType == "segm" or iouType == "bbox":
- self.setDetParams()
- elif iouType == "keypoints":
- self.setKpParams()
- elif iouType == "densepose":
- self.setUvParams()
- else:
- raise Exception("iouType not supported")
- self.iouType = iouType
- # useSegm is deprecated
- self.useSegm = None
diff --git a/spaces/CVPR/Example-Echocardiogram-Segmentation/app.py b/spaces/CVPR/Example-Echocardiogram-Segmentation/app.py
deleted file mode 100644
index 4af9e8f54eefe73bb475d2cfe2e25a1aec24e49d..0000000000000000000000000000000000000000
--- a/spaces/CVPR/Example-Echocardiogram-Segmentation/app.py
+++ /dev/null
@@ -1,93 +0,0 @@
-import os, os.path
-from os.path import splitext
-import numpy as np
-import sys
-import matplotlib.pyplot as plt
-import torch
-import torchvision
-import wget
-
-
-destination_folder = "output"
-destination_for_weights = "weights"
-
-if os.path.exists(destination_for_weights):
- print("The weights are at", destination_for_weights)
-else:
- print("Creating folder at ", destination_for_weights, " to store weights")
- os.mkdir(destination_for_weights)
-
-segmentationWeightsURL = 'https://github.com/douyang/EchoNetDynamic/releases/download/v1.0.0/deeplabv3_resnet50_random.pt'
-
-if not os.path.exists(os.path.join(destination_for_weights, os.path.basename(segmentationWeightsURL))):
- print("Downloading Segmentation Weights, ", segmentationWeightsURL," to ",os.path.join(destination_for_weights, os.path.basename(segmentationWeightsURL)))
- filename = wget.download(segmentationWeightsURL, out = destination_for_weights)
-else:
- print("Segmentation Weights already present")
-
-torch.cuda.empty_cache()
-
-def collate_fn(x):
- x, f = zip(*x)
- i = list(map(lambda t: t.shape[1], x))
- x = torch.as_tensor(np.swapaxes(np.concatenate(x, 1), 0, 1))
- return x, f, i
-
-model = torchvision.models.segmentation.deeplabv3_resnet50(pretrained=False, aux_loss=False)
-model.classifier[-1] = torch.nn.Conv2d(model.classifier[-1].in_channels, 1, kernel_size=model.classifier[-1].kernel_size)
-
-print("loading weights from ", os.path.join(destination_for_weights, "deeplabv3_resnet50_random"))
-
-if torch.cuda.is_available():
- print("cuda is available, original weights")
- device = torch.device("cuda")
- model = torch.nn.DataParallel(model)
- model.to(device)
- checkpoint = torch.load(os.path.join(destination_for_weights, os.path.basename(segmentationWeightsURL)))
- model.load_state_dict(checkpoint['state_dict'])
-else:
- print("cuda is not available, cpu weights")
- device = torch.device("cpu")
- checkpoint = torch.load(os.path.join(destination_for_weights, os.path.basename(segmentationWeightsURL)), map_location = "cpu")
- state_dict_cpu = {k[7:]: v for (k, v) in checkpoint['state_dict'].items()}
- model.load_state_dict(state_dict_cpu)
-
-model.eval()
-
-def segment(inp):
- x = inp.transpose([2, 0, 1]) # channels-first
- x = np.expand_dims(x, axis=0) # adding a batch dimension
-
- mean = x.mean(axis=(0, 2, 3))
- std = x.std(axis=(0, 2, 3))
- x = x - mean.reshape(1, 3, 1, 1)
- x = x / std.reshape(1, 3, 1, 1)
-
- with torch.no_grad():
- x = torch.from_numpy(x).type('torch.FloatTensor').to(device)
- output = model(x)
-
- y = output['out'].numpy()
- y = y.squeeze()
-
- out = y>0
-
- mask = inp.copy()
- mask[out] = np.array([0, 0, 255])
-
- return mask
-
-import gradio as gr
-
-i = gr.inputs.Image(shape=(112, 112))
-o = gr.outputs.Image()
-
-examples = [["img1.jpg"], ["img2.jpg"]]
-title = "Example: Echocardiogram Segmentation" #"Left Ventricle Segmentation"
-description = "This semantic segmentation model identifies the left ventricle in echocardiogram images. Read more at the links below."
-# videos. Accurate evaluation of the motion and size of the left ventricle is crucial for the assessment of cardiac function and ejection fraction. In this interface, the user inputs apical-4-chamber images from echocardiography videos and the model will output a prediction of the localization of the left ventricle in blue. This model was trained on the publicly released EchoNet-Dynamic dataset of 10k echocardiogram videos with 20k expert annotations of the left ventricle and published as part of ‘Video-based AI for beat-to-beat assessment of cardiac function’ by Ouyang et al. in Nature, 2020."
-thumbnail = "https://raw.githubusercontent.com/gradio-app/hub-echonet/master/thumbnail.png"
-
-article = "