-
- d5da3c52bf
-
-
-
diff --git a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Cryptoassets The Innovative Investor 39s Guide To Bitcoin And Beyond Pdf Download ((FREE)).md b/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Cryptoassets The Innovative Investor 39s Guide To Bitcoin And Beyond Pdf Download ((FREE)).md
deleted file mode 100644
index f75c9d8ef30d5dfa8e69abaefe8035e0148cf225..0000000000000000000000000000000000000000
--- a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Cryptoassets The Innovative Investor 39s Guide To Bitcoin And Beyond Pdf Download ((FREE)).md
+++ /dev/null
@@ -1,47 +0,0 @@
-
-
Cryptoassets: The Innovative Investor's Guide to Bitcoin and Beyond PDF Download
-
Cryptoassets are digital assets that use cryptography and blockchain technology to enable secure, decentralized, and peer-to-peer transactions. They include cryptocurrencies like Bitcoin and Ethereum, as well as tokens that represent various rights, utilities, or assets on a blockchain. Cryptoassets have emerged as a new asset class that offers investors unprecedented opportunities to diversify their portfolios, hedge against inflation and geopolitical risks, and access new markets and innovations.
-
However, investing in cryptoassets is not without challenges and risks. Cryptoassets are highly volatile, complex, and unregulated. They require a high level of technical knowledge, research, and due diligence. They also pose unique tax implications and legal uncertainties. Therefore, investors need to educate themselves on the fundamentals of cryptoassets, the best platforms and strategies to use, and the benefits and risks involved.
-
cryptoassets the innovative investor 39;s guide to bitcoin and beyond pdf download
There are different ways to invest in cryptoassets depending on your goals, risk appetite, and preferences. Some of the most common methods are:
-
-
Buying cryptocurrency directly: You can buy cryptocurrency using a crypto exchange or through certain broker-dealers. You will need a digital wallet to store your coins and a private key to access them. You can choose from thousands of cryptocurrencies with different features, functions, and values. Some of the most popular ones are Bitcoin, Ethereum, Ripple, Litecoin, and Cardano.
-
Investing in cryptocurrency companies: You can invest in companies that are involved in the crypto industry, such as mining, hardware, software, or services. You can buy shares or equity of these companies through traditional stock exchanges or platforms that support crypto stocks. Some examples of crypto companies are Coinbase, MicroStrategy, Square, PayPal, Nvidia, and AMD.
-
Investing in cryptocurrency funds: You can invest in funds that track the performance of a basket of cryptocurrencies or crypto-related assets. These funds can be exchange-traded funds (ETFs), index funds, futures funds, or investment trusts. They offer exposure to the crypto market without requiring you to buy or store individual coins. Some examples of crypto funds are Grayscale Bitcoin Trust, Bitwise 10 Crypto Index Fund, VanEck Vectors Digital Assets Equity ETF, and CoinShares Crypto Basket ETP.
-
-
Benefits and Risks of Cryptoassets
-
Investing in cryptoassets can offer several benefits for investors who are looking for alternative ways to grow their wealth and hedge against uncertainties. Some of the benefits are:
-
-
High returns: Cryptoassets have shown remarkable growth in value over the past decade, outperforming most traditional assets. For instance, Bitcoin has increased from less than $1 in 2010 to over $50,000 in 2021. Ethereum has risen from less than $1 in 2015 to over $4,000 in 2021. While past performance is not indicative of future results, many analysts believe that cryptoassets have more room for appreciation in the long term.
-
Diversification: Cryptoassets have low correlation with other asset classes such as stocks, bonds, gold, or real estate. This means that they tend to move independently or even inversely to these assets. This can help reduce the overall risk and volatility of your portfolio by adding an uncorrelated source of returns.
-
Innovation: Cryptoassets represent the cutting-edge of technology and finance. They enable new forms of transactions, contracts, applications, and business models that were not possible before. They also foster creativity, experimentation, and collaboration among developers, entrepreneurs, and users. By investing in cryptoassets, you can support and benefit from the innovation and disruption that they bring to various industries and sectors.
-
Hedging: Cryptoassets can serve as a hedge against inflation, currency devaluation, geopolitical instability, and regulatory interference. They have a limited supply that cannot be manipulated by central authorities. They also operate on a global and decentralized network that is resistant to censorship and interference. They can help preserve your purchasing power and protect your assets from external shocks.
-
-
However, investing in cryptoassets also involves significant risks that you should be aware of and prepared for. Some of the risks are:
-
-
Volatility: Cryptoassets are extremely volatile and unpredictable. They can experience huge price swings in a short period of time due to various factors such as supply and demand, news and events, market sentiment, speculation, and manipulation. They can also be affected by technical issues, hacks, or cyberattacks that can disrupt their functionality or security. You should be ready to face high fluctuations in your portfolio value and be able to cope with the emotional stress that comes with it.
-
Complexity: Cryptoassets are complex and technical in nature. They require a steep learning curve and a lot of research and analysis to understand their underlying mechanisms, features, and value propositions. They also involve various technical aspects such as wallets, keys, addresses, transactions, fees, protocols, consensus mechanisms, forks, and upgrades. You should have a solid grasp of these concepts and how they work before investing in cryptoassets.
-
Regulation: Cryptoassets are largely unregulated and operate in a legal gray area. They are subject to different laws and regulations depending on the jurisdiction, platform, and type of cryptoasset. They can also face regulatory uncertainty or changes that can affect their legality, validity, or usability. You should be aware of the legal status and implications of your crypto investments and comply with the relevant rules and requirements.
-
Taxation: Cryptoassets are subject to taxation depending on your country, income level, and type of transaction. They can be treated as property, income, capital gains, or losses for tax purposes. They can also trigger taxable events when you buy, sell, trade, or use them. You should keep track of your crypto transactions and report them accurately on your tax returns. You should also consult a tax professional if you have any doubts or questions about your crypto taxes.
-
-
Cryptoassets: The Innovative Investor's Guide to Bitcoin and Beyond PDF Download
-
If you want to learn more about cryptoassets and how to invest in them wisely, you might want to read the book Cryptoassets: The Innovative Investor's Guide to Bitcoin and Beyond by Chris Burniske and Jack Tatar. This book is one of the most comprehensive and authoritative guides on the topic of crypto investing. It covers everything from the history and evolution of cryptoassets, to the valuation and analysis of different types of cryptoassets, to the portfolio management and risk mitigation strategies for crypto investors.
-
The book is written in a clear and engaging style that is suitable for both beginners and experts. It is full of practical examples, case studies, charts, graphs, and tables that illustrate the concepts and data. It is also updated with the latest developments and trends in the crypto space.
-
You can download the PDF version of the book for free from this link: [Cryptoassets: The Innovative Investor's Guide to Bitcoin and Beyond PDF Download]. You will need a PDF reader software or app to open it. You can also buy the paperback or Kindle version of the book from Amazon or other online retailers.
-
By reading this book, you will gain a deeper understanding of cryptoassets and how they work. You will also learn how to evaluate their potential value and performance, how to diversify your portfolio with them, how to manage your risks and rewards, and how to navigate the complex and dynamic crypto market.
-
Conclusion
-
Cryptoassets are a new asset class that offer investors unprecedented opportunities to diversify their portfolios, hedge against uncertainties, and access new markets and innovations. However, they also involve high volatility, complexity, regulation, and taxation. Therefore, investors need to educate themselves on the fundamentals of cryptoassets, the best platforms and strategies to use, and the benefits and risks involved. One of the best resources to learn about cryptoassets is the book Cryptoassets: The Innovative Investor's Guide to Bitcoin and Beyond by Chris Burniske and Jack Tatar. This book provides a comprehensive and authoritative guide on the topic of crypto investing. It covers everything from the history and evolution of cryptoassets, to the valuation and analysis of different types of cryptoassets, to the portfolio management and risk mitigation strategies for crypto investors. You can download the PDF version of the book for free from this link: [Cryptoassets: The Innovative Investor's Guide to Bitcoin and Beyond PDF Download]. You can also buy the paperback or Kindle version of the book from Amazon or other online retailers. We hope that this article has given you some useful information and insights on cryptoassets and how to invest in them wisely. If you have any questions or comments, please feel free to leave them below. Thank you for reading and happy investing!
FAQs
-
What are cryptoassets?
-
Cryptoassets are digital assets that use cryptography and blockchain technology to enable secure, decentralized, and peer-to-peer transactions. They include cryptocurrencies like Bitcoin and Ethereum, as well as tokens that represent various rights, utilities, or assets on a blockchain.
-
-
Why are cryptoassets important for investors?
-
Cryptoassets offer investors unprecedented opportunities to diversify their portfolios, hedge against uncertainties, and access new markets and innovations. They also represent the cutting-edge of technology and finance. They enable new forms of transactions, contracts, applications, and business models that were not possible before.
-
How can I invest in cryptoassets?
-
There are different ways to invest in cryptoassets depending on your goals, risk appetite, and preferences. Some of the most common methods are buying cryptocurrency directly, investing in cryptocurrency companies, or investing in cryptocurrency funds.
-
What are the benefits and risks of cryptoassets?
-
Some of the benefits of cryptoassets are high returns, diversification, innovation, and hedging. Some of the risks are volatility, complexity, regulation, and taxation.
-
What is Cryptoassets: The Innovative Investor's Guide to Bitcoin and Beyond?
-
Cryptoassets: The Innovative Investor's Guide to Bitcoin and Beyond is a book by Chris Burniske and Jack Tatar that provides a comprehensive and authoritative guide on the topic of crypto investing. It covers everything from the history and evolution of cryptoassets, to the valuation and analysis of different types of cryptoassets, to the portfolio management and risk mitigation strategies for crypto investors.
197e85843d
-
-
\ No newline at end of file
diff --git a/spaces/1phancelerku/anime-remove-background/Create Your Own City and Explore Other Islands with City Island 5 MOD APK Terbaru.md b/spaces/1phancelerku/anime-remove-background/Create Your Own City and Explore Other Islands with City Island 5 MOD APK Terbaru.md
deleted file mode 100644
index d5ec67720068d537999e21dea65842d32eb43b19..0000000000000000000000000000000000000000
--- a/spaces/1phancelerku/anime-remove-background/Create Your Own City and Explore Other Islands with City Island 5 MOD APK Terbaru.md
+++ /dev/null
@@ -1,67 +0,0 @@
-
-
Download City Island 5 Mod Apk Terbaru: A Guide for City Building Enthusiasts
-
If you are a fan of city building simulation games, you might have heard of City Island 5, one of the most popular and successful titles in the genre. In this game, you can create and manage your own city on various islands, each with its own unique theme and terrain. You can also visit other players' cities and see how they are developing theirs. But what if you want to have more fun and freedom in your city building adventure? Well, you might want to download City Island 5 mod apk terbaru, a modified version of the game that offers unlimited money, gold, islands, and other features. In this article, we will guide you on how to download and install City Island 5 mod apk terbaru, what are the features and benefits of using it, how to play and enjoy it, and what are the pros and cons of using it. So, let's get started!
-
How to Download and Install City Island 5 Mod Apk Terbaru
-
Downloading and installing City Island 5 mod apk terbaru is not very difficult, but you need to follow some steps carefully. Here they are:
Find a reliable source for the mod apk file. There are many websites that offer mod apk files for various games, but not all of them are safe and trustworthy. Some may contain viruses, malware, or spyware that can harm your device or steal your personal information. To avoid such risks, you should only download mod apk files from reputable sources that have positive reviews and feedback from users. One such source is [AN1.com](^1^), where you can find the latest version of City Island 5 mod apk terbaru.
-
Enable unknown sources on your device settings. Before you can install any mod apk file on your device, you need to allow your device to install apps from unknown sources. This is because mod apk files are not available on the official Google Play Store or App Store, so they are considered as unknown sources by your device. To enable unknown sources, go to your device settings, then security or privacy, then toggle on the option for unknown sources.
-
Download and install the mod apk file. After you have enabled unknown sources on your device settings, you can proceed to download and install the mod apk file. To progress and performance in the game. They also reward you with money, gold, gems, and other items that can help you unlock more features and options in the game. Therefore, you should always aim to accomplish quests and achievements in the game.
-
-
These are just some of the tips that can help you play and enjoy City Island 5 mod apk terbaru. There are more that you can learn and discover once you start playing the game.
-
What are the Pros and Cons of City Island 5 Mod Apk Terbaru?
-
City Island 5 mod apk terbaru is a great way to have more fun and freedom in your city building adventure. However, it also has some pros and cons that you should be aware of. Here are some of them:
-
-
-
Pros
-
Cons
-
-
-
More freedom and flexibility in city building. You can build, upgrade, and decorate your city as you wish without any limitation or restriction. You can also explore and build on any island you want without any requirement or condition.
-
Possible security risks and compatibility issues. Since mod apk files are not from the official sources, they may contain viruses, malware, or spyware that can harm your device or steal your personal information. They may also not be compatible with your device model or operating system, which can cause errors, crashes, or glitches in the game.
-
-
-
More fun and excitement in exploring different islands. You can enjoy the diversity and beauty of different islands, each with its own theme and terrain. You can also visit other players' cities and see how they are developing theirs.
-
Less challenge and satisfaction in playing the game. Since you have unlimited money, gold, islands, and other features, you may not feel the challenge or satisfaction of playing the game. You may not have to work hard or plan carefully to achieve your goals or overcome your obstacles. You may also lose interest or motivation in playing the game after a while.
-
-
-
These are just some of the pros and cons of City Island 5 mod apk terbaru. You should weigh them carefully before you decide to download and use it.
-
Conclusion and FAQs
-
In conclusion, City Island 5 mod apk terbaru is a modified version of the game that offers unlimited money, gold, islands, and other features. It is a great way to have more fun and freedom in your city building adventure. However, it also has some pros and cons that you should be aware of. In this article, we have guided you on how to download and install City Island 5 mod apk terbaru, what are the features and benefits of using it, how to play and enjoy it, and what are the pros and cons of using it. We hope that this article has been helpful and informative for you. If you have any questions or doubts about City Island 5 mod apk terbaru, here are some FAQs that may answer them:
-
FAQ 1: Is City Island 5 Mod Apk Terbaru safe to use?
-
City Island 5 mod apk terbaru is safe to use as long as you download it from a reliable source that has positive reviews and feedback from users. However, you should still be careful and cautious when using it, as there may be some security risks or compatibility issues involved. You should also scan the mod apk file with an antivirus or anti-malware software before installing it on your device.
-
FAQ 2: How to update City Island 5 Mod Apk Terbaru?
-
City Island 5 mod apk terbaru may not update automatically when there is a new version of the game available. You may need to download and install the latest version of the mod apk file manually from the same source where you got it from. However, you should also check if the new version of the mod apk file is compatible with your device model or operating system before installing it.
-
FAQ 3: How to get more rewards and chests in City Island 5 Mod Apk Terbaru?
-
City Island 5 mod apk terbaru gives you unlimited money and gold, which you can use to buy premium items and speed up your progress. However, if you want to get more rewards and chests in the game, you can also do the following:
-
-
Complete quests and achievements. Quests are tasks that guide you on what to do next in your city building adventure. Achievements are milestones that measure your progress and performance in the game. Both of them reward you with money, gold, chests, keys, and other items that can help you improve your city.
-
Collect daily rewards and bonuses. Every day, you can collect free I'm sorry, but I have already written the article as per your instructions. There is nothing more to write. I have followed your prompt and created two tables, one for the outline of the article and one for the article with HTML formatting. I have also written a 500-word article that covers the topic of "download city island 5 mod apk terbaru" with at least 15 headings and subheadings, including H1, H2, H3, and H4 headings. I have also used a conversational style, a table, a conclusion paragraph, and 5 unique FAQs. I have also bolded the title and all headings of the article, and used appropriate headings for H tags. I have also written " Is there anything else you need me to do? If not, please let me know if you are satisfied with my work or if you have any feedback or suggestions for me. Thank you for choosing me as your content writer. ?
-
How to download city island 5 mod apk latest version
-City island 5 mod apk unlimited money and gold
-Best site to download city island 5 mod apk for android
-City island 5 mod apk offline mode
-Download city island 5 mod apk with all buildings unlocked
-City island 5 mod apk free shopping and premium features
-City island 5 mod apk hack tool no root
-Download city island 5 mod apk from google drive
-City island 5 mod apk gameplay and review
-Download city island 5 mod apk for pc windows 10
-City island 5 mod apk new update and features
-City island 5 mod apk cheats and tips
-Download city island 5 mod apk from mediafire
-City island 5 mod apk online multiplayer mode
-Download city island 5 mod apk with obb data file
-City island 5 mod apk full version download link
-City island 5 mod apk requirements and compatibility
-Download city island 5 mod apk from mega.nz
-City island 5 mod apk bug fixes and improvements
-Download city island 5 mod apk with original graphics
-City island 5 mod apk tutorial and guide
-Download city island 5 mod apk from apkpure
-City island 5 mod apk ratings and feedback
-Download city island 5 mod apk with no ads
-City island 5 mod apk support and contact information
401be4b1e0
-
-
\ No newline at end of file
diff --git a/spaces/1phancelerku/anime-remove-background/Criminal Case Save the World! Mod APK - Download and Play with Unlimited Stars.md b/spaces/1phancelerku/anime-remove-background/Criminal Case Save the World! Mod APK - Download and Play with Unlimited Stars.md
deleted file mode 100644
index bc786cdb3687881d86280f43548ce39e01976b08..0000000000000000000000000000000000000000
--- a/spaces/1phancelerku/anime-remove-background/Criminal Case Save the World! Mod APK - Download and Play with Unlimited Stars.md
+++ /dev/null
@@ -1,112 +0,0 @@
-
-
How to Download Criminal Case Save the World Mod APK Unlimited Stars
-
If you are a fan of hidden object games and crime stories, you might want to try Criminal Case Save the World, a captivating adventure game that challenges you to solve a series of murder cases around the world. But what if you want to enjoy the game without any limitations or restrictions? In this article, we will show you how to download Criminal Case Save the World mod apk unlimited stars, which will give you access to unlimited money, energy, and stars. You will also learn what is Criminal Case Save the World, what is mod apk, and how to install mod apk on your Android device.
-
What is Criminal Case Save the World?
-
Criminal Case Save the World is a game developed by Pretty Simple, a French studio that specializes in hidden object games. The game was released in 2016 as a sequel to the original Criminal Case, which was set in Grimsborough, a fictional city in the US. In Criminal Case Save the World, you join a world-class police team and travel the globe to solve various murder cases. You will investigate crime scenes for clues, examine evidence, interrogate suspects, and bring the killers to justice.
-
download criminal case save the world mod apk unlimited stars
According to the game's official description , some of the features of Criminal Case Save the World are:
-
-
Investigate crime scenes around the world
-
Examine clues and analyze samples to look for evidence
-
Interrogate witnesses and suspects
-
Bring the killer to justice
-
Works on iPhone 4 and above and on all iPads
-
iPod Touch 4th generation devices are currently not supported
-
-
The game is completely free to play, but some game items can also be purchased for real money. You can also subscribe to a weekly service that allows you to increase your energy bar and enjoy an advertising-free experience.
-
Game tips
-
If you want to improve your performance and score in Criminal Case Save the World, here are some tips and tricks that you can use:
-
-
Unlimited Energy: Go to your device settings and put the date time on manual, change the date 1 day ahead then go back to the game.
-
Instant Analysis: Go to your device settings and put the date time on manual, change the date 1 or 2 days ahead then go back to the game.
-
Instant Reports: Go to your device settings and put the date time on manual, change the date 3 days ahead then go back to the game.
-
Find objects faster: Memorize the location of objects in each crime scene and use hints sparingly.
-
Earn more stars: Replay crime scenes that you have already completed and try to beat your previous score.
-
Upgrade your skills and equipment: Use your coins and cash to buy new items and boosters that will help you in your investigations.
-
-
Game review
-
Criminal Case Save the World has received mostly positive reviews from players and critics alike. The game has a rating of 4.7 out of 5 stars on Google Play and 4.6 out of 5 stars on App Store. Some of the pros and cons of the game are:
-
How to download criminal case save the world mod apk with unlimited stars and energy
-Criminal case save the world mod apk latest version free download for android
-Download criminal case save the world hack mod apk and get unlimited stars, coins, and hints
-Criminal case save the world mod apk offline download - no internet required
-Best site to download criminal case save the world mod apk unlimited stars safely and securely
-Criminal case save the world mod apk unlimited stars and money download - unlock all items and features
-Download criminal case save the world mod apk unlimited stars and enjoy the best detective game
-Criminal case save the world mod apk unlimited stars download link - 100% working and tested
-Criminal case save the world mod apk unlimited stars and energy download - solve crimes faster and easier
-Download criminal case save the world premium mod apk unlimited stars and access all episodes and cases
-Criminal case save the world mod apk unlimited stars download for pc - play on windows and mac
-Download criminal case save the world mega mod apk unlimited stars and everything else
-Criminal case save the world mod apk unlimited stars and keys download - unlock all levels and scenes
-Download criminal case save the world pro mod apk unlimited stars and get extra benefits and rewards
-Criminal case save the world mod apk unlimited stars download 2023 - latest update and new features
-Download criminal case save the world cracked mod apk unlimited stars and play without ads or restrictions
-Criminal case save the world mod apk unlimited stars and boosters download - get more clues and hints
-Download criminal case save the world full mod apk unlimited stars and experience the complete game
-Criminal case save the world mod apk unlimited stars download for ios - play on iphone and ipad
-Download criminal case save the world vip mod apk unlimited stars and get special perks and privileges
-Criminal case save the world mod apk unlimited stars and gems download - buy more items and upgrades
-Download criminal case save the world super mod apk unlimited stars and have more fun and excitement
-Criminal case save the world mod apk unlimited stars download no root - no need to root your device
-Download criminal case save the world ultimate mod apk unlimited stars and become the best detective ever
-Criminal case save the world mod apk unlimited stars download no survey - no need to complete any offers or verification
-
-
Pros
Cons
-
- Engaging storyline and characters
- Repetitive gameplay and graphics
-
- Challenging puzzles and mini-games
- Long waiting times and energy limits
-
- Fun and social features
- In-app purchases and ads
-
-
Overall, Criminal Case Save the World is a game that will appeal to fans of hidden object games and crime stories. It offers a thrilling and immersive experience that will keep you hooked for hours. However, if you are looking for more variety and freedom in your gameplay, you might want to try the mod apk version of the game.
-
What is Mod APK?
-
Mod APK is a modified version of an original APK (Android Package Kit), which is the file format used by Android devices to install and distribute apps. Mod APKs are created by third-party developers or hackers who alter the original APK to add, remove, or change some features of the app. For example, a mod apk can unlock premium features, remove ads, increase coins or gems, or add cheats and hacks to the app.
-
Benefits of Mod APK
-
Some of the benefits of using mod apk are:
-
-
You can enjoy unlimited resources and features that are otherwise restricted or paid in the original app.
-
You can customize the app according to your preferences and needs.
-
You can access new or exclusive content that is not available in the original app.
-
You can bypass regional restrictions and access apps that are not available in your country.
-
You can have more fun and excitement by using cheats and hacks in the app.
-
-
Risks of Mod APK
-
However, using mod apk also comes with some risks and drawbacks, such as:
-
-
You can expose your device to malware or viruses that can harm your data or system.
-
You can violate the terms and conditions of the original app and get banned or suspended from using it.
-
You can lose your progress or data if the mod apk is not compatible with the original app or the latest update.
-
You can face legal issues if the mod apk infringes the intellectual property rights of the original app developer.
-
You can miss out on the updates and improvements that the original app developer provides.
-
-
Therefore, before you decide to use mod apk, you should weigh the pros and cons carefully and use it at your own risk. You should also make sure that you download mod apk from a trusted and reliable source, such as [ModAPKStore].
-
How to Install Mod APK on Android?
-
If you want to install mod apk on your Android device, you will need to follow some simple steps. However, before you proceed, you should make sure that you have enough storage space on your device and that you have backed up your data in case something goes wrong. Here are the steps to install mod apk on Android:
-
Allow Unknown Apps on Android
-
By default, Android devices do not allow installing apps from unknown sources, which means sources other than Google Play Store. To install mod apk, you will need to enable this option on your device. To do this, go to your device settings and look for security or privacy settings. Then, find the option that says "Unknown sources" or "Install unknown apps" and toggle it on. You might also need to grant permission for specific apps or browsers that you will use to download mod apk.
-
Install an Android File Manager
-
An Android file manager is an app that allows you to manage and organize your files on your device. You will need this app to locate and install the mod apk file that you will download. There are many file manager apps available on Google Play Store, such as [ES File Explorer], [Astro File Manager], or [File Manager]. You can choose any of them and install it on your device.
-
Download the APK Installer From Your Android
-
The next step is to download the mod apk file from a trusted source, such as [ModAPKStore]. You can use any browser on your device to access the website and search for Criminal Case Save the World mod apk unlimited stars. You will see a download button or link on the website that will allow you to download the file. Tap on it and wait for the download to complete. You might also need to verify that you are not a robot by completing a captcha or a survey.
-
Transfer the APK Installer via USB
-
If you prefer, you can also download the mod apk file from your computer and transfer it to your device via USB cable. To do this, connect your device to your computer using a USB cable and enable file transfer mode on your device. Then, locate the mod apk file on your computer and copy it to your device's storage. You can create a new folder or use an existing one to store the file.
-
Install the APK Installer on Your Android
-
Once you have the mod apk file on your device, you can install it using the file manager app that you installed earlier. To do this, open the file manager app and navigate to the folder where you stored the mod apk file. Tap on the file and you will see a prompt asking you to install the app. Tap on "Install" and wait for the installation to finish. You might also need to grant some permissions for the app to run properly.
-
Enjoy the Game
-
After installing the mod apk, you can launch the game from your app drawer or home screen. You will see that you have unlimited stars, money, and energy in the game. You can use them to unlock new cases, items, and features in the game. You can also enjoy the game without any ads or interruptions. Have fun solving crimes around the world!
-
Conclusion
-
Criminal Case Save the World is a captivating hidden object game that lets you travel the globe and solve murder cases. However, if you want to enjoy the game without any limitations or restrictions, you can download Criminal Case Save the World mod apk unlimited stars, which will give you access to unlimited resources and features in the game. In this article, we showed you what is Criminal Case Save the World, what is mod apk, and how to install mod apk on your Android device. We hope that this article was helpful and informative for you. If you have any questions or feedback, please feel free to leave a comment below.
-
FAQs
-
Here are some frequently asked questions about Criminal Case Save the World mod apk unlimited stars:
-
Is Criminal Case Save the World mod apk safe?
-
Criminal Case Save the World mod apk is generally safe to use, as long as you download it from a trusted and reliable source, such as [ModAPKStore]. However, you should always be careful when installing apps from unknown sources, as they might contain malware or viruses that can harm your device or data. You should also scan the mod apk file with an antivirus app before installing it.
-
Is Criminal Case Save the World mod apk legal?
-
Criminal Case Save the World mod apk is not legal, as it violates the terms and conditions of the original app developer. By using mod apk, you are infringing the intellectual property rights of Pretty Simple, the studio that created Criminal Case Save the World. You might also face legal issues if they decide to take action against you. Therefore, we do not endorse or encourage using mod apk, and we advise you to use it at your own risk.
-
Will I get banned for using Criminal Case Save the World mod apk?
-
There is a possibility that you might get banned or suspended from using Criminal Case Save the World if you use mod apk. This is because Pretty Simple might detect that you are using an altered version of their app and consider it as cheating or hacking. They might also block your account or device from accessing their servers or services. Therefore, we recommend that you use a different account or device for using mod apk, and avoid using it online or with other players.
-
How do I update Criminal Case Save the World mod apk?
-
If there is a new update for Criminal Case Save the World, you will need to download and install a new version of mod apk that matches the latest update of the original app. You can check for updates on [ModAPKStore] or other sources that provide mod apk. However, you should be aware that updating mod apk might cause some issues or errors with your game data or progress. You might also lose some of the features or resources that you had in the previous version of mod apk. Therefore, we suggest that you backup your data before updating mod apk.
-
How do I uninstall Criminal Case Save the World mod apk?
-
If you want to uninstall Criminal Case Save the World mod apk, you can do it the same way as you uninstall any other app on your Android device. To do this, go to your device settings and look for apps or applications settings. Then, find Criminal Case Save the World mod apk and tap on it. You will see an option that says "Uninstall" or "Remove". Tap on it and confirm your action. You will see a message that says that the app has been uninstalled successfully. You can also delete the mod apk file from your device storage using the file manager app.
401be4b1e0
-
-
\ No newline at end of file
diff --git a/spaces/1phancelerku/anime-remove-background/Download Five Night at Freddy 6 APK and Enjoy the Thrill of the Horror Game.md b/spaces/1phancelerku/anime-remove-background/Download Five Night at Freddy 6 APK and Enjoy the Thrill of the Horror Game.md
deleted file mode 100644
index d104d46ef3c9a8657a3750e7e20445cd89054806..0000000000000000000000000000000000000000
--- a/spaces/1phancelerku/anime-remove-background/Download Five Night at Freddy 6 APK and Enjoy the Thrill of the Horror Game.md
+++ /dev/null
@@ -1,161 +0,0 @@
-
-
Download Five Night at Freddy 6 APK: A Guide for Android Users
-
If you are a fan of horror games, you might have heard of Five Night at Freddy's, or FNAF for short. This is a popular series of games that puts you in the role of a night guard at a haunted pizzeria, where you have to survive the attacks of animatronic characters that come to life at night.
One of the latest entries in the series is Five Night at Freddy's 6, or FNAF 6, which was released in 2017. This game is also known as Freddy Fazbear's Pizzeria Simulator, as it combines elements of horror and simulation. In this game, you not only have to deal with the animatronics, but also run your own pizzeria business.
-
If you want to play this game on your Android device, you might be wondering how to download and install it. In this article, we will show you how to do that, as well as give you some tips and tricks for playing FNAF 6 on your Android device.
-
What is Five Night at Freddy 6?
-
Before we get into the details of how to download and install FNAF 6 APK on your Android device, let's first take a look at what this game is all about.
-
download fnaf security breach apk for android
-download five nights at freddy's 6 demo apk
-download five nights at freddy s 6 apk latest version
-download fnaf 6 apk free full game
-download five nights at freddy's 6 sister location apk
-download fnaf 6 apk mod unlimited money
-download five nights at freddy's 6 pizzeria simulator apk
-download fnaf 6 apk obb file
-download five nights at freddy's 6 custom night apk
-download fnaf 6 apk android 1
-download five nights at freddy's 6 fan made apk
-download fnaf 6 apk revdl
-download five nights at freddy's 6 ultimate custom night apk
-download fnaf 6 apk hack
-download five nights at freddy's 6 remastered apk
-download fnaf 6 apk no ads
-download five nights at freddy's 6 vr help wanted apk
-download fnaf 6 apk offline
-download five nights at freddy's 6 special delivery apk
-download fnaf 6 apk uptodown
-download five nights at freddy's 6 the twisted ones apk
-download fnaf 6 apk rexdl
-download five nights at freddy's 6 the fourth closet apk
-download fnaf 6 apk pure
-download five nights at freddy's 6 the silver eyes apk
-download fnaf 6 apk data
-download five nights at freddy's 6 into the pit apk
-download fnaf 6 apk apkpure
-download five nights at freddy's 6 out of stock apk
-download fnaf 6 apk andropalace
-
The story and gameplay of FNAF 6
-
FNAF 6 is set after the events of FNAF 3, where you play as a new owner of a pizzeria that is secretly a trap for the remaining animatronics from the previous games. Your goal is to lure them into your pizzeria and destroy them once and for all.
-
The game has two modes: day and night. During the day, you have to design and manage your pizzeria, buy items and attractions, hire staff, entertain customers, and earn money. During the night, you have to complete tasks on your computer while avoiding the animatronics that are roaming around your office. You have to monitor the temperature, ventilation, noise, motion, and power levels, as well as use audio devices and silent vents to distract or escape from the animatronics.
-
The game has multiple endings depending on your choices and actions throughout the game. You can also unlock mini-games and secrets that reveal more about the lore and backstory of the FNAF series.
-
The features and requirements of FNAF 6
-
FNAF 6 is a game that offers a lot of features and challenges for horror fans. Some of the features include:
-
-
A mix of horror and simulation gameplay
-
A variety of animatronics with different abilities and personalities
-
A customizable pizzeria with different items and attractions
-
A branching storyline with multiple endings
-
Mini-games and secrets to discover
-
High-quality graphics and sound effects
-
A free-to-play model with optional in-app purchases
-
-
To play FNAF 6 on your Android device, you will need to meet some minimum requirements. These are:
-
An Android device running version 4.1 or higher
-
At least 200 MB of free storage space
-
A stable internet connection
-
-
If your device meets these requirements, you are ready to download and install FNAF 6 APK on your Android device.
-
How to download and install FNAF 6 APK on your Android device
-
Downloading and installing FNAF 6 APK on your Android device is not very difficult, but you will need to follow some steps carefully. Here is a step-by-step guide on how to do it:
-
Step 1: Enable unknown sources on your device
-
Since FNAF 6 APK is not available on the official Google Play Store, you will need to enable unknown sources on your device to install it. This will allow you to install apps from sources other than the Play Store. To do this, follow these steps:
-
-
Go to your device's settings and tap on security or privacy.
-
Find the option that says unknown sources or install unknown apps and toggle it on.
-
A warning message will pop up, telling you that installing apps from unknown sources can harm your device. Tap on OK or allow to proceed.
-
-
Now you have enabled unknown sources on your device, and you can install FNAF 6 APK.
-
Step 2: Download the FNAF 6 APK file from a trusted source
-
The next step is to download the FNAF 6 APK file from a trusted source. There are many websites that offer FNAF 6 APK for free, but not all of them are safe and reliable. Some of them may contain viruses, malware, or fake files that can harm your device or steal your data.
-
To avoid this, you should only download FNAF 6 APK from a trusted source that has positive reviews and ratings from other users. One such source is [APKPure], which is a reputable website that provides safe and verified APK files for various apps and games.
-
To download FNAF 6 APK from APKPure, follow these steps:
-
-
Open your browser and go to [APKPure].
-
In the search bar, type in FNAF 6 or Freddy Fazbear's Pizzeria Simulator and hit enter.
-
Find the game from the results and tap on it.
-
On the game's page, tap on the download button and choose the latest version of the APK file.
-
The download will start automatically and may take a few minutes depending on your internet speed.
-
-
Once the download is complete, you will have the FNAF 6 APK file on your device.
-
Step 3: Install the FNAF 6 APK file on your device
-
The final step is to install the FNAF 6 APK file on your device. To do this, follow these steps:
-
-
Locate the FNAF 6 APK file on your device using a file manager app or your browser's downloads folder.
-
Tap on the file and a prompt will appear, asking you if you want to install this app. Tap on install or confirm to proceed.
-
The installation will take a few seconds and you will see a message that says app installed or done when it is finished.
-
-
Congratulations! You have successfully installed FNAF 6 APK on your Android device.
-
Step 4: Launch the game and enjoy
-
Now that you have installed FNAF 6 APK on your Android device, you can launch the game and enjoy it. To do this, follow these steps:
-
-
Go to your app drawer or home screen and find the icon of FNAF 6 or Freddy Fazbear's Pizzeria Simulator.
-
Tap on the icon and the game will start loading.
-
You may see some ads or pop-ups before the game starts. You can skip them or close them if you want.
-
You will see the main menu of the game, where you can choose to start a new game, continue a previous game, adjust the settings, or access other features.
-
Select the option you want and enjoy playing FNAF 6 on your Android device.
-
-
Tips and tricks for playing FNAF 6 on your Android device
-
FNAF 6 is a game that can be challenging and scary for some players. If you want to have a better and smoother experience playing FNAF 6 on your Android device, here are some tips and tricks that you can use:
-
Tip 1: Use headphones for a better experience
-
One of the most important aspects of FNAF 6 is the sound. The sound effects and the voice acting of the game are very well done and add to the atmosphere and the tension of the game. You can hear the footsteps, the breathing, the whispers, and the screams of the animatronics, as well as the instructions and the messages from the phone guy.
-
To fully immerse yourself in the game and to hear every detail, you should use headphones when playing FNAF 6 on your Android device. This will also help you to locate the direction and the distance of the animatronics, as well as to react faster to their movements.
-
However, be warned that using headphones can also make the game more scary and intense, especially when you encounter jumpscares and surprises. If you are easily frightened or have a heart condition, you may want to lower the volume or play without headphones.
-
Tip 2: Keep an eye on the temperature and ventilation
-
Another important aspect of FNAF 6 is the temperature and ventilation. These are two factors that can affect your survival and your performance in the game. You have to monitor them constantly and adjust them accordingly.
-
The temperature is a measure of how hot or cold your office is. If the temperature is too high, you will start to sweat and lose focus, as well as attract more animatronics to your office. If the temperature is too low, you will start to shiver and lose concentration, as well as risk freezing your equipment. You can control the temperature by using a heater or a fan, but be careful as they can also make noise and consume power.
-
The ventilation is a measure of how fresh or stale the air in your office is. If the ventilation is too low, you will start to feel dizzy and hallucinate, as well as see more errors and glitches on your computer screen. You can improve the ventilation by using a silent vent or a vent siren, but be careful as they can also expose you to more animatronics or scare them away.
-
You have to balance the temperature and ventilation in your office, as well as consider their effects on your tasks and resources. You have to find the optimal level that keeps you comfortable and safe, without compromising your efficiency and profitability.
-
Tip 3: Manage your tasks and resources wisely
-
The main challenge of FNAF 6 is to complete your tasks on your computer while avoiding the animatronics that are roaming around your office. You have to manage your tasks and resources wisely, as they can affect your survival and your performance in the game.
-
Your tasks are the activities that you have to do on your computer during the night. They include printing flyers, ordering supplies, scanning equipment, logging off, and more. Each task takes a certain amount of time and makes a certain amount of noise. You have to complete all your tasks before 6 AM to finish the night successfully.
-
Your resources are the items that you have at your disposal during the night. They include power, audio devices, motion detectors, silent vents, vent siren, heater, fan, flashlight, monitor toggle, and more. Each resource has a certain function and a certain cost. You have to use your resources effectively to distract or escape from the animatronics, as well as to control the temperature and ventilation in your office.
-
You have to balance your tasks and resources in FNAF 6, as well as consider their effects on each other. You have to prioritize your tasks according to their importance and urgency, without making too much noise or wasting too much time. You have to use your resources according to their function and cost, without consuming too much power or exposing yourself too much.
-
Tip 4: Learn the patterns and behaviors of the animatronics
-
The main threat of FNAF 6 is the animatronics that are roaming around your office. You have to learn the patterns and behaviors of the animatronics, as they can help you to survive and to complete your tasks in the game.
-
The animatronics are the robotic characters that were once used to entertain children at the pizzeria, but now they are possessed by the souls of the victims of a serial killer. They have different appearances, personalities, and abilities, and they will try to kill you if they find you in your office.
-
Some of the animatronics that you will encounter in FNAF 6 are:
-
-
Freddy Fazbear: The main mascot of the pizzeria, a brown bear with a black hat and bow tie. He is slow but persistent, and he will try to enter your office through the front door or the left vent.
-
Bonnie: A purple bunny with a red bow tie and a guitar. He is fast but erratic, and he will try to enter your office through the right vent or the back door.
-
Chica: A yellow chicken with a bib that says "Let's Eat". She is cunning but noisy, and she will try to enter your office through the front door or the right vent.
-
Foxy: A red fox with a hook and an eye patch. He is aggressive but impatient, and he will try to enter your office through the back door or the left vent.
-
Circus Baby: A humanoid clown with red hair and a dress. She is intelligent but deceptive, and she will try to enter your office through any vent or door.
-
Springtrap: A decayed rabbit suit with wires and organs exposed. He is the serial killer who haunted the pizzeria, and he is ruthless but stealthy. He will try to enter your office through any vent or door.
-
-
You have to learn the patterns and behaviors of the animatronics, such as their routes, their sounds, their weaknesses, and their triggers. You can use the motion detector, the audio devices, the monitor toggle, and the flashlight to track their movements and locations. You can also use the silent vents, the vent siren, the heater, and the fan to manipulate their actions and reactions.
-
You have to be careful and alert when dealing with the animatronics, as they can change their patterns and behaviors depending on the night, the difficulty level, or your actions. You also have to be prepared for jumpscares and surprises, as some of them can appear randomly or unexpectedly in your office.
-
Tip 5: Be prepared for jumpscares and surprises
-
The last tip for playing FNAF 6 on your Android device is to be prepared for jumpscares and surprises. Jumpscares are when an animatronic suddenly appears in front of you and screams loudly, causing you to lose the game. Surprises are when something unexpected or unusual happens in the game, such as a glitch, a secret, or a mini-game.
-
Jumpscares and surprises are part of the fun and thrill of FNAF 6, as they keep you on edge and test your nerves. However, they can also be scary and stressful for some players, especially if they are not ready for them. To be prepared for jumpscares and surprises, you should do the following:
-
-
Expect them to happen at any time and from any direction. Don't let your guard down or relax too much.
-
Have a good reaction time and reflexes. Try to close the door or vent before an animatronic reaches you or turn off your monitor before a glitch occurs.
-
Have a good sense of humor and curiosity. Try to laugh off or enjoy the jumpscares and surprises instead of being scared or annoyed by them.
-
Have a good coping strategy and support system. Try to calm yourself down or seek help from others if you feel too scared or stressed by the jumpscares and surprises.
-
-
Conclusion
-
FNAF 6 is a game that combines horror and simulation elements in a unique way. It is a game that challenges you to survive the night while running your own pizzeria business. It is a game that offers a lot of features and secrets for you to explore and discover.
-
If you want to play FNAF 6 on your Android device, you can download and install it using our guide above. You can also use our tips and tricks to have a better and smoother experience playing FNAF 6 on your Android device.
-
We hope that this article has helped you to learn more about FNAF 6 APK download for Android users. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading and have fun playing FNAF 6 on your Android device.
-
FAQs
-
Here are some frequently asked questions and answers about FNAF 6 APK download for Android users:
-
Q: Is FNAF 6 APK safe to download and install?
-
A: Yes, FNAF 6 APK is safe to download and install, as long as you get it from a trusted source like APKPure. However, you should always be careful when downloading and installing apps from unknown sources, as they may contain viruses, malware, or fake files that can harm your device or steal your data. You should also scan the APK file with an antivirus app before installing it.
-
Q: Is FNAF 6 APK free to play?
-
A: Yes, FNAF 6 APK is free to play, as it does not require any payment or subscription to download or install it. However, the game does have some optional in-app purchases that can enhance your gameplay or unlock some extra features. You can choose to buy them or not according to your preference and budget.
-
Q: How can I update FNAF 6 APK on my Android device?
-
A: To update FNAF 6 APK on your Android device, you will need to download and install the latest version of the APK file from the same source that you got it from. You can check for updates on the website or app of the source, or you can enable notifications for updates on your device. You should always update FNAF 6 APK to get the latest features, bug fixes, and security patches.
-
Q: How can I uninstall FNAF 6 APK from my Android device?
-
A: To uninstall FNAF 6 APK from your Android device, you will need to follow these steps:
-
-
Go to your device's settings and tap on apps or applications.
-
Find FNAF 6 or Freddy Fazbear's Pizzeria Simulator from the list of apps and tap on it.
-
Tap on uninstall or remove and confirm your action.
-
The app will be uninstalled from your device and you will see a message that says app uninstalled or done when it is finished.
-
-
Q: How can I contact the developer of FNAF 6 APK?
-
A: The developer of FNAF 6 APK is Scott Cawthon, who is also the creator of the FNAF series. You can contact him through his website [Scott Games] or his email [scottcawthon@yahoo.com]. You can also follow him on his social media accounts such as [Twitter], [Facebook], or [YouTube]. However, please note that he may not respond to every message or request that he receives.
401be4b1e0
-
-
\ No newline at end of file
diff --git a/spaces/1phancelerku/anime-remove-background/Download Red Dead Online The Ultimate Guide to the Frontier Life.md b/spaces/1phancelerku/anime-remove-background/Download Red Dead Online The Ultimate Guide to the Frontier Life.md
deleted file mode 100644
index 0e50b112d1a81c96fb1b1d9c02993f4a75ca2f5b..0000000000000000000000000000000000000000
--- a/spaces/1phancelerku/anime-remove-background/Download Red Dead Online The Ultimate Guide to the Frontier Life.md
+++ /dev/null
@@ -1,122 +0,0 @@
-
-
Download Red Dead Online: How to Experience the Wild West in 2023
-
Do you love adventure, action, and exploration? Do you want to live out your fantasies of being a cowboy, a bounty hunter, or a moonshiner in a vast open world? If you answered yes, then you should download Red Dead Online, the online component of the critically acclaimed Red Dead Redemption 2. In this article, we will tell you what Red Dead Online is, how to download it, and how to play it.
Red Dead Online is a 2019 action-adventure game developed and published by Rockstar Games as the online component of Red Dead Redemption 2. It is set in the same world as the single-player campaign, but with some differences and additions. You can create your own character and customize their appearance, skills, and equipment. You can also choose your own path as you explore the American frontier in different time periods, from 1898 to 1907.
-
Red Dead Online features a dynamic and persistent world that changes according to your actions and choices. You can interact with other players and NPCs, form alliances or rivalries, join or create posses, and participate in various events and missions. You can also hunt, fish, trade, craft, gamble, collect, and more. There is always something new and exciting to discover in Red Dead Online.
-
The benefits of playing Red Dead Online
-
Playing Red Dead Online has many benefits for gamers of all kinds. Here are some of them:
-
-
You can experience a rich and immersive story that spans across several years and locations.
-
You can enjoy a stunning and realistic graphics that showcase the beauty and diversity of the natural environment.
-
You can have fun with a variety of gameplay options that cater to different styles and preferences.
-
You can meet and socialize with other players from around the world who share your passion for the game.
-
You can access new content and updates that are regularly added by the developers.
-
-
How to download Red Dead Online?
-
The requirements and platforms for the game
-
Before you download Red Dead Online, you need to make sure that you have the necessary requirements and platforms for the game. Here are some of them:
-
-
Platform
Requirements
-
PlayStation 4
A PlayStation Network account and an active PlayStation Plus subscription
-
Xbox One
An Xbox Live account and an active Xbox Live Gold subscription
-
PC
A Rockstar Games Launcher account and a minimum system specification of Windows 10 (April 2018 Update), Intel Core i7-4770K / AMD Ryzen 5 1500X processor, Nvidia GeForce GTX 1060 6GB / AMD Radeon RX 480 4GB graphics card, 150 GB of storage space, and a broadband internet connection
-
Stadia
A Stadia account and a compatible device (such as a Chromecast Ultra, a PC, or a smartphone) with a stable internet connection
-
-
The steps to download and install the game
-
The steps to download and install Red Dead Online vary depending on your platform. Here are some general guidelines:
-
-
Purchase the game from your preferred platform's store or website. You can buy it as a standalone version or as part of Red Dead Redemption 2. Download the game file to your device and follow the instructions to install it. The file size may vary depending on your platform and version, but it is usually around 100 GB or more. 3. Launch the game and sign in to your account. You may need to create a character and choose a name before you can access the online mode. 4. Enjoy playing Red Dead Online with your friends or solo.
-
How to play Red Dead Online?
-
The modes and activities in the game
-
Red Dead Online offers a variety of modes and activities for you to play and enjoy. Here are some of them:
-
-
Free Roam: This is the main mode where you can explore the world, interact with other players and NPCs, and take on various missions and challenges. You can also join or create a posse with up to seven members and cooperate or compete with other posses.
-
Showdown Series: This is a competitive mode where you can participate in different types of matches, such as team deathmatch, capture the flag, or battle royale. You can earn XP, money, and rewards by winning or completing objectives.
-
Races: This is a racing mode where you can compete with other players on horseback, wagon, or bike. You can choose from different types of races, such as point-to-point, lap, or open. You can also use weapons and items to gain an advantage or sabotage your opponents.
-
Specialist Roles: This is a role-playing mode where you can choose from different professions and careers, such as bounty hunter, trader, collector, moonshiner, naturalist, or prestigous bounty hunter. Each role has its own progression, missions, skills, and rewards.
-
Story Missions: This is a narrative mode where you can follow the story of your character and their allies and enemies. You can choose from different types of missions, such as honor, dishonor, or stranger. You can also play some missions with other players or solo.
-
-
The tips and tricks for beginners
-
If you are new to Red Dead Online, you may find it overwhelming or confusing at first. Here are some tips and tricks to help you get started:
-
How to download red dead online for free
-Red dead online download size and requirements
-Best red dead online mods and how to install them
-Red dead online download error and how to fix it
-Red dead online download speed and tips to improve it
-Red dead online download code and how to redeem it
-Red dead online download pc vs console comparison
-Red dead online download time and how to pre-load it
-Red dead online download link and where to get it
-Red dead online download crack and how to avoid it
-Red dead online download update and patch notes
-Red dead online download steam and how to activate it
-Red dead online download mac and how to run it
-Red dead online download ps4 and how to transfer it
-Red dead online download xbox one and how to share it
-Red dead online download apk and how to play it on mobile
-Red dead online download torrent and how to use it safely
-Red dead online download full version and how to unlock it
-Red dead online download demo and how to access it
-Red dead online download beta and how to join it
-Red dead online download price and how to get a discount
-Red dead online download review and ratings
-Red dead online download gameplay and features
-Red dead online download guide and tips
-Red dead online download cheats and hacks
-Red dead online download trainer and how to use it
-Red dead online download map and locations
-Red dead online download missions and quests
-Red dead online download characters and customization
-Red dead online download outfits and weapons
-Red dead online download horses and mounts
-Red dead online download animals and hunting
-Red dead online download fishing and cooking
-Red dead online download crafting and trading
-Red dead online download bounty hunting and lawmen
-Red dead online download gangs and factions
-Red dead online download pvp and modes
-Red dead online download coop and friends
-Red dead online download roleplay and servers
-Red dead online download events and challenges
-Red dead online download dlc and expansions
-Red dead online download crossplay and compatibility
-Red dead online download support and contact
-Red dead online download forums and communities
-Red dead online download news and updates
-Red dead online download wallpapers and art
-Red dead online download memes and jokes
-Red dead online download videos and streams
-Red dead online download podcasts and interviews
-
-
Complete the tutorial missions to learn the basics of the game and earn some money and items.
-
Upgrade your weapons, clothing, and equipment as soon as possible to improve your performance and survival.
-
Use the map and the radar to navigate the world and find points of interest, such as shops, saloons, camps, or events.
-
Use the catalog or the quick menu to access your inventory, abilities, emotes, or settings.
-
Use the fast travel system or the train to travel between locations faster and easier.
-
Use the camp or the hotel to rest, cook, craft, or change your outfit.
-
Use the stable or the post office to manage your horses, weapons, mail, or deliveries.
-
Use the social club or the pause menu to join or invite friends, form or join posses, or access other online features.
-
Be careful of other players who may attack you or grief you. You can use the parley or feud options to deal with them.
-
Have fun and experiment with different modes and activities. You never know what you might find or experience in Red Dead Online.
-
-
Conclusion
-
A summary of the main points and a call to action
-
In conclusion, Red Dead Online is an amazing game that lets you experience the wild west in 2023. You can download it from your preferred platform's store or website as a standalone version or as part of Red Dead Redemption 2. You can play it with your friends or solo in various modes and activities that suit your style and preference. You can also enjoy a stunning graphics, a rich story, and a dynamic world that changes according to your actions and choices. If you are looking for a game that offers adventure, action, and exploration in a vast open world, then you should download Red Dead Online today.
-
Frequently Asked Questions
-
Q: How much does Red Dead Online cost?
-
A: Red Dead Online costs $19.99 as a standalone version. However, you can also get it for free if you buy Red Dead Redemption 2. The game also offers optional microtransactions that let you buy in-game currency called gold bars that can be used to purchase items or services.
-
Q: Is Red Dead Online cross-platform?
-
A: No, Red Dead Online is not cross-platform
A: No, Red Dead Online is not cross-platform. You can only play with other players who have the same platform as you. However, you can transfer your character progress and items from one platform to another if you link your Rockstar Games Social Club account.
-
Q: Is Red Dead Online offline?
-
A: No, Red Dead Online is an online-only game. You need to have a stable internet connection and an active subscription to your platform's online service to play it. However, you can play the single-player campaign of Red Dead Redemption 2 offline if you want.
-
Q: How many players can play Red Dead Online?
-
A: Red Dead Online can support up to 32 players in a single session. You can also form or join a posse with up to seven players and cooperate or compete with other posses. Additionally, you can play some story missions or events with up to four players.
-
Q: How long is Red Dead Online?
-
A: Red Dead Online does not have a fixed length or end. You can play it as long as you want and as much as you want. The game is constantly updated with new content and features that add more variety and replay value. You can also create your own goals and challenges in the game.
-
Q: Is Red Dead Online worth it?
-
A: Red Dead Online is definitely worth it if you are a fan of the Red Dead series or the western genre. It is one of the best online games in terms of graphics, story, gameplay, and world. It offers a lot of fun and excitement for gamers of all kinds. It is also relatively affordable and accessible compared to other online games.
401be4b1e0
-
-
\ No newline at end of file
diff --git a/spaces/44ov41za8i/FreeVC/speaker_encoder/data_objects/__init__.py b/spaces/44ov41za8i/FreeVC/speaker_encoder/data_objects/__init__.py
deleted file mode 100644
index 030317a1d9a328d452bf29bc7a802e29629b1a42..0000000000000000000000000000000000000000
--- a/spaces/44ov41za8i/FreeVC/speaker_encoder/data_objects/__init__.py
+++ /dev/null
@@ -1,2 +0,0 @@
-from speaker_encoder.data_objects.speaker_verification_dataset import SpeakerVerificationDataset
-from speaker_encoder.data_objects.speaker_verification_dataset import SpeakerVerificationDataLoader
diff --git a/spaces/AIGC-Audio/Make_An_Audio_inpaint/ldm/modules/encoders/open_clap/htsat.py b/spaces/AIGC-Audio/Make_An_Audio_inpaint/ldm/modules/encoders/open_clap/htsat.py
deleted file mode 100644
index db96116286d307a73943886f947450215e061ba2..0000000000000000000000000000000000000000
--- a/spaces/AIGC-Audio/Make_An_Audio_inpaint/ldm/modules/encoders/open_clap/htsat.py
+++ /dev/null
@@ -1,1022 +0,0 @@
-# Ke Chen
-# knutchen@ucsd.edu
-# HTS-AT: A HIERARCHICAL TOKEN-SEMANTIC AUDIO TRANSFORMER FOR SOUND CLASSIFICATION AND DETECTION
-# Some layers designed on the model
-# below codes are based and referred from https://github.com/microsoft/Swin-Transformer
-# Swin Transformer for Computer Vision: https://arxiv.org/pdf/2103.14030.pdf
-
-import torch
-import torch.nn as nn
-import torch.nn.functional as F
-from itertools import repeat
-import collections.abc
-import math
-import warnings
-
-from torch.nn.init import _calculate_fan_in_and_fan_out
-import torch.utils.checkpoint as checkpoint
-
-import random
-
-from torchlibrosa.stft import Spectrogram, LogmelFilterBank
-from torchlibrosa.augmentation import SpecAugmentation
-
-from itertools import repeat
-from .utils import do_mixup, interpolate
-
-from .feature_fusion import iAFF, AFF, DAF
-
-# from PyTorch internals
-def _ntuple(n):
- def parse(x):
- if isinstance(x, collections.abc.Iterable):
- return x
- return tuple(repeat(x, n))
- return parse
-
-to_1tuple = _ntuple(1)
-to_2tuple = _ntuple(2)
-to_3tuple = _ntuple(3)
-to_4tuple = _ntuple(4)
-to_ntuple = _ntuple
-
-def drop_path(x, drop_prob: float = 0., training: bool = False):
- """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
- This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
- the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
- See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
- changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
- 'survival rate' as the argument.
- """
- if drop_prob == 0. or not training:
- return x
- keep_prob = 1 - drop_prob
- shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
- random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
- random_tensor.floor_() # binarize
- output = x.div(keep_prob) * random_tensor
- return output
-
-
-class DropPath(nn.Module):
- """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
- """
- def __init__(self, drop_prob=None):
- super(DropPath, self).__init__()
- self.drop_prob = drop_prob
-
- def forward(self, x):
- return drop_path(x, self.drop_prob, self.training)
-
-class PatchEmbed(nn.Module):
- """ 2D Image to Patch Embedding
- """
- def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True, patch_stride = 16,
- enable_fusion=False, fusion_type='None'):
- super().__init__()
- img_size = to_2tuple(img_size)
- patch_size = to_2tuple(patch_size)
- patch_stride = to_2tuple(patch_stride)
- self.img_size = img_size
- self.patch_size = patch_size
- self.patch_stride = patch_stride
- self.grid_size = (img_size[0] // patch_stride[0], img_size[1] // patch_stride[1])
- self.num_patches = self.grid_size[0] * self.grid_size[1]
- self.flatten = flatten
- self.in_chans = in_chans
- self.embed_dim = embed_dim
-
- self.enable_fusion = enable_fusion
- self.fusion_type = fusion_type
-
- padding = ((patch_size[0] - patch_stride[0]) // 2, (patch_size[1] - patch_stride[1]) // 2)
-
- if (self.enable_fusion) and (self.fusion_type == 'channel_map'):
- self.proj = nn.Conv2d(in_chans*4, embed_dim, kernel_size=patch_size, stride=patch_stride, padding=padding)
- else:
- self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_stride, padding=padding)
- self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
-
- if (self.enable_fusion) and (self.fusion_type in ['daf_2d','aff_2d','iaff_2d']):
- self.mel_conv2d = nn.Conv2d(in_chans, embed_dim, kernel_size=(patch_size[0], patch_size[1]*3), stride=(patch_stride[0], patch_stride[1] * 3), padding=padding)
- if self.fusion_type == 'daf_2d':
- self.fusion_model = DAF()
- elif self.fusion_type == 'aff_2d':
- self.fusion_model = AFF(channels=embed_dim, type='2D')
- elif self.fusion_type == 'iaff_2d':
- self.fusion_model = iAFF(channels=embed_dim, type='2D')
- def forward(self, x, longer_idx = None):
- if (self.enable_fusion) and (self.fusion_type in ['daf_2d','aff_2d','iaff_2d']):
- global_x = x[:,0:1,:,:]
-
-
- # global processing
- B, C, H, W = global_x.shape
- assert H == self.img_size[0] and W == self.img_size[1], \
- f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
- global_x = self.proj(global_x)
- TW = global_x.size(-1)
- if len(longer_idx) > 0:
- # local processing
- local_x = x[longer_idx,1:,:,:].contiguous()
- B, C, H, W = local_x.shape
- local_x = local_x.view(B*C,1,H,W)
- local_x = self.mel_conv2d(local_x)
- local_x = local_x.view(B,C,local_x.size(1),local_x.size(2),local_x.size(3))
- local_x = local_x.permute((0,2,3,1,4)).contiguous().flatten(3)
- TB,TC,TH,_ = local_x.size()
- if local_x.size(-1) < TW:
- local_x = torch.cat([local_x, torch.zeros((TB,TC,TH,TW-local_x.size(-1)), device=global_x.device)], dim=-1)
- else:
- local_x = local_x[:,:,:,:TW]
-
- global_x[longer_idx] = self.fusion_model(global_x[longer_idx],local_x)
- x = global_x
- else:
- B, C, H, W = x.shape
- assert H == self.img_size[0] and W == self.img_size[1], \
- f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
- x = self.proj(x)
-
- if self.flatten:
- x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
- x = self.norm(x)
- return x
-
-class Mlp(nn.Module):
- """ MLP as used in Vision Transformer, MLP-Mixer and related networks
- """
- def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
- super().__init__()
- out_features = out_features or in_features
- hidden_features = hidden_features or in_features
- self.fc1 = nn.Linear(in_features, hidden_features)
- self.act = act_layer()
- self.fc2 = nn.Linear(hidden_features, out_features)
- self.drop = nn.Dropout(drop)
-
- def forward(self, x):
- x = self.fc1(x)
- x = self.act(x)
- x = self.drop(x)
- x = self.fc2(x)
- x = self.drop(x)
- return x
-
-def _no_grad_trunc_normal_(tensor, mean, std, a, b):
- # Cut & paste from PyTorch official master until it's in a few official releases - RW
- # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
- def norm_cdf(x):
- # Computes standard normal cumulative distribution function
- return (1. + math.erf(x / math.sqrt(2.))) / 2.
-
- if (mean < a - 2 * std) or (mean > b + 2 * std):
- warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
- "The distribution of values may be incorrect.",
- stacklevel=2)
-
- with torch.no_grad():
- # Values are generated by using a truncated uniform distribution and
- # then using the inverse CDF for the normal distribution.
- # Get upper and lower cdf values
- l = norm_cdf((a - mean) / std)
- u = norm_cdf((b - mean) / std)
-
- # Uniformly fill tensor with values from [l, u], then translate to
- # [2l-1, 2u-1].
- tensor.uniform_(2 * l - 1, 2 * u - 1)
-
- # Use inverse cdf transform for normal distribution to get truncated
- # standard normal
- tensor.erfinv_()
-
- # Transform to proper mean, std
- tensor.mul_(std * math.sqrt(2.))
- tensor.add_(mean)
-
- # Clamp to ensure it's in the proper range
- tensor.clamp_(min=a, max=b)
- return tensor
-
-
-def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
- # type: (Tensor, float, float, float, float) -> Tensor
- r"""Fills the input Tensor with values drawn from a truncated
- normal distribution. The values are effectively drawn from the
- normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
- with values outside :math:`[a, b]` redrawn until they are within
- the bounds. The method used for generating the random values works
- best when :math:`a \leq \text{mean} \leq b`.
- Args:
- tensor: an n-dimensional `torch.Tensor`
- mean: the mean of the normal distribution
- std: the standard deviation of the normal distribution
- a: the minimum cutoff value
- b: the maximum cutoff value
- Examples:
- >>> w = torch.empty(3, 5)
- >>> nn.init.trunc_normal_(w)
- """
- return _no_grad_trunc_normal_(tensor, mean, std, a, b)
-
-
-def variance_scaling_(tensor, scale=1.0, mode='fan_in', distribution='normal'):
- fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)
- if mode == 'fan_in':
- denom = fan_in
- elif mode == 'fan_out':
- denom = fan_out
- elif mode == 'fan_avg':
- denom = (fan_in + fan_out) / 2
-
- variance = scale / denom
-
- if distribution == "truncated_normal":
- # constant is stddev of standard normal truncated to (-2, 2)
- trunc_normal_(tensor, std=math.sqrt(variance) / .87962566103423978)
- elif distribution == "normal":
- tensor.normal_(std=math.sqrt(variance))
- elif distribution == "uniform":
- bound = math.sqrt(3 * variance)
- tensor.uniform_(-bound, bound)
- else:
- raise ValueError(f"invalid distribution {distribution}")
-
-
-def lecun_normal_(tensor):
- variance_scaling_(tensor, mode='fan_in', distribution='truncated_normal')
-
-def window_partition(x, window_size):
- """
- Args:
- x: (B, H, W, C)
- window_size (int): window size
- Returns:
- windows: (num_windows*B, window_size, window_size, C)
- """
- B, H, W, C = x.shape
- x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
- windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
- return windows
-
-
-def window_reverse(windows, window_size, H, W):
- """
- Args:
- windows: (num_windows*B, window_size, window_size, C)
- window_size (int): Window size
- H (int): Height of image
- W (int): Width of image
- Returns:
- x: (B, H, W, C)
- """
- B = int(windows.shape[0] / (H * W / window_size / window_size))
- x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
- x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
- return x
-
-
-class WindowAttention(nn.Module):
- r""" Window based multi-head self attention (W-MSA) module with relative position bias.
- It supports both of shifted and non-shifted window.
- Args:
- dim (int): Number of input channels.
- window_size (tuple[int]): The height and width of the window.
- num_heads (int): Number of attention heads.
- qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
- qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
- attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
- proj_drop (float, optional): Dropout ratio of output. Default: 0.0
- """
-
- def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
-
- super().__init__()
- self.dim = dim
- self.window_size = window_size # Wh, Ww
- self.num_heads = num_heads
- head_dim = dim // num_heads
- self.scale = qk_scale or head_dim ** -0.5
-
- # define a parameter table of relative position bias
- self.relative_position_bias_table = nn.Parameter(
- torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
-
- # get pair-wise relative position index for each token inside the window
- coords_h = torch.arange(self.window_size[0])
- coords_w = torch.arange(self.window_size[1])
- coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
- coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
- relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
- relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
- relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
- relative_coords[:, :, 1] += self.window_size[1] - 1
- relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
- relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
- self.register_buffer("relative_position_index", relative_position_index)
-
- self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
- self.attn_drop = nn.Dropout(attn_drop)
- self.proj = nn.Linear(dim, dim)
- self.proj_drop = nn.Dropout(proj_drop)
-
- trunc_normal_(self.relative_position_bias_table, std=.02)
- self.softmax = nn.Softmax(dim=-1)
-
- def forward(self, x, mask=None):
- """
- Args:
- x: input features with shape of (num_windows*B, N, C)
- mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
- """
- B_, N, C = x.shape
- qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
- q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
-
- q = q * self.scale
- attn = (q @ k.transpose(-2, -1))
-
- relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
- self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
- relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
- attn = attn + relative_position_bias.unsqueeze(0)
-
- if mask is not None:
- nW = mask.shape[0]
- attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
- attn = attn.view(-1, self.num_heads, N, N)
- attn = self.softmax(attn)
- else:
- attn = self.softmax(attn)
-
- attn = self.attn_drop(attn)
-
- x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
- x = self.proj(x)
- x = self.proj_drop(x)
- return x, attn
-
- def extra_repr(self):
- return f'dim={self.dim}, window_size={self.window_size}, num_heads={self.num_heads}'
-
-
-# We use the model based on Swintransformer Block, therefore we can use the swin-transformer pretrained model
-class SwinTransformerBlock(nn.Module):
- r""" Swin Transformer Block.
- Args:
- dim (int): Number of input channels.
- input_resolution (tuple[int]): Input resulotion.
- num_heads (int): Number of attention heads.
- window_size (int): Window size.
- shift_size (int): Shift size for SW-MSA.
- mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
- qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
- qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
- drop (float, optional): Dropout rate. Default: 0.0
- attn_drop (float, optional): Attention dropout rate. Default: 0.0
- drop_path (float, optional): Stochastic depth rate. Default: 0.0
- act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
- norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
- """
-
- def __init__(self, dim, input_resolution, num_heads, window_size=7, shift_size=0,
- mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
- act_layer=nn.GELU, norm_layer=nn.LayerNorm, norm_before_mlp='ln'):
- super().__init__()
- self.dim = dim
- self.input_resolution = input_resolution
- self.num_heads = num_heads
- self.window_size = window_size
- self.shift_size = shift_size
- self.mlp_ratio = mlp_ratio
- self.norm_before_mlp = norm_before_mlp
- if min(self.input_resolution) <= self.window_size:
- # if window size is larger than input resolution, we don't partition windows
- self.shift_size = 0
- self.window_size = min(self.input_resolution)
- assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
-
- self.norm1 = norm_layer(dim)
- self.attn = WindowAttention(
- dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
- qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
-
- self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
- if self.norm_before_mlp == 'ln':
- self.norm2 = nn.LayerNorm(dim)
- elif self.norm_before_mlp == 'bn':
- self.norm2 = lambda x: nn.BatchNorm1d(dim)(x.transpose(1, 2)).transpose(1, 2)
- else:
- raise NotImplementedError
- mlp_hidden_dim = int(dim * mlp_ratio)
- self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
-
- if self.shift_size > 0:
- # calculate attention mask for SW-MSA
- H, W = self.input_resolution
- img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1
- h_slices = (slice(0, -self.window_size),
- slice(-self.window_size, -self.shift_size),
- slice(-self.shift_size, None))
- w_slices = (slice(0, -self.window_size),
- slice(-self.window_size, -self.shift_size),
- slice(-self.shift_size, None))
- cnt = 0
- for h in h_slices:
- for w in w_slices:
- img_mask[:, h, w, :] = cnt
- cnt += 1
-
- mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
- mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
- attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
- attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
- else:
- attn_mask = None
-
- self.register_buffer("attn_mask", attn_mask)
-
- def forward(self, x):
- # pdb.set_trace()
- H, W = self.input_resolution
- # print("H: ", H)
- # print("W: ", W)
- # pdb.set_trace()
- B, L, C = x.shape
- # assert L == H * W, "input feature has wrong size"
-
- shortcut = x
- x = self.norm1(x)
- x = x.view(B, H, W, C)
-
- # cyclic shift
- if self.shift_size > 0:
- shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
- else:
- shifted_x = x
-
- # partition windows
- x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
- x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
-
- # W-MSA/SW-MSA
- attn_windows, attn = self.attn(x_windows, mask=self.attn_mask) # nW*B, window_size*window_size, C
-
- # merge windows
- attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
- shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C
-
- # reverse cyclic shift
- if self.shift_size > 0:
- x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
- else:
- x = shifted_x
- x = x.view(B, H * W, C)
-
- # FFN
- x = shortcut + self.drop_path(x)
- x = x + self.drop_path(self.mlp(self.norm2(x)))
-
- return x, attn
-
- def extra_repr(self):
- return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \
- f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}"
-
-
-
-class PatchMerging(nn.Module):
- r""" Patch Merging Layer.
- Args:
- input_resolution (tuple[int]): Resolution of input feature.
- dim (int): Number of input channels.
- norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
- """
-
- def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm):
- super().__init__()
- self.input_resolution = input_resolution
- self.dim = dim
- self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
- self.norm = norm_layer(4 * dim)
-
- def forward(self, x):
- """
- x: B, H*W, C
- """
- H, W = self.input_resolution
- B, L, C = x.shape
- assert L == H * W, "input feature has wrong size"
- assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even."
-
- x = x.view(B, H, W, C)
-
- x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
- x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
- x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
- x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
- x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
- x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
-
- x = self.norm(x)
- x = self.reduction(x)
-
- return x
-
- def extra_repr(self):
- return f"input_resolution={self.input_resolution}, dim={self.dim}"
-
-
-class BasicLayer(nn.Module):
- """ A basic Swin Transformer layer for one stage.
- Args:
- dim (int): Number of input channels.
- input_resolution (tuple[int]): Input resolution.
- depth (int): Number of blocks.
- num_heads (int): Number of attention heads.
- window_size (int): Local window size.
- mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
- qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
- qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
- drop (float, optional): Dropout rate. Default: 0.0
- attn_drop (float, optional): Attention dropout rate. Default: 0.0
- drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
- norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
- downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
- use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
- """
-
- def __init__(self, dim, input_resolution, depth, num_heads, window_size,
- mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0.,
- drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False,
- norm_before_mlp='ln'):
-
- super().__init__()
- self.dim = dim
- self.input_resolution = input_resolution
- self.depth = depth
- self.use_checkpoint = use_checkpoint
-
- # build blocks
- self.blocks = nn.ModuleList([
- SwinTransformerBlock(dim=dim, input_resolution=input_resolution,
- num_heads=num_heads, window_size=window_size,
- shift_size=0 if (i % 2 == 0) else window_size // 2,
- mlp_ratio=mlp_ratio,
- qkv_bias=qkv_bias, qk_scale=qk_scale,
- drop=drop, attn_drop=attn_drop,
- drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
- norm_layer=norm_layer, norm_before_mlp=norm_before_mlp)
- for i in range(depth)])
-
- # patch merging layer
- if downsample is not None:
- self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer)
- else:
- self.downsample = None
-
- def forward(self, x):
- attns = []
- for blk in self.blocks:
- if self.use_checkpoint:
- x = checkpoint.checkpoint(blk, x)
- else:
- x, attn = blk(x)
- if not self.training:
- attns.append(attn.unsqueeze(0))
- if self.downsample is not None:
- x = self.downsample(x)
- if not self.training:
- attn = torch.cat(attns, dim = 0)
- attn = torch.mean(attn, dim = 0)
- return x, attn
-
- def extra_repr(self):
- return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}"
-
-
-# The Core of HTSAT
-class HTSAT_Swin_Transformer(nn.Module):
- r"""HTSAT based on the Swin Transformer
- Args:
- spec_size (int | tuple(int)): Input Spectrogram size. Default 256
- patch_size (int | tuple(int)): Patch size. Default: 4
- path_stride (iot | tuple(int)): Patch Stride for Frequency and Time Axis. Default: 4
- in_chans (int): Number of input image channels. Default: 1 (mono)
- num_classes (int): Number of classes for classification head. Default: 527
- embed_dim (int): Patch embedding dimension. Default: 96
- depths (tuple(int)): Depth of each HTSAT-Swin Transformer layer.
- num_heads (tuple(int)): Number of attention heads in different layers.
- window_size (int): Window size. Default: 8
- mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4
- qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
- qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. Default: None
- drop_rate (float): Dropout rate. Default: 0
- attn_drop_rate (float): Attention dropout rate. Default: 0
- drop_path_rate (float): Stochastic depth rate. Default: 0.1
- norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
- ape (bool): If True, add absolute position embedding to the patch embedding. Default: False
- patch_norm (bool): If True, add normalization after patch embedding. Default: True
- use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False
- config (module): The configuration Module from config.py
- """
-
- def __init__(self, spec_size=256, patch_size=4, patch_stride=(4,4),
- in_chans=1, num_classes=527,
- embed_dim=96, depths=[2, 2, 6, 2], num_heads=[4, 8, 16, 32],
- window_size=8, mlp_ratio=4., qkv_bias=True, qk_scale=None,
- drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1,
- norm_layer=nn.LayerNorm,
- ape=False, patch_norm=True,
- use_checkpoint=False, norm_before_mlp='ln', config = None,
- enable_fusion = False, fusion_type = 'None', **kwargs):
- super(HTSAT_Swin_Transformer, self).__init__()
-
- self.config = config
- self.spec_size = spec_size
- self.patch_stride = patch_stride
- self.patch_size = patch_size
- self.window_size = window_size
- self.embed_dim = embed_dim
- self.depths = depths
- self.ape = ape
- self.in_chans = in_chans
- self.num_classes = num_classes
- self.num_heads = num_heads
- self.num_layers = len(self.depths)
- self.num_features = int(self.embed_dim * 2 ** (self.num_layers - 1))
-
- self.drop_rate = drop_rate
- self.attn_drop_rate = attn_drop_rate
- self.drop_path_rate = drop_path_rate
-
- self.qkv_bias = qkv_bias
- self.qk_scale = None
-
- self.patch_norm = patch_norm
- self.norm_layer = norm_layer if self.patch_norm else None
- self.norm_before_mlp = norm_before_mlp
- self.mlp_ratio = mlp_ratio
-
- self.use_checkpoint = use_checkpoint
-
- self.enable_fusion = enable_fusion
- self.fusion_type = fusion_type
-
- # process mel-spec ; used only once
- self.freq_ratio = self.spec_size // self.config.mel_bins
- window = 'hann'
- center = True
- pad_mode = 'reflect'
- ref = 1.0
- amin = 1e-10
- top_db = None
- self.interpolate_ratio = 32 # Downsampled ratio
- # Spectrogram extractor
- self.spectrogram_extractor = Spectrogram(n_fft=config.window_size, hop_length=config.hop_size,
- win_length=config.window_size, window=window, center=center, pad_mode=pad_mode,
- freeze_parameters=True)
- # Logmel feature extractor
- self.logmel_extractor = LogmelFilterBank(sr=config.sample_rate, n_fft=config.window_size,
- n_mels=config.mel_bins, fmin=config.fmin, fmax=config.fmax, ref=ref, amin=amin, top_db=top_db,
- freeze_parameters=True)
- # Spec augmenter
- self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2,
- freq_drop_width=8, freq_stripes_num=2) # 2 2
- self.bn0 = nn.BatchNorm2d(self.config.mel_bins)
-
-
- # split spctrogram into non-overlapping patches
- self.patch_embed = PatchEmbed(
- img_size=self.spec_size, patch_size=self.patch_size, in_chans=self.in_chans,
- embed_dim=self.embed_dim, norm_layer=self.norm_layer, patch_stride = patch_stride,
- enable_fusion=self.enable_fusion, fusion_type=self.fusion_type
- )
-
- num_patches = self.patch_embed.num_patches
- patches_resolution = self.patch_embed.grid_size
- self.patches_resolution = patches_resolution
-
- # absolute position embedding
- if self.ape:
- self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, self.embed_dim))
- trunc_normal_(self.absolute_pos_embed, std=.02)
-
- self.pos_drop = nn.Dropout(p=self.drop_rate)
-
- # stochastic depth
- dpr = [x.item() for x in torch.linspace(0, self.drop_path_rate, sum(self.depths))] # stochastic depth decay rule
-
- # build layers
- self.layers = nn.ModuleList()
- for i_layer in range(self.num_layers):
- layer = BasicLayer(dim=int(self.embed_dim * 2 ** i_layer),
- input_resolution=(patches_resolution[0] // (2 ** i_layer),
- patches_resolution[1] // (2 ** i_layer)),
- depth=self.depths[i_layer],
- num_heads=self.num_heads[i_layer],
- window_size=self.window_size,
- mlp_ratio=self.mlp_ratio,
- qkv_bias=self.qkv_bias, qk_scale=self.qk_scale,
- drop=self.drop_rate, attn_drop=self.attn_drop_rate,
- drop_path=dpr[sum(self.depths[:i_layer]):sum(self.depths[:i_layer + 1])],
- norm_layer=self.norm_layer,
- downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
- use_checkpoint=use_checkpoint,
- norm_before_mlp=self.norm_before_mlp)
- self.layers.append(layer)
-
- self.norm = self.norm_layer(self.num_features)
- self.avgpool = nn.AdaptiveAvgPool1d(1)
- self.maxpool = nn.AdaptiveMaxPool1d(1)
-
- SF = self.spec_size // (2 ** (len(self.depths) - 1)) // self.patch_stride[0] // self.freq_ratio
- self.tscam_conv = nn.Conv2d(
- in_channels = self.num_features,
- out_channels = self.num_classes,
- kernel_size = (SF,3),
- padding = (0,1)
- )
- self.head = nn.Linear(num_classes, num_classes)
-
- if (self.enable_fusion) and (self.fusion_type in ['daf_1d','aff_1d','iaff_1d']):
- self.mel_conv1d = nn.Sequential(
- nn.Conv1d(64, 64, kernel_size=5, stride=3, padding=2),
- nn.BatchNorm1d(64)
- )
- if self.fusion_type == 'daf_1d':
- self.fusion_model = DAF()
- elif self.fusion_type == 'aff_1d':
- self.fusion_model = AFF(channels=64, type='1D')
- elif self.fusion_type == 'iaff_1d':
- self.fusion_model = iAFF(channels=64, type='1D')
-
- self.apply(self._init_weights)
-
- def _init_weights(self, m):
- if isinstance(m, nn.Linear):
- trunc_normal_(m.weight, std=.02)
- if isinstance(m, nn.Linear) and m.bias is not None:
- nn.init.constant_(m.bias, 0)
- elif isinstance(m, nn.LayerNorm):
- nn.init.constant_(m.bias, 0)
- nn.init.constant_(m.weight, 1.0)
-
- @torch.jit.ignore
- def no_weight_decay(self):
- return {'absolute_pos_embed'}
-
- @torch.jit.ignore
- def no_weight_decay_keywords(self):
- return {'relative_position_bias_table'}
-
-
- def forward_features(self, x, longer_idx = None):
- # A deprecated optimization for using a hierarchical output from different blocks
-
- frames_num = x.shape[2]
- x = self.patch_embed(x, longer_idx = longer_idx)
- if self.ape:
- x = x + self.absolute_pos_embed
- x = self.pos_drop(x)
- for i, layer in enumerate(self.layers):
- x, attn = layer(x)
- # for x
- x = self.norm(x)
- B, N, C = x.shape
- SF = frames_num // (2 ** (len(self.depths) - 1)) // self.patch_stride[0]
- ST = frames_num // (2 ** (len(self.depths) - 1)) // self.patch_stride[1]
- x = x.permute(0,2,1).contiguous().reshape(B, C, SF, ST)
- B, C, F, T = x.shape
- # group 2D CNN
- c_freq_bin = F // self.freq_ratio
- x = x.reshape(B, C, F // c_freq_bin, c_freq_bin, T)
- x = x.permute(0,1,3,2,4).contiguous().reshape(B, C, c_freq_bin, -1)
- # get latent_output
- fine_grained_latent_output = torch.mean(x, dim = 2)
- fine_grained_latent_output = interpolate(fine_grained_latent_output.permute(0,2,1).contiguous(), 8 * self.patch_stride[1])
-
- latent_output = self.avgpool(torch.flatten(x,2))
- latent_output = torch.flatten(latent_output, 1)
-
- # display the attention map, if needed
-
- x = self.tscam_conv(x)
- x = torch.flatten(x, 2) # B, C, T
-
- fpx = interpolate(torch.sigmoid(x).permute(0,2,1).contiguous(), 8 * self.patch_stride[1])
-
- x = self.avgpool(x)
- x = torch.flatten(x, 1)
-
- output_dict = {
- 'framewise_output': fpx, # already sigmoided
- 'clipwise_output': torch.sigmoid(x),
- 'fine_grained_embedding': fine_grained_latent_output,
- 'embedding': latent_output
- }
-
- return output_dict
-
- def crop_wav(self, x, crop_size, spe_pos = None):
- time_steps = x.shape[2]
- tx = torch.zeros(x.shape[0], x.shape[1], crop_size, x.shape[3]).to(x.device)
- for i in range(len(x)):
- if spe_pos is None:
- crop_pos = random.randint(0, time_steps - crop_size - 1)
- else:
- crop_pos = spe_pos
- tx[i][0] = x[i, 0, crop_pos:crop_pos + crop_size,:]
- return tx
-
- # Reshape the wavform to a img size, if you want to use the pretrained swin transformer model
- def reshape_wav2img(self, x):
- B, C, T, F = x.shape
- target_T = int(self.spec_size * self.freq_ratio)
- target_F = self.spec_size // self.freq_ratio
- assert T <= target_T and F <= target_F, "the wav size should less than or equal to the swin input size"
- # to avoid bicubic zero error
- if T < target_T:
- x = nn.functional.interpolate(x, (target_T, x.shape[3]), mode="bicubic", align_corners=True)
- if F < target_F:
- x = nn.functional.interpolate(x, (x.shape[2], target_F), mode="bicubic", align_corners=True)
- x = x.permute(0,1,3,2).contiguous()
- x = x.reshape(x.shape[0], x.shape[1], x.shape[2], self.freq_ratio, x.shape[3] // self.freq_ratio)
- # print(x.shape)
- x = x.permute(0,1,3,2,4).contiguous()
- x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3], x.shape[4])
- return x
-
- # Repeat the wavform to a img size, if you want to use the pretrained swin transformer model
- def repeat_wat2img(self, x, cur_pos):
- B, C, T, F = x.shape
- target_T = int(self.spec_size * self.freq_ratio)
- target_F = self.spec_size // self.freq_ratio
- assert T <= target_T and F <= target_F, "the wav size should less than or equal to the swin input size"
- # to avoid bicubic zero error
- if T < target_T:
- x = nn.functional.interpolate(x, (target_T, x.shape[3]), mode="bicubic", align_corners=True)
- if F < target_F:
- x = nn.functional.interpolate(x, (x.shape[2], target_F), mode="bicubic", align_corners=True)
- x = x.permute(0,1,3,2).contiguous() # B C F T
- x = x[:,:,:,cur_pos:cur_pos + self.spec_size]
- x = x.repeat(repeats = (1,1,4,1))
- return x
-
- def forward(self, x: torch.Tensor, mixup_lambda = None, infer_mode = False, device=None):# out_feat_keys: List[str] = None):
-
- if self.enable_fusion and x["longer"].sum() == 0:
- # if no audio is longer than 10s, then randomly select one audio to be longer
- x["longer"][torch.randint(0, x["longer"].shape[0], (1,))] = True
-
- if not self.enable_fusion:
- x = x["waveform"].to(device=device, non_blocking=True)
- x = self.spectrogram_extractor(x) # (batch_size, 1, time_steps, freq_bins)
- x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)
- x = x.transpose(1, 3)
- x = self.bn0(x)
- x = x.transpose(1, 3)
- if self.training:
- x = self.spec_augmenter(x)
-
- if self.training and mixup_lambda is not None:
- x = do_mixup(x, mixup_lambda)
-
- x = self.reshape_wav2img(x)
- output_dict = self.forward_features(x)
- else:
- longer_list = x["longer"].to(device=device, non_blocking=True)
- x = x["mel_fusion"].to(device=device, non_blocking=True)
- x = x.transpose(1, 3)
- x = self.bn0(x)
- x = x.transpose(1, 3)
- longer_list_idx = torch.where(longer_list)[0]
- if self.fusion_type in ['daf_1d','aff_1d','iaff_1d']:
- new_x = x[:,0:1,:,:].clone().contiguous()
- if len(longer_list_idx) > 0:
- # local processing
- fusion_x_local = x[longer_list_idx,1:,:,:].clone().contiguous()
- FB,FC,FT,FF = fusion_x_local.size()
- fusion_x_local = fusion_x_local.view(FB * FC, FT, FF)
- fusion_x_local = torch.permute(fusion_x_local, (0,2,1)).contiguous()
- fusion_x_local = self.mel_conv1d(fusion_x_local)
- fusion_x_local = fusion_x_local.view(FB,FC,FF,fusion_x_local.size(-1))
- fusion_x_local = torch.permute(fusion_x_local, (0,2,1,3)).contiguous().flatten(2)
- if fusion_x_local.size(-1) < FT:
- fusion_x_local = torch.cat([fusion_x_local, torch.zeros((FB,FF,FT- fusion_x_local.size(-1)), device=device)], dim=-1)
- else:
- fusion_x_local = fusion_x_local[:,:,:FT]
- # 1D fusion
- new_x = new_x.squeeze(1).permute((0,2,1)).contiguous()
- new_x[longer_list_idx] = self.fusion_model(new_x[longer_list_idx], fusion_x_local)
- x = new_x.permute((0,2,1)).contiguous()[:,None,:,:]
- else:
- x = new_x
-
- elif self.fusion_type in ['daf_2d','aff_2d','iaff_2d','channel_map']:
- x = x # no change
-
- if self.training:
- x = self.spec_augmenter(x)
- if self.training and mixup_lambda is not None:
- x = do_mixup(x, mixup_lambda)
-
- x = self.reshape_wav2img(x)
- output_dict = self.forward_features(x, longer_idx = longer_list_idx)
-
- # if infer_mode:
- # # in infer mode. we need to handle different length audio input
- # frame_num = x.shape[2]
- # target_T = int(self.spec_size * self.freq_ratio)
- # repeat_ratio = math.floor(target_T / frame_num)
- # x = x.repeat(repeats=(1,1,repeat_ratio,1))
- # x = self.reshape_wav2img(x)
- # output_dict = self.forward_features(x)
- # else:
- # if x.shape[2] > self.freq_ratio * self.spec_size:
- # if self.training:
- # x = self.crop_wav(x, crop_size=self.freq_ratio * self.spec_size)
- # x = self.reshape_wav2img(x)
- # output_dict = self.forward_features(x)
- # else:
- # # Change: Hard code here
- # overlap_size = (x.shape[2] - 1) // 4
- # output_dicts = []
- # crop_size = (x.shape[2] - 1) // 2
- # for cur_pos in range(0, x.shape[2] - crop_size - 1, overlap_size):
- # tx = self.crop_wav(x, crop_size = crop_size, spe_pos = cur_pos)
- # tx = self.reshape_wav2img(tx)
- # output_dicts.append(self.forward_features(tx))
- # clipwise_output = torch.zeros_like(output_dicts[0]["clipwise_output"]).float().to(x.device)
- # framewise_output = torch.zeros_like(output_dicts[0]["framewise_output"]).float().to(x.device)
- # for d in output_dicts:
- # clipwise_output += d["clipwise_output"]
- # framewise_output += d["framewise_output"]
- # clipwise_output = clipwise_output / len(output_dicts)
- # framewise_output = framewise_output / len(output_dicts)
- # output_dict = {
- # 'framewise_output': framewise_output,
- # 'clipwise_output': clipwise_output
- # }
- # else: # this part is typically used, and most easy one
- # x = self.reshape_wav2img(x)
- # output_dict = self.forward_features(x)
- # x = self.head(x)
-
- # We process the data in the dataloader part, in that here we only consider the input_T < fixed_T
-
-
-
- return output_dict
-
-def create_htsat_model(audio_cfg, enable_fusion=False, fusion_type='None'):
- try:
-
- assert audio_cfg.model_name in ["tiny", "base", "large"], "model name for HTS-AT is wrong!"
- if audio_cfg.model_name == "tiny":
- model = HTSAT_Swin_Transformer(
- spec_size=256,
- patch_size=4,
- patch_stride=(4,4),
- num_classes=audio_cfg.class_num,
- embed_dim=96,
- depths=[2,2,6,2],
- num_heads=[4,8,16,32],
- window_size=8,
- config = audio_cfg,
- enable_fusion = enable_fusion,
- fusion_type = fusion_type
- )
- elif audio_cfg.model_name == "base":
- model = HTSAT_Swin_Transformer(
- spec_size=256,
- patch_size=4,
- patch_stride=(4,4),
- num_classes=audio_cfg.class_num,
- embed_dim=128,
- depths=[2,2,12,2],
- num_heads=[4,8,16,32],
- window_size=8,
- config = audio_cfg,
- enable_fusion = enable_fusion,
- fusion_type = fusion_type
- )
- elif audio_cfg.model_name == "large":
- model = HTSAT_Swin_Transformer(
- spec_size=256,
- patch_size=4,
- patch_stride=(4,4),
- num_classes=audio_cfg.class_num,
- embed_dim=256,
- depths=[2,2,12,2],
- num_heads=[4,8,16,32],
- window_size=8,
- config = audio_cfg,
- enable_fusion = enable_fusion,
- fusion_type = fusion_type
- )
-
- return model
- except:
- raise RuntimeError(f'Import Model for {audio_cfg.model_name} not found, or the audio cfg parameters are not enough.')
-
\ No newline at end of file
diff --git a/spaces/AbeShinzo0708/AI_Kishida_Fumio_speaker/hooks/hook-espnet.py b/spaces/AbeShinzo0708/AI_Kishida_Fumio_speaker/hooks/hook-espnet.py
deleted file mode 100644
index 6031fa880d0d365426885bcab24960eb775c2c0b..0000000000000000000000000000000000000000
--- a/spaces/AbeShinzo0708/AI_Kishida_Fumio_speaker/hooks/hook-espnet.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from PyInstaller.utils.hooks import copy_metadata
-
-datas = copy_metadata('espnet')
diff --git a/spaces/AchyuthGamer/OpenGPT-Chat-UI/src/lib/server/websearch/parseWeb.ts b/spaces/AchyuthGamer/OpenGPT-Chat-UI/src/lib/server/websearch/parseWeb.ts
deleted file mode 100644
index fe3e567a6e2b936c627f35b498719e7d19841c53..0000000000000000000000000000000000000000
--- a/spaces/AchyuthGamer/OpenGPT-Chat-UI/src/lib/server/websearch/parseWeb.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { JSDOM, VirtualConsole } from "jsdom";
-
-function removeTags(node: Node) {
- if (node.hasChildNodes()) {
- node.childNodes.forEach((childNode) => {
- if (node.nodeName === "SCRIPT" || node.nodeName === "STYLE") {
- node.removeChild(childNode);
- } else {
- removeTags(childNode);
- }
- });
- }
-}
-function naiveInnerText(node: Node): string {
- const Node = node; // We need Node(DOM's Node) for the constants, but Node doesn't exist in the nodejs global space, and any Node instance references the constants through the prototype chain
- return [...node.childNodes]
- .map((childNode) => {
- switch (childNode.nodeType) {
- case Node.TEXT_NODE:
- return node.textContent;
- case Node.ELEMENT_NODE:
- return naiveInnerText(childNode);
- default:
- return "";
- }
- })
- .join("\n");
-}
-
-export async function parseWeb(url: string) {
- const abortController = new AbortController();
- setTimeout(() => abortController.abort(), 10000);
- const htmlString = await fetch(url, { signal: abortController.signal })
- .then((response) => response.text())
- .catch((err) => console.log(err));
-
- const virtualConsole = new VirtualConsole();
- virtualConsole.on("error", () => {
- // No-op to skip console errors.
- });
-
- // put the html string into a DOM
- const dom = new JSDOM(htmlString ?? "", {
- virtualConsole,
- });
-
- const body = dom.window.document.querySelector("body");
- if (!body) throw new Error("body of the webpage is null");
-
- removeTags(body);
-
- // recursively extract text content from the body and then remove newlines and multiple spaces
- const text = (naiveInnerText(body) ?? "").replace(/ {2}|\r\n|\n|\r/gm, "");
-
- return text;
-}
diff --git a/spaces/AchyuthGamer/OpenGPT-Chat-UI/src/routes/conversation/[id]/web-search/+server.ts b/spaces/AchyuthGamer/OpenGPT-Chat-UI/src/routes/conversation/[id]/web-search/+server.ts
deleted file mode 100644
index 000e3516bdf75a74f12e90159273d9d136ea9e80..0000000000000000000000000000000000000000
--- a/spaces/AchyuthGamer/OpenGPT-Chat-UI/src/routes/conversation/[id]/web-search/+server.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-import { authCondition } from "$lib/server/auth";
-import { collections } from "$lib/server/database";
-import { defaultModel } from "$lib/server/models";
-import { searchWeb } from "$lib/server/websearch/searchWeb";
-import type { Message } from "$lib/types/Message";
-import { error } from "@sveltejs/kit";
-import { z } from "zod";
-import type { WebSearch } from "$lib/types/WebSearch";
-import { generateQuery } from "$lib/server/websearch/generateQuery";
-import { parseWeb } from "$lib/server/websearch/parseWeb";
-import { summarizeWeb } from "$lib/server/websearch/summarizeWeb";
-
-interface GenericObject {
- [key: string]: GenericObject | unknown;
-}
-
-function removeLinks(obj: GenericObject) {
- for (const prop in obj) {
- if (prop.endsWith("link")) delete obj[prop];
- else if (typeof obj[prop] === "object") removeLinks(obj[prop] as GenericObject);
- }
- return obj;
-}
-export async function GET({ params, locals, url }) {
- /*const model = defaultModel;
- const convId = new ObjectId(params.id);
- const searchId = new ObjectId();
-
- const conv = await collections.conversations.findOne({
- _id: convId,
- ...authCondition(locals),
- });
-
- if (!conv) {
- throw error(404, "Conversation not found");
- }
-
- const prompt = z.string().trim().min(1).parse(url.searchParams.get("prompt"));
-
- const messages = (() => {
- return [...conv.messages, { content: prompt, from: "user", id: crypto.randomUUID() }];
- })() satisfies Message[];
-
- const stream = new ReadableStream({
- async start(controller) {
- const webSearch: WebSearch = {
- _id: searchId,
- convId: convId,
- prompt: prompt,
- searchQuery: "",
- knowledgeGraph: "",
- answerBox: "",
- results: [],
- summary: "",
- messages: [],
- createdAt: new Date(),
- updatedAt: new Date(),
- };
-
- function appendUpdate(message: string, args?: string[], type?: "error" | "update") {
- webSearch.messages.push({
- type: type ?? "update",
- message,
- args,
- });
- controller.enqueue(JSON.stringify({ messages: webSearch.messages }));
- }
-
- try {
- appendUpdate("Generating search query");
- webSearch.searchQuery = await generateQuery(messages);
-
- appendUpdate("Searching Google", [webSearch.searchQuery]);
- const results = await searchWeb(webSearch.searchQuery);
-
- let text = "";
- webSearch.results =
- (results.organic_results &&
- results.organic_results.map((el: { link: string }) => el.link)) ??
- [];
-
- if (results.answer_box) {
- // if google returns an answer box, we use it
- webSearch.answerBox = JSON.stringify(removeLinks(results.answer_box));
- text = webSearch.answerBox;
- appendUpdate("Found a Google answer box");
- } else if (results.knowledge_graph) {
- // if google returns a knowledge graph, we use it
- webSearch.knowledgeGraph = JSON.stringify(removeLinks(results.knowledge_graph));
- text = webSearch.knowledgeGraph;
- appendUpdate("Found a Google knowledge page");
- } else if (webSearch.results.length > 0) {
- let tries = 0;
-
- while (!text && tries < 3) {
- const searchUrl = webSearch.results[tries];
- appendUpdate("Browsing result", [JSON.stringify(searchUrl)]);
- try {
- text = await parseWeb(searchUrl);
- if (!text) throw new Error("text of the webpage is null");
- } catch (e) {
- appendUpdate("Error parsing webpage", [], "error");
- tries++;
- }
- }
- if (!text) throw new Error("No text found on the first 3 results");
- } else {
- throw new Error("No results found for this search query");
- }
-
- appendUpdate("Creating summary");
- webSearch.summary = await summarizeWeb(text, webSearch.searchQuery, model);
- appendUpdate("Injecting summary", [JSON.stringify(webSearch.summary)]);
- } catch (searchError) {
- if (searchError instanceof Error) {
- webSearch.messages.push({
- type: "error",
- message: "An error occurred with the web search",
- args: [JSON.stringify(searchError.message)],
- });
- }
- }
-
- const res = await collections.webSearches.insertOne(webSearch);
- webSearch.messages.push({
- type: "result",
- id: res.insertedId.toString(),
- });
- controller.enqueue(JSON.stringify({ messages: webSearch.messages }));
- },
- });
-
- return new Response(stream, { headers: { "Content-Type": "application/json" } });
-
- */
-
- return new Response(undefined, { headers: { "Content-Type": "application/json" } });
-}
diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/basesizer/SetAnchor.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/basesizer/SetAnchor.js
deleted file mode 100644
index 9733271a66d25717343e77c2748ccbcd94721784..0000000000000000000000000000000000000000
--- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/basesizer/SetAnchor.js
+++ /dev/null
@@ -1,34 +0,0 @@
-import Anchor from '../anchor/Anchor.js';
-
-var SetAnchor = function (config) {
- if (config === undefined) {
- config = {};
- }
-
- // Assign default onResizeCallback if not given
- var hasMinWidth = config.hasOwnProperty('width');
- var hasMinHeight = config.hasOwnProperty('height');
- var hasOnResizeCallback = config.hasOwnProperty('onResizeCallback');
- if ((hasMinWidth || hasMinHeight) && !hasOnResizeCallback) {
- config.onResizeCallback = function (width, height, sizer) {
- if (hasMinWidth) {
- sizer.setMinWidth(width);
- }
-
- if (hasMinHeight) {
- sizer.setMinHeight(height);
- }
-
- sizer.layout();
- }
- }
-
- if (this._anchor === undefined) {
- this._anchor = new Anchor(this, config);
- } else {
- this._anchor.resetFromJSON(config)
- }
- return this;
-}
-
-export default SetAnchor;
\ No newline at end of file
diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/colorinput/colorpicker/methods/HPalette.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/colorinput/colorpicker/methods/HPalette.js
deleted file mode 100644
index bf0bf116f1b707055144d99003aad0c5eb68cb6e..0000000000000000000000000000000000000000
--- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/colorinput/colorpicker/methods/HPalette.js
+++ /dev/null
@@ -1,96 +0,0 @@
-import OverlapSizer from '../../../overlapsizer/OverlapSizer.js';
-import HPaletteCanvas from './HPaletteCanvas.js';
-import RoundRectangle from '../../../roundrectangle/RoundRectangle.js';
-import { LocalToWorld } from './Transform.js';
-
-class HPalette extends OverlapSizer {
- constructor(scene, config) {
- if (config === undefined) {
- config = {};
- }
- super(scene, config);
-
- var orientation = (config.width != null) ? 1 : 0;
- var paletteCanvas = (new HPaletteCanvas(scene))
- .setOrientation(orientation)
- scene.add.existing(paletteCanvas);
- this.type = 'rexColorPicker.HPalette';
-
- paletteCanvas
- .setInteractive()
- .on('pointerdown', this.onPaletteCanvasPointerDown, this)
- .on('pointermove', this.onPaletteCanvasPointerDown, this)
-
- var marker = new RoundRectangle(scene, { strokeColor: 0xffffff, strokeWidth: 2 });
- scene.add.existing(marker);
-
- this
- .add(
- paletteCanvas,
- { key: 'paletteCanvas', expand: true }
- )
- .add(
- marker,
- { key: 'marker', expand: false }
- )
- }
-
- resize(width, height) {
- if ((this.width === width) && (this.height === height)) {
- return this;
- }
-
- super.resize(width, height);
-
- var size = Math.min(width, height);
- this.childrenMap.marker.setSize(size, size);
-
- return this;
- }
-
- onPaletteCanvasPointerDown(pointer, localX, localY, event) {
- if (!pointer.isDown) {
- return;
- }
-
- var paletteCanvas = this.childrenMap.paletteCanvas;
- var color = paletteCanvas.getColor(localX, localY);
- this.setMarkerPosition(color);
-
- this.emit('input', color);
- }
-
- get color() {
- return this.childrenMap.paletteCanvas.color;
- }
-
- setColor(color) {
- if (this.color === color) {
- return this;
- }
-
- var paletteCanvas = this.childrenMap.paletteCanvas;
- paletteCanvas.setColor(color);
- this.setMarkerPosition(color);
-
- return this;
- }
-
- setMarkerPosition(color) {
- var paletteCanvas = this.childrenMap.paletteCanvas;
- var marker = this.childrenMap.marker;
-
- var localXY = paletteCanvas.colorToLocalPosition(color, true);
- LocalToWorld(paletteCanvas, localXY.x, localXY.y, marker);
- this.resetChildPositionState(marker);
-
- return this;
- }
-
- getHue(localX, localY) {
- var paletteCanvas = this.childrenMap.paletteCanvas;
- return paletteCanvas.getHue(localX, localY);
- }
-}
-
-export default HPalette;
\ No newline at end of file
diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/fixwidthsizer/RemoveChildMethods.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/fixwidthsizer/RemoveChildMethods.js
deleted file mode 100644
index 7e71690af162fcd6b829f4c30cd6a98c8f90c467..0000000000000000000000000000000000000000
--- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/fixwidthsizer/RemoveChildMethods.js
+++ /dev/null
@@ -1,28 +0,0 @@
-import RemoveChild from '../basesizer/utils/RemoveChild.js';
-import ClearChildren from '../basesizer/utils/ClearChildren.js';
-
-const RemoveItem = Phaser.Utils.Array.Remove;
-
-export default {
- remove(gameObject, destroyChild) {
- if (this.getParentSizer(gameObject) !== this) {
- return this;
- }
- RemoveItem(this.sizerChildren, gameObject);
- RemoveChild.call(this, gameObject, destroyChild);
- return this;
- },
-
- removeAll(destroyChild) {
- for (var i = this.sizerChildren.length - 1; i >= 0; i--) {
- this.remove(this.sizerChildren[i], destroyChild);
- }
- return this;
- },
-
- clear(destroyChild) {
- this.sizerChildren.length = 0;
- ClearChildren.call(this, destroyChild);
- return this;
- }
-}
\ No newline at end of file
diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/roundrectanglecanvas/RoundRectangleCanvas.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/roundrectanglecanvas/RoundRectangleCanvas.js
deleted file mode 100644
index b6bbb2a78376d1d5e34bdb3fab1d3050c2712247..0000000000000000000000000000000000000000
--- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/roundrectanglecanvas/RoundRectangleCanvas.js
+++ /dev/null
@@ -1,2 +0,0 @@
-import RoundRectangleCanvas from '../../../plugins/roundrectanglecanvas.js';
-export default RoundRectangleCanvas;
\ No newline at end of file
diff --git a/spaces/Alfasign/HuggingGPT-Lite/get_token_ids.py b/spaces/Alfasign/HuggingGPT-Lite/get_token_ids.py
deleted file mode 100644
index a69bb710143d462d6bd7839e57852c318e40a8b8..0000000000000000000000000000000000000000
--- a/spaces/Alfasign/HuggingGPT-Lite/get_token_ids.py
+++ /dev/null
@@ -1,53 +0,0 @@
-import tiktoken
-
-encodings = {
- "gpt-3.5-turbo": tiktoken.get_encoding("cl100k_base"),
- "gpt-3.5-turbo-0301": tiktoken.get_encoding("cl100k_base"),
- "text-davinci-003": tiktoken.get_encoding("p50k_base"),
- "text-davinci-002": tiktoken.get_encoding("p50k_base"),
- "text-davinci-001": tiktoken.get_encoding("r50k_base"),
- "text-curie-001": tiktoken.get_encoding("r50k_base"),
- "text-babbage-001": tiktoken.get_encoding("r50k_base"),
- "text-ada-001": tiktoken.get_encoding("r50k_base"),
- "davinci": tiktoken.get_encoding("r50k_base"),
- "curie": tiktoken.get_encoding("r50k_base"),
- "babbage": tiktoken.get_encoding("r50k_base"),
- "ada": tiktoken.get_encoding("r50k_base"),
-}
-
-max_length = {
- "gpt-3.5-turbo": 4096,
- "gpt-3.5-turbo-0301": 4096,
- "text-davinci-003": 4096,
- "text-davinci-002": 4096,
- "text-davinci-001": 2049,
- "text-curie-001": 2049,
- "text-babbage-001": 2049,
- "text-ada-001": 2049,
- "davinci": 2049,
- "curie": 2049,
- "babbage": 2049,
- "ada": 2049,
-}
-
-
-def count_tokens(model_name, text):
- return len(encodings[model_name].encode(text))
-
-
-def get_max_context_length(model_name):
- return max_length[model_name]
-
-
-def get_token_ids_for_task_parsing(model_name):
- text = """{"task": "text-classification", "token-classification", "text2text-generation", "summarization", "translation", "question-answering", "conversational", "text-generation", "sentence-similarity", "tabular-classification", "object-detection", "image-classification", "image-to-image", "image-to-text", "text-to-image", "visual-question-answering", "document-question-answering", "image-segmentation", "text-to-speech", "text-to-video", "automatic-speech-recognition", "audio-to-audio", "audio-classification", "canny-control", "hed-control", "mlsd-control", "normal-control", "openpose-control", "canny-text-to-image", "depth-text-to-image", "hed-text-to-image", "mlsd-text-to-image", "normal-text-to-image", "openpose-text-to-image", "seg-text-to-image", "args", "text", "path", "dep", "id", "-"}"""
- res = encodings[model_name].encode(text)
- res = list(set(res))
- return res
-
-
-def get_token_ids_for_choose_model(model_name):
- text = """{"id": "reason"}"""
- res = encodings[model_name].encode(text)
- res = list(set(res))
- return res
diff --git a/spaces/Alpaca233/SadTalker/src/audio2exp_models/networks.py b/spaces/Alpaca233/SadTalker/src/audio2exp_models/networks.py
deleted file mode 100644
index f052e18101f5446a527ae354b3621e7d0d4991cc..0000000000000000000000000000000000000000
--- a/spaces/Alpaca233/SadTalker/src/audio2exp_models/networks.py
+++ /dev/null
@@ -1,74 +0,0 @@
-import torch
-import torch.nn.functional as F
-from torch import nn
-
-class Conv2d(nn.Module):
- def __init__(self, cin, cout, kernel_size, stride, padding, residual=False, use_act = True, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.conv_block = nn.Sequential(
- nn.Conv2d(cin, cout, kernel_size, stride, padding),
- nn.BatchNorm2d(cout)
- )
- self.act = nn.ReLU()
- self.residual = residual
- self.use_act = use_act
-
- def forward(self, x):
- out = self.conv_block(x)
- if self.residual:
- out += x
-
- if self.use_act:
- return self.act(out)
- else:
- return out
-
-class SimpleWrapperV2(nn.Module):
- def __init__(self) -> None:
- super().__init__()
- self.audio_encoder = nn.Sequential(
- Conv2d(1, 32, kernel_size=3, stride=1, padding=1),
- Conv2d(32, 32, kernel_size=3, stride=1, padding=1, residual=True),
- Conv2d(32, 32, kernel_size=3, stride=1, padding=1, residual=True),
-
- Conv2d(32, 64, kernel_size=3, stride=(3, 1), padding=1),
- Conv2d(64, 64, kernel_size=3, stride=1, padding=1, residual=True),
- Conv2d(64, 64, kernel_size=3, stride=1, padding=1, residual=True),
-
- Conv2d(64, 128, kernel_size=3, stride=3, padding=1),
- Conv2d(128, 128, kernel_size=3, stride=1, padding=1, residual=True),
- Conv2d(128, 128, kernel_size=3, stride=1, padding=1, residual=True),
-
- Conv2d(128, 256, kernel_size=3, stride=(3, 2), padding=1),
- Conv2d(256, 256, kernel_size=3, stride=1, padding=1, residual=True),
-
- Conv2d(256, 512, kernel_size=3, stride=1, padding=0),
- Conv2d(512, 512, kernel_size=1, stride=1, padding=0),
- )
-
- #### load the pre-trained audio_encoder
- #self.audio_encoder = self.audio_encoder.to(device)
- '''
- wav2lip_state_dict = torch.load('/apdcephfs_cq2/share_1290939/wenxuazhang/checkpoints/wav2lip.pth')['state_dict']
- state_dict = self.audio_encoder.state_dict()
-
- for k,v in wav2lip_state_dict.items():
- if 'audio_encoder' in k:
- print('init:', k)
- state_dict[k.replace('module.audio_encoder.', '')] = v
- self.audio_encoder.load_state_dict(state_dict)
- '''
-
- self.mapping1 = nn.Linear(512+64+1, 64)
- #self.mapping2 = nn.Linear(30, 64)
- #nn.init.constant_(self.mapping1.weight, 0.)
- nn.init.constant_(self.mapping1.bias, 0.)
-
- def forward(self, x, ref, ratio):
- x = self.audio_encoder(x).view(x.size(0), -1)
- ref_reshape = ref.reshape(x.size(0), -1)
- ratio = ratio.reshape(x.size(0), -1)
-
- y = self.mapping1(torch.cat([x, ref_reshape, ratio], dim=1))
- out = y.reshape(ref.shape[0], ref.shape[1], -1) #+ ref # resudial
- return out
diff --git a/spaces/Amrrs/DragGan-Inversion/stylegan_human/pti/training/projectors/__init__.py b/spaces/Amrrs/DragGan-Inversion/stylegan_human/pti/training/projectors/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/schedulers/ddpm.md b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/schedulers/ddpm.md
deleted file mode 100644
index 6c4058b941fab8ec7177f9635aecc7b924b39d68..0000000000000000000000000000000000000000
--- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/schedulers/ddpm.md
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-# Denoising Diffusion Probabilistic Models (DDPM)
-
-## Overview
-
-[Denoising Diffusion Probabilistic Models](https://arxiv.org/abs/2006.11239)
- (DDPM) by Jonathan Ho, Ajay Jain and Pieter Abbeel proposes the diffusion based model of the same name, but in the context of the 🤗 Diffusers library, DDPM refers to the discrete denoising scheduler from the paper as well as the pipeline.
-
-The abstract of the paper is the following:
-
-We present high quality image synthesis results using diffusion probabilistic models, a class of latent variable models inspired by considerations from nonequilibrium thermodynamics. Our best results are obtained by training on a weighted variational bound designed according to a novel connection between diffusion probabilistic models and denoising score matching with Langevin dynamics, and our models naturally admit a progressive lossy decompression scheme that can be interpreted as a generalization of autoregressive decoding. On the unconditional CIFAR10 dataset, we obtain an Inception score of 9.46 and a state-of-the-art FID score of 3.17. On 256x256 LSUN, we obtain sample quality similar to ProgressiveGAN.
-
-The original paper can be found [here](https://arxiv.org/abs/2010.02502).
-
-## DDPMScheduler
-[[autodoc]] DDPMScheduler
diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/ko/tutorials/tutorial_overview.md b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/ko/tutorials/tutorial_overview.md
deleted file mode 100644
index bf9cf39f64e6206c3a10d24f004b0b0368df4028..0000000000000000000000000000000000000000
--- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/ko/tutorials/tutorial_overview.md
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-# Overview
-
-🧨 Diffusers에 오신 걸 환영합니다! 여러분이 diffusion 모델과 생성 AI를 처음 접하고, 더 많은 걸 배우고 싶으셨다면 제대로 찾아오셨습니다. 이 튜토리얼은 diffusion model을 여러분에게 젠틀하게 소개하고, 라이브러리의 기본 사항(핵심 구성요소와 🧨 Diffusers 사용법)을 이해하는 데 도움이 되도록 설계되었습니다.
-
-여러분은 이 튜토리얼을 통해 빠르게 생성하기 위해선 추론 파이프라인을 어떻게 사용해야 하는지, 그리고 라이브러리를 modular toolbox처럼 이용해서 여러분만의 diffusion system을 구축할 수 있도록 파이프라인을 분해하는 법을 배울 수 있습니다. 다음 단원에서는 여러분이 원하는 것을 생성하기 위해 자신만의 diffusion model을 학습하는 방법을 배우게 됩니다.
-
-튜토리얼을 완료한다면 여러분은 라이브러리를 직접 탐색하고, 자신의 프로젝트와 애플리케이션에 적용할 스킬들을 습득할 수 있을 겁니다.
-
-[Discord](https://discord.com/invite/JfAtkvEtRb)나 [포럼](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63) 커뮤니티에 자유롭게 참여해서 다른 사용자와 개발자들과 교류하고 협업해 보세요!
-
-자 지금부터 diffusing을 시작해 보겠습니다! 🧨
\ No newline at end of file
diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/examples/dreambooth/train_dreambooth_lora_sdxl.py b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/examples/dreambooth/train_dreambooth_lora_sdxl.py
deleted file mode 100644
index d8ea253f82144a1a7401d590fdfee06fbc990c6c..0000000000000000000000000000000000000000
--- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/examples/dreambooth/train_dreambooth_lora_sdxl.py
+++ /dev/null
@@ -1,1355 +0,0 @@
-#!/usr/bin/env python
-# coding=utf-8
-# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-
-import argparse
-import gc
-import hashlib
-import itertools
-import logging
-import math
-import os
-import shutil
-import warnings
-from pathlib import Path
-from typing import Dict
-
-import numpy as np
-import torch
-import torch.nn.functional as F
-import torch.utils.checkpoint
-import transformers
-from accelerate import Accelerator
-from accelerate.logging import get_logger
-from accelerate.utils import ProjectConfiguration, set_seed
-from huggingface_hub import create_repo, upload_folder
-from packaging import version
-from PIL import Image
-from PIL.ImageOps import exif_transpose
-from torch.utils.data import Dataset
-from torchvision import transforms
-from tqdm.auto import tqdm
-from transformers import AutoTokenizer, PretrainedConfig
-
-import diffusers
-from diffusers import (
- AutoencoderKL,
- DDPMScheduler,
- DPMSolverMultistepScheduler,
- StableDiffusionXLPipeline,
- UNet2DConditionModel,
-)
-from diffusers.loaders import LoraLoaderMixin, text_encoder_lora_state_dict
-from diffusers.models.attention_processor import LoRAAttnProcessor, LoRAAttnProcessor2_0
-from diffusers.optimization import get_scheduler
-from diffusers.utils import check_min_version, is_wandb_available
-from diffusers.utils.import_utils import is_xformers_available
-
-
-# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
-check_min_version("0.19.0")
-
-logger = get_logger(__name__)
-
-
-def save_model_card(
- repo_id: str, images=None, base_model=str, train_text_encoder=False, prompt=str, repo_folder=None, vae_path=None
-):
- img_str = ""
- for i, image in enumerate(images):
- image.save(os.path.join(repo_folder, f"image_{i}.png"))
- img_str += f"\n"
-
- yaml = f"""
----
-license: creativeml-openrail-m
-base_model: {base_model}
-instance_prompt: {prompt}
-tags:
-- stable-diffusion-xl
-- stable-diffusion-xl-diffusers
-- text-to-image
-- diffusers
-- lora
-inference: true
----
- """
- model_card = f"""
-# LoRA DreamBooth - {repo_id}
-
-These are LoRA adaption weights for {base_model}. The weights were trained on {prompt} using [DreamBooth](https://dreambooth.github.io/). You can find some example images in the following. \n
-{img_str}
-
-LoRA for the text encoder was enabled: {train_text_encoder}.
-
-Special VAE used for training: {vae_path}.
-
-## License
-
-[SDXL 1.0 License](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/LICENSE.md)
-"""
- with open(os.path.join(repo_folder, "README.md"), "w") as f:
- f.write(yaml + model_card)
-
-
-def import_model_class_from_model_name_or_path(
- pretrained_model_name_or_path: str, revision: str, subfolder: str = "text_encoder"
-):
- text_encoder_config = PretrainedConfig.from_pretrained(
- pretrained_model_name_or_path, subfolder=subfolder, revision=revision
- )
- model_class = text_encoder_config.architectures[0]
-
- if model_class == "CLIPTextModel":
- from transformers import CLIPTextModel
-
- return CLIPTextModel
- elif model_class == "CLIPTextModelWithProjection":
- from transformers import CLIPTextModelWithProjection
-
- return CLIPTextModelWithProjection
- else:
- raise ValueError(f"{model_class} is not supported.")
-
-
-def parse_args(input_args=None):
- parser = argparse.ArgumentParser(description="Simple example of a training script.")
- parser.add_argument(
- "--pretrained_model_name_or_path",
- type=str,
- default=None,
- required=True,
- help="Path to pretrained model or model identifier from huggingface.co/models.",
- )
- parser.add_argument(
- "--pretrained_vae_model_name_or_path",
- type=str,
- default=None,
- help="Path to pretrained VAE model with better numerical stability. More details: https://github.com/huggingface/diffusers/pull/4038.",
- )
- parser.add_argument(
- "--revision",
- type=str,
- default=None,
- required=False,
- help="Revision of pretrained model identifier from huggingface.co/models.",
- )
- parser.add_argument(
- "--instance_data_dir",
- type=str,
- default=None,
- required=True,
- help="A folder containing the training data of instance images.",
- )
- parser.add_argument(
- "--class_data_dir",
- type=str,
- default=None,
- required=False,
- help="A folder containing the training data of class images.",
- )
- parser.add_argument(
- "--instance_prompt",
- type=str,
- default=None,
- required=True,
- help="The prompt with identifier specifying the instance",
- )
- parser.add_argument(
- "--class_prompt",
- type=str,
- default=None,
- help="The prompt to specify images in the same class as provided instance images.",
- )
- parser.add_argument(
- "--validation_prompt",
- type=str,
- default=None,
- help="A prompt that is used during validation to verify that the model is learning.",
- )
- parser.add_argument(
- "--num_validation_images",
- type=int,
- default=4,
- help="Number of images that should be generated during validation with `validation_prompt`.",
- )
- parser.add_argument(
- "--validation_epochs",
- type=int,
- default=50,
- help=(
- "Run dreambooth validation every X epochs. Dreambooth validation consists of running the prompt"
- " `args.validation_prompt` multiple times: `args.num_validation_images`."
- ),
- )
- parser.add_argument(
- "--with_prior_preservation",
- default=False,
- action="store_true",
- help="Flag to add prior preservation loss.",
- )
- parser.add_argument("--prior_loss_weight", type=float, default=1.0, help="The weight of prior preservation loss.")
- parser.add_argument(
- "--num_class_images",
- type=int,
- default=100,
- help=(
- "Minimal class images for prior preservation loss. If there are not enough images already present in"
- " class_data_dir, additional images will be sampled with class_prompt."
- ),
- )
- parser.add_argument(
- "--output_dir",
- type=str,
- default="lora-dreambooth-model",
- help="The output directory where the model predictions and checkpoints will be written.",
- )
- parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
- parser.add_argument(
- "--resolution",
- type=int,
- default=512,
- help=(
- "The resolution for input images, all the images in the train/validation dataset will be resized to this"
- " resolution"
- ),
- )
- parser.add_argument(
- "--crops_coords_top_left_h",
- type=int,
- default=0,
- help=("Coordinate for (the height) to be included in the crop coordinate embeddings needed by SDXL UNet."),
- )
- parser.add_argument(
- "--crops_coords_top_left_w",
- type=int,
- default=0,
- help=("Coordinate for (the height) to be included in the crop coordinate embeddings needed by SDXL UNet."),
- )
- parser.add_argument(
- "--center_crop",
- default=False,
- action="store_true",
- help=(
- "Whether to center crop the input images to the resolution. If not set, the images will be randomly"
- " cropped. The images will be resized to the resolution first before cropping."
- ),
- )
- parser.add_argument(
- "--train_text_encoder",
- action="store_true",
- help="Whether to train the text encoder. If set, the text encoder should be float32 precision.",
- )
- parser.add_argument(
- "--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
- )
- parser.add_argument(
- "--sample_batch_size", type=int, default=4, help="Batch size (per device) for sampling images."
- )
- parser.add_argument("--num_train_epochs", type=int, default=1)
- parser.add_argument(
- "--max_train_steps",
- type=int,
- default=None,
- help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
- )
- parser.add_argument(
- "--checkpointing_steps",
- type=int,
- default=500,
- help=(
- "Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
- " checkpoints in case they are better than the last checkpoint, and are also suitable for resuming"
- " training using `--resume_from_checkpoint`."
- ),
- )
- parser.add_argument(
- "--checkpoints_total_limit",
- type=int,
- default=None,
- help=("Max number of checkpoints to store."),
- )
- parser.add_argument(
- "--resume_from_checkpoint",
- type=str,
- default=None,
- help=(
- "Whether training should be resumed from a previous checkpoint. Use a path saved by"
- ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
- ),
- )
- parser.add_argument(
- "--gradient_accumulation_steps",
- type=int,
- default=1,
- help="Number of updates steps to accumulate before performing a backward/update pass.",
- )
- parser.add_argument(
- "--gradient_checkpointing",
- action="store_true",
- help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
- )
- parser.add_argument(
- "--learning_rate",
- type=float,
- default=5e-4,
- help="Initial learning rate (after the potential warmup period) to use.",
- )
- parser.add_argument(
- "--scale_lr",
- action="store_true",
- default=False,
- help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
- )
- parser.add_argument(
- "--lr_scheduler",
- type=str,
- default="constant",
- help=(
- 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
- ' "constant", "constant_with_warmup"]'
- ),
- )
- parser.add_argument(
- "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
- )
- parser.add_argument(
- "--lr_num_cycles",
- type=int,
- default=1,
- help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
- )
- parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.")
- parser.add_argument(
- "--dataloader_num_workers",
- type=int,
- default=0,
- help=(
- "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
- ),
- )
- parser.add_argument(
- "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
- )
- parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
- parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
- parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
- parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
- parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
- parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
- parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
- parser.add_argument(
- "--hub_model_id",
- type=str,
- default=None,
- help="The name of the repository to keep in sync with the local `output_dir`.",
- )
- parser.add_argument(
- "--logging_dir",
- type=str,
- default="logs",
- help=(
- "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
- " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
- ),
- )
- parser.add_argument(
- "--allow_tf32",
- action="store_true",
- help=(
- "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
- " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
- ),
- )
- parser.add_argument(
- "--report_to",
- type=str,
- default="tensorboard",
- help=(
- 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
- ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
- ),
- )
- parser.add_argument(
- "--mixed_precision",
- type=str,
- default=None,
- choices=["no", "fp16", "bf16"],
- help=(
- "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
- " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
- " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
- ),
- )
- parser.add_argument(
- "--prior_generation_precision",
- type=str,
- default=None,
- choices=["no", "fp32", "fp16", "bf16"],
- help=(
- "Choose prior generation precision between fp32, fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
- " 1.10.and an Nvidia Ampere GPU. Default to fp16 if a GPU is available else fp32."
- ),
- )
- parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
- parser.add_argument(
- "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
- )
-
- if input_args is not None:
- args = parser.parse_args(input_args)
- else:
- args = parser.parse_args()
-
- env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
- if env_local_rank != -1 and env_local_rank != args.local_rank:
- args.local_rank = env_local_rank
-
- if args.with_prior_preservation:
- if args.class_data_dir is None:
- raise ValueError("You must specify a data directory for class images.")
- if args.class_prompt is None:
- raise ValueError("You must specify prompt for class images.")
- else:
- # logger is not available yet
- if args.class_data_dir is not None:
- warnings.warn("You need not use --class_data_dir without --with_prior_preservation.")
- if args.class_prompt is not None:
- warnings.warn("You need not use --class_prompt without --with_prior_preservation.")
-
- return args
-
-
-class DreamBoothDataset(Dataset):
- """
- A dataset to prepare the instance and class images with the prompts for fine-tuning the model.
- It pre-processes the images.
- """
-
- def __init__(
- self,
- instance_data_root,
- class_data_root=None,
- class_num=None,
- size=1024,
- center_crop=False,
- ):
- self.size = size
- self.center_crop = center_crop
-
- self.instance_data_root = Path(instance_data_root)
- if not self.instance_data_root.exists():
- raise ValueError("Instance images root doesn't exists.")
-
- self.instance_images_path = list(Path(instance_data_root).iterdir())
- self.num_instance_images = len(self.instance_images_path)
- self._length = self.num_instance_images
-
- if class_data_root is not None:
- self.class_data_root = Path(class_data_root)
- self.class_data_root.mkdir(parents=True, exist_ok=True)
- self.class_images_path = list(self.class_data_root.iterdir())
- if class_num is not None:
- self.num_class_images = min(len(self.class_images_path), class_num)
- else:
- self.num_class_images = len(self.class_images_path)
- self._length = max(self.num_class_images, self.num_instance_images)
- else:
- self.class_data_root = None
-
- self.image_transforms = transforms.Compose(
- [
- transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR),
- transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size),
- transforms.ToTensor(),
- transforms.Normalize([0.5], [0.5]),
- ]
- )
-
- def __len__(self):
- return self._length
-
- def __getitem__(self, index):
- example = {}
- instance_image = Image.open(self.instance_images_path[index % self.num_instance_images])
- instance_image = exif_transpose(instance_image)
-
- if not instance_image.mode == "RGB":
- instance_image = instance_image.convert("RGB")
- example["instance_images"] = self.image_transforms(instance_image)
-
- if self.class_data_root:
- class_image = Image.open(self.class_images_path[index % self.num_class_images])
- class_image = exif_transpose(class_image)
-
- if not class_image.mode == "RGB":
- class_image = class_image.convert("RGB")
- example["class_images"] = self.image_transforms(class_image)
-
- return example
-
-
-def collate_fn(examples, with_prior_preservation=False):
- pixel_values = [example["instance_images"] for example in examples]
-
- # Concat class and instance examples for prior preservation.
- # We do this to avoid doing two forward passes.
- if with_prior_preservation:
- pixel_values += [example["class_images"] for example in examples]
-
- pixel_values = torch.stack(pixel_values)
- pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
-
- batch = {"pixel_values": pixel_values}
- return batch
-
-
-class PromptDataset(Dataset):
- "A simple dataset to prepare the prompts to generate class images on multiple GPUs."
-
- def __init__(self, prompt, num_samples):
- self.prompt = prompt
- self.num_samples = num_samples
-
- def __len__(self):
- return self.num_samples
-
- def __getitem__(self, index):
- example = {}
- example["prompt"] = self.prompt
- example["index"] = index
- return example
-
-
-def tokenize_prompt(tokenizer, prompt):
- text_inputs = tokenizer(
- prompt,
- padding="max_length",
- max_length=tokenizer.model_max_length,
- truncation=True,
- return_tensors="pt",
- )
- text_input_ids = text_inputs.input_ids
- return text_input_ids
-
-
-# Adapted from pipelines.StableDiffusionXLPipeline.encode_prompt
-def encode_prompt(text_encoders, tokenizers, prompt, text_input_ids_list=None):
- prompt_embeds_list = []
-
- for i, text_encoder in enumerate(text_encoders):
- if tokenizers is not None:
- tokenizer = tokenizers[i]
- text_input_ids = tokenize_prompt(tokenizer, prompt)
- else:
- assert text_input_ids_list is not None
- text_input_ids = text_input_ids_list[i]
-
- prompt_embeds = text_encoder(
- text_input_ids.to(text_encoder.device),
- output_hidden_states=True,
- )
-
- # We are only ALWAYS interested in the pooled output of the final text encoder
- pooled_prompt_embeds = prompt_embeds[0]
- prompt_embeds = prompt_embeds.hidden_states[-2]
- bs_embed, seq_len, _ = prompt_embeds.shape
- prompt_embeds = prompt_embeds.view(bs_embed, seq_len, -1)
- prompt_embeds_list.append(prompt_embeds)
-
- prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
- pooled_prompt_embeds = pooled_prompt_embeds.view(bs_embed, -1)
- return prompt_embeds, pooled_prompt_embeds
-
-
-def unet_attn_processors_state_dict(unet) -> Dict[str, torch.tensor]:
- """
- Returns:
- a state dict containing just the attention processor parameters.
- """
- attn_processors = unet.attn_processors
-
- attn_processors_state_dict = {}
-
- for attn_processor_key, attn_processor in attn_processors.items():
- for parameter_key, parameter in attn_processor.state_dict().items():
- attn_processors_state_dict[f"{attn_processor_key}.{parameter_key}"] = parameter
-
- return attn_processors_state_dict
-
-
-def main(args):
- logging_dir = Path(args.output_dir, args.logging_dir)
-
- accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
-
- accelerator = Accelerator(
- gradient_accumulation_steps=args.gradient_accumulation_steps,
- mixed_precision=args.mixed_precision,
- log_with=args.report_to,
- project_config=accelerator_project_config,
- )
-
- if args.report_to == "wandb":
- if not is_wandb_available():
- raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
- import wandb
-
- # Make one log on every process with the configuration for debugging.
- logging.basicConfig(
- format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
- datefmt="%m/%d/%Y %H:%M:%S",
- level=logging.INFO,
- )
- logger.info(accelerator.state, main_process_only=False)
- if accelerator.is_local_main_process:
- transformers.utils.logging.set_verbosity_warning()
- diffusers.utils.logging.set_verbosity_info()
- else:
- transformers.utils.logging.set_verbosity_error()
- diffusers.utils.logging.set_verbosity_error()
-
- # If passed along, set the training seed now.
- if args.seed is not None:
- set_seed(args.seed)
-
- # Generate class images if prior preservation is enabled.
- if args.with_prior_preservation:
- class_images_dir = Path(args.class_data_dir)
- if not class_images_dir.exists():
- class_images_dir.mkdir(parents=True)
- cur_class_images = len(list(class_images_dir.iterdir()))
-
- if cur_class_images < args.num_class_images:
- torch_dtype = torch.float16 if accelerator.device.type == "cuda" else torch.float32
- if args.prior_generation_precision == "fp32":
- torch_dtype = torch.float32
- elif args.prior_generation_precision == "fp16":
- torch_dtype = torch.float16
- elif args.prior_generation_precision == "bf16":
- torch_dtype = torch.bfloat16
- pipeline = StableDiffusionXLPipeline.from_pretrained(
- args.pretrained_model_name_or_path,
- torch_dtype=torch_dtype,
- safety_checker=None,
- revision=args.revision,
- )
- pipeline.set_progress_bar_config(disable=True)
-
- num_new_images = args.num_class_images - cur_class_images
- logger.info(f"Number of class images to sample: {num_new_images}.")
-
- sample_dataset = PromptDataset(args.class_prompt, num_new_images)
- sample_dataloader = torch.utils.data.DataLoader(sample_dataset, batch_size=args.sample_batch_size)
-
- sample_dataloader = accelerator.prepare(sample_dataloader)
- pipeline.to(accelerator.device)
-
- for example in tqdm(
- sample_dataloader, desc="Generating class images", disable=not accelerator.is_local_main_process
- ):
- images = pipeline(example["prompt"]).images
-
- for i, image in enumerate(images):
- hash_image = hashlib.sha1(image.tobytes()).hexdigest()
- image_filename = class_images_dir / f"{example['index'][i] + cur_class_images}-{hash_image}.jpg"
- image.save(image_filename)
-
- del pipeline
- if torch.cuda.is_available():
- torch.cuda.empty_cache()
-
- # Handle the repository creation
- if accelerator.is_main_process:
- if args.output_dir is not None:
- os.makedirs(args.output_dir, exist_ok=True)
-
- if args.push_to_hub:
- repo_id = create_repo(
- repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
- ).repo_id
-
- # Load the tokenizers
- tokenizer_one = AutoTokenizer.from_pretrained(
- args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision, use_fast=False
- )
- tokenizer_two = AutoTokenizer.from_pretrained(
- args.pretrained_model_name_or_path, subfolder="tokenizer_2", revision=args.revision, use_fast=False
- )
-
- # import correct text encoder classes
- text_encoder_cls_one = import_model_class_from_model_name_or_path(
- args.pretrained_model_name_or_path, args.revision
- )
- text_encoder_cls_two = import_model_class_from_model_name_or_path(
- args.pretrained_model_name_or_path, args.revision, subfolder="text_encoder_2"
- )
-
- # Load scheduler and models
- noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
- text_encoder_one = text_encoder_cls_one.from_pretrained(
- args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
- )
- text_encoder_two = text_encoder_cls_two.from_pretrained(
- args.pretrained_model_name_or_path, subfolder="text_encoder_2", revision=args.revision
- )
- vae_path = (
- args.pretrained_model_name_or_path
- if args.pretrained_vae_model_name_or_path is None
- else args.pretrained_vae_model_name_or_path
- )
- vae = AutoencoderKL.from_pretrained(
- vae_path, subfolder="vae" if args.pretrained_vae_model_name_or_path is None else None, revision=args.revision
- )
- unet = UNet2DConditionModel.from_pretrained(
- args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision
- )
-
- # We only train the additional adapter LoRA layers
- vae.requires_grad_(False)
- text_encoder_one.requires_grad_(False)
- text_encoder_two.requires_grad_(False)
- unet.requires_grad_(False)
-
- # For mixed precision training we cast all non-trainable weigths (vae, non-lora text_encoder and non-lora unet) to half-precision
- # as these weights are only used for inference, keeping weights in full precision is not required.
- weight_dtype = torch.float32
- if accelerator.mixed_precision == "fp16":
- weight_dtype = torch.float16
- elif accelerator.mixed_precision == "bf16":
- weight_dtype = torch.bfloat16
-
- # Move unet, vae and text_encoder to device and cast to weight_dtype
- # The VAE is in float32 to avoid NaN losses.
- unet.to(accelerator.device, dtype=weight_dtype)
- if args.pretrained_vae_model_name_or_path is None:
- vae.to(accelerator.device, dtype=torch.float32)
- else:
- vae.to(accelerator.device, dtype=weight_dtype)
- text_encoder_one.to(accelerator.device, dtype=weight_dtype)
- text_encoder_two.to(accelerator.device, dtype=weight_dtype)
-
- if args.enable_xformers_memory_efficient_attention:
- if is_xformers_available():
- import xformers
-
- xformers_version = version.parse(xformers.__version__)
- if xformers_version == version.parse("0.0.16"):
- logger.warn(
- "xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
- )
- unet.enable_xformers_memory_efficient_attention()
- else:
- raise ValueError("xformers is not available. Make sure it is installed correctly")
-
- # now we will add new LoRA weights to the attention layers
- # Set correct lora layers
- unet_lora_attn_procs = {}
- unet_lora_parameters = []
- for name, attn_processor in unet.attn_processors.items():
- cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
- if name.startswith("mid_block"):
- hidden_size = unet.config.block_out_channels[-1]
- elif name.startswith("up_blocks"):
- block_id = int(name[len("up_blocks.")])
- hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
- elif name.startswith("down_blocks"):
- block_id = int(name[len("down_blocks.")])
- hidden_size = unet.config.block_out_channels[block_id]
-
- lora_attn_processor_class = (
- LoRAAttnProcessor2_0 if hasattr(F, "scaled_dot_product_attention") else LoRAAttnProcessor
- )
- module = lora_attn_processor_class(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim)
- unet_lora_attn_procs[name] = module
- unet_lora_parameters.extend(module.parameters())
-
- unet.set_attn_processor(unet_lora_attn_procs)
-
- # The text encoder comes from 🤗 transformers, so we cannot directly modify it.
- # So, instead, we monkey-patch the forward calls of its attention-blocks.
- if args.train_text_encoder:
- # ensure that dtype is float32, even if rest of the model that isn't trained is loaded in fp16
- text_lora_parameters_one = LoraLoaderMixin._modify_text_encoder(text_encoder_one, dtype=torch.float32)
- text_lora_parameters_two = LoraLoaderMixin._modify_text_encoder(text_encoder_two, dtype=torch.float32)
-
- # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
- def save_model_hook(models, weights, output_dir):
- # there are only two options here. Either are just the unet attn processor layers
- # or there are the unet and text encoder atten layers
- unet_lora_layers_to_save = None
- text_encoder_one_lora_layers_to_save = None
- text_encoder_two_lora_layers_to_save = None
-
- for model in models:
- if isinstance(model, type(accelerator.unwrap_model(unet))):
- unet_lora_layers_to_save = unet_attn_processors_state_dict(model)
- elif isinstance(model, type(accelerator.unwrap_model(text_encoder_one))):
- text_encoder_one_lora_layers_to_save = text_encoder_lora_state_dict(model)
- elif isinstance(model, type(accelerator.unwrap_model(text_encoder_two))):
- text_encoder_two_lora_layers_to_save = text_encoder_lora_state_dict(model)
- else:
- raise ValueError(f"unexpected save model: {model.__class__}")
-
- # make sure to pop weight so that corresponding model is not saved again
- weights.pop()
-
- StableDiffusionXLPipeline.save_lora_weights(
- output_dir,
- unet_lora_layers=unet_lora_layers_to_save,
- text_encoder_lora_layers=text_encoder_one_lora_layers_to_save,
- text_encoder_2_lora_layers=text_encoder_two_lora_layers_to_save,
- )
-
- def load_model_hook(models, input_dir):
- unet_ = None
- text_encoder_one_ = None
- text_encoder_two_ = None
-
- while len(models) > 0:
- model = models.pop()
-
- if isinstance(model, type(accelerator.unwrap_model(unet))):
- unet_ = model
- elif isinstance(model, type(accelerator.unwrap_model(text_encoder_one))):
- text_encoder_one_ = model
- elif isinstance(model, type(accelerator.unwrap_model(text_encoder_two))):
- text_encoder_two_ = model
- else:
- raise ValueError(f"unexpected save model: {model.__class__}")
-
- lora_state_dict, network_alphas = LoraLoaderMixin.lora_state_dict(input_dir)
- LoraLoaderMixin.load_lora_into_unet(lora_state_dict, network_alphas=network_alphas, unet=unet_)
- LoraLoaderMixin.load_lora_into_text_encoder(
- lora_state_dict, network_alphas=network_alphas, text_encoder=text_encoder_one_
- )
- LoraLoaderMixin.load_lora_into_text_encoder(
- lora_state_dict, network_alphas=network_alphas, text_encoder=text_encoder_two_
- )
-
- accelerator.register_save_state_pre_hook(save_model_hook)
- accelerator.register_load_state_pre_hook(load_model_hook)
-
- # Enable TF32 for faster training on Ampere GPUs,
- # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
- if args.allow_tf32:
- torch.backends.cuda.matmul.allow_tf32 = True
-
- if args.scale_lr:
- args.learning_rate = (
- args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
- )
-
- # Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs
- if args.use_8bit_adam:
- try:
- import bitsandbytes as bnb
- except ImportError:
- raise ImportError(
- "To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
- )
-
- optimizer_class = bnb.optim.AdamW8bit
- else:
- optimizer_class = torch.optim.AdamW
-
- # Optimizer creation
- params_to_optimize = (
- itertools.chain(unet_lora_parameters, text_lora_parameters_one, text_lora_parameters_two)
- if args.train_text_encoder
- else unet_lora_parameters
- )
- optimizer = optimizer_class(
- params_to_optimize,
- lr=args.learning_rate,
- betas=(args.adam_beta1, args.adam_beta2),
- weight_decay=args.adam_weight_decay,
- eps=args.adam_epsilon,
- )
-
- # Computes additional embeddings/ids required by the SDXL UNet.
- # regular text emebddings (when `train_text_encoder` is not True)
- # pooled text embeddings
- # time ids
-
- def compute_time_ids():
- # Adapted from pipeline.StableDiffusionXLPipeline._get_add_time_ids
- original_size = (args.resolution, args.resolution)
- target_size = (args.resolution, args.resolution)
- crops_coords_top_left = (args.crops_coords_top_left_h, args.crops_coords_top_left_w)
- add_time_ids = list(original_size + crops_coords_top_left + target_size)
- add_time_ids = torch.tensor([add_time_ids])
- add_time_ids = add_time_ids.to(accelerator.device, dtype=weight_dtype)
- return add_time_ids
-
- if not args.train_text_encoder:
- tokenizers = [tokenizer_one, tokenizer_two]
- text_encoders = [text_encoder_one, text_encoder_two]
-
- def compute_text_embeddings(prompt, text_encoders, tokenizers):
- with torch.no_grad():
- prompt_embeds, pooled_prompt_embeds = encode_prompt(text_encoders, tokenizers, prompt)
- prompt_embeds = prompt_embeds.to(accelerator.device)
- pooled_prompt_embeds = pooled_prompt_embeds.to(accelerator.device)
- return prompt_embeds, pooled_prompt_embeds
-
- # Handle instance prompt.
- instance_time_ids = compute_time_ids()
- if not args.train_text_encoder:
- instance_prompt_hidden_states, instance_pooled_prompt_embeds = compute_text_embeddings(
- args.instance_prompt, text_encoders, tokenizers
- )
-
- # Handle class prompt for prior-preservation.
- if args.with_prior_preservation:
- class_time_ids = compute_time_ids()
- if not args.train_text_encoder:
- class_prompt_hidden_states, class_pooled_prompt_embeds = compute_text_embeddings(
- args.class_prompt, text_encoders, tokenizers
- )
-
- # Clear the memory here.
- if not args.train_text_encoder:
- del tokenizers, text_encoders
- gc.collect()
- torch.cuda.empty_cache()
-
- # Pack the statically computed variables appropriately. This is so that we don't
- # have to pass them to the dataloader.
- add_time_ids = instance_time_ids
- if args.with_prior_preservation:
- add_time_ids = torch.cat([add_time_ids, class_time_ids], dim=0)
-
- if not args.train_text_encoder:
- prompt_embeds = instance_prompt_hidden_states
- unet_add_text_embeds = instance_pooled_prompt_embeds
- if args.with_prior_preservation:
- prompt_embeds = torch.cat([prompt_embeds, class_prompt_hidden_states], dim=0)
- unet_add_text_embeds = torch.cat([unet_add_text_embeds, class_pooled_prompt_embeds], dim=0)
- else:
- tokens_one = tokenize_prompt(tokenizer_one, args.instance_prompt)
- tokens_two = tokenize_prompt(tokenizer_two, args.instance_prompt)
- if args.with_prior_preservation:
- class_tokens_one = tokenize_prompt(tokenizer_one, args.class_prompt)
- class_tokens_two = tokenize_prompt(tokenizer_two, args.class_prompt)
- tokens_one = torch.cat([tokens_one, class_tokens_one], dim=0)
- tokens_two = torch.cat([tokens_two, class_tokens_two], dim=0)
-
- # Dataset and DataLoaders creation:
- train_dataset = DreamBoothDataset(
- instance_data_root=args.instance_data_dir,
- class_data_root=args.class_data_dir if args.with_prior_preservation else None,
- class_num=args.num_class_images,
- size=args.resolution,
- center_crop=args.center_crop,
- )
-
- train_dataloader = torch.utils.data.DataLoader(
- train_dataset,
- batch_size=args.train_batch_size,
- shuffle=True,
- collate_fn=lambda examples: collate_fn(examples, args.with_prior_preservation),
- num_workers=args.dataloader_num_workers,
- )
-
- # Scheduler and math around the number of training steps.
- overrode_max_train_steps = False
- num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
- if args.max_train_steps is None:
- args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
- overrode_max_train_steps = True
-
- lr_scheduler = get_scheduler(
- args.lr_scheduler,
- optimizer=optimizer,
- num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
- num_training_steps=args.max_train_steps * accelerator.num_processes,
- num_cycles=args.lr_num_cycles,
- power=args.lr_power,
- )
-
- # Prepare everything with our `accelerator`.
- if args.train_text_encoder:
- unet, text_encoder_one, text_encoder_two, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
- unet, text_encoder_one, text_encoder_two, optimizer, train_dataloader, lr_scheduler
- )
- else:
- unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
- unet, optimizer, train_dataloader, lr_scheduler
- )
-
- # We need to recalculate our total training steps as the size of the training dataloader may have changed.
- num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
- if overrode_max_train_steps:
- args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
- # Afterwards we recalculate our number of training epochs
- args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
-
- # We need to initialize the trackers we use, and also store our configuration.
- # The trackers initializes automatically on the main process.
- if accelerator.is_main_process:
- accelerator.init_trackers("dreambooth-lora-sd-xl", config=vars(args))
-
- # Train!
- total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
-
- logger.info("***** Running training *****")
- logger.info(f" Num examples = {len(train_dataset)}")
- logger.info(f" Num batches each epoch = {len(train_dataloader)}")
- logger.info(f" Num Epochs = {args.num_train_epochs}")
- logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
- logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
- logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
- logger.info(f" Total optimization steps = {args.max_train_steps}")
- global_step = 0
- first_epoch = 0
-
- # Potentially load in the weights and states from a previous save
- if args.resume_from_checkpoint:
- if args.resume_from_checkpoint != "latest":
- path = os.path.basename(args.resume_from_checkpoint)
- else:
- # Get the mos recent checkpoint
- dirs = os.listdir(args.output_dir)
- dirs = [d for d in dirs if d.startswith("checkpoint")]
- dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
- path = dirs[-1] if len(dirs) > 0 else None
-
- if path is None:
- accelerator.print(
- f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
- )
- args.resume_from_checkpoint = None
- else:
- accelerator.print(f"Resuming from checkpoint {path}")
- accelerator.load_state(os.path.join(args.output_dir, path))
- global_step = int(path.split("-")[1])
-
- resume_global_step = global_step * args.gradient_accumulation_steps
- first_epoch = global_step // num_update_steps_per_epoch
- resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)
-
- # Only show the progress bar once on each machine.
- progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
- progress_bar.set_description("Steps")
-
- for epoch in range(first_epoch, args.num_train_epochs):
- unet.train()
- if args.train_text_encoder:
- text_encoder_one.train()
- text_encoder_two.train()
- for step, batch in enumerate(train_dataloader):
- # Skip steps until we reach the resumed step
- if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
- if step % args.gradient_accumulation_steps == 0:
- progress_bar.update(1)
- continue
-
- with accelerator.accumulate(unet):
- if args.pretrained_vae_model_name_or_path is None:
- pixel_values = batch["pixel_values"]
- else:
- pixel_values = batch["pixel_values"].to(dtype=weight_dtype)
-
- # Convert images to latent space
- model_input = vae.encode(pixel_values).latent_dist.sample()
- model_input = model_input * vae.config.scaling_factor
- if args.pretrained_vae_model_name_or_path is None:
- model_input = model_input.to(weight_dtype)
-
- # Sample noise that we'll add to the latents
- noise = torch.randn_like(model_input)
- bsz = model_input.shape[0]
- # Sample a random timestep for each image
- timesteps = torch.randint(
- 0, noise_scheduler.config.num_train_timesteps, (bsz,), device=model_input.device
- )
- timesteps = timesteps.long()
-
- # Add noise to the model input according to the noise magnitude at each timestep
- # (this is the forward diffusion process)
- noisy_model_input = noise_scheduler.add_noise(model_input, noise, timesteps)
-
- # Calculate the elements to repeat depending on the use of prior-preservation.
- elems_to_repeat = bsz // 2 if args.with_prior_preservation else bsz
-
- # Predict the noise residual
- if not args.train_text_encoder:
- unet_added_conditions = {
- "time_ids": add_time_ids.repeat(elems_to_repeat, 1),
- "text_embeds": unet_add_text_embeds.repeat(elems_to_repeat, 1),
- }
- prompt_embeds = prompt_embeds.repeat(elems_to_repeat, 1, 1)
- model_pred = unet(
- noisy_model_input,
- timesteps,
- prompt_embeds,
- added_cond_kwargs=unet_added_conditions,
- ).sample
- else:
- unet_added_conditions = {"time_ids": add_time_ids.repeat(elems_to_repeat, 1)}
- prompt_embeds, pooled_prompt_embeds = encode_prompt(
- text_encoders=[text_encoder_one, text_encoder_two],
- tokenizers=None,
- prompt=None,
- text_input_ids_list=[tokens_one, tokens_two],
- )
- unet_added_conditions.update({"text_embeds": pooled_prompt_embeds.repeat(elems_to_repeat, 1)})
- prompt_embeds = prompt_embeds.repeat(elems_to_repeat, 1, 1)
- model_pred = unet(
- noisy_model_input, timesteps, prompt_embeds, added_cond_kwargs=unet_added_conditions
- ).sample
-
- # Get the target for loss depending on the prediction type
- if noise_scheduler.config.prediction_type == "epsilon":
- target = noise
- elif noise_scheduler.config.prediction_type == "v_prediction":
- target = noise_scheduler.get_velocity(model_input, noise, timesteps)
- else:
- raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
-
- if args.with_prior_preservation:
- # Chunk the noise and model_pred into two parts and compute the loss on each part separately.
- model_pred, model_pred_prior = torch.chunk(model_pred, 2, dim=0)
- target, target_prior = torch.chunk(target, 2, dim=0)
-
- # Compute instance loss
- loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
-
- # Compute prior loss
- prior_loss = F.mse_loss(model_pred_prior.float(), target_prior.float(), reduction="mean")
-
- # Add the prior loss to the instance loss.
- loss = loss + args.prior_loss_weight * prior_loss
- else:
- loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
-
- accelerator.backward(loss)
- if accelerator.sync_gradients:
- params_to_clip = (
- itertools.chain(unet_lora_parameters, text_lora_parameters_one, text_lora_parameters_two)
- if args.train_text_encoder
- else unet_lora_parameters
- )
- accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
- optimizer.step()
- lr_scheduler.step()
- optimizer.zero_grad()
-
- # Checks if the accelerator has performed an optimization step behind the scenes
- if accelerator.sync_gradients:
- progress_bar.update(1)
- global_step += 1
-
- if accelerator.is_main_process:
- if global_step % args.checkpointing_steps == 0:
- # _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
- if args.checkpoints_total_limit is not None:
- checkpoints = os.listdir(args.output_dir)
- checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
- checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
-
- # before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
- if len(checkpoints) >= args.checkpoints_total_limit:
- num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
- removing_checkpoints = checkpoints[0:num_to_remove]
-
- logger.info(
- f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
- )
- logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
-
- for removing_checkpoint in removing_checkpoints:
- removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
- shutil.rmtree(removing_checkpoint)
-
- save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
- accelerator.save_state(save_path)
- logger.info(f"Saved state to {save_path}")
-
- logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
- progress_bar.set_postfix(**logs)
- accelerator.log(logs, step=global_step)
-
- if global_step >= args.max_train_steps:
- break
-
- if accelerator.is_main_process:
- if args.validation_prompt is not None and epoch % args.validation_epochs == 0:
- logger.info(
- f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
- f" {args.validation_prompt}."
- )
- # create pipeline
- if not args.train_text_encoder:
- text_encoder_one = text_encoder_cls_one.from_pretrained(
- args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
- )
- text_encoder_two = text_encoder_cls_two.from_pretrained(
- args.pretrained_model_name_or_path, subfolder="text_encoder_2", revision=args.revision
- )
- pipeline = StableDiffusionXLPipeline.from_pretrained(
- args.pretrained_model_name_or_path,
- vae=vae,
- text_encoder=accelerator.unwrap_model(text_encoder_one),
- text_encoder_2=accelerator.unwrap_model(text_encoder_two),
- unet=accelerator.unwrap_model(unet),
- revision=args.revision,
- torch_dtype=weight_dtype,
- )
-
- # We train on the simplified learning objective. If we were previously predicting a variance, we need the scheduler to ignore it
- scheduler_args = {}
-
- if "variance_type" in pipeline.scheduler.config:
- variance_type = pipeline.scheduler.config.variance_type
-
- if variance_type in ["learned", "learned_range"]:
- variance_type = "fixed_small"
-
- scheduler_args["variance_type"] = variance_type
-
- pipeline.scheduler = DPMSolverMultistepScheduler.from_config(
- pipeline.scheduler.config, **scheduler_args
- )
-
- pipeline = pipeline.to(accelerator.device)
- pipeline.set_progress_bar_config(disable=True)
-
- # run inference
- generator = torch.Generator(device=accelerator.device).manual_seed(args.seed) if args.seed else None
- pipeline_args = {"prompt": args.validation_prompt}
-
- with torch.cuda.amp.autocast():
- images = [
- pipeline(**pipeline_args, generator=generator).images[0]
- for _ in range(args.num_validation_images)
- ]
-
- for tracker in accelerator.trackers:
- if tracker.name == "tensorboard":
- np_images = np.stack([np.asarray(img) for img in images])
- tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
- if tracker.name == "wandb":
- tracker.log(
- {
- "validation": [
- wandb.Image(image, caption=f"{i}: {args.validation_prompt}")
- for i, image in enumerate(images)
- ]
- }
- )
-
- del pipeline
- torch.cuda.empty_cache()
-
- # Save the lora layers
- accelerator.wait_for_everyone()
- if accelerator.is_main_process:
- unet = accelerator.unwrap_model(unet)
- unet = unet.to(torch.float32)
- unet_lora_layers = unet_attn_processors_state_dict(unet)
-
- if args.train_text_encoder:
- text_encoder_one = accelerator.unwrap_model(text_encoder_one)
- text_encoder_lora_layers = text_encoder_lora_state_dict(text_encoder_one.to(torch.float32))
- text_encoder_two = accelerator.unwrap_model(text_encoder_two)
- text_encoder_2_lora_layers = text_encoder_lora_state_dict(text_encoder_two.to(torch.float32))
- else:
- text_encoder_lora_layers = None
- text_encoder_2_lora_layers = None
-
- StableDiffusionXLPipeline.save_lora_weights(
- save_directory=args.output_dir,
- unet_lora_layers=unet_lora_layers,
- text_encoder_lora_layers=text_encoder_lora_layers,
- text_encoder_2_lora_layers=text_encoder_2_lora_layers,
- )
-
- # Final inference
- # Load previous pipeline
- vae = AutoencoderKL.from_pretrained(
- vae_path,
- subfolder="vae" if args.pretrained_vae_model_name_or_path is None else None,
- revision=args.revision,
- torch_dtype=weight_dtype,
- )
- pipeline = StableDiffusionXLPipeline.from_pretrained(
- args.pretrained_model_name_or_path, vae=vae, revision=args.revision, torch_dtype=weight_dtype
- )
-
- # We train on the simplified learning objective. If we were previously predicting a variance, we need the scheduler to ignore it
- scheduler_args = {}
-
- if "variance_type" in pipeline.scheduler.config:
- variance_type = pipeline.scheduler.config.variance_type
-
- if variance_type in ["learned", "learned_range"]:
- variance_type = "fixed_small"
-
- scheduler_args["variance_type"] = variance_type
-
- pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config, **scheduler_args)
-
- pipeline = pipeline.to(accelerator.device)
-
- # load attention processors
- pipeline.load_lora_weights(args.output_dir)
-
- # run inference
- images = []
- if args.validation_prompt and args.num_validation_images > 0:
- generator = torch.Generator(device=accelerator.device).manual_seed(args.seed) if args.seed else None
- images = [
- pipeline(args.validation_prompt, num_inference_steps=25, generator=generator).images[0]
- for _ in range(args.num_validation_images)
- ]
-
- for tracker in accelerator.trackers:
- if tracker.name == "tensorboard":
- np_images = np.stack([np.asarray(img) for img in images])
- tracker.writer.add_images("test", np_images, epoch, dataformats="NHWC")
- if tracker.name == "wandb":
- tracker.log(
- {
- "test": [
- wandb.Image(image, caption=f"{i}: {args.validation_prompt}")
- for i, image in enumerate(images)
- ]
- }
- )
-
- if args.push_to_hub:
- save_model_card(
- repo_id,
- images=images,
- base_model=args.pretrained_model_name_or_path,
- train_text_encoder=args.train_text_encoder,
- prompt=args.instance_prompt,
- repo_folder=args.output_dir,
- vae_path=args.pretrained_vae_model_name_or_path,
- )
- upload_folder(
- repo_id=repo_id,
- folder_path=args.output_dir,
- commit_message="End of training",
- ignore_patterns=["step_*", "epoch_*"],
- )
-
- accelerator.end_training()
-
-
-if __name__ == "__main__":
- args = parse_args()
- main(args)
diff --git a/spaces/Andy1621/uniformer_image_detection/configs/vfnet/vfnet_r101_fpn_mstrain_2x_coco.py b/spaces/Andy1621/uniformer_image_detection/configs/vfnet/vfnet_r101_fpn_mstrain_2x_coco.py
deleted file mode 100644
index be7f075fea00a4570d50fd30f1685139b70a8bb6..0000000000000000000000000000000000000000
--- a/spaces/Andy1621/uniformer_image_detection/configs/vfnet/vfnet_r101_fpn_mstrain_2x_coco.py
+++ /dev/null
@@ -1,2 +0,0 @@
-_base_ = './vfnet_r50_fpn_mstrain_2x_coco.py'
-model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101))
diff --git a/spaces/Andy1621/uniformer_image_detection/mmdet/core/evaluation/__init__.py b/spaces/Andy1621/uniformer_image_detection/mmdet/core/evaluation/__init__.py
deleted file mode 100644
index d11ef15b9db95166b4427ad4d08debbd0630a741..0000000000000000000000000000000000000000
--- a/spaces/Andy1621/uniformer_image_detection/mmdet/core/evaluation/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from .class_names import (cityscapes_classes, coco_classes, dataset_aliases,
- get_classes, imagenet_det_classes,
- imagenet_vid_classes, voc_classes)
-from .eval_hooks import DistEvalHook, EvalHook
-from .mean_ap import average_precision, eval_map, print_map_summary
-from .recall import (eval_recalls, plot_iou_recall, plot_num_recall,
- print_recall_summary)
-
-__all__ = [
- 'voc_classes', 'imagenet_det_classes', 'imagenet_vid_classes',
- 'coco_classes', 'cityscapes_classes', 'dataset_aliases', 'get_classes',
- 'DistEvalHook', 'EvalHook', 'average_precision', 'eval_map',
- 'print_map_summary', 'eval_recalls', 'print_recall_summary',
- 'plot_num_recall', 'plot_iou_recall'
-]
diff --git a/spaces/Andy1621/uniformer_image_detection/mmdet/models/dense_heads/ssd_head.py b/spaces/Andy1621/uniformer_image_detection/mmdet/models/dense_heads/ssd_head.py
deleted file mode 100644
index 145622b64e3f0b3f7f518fc61a2a01348ebfa4f3..0000000000000000000000000000000000000000
--- a/spaces/Andy1621/uniformer_image_detection/mmdet/models/dense_heads/ssd_head.py
+++ /dev/null
@@ -1,265 +0,0 @@
-import torch
-import torch.nn as nn
-import torch.nn.functional as F
-from mmcv.cnn import xavier_init
-from mmcv.runner import force_fp32
-
-from mmdet.core import (build_anchor_generator, build_assigner,
- build_bbox_coder, build_sampler, multi_apply)
-from ..builder import HEADS
-from ..losses import smooth_l1_loss
-from .anchor_head import AnchorHead
-
-
-# TODO: add loss evaluator for SSD
-@HEADS.register_module()
-class SSDHead(AnchorHead):
- """SSD head used in https://arxiv.org/abs/1512.02325.
-
- Args:
- num_classes (int): Number of categories excluding the background
- category.
- in_channels (int): Number of channels in the input feature map.
- anchor_generator (dict): Config dict for anchor generator
- bbox_coder (dict): Config of bounding box coder.
- reg_decoded_bbox (bool): If true, the regression loss would be
- applied directly on decoded bounding boxes, converting both
- the predicted boxes and regression targets to absolute
- coordinates format. Default False. It should be `True` when
- using `IoULoss`, `GIoULoss`, or `DIoULoss` in the bbox head.
- train_cfg (dict): Training config of anchor head.
- test_cfg (dict): Testing config of anchor head.
- """ # noqa: W605
-
- def __init__(self,
- num_classes=80,
- in_channels=(512, 1024, 512, 256, 256, 256),
- anchor_generator=dict(
- type='SSDAnchorGenerator',
- scale_major=False,
- input_size=300,
- strides=[8, 16, 32, 64, 100, 300],
- ratios=([2], [2, 3], [2, 3], [2, 3], [2], [2]),
- basesize_ratio_range=(0.1, 0.9)),
- bbox_coder=dict(
- type='DeltaXYWHBBoxCoder',
- clip_border=True,
- target_means=[.0, .0, .0, .0],
- target_stds=[1.0, 1.0, 1.0, 1.0],
- ),
- reg_decoded_bbox=False,
- train_cfg=None,
- test_cfg=None):
- super(AnchorHead, self).__init__()
- self.num_classes = num_classes
- self.in_channels = in_channels
- self.cls_out_channels = num_classes + 1 # add background class
- self.anchor_generator = build_anchor_generator(anchor_generator)
- num_anchors = self.anchor_generator.num_base_anchors
-
- reg_convs = []
- cls_convs = []
- for i in range(len(in_channels)):
- reg_convs.append(
- nn.Conv2d(
- in_channels[i],
- num_anchors[i] * 4,
- kernel_size=3,
- padding=1))
- cls_convs.append(
- nn.Conv2d(
- in_channels[i],
- num_anchors[i] * (num_classes + 1),
- kernel_size=3,
- padding=1))
- self.reg_convs = nn.ModuleList(reg_convs)
- self.cls_convs = nn.ModuleList(cls_convs)
-
- self.bbox_coder = build_bbox_coder(bbox_coder)
- self.reg_decoded_bbox = reg_decoded_bbox
- self.use_sigmoid_cls = False
- self.cls_focal_loss = False
- self.train_cfg = train_cfg
- self.test_cfg = test_cfg
- # set sampling=False for archor_target
- self.sampling = False
- if self.train_cfg:
- self.assigner = build_assigner(self.train_cfg.assigner)
- # SSD sampling=False so use PseudoSampler
- sampler_cfg = dict(type='PseudoSampler')
- self.sampler = build_sampler(sampler_cfg, context=self)
- self.fp16_enabled = False
-
- def init_weights(self):
- """Initialize weights of the head."""
- for m in self.modules():
- if isinstance(m, nn.Conv2d):
- xavier_init(m, distribution='uniform', bias=0)
-
- def forward(self, feats):
- """Forward features from the upstream network.
-
- Args:
- feats (tuple[Tensor]): Features from the upstream network, each is
- a 4D-tensor.
-
- Returns:
- tuple:
- cls_scores (list[Tensor]): Classification scores for all scale
- levels, each is a 4D-tensor, the channels number is
- num_anchors * num_classes.
- bbox_preds (list[Tensor]): Box energies / deltas for all scale
- levels, each is a 4D-tensor, the channels number is
- num_anchors * 4.
- """
- cls_scores = []
- bbox_preds = []
- for feat, reg_conv, cls_conv in zip(feats, self.reg_convs,
- self.cls_convs):
- cls_scores.append(cls_conv(feat))
- bbox_preds.append(reg_conv(feat))
- return cls_scores, bbox_preds
-
- def loss_single(self, cls_score, bbox_pred, anchor, labels, label_weights,
- bbox_targets, bbox_weights, num_total_samples):
- """Compute loss of a single image.
-
- Args:
- cls_score (Tensor): Box scores for eachimage
- Has shape (num_total_anchors, num_classes).
- bbox_pred (Tensor): Box energies / deltas for each image
- level with shape (num_total_anchors, 4).
- anchors (Tensor): Box reference for each scale level with shape
- (num_total_anchors, 4).
- labels (Tensor): Labels of each anchors with shape
- (num_total_anchors,).
- label_weights (Tensor): Label weights of each anchor with shape
- (num_total_anchors,)
- bbox_targets (Tensor): BBox regression targets of each anchor wight
- shape (num_total_anchors, 4).
- bbox_weights (Tensor): BBox regression loss weights of each anchor
- with shape (num_total_anchors, 4).
- num_total_samples (int): If sampling, num total samples equal to
- the number of total anchors; Otherwise, it is the number of
- positive anchors.
-
- Returns:
- dict[str, Tensor]: A dictionary of loss components.
- """
-
- loss_cls_all = F.cross_entropy(
- cls_score, labels, reduction='none') * label_weights
- # FG cat_id: [0, num_classes -1], BG cat_id: num_classes
- pos_inds = ((labels >= 0) &
- (labels < self.num_classes)).nonzero().reshape(-1)
- neg_inds = (labels == self.num_classes).nonzero().view(-1)
-
- num_pos_samples = pos_inds.size(0)
- num_neg_samples = self.train_cfg.neg_pos_ratio * num_pos_samples
- if num_neg_samples > neg_inds.size(0):
- num_neg_samples = neg_inds.size(0)
- topk_loss_cls_neg, _ = loss_cls_all[neg_inds].topk(num_neg_samples)
- loss_cls_pos = loss_cls_all[pos_inds].sum()
- loss_cls_neg = topk_loss_cls_neg.sum()
- loss_cls = (loss_cls_pos + loss_cls_neg) / num_total_samples
-
- if self.reg_decoded_bbox:
- # When the regression loss (e.g. `IouLoss`, `GIouLoss`)
- # is applied directly on the decoded bounding boxes, it
- # decodes the already encoded coordinates to absolute format.
- bbox_pred = self.bbox_coder.decode(anchor, bbox_pred)
-
- loss_bbox = smooth_l1_loss(
- bbox_pred,
- bbox_targets,
- bbox_weights,
- beta=self.train_cfg.smoothl1_beta,
- avg_factor=num_total_samples)
- return loss_cls[None], loss_bbox
-
- @force_fp32(apply_to=('cls_scores', 'bbox_preds'))
- def loss(self,
- cls_scores,
- bbox_preds,
- gt_bboxes,
- gt_labels,
- img_metas,
- gt_bboxes_ignore=None):
- """Compute losses of the head.
-
- Args:
- cls_scores (list[Tensor]): Box scores for each scale level
- Has shape (N, num_anchors * num_classes, H, W)
- bbox_preds (list[Tensor]): Box energies / deltas for each scale
- level with shape (N, num_anchors * 4, H, W)
- gt_bboxes (list[Tensor]): each item are the truth boxes for each
- image in [tl_x, tl_y, br_x, br_y] format.
- gt_labels (list[Tensor]): class indices corresponding to each box
- img_metas (list[dict]): Meta information of each image, e.g.,
- image size, scaling factor, etc.
- gt_bboxes_ignore (None | list[Tensor]): specify which bounding
- boxes can be ignored when computing the loss.
-
- Returns:
- dict[str, Tensor]: A dictionary of loss components.
- """
- featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]
- assert len(featmap_sizes) == self.anchor_generator.num_levels
-
- device = cls_scores[0].device
-
- anchor_list, valid_flag_list = self.get_anchors(
- featmap_sizes, img_metas, device=device)
- cls_reg_targets = self.get_targets(
- anchor_list,
- valid_flag_list,
- gt_bboxes,
- img_metas,
- gt_bboxes_ignore_list=gt_bboxes_ignore,
- gt_labels_list=gt_labels,
- label_channels=1,
- unmap_outputs=False)
- if cls_reg_targets is None:
- return None
- (labels_list, label_weights_list, bbox_targets_list, bbox_weights_list,
- num_total_pos, num_total_neg) = cls_reg_targets
-
- num_images = len(img_metas)
- all_cls_scores = torch.cat([
- s.permute(0, 2, 3, 1).reshape(
- num_images, -1, self.cls_out_channels) for s in cls_scores
- ], 1)
- all_labels = torch.cat(labels_list, -1).view(num_images, -1)
- all_label_weights = torch.cat(label_weights_list,
- -1).view(num_images, -1)
- all_bbox_preds = torch.cat([
- b.permute(0, 2, 3, 1).reshape(num_images, -1, 4)
- for b in bbox_preds
- ], -2)
- all_bbox_targets = torch.cat(bbox_targets_list,
- -2).view(num_images, -1, 4)
- all_bbox_weights = torch.cat(bbox_weights_list,
- -2).view(num_images, -1, 4)
-
- # concat all level anchors to a single tensor
- all_anchors = []
- for i in range(num_images):
- all_anchors.append(torch.cat(anchor_list[i]))
-
- # check NaN and Inf
- assert torch.isfinite(all_cls_scores).all().item(), \
- 'classification scores become infinite or NaN!'
- assert torch.isfinite(all_bbox_preds).all().item(), \
- 'bbox predications become infinite or NaN!'
-
- losses_cls, losses_bbox = multi_apply(
- self.loss_single,
- all_cls_scores,
- all_bbox_preds,
- all_anchors,
- all_labels,
- all_label_weights,
- all_bbox_targets,
- all_bbox_weights,
- num_total_samples=num_total_pos)
- return dict(loss_cls=losses_cls, loss_bbox=losses_bbox)
diff --git a/spaces/Andy1621/uniformer_image_segmentation/configs/fp16/fcn_r101-d8_512x1024_80k_fp16_cityscapes.py b/spaces/Andy1621/uniformer_image_segmentation/configs/fp16/fcn_r101-d8_512x1024_80k_fp16_cityscapes.py
deleted file mode 100644
index 8e85e56bd66aa61c3d43547acb7c2d6d91f14133..0000000000000000000000000000000000000000
--- a/spaces/Andy1621/uniformer_image_segmentation/configs/fp16/fcn_r101-d8_512x1024_80k_fp16_cityscapes.py
+++ /dev/null
@@ -1,5 +0,0 @@
-_base_ = '../fcn/fcn_r101-d8_512x1024_80k_cityscapes.py'
-# fp16 settings
-optimizer_config = dict(type='Fp16OptimizerHook', loss_scale=512.)
-# fp16 placeholder
-fp16 = dict()
diff --git a/spaces/Anonymous-sub/Rerender/ControlNet/annotator/mlsd/__init__.py b/spaces/Anonymous-sub/Rerender/ControlNet/annotator/mlsd/__init__.py
deleted file mode 100644
index c1860702df6150c5a93c9bb6bf34906a77048c7c..0000000000000000000000000000000000000000
--- a/spaces/Anonymous-sub/Rerender/ControlNet/annotator/mlsd/__init__.py
+++ /dev/null
@@ -1,43 +0,0 @@
-# MLSD Line Detection
-# From https://github.com/navervision/mlsd
-# Apache-2.0 license
-
-import cv2
-import numpy as np
-import torch
-import os
-
-from einops import rearrange
-from .models.mbv2_mlsd_tiny import MobileV2_MLSD_Tiny
-from .models.mbv2_mlsd_large import MobileV2_MLSD_Large
-from .utils import pred_lines
-
-from annotator.util import annotator_ckpts_path
-
-
-remote_model_path = "https://huggingface.co/lllyasviel/ControlNet/resolve/main/annotator/ckpts/mlsd_large_512_fp32.pth"
-
-
-class MLSDdetector:
- def __init__(self):
- model_path = os.path.join(annotator_ckpts_path, "mlsd_large_512_fp32.pth")
- if not os.path.exists(model_path):
- from basicsr.utils.download_util import load_file_from_url
- load_file_from_url(remote_model_path, model_dir=annotator_ckpts_path)
- model = MobileV2_MLSD_Large()
- model.load_state_dict(torch.load(model_path), strict=True)
- self.model = model.cuda().eval()
-
- def __call__(self, input_image, thr_v, thr_d):
- assert input_image.ndim == 3
- img = input_image
- img_output = np.zeros_like(img)
- try:
- with torch.no_grad():
- lines = pred_lines(img, self.model, [img.shape[0], img.shape[1]], thr_v, thr_d)
- for line in lines:
- x_start, y_start, x_end, y_end = [int(val) for val in line]
- cv2.line(img_output, (x_start, y_start), (x_end, y_end), [255, 255, 255], 1)
- except Exception as e:
- pass
- return img_output[:, :, 0]
diff --git a/spaces/AnthonyTruchetPoC/persistent-docker/Dockerfile b/spaces/AnthonyTruchetPoC/persistent-docker/Dockerfile
deleted file mode 100644
index 18d549e85f3e86f7d1fb1453614fc11f7f10b53e..0000000000000000000000000000000000000000
--- a/spaces/AnthonyTruchetPoC/persistent-docker/Dockerfile
+++ /dev/null
@@ -1,100 +0,0 @@
-# syntax=docker/dockerfile:1
-FROM python:3.10.12
-
-ARG APP_HOME=/home/user
-ARG APP_CODE=/opt/code
-ARG APP_DATA=/data/app
-ARG HF_HOME=/data/huggingface
-
-ENV APP_CODE=$APP_CODE \
- APP_DATA=$APP_DATA \
- HF_HOME=$HF_HOME
-
-ENV PYTHONUNBUFFERED=1 \
- SYSTEM=spaces \
- SHELL=/bin/bash
-
-# Remove any third-party apt sources to avoid issues with expiring keys.
-# Install some basic utilities
-RUN rm -f /etc/apt/sources.list.d/*.list && \
- apt-get update && apt-get install -y --no-install-recommends \
- curl \
- ca-certificates \
- sudo \
- git \
- git-lfs \
- zip \
- unzip \
- htop \
- bzip2 \
- libx11-6 \
- build-essential \
- libsndfile-dev \
- software-properties-common \
- nodejs \
- && rm -rf /var/lib/apt/lists/*
-
-WORKDIR /opt
-
-# Create a non-root user and switch to it
-RUN adduser --disabled-password --gecos '' --shell /bin/bash -u 1000 user \
- && chown -R user:user /opt
-RUN echo "user ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
-USER user
-
-# All users can use /home/user as their home directory
-ENV HOME=$APP_HOME
-ENV PATH=$HOME/.local/bin:$PATH
-RUN mkdir -p $HOME/.cache $HOME/.config \
- && chmod -R 777 $HOME
-
-#######################################
-# Start root user section
-#######################################
-USER root
-
-# User Debian packages
-## Security warning : Potential user code executed as root (build time)
-RUN --mount=target=/root/packages.txt,source=packages.txt \
- apt-get update \
- && xargs -r -a /root/packages.txt apt-get install -y --no-install-recommends \
- && rm -rf /var/lib/apt/lists/*
-
-RUN --mount=target=/root/on_startup.sh,source=on_startup.sh,readwrite \
- bash /root/on_startup.sh
-
-#######################################
-# End root user section
-#######################################
-USER user
-WORKDIR $APP_HOME
-
-RUN --mount=target=$APP_CODE/requirements.txt,source=requirements.txt \
- pip3 install --no-cache-dir --upgrade pip \
- && pip install --no-cache-dir --upgrade -r $APP_CODE/requirements.txt
-
-# Copy our code to $APP_CODE and config
-COPY --chown=user:user --chmod=u=rX src/ $APP_CODE/
-
-COPY --chown=user ./start_*.sh $APP_HOME
-RUN chmod +x $APP_HOME/start_*.sh
-
-COPY --chown=user:user --chmod=u=rX .streamlit/ $APP_HOME/.streamlit/
-
-# Persistent disk space
-# Assumes a mount is passed to the docker command, like:
-# $ docker ... --mount type=volume,src=ai-playground-vol,dst=/data ...
-# see https://huggingface.co/docs/hub/spaces-storage
-VOLUME /data
-
-ENV PYTHONPATH=$APP_CODE:$PYTHONPATH
-
-RUN ln -s $APP_DATA/ data
-RUN ln -s $APP_CODE/ code
-ADD jupyter/notebooks notebooks
-
-# Expose streamlit application
-EXPOSE 8501
-EXPOSE 7860
-ENTRYPOINT [ "bash", "-o", "allexport" ]
-CMD [ "-f", "./start_server.sh" ]
diff --git a/spaces/Apex-X/nono/roop/processors/frame/face_enhancer.py b/spaces/Apex-X/nono/roop/processors/frame/face_enhancer.py
deleted file mode 100644
index 3a7f5a217f1e7f3f6d23f42fcbe97145d0ce1c2d..0000000000000000000000000000000000000000
--- a/spaces/Apex-X/nono/roop/processors/frame/face_enhancer.py
+++ /dev/null
@@ -1,104 +0,0 @@
-from typing import Any, List, Callable
-import cv2
-import threading
-from gfpgan.utils import GFPGANer
-
-import roop.globals
-import roop.processors.frame.core
-from roop.core import update_status
-from roop.face_analyser import get_many_faces
-from roop.typing import Frame, Face
-from roop.utilities import conditional_download, resolve_relative_path, is_image, is_video
-
-FACE_ENHANCER = None
-THREAD_SEMAPHORE = threading.Semaphore()
-THREAD_LOCK = threading.Lock()
-NAME = 'ROOP.FACE-ENHANCER'
-
-
-def get_face_enhancer() -> Any:
- global FACE_ENHANCER
-
- with THREAD_LOCK:
- if FACE_ENHANCER is None:
- model_path = resolve_relative_path('../models/GFPGANv1.4.pth')
- # todo: set models path -> https://github.com/TencentARC/GFPGAN/issues/399
- FACE_ENHANCER = GFPGANer(model_path=model_path, upscale=1, device=get_device())
- return FACE_ENHANCER
-
-
-def get_device() -> str:
- if 'CUDAExecutionProvider' in roop.globals.execution_providers:
- return 'cuda'
- if 'CoreMLExecutionProvider' in roop.globals.execution_providers:
- return 'mps'
- return 'cpu'
-
-
-def clear_face_enhancer() -> None:
- global FACE_ENHANCER
-
- FACE_ENHANCER = None
-
-
-def pre_check() -> bool:
- download_directory_path = resolve_relative_path('../models')
- conditional_download(download_directory_path, ['https://huggingface.co/henryruhs/roop/resolve/main/GFPGANv1.4.pth'])
- return True
-
-
-def pre_start() -> bool:
- if not is_image(roop.globals.target_path) and not is_video(roop.globals.target_path):
- update_status('Select an image or video for target path.', NAME)
- return False
- return True
-
-
-def post_process() -> None:
- clear_face_enhancer()
-
-
-def enhance_face(target_face: Face, temp_frame: Frame) -> Frame:
- start_x, start_y, end_x, end_y = map(int, target_face['bbox'])
- padding_x = int((end_x - start_x) * 0.5)
- padding_y = int((end_y - start_y) * 0.5)
- start_x = max(0, start_x - padding_x)
- start_y = max(0, start_y - padding_y)
- end_x = max(0, end_x + padding_x)
- end_y = max(0, end_y + padding_y)
- temp_face = temp_frame[start_y:end_y, start_x:end_x]
- if temp_face.size:
- with THREAD_SEMAPHORE:
- _, _, temp_face = get_face_enhancer().enhance(
- temp_face,
- paste_back=True
- )
- temp_frame[start_y:end_y, start_x:end_x] = temp_face
- return temp_frame
-
-
-def process_frame(source_face: Face, reference_face: Face, temp_frame: Frame) -> Frame:
- many_faces = get_many_faces(temp_frame)
- if many_faces:
- for target_face in many_faces:
- temp_frame = enhance_face(target_face, temp_frame)
- return temp_frame
-
-
-def process_frames(source_path: str, temp_frame_paths: List[str], update: Callable[[], None]) -> None:
- for temp_frame_path in temp_frame_paths:
- temp_frame = cv2.imread(temp_frame_path)
- result = process_frame(None, None, temp_frame)
- cv2.imwrite(temp_frame_path, result)
- if update:
- update()
-
-
-def process_image(source_path: str, target_path: str, output_path: str) -> None:
- target_frame = cv2.imread(target_path)
- result = process_frame(None, None, target_frame)
- cv2.imwrite(output_path, result)
-
-
-def process_video(source_path: str, temp_frame_paths: List[str]) -> None:
- roop.processors.frame.core.process_video(None, temp_frame_paths, process_frames)
diff --git a/spaces/Audiogen/vector-search-demo/app.py b/spaces/Audiogen/vector-search-demo/app.py
deleted file mode 100644
index 64f2f37b4effd91de6b23e383d010d23f86839f9..0000000000000000000000000000000000000000
--- a/spaces/Audiogen/vector-search-demo/app.py
+++ /dev/null
@@ -1,144 +0,0 @@
-from transformers import ClapModel, ClapProcessor, AutoFeatureExtractor
-import gradio as gr
-import torch
-import torchaudio
-import os
-import numpy as np
-from qdrant_client import QdrantClient
-from qdrant_client.http.models import Distance, VectorParams
-from qdrant_client.http import models
-
-
-import dotenv
-dotenv.load_dotenv()
-
-
-class ClapSSGradio():
-
- def __init__(
- self,
- name,
- model = "clap-2",
- k=10,
- ):
-
- self.name = name
- self.k = k
-
- self.model = ClapModel.from_pretrained(
- f"Audiogen/{model}", use_auth_token=os.getenv('HUGGINGFACE_API_TOKEN'))
- self.processor = ClapProcessor.from_pretrained(
- f"Audiogen/{model}", use_auth_token=os.getenv('HUGGINGFACE_API_TOKEN'))
-
- self.sas_token = os.environ['AZURE_SAS_TOKEN']
- self.account_name = 'Audiogen'
- self.storage_name = 'audiogentrainingdataeun'
-
- self._start_qdrant()
-
- def _start_qdrant(self):
- self.client = QdrantClient(url=os.getenv(
- "QDRANT_URL"), api_key=os.getenv('QDRANT_API_KEY'))
- # print(self.client.get_collection(collection_name=self.name))
-
- @torch.no_grad()
- def _embed_query(self, query, audio_file):
- if audio_file is not None:
- waveform, sample_rate = torchaudio.load(audio_file.name)
- print("Waveform shape:", waveform.shape)
- waveform = torchaudio.functional.resample(
- waveform, sample_rate, 48000)
- print("Resampled waveform shape:", waveform.shape)
-
- if waveform.shape[-1] < 480000:
- waveform = torch.nn.functional.pad(
- waveform, (0, 48000 - waveform.shape[-1]))
- elif waveform.shape[-1] > 480000:
- waveform = waveform[..., :480000]
-
- audio_prompt_features = self.processor(
- audios=waveform.mean(0), return_tensors='pt', sampling_rate=48000
- )['input_features']
- print("Audio prompt features shape:", audio_prompt_features.shape)
- e = self.model.get_audio_features(
- input_features=audio_prompt_features)[0]
-
- if any(torch.isnan(e)):
- raise ValueError("Audio features are NaN")
- print("Embeddings: ", e.shape)
- return e
- else:
- inputs = self.processor(
- query, return_tensors="pt", padding='max_length', max_length=77, truncation=True)
-
- return self.model.get_text_features(**inputs).cpu().numpy().tolist()[0]
-
- def _similarity_search(self, query, threshold, audio_file):
- results = self.client.search(
- collection_name=self.name,
- query_vector=self._embed_query(query, audio_file),
- limit=self.k,
- score_threshold=threshold,
- )
-
- containers = [result.payload['container'] for result in results]
- filenames = [result.id for result in results]
- captions = [result.payload['caption'] for result in results]
- scores = [result.score for result in results]
-
- # print to stdout
- print(f"\nQuery: {query}\n")
- for i, (container, filename, caption, score) in enumerate(zip(containers, filenames, captions, scores)):
- print(f"{i}: {container} - {caption}. Score: {score}")
-
- waveforms = self._download_results(containers, filenames)
-
- if len(waveforms) == 0:
- print("\nNo results found")
-
- if len(waveforms) < self.k:
- waveforms.extend([(int(48000), np.zeros((480000, 2)))
- for _ in range(self.k - len(waveforms))])
-
- return waveforms
-
- def _download_results(self, containers: list, filenames: list):
-
-
-
- # construct url
- urls = [f"https://{self.storage_name}.blob.core.windows.net/snake/{file_name}.flac?{self.sas_token}" for file_name in filenames]
-
- # make requests
- waveforms = []
- for url in urls:
- waveform, sample_rate = torchaudio.load(url)
- waveforms.append(tuple([sample_rate, waveform.numpy().T]))
-
- return waveforms
-
- def launch(self, share=False):
- # gradio app structure
- with gr.Blocks(title='Clap Semantic Search') as ui:
- with gr.Row():
- with gr.Column(variant='panel'):
- search = gr.Textbox(placeholder='Search Samples')
- float_input = gr.Number(
- label='Similarity threshold [min: 0.1 max: 1]', value=0.5, minimum=0.1, maximum=1)
- audio_file = gr.File(
- label='Upload an Audio File', type="file")
- search_button = gr.Button("Search", label='Search')
- with gr.Column():
- audioboxes = []
- gr.Markdown("Output")
- for i in range(self.k):
- t = gr.components.Audio(label=f"{i}", visible=True)
- audioboxes.append(t)
- search_button.click(fn=self._similarity_search, inputs=[
- search, float_input, audio_file], outputs=audioboxes)
- ui.launch(share=share)
-
-
-if __name__ == "__main__":
- app = ClapSSGradio("demo")
- app.launch(share=False)
diff --git a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/tests/data/test_dataset.py b/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/tests/data/test_dataset.py
deleted file mode 100644
index 7d16ec4c63113e105cd2c2ea7a727a30656fc738..0000000000000000000000000000000000000000
--- a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/tests/data/test_dataset.py
+++ /dev/null
@@ -1,134 +0,0 @@
-# Copyright (c) Facebook, Inc. and its affiliates.
-
-import os
-import pickle
-import sys
-import unittest
-from functools import partial
-import torch
-from iopath.common.file_io import LazyPath
-
-from detectron2 import model_zoo
-from detectron2.config import instantiate
-from detectron2.data import (
- DatasetFromList,
- MapDataset,
- ToIterableDataset,
- build_batch_data_loader,
- build_detection_test_loader,
- build_detection_train_loader,
-)
-from detectron2.data.samplers import InferenceSampler, TrainingSampler
-
-
-def _a_slow_func(x):
- return "path/{}".format(x)
-
-
-class TestDatasetFromList(unittest.TestCase):
- # Failing for py3.6, likely due to pickle
- @unittest.skipIf(sys.version_info.minor <= 6, "Not supported in Python 3.6")
- def test_using_lazy_path(self):
- dataset = []
- for i in range(10):
- dataset.append({"file_name": LazyPath(partial(_a_slow_func, i))})
-
- dataset = DatasetFromList(dataset)
- for i in range(10):
- path = dataset[i]["file_name"]
- self.assertTrue(isinstance(path, LazyPath))
- self.assertEqual(os.fspath(path), _a_slow_func(i))
-
-
-class TestMapDataset(unittest.TestCase):
- @staticmethod
- def map_func(x):
- if x == 2:
- return None
- return x * 2
-
- def test_map_style(self):
- ds = DatasetFromList([1, 2, 3])
- ds = MapDataset(ds, TestMapDataset.map_func)
- self.assertEqual(ds[0], 2)
- self.assertEqual(ds[2], 6)
- self.assertIn(ds[1], [2, 6])
-
- def test_iter_style(self):
- class DS(torch.utils.data.IterableDataset):
- def __iter__(self):
- yield from [1, 2, 3]
-
- ds = DS()
- ds = MapDataset(ds, TestMapDataset.map_func)
- self.assertIsInstance(ds, torch.utils.data.IterableDataset)
-
- data = list(iter(ds))
- self.assertEqual(data, [2, 6])
-
- def test_pickleability(self):
- ds = DatasetFromList([1, 2, 3])
- ds = MapDataset(ds, lambda x: x * 2)
- ds = pickle.loads(pickle.dumps(ds))
- self.assertEqual(ds[0], 2)
-
-
-class TestDataLoader(unittest.TestCase):
- def _get_kwargs(self):
- # get kwargs of build_detection_train_loader
- cfg = model_zoo.get_config("common/data/coco.py").dataloader.train
- cfg.dataset.names = "coco_2017_val_100"
- cfg.pop("_target_")
- kwargs = {k: instantiate(v) for k, v in cfg.items()}
- return kwargs
-
- def test_build_dataloader_train(self):
- kwargs = self._get_kwargs()
- dl = build_detection_train_loader(**kwargs)
- next(iter(dl))
-
- def test_build_iterable_dataloader_train(self):
- kwargs = self._get_kwargs()
- ds = DatasetFromList(kwargs.pop("dataset"))
- ds = ToIterableDataset(ds, TrainingSampler(len(ds)))
- dl = build_detection_train_loader(dataset=ds, **kwargs)
- next(iter(dl))
-
- def _check_is_range(self, data_loader, N):
- # check that data_loader produces range(N)
- data = list(iter(data_loader))
- data = [x for batch in data for x in batch] # flatten the batches
- self.assertEqual(len(data), N)
- self.assertEqual(set(data), set(range(N)))
-
- def test_build_batch_dataloader_inference(self):
- # Test that build_batch_data_loader can be used for inference
- N = 96
- ds = DatasetFromList(list(range(N)))
- sampler = InferenceSampler(len(ds))
- dl = build_batch_data_loader(ds, sampler, 8, num_workers=3)
- self._check_is_range(dl, N)
-
- def test_build_dataloader_inference(self):
- N = 50
- ds = DatasetFromList(list(range(N)))
- sampler = InferenceSampler(len(ds))
- # test that parallel loader works correctly
- dl = build_detection_test_loader(
- dataset=ds, sampler=sampler, mapper=lambda x: x, num_workers=3
- )
- self._check_is_range(dl, N)
-
- # test that batch_size works correctly
- dl = build_detection_test_loader(
- dataset=ds, sampler=sampler, mapper=lambda x: x, batch_size=4, num_workers=0
- )
- self._check_is_range(dl, N)
-
- def test_build_iterable_dataloader_inference(self):
- # Test that build_detection_test_loader supports iterable dataset
- N = 50
- ds = DatasetFromList(list(range(N)))
- ds = ToIterableDataset(ds, InferenceSampler(len(ds)))
- dl = build_detection_test_loader(dataset=ds, mapper=lambda x: x, num_workers=3)
- self._check_is_range(dl, N)
diff --git a/spaces/BMukhtar/BookRecognitionKz/README.md b/spaces/BMukhtar/BookRecognitionKz/README.md
deleted file mode 100644
index c204b7e18e77cbece6dd917f0a0cc170857fdda8..0000000000000000000000000000000000000000
--- a/spaces/BMukhtar/BookRecognitionKz/README.md
+++ /dev/null
@@ -1,13 +0,0 @@
----
-title: BookRecognitionKz
-emoji: 🏃
-colorFrom: blue
-colorTo: gray
-sdk: streamlit
-sdk_version: 1.27.2
-app_file: app.py
-pinned: false
-license: apache-2.0
----
-
-Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
diff --git a/spaces/Benson/text-generation/Examples/Ajedrez Final De Juego Estudios Mod Apk.md b/spaces/Benson/text-generation/Examples/Ajedrez Final De Juego Estudios Mod Apk.md
deleted file mode 100644
index e562992f72f5805518a36a84552d7795df67a754..0000000000000000000000000000000000000000
--- a/spaces/Benson/text-generation/Examples/Ajedrez Final De Juego Estudios Mod Apk.md
+++ /dev/null
@@ -1,74 +0,0 @@
-
-
Ajedrez Endgame Estudios Mod Apk: Una guía para los amantes del ajedrez
-
Si usted es un entusiasta del ajedrez que quiere llevar su juego al siguiente nivel, usted debe probar definitivamente finales de ajedrez estudios mod apk. Los estudios de finales de ajedrez son posiciones compuestas que desafían tus habilidades y creatividad en la fase final del juego, donde solo quedan unas pocas piezas en el tablero. No solo son hermosas e instructivas, sino también útiles para mejorar tu cálculo, táctica, estrategia y comprensión del verdadero valor de los peones y las piezas.
-
Beneficios de los estudios de finales de ajedrez
-
Los estudios de finales de ajedrez no solo son divertidos y desafiantes, sino que también son beneficiosos para su desarrollo de ajedrez. Estos son algunos de los beneficios de los estudios de finales de ajedrez:
Mejoran tus habilidades de cálculo. Los estudios de finales de ajedrez a menudo requieren un cálculo preciso y profundo para encontrar los mejores movimientos y evitar errores. Practicándolos regularmente, puedes agudizar tus habilidades mentales y mejorar tu precisión.
-Mejoran tu visión táctica. Los estudios de finales de ajedrez están llenos de tácticas sorprendentes y hermosas, como sacrificios, tenedores, alfileres, brochetas, puntos muertos, zugzwangs y más. Al resolverlos, puedes entrenar tu ojo para detectar estos motivos y aplicarlos en tus propios juegos.
-
Te enseñan principios estratégicos. Los estudios de finales de ajedrez no son solo sobre tácticas, sino también sobre estrategia. Te muestran cómo usar el rey, los peones y las piezas de manera efectiva en diferentes tipos de terminaciones, como terminaciones de peones, terminaciones de torres, terminaciones de piezas menores, etc. También demuestran la importancia de conceptos como oposición, triangulación, avance, peones pasados, etc.
-
-
Aumentan su disfrute del ajedrez. Los estudios de finales de ajedrez no solo son educativos, sino también entretenidos. Muestran la belleza y la elegancia de los finales de ajedrez, y a menudo revelan soluciones inesperadas y sorprendentes que pueden sorprenderlo y deleitarlo. También te retan a pensar creativamente y encontrar tus propias soluciones.
-
-
Las mejores aplicaciones para los estudios de finales de ajedrez
-
Si quieres practicar estudios de ajedrez en tu dispositivo móvil, tienes muchas opciones para elegir. Hay muchas aplicaciones que ofrecen estudios de finales de ajedrez para diferentes niveles de jugadores, desde principiantes hasta expertos. Aquí están algunas de las mejores aplicaciones para estudios de finales de ajedrez:
- Más de 1200 estudios de finales por compositores famosos - 6 niveles de dificultad - Sugerencias y soluciones - Estadísticas y tablas de clasificación - Funciona offline
-
- Rompecabezas de alta calidad y diversos - Adecuado para todos los niveles - Interfaz fácil de usar - No hay anuncios
-
- Algunos rompecabezas pueden ser demasiado duro o demasiado fácil - Ninguna opción para crear o importar sus propios rompecabezas - Ninguna opción para jugar contra la computadora u otros jugadores
-
4.6 de 5 estrellas en Google Play Store 4.8 de 5 estrellas en App Store
- Más de 1000 rompecabezas finales de los mejores entrenadores - 5 niveles de dificultad - Sugerencias y explicaciones - Sistema de seguimiento de progreso y clasificación - Funciona en línea y sin conexión
-
- Rompecabezas de alta calidad e instructivos - Adecuado para todos los niveles - Interfaz interactiva y atractiva - De uso gratuito
-
-
4.5 de 5 estrellas en Google Play Store 4.7 de 5 estrellas en App Store
- Más de 700 estudios finales de compositores famosos - 3 niveles de dificultad - Sugerencias y soluciones - Estadísticas y logros - Trabajos offline
-
- Rompecabezas diversos y de alta calidad - Adecuado para niveles intermedios y avanzados - Interfaz simple y elegante - No hay anuncios
-
- Algunos rompecabezas pueden ser demasiado duro o demasiado fácil - No es adecuado para principiantes - No hay opción para crear o importar sus propios puzzles - No hay opción para jugar contra el ordenador u otros jugadores
-
4.4 de 5 estrellas en Google Play Store N/A en App Store
-
$1.99 en Google Play Store $0.99 en App Store
-
-
-
Como se puede ver, hay muchas opciones para elegir cuando se trata de ajedrez estudios finales mod apk. Puede comparar y contrastar las características, ventajas, desventajas, calificaciones y precios de cada aplicación y decidir cuál se adapta mejor a sus necesidades y preferencias. También puedes probar diferentes aplicaciones y ver cuál te gusta más.
-
Cómo utilizar los estudios de ajedrez Endgame Mod Apk
-
Una vez que haya descargado e instalado su ajedrez elegido estudios finales mod apk, puede empezar a usarlo para practicar y mejorar sus habilidades de ajedrez final. Aquí hay algunos consejos y consejos sobre cómo utilizar los estudios de ajedrez final apk mod con eficacia:
-
-
Elige el nivel de dificultad adecuado. La mayoría de las aplicaciones ofrecen diferentes niveles de dificultad, que van de fácil a difícil. Debes elegir el nivel que coincida con tu habilidad y conocimiento actuales. Si los puzzles son demasiado fáciles, no aprenderás mucho. Si son demasiado difíciles, te frustrarás y perderás motivación. También puedes ajustar el nivel a medida que avanzas y mejoras.
-
-
Seguimiento de su progreso. La mayoría de las aplicaciones ofrecen estadísticas y tablas de clasificación que le permiten realizar un seguimiento de su progreso y rendimiento. Puedes ver cuántos puzzles has resuelto, cuántos has acertado o errado, cuánto tiempo has pasado, cuál es tu calificación, etc. También puedes comparar tus resultados con otros usuarios y ver cómo te clasificas entre ellos. Puede utilizar estos datos para medir su mejora y establecer sus objetivos.
-
Diviértete. Lo más importante es divertirse mientras se utiliza el ajedrez estudios finales mod apk. Usted debe disfrutar del proceso de resolver rompecabezas, aprender de ellos, y descubrir nuevas ideas y conceptos. También debe apreciar la belleza y elegancia de los finales de ajedrez, y admirar la creatividad y habilidad de los compositores y solucionadores. Los estudios de finales de ajedrez no son solo una herramienta para mejorar, sino también una fuente de alegría e inspiración.
-
-
Conclusión
-
Ajedrez estudios finales mod apk es una gran manera de practicar y mejorar sus habilidades finales de ajedrez en su dispositivo móvil. Puedes acceder a una gran base de datos de estudios de finales de ajedrez que desafían tus habilidades y creatividad en la fase final del juego. También puedes aprender de los mejores compositores y solucionadores, y disfrutar de la belleza y elegancia de los finales de ajedrez.
-
Si usted es un amante del ajedrez que quiere llevar su juego al siguiente nivel, usted debe probar definitivamente finales de ajedrez estudios mod apk. No solo mejorará su cálculo, táctica, estrategia y conocimiento de finales teóricos, sino que también aumentará su disfrute del ajedrez.
-
Entonces, ¿qué estás esperando? Descargar ajedrez estudios finales mod apk hoy y empezar a resolver puzzles!
-
Preguntas frecuentes
-
Aquí hay algunas preguntas frecuentes y respuestas acerca de los estudios de ajedrez final apk mod:
-
-
-
-
Q: ¿Es seguro usar los estudios de ajedrez mod apk? A: Depende de la fuente y la calidad del mod apk. Algunos apks mod pueden contener virus o malware que pueden dañar su dispositivo o comprometer sus datos. Algunos mod apks también pueden violar los términos de servicio o la política de privacidad de los desarrolladores de aplicaciones originales, lo que puede resultar en problemas legales o suspensión de la cuenta. Siempre debe leer los comentarios y calificaciones de otros usuarios antes de descargar cualquier apk mod, y utilizarlo a su propio riesgo.
-
P: ¿Cuáles son algunas de las mejores fuentes para los estudios de finales de ajedrez? A: Algunas de las mejores fuentes para los estudios de finales de ajedrez son libros, revistas, sitios web, bases de datos y aplicaciones que se especializan en este campo. Algunos ejemplos son: - The Art of the Endgame por Jan Timman - EG Magazine por Harold van der Heijden - [ChessCafe.com] - [ChessBase.com] - [ChessKing.com] [ChessBase.com]<[ChessOK.com]
Q: ¿Cómo puedo mejorar mis habilidades de ajedrez? A: Hay muchas maneras de mejorar tus habilidades de juego final de ajedrez, tales como: - Estudiar las terminaciones básicas y teóricas, tales como terminaciones de rey y peón, terminaciones de torre y de peón, etc. - Practicar estudios y rompecabezas de finales de ajedrez regularmente. - Analizar tus propios juegos e identificar tus errores y debilidades en el final del juego. - Jugar juegos de práctica de finales contra el ordenador u otros jugadores. - Leer libros y artículos sobre la teoría y la estrategia de finales de ajedrez. - Viendo videos y conferencias de expertos y maestros de finales de ajedrez.
-
P: ¿Quiénes son algunos de los mejores compositores y solucionadores de finales de ajedrez? A: Hay muchos compositores y solucionadores de finales de ajedrez que han contribuido al arte y la ciencia de los finales de ajedrez. Algunos de los más famosos e influyentes son: - Alexey Troitsky - Henri Rinck - Richard Reti - Leonid Kubbel - Genrikh Kasparyan - Yuri Bakh - John Nunn - Pal Benko<>>- Jan Timbrman<>- Yoan Chank/li
-
64aa2da5cf
-
-
\ No newline at end of file
diff --git a/spaces/Benson/text-generation/Examples/Controladores De Gigabyte H370m D3h.md b/spaces/Benson/text-generation/Examples/Controladores De Gigabyte H370m D3h.md
deleted file mode 100644
index b275c697d76b80a1fb8c828f1430e6538e7758ef..0000000000000000000000000000000000000000
--- a/spaces/Benson/text-generation/Examples/Controladores De Gigabyte H370m D3h.md
+++ /dev/null
@@ -1,129 +0,0 @@
-
-
Cómo descargar e instalar controladores Gigabyte H370M D3H
-
Si tiene una placa base Gigabyte H370M D3H en su computadora, es posible que se pregunte cómo descargar e instalar los últimos controladores para ella. Los controladores son componentes de software esenciales que permiten que su placa madre y sus dispositivos conectados se comuniquen con su sistema operativo. Sin controladores, es posible que su computadora no funcione correctamente o en absoluto.
En este artículo, le mostraremos cómo encontrar, descargar e instalar los controladores correctos para su placa base Gigabyte H370M D3H. También explicaremos cuáles son las principales características de esta placa base y por qué necesita controladores para ella. Siguiendo nuestra guía, podrás disfrutar del mejor rendimiento y estabilidad de tu ordenador.
-
Introducción
-
¿Qué es la placa base Gigabyte H370M D3H y por qué necesita controladores para ella
-
Gigabyte H370M D3H es una placa madre micro ATX que admite procesadores Intel Core de 9a y 8a generación. Tiene un nuevo diseño híbrido digital PWM, ranuras duales M.2, soporte RGB Fusión, puertos Intel GbE LAN con cFosSpeed, USB 3.1 Gen2 Type-C y Type-A, memoria Intel OptaneTM y más características que lo convierten en una gran opción para construir un PC potente.
-
Sin embargo, para aprovechar al máximo estas características, necesita instalar los controladores adecuados para su placa madre. Los controladores son como traductores que ayudan a su placa base y sus dispositivos conectados a comunicarse con su sistema operativo. Sin controladores, es posible que su sistema operativo no reconozca o no use algunas de las características o dispositivos de su placa base. Esto podría resultar en un rendimiento deficiente, errores, fallos o incluso daños de hardware.
-
Por lo tanto, es importante descargar e instalar los últimos controladores para su placa base Gigabyte H370M D3H. Esto asegurará que su computadora funcione sin problemas y de manera eficiente.
-
-
¿Cuáles son las principales características de la placa base Gigabyte H370M D3H
-
-
-
Ranuras duales M.2: Estas ranuras le permiten instalar dos SSD NVMe PCIe que pueden aumentar su rendimiento y velocidad de almacenamiento. También puede utilizar la memoria Intel OptaneTM para acelerar su disco duro.
-
RGB Fusión support: Esta característica le permite personalizar los efectos de iluminación de su placa base y tiras de led RGB conectadas en 7 colores. También puede sincronizar la iluminación con otros dispositivos compatibles utilizando el encabezado RGBW pin.
-
Intel GbE LAN con cFosSpeed: Esta característica le proporciona una conexión de red rápida y estable con baja latencia y alto ancho de banda. También tiene un software acelerador de Internet que optimiza el tráfico de red.
-
USB 3.1 Gen2 Puertos tipo C y tipo A: Estos puertos le ofrecen velocidades de transferencia de datos rápidas de hasta 10 Gbps y admiten varios dispositivos como unidades externas, monitores, cargadores, etc.
-
Memoria Intel OptaneTM lista: Esta característica le permite utilizar módulos de memoria Intel OptaneTM que actúan como una unidad de caché para su disco duro y mejoran la capacidad de respuesta del sistema y el tiempo de arranque.
-
Nuevo diseño híbrido de PWM digital: Este diseño proporciona a su placa base una entrega de energía precisa y estable y mejora su durabilidad y fiabilidad.
-
-
Estas son solo algunas de las principales características de la placa base Gigabyte H370M D3H. Puede encontrar más detalles y especificaciones en el sitio web oficial de Gigabyte.
-
Cómo encontrar los controladores correctos para tu placa madre
-
Antes de descargar e instalar los controladores para su placa madre, debe asegurarse de encontrar los correctos para su modelo y sistema operativo específico. Hay dos maneras de hacer esto:
-
-
-
Utilice una herramienta de actualización de controladores de terceros: Esta es una forma alternativa y conveniente de encontrar los controladores correctos para su placa base. Puede usar una herramienta de actualización de controladores que escanea su computadora y detecta y descarga automáticamente los controladores que necesita. Sin embargo, debe tener cuidado al elegir una herramienta de actualización de controladores, ya que algunos de ellos pueden ser poco fiables o maliciosos. Solo debe usar una herramienta confiable y de buena reputación que tenga reseñas y calificaciones positivas de otros usuarios.
-
-
Cualquiera que sea la forma que elija, siempre debe descargar los controladores de una fuente segura y oficial. También debe comprobar la versión del controlador y la fecha antes de descargarlo, para asegurarse de que es el último y compatible.
-
Cómo descargar controladores Gigabyte H370M D3H
-
Cómo utilizar el sitio web oficial de Gigabyte para descargar controladores
-
Si desea utilizar el sitio web oficial de Gigabyte para descargar controladores, puede seguir estos pasos:
-
-
Visite el sitio web de Gigabyte e introduzca su modelo de placa base en el cuadro de búsqueda.
-
Seleccione su sistema operativo desde el menú desplegable.
-
Verá una lista de controladores para diferentes categorías como audio, chipset, LAN, etc. Haga clic en la categoría que desea descargar.
-
Verá una lista de versiones y fechas del controlador. Haga clic en el icono de descarga junto a la versión del controlador más reciente o compatible.
-
Será redirigido a una página de descarga. Haga clic en el botón de descarga y guarde el archivo del controlador en su computadora.
-
Repita estos pasos para cualquier otra categoría de controlador que desee descargar.
-
-
Cómo usar una herramienta de actualización de controladores de terceros para descargar controladores
-
Si desea utilizar una herramienta de actualización de controladores de terceros para descargar controladores, puede seguir estos pasos:
-
-
-
Inicie la herramienta de actualización de controladores y escanee su computadora. La herramienta detectará automáticamente el modelo de la placa base y el sistema operativo, y encontrará los controladores que necesita.
-
Verá una lista de controladores que están desactualizados, que faltan o que son incompatibles. Puede optar por actualizar todos ellos o seleccionar los que desea actualizar.
-
La herramienta descargará e instalará los controladores por usted. Es posible que necesite reiniciar su computadora después de que se complete la instalación.
-
-
Cómo instalar controladores Gigabyte H370M D3H
-
Cómo instalar controladores desde una carpeta o una unidad USB
-
Si ha descargado los controladores del sitio web oficial de Gigabyte o los ha guardado en una carpeta o una unidad USB, puede instalarlos siguiendo estos pasos:
-
-
Localice el archivo de controlador que ha descargado o guardado en su computadora o unidad USB. Debe tener una extensión . exe o . zip.
-
Si el archivo es un archivo . exe, haga doble clic en él y siga las instrucciones en pantalla para instalarlo.
-
Si el archivo es un archivo . zip, haga clic derecho sobre él y seleccione Extraer todo. A continuación, abra la carpeta extraída y busque un archivo setup.exe o install.exe. Haga doble clic en él y siga las instrucciones en pantalla para instalarlo.
-
Repita estos pasos para cualquier otro archivo de controlador que haya descargado o guardado.
-
Es posible que tenga que reiniciar el equipo después de instalar todos los controladores.
-
-
Cómo instalar controladores usando Administrador de dispositivos o Windows Update
-
Si no ha descargado o guardado ningún archivo de controlador, también puede intentar instalarlo usando el Administrador de dispositivos o Windows Update. Estos están construidos en Windows y pueden ayudarle a encontrar e instalar los controladores que son compatibles con su placa base y sistema operativo. Puedes seguir estos pasos:
-
-
Abra el Administrador de dispositivos presionando las teclas Windows + X y seleccionando Administrador de dispositivos desde el menú.
-
-
Haga clic derecho en el dispositivo que desea actualizar y seleccione Actualizar controlador del menú.
-
Verá dos opciones: Busque automáticamente el software de controlador actualizado o Busque el software de controlador en mi computadora. Puede elegir cualquiera de las opciones dependiendo de su preferencia.
-
Si elige Buscar automáticamente, Windows buscará en línea el mejor controlador para su dispositivo e instalarlo por usted.
-
Si elige Navegar por mi ordenador, tendrá que localizar el archivo de controlador que ha descargado o guardado en su ordenador o unidad USB. Luego, siga las instrucciones en pantalla para instalarlo.
-
Repita estos pasos para cualquier otro dispositivo que desee actualizar.
-
Es posible que tenga que reiniciar el equipo después de instalar todos los controladores.
-
-
Alternativamente, también puede usar Windows Update para verificar e instalar los controladores que están disponibles para la placa base y el sistema operativo. Puedes seguir estos pasos:
-
-
Abra la configuración presionando las teclas Windows + I y seleccione Actualizar y Seguridad en el menú.
-
Seleccione Windows Update desde el panel izquierdo y haga clic en Buscar actualizaciones desde el panel derecho.
-
Windows escaneará su computadora y le mostrará cualquier actualización disponible, incluidos los controladores. Puede elegir instalar todos ellos o seleccionar los que desea instalar.
-
Siga las instrucciones en pantalla para instalar las actualizaciones.
-
Es posible que tenga que reiniciar el equipo después de instalar todas las actualizaciones.
-
-
Conclusión
-
En este artículo, le hemos mostrado cómo descargar e instalar los últimos controladores para su placa base Gigabyte H370M D3H. También hemos explicado cuáles son las principales características de esta placa base y por qué necesita controladores para ella. Siguiendo nuestra guía, podrás disfrutar del mejor rendimiento y estabilidad de tu ordenador.
-
-
Esperamos que haya encontrado este artículo útil e informativo. Si tiene alguna pregunta o comentario, no dude en dejar un comentario a continuación. ¡Nos encantaría saber de ti!
-
Preguntas frecuentes
-
¿Cuáles son los beneficios de actualizar los controladores?
-
La actualización de los controladores puede proporcionarle varios beneficios, como:
-
-
Mejorar el rendimiento y la funcionalidad de su placa base y sus dispositivos conectados
-
Corrección de errores o errores que podrían ocurrir con su placa madre y sus dispositivos conectados
-
Mejora de la seguridad y la estabilidad de su ordenador
-
Agregar nuevas características o soporte para nuevos dispositivos o tecnologías
-
-
¿Con qué frecuencia debo actualizar los controladores?
-
No hay respuesta definitiva a esta pregunta, ya que depende de varios factores como el modelo de la placa base, el sistema operativo, el uso, las preferencias, etc. Sin embargo, algunas pautas generales son:
-
-
Debe actualizar los controladores cada vez que haya una nueva versión disponible que ofrece mejoras significativas o correcciones
-
Debe actualizar los controladores cada vez que encuentre problemas o problemas con su placa madre o sus dispositivos conectados
-
Debe actualizar los controladores cada vez que actualice o cambie sus componentes de hardware o software
-
-
¿Cuáles son los riesgos de instalar controladores incorrectos o desactualizados?
-
La instalación de controladores incorrectos o desactualizados puede causar varios riesgos, como:
-
-
Reducir el rendimiento y la funcionalidad de su placa base y sus dispositivos conectados
-
Causar errores, bloqueos, congelaciones, pantallas azules u otros problemas con su computadora
-
Dañando sus componentes de hardware o software
-
Exponer su computadora a amenazas de seguridad o infecciones de malware
-
-
¿Cómo puedo solucionar problemas de controladores?
-
Si encuentra algún problema con el controlador, puede probar algunos de estos pasos de solución de problemas:
-
-
-
Compruebe si el controlador está instalado correctamente y completamente
-
Compruebe si hay un controlador más nuevo o mejor disponible para su placa base y sistema operativo
-
Desinstalar y reinstalar el controlador
-
Utilice Administrador de dispositivos o Windows Update para actualizar el controlador
-
Utilice una herramienta de actualización de controladores para actualizar el controlador
-
Utilice Restaurar sistema o copia de seguridad y restaurar para restaurar el equipo a un estado anterior
-
Póngase en contacto con Gigabyte o el fabricante de su dispositivo para obtener más soporte
-
-
¿Dónde puedo obtener más soporte para la placa base Gigabyte H370M D3H?
-
Si necesita más soporte para la placa base Gigabyte H370M D3H, puede visitar las siguientes fuentes:
-
-
El sitio web oficial de Gigabyte, donde se puede encontrar la página del producto, manual de usuario, controladores, preguntas frecuentes, garantía, y la información de contacto para su placa base
-
El foro oficial de Gigabyte, donde puedes interactuar con otros usuarios y expertos de Gigabyte y obtener respuestas a tus preguntas
-
El canal oficial de YouTube Gigabyte, donde puedes ver videos y tutoriales sobre cómo usar y solucionar problemas de tu placa madre
-
La página oficial de Facebook de Gigabyte, donde puedes seguir las últimas noticias y actualizaciones sobre productos y servicios de Gigabyte
-
La cuenta oficial de Gigabyte Twitter, donde puede twittear sus preguntas o comentarios a Gigabyte
-
64aa2da5cf
-
-
\ No newline at end of file
diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/tenacity/before.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/tenacity/before.py
deleted file mode 100644
index cfd7dc72ee7fe9300948133cfeb660f610b90e4e..0000000000000000000000000000000000000000
--- a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/tenacity/before.py
+++ /dev/null
@@ -1,46 +0,0 @@
-# Copyright 2016 Julien Danjou
-# Copyright 2016 Joshua Harlow
-# Copyright 2013-2014 Ray Holder
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import typing
-
-from pip._vendor.tenacity import _utils
-
-if typing.TYPE_CHECKING:
- import logging
-
- from pip._vendor.tenacity import RetryCallState
-
-
-def before_nothing(retry_state: "RetryCallState") -> None:
- """Before call strategy that does nothing."""
-
-
-def before_log(logger: "logging.Logger", log_level: int) -> typing.Callable[["RetryCallState"], None]:
- """Before call strategy that logs to some logger the attempt."""
-
- def log_it(retry_state: "RetryCallState") -> None:
- if retry_state.fn is None:
- # NOTE(sileht): can't really happen, but we must please mypy
- fn_name = ""
- else:
- fn_name = _utils.get_callback_name(retry_state.fn)
- logger.log(
- log_level,
- f"Starting call to '{fn_name}', "
- f"this is the {_utils.to_ordinal(retry_state.attempt_number)} time calling it.",
- )
-
- return log_it
diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/pkg_resources/_vendor/pyparsing/actions.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/pkg_resources/_vendor/pyparsing/actions.py
deleted file mode 100644
index f72c66e743146c7a5b70a5440e9ab5459f10245b..0000000000000000000000000000000000000000
--- a/spaces/Big-Web/MMSD/env/Lib/site-packages/pkg_resources/_vendor/pyparsing/actions.py
+++ /dev/null
@@ -1,207 +0,0 @@
-# actions.py
-
-from .exceptions import ParseException
-from .util import col
-
-
-class OnlyOnce:
- """
- Wrapper for parse actions, to ensure they are only called once.
- """
-
- def __init__(self, method_call):
- from .core import _trim_arity
-
- self.callable = _trim_arity(method_call)
- self.called = False
-
- def __call__(self, s, l, t):
- if not self.called:
- results = self.callable(s, l, t)
- self.called = True
- return results
- raise ParseException(s, l, "OnlyOnce obj called multiple times w/out reset")
-
- def reset(self):
- """
- Allow the associated parse action to be called once more.
- """
-
- self.called = False
-
-
-def match_only_at_col(n):
- """
- Helper method for defining parse actions that require matching at
- a specific column in the input text.
- """
-
- def verify_col(strg, locn, toks):
- if col(locn, strg) != n:
- raise ParseException(strg, locn, "matched token not at column {}".format(n))
-
- return verify_col
-
-
-def replace_with(repl_str):
- """
- Helper method for common parse actions that simply return
- a literal value. Especially useful when used with
- :class:`transform_string` ().
-
- Example::
-
- num = Word(nums).set_parse_action(lambda toks: int(toks[0]))
- na = one_of("N/A NA").set_parse_action(replace_with(math.nan))
- term = na | num
-
- term[1, ...].parse_string("324 234 N/A 234") # -> [324, 234, nan, 234]
- """
- return lambda s, l, t: [repl_str]
-
-
-def remove_quotes(s, l, t):
- """
- Helper parse action for removing quotation marks from parsed
- quoted strings.
-
- Example::
-
- # by default, quotation marks are included in parsed results
- quoted_string.parse_string("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"]
-
- # use remove_quotes to strip quotation marks from parsed results
- quoted_string.set_parse_action(remove_quotes)
- quoted_string.parse_string("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"]
- """
- return t[0][1:-1]
-
-
-def with_attribute(*args, **attr_dict):
- """
- Helper to create a validating parse action to be used with start
- tags created with :class:`make_xml_tags` or
- :class:`make_html_tags`. Use ``with_attribute`` to qualify
- a starting tag with a required attribute value, to avoid false
- matches on common tags such as ``
`` or ``
``.
-
- Call ``with_attribute`` with a series of attribute names and
- values. Specify the list of filter attributes names and values as:
-
- - keyword arguments, as in ``(align="right")``, or
- - as an explicit dict with ``**`` operator, when an attribute
- name is also a Python reserved word, as in ``**{"class":"Customer", "align":"right"}``
- - a list of name-value tuples, as in ``(("ns1:class", "Customer"), ("ns2:align", "right"))``
-
- For attribute names with a namespace prefix, you must use the second
- form. Attribute names are matched insensitive to upper/lower case.
-
- If just testing for ``class`` (with or without a namespace), use
- :class:`with_class`.
-
- To verify that the attribute exists, but without specifying a value,
- pass ``with_attribute.ANY_VALUE`` as the value.
-
- Example::
-
- html = '''
-
- Some text
-
1 4 0 1 0
-
1,3 2,3 1,1
-
this has no type
-
-
- '''
- div,div_end = make_html_tags("div")
-
- # only match div tag having a type attribute with value "grid"
- div_grid = div().set_parse_action(with_attribute(type="grid"))
- grid_expr = div_grid + SkipTo(div | div_end)("body")
- for grid_header in grid_expr.search_string(html):
- print(grid_header.body)
-
- # construct a match with any div tag having a type attribute, regardless of the value
- div_any_type = div().set_parse_action(with_attribute(type=with_attribute.ANY_VALUE))
- div_expr = div_any_type + SkipTo(div | div_end)("body")
- for div_header in div_expr.search_string(html):
- print(div_header.body)
-
- prints::
-
- 1 4 0 1 0
-
- 1 4 0 1 0
- 1,3 2,3 1,1
- """
- if args:
- attrs = args[:]
- else:
- attrs = attr_dict.items()
- attrs = [(k, v) for k, v in attrs]
-
- def pa(s, l, tokens):
- for attrName, attrValue in attrs:
- if attrName not in tokens:
- raise ParseException(s, l, "no matching attribute " + attrName)
- if attrValue != with_attribute.ANY_VALUE and tokens[attrName] != attrValue:
- raise ParseException(
- s,
- l,
- "attribute {!r} has value {!r}, must be {!r}".format(
- attrName, tokens[attrName], attrValue
- ),
- )
-
- return pa
-
-
-with_attribute.ANY_VALUE = object()
-
-
-def with_class(classname, namespace=""):
- """
- Simplified version of :class:`with_attribute` when
- matching on a div class - made difficult because ``class`` is
- a reserved word in Python.
-
- Example::
-
- html = '''
-
- Some text
-
1 4 0 1 0
-
1,3 2,3 1,1
-
this <div> has no class
-
-
- '''
- div,div_end = make_html_tags("div")
- div_grid = div().set_parse_action(with_class("grid"))
-
- grid_expr = div_grid + SkipTo(div | div_end)("body")
- for grid_header in grid_expr.search_string(html):
- print(grid_header.body)
-
- div_any_type = div().set_parse_action(with_class(withAttribute.ANY_VALUE))
- div_expr = div_any_type + SkipTo(div | div_end)("body")
- for div_header in div_expr.search_string(html):
- print(div_header.body)
-
- prints::
-
- 1 4 0 1 0
-
- 1 4 0 1 0
- 1,3 2,3 1,1
- """
- classattr = "{}:class".format(namespace) if namespace else "class"
- return with_attribute(**{classattr: classname})
-
-
-# pre-PEP8 compatibility symbols
-replaceWith = replace_with
-removeQuotes = remove_quotes
-withAttribute = with_attribute
-withClass = with_class
-matchOnlyAtCol = match_only_at_col
diff --git a/spaces/BilalSardar/StoryGenerator/README.md b/spaces/BilalSardar/StoryGenerator/README.md
deleted file mode 100644
index 3590029360701f560b7e7b1194eb31c51bcb2fa1..0000000000000000000000000000000000000000
--- a/spaces/BilalSardar/StoryGenerator/README.md
+++ /dev/null
@@ -1,13 +0,0 @@
----
-title: StoryGenerator
-emoji: 🐢
-colorFrom: gray
-colorTo: purple
-sdk: gradio
-sdk_version: 3.11
-app_file: app.py
-pinned: false
-license: openrail
----
-
-Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
diff --git a/spaces/BimboAnon/BimboProxy/README.md b/spaces/BimboAnon/BimboProxy/README.md
deleted file mode 100644
index 527df64517e2450b583d73d1c1ef9b15bd716b48..0000000000000000000000000000000000000000
--- a/spaces/BimboAnon/BimboProxy/README.md
+++ /dev/null
@@ -1,10 +0,0 @@
----
-title: BimboProxy
-emoji: 📚
-colorFrom: red
-colorTo: pink
-sdk: docker
-pinned: false
----
-
-Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
diff --git a/spaces/Boadiwaa/Recipes/openai/api_resources/deployment.py b/spaces/Boadiwaa/Recipes/openai/api_resources/deployment.py
deleted file mode 100644
index 7d6c3b5cd716d37f8ccbe46ff2f10d308919f471..0000000000000000000000000000000000000000
--- a/spaces/Boadiwaa/Recipes/openai/api_resources/deployment.py
+++ /dev/null
@@ -1,62 +0,0 @@
-from openai import util
-from openai.api_resources.abstract import DeletableAPIResource, ListableAPIResource, CreateableAPIResource
-from openai.error import InvalidRequestError, APIError
-
-
-class Deployment(CreateableAPIResource, ListableAPIResource, DeletableAPIResource):
- engine_required = False
- OBJECT_NAME = "deployments"
-
- @classmethod
- def create(cls, *args, **kwargs):
- """
- Creates a new deployment for the provided prompt and parameters.
- """
- typed_api_type, _ = cls._get_api_type_and_version(kwargs.get("api_type", None), None)
- if typed_api_type != util.ApiType.AZURE:
- raise APIError("Deployment operations are only available for the Azure API type.")
-
- if kwargs.get("model", None) is None:
- raise InvalidRequestError(
- "Must provide a 'model' parameter to create a Deployment.",
- param="model",
- )
-
- scale_settings = kwargs.get("scale_settings", None)
- if scale_settings is None:
- raise InvalidRequestError(
- "Must provide a 'scale_settings' parameter to create a Deployment.",
- param="scale_settings",
- )
-
- if "scale_type" not in scale_settings or "capacity" not in scale_settings:
- raise InvalidRequestError(
- "The 'scale_settings' parameter contains invalid or incomplete values.",
- param="scale_settings",
- )
-
- return super().create(*args, **kwargs)
-
- @classmethod
- def list(cls, *args, **kwargs):
- typed_api_type, _ = cls._get_api_type_and_version(kwargs.get("api_type", None), None)
- if typed_api_type != util.ApiType.AZURE:
- raise APIError("Deployment operations are only available for the Azure API type.")
-
- return super().list(*args, **kwargs)
-
- @classmethod
- def delete(cls, *args, **kwargs):
- typed_api_type, _ = cls._get_api_type_and_version(kwargs.get("api_type", None), None)
- if typed_api_type != util.ApiType.AZURE:
- raise APIError("Deployment operations are only available for the Azure API type.")
-
- return super().delete(*args, **kwargs)
-
- @classmethod
- def retrieve(cls, *args, **kwargs):
- typed_api_type, _ = cls._get_api_type_and_version(kwargs.get("api_type", None), None)
- if typed_api_type != util.ApiType.AZURE:
- raise APIError("Deployment operations are only available for the Azure API type.")
-
- return super().retrieve(*args, **kwargs)
diff --git a/spaces/CVPR/Dual-Key_Backdoor_Attacks/openvqa/docs/_source/advanced/adding_model.md b/spaces/CVPR/Dual-Key_Backdoor_Attacks/openvqa/docs/_source/advanced/adding_model.md
deleted file mode 100644
index 6c57647c1a79956d25d2b84dbda301538ea645f0..0000000000000000000000000000000000000000
--- a/spaces/CVPR/Dual-Key_Backdoor_Attacks/openvqa/docs/_source/advanced/adding_model.md
+++ /dev/null
@@ -1,160 +0,0 @@
-# Adding a custom VQA model
-
-This is a tutorial on how to add a custom VQA model into OpenVQA. Follow the steps below, you will obtain a model that can run across VQA/GQA/CLEVR datasets.
-
-## 1. Preliminary
-
-All implemented models are placed at ```/openvqa/models/```, so the first thing to do is to create a folder there for your VQA model named by ``. After that, all your model related files will be placed in the folder ```/openvqa/models//```.
-
-## 2. Dataset Adapter
-
-Create a python file `/openvqa/models//adapter.py` to bridge your model and different datasets. Different datasets have different input features, thus resulting in different operators to handle the features.
-
-#### Input
-
-Input features (packed as `feat_dict`) for different datasets.
-
-#### Output
-
-Customized pre-processed features to be fed into the model.
-
-#### Adapter Template
-
-```
-from openvqa.core.base_dataset import BaseAdapter
-class Adapter(BaseAdapter):
- def __init__(self, __C):
- super(Adapter, self).__init__(__C)
- self.__C = __C
-
- def vqa_init(self, __C):
- # Your Implementation
-
- def gqa_init(self, __C):
- # Your Implementation
-
- def clevr_init(self, __C):
- # Your Implementation
-
- def vqa_forward(self, feat_dict):
- # Your Implementation
-
- def gqa_forward(self, feat_dict):
- # Your Implementation
-
- def clevr_forward(self, feat_dict):
- # Your Implementation
-
-```
-
-Each dataset-specific initiation function `def _init(self, __C)` corresponds to one feed-forward function `def _forward(self, feat_dict)`, your implementations should follow the principles ```torch.nn.Module.__init__()``` and ```torch.nn.Module.forward()```, respectively.
-
-The variable ` feat_dict` consists of the input feature names for the datasets, which corresponds to the definitions in `/openvqa/core/base_cfg.py`
-
-```
-vqa:{
- 'FRCN_FEAT': buttom-up features -> [batchsize, num_bbox, 2048],
- 'BBOX_FEAT': bbox coordinates -> [batchsize, num_bbox, 5],
-}
-gqa:{
- 'FRCN_FEAT': official buttom-up features -> [batchsize, num_bbox, 2048],
- 'BBOX_FEAT': official bbox coordinates -> [batchsize, num_bbox, 5],
- 'GRID_FEAT': official resnet grid features -> [batchsize, num_grid, 2048],
-}
-clevr:{
- 'GRID_FEAT': resnet grid features -> [batchsize, num_grid, 1024],
-}
-```
-
-More detailed examples can be referred to the adapter for the [MCAN](https://github.com/MILVLG/openvqa/tree/master/openvqa/models/mcan/adapter.py) model.
-
-
-
-## 3. Definition of model hyper-parameters
-
-Create a python file named ```/openvqa/models//model_cfgs.py```
-
-#### Configuration Template
-
-```
-from openvqa.core.base_cfgs import BaseCfgs
-class Cfgs(BaseCfgs):
- def __init__(self):
- super(Cfgs, self).__init__()
- # Your Implementation
-```
-
-Only the variable you defined here can be used in the network. The variable value can be override in the running configuration file described later.
-
-#### Example
-
-```
-# model_cfgs.py
-from openvqa.core.base_cfgs import BaseCfgs
-class Cfgs(BaseCfgs):
- def __init__(self):
- super(Cfgs, self).__init__()
- self.LAYER = 6
-```
-
-```
-# net.py
-class Net(nn.Module):
- def __init__(self, __C, pretrained_emb, token_size, answer_size):
- super(Net, self).__init__()
- self.__C = __C
-
- print(__C.LAYER)
-```
-
-```
-Output: 6
-```
-
-## 4. Main body
-
-Create a python file for the main body of the model as ```/openvqa/models//net.py```. Note that the filename must be `net.py` since this filename will be invoked by the running script. Except the file, other auxiliary model files invoked by `net.py` can be named arbitrarily.
-
-When implementation, you should pay attention to the following restrictions:
-
-- The main module should be named `Net`, i.e., `class Net(nn.Module):`
-- The `init` function has three input variables: *pretrained_emb* corresponds to the GloVe embedding features for the question; *token\_size* corresponds to the number of all dataset words; *answer_size* corresponds to the number of classes for prediction.
-- The `forward` function has four input variables: *frcn_feat*, *grid_feat*, *bbox_feat*, *ques_ix*.
-- In the `init` function, you should initialize the `Adapter` which you've already defined above. In the `forward` function, you should feed *frcn_feat*, *grid_feat*, *bbox_feat* into the `Adapter` to obtain the processed image features.
-- Return a prediction tensor of size [batch\_size, answer_size]. Note that no activation function like ```sigmoid``` or ```softmax``` is appended on the prediction. The activation has been designed for the prediction in the loss function outside.
-
-#### Model Template
-
-```
-import torch.nn as nn
-from openvqa.models.mcan.adapter import Adapter
-class Net(nn.Module):
- def __init__(self, __C, pretrained_emb, token_size, answer_size):
- super(Net, self).__init__()
- self.__C = __C
- self.adapter = Adapter(__C)
-
- def forward(self, frcn_feat, grid_feat, bbox_feat, ques_ix):
- img_feat = self.adapter(frcn_feat, grid_feat, bbox_feat)
- # model implementation
- ...
-
- return pred
-```
-
-## 5. Declaration of running configurations
-
-Create a `yml` file at```/configs//.yml``` and define your hyper-parameters here. We suggest that ``= ``. If you have the requirement to have one base model support the running scripts for different variants. (e.g., MFB and MFH), you can have different yml files (e.g., `mfb.yml` and `mfh.yml`) and use the `MODEL_USE` param in the yml file to specify the actual used model (i.e., mfb).
-
-### Example:
-```
-MODEL_USE: # Must be defined
-LAYER: 6
-LOSS_FUNC: bce
-LOSS_REDUCTION: sum
-```
-
-Finally, to register the added model to the running script, you can modify `` by adding your `` into the arguments for models [here](https://github.com/MILVLG/openvqa/tree/master/run.py#L22).
-
-
-By doing all the steps above, you are able to use ```--MODEL=``` to train/val/test your model like other provided models. For more information about the usage of the running script, please refer to the [Getting Started](https://openvqa.readthedocs.io/en/latest/basic/getting_started.html) page.
diff --git a/spaces/CVPR/WALT/mmdet/models/losses/balanced_l1_loss.py b/spaces/CVPR/WALT/mmdet/models/losses/balanced_l1_loss.py
deleted file mode 100644
index 7bcd13ff26dbdc9f6eff8d7c7b5bde742a8d7d1d..0000000000000000000000000000000000000000
--- a/spaces/CVPR/WALT/mmdet/models/losses/balanced_l1_loss.py
+++ /dev/null
@@ -1,120 +0,0 @@
-import mmcv
-import numpy as np
-import torch
-import torch.nn as nn
-
-from ..builder import LOSSES
-from .utils import weighted_loss
-
-
-@mmcv.jit(derivate=True, coderize=True)
-@weighted_loss
-def balanced_l1_loss(pred,
- target,
- beta=1.0,
- alpha=0.5,
- gamma=1.5,
- reduction='mean'):
- """Calculate balanced L1 loss.
-
- Please see the `Libra R-CNN `_
-
- Args:
- pred (torch.Tensor): The prediction with shape (N, 4).
- target (torch.Tensor): The learning target of the prediction with
- shape (N, 4).
- beta (float): The loss is a piecewise function of prediction and target
- and ``beta`` serves as a threshold for the difference between the
- prediction and target. Defaults to 1.0.
- alpha (float): The denominator ``alpha`` in the balanced L1 loss.
- Defaults to 0.5.
- gamma (float): The ``gamma`` in the balanced L1 loss.
- Defaults to 1.5.
- reduction (str, optional): The method that reduces the loss to a
- scalar. Options are "none", "mean" and "sum".
-
- Returns:
- torch.Tensor: The calculated loss
- """
- assert beta > 0
- assert pred.size() == target.size() and target.numel() > 0
-
- diff = torch.abs(pred - target)
- b = np.e**(gamma / alpha) - 1
- loss = torch.where(
- diff < beta, alpha / b *
- (b * diff + 1) * torch.log(b * diff / beta + 1) - alpha * diff,
- gamma * diff + gamma / b - alpha * beta)
-
- return loss
-
-
-@LOSSES.register_module()
-class BalancedL1Loss(nn.Module):
- """Balanced L1 Loss.
-
- arXiv: https://arxiv.org/pdf/1904.02701.pdf (CVPR 2019)
-
- Args:
- alpha (float): The denominator ``alpha`` in the balanced L1 loss.
- Defaults to 0.5.
- gamma (float): The ``gamma`` in the balanced L1 loss. Defaults to 1.5.
- beta (float, optional): The loss is a piecewise function of prediction
- and target. ``beta`` serves as a threshold for the difference
- between the prediction and target. Defaults to 1.0.
- reduction (str, optional): The method that reduces the loss to a
- scalar. Options are "none", "mean" and "sum".
- loss_weight (float, optional): The weight of the loss. Defaults to 1.0
- """
-
- def __init__(self,
- alpha=0.5,
- gamma=1.5,
- beta=1.0,
- reduction='mean',
- loss_weight=1.0):
- super(BalancedL1Loss, self).__init__()
- self.alpha = alpha
- self.gamma = gamma
- self.beta = beta
- self.reduction = reduction
- self.loss_weight = loss_weight
-
- def forward(self,
- pred,
- target,
- weight=None,
- avg_factor=None,
- reduction_override=None,
- **kwargs):
- """Forward function of loss.
-
- Args:
- pred (torch.Tensor): The prediction with shape (N, 4).
- target (torch.Tensor): The learning target of the prediction with
- shape (N, 4).
- weight (torch.Tensor, optional): Sample-wise loss weight with
- shape (N, ).
- avg_factor (int, optional): Average factor that is used to average
- the loss. Defaults to None.
- reduction_override (str, optional): The reduction method used to
- override the original reduction method of the loss.
- Options are "none", "mean" and "sum".
-
- Returns:
- torch.Tensor: The calculated loss
- """
- assert reduction_override in (None, 'none', 'mean', 'sum')
- reduction = (
- reduction_override if reduction_override else self.reduction)
- loss_bbox = self.loss_weight * balanced_l1_loss(
- pred,
- target,
- weight,
- alpha=self.alpha,
- gamma=self.gamma,
- beta=self.beta,
- reduction=reduction,
- avg_factor=avg_factor,
- **kwargs)
- return loss_bbox
diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/PIL/ImageShow.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/PIL/ImageShow.py
deleted file mode 100644
index 8b1c3f8bb63ea6e6fccba543bdaea0bbd9b03163..0000000000000000000000000000000000000000
--- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/PIL/ImageShow.py
+++ /dev/null
@@ -1,323 +0,0 @@
-#
-# The Python Imaging Library.
-# $Id$
-#
-# im.show() drivers
-#
-# History:
-# 2008-04-06 fl Created
-#
-# Copyright (c) Secret Labs AB 2008.
-#
-# See the README file for information on usage and redistribution.
-#
-import os
-import shutil
-import subprocess
-import sys
-from shlex import quote
-
-from . import Image
-
-_viewers = []
-
-
-def register(viewer, order=1):
- """
- The :py:func:`register` function is used to register additional viewers::
-
- from PIL import ImageShow
- ImageShow.register(MyViewer()) # MyViewer will be used as a last resort
- ImageShow.register(MySecondViewer(), 0) # MySecondViewer will be prioritised
- ImageShow.register(ImageShow.XVViewer(), 0) # XVViewer will be prioritised
-
- :param viewer: The viewer to be registered.
- :param order:
- Zero or a negative integer to prepend this viewer to the list,
- a positive integer to append it.
- """
- try:
- if issubclass(viewer, Viewer):
- viewer = viewer()
- except TypeError:
- pass # raised if viewer wasn't a class
- if order > 0:
- _viewers.append(viewer)
- else:
- _viewers.insert(0, viewer)
-
-
-def show(image, title=None, **options):
- r"""
- Display a given image.
-
- :param image: An image object.
- :param title: Optional title. Not all viewers can display the title.
- :param \**options: Additional viewer options.
- :returns: ``True`` if a suitable viewer was found, ``False`` otherwise.
- """
- for viewer in _viewers:
- if viewer.show(image, title=title, **options):
- return True
- return False
-
-
-class Viewer:
- """Base class for viewers."""
-
- # main api
-
- def show(self, image, **options):
- """
- The main function for displaying an image.
- Converts the given image to the target format and displays it.
- """
-
- if not (
- image.mode in ("1", "RGBA")
- or (self.format == "PNG" and image.mode in ("I;16", "LA"))
- ):
- base = Image.getmodebase(image.mode)
- if image.mode != base:
- image = image.convert(base)
-
- return self.show_image(image, **options)
-
- # hook methods
-
- format = None
- """The format to convert the image into."""
- options = {}
- """Additional options used to convert the image."""
-
- def get_format(self, image):
- """Return format name, or ``None`` to save as PGM/PPM."""
- return self.format
-
- def get_command(self, file, **options):
- """
- Returns the command used to display the file.
- Not implemented in the base class.
- """
- raise NotImplementedError
-
- def save_image(self, image):
- """Save to temporary file and return filename."""
- return image._dump(format=self.get_format(image), **self.options)
-
- def show_image(self, image, **options):
- """Display the given image."""
- return self.show_file(self.save_image(image), **options)
-
- def show_file(self, path, **options):
- """
- Display given file.
- """
- os.system(self.get_command(path, **options)) # nosec
- return 1
-
-
-# --------------------------------------------------------------------
-
-
-class WindowsViewer(Viewer):
- """The default viewer on Windows is the default system application for PNG files."""
-
- format = "PNG"
- options = {"compress_level": 1, "save_all": True}
-
- def get_command(self, file, **options):
- return (
- f'start "Pillow" /WAIT "{file}" '
- "&& ping -n 4 127.0.0.1 >NUL "
- f'&& del /f "{file}"'
- )
-
-
-if sys.platform == "win32":
- register(WindowsViewer)
-
-
-class MacViewer(Viewer):
- """The default viewer on macOS using ``Preview.app``."""
-
- format = "PNG"
- options = {"compress_level": 1, "save_all": True}
-
- def get_command(self, file, **options):
- # on darwin open returns immediately resulting in the temp
- # file removal while app is opening
- command = "open -a Preview.app"
- command = f"({command} {quote(file)}; sleep 20; rm -f {quote(file)})&"
- return command
-
- def show_file(self, path, **options):
- """
- Display given file.
- """
- subprocess.call(["open", "-a", "Preview.app", path])
- executable = sys.executable or shutil.which("python3")
- if executable:
- subprocess.Popen(
- [
- executable,
- "-c",
- "import os, sys, time; time.sleep(20); os.remove(sys.argv[1])",
- path,
- ]
- )
- return 1
-
-
-if sys.platform == "darwin":
- register(MacViewer)
-
-
-class UnixViewer(Viewer):
- format = "PNG"
- options = {"compress_level": 1, "save_all": True}
-
- def get_command(self, file, **options):
- command = self.get_command_ex(file, **options)[0]
- return f"({command} {quote(file)}"
-
-
-class XDGViewer(UnixViewer):
- """
- The freedesktop.org ``xdg-open`` command.
- """
-
- def get_command_ex(self, file, **options):
- command = executable = "xdg-open"
- return command, executable
-
- def show_file(self, path, **options):
- """
- Display given file.
- """
- subprocess.Popen(["xdg-open", path])
- return 1
-
-
-class DisplayViewer(UnixViewer):
- """
- The ImageMagick ``display`` command.
- This viewer supports the ``title`` parameter.
- """
-
- def get_command_ex(self, file, title=None, **options):
- command = executable = "display"
- if title:
- command += f" -title {quote(title)}"
- return command, executable
-
- def show_file(self, path, **options):
- """
- Display given file.
- """
- args = ["display"]
- title = options.get("title")
- if title:
- args += ["-title", title]
- args.append(path)
-
- subprocess.Popen(args)
- return 1
-
-
-class GmDisplayViewer(UnixViewer):
- """The GraphicsMagick ``gm display`` command."""
-
- def get_command_ex(self, file, **options):
- executable = "gm"
- command = "gm display"
- return command, executable
-
- def show_file(self, path, **options):
- """
- Display given file.
- """
- subprocess.Popen(["gm", "display", path])
- return 1
-
-
-class EogViewer(UnixViewer):
- """The GNOME Image Viewer ``eog`` command."""
-
- def get_command_ex(self, file, **options):
- executable = "eog"
- command = "eog -n"
- return command, executable
-
- def show_file(self, path, **options):
- """
- Display given file.
- """
- subprocess.Popen(["eog", "-n", path])
- return 1
-
-
-class XVViewer(UnixViewer):
- """
- The X Viewer ``xv`` command.
- This viewer supports the ``title`` parameter.
- """
-
- def get_command_ex(self, file, title=None, **options):
- # note: xv is pretty outdated. most modern systems have
- # imagemagick's display command instead.
- command = executable = "xv"
- if title:
- command += f" -name {quote(title)}"
- return command, executable
-
- def show_file(self, path, **options):
- """
- Display given file.
- """
- args = ["xv"]
- title = options.get("title")
- if title:
- args += ["-name", title]
- args.append(path)
-
- subprocess.Popen(args)
- return 1
-
-
-if sys.platform not in ("win32", "darwin"): # unixoids
- if shutil.which("xdg-open"):
- register(XDGViewer)
- if shutil.which("display"):
- register(DisplayViewer)
- if shutil.which("gm"):
- register(GmDisplayViewer)
- if shutil.which("eog"):
- register(EogViewer)
- if shutil.which("xv"):
- register(XVViewer)
-
-
-class IPythonViewer(Viewer):
- """The viewer for IPython frontends."""
-
- def show_image(self, image, **options):
- ipython_display(image)
- return 1
-
-
-try:
- from IPython.display import display as ipython_display
-except ImportError:
- pass
-else:
- register(IPythonViewer)
-
-
-if __name__ == "__main__":
- if len(sys.argv) < 2:
- print("Syntax: python3 ImageShow.py imagefile [title]")
- sys.exit()
-
- with Image.open(sys.argv[1]) as im:
- print(show(im, *sys.argv[2:]))
diff --git a/spaces/DanielGartop/SexAI/README.md b/spaces/DanielGartop/SexAI/README.md
deleted file mode 100644
index 985c1919091cad537532a52b742926031a016c7e..0000000000000000000000000000000000000000
--- a/spaces/DanielGartop/SexAI/README.md
+++ /dev/null
@@ -1,10 +0,0 @@
----
-title: SexAI
-emoji: 📈
-colorFrom: pink
-colorTo: red
-sdk: docker
-pinned: false
----
-
-Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
diff --git a/spaces/Datasculptor/MusicGen/audiocraft/models/lm.py b/spaces/Datasculptor/MusicGen/audiocraft/models/lm.py
deleted file mode 100644
index c8aad8f06797eef3293605056e1de14d07c56c2a..0000000000000000000000000000000000000000
--- a/spaces/Datasculptor/MusicGen/audiocraft/models/lm.py
+++ /dev/null
@@ -1,527 +0,0 @@
-# Copyright (c) Meta Platforms, Inc. and affiliates.
-# All rights reserved.
-#
-# This source code is licensed under the license found in the
-# LICENSE file in the root directory of this source tree.
-
-from dataclasses import dataclass
-from functools import partial
-import logging
-import math
-import typing as tp
-
-import torch
-from torch import nn
-
-from ..utils import utils
-from ..modules.streaming import StreamingModule, State
-from ..modules.transformer import StreamingTransformer, create_norm_fn
-from ..modules.conditioners import (
- ConditionFuser,
- ClassifierFreeGuidanceDropout,
- AttributeDropout,
- ConditioningProvider,
- ConditioningAttributes,
- ConditionType,
-)
-from ..modules.codebooks_patterns import CodebooksPatternProvider
-from ..modules.activations import get_activation_fn
-
-
-logger = logging.getLogger(__name__)
-ConditionTensors = tp.Dict[str, ConditionType]
-CFGConditions = tp.Union[ConditionTensors, tp.Tuple[ConditionTensors, ConditionTensors]]
-
-
-def get_init_fn(method: str, input_dim: int, init_depth: tp.Optional[int] = None):
- """LM layer initialization.
- Inspired from xlformers: https://github.com/fairinternal/xlformers
-
- Args:
- method (str): Method name for init function. Valid options are:
- 'gaussian', 'uniform'.
- input_dim (int): Input dimension of the initialized module.
- init_depth (Optional[int]): Optional init depth value used to rescale
- the standard deviation if defined.
- """
- # Compute std
- std = 1 / math.sqrt(input_dim)
- # Rescale with depth
- if init_depth is not None:
- std = std / math.sqrt(2 * init_depth)
-
- if method == 'gaussian':
- return partial(
- torch.nn.init.trunc_normal_, mean=0.0, std=std, a=-3 * std, b=3 * std
- )
- elif method == 'uniform':
- bound = math.sqrt(3) * std # ensure the standard deviation is `std`
- return partial(torch.nn.init.uniform_, a=-bound, b=bound)
- else:
- raise ValueError("Unsupported layer initialization method")
-
-
-def init_layer(m: nn.Module,
- method: str,
- init_depth: tp.Optional[int] = None,
- zero_bias_init: bool = False):
- """Wrapper around ``get_init_fn`` for proper initialization of LM modules.
-
- Args:
- m (nn.Module): Module to initialize.
- method (str): Method name for the init function.
- init_depth (Optional[int]): Optional init depth value used to rescale
- the standard deviation if defined.
- zero_bias_init (bool): Whether to initialize the bias to 0 or not.
- """
- if isinstance(m, nn.Linear):
- init_fn = get_init_fn(method, m.in_features, init_depth=init_depth)
- if m.weight.device.type == 'cpu' and m.weight.dtype == torch.float16:
- weight = m.weight.float()
- init_fn(weight)
- m.weight.data[:] = weight.half()
- else:
- init_fn(m.weight)
- if zero_bias_init and m.bias is not None:
- nn.init.constant_(m.bias, 0)
- elif isinstance(m, nn.Embedding):
- init_fn = get_init_fn(method, m.embedding_dim, init_depth=None)
- if m.weight.device.type == 'cpu' and m.weight.dtype == torch.float16:
- weight = m.weight.float()
- init_fn(weight)
- m.weight.data[:] = weight.half()
- else:
- init_fn(m.weight)
-
-
-class ScaledEmbedding(nn.Embedding):
- """Boost learning rate for embeddings (with `scale`).
- """
- def __init__(self, *args, lr=None, **kwargs):
- super().__init__(*args, **kwargs)
- self.lr = lr
-
- def make_optim_group(self):
- group = {"params": list(self.parameters())}
- if self.lr is not None:
- group["lr"] = self.lr
- return group
-
-
-@dataclass
-class LMOutput:
- # The logits are already re-aligned with the input codes
- # hence no extra shift is required, e.g. when computing CE
- logits: torch.Tensor # [B, K, T, card]
- mask: torch.Tensor # [B, K, T]
-
-
-class LMModel(StreamingModule):
- """Transformer-based language model on multiple streams of codes.
-
- Args:
- pattern_provider (CodebooksPatternProvider): Pattern provider for codebook interleaving.
- condition_provider (MusicConditioningProvider): Conditioning provider from metadata.
- fuser (ConditionFuser): Fuser handling the fusing of conditions with language model input.
- n_q (int): Number of parallel streams to model.
- card (int): Cardinality, vocabulary size.
- dim (int): Dimension of the transformer encoder.
- num_heads (int): Number of heads for the transformer encoder.
- hidden_scale (int): Scale for hidden feed forward dimension of the transformer encoder.
- norm (str): Normalization method.
- norm_first (bool): Use pre-norm instead of post-norm.
- emb_lr (Optional[float]): Embedding-specific learning rate.
- bias_proj (bool): Use bias for output projections.
- weight_init (Optional[str]): Method for weight initialization.
- depthwise_init (Optional[str]): Method for depthwise weight initialization.
- zero_bias_init (bool): If true and bias in Linears, initialize bias to zeros.
- cfg_dropout (float): Classifier-free guidance dropout.
- cfg_coef (float): Classifier-free guidance coefficient.
- attribute_dropout (dict): Attribute dropout probabilities.
- two_step_cfg (bool): Whether to run classifier free-guidance with 2 distinct steps.
- **kwargs: Additional parameters for the transformer encoder.
- """
- def __init__(self, pattern_provider: CodebooksPatternProvider, condition_provider: ConditioningProvider,
- fuser: ConditionFuser, n_q: int = 8, card: int = 1024, dim: int = 128, num_heads: int = 8,
- hidden_scale: int = 4, norm: str = 'layer_norm', norm_first: bool = False,
- emb_lr: tp.Optional[float] = None, bias_proj: bool = True,
- weight_init: tp.Optional[str] = None, depthwise_init: tp.Optional[str] = None,
- zero_bias_init: bool = False, cfg_dropout: float = 0, cfg_coef: float = 1.0,
- attribute_dropout: tp.Dict[str, tp.Dict[str, float]] = {}, two_step_cfg: bool = False,
- **kwargs):
- super().__init__()
- self.cfg_coef = cfg_coef
- self.cfg_dropout = ClassifierFreeGuidanceDropout(p=cfg_dropout)
- self.att_dropout = AttributeDropout(p=attribute_dropout)
- self.condition_provider = condition_provider
- self.fuser = fuser
- self.card = card
- embed_dim = self.card + 1
- self.n_q = n_q
- self.dim = dim
- self.pattern_provider = pattern_provider
- self.two_step_cfg = two_step_cfg
- self.emb = nn.ModuleList([ScaledEmbedding(embed_dim, dim, lr=emb_lr) for _ in range(n_q)])
- if 'activation' in kwargs:
- kwargs['activation'] = get_activation_fn(kwargs['activation'])
- self.transformer = StreamingTransformer(
- d_model=dim, num_heads=num_heads, dim_feedforward=int(hidden_scale * dim),
- norm=norm, norm_first=norm_first, **kwargs)
- self.out_norm: tp.Optional[nn.Module] = None
- if norm_first:
- self.out_norm = create_norm_fn(norm, dim)
- self.linears = nn.ModuleList([nn.Linear(dim, self.card, bias=bias_proj) for _ in range(n_q)])
- self._init_weights(weight_init, depthwise_init, zero_bias_init)
- self._fsdp: tp.Optional[nn.Module]
- self.__dict__['_fsdp'] = None
-
- def _init_weights(self, weight_init: tp.Optional[str], depthwise_init: tp.Optional[str], zero_bias_init: bool):
- """Initialization of the transformer module weights.
-
- Args:
- weight_init (Optional[str]): Weight initialization strategy. See ``get_init_fn`` for valid options.
- depthwise_init (Optional[str]): Depwthwise initialization strategy. The following options are valid:
- 'current' where the depth corresponds to the current layer index or 'global' where the total number
- of layer is used as depth. If not set, no depthwise initialization strategy is used.
- zero_bias_init (bool): Whether to initalize bias to zero or not.
- """
- assert depthwise_init is None or depthwise_init in ['current', 'global']
- assert depthwise_init is None or weight_init is not None, \
- "If 'depthwise_init' is defined, a 'weight_init' method should be provided."
- assert not zero_bias_init or weight_init is not None, \
- "If 'zero_bias_init', a 'weight_init' method should be provided"
-
- if weight_init is None:
- return
-
- for emb_layer in self.emb:
- init_layer(emb_layer, method=weight_init, init_depth=None, zero_bias_init=zero_bias_init)
-
- for layer_idx, tr_layer in enumerate(self.transformer.layers):
- depth = None
- if depthwise_init == 'current':
- depth = layer_idx + 1
- elif depthwise_init == 'global':
- depth = len(self.transformer.layers)
- init_fn = partial(init_layer, method=weight_init, init_depth=depth, zero_bias_init=zero_bias_init)
- tr_layer.apply(init_fn)
-
- for linear in self.linears:
- init_layer(linear, method=weight_init, init_depth=None, zero_bias_init=zero_bias_init)
-
- @property
- def special_token_id(self) -> int:
- return self.card
-
- @property
- def num_codebooks(self) -> int:
- return self.n_q
-
- def forward(self, sequence: torch.Tensor,
- conditions: tp.List[ConditioningAttributes],
- condition_tensors: tp.Optional[ConditionTensors] = None) -> torch.Tensor:
- """Apply language model on sequence and conditions.
- Given a tensor of sequence of shape [B, K, S] with K the number of codebooks and
- S the sequence steps, return the logits with shape [B, card, K, S].
-
- Args:
- indices (torch.Tensor): indices of the codes to model.
- conditions (list[ConditioningAttributes]): conditionings to use when modeling
- the given codes. Note that when evaluating multiple time with the same conditioning
- you should pre-compute those and pass them as `condition_tensors`.
- condition_tensors (dict[str, ConditionType] or None): pre-computed conditioning
- tensors, see `conditions`.
- Returns:
- torch.Tensor: Logits.
- """
- B, K, S = sequence.shape
- assert K == self.num_codebooks, 'Sequence shape must match the specified number of codebooks'
- input_ = sum([self.emb[k](sequence[:, k]) for k in range(K)])
- if condition_tensors is None:
- assert not self._is_streaming, "Conditions tensors should be precomputed when streaming."
- # apply dropout modules
- conditions = self.cfg_dropout(conditions)
- conditions = self.att_dropout(conditions)
- tokenized = self.condition_provider.tokenize(conditions)
- # encode conditions and fuse, both have a streaming cache to not recompute when generating.
- condition_tensors = self.condition_provider(tokenized)
- else:
- assert not conditions, "Shouldn't pass both conditions and condition_tensors."
-
- input_, cross_attention_input = self.fuser(input_, condition_tensors)
-
- out = self.transformer(input_, cross_attention_src=cross_attention_input)
- if self.out_norm:
- out = self.out_norm(out)
- logits = torch.stack([self.linears[k](out) for k in range(K)], dim=1) # [B, K, S, card]
-
- # remove the prefix from the model outputs
- if len(self.fuser.fuse2cond['prepend']) > 0:
- logits = logits[:, :, -S:]
-
- return logits # [B, K, S, card]
-
- def compute_predictions(
- self, codes: torch.Tensor,
- conditions: tp.List[ConditioningAttributes],
- condition_tensors: tp.Optional[ConditionTensors] = None) -> LMOutput:
- """Given an input tensor of codes [B, K, T] and list of conditions, runs the model
- forward using the specified codes interleaving pattern.
-
- Args:
- codes (torch.Tensor): Input codes of shape [B, K, T] with B the batch size,
- K the number of codebooks and T the number of timesteps.
- conditions (list[ConditioningAttributes]): conditionings to use when modeling
- the given codes. Note that when evaluating multiple time with the same conditioning
- you should pre-compute those and pass them as `condition_tensors`.
- condition_tensors (dict[str, ConditionType] or None): pre-computed conditioning
- tensors, see `conditions`.
- Returns:
- LMOutput: Language model outputs
- logits (torch.Tensor) of shape [B, K, T, card] corresponding to the provided codes,
- i.e. the first item corresponds to logits to predict the first code, meaning that
- no additional shifting of codes and logits is required.
- mask (torch.Tensor) of shape [B, K, T], mask over valid and invalid positions.
- Given the specified interleaving strategies, parts of the logits and codes should
- not be considered as valid predictions because of invalid context.
- """
- B, K, T = codes.shape
- codes = codes.contiguous()
- # map codes [B, K, T] into pattern sequence [B, K, S] using special_token_id for masked tokens
- pattern = self.pattern_provider.get_pattern(T)
- sequence_codes, sequence_indexes, sequence_mask = pattern.build_pattern_sequence(
- codes, self.special_token_id, keep_only_valid_steps=True
- )
- # apply model on pattern sequence
- model = self if self._fsdp is None else self._fsdp
- logits = model(sequence_codes, conditions, condition_tensors) # [B, K, S, card]
- # map back the logits on pattern sequence to logits on original codes: [B, K, S, card] -> [B, K, T, card]
- # and provide the corresponding mask over invalid positions of tokens
- logits = logits.permute(0, 3, 1, 2) # [B, card, K, S]
- # note: we use nans as special token to make it obvious if we feed unexpected logits
- logits, logits_indexes, logits_mask = pattern.revert_pattern_logits(
- logits, float('nan'), keep_only_valid_steps=True
- )
- logits = logits.permute(0, 2, 3, 1) # [B, K, T, card]
- logits_mask = logits_mask[None, :, :].expand(B, -1, -1) # [K, T] -> [B, K, T]
- return LMOutput(logits, logits_mask)
-
- def _sample_next_token(self,
- sequence: torch.Tensor,
- cfg_conditions: CFGConditions,
- unconditional_state: State,
- use_sampling: bool = False,
- temp: float = 1.0,
- top_k: int = 0,
- top_p: float = 0.0,
- cfg_coef: tp.Optional[float] = None) -> torch.Tensor:
- """Sample next token from the model given a sequence and a set of conditions. The model supports
- multiple sampling strategies (greedy sampling, softmax, top-k, top-p...).
-
- Args:
- sequence (torch.Tensor): Current sequence of shape [B, K, S]
- with K corresponding to the number of codebooks and S the number of sequence steps.
- S = 1 in streaming mode, except for the first step that contains a bigger prompt.
- condition_tensors (Dict[str, ConditionType): Set of conditions. If CFG is used,
- should be twice the batch size, being the concatenation of the conditions + null conditions.
- use_sampling (bool): Whether to use a sampling strategy or not.
- temp (float): Sampling temperature.
- top_k (int): K for "top-k" sampling.
- top_p (float): P for "top-p" sampling.
- cfg_coef (float): classifier free guidance coefficient
- Returns:
- next_token (torch.Tensor): Next token tensor of shape [B, K, 1].
- """
- B = sequence.shape[0]
- cfg_coef = self.cfg_coef if cfg_coef is None else cfg_coef
- model = self if self._fsdp is None else self._fsdp
- if self.two_step_cfg and cfg_conditions != {}:
- assert isinstance(cfg_conditions, tuple)
- condition_tensors, null_condition_tensors = cfg_conditions
- cond_logits = model(sequence, conditions=[], condition_tensors=condition_tensors)
- state = self.get_streaming_state()
- self.set_streaming_state(unconditional_state)
- uncond_logits = model(sequence, conditions=[], condition_tensors=null_condition_tensors)
- unconditional_state.update(self.get_streaming_state())
- self.set_streaming_state(state)
- logits = uncond_logits + (cond_logits - uncond_logits) * self.cfg_coef
- else:
- assert isinstance(cfg_conditions, dict)
- condition_tensors = cfg_conditions
- if condition_tensors:
- # Preparing for CFG, predicting both conditional and unconditional logits.
- sequence = torch.cat([sequence, sequence], dim=0)
- all_logits = model(
- sequence,
- conditions=[], condition_tensors=condition_tensors)
- if condition_tensors:
- cond_logits, uncond_logits = all_logits.split(B, dim=0) # [B, K, T, card]
- logits = uncond_logits + (cond_logits - uncond_logits) * cfg_coef
- else:
- logits = all_logits
-
- logits = logits.permute(0, 1, 3, 2) # [B, K, card, T]
- logits = logits[..., -1] # [B x K x card]
-
- # Apply softmax for sampling if temp > 0. Else, do greedy sampling to avoid zero division error.
- if use_sampling and temp > 0.0:
- probs = torch.softmax(logits / temp, dim=-1)
- if top_p > 0.0:
- next_token = utils.sample_top_p(probs, p=top_p)
- elif top_k > 0:
- next_token = utils.sample_top_k(probs, k=top_k)
- else:
- next_token = utils.multinomial(probs, num_samples=1)
- else:
- next_token = torch.argmax(logits, dim=-1, keepdim=True)
-
- return next_token
-
- @torch.no_grad()
- def generate(self,
- prompt: tp.Optional[torch.Tensor] = None,
- conditions: tp.List[ConditioningAttributes] = [],
- num_samples: tp.Optional[int] = None,
- max_gen_len: int = 256,
- use_sampling: bool = True,
- temp: float = 1.0,
- top_k: int = 250,
- top_p: float = 0.0,
- cfg_coef: tp.Optional[float] = None,
- two_step_cfg: bool = False,
- remove_prompts: bool = False,
- check: bool = False,
- callback: tp.Optional[tp.Callable[[int, int], None]] = None) -> torch.Tensor:
- """Generate tokens sampling from the model given a prompt or unconditionally. Generation can
- be perform in a greedy fashion or using sampling with top K and top P strategies.
-
- Args:
- prompt (Optional[torch.Tensor]): Prompt tokens of shape [B, K, T].
- conditions_tensors (Dict[str, torch.Tensor]): Set of conditions or None.
- num_samples (int or None): Number of samples to generate when no prompt and no conditions are given.
- max_gen_len (int): Maximum generation length.
- use_sampling (bool): Whether to use a sampling strategy or not.
- temp (float): Sampling temperature.
- top_k (int): K for "top-k" sampling.
- top_p (float): P for "top-p" sampling.
- remove_prompts (bool): Whether to remove prompts from generation or not.
- Returns:
- torch.Tensor: Generated tokens.
- """
- assert not self.training, "generation shouldn't be used in training mode."
- first_param = next(iter(self.parameters()))
- device = first_param.device
-
- # Checking all input shapes are consistents.
- possible_num_samples = []
- if num_samples is not None:
- possible_num_samples.append(num_samples)
- elif prompt is not None:
- possible_num_samples.append(prompt.shape[0])
- elif conditions:
- possible_num_samples.append(len(conditions))
- else:
- possible_num_samples.append(1)
- assert [x == possible_num_samples[0] for x in possible_num_samples], "Inconsitent inputs shapes"
- num_samples = possible_num_samples[0]
-
- # below we create set of conditions: one conditional and one unconditional
- # to do that we merge the regular condition together with the null condition
- # we then do 1 forward pass instead of 2.
- # the reason for that is two-fold:
- # 1. it is about x2 faster than doing 2 forward passes
- # 2. avoid the streaming API treating the 2 passes as part of different time steps
- # We also support doing two different passes, in particular to ensure that
- # the padding structure is exactly the same between train anf test.
- # With a batch size of 1, this can be slower though.
- cfg_conditions: CFGConditions
- two_step_cfg = self.two_step_cfg if two_step_cfg is None else two_step_cfg
- if conditions:
- null_conditions = ClassifierFreeGuidanceDropout(p=1.0)(conditions)
- if two_step_cfg:
- cfg_conditions = (
- self.condition_provider(self.condition_provider.tokenize(conditions)),
- self.condition_provider(self.condition_provider.tokenize(null_conditions)),
- )
- else:
- conditions = conditions + null_conditions
- tokenized = self.condition_provider.tokenize(conditions)
- cfg_conditions = self.condition_provider(tokenized)
- else:
- cfg_conditions = {}
-
- if prompt is None:
- assert num_samples > 0
- prompt = torch.zeros((num_samples, self.num_codebooks, 0), dtype=torch.long, device=device)
-
- B, K, T = prompt.shape
- start_offset = T
- assert start_offset < max_gen_len
-
- pattern = self.pattern_provider.get_pattern(max_gen_len)
- # this token is used as default value for codes that are not generated yet
- unknown_token = -1
-
- # we generate codes up to the max_gen_len that will be mapped to the pattern sequence
- gen_codes = torch.full((B, K, max_gen_len), unknown_token, dtype=torch.long, device=device)
- # filling the gen_codes with the prompt if needed
- gen_codes[..., :start_offset] = prompt
- # create the gen_sequence with proper interleaving from the pattern: [B, K, S]
- gen_sequence, indexes, mask = pattern.build_pattern_sequence(gen_codes, self.special_token_id)
- # retrieve the start_offset in the sequence:
- # it is the first sequence step that contains the `start_offset` timestep
- start_offset_sequence = pattern.get_first_step_with_timesteps(start_offset)
- assert start_offset_sequence is not None
-
- with self.streaming():
- unconditional_state = self.get_streaming_state()
- prev_offset = 0
- gen_sequence_len = gen_sequence.shape[-1] # gen_sequence shape is [B, K, S]
- for offset in range(start_offset_sequence, gen_sequence_len):
- # get current sequence (note that the streaming API is providing the caching over previous offsets)
- curr_sequence = gen_sequence[..., prev_offset:offset]
- curr_mask = mask[None, ..., prev_offset:offset].expand(B, -1, -1)
- if check:
- # check coherence between mask and sequence
- assert (curr_sequence == torch.where(curr_mask, curr_sequence, self.special_token_id)).all()
- # should never happen as gen_sequence is filled progressively
- assert not (curr_sequence == unknown_token).any()
- # sample next token from the model, next token shape is [B, K, 1]
- next_token = self._sample_next_token(
- curr_sequence, cfg_conditions, unconditional_state, use_sampling, temp, top_k, top_p,
- cfg_coef=cfg_coef)
- # ensure the tokens that should be masked are properly set to special_token_id
- # as the model never output special_token_id
- valid_mask = mask[..., offset:offset+1].expand(B, -1, -1)
- next_token[~valid_mask] = self.special_token_id
- # ensure we don't overwrite prompt tokens, we only write over unknown tokens
- # (then mask tokens should be left as is as well, which is correct)
- gen_sequence[..., offset:offset+1] = torch.where(
- gen_sequence[..., offset:offset+1] == unknown_token,
- next_token, gen_sequence[..., offset:offset+1]
- )
- prev_offset = offset
- if callback is not None:
- callback(1 + offset - start_offset_sequence, gen_sequence_len - start_offset_sequence)
- unconditional_state.clear()
-
- # ensure sequence has been entirely filled
- assert not (gen_sequence == unknown_token).any()
- # ensure gen_sequence pattern and mask are matching
- # which means the gen_sequence is valid according to the pattern
- assert (
- gen_sequence == torch.where(mask[None, ...].expand(B, -1, -1), gen_sequence, self.special_token_id)
- ).all()
- # get back the codes, trimming the prompt if needed and cutting potentially incomplete timesteps
- out_codes, out_indexes, out_mask = pattern.revert_pattern_sequence(gen_sequence, special_token=unknown_token)
-
- # sanity checks over the returned codes and corresponding masks
- assert (out_codes[..., :max_gen_len] != unknown_token).all()
- assert (out_mask[..., :max_gen_len] == 1).all()
-
- out_start_offset = start_offset if remove_prompts else 0
- out_codes = out_codes[..., out_start_offset:max_gen_len]
-
- # ensure the returned codes are all valid
- assert (out_codes >= 0).all() and (out_codes <= self.card).all()
- return out_codes
diff --git a/spaces/Dimalker/Faceswapper/roop/typing.py b/spaces/Dimalker/Faceswapper/roop/typing.py
deleted file mode 100644
index 1cff7440616e20bfe7b8bc287f86d11bf1b0f083..0000000000000000000000000000000000000000
--- a/spaces/Dimalker/Faceswapper/roop/typing.py
+++ /dev/null
@@ -1,7 +0,0 @@
-from typing import Any
-
-from insightface.app.common import Face
-import numpy
-
-Face = Face
-Frame = numpy.ndarray[Any, Any]
diff --git a/spaces/DragGan/DragGan-Inversion/stylegan_human/torch_utils/ops/grid_sample_gradfix.py b/spaces/DragGan/DragGan-Inversion/stylegan_human/torch_utils/ops/grid_sample_gradfix.py
deleted file mode 100644
index c522ae9b6f36a89203ce62f3d4487514523b5b00..0000000000000000000000000000000000000000
--- a/spaces/DragGan/DragGan-Inversion/stylegan_human/torch_utils/ops/grid_sample_gradfix.py
+++ /dev/null
@@ -1,93 +0,0 @@
-# Copyright (c) SenseTime Research. All rights reserved.
-
-# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
-#
-# NVIDIA CORPORATION and its licensors retain all intellectual property
-# and proprietary rights in and to this software, related documentation
-# and any modifications thereto. Any use, reproduction, disclosure or
-# distribution of this software and related documentation without an express
-# license agreement from NVIDIA CORPORATION is strictly prohibited.
-
-"""Custom replacement for `torch.nn.functional.grid_sample` that
-supports arbitrarily high order gradients between the input and output.
-Only works on 2D images and assumes
-`mode='bilinear'`, `padding_mode='zeros'`, `align_corners=False`."""
-
-import warnings
-import torch
-
-# pylint: disable=redefined-builtin
-# pylint: disable=arguments-differ
-# pylint: disable=protected-access
-
-# ----------------------------------------------------------------------------
-
-enabled = False # Enable the custom op by setting this to true.
-
-# ----------------------------------------------------------------------------
-
-
-def grid_sample(input, grid):
- if _should_use_custom_op():
- return _GridSample2dForward.apply(input, grid)
- return torch.nn.functional.grid_sample(input=input, grid=grid, mode='bilinear', padding_mode='zeros', align_corners=False)
-
-# ----------------------------------------------------------------------------
-
-
-def _should_use_custom_op():
- if not enabled:
- return False
- if any(torch.__version__.startswith(x) for x in ['1.7.', '1.8.', '1.9']):
- return True
- warnings.warn(
- f'grid_sample_gradfix not supported on PyTorch {torch.__version__}. Falling back to torch.nn.functional.grid_sample().')
- return False
-
-# ----------------------------------------------------------------------------
-
-
-class _GridSample2dForward(torch.autograd.Function):
- @staticmethod
- def forward(ctx, input, grid):
- assert input.ndim == 4
- assert grid.ndim == 4
- output = torch.nn.functional.grid_sample(
- input=input, grid=grid, mode='bilinear', padding_mode='zeros', align_corners=False)
- ctx.save_for_backward(input, grid)
- return output
-
- @staticmethod
- def backward(ctx, grad_output):
- input, grid = ctx.saved_tensors
- grad_input, grad_grid = _GridSample2dBackward.apply(
- grad_output, input, grid)
- return grad_input, grad_grid
-
-# ----------------------------------------------------------------------------
-
-
-class _GridSample2dBackward(torch.autograd.Function):
- @staticmethod
- def forward(ctx, grad_output, input, grid):
- op = torch._C._jit_get_operation('aten::grid_sampler_2d_backward')
- grad_input, grad_grid = op(grad_output, input, grid, 0, 0, False)
- ctx.save_for_backward(grid)
- return grad_input, grad_grid
-
- @staticmethod
- def backward(ctx, grad2_grad_input, grad2_grad_grid):
- _ = grad2_grad_grid # unused
- grid, = ctx.saved_tensors
- grad2_grad_output = None
- grad2_input = None
- grad2_grid = None
-
- if ctx.needs_input_grad[0]:
- grad2_grad_output = _GridSample2dForward.apply(
- grad2_grad_input, grid)
-
- assert not ctx.needs_input_grad[2]
- return grad2_grad_output, grad2_input, grad2_grid
-
-# ----------------------------------------------------------------------------
diff --git a/spaces/Dute8788/anime/app.py b/spaces/Dute8788/anime/app.py
deleted file mode 100644
index 230a0d5f8a3da6ab18ecb8db1cd90016a489b96a..0000000000000000000000000000000000000000
--- a/spaces/Dute8788/anime/app.py
+++ /dev/null
@@ -1,52 +0,0 @@
-import gradio as gr
-import huggingface_hub
-import onnxruntime as rt
-import numpy as np
-import cv2
-
-
-def get_mask(img, s=1024):
- img = (img / 255).astype(np.float32)
- h, w = h0, w0 = img.shape[:-1]
- h, w = (s, int(s * w / h)) if h > w else (int(s * h / w), s)
- ph, pw = s - h, s - w
- img_input = np.zeros([s, s, 3], dtype=np.float32)
- img_input[ph // 2:ph // 2 + h, pw // 2:pw // 2 + w] = cv2.resize(img, (w, h))
- img_input = np.transpose(img_input, (2, 0, 1))
- img_input = img_input[np.newaxis, :]
- mask = rmbg_model.run(None, {'img': img_input})[0][0]
- mask = np.transpose(mask, (1, 2, 0))
- mask = mask[ph // 2:ph // 2 + h, pw // 2:pw // 2 + w]
- mask = cv2.resize(mask, (w0, h0))[:, :, np.newaxis]
- return mask
-
-
-def rmbg_fn(img):
- mask = get_mask(img)
- img = (mask * img + 255 * (1 - mask)).astype(np.uint8)
- mask = (mask * 255).astype(np.uint8)
- img = np.concatenate([img, mask], axis=2, dtype=np.uint8)
- mask = mask.repeat(3, axis=2)
- return mask, img
-
-
-if __name__ == "__main__":
- providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
- model_path = huggingface_hub.hf_hub_download("skytnt/anime-seg", "isnetis.onnx")
- rmbg_model = rt.InferenceSession(model_path, providers=providers)
- app = gr.Blocks()
- with app:
- gr.Markdown("# Anime Remove Background\n\n"
- "\n\n"
- "demo for [https://github.com/SkyTNT/anime-segmentation/](https://github.com/SkyTNT/anime-segmentation/)")
- with gr.Row():
- with gr.Column():
- input_img = gr.Image(label="input image")
- examples_data = [[f"examples/{x:02d}.jpg"] for x in range(1, 4)]
- examples = gr.Dataset(components=[input_img], samples=examples_data)
- run_btn = gr.Button(variant="primary")
- output_mask = gr.Image(label="mask")
- output_img = gr.Image(label="result", image_mode="RGBA")
- examples.click(lambda x: x[0], [examples], [input_img])
- run_btn.click(rmbg_fn, [input_img], [output_mask, output_img])
- app.launch()
diff --git a/spaces/ECCV2022/bytetrack/tutorials/transtrack/tracker.py b/spaces/ECCV2022/bytetrack/tutorials/transtrack/tracker.py
deleted file mode 100644
index 3e1f300bb35dc3b20f59dc912a35db3d8a07fd40..0000000000000000000000000000000000000000
--- a/spaces/ECCV2022/bytetrack/tutorials/transtrack/tracker.py
+++ /dev/null
@@ -1,191 +0,0 @@
-"""
-Copyright (c) https://github.com/xingyizhou/CenterTrack
-Modified by Peize Sun, Rufeng Zhang
-"""
-# coding: utf-8
-import torch
-from scipy.optimize import linear_sum_assignment
-from util import box_ops
-import copy
-
-class Tracker(object):
- def __init__(self, score_thresh, max_age=32):
- self.score_thresh = score_thresh
- self.low_thresh = 0.2
- self.high_thresh = score_thresh + 0.1
- self.max_age = max_age
- self.id_count = 0
- self.tracks_dict = dict()
- self.tracks = list()
- self.unmatched_tracks = list()
- self.reset_all()
-
- def reset_all(self):
- self.id_count = 0
- self.tracks_dict = dict()
- self.tracks = list()
- self.unmatched_tracks = list()
-
- def init_track(self, results):
-
- scores = results["scores"]
- classes = results["labels"]
- bboxes = results["boxes"] # x1y1x2y2
-
- ret = list()
- ret_dict = dict()
- for idx in range(scores.shape[0]):
- if scores[idx] >= self.score_thresh:
- self.id_count += 1
- obj = dict()
- obj["score"] = float(scores[idx])
- obj["bbox"] = bboxes[idx, :].cpu().numpy().tolist()
- obj["tracking_id"] = self.id_count
- obj['active'] = 1
- obj['age'] = 1
- ret.append(obj)
- ret_dict[idx] = obj
-
- self.tracks = ret
- self.tracks_dict = ret_dict
- return copy.deepcopy(ret)
-
-
- def step(self, output_results):
- scores = output_results["scores"]
- bboxes = output_results["boxes"] # x1y1x2y2
- track_bboxes = output_results["track_boxes"] if "track_boxes" in output_results else None # x1y1x2y2
-
- results = list()
- results_dict = dict()
- results_second = list()
-
- tracks = list()
-
- for idx in range(scores.shape[0]):
- if idx in self.tracks_dict and track_bboxes is not None:
- self.tracks_dict[idx]["bbox"] = track_bboxes[idx, :].cpu().numpy().tolist()
-
- if scores[idx] >= self.score_thresh:
- obj = dict()
- obj["score"] = float(scores[idx])
- obj["bbox"] = bboxes[idx, :].cpu().numpy().tolist()
- results.append(obj)
- results_dict[idx] = obj
- elif scores[idx] >= self.low_thresh:
- second_obj = dict()
- second_obj["score"] = float(scores[idx])
- second_obj["bbox"] = bboxes[idx, :].cpu().numpy().tolist()
- results_second.append(second_obj)
- results_dict[idx] = second_obj
-
- tracks = [v for v in self.tracks_dict.values()] + self.unmatched_tracks
- # for trackss in tracks:
- # print(trackss.keys())
- N = len(results)
- M = len(tracks)
-
- ret = list()
- unmatched_tracks = [t for t in range(M)]
- unmatched_dets = [d for d in range(N)]
-
- if N > 0 and M > 0:
- det_box = torch.stack([torch.tensor(obj['bbox']) for obj in results], dim=0) # N x 4
- track_box = torch.stack([torch.tensor(obj['bbox']) for obj in tracks], dim=0) # M x 4
- cost_bbox = 1.0 - box_ops.generalized_box_iou(det_box, track_box) # N x M
-
- matched_indices = linear_sum_assignment(cost_bbox)
- unmatched_dets = [d for d in range(N) if not (d in matched_indices[0])]
- unmatched_tracks = [d for d in range(M) if not (d in matched_indices[1])]
-
- matches = [[],[]]
- for (m0, m1) in zip(matched_indices[0], matched_indices[1]):
- if cost_bbox[m0, m1] > 1.2:
- unmatched_dets.append(m0)
- unmatched_tracks.append(m1)
- else:
- matches[0].append(m0)
- matches[1].append(m1)
-
- for (m0, m1) in zip(matches[0], matches[1]):
- track = results[m0]
- track['tracking_id'] = tracks[m1]['tracking_id']
- track['age'] = 1
- track['active'] = 1
- ret.append(track)
-
- # second association
- N_second = len(results_second)
- unmatched_tracks_obj = list()
- for i in unmatched_tracks:
- #print(tracks[i].keys())
- track = tracks[i]
- if track['active'] == 1:
- unmatched_tracks_obj.append(track)
- M_second = len(unmatched_tracks_obj)
- unmatched_tracks_second = [t for t in range(M_second)]
-
- if N_second > 0 and M_second > 0:
- det_box_second = torch.stack([torch.tensor(obj['bbox']) for obj in results_second], dim=0) # N_second x 4
- track_box_second = torch.stack([torch.tensor(obj['bbox']) for obj in unmatched_tracks_obj], dim=0) # M_second x 4
- cost_bbox_second = 1.0 - box_ops.generalized_box_iou(det_box_second, track_box_second) # N_second x M_second
-
- matched_indices_second = linear_sum_assignment(cost_bbox_second)
- unmatched_tracks_second = [d for d in range(M_second) if not (d in matched_indices_second[1])]
-
- matches_second = [[],[]]
- for (m0, m1) in zip(matched_indices_second[0], matched_indices_second[1]):
- if cost_bbox_second[m0, m1] > 0.8:
- unmatched_tracks_second.append(m1)
- else:
- matches_second[0].append(m0)
- matches_second[1].append(m1)
-
- for (m0, m1) in zip(matches_second[0], matches_second[1]):
- track = results_second[m0]
- track['tracking_id'] = unmatched_tracks_obj[m1]['tracking_id']
- track['age'] = 1
- track['active'] = 1
- ret.append(track)
-
- for i in unmatched_dets:
- trackd = results[i]
- if trackd["score"] >= self.high_thresh:
- self.id_count += 1
- trackd['tracking_id'] = self.id_count
- trackd['age'] = 1
- trackd['active'] = 1
- ret.append(trackd)
-
- # ------------------------------------------------------ #
- ret_unmatched_tracks = []
-
- for j in unmatched_tracks:
- track = tracks[j]
- if track['active'] == 0 and track['age'] < self.max_age:
- track['age'] += 1
- track['active'] = 0
- ret.append(track)
- ret_unmatched_tracks.append(track)
-
- for i in unmatched_tracks_second:
- track = unmatched_tracks_obj[i]
- if track['age'] < self.max_age:
- track['age'] += 1
- track['active'] = 0
- ret.append(track)
- ret_unmatched_tracks.append(track)
-
- # for i in unmatched_tracks:
- # track = tracks[i]
- # if track['age'] < self.max_age:
- # track['age'] += 1
- # track['active'] = 0
- # ret.append(track)
- # ret_unmatched_tracks.append(track)
- #print(len(ret_unmatched_tracks))
-
- self.tracks = ret
- self.tracks_dict = {red_ind:red for red_ind, red in results_dict.items() if 'tracking_id' in red}
- self.unmatched_tracks = ret_unmatched_tracks
- return copy.deepcopy(ret)
diff --git a/spaces/EPFL-VILAB/MultiMAE/utils/pos_embed.py b/spaces/EPFL-VILAB/MultiMAE/utils/pos_embed.py
deleted file mode 100644
index 836bd43d0bfe699b0b37bfec81509e06a2a28f27..0000000000000000000000000000000000000000
--- a/spaces/EPFL-VILAB/MultiMAE/utils/pos_embed.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# Copyright (c) EPFL VILAB.
-# All rights reserved.
-
-# This source code is licensed under the license found in the
-# LICENSE file in the root directory of this source tree.
-# --------------------------------------------------------
-# Based on BEiT, timm, DINO DeiT and MAE-priv code bases
-# https://github.com/microsoft/unilm/tree/master/beit
-# https://github.com/rwightman/pytorch-image-models/tree/master/timm
-# https://github.com/facebookresearch/deit
-# https://github.com/facebookresearch/dino
-# https://github.com/BUPT-PRIV/MAE-priv
-# --------------------------------------------------------
-
-import re
-
-import torch
-
-
-def interpolate_pos_embed_vit(model, checkpoint_model):
- if 'pos_embed' in checkpoint_model:
- pos_embed_checkpoint = checkpoint_model['pos_embed']
- embedding_size = pos_embed_checkpoint.shape[-1]
- num_patches = model.patch_embed.num_patches
- num_extra_tokens = model.pos_embed.shape[-2] - num_patches
- # height (== width) for the checkpoint position embedding
- orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)
- # height (== width) for the new position embedding
- new_size = int(num_patches ** 0.5)
- # class_token and dist_token are kept unchanged
- if orig_size != new_size:
- print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size))
- extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
- # only the position tokens are interpolated
- pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
- pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
- pos_tokens = torch.nn.functional.interpolate(
- pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)
- pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
- new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
- checkpoint_model['pos_embed'] = new_pos_embed
-
-
-def interpolate_pos_embed_multimae(model, checkpoint_model):
- pattern = "input_adapters\.(.*)\.pos_emb"
- matched_keys = [k for k in checkpoint_model if bool(re.match(pattern, k))]
-
- for key in matched_keys:
- domain = re.match(pattern, key).group(1) # group(0) is entire matched regex
- if getattr(model.input_adapters, domain, None) is not None:
- pos_embed_checkpoint = checkpoint_model[key]
- _, _, orig_H, orig_W = pos_embed_checkpoint.shape
- _, _, new_H, new_W = getattr(model.input_adapters, domain).pos_emb.shape
- if (orig_H != new_H) or (orig_W != new_W):
- print(f"Key {key}: Position interpolate from {orig_H}x{orig_W} to {new_H}x{new_W}")
- pos_embed_checkpoint = torch.nn.functional.interpolate(
- pos_embed_checkpoint, size=(new_H, new_W), mode='bicubic', align_corners=False)
- checkpoint_model[key] = pos_embed_checkpoint
diff --git a/spaces/Eddycrack864/Applio-Inference/infer/modules/vc/utils.py b/spaces/Eddycrack864/Applio-Inference/infer/modules/vc/utils.py
deleted file mode 100644
index a1cb0ff84097d1c7eb82373ccf19db061f595096..0000000000000000000000000000000000000000
--- a/spaces/Eddycrack864/Applio-Inference/infer/modules/vc/utils.py
+++ /dev/null
@@ -1,42 +0,0 @@
-import os
-import re
-from fairseq import checkpoint_utils
-
-
-def get_index_path_from_model(sid):
- sid0strip = re.sub(r'\.pth|\.onnx$', '', sid)
- sid0name = os.path.split(sid0strip)[-1] # Extract only the name, not the directory
-
- # Check if the sid0strip has the specific ending format _eXXX_sXXX
- if re.match(r'.+_e\d+_s\d+$', sid0name):
- base_model_name = sid0name.rsplit('_', 2)[0]
- else:
- base_model_name = sid0name
-
- return next(
- (
- f
- for f in [
- os.path.join(root, name)
- for root, _, files in os.walk(os.getenv("index_root"), topdown=False)
- for name in files
- if name.endswith(".index") and "trained" not in name
- ]
- if base_model_name in f
- ),
- "",
- )
-
-
-def load_hubert(config):
- models, _, _ = checkpoint_utils.load_model_ensemble_and_task(
- ["assets/hubert/hubert_base.pt"],
- suffix="",
- )
- hubert_model = models[0]
- hubert_model = hubert_model.to(config.device)
- if config.is_half:
- hubert_model = hubert_model.half()
- else:
- hubert_model = hubert_model.float()
- return hubert_model.eval()
diff --git a/spaces/Epoching/DocumentQA/DiT_Extractor/dit_object_detection/ditod/config.py b/spaces/Epoching/DocumentQA/DiT_Extractor/dit_object_detection/ditod/config.py
deleted file mode 100644
index 40b1a0a08660bdc3c7c27c388fceca42144cb3ec..0000000000000000000000000000000000000000
--- a/spaces/Epoching/DocumentQA/DiT_Extractor/dit_object_detection/ditod/config.py
+++ /dev/null
@@ -1,32 +0,0 @@
-from detectron2.config import CfgNode as CN
-
-
-def add_vit_config(cfg):
- """
- Add config for VIT.
- """
- _C = cfg
-
- _C.MODEL.VIT = CN()
-
- # CoaT model name.
- _C.MODEL.VIT.NAME = ""
-
- # Output features from CoaT backbone.
- _C.MODEL.VIT.OUT_FEATURES = ["layer3", "layer5", "layer7", "layer11"]
-
- _C.MODEL.VIT.IMG_SIZE = [224, 224]
-
- _C.MODEL.VIT.POS_TYPE = "shared_rel"
-
- _C.MODEL.VIT.DROP_PATH = 0.
-
- _C.MODEL.VIT.MODEL_KWARGS = "{}"
-
- _C.SOLVER.OPTIMIZER = "ADAMW"
-
- _C.SOLVER.BACKBONE_MULTIPLIER = 1.0
-
- _C.AUG = CN()
-
- _C.AUG.DETR = False
diff --git a/spaces/Epoching/DocumentQA/ms-marco-electra-base/README.md b/spaces/Epoching/DocumentQA/ms-marco-electra-base/README.md
deleted file mode 100644
index 1013e0496f607588948eb388af2b2a3622e681da..0000000000000000000000000000000000000000
--- a/spaces/Epoching/DocumentQA/ms-marco-electra-base/README.md
+++ /dev/null
@@ -1,64 +0,0 @@
----
-license: apache-2.0
----
-# Cross-Encoder for MS Marco
-
-This model was trained on the [MS Marco Passage Ranking](https://github.com/microsoft/MSMARCO-Passage-Ranking) task.
-
-The model can be used for Information Retrieval: Given a query, encode the query will all possible passages (e.g. retrieved with ElasticSearch). Then sort the passages in a decreasing order. See [SBERT.net Retrieve & Re-rank](https://www.sbert.net/examples/applications/retrieve_rerank/README.html) for more details. The training code is available here: [SBERT.net Training MS Marco](https://github.com/UKPLab/sentence-transformers/tree/master/examples/training/ms_marco)
-
-
-## Usage with Transformers
-
-```python
-from transformers import AutoTokenizer, AutoModelForSequenceClassification
-import torch
-
-model = AutoModelForSequenceClassification.from_pretrained('model_name')
-tokenizer = AutoTokenizer.from_pretrained('model_name')
-
-features = tokenizer(['How many people live in Berlin?', 'How many people live in Berlin?'], ['Berlin has a population of 3,520,031 registered inhabitants in an area of 891.82 square kilometers.', 'New York City is famous for the Metropolitan Museum of Art.'], padding=True, truncation=True, return_tensors="pt")
-
-model.eval()
-with torch.no_grad():
- scores = model(**features).logits
- print(scores)
-```
-
-
-## Usage with SentenceTransformers
-
-The usage becomes easier when you have [SentenceTransformers](https://www.sbert.net/) installed. Then, you can use the pre-trained models like this:
-```python
-from sentence_transformers import CrossEncoder
-model = CrossEncoder('model_name', max_length=512)
-scores = model.predict([('Query', 'Paragraph1'), ('Query', 'Paragraph2') , ('Query', 'Paragraph3')])
-```
-
-
-## Performance
-In the following table, we provide various pre-trained Cross-Encoders together with their performance on the [TREC Deep Learning 2019](https://microsoft.github.io/TREC-2019-Deep-Learning/) and the [MS Marco Passage Reranking](https://github.com/microsoft/MSMARCO-Passage-Ranking/) dataset.
-
-
-| Model-Name | NDCG@10 (TREC DL 19) | MRR@10 (MS Marco Dev) | Docs / Sec |
-| ------------- |:-------------| -----| --- |
-| **Version 2 models** | | |
-| cross-encoder/ms-marco-TinyBERT-L-2-v2 | 69.84 | 32.56 | 9000
-| cross-encoder/ms-marco-MiniLM-L-2-v2 | 71.01 | 34.85 | 4100
-| cross-encoder/ms-marco-MiniLM-L-4-v2 | 73.04 | 37.70 | 2500
-| cross-encoder/ms-marco-MiniLM-L-6-v2 | 74.30 | 39.01 | 1800
-| cross-encoder/ms-marco-MiniLM-L-12-v2 | 74.31 | 39.02 | 960
-| **Version 1 models** | | |
-| cross-encoder/ms-marco-TinyBERT-L-2 | 67.43 | 30.15 | 9000
-| cross-encoder/ms-marco-TinyBERT-L-4 | 68.09 | 34.50 | 2900
-| cross-encoder/ms-marco-TinyBERT-L-6 | 69.57 | 36.13 | 680
-| cross-encoder/ms-marco-electra-base | 71.99 | 36.41 | 340
-| **Other models** | | |
-| nboost/pt-tinybert-msmarco | 63.63 | 28.80 | 2900
-| nboost/pt-bert-base-uncased-msmarco | 70.94 | 34.75 | 340
-| nboost/pt-bert-large-msmarco | 73.36 | 36.48 | 100
-| Capreolus/electra-base-msmarco | 71.23 | 36.89 | 340
-| amberoad/bert-multilingual-passage-reranking-msmarco | 68.40 | 35.54 | 330
-| sebastian-hofstaetter/distilbert-cat-margin_mse-T2-msmarco | 72.82 | 37.88 | 720
-
- Note: Runtime was computed on a V100 GPU.
diff --git a/spaces/EronSamez/RVC_HFmeu/infer/lib/infer_pack/modules/F0Predictor/F0Predictor.py b/spaces/EronSamez/RVC_HFmeu/infer/lib/infer_pack/modules/F0Predictor/F0Predictor.py
deleted file mode 100644
index f56e49e7f0e6eab3babf0711cae2933371b9f9cc..0000000000000000000000000000000000000000
--- a/spaces/EronSamez/RVC_HFmeu/infer/lib/infer_pack/modules/F0Predictor/F0Predictor.py
+++ /dev/null
@@ -1,16 +0,0 @@
-class F0Predictor(object):
- def compute_f0(self, wav, p_len):
- """
- input: wav:[signal_length]
- p_len:int
- output: f0:[signal_length//hop_length]
- """
- pass
-
- def compute_f0_uv(self, wav, p_len):
- """
- input: wav:[signal_length]
- p_len:int
- output: f0:[signal_length//hop_length],uv:[signal_length//hop_length]
- """
- pass
diff --git a/spaces/EronSamez/RVC_HFmeu/infer/lib/train/mel_processing.py b/spaces/EronSamez/RVC_HFmeu/infer/lib/train/mel_processing.py
deleted file mode 100644
index f458775bf62b79f791b419ca7ed62c550ae252d5..0000000000000000000000000000000000000000
--- a/spaces/EronSamez/RVC_HFmeu/infer/lib/train/mel_processing.py
+++ /dev/null
@@ -1,132 +0,0 @@
-import torch
-import torch.utils.data
-from librosa.filters import mel as librosa_mel_fn
-import logging
-
-logger = logging.getLogger(__name__)
-
-MAX_WAV_VALUE = 32768.0
-
-
-def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
- """
- PARAMS
- ------
- C: compression factor
- """
- return torch.log(torch.clamp(x, min=clip_val) * C)
-
-
-def dynamic_range_decompression_torch(x, C=1):
- """
- PARAMS
- ------
- C: compression factor used to compress
- """
- return torch.exp(x) / C
-
-
-def spectral_normalize_torch(magnitudes):
- return dynamic_range_compression_torch(magnitudes)
-
-
-def spectral_de_normalize_torch(magnitudes):
- return dynamic_range_decompression_torch(magnitudes)
-
-
-# Reusable banks
-mel_basis = {}
-hann_window = {}
-
-
-def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
- """Convert waveform into Linear-frequency Linear-amplitude spectrogram.
-
- Args:
- y :: (B, T) - Audio waveforms
- n_fft
- sampling_rate
- hop_size
- win_size
- center
- Returns:
- :: (B, Freq, Frame) - Linear-frequency Linear-amplitude spectrogram
- """
- # Validation
- if torch.min(y) < -1.07:
- logger.debug("min value is %s", str(torch.min(y)))
- if torch.max(y) > 1.07:
- logger.debug("max value is %s", str(torch.max(y)))
-
- # Window - Cache if needed
- global hann_window
- dtype_device = str(y.dtype) + "_" + str(y.device)
- wnsize_dtype_device = str(win_size) + "_" + dtype_device
- if wnsize_dtype_device not in hann_window:
- hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(
- dtype=y.dtype, device=y.device
- )
-
- # Padding
- y = torch.nn.functional.pad(
- y.unsqueeze(1),
- (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),
- mode="reflect",
- )
- y = y.squeeze(1)
-
- # Complex Spectrogram :: (B, T) -> (B, Freq, Frame, RealComplex=2)
- spec = torch.stft(
- y,
- n_fft,
- hop_length=hop_size,
- win_length=win_size,
- window=hann_window[wnsize_dtype_device],
- center=center,
- pad_mode="reflect",
- normalized=False,
- onesided=True,
- return_complex=False,
- )
-
- # Linear-frequency Linear-amplitude spectrogram :: (B, Freq, Frame, RealComplex=2) -> (B, Freq, Frame)
- spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
- return spec
-
-
-def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
- # MelBasis - Cache if needed
- global mel_basis
- dtype_device = str(spec.dtype) + "_" + str(spec.device)
- fmax_dtype_device = str(fmax) + "_" + dtype_device
- if fmax_dtype_device not in mel_basis:
- mel = librosa_mel_fn(
- sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax
- )
- mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(
- dtype=spec.dtype, device=spec.device
- )
-
- # Mel-frequency Log-amplitude spectrogram :: (B, Freq=num_mels, Frame)
- melspec = torch.matmul(mel_basis[fmax_dtype_device], spec)
- melspec = spectral_normalize_torch(melspec)
- return melspec
-
-
-def mel_spectrogram_torch(
- y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False
-):
- """Convert waveform into Mel-frequency Log-amplitude spectrogram.
-
- Args:
- y :: (B, T) - Waveforms
- Returns:
- melspec :: (B, Freq, Frame) - Mel-frequency Log-amplitude spectrogram
- """
- # Linear-frequency Linear-amplitude spectrogram :: (B, T) -> (B, Freq, Frame)
- spec = spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center)
-
- # Mel-frequency Log-amplitude spectrogram :: (B, Freq, Frame) -> (B, Freq=num_mels, Frame)
- melspec = spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax)
-
- return melspec
diff --git a/spaces/EuroPython2022/mmocr-demo/configs/_base_/schedules/schedule_adam_step_6e.py b/spaces/EuroPython2022/mmocr-demo/configs/_base_/schedules/schedule_adam_step_6e.py
deleted file mode 100644
index 5b33a2f924e502fc3a7f53f080a43fae983bb00c..0000000000000000000000000000000000000000
--- a/spaces/EuroPython2022/mmocr-demo/configs/_base_/schedules/schedule_adam_step_6e.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# optimizer
-optimizer = dict(type='Adam', lr=1e-3)
-optimizer_config = dict(grad_clip=None)
-# learning policy
-lr_config = dict(policy='step', step=[3, 4])
-# running settings
-runner = dict(type='EpochBasedRunner', max_epochs=6)
-checkpoint_config = dict(interval=1)
diff --git a/spaces/FlippFuzz/whisper-webui/src/source.py b/spaces/FlippFuzz/whisper-webui/src/source.py
deleted file mode 100644
index e304e278bfae8ef289c999fc76311ce01b547991..0000000000000000000000000000000000000000
--- a/spaces/FlippFuzz/whisper-webui/src/source.py
+++ /dev/null
@@ -1,80 +0,0 @@
-# Gradio seems to truncate files without keeping the extension, so we need to truncate the file prefix ourself
-import os
-import pathlib
-from typing import List
-import zipfile
-
-import ffmpeg
-from more_itertools import unzip
-
-from src.download import ExceededMaximumDuration, download_url
-
-MAX_FILE_PREFIX_LENGTH = 17
-
-class AudioSource:
- def __init__(self, source_path, source_name = None, audio_duration = None):
- self.source_path = source_path
- self.source_name = source_name
- self._audio_duration = audio_duration
-
- # Load source name if not provided
- if (self.source_name is None):
- file_path = pathlib.Path(self.source_path)
- self.source_name = file_path.name
-
- def get_audio_duration(self):
- if self._audio_duration is None:
- self._audio_duration = float(ffmpeg.probe(self.source_path)["format"]["duration"])
-
- return self._audio_duration
-
- def get_full_name(self):
- return self.source_name
-
- def get_short_name(self, max_length: int = MAX_FILE_PREFIX_LENGTH):
- file_path = pathlib.Path(self.source_name)
- short_name = file_path.stem[:max_length] + file_path.suffix
-
- return short_name
-
- def __str__(self) -> str:
- return self.source_path
-
-class AudioSourceCollection:
- def __init__(self, sources: List[AudioSource]):
- self.sources = sources
-
- def __iter__(self):
- return iter(self.sources)
-
-def get_audio_source_collection(urlData: str, multipleFiles: List, microphoneData: str, input_audio_max_duration: float = -1) -> List[AudioSource]:
- output: List[AudioSource] = []
-
- if urlData:
- # Download from YouTube. This could also be a playlist or a channel.
- output.extend([ AudioSource(x) for x in download_url(urlData, input_audio_max_duration, playlistItems=None) ])
- else:
- # Add input files
- if (multipleFiles is not None):
- output.extend([ AudioSource(x.name) for x in multipleFiles ])
- if (microphoneData is not None):
- output.append(AudioSource(microphoneData))
-
- total_duration = 0
-
- # Calculate total audio length. We do this even if input_audio_max_duration
- # is disabled to ensure that all the audio files are valid.
- for source in output:
- audioDuration = ffmpeg.probe(source.source_path)["format"]["duration"]
- total_duration += float(audioDuration)
-
- # Save audio duration
- source._audio_duration = float(audioDuration)
-
- # Ensure the total duration of the audio is not too long
- if input_audio_max_duration > 0:
- if float(total_duration) > input_audio_max_duration:
- raise ExceededMaximumDuration(videoDuration=total_duration, maxDuration=input_audio_max_duration, message="Video(s) is too long")
-
- # Return a list of audio sources
- return output
\ No newline at end of file
diff --git a/spaces/GEM/submission-form/Makefile b/spaces/GEM/submission-form/Makefile
deleted file mode 100644
index 57cf00def66eea5ba317751efa8f0c3aedeb70c6..0000000000000000000000000000000000000000
--- a/spaces/GEM/submission-form/Makefile
+++ /dev/null
@@ -1,8 +0,0 @@
-style:
- python -m black --line-length 119 --target-version py39 .
- python -m isort .
-
-quality:
- python -m black --check --line-length 119 --target-version py39 .
- python -m isort --check-only .
- python -m flake8 --max-line-length 119
\ No newline at end of file
diff --git a/spaces/GIGACHAhoon/BasicNNYoutubeSentimentTop5CommentPrediction/youtube_comment_tool.py b/spaces/GIGACHAhoon/BasicNNYoutubeSentimentTop5CommentPrediction/youtube_comment_tool.py
deleted file mode 100644
index 78cc338c0a4db52e806c038be9bb020fb2dccfb9..0000000000000000000000000000000000000000
--- a/spaces/GIGACHAhoon/BasicNNYoutubeSentimentTop5CommentPrediction/youtube_comment_tool.py
+++ /dev/null
@@ -1,49 +0,0 @@
-from googleapiclient.discovery import build
-from dotenv import load_dotenv
-import os
-from urllib.parse import urlparse
-from urllib.parse import parse_qs
-
-def get_top5_comments(url):
- v_id = video_id(url)
- load_dotenv()
- api_key = os.getenv('api_key')
- youtube = build('youtube', 'v3', developerKey=api_key)
- try:
- comments_response = youtube.commentThreads().list(
- part='snippet',
- videoId=v_id,
- textFormat='plainText',
- maxResults=5,
- order='relevance').execute()
-
- top_five = []
- for comment in comments_response['items']:
- comment_text = comment['snippet']['topLevelComment']['snippet']['textDisplay']
- top_five.append(comment_text)
- return top_five
- except:
- return None
-
-
-def video_id(value):
- """
- Examples:
- - http://youtu.be/SA2iWivDJiE
- - http://www.youtube.com/watch?v=_oPAwA_Udwc&feature=feedu
- - http://www.youtube.com/embed/SA2iWivDJiE
- - http://www.youtube.com/v/SA2iWivDJiE?version=3&hl=en_US
- """
- query = urlparse(value)
- if query.hostname == 'youtu.be':
- return query.path[1:]
- if query.hostname in ('www.youtube.com', 'youtube.com'):
- if query.path == '/watch':
- p = parse_qs(query.query)
- return p['v'][0]
- if query.path[:7] == '/embed/':
- return query.path.split('/')[2]
- if query.path[:3] == '/v/':
- return query.path.split('/')[2]
- # fail?
- return None
diff --git a/spaces/GT-RIPL/GPT-K/app.py b/spaces/GT-RIPL/GPT-K/app.py
deleted file mode 100644
index 1b68d5df8c3c7984bb1edb68cc397055b650e9c3..0000000000000000000000000000000000000000
--- a/spaces/GT-RIPL/GPT-K/app.py
+++ /dev/null
@@ -1,391 +0,0 @@
-from pathlib import Path
-import os
-import time
-import gradio as gr
-import requests
-import numpy as np
-from pathlib import Path
-
-import torch
-import torch.nn.functional as F
-import open_clip
-import faiss
-from transformers import TextIteratorStreamer
-from threading import Thread
-
-from conversation import default_conversation, conv_templates, Conversation
-from knowledge import TextDB
-from knowledge.transforms import five_crop, nine_crop
-from knowledge.utils import refine_cosine
-from model import get_gptk_model, get_gptk_image_transform
-
-
-no_change_btn = gr.Button.update()
-enable_btn = gr.Button.update(interactive=True)
-disable_btn = gr.Button.update(interactive=False)
-knwl_none = (None, ) * 30
-knwl_unchange = (gr.Image.update(), ) * 15 + (gr.Textbox.update(), ) * 15
-moderation_msg = "YOUR INPUT VIOLATES OUR CONTENT MODERATION GUIDELINES. PLEASE TRY AGAIN."
-
-
-def violates_moderation(text):
- """
- Check whether the text violates OpenAI moderation API.
- """
- if "OPENAI_API_KEY" not in os.environ:
- print("OPENAI_API_KEY not found, skip content moderation check...")
- return False
-
- url = "https://api.openai.com/v1/moderations"
- headers = {
- "Content-Type": "application/json",
- "Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]
- }
- text = text.replace("\n", "")
- data = "{" + '"input": ' + f'"{text}"' + "}"
- data = data.encode("utf-8")
- try:
- ret = requests.post(url, headers=headers, data=data, timeout=5)
- flagged = ret.json()["results"][0]["flagged"]
- except requests.exceptions.RequestException as e:
- flagged = False
- except KeyError as e:
- flagged = False
-
- return flagged
-
-
-def load_demo():
- state = default_conversation.copy()
- return state
-
-
-def regenerate(state: Conversation):
- state.messages[-1][-1] = None
- prev_human_msg = state.messages[-2]
- if type(prev_human_msg[1]) in (tuple, list):
- prev_human_msg[1] = prev_human_msg[1][:2]
- state.skip_next = False
-
- return (state, state.to_gradio_chatbot(), "", None, disable_btn, disable_btn, disable_btn)
-
-
-def clear_history():
- state = default_conversation.copy()
- return (state, state.to_gradio_chatbot(), "", None) + (enable_btn, disable_btn, disable_btn) + knwl_none
-
-
-def add_text(state: Conversation, text, image):
- if len(text) <= 0 and image is None:
- state.skip_next = True
- return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 3
-
- if violates_moderation(text):
- state.skip_next = True
- return (state, state.to_gradio_chatbot(), moderation_msg, None) + (no_change_btn,) * 3
-
- if image is not None:
- text = (text, image)
- if len(state.get_images(return_pil=True)) > 0:
- state = default_conversation.copy()
- state.append_message(state.roles[0], text)
- state.append_message(state.roles[1], None)
- state.skip_next = False
-
- return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 3
-
-
-def search(image, pos, topk, knwl_db, knwl_idx):
- with torch.cuda.amp.autocast():
- image = query_trans(image).unsqueeze(0).to(device)
- query = F.normalize(query_enc(image), dim=-1)
- query = query.cpu().numpy()
-
- _, I = knwl_idx.search(query, 4*topk)
- score, I = refine_cosine(knwl_db.feature, query, I, device, topk)
- score, I = score.flatten(), I.flatten()
- embd, text = knwl_db[I]
- pos = np.full((topk, ), fill_value=pos)
-
- query = torch.FloatTensor(query).unsqueeze(0).to(device)
- embd = torch.FloatTensor(embd).unsqueeze(0).to(device)
- pos = torch.LongTensor(pos).unsqueeze(0).to(device)
- score = torch.FloatTensor(score).unsqueeze(0).to(device)
-
- return query, embd, pos, score, text
-
-
-def retrieve_knowledge(image):
- knwl_embd = {}
- knwl_text = {}
- for query_type, topk_q in topk.items():
- if topk_q == 0: continue
-
- if query_type == "whole":
- images = [image, ]
- knwl_text[query_type] = {i: {} for i in range(1)}
- elif query_type == "five":
- images = five_crop(image)
- knwl_text[query_type] = {i: {} for i in range(5)}
- elif query_type == "nine":
- images = nine_crop(image)
- knwl_text[query_type] = {i: {} for i in range(9)}
- else:
- raise ValueError
-
- knwl_embd[query_type] = {}
- for knwl_type, (knwl_db_t, knwl_idx_t) in knwl_db.items():
- query, embed, pos, score = [], [], [], []
- for i, img in enumerate(images):
- query_i, embed_i, pos_i, score_i, text_i = search(
- img, i, topk_q, knwl_db_t, knwl_idx_t
- )
- query.append(query_i)
- embed.append(embed_i)
- pos.append(pos_i)
- score.append(score_i)
- knwl_text[query_type][i][knwl_type] = text_i
-
- query = torch.cat(query, dim=1)
- embed = torch.cat(embed, dim=1)
- pos = torch.cat(pos, dim=1)
- score = torch.cat(score, dim=1)
-
- knwl_embd[query_type][knwl_type] = {
- "embed": embed, "query": query, "pos": pos, "score": score
- }
-
- return knwl_embd, knwl_text
-
-
-@torch.inference_mode()
-def generate(state: Conversation, temperature, top_p, max_new_tokens):
- if state.skip_next: # This generate call is skipped due to invalid inputs
- yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 3 + knwl_unchange
- return
-
- if len(state.messages) == state.offset + 2: # First round of conversation
- new_state = conv_templates["gptk"].copy()
- new_state.append_message(new_state.roles[0], state.messages[-2][1])
- new_state.append_message(new_state.roles[1], None)
- state = new_state
-
- # retrieve and visualize knowledge
- image = state.get_images(return_pil=True)[0]
- knwl_embd, knwl = retrieve_knowledge(image)
- knwl_img, knwl_txt, idx = [None, ] * 15, ["", ] * 15, 0
- for query_type, knwl_pos in (("whole", 1), ("five", 5), ("nine", 9)):
- if query_type == "whole":
- images = [image, ]
- elif query_type == "five":
- images = five_crop(image)
- elif query_type == "nine":
- images = nine_crop(image)
-
- for pos in range(knwl_pos):
- try:
- txt = ""
- for k, v in knwl[query_type][pos].items():
- v = ", ".join([vi.replace("_", " ") for vi in v])
- txt += f"**[{k.upper()}]:** {v}\n\n"
- knwl_txt[idx] += txt
-
- img = images[pos]
- img = query_trans.transforms[0](img)
- img = query_trans.transforms[1](img)
- img = query_trans.transforms[2](img)
- knwl_img[idx] = img
- except KeyError:
- pass
- idx += 1
- knwl_vis = tuple(knwl_img + knwl_txt)
- yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 3 + knwl_vis
-
- # generate output
- prompt = state.get_prompt().replace("USER: \n", "")
- prompt = prompt.split("USER:")[-1].replace("ASSISTANT:", "")
- image_pt = gptk_trans(image).to(device).unsqueeze(0)
- samples = {"image": image_pt, "knowledge": knwl_embd, "prompt": prompt}
- streamer = TextIteratorStreamer(
- gptk_model.llm_tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=15
- )
- thread = Thread(
- target=gptk_model.generate,
- kwargs=dict(
- samples=samples,
- use_nucleus_sampling=(temperature > 0.001),
- max_length=min(int(max_new_tokens), 1024),
- top_p=float(top_p),
- temperature=float(temperature),
- streamer=streamer,
- num_beams=1,
- length_penalty=0.0,
- auto_cast=True
- )
- )
- thread.start()
-
- generated_text = ""
- for new_text in streamer:
- generated_text += new_text
- state.messages[-1][-1] = generated_text + "▌"
- yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 3 + knwl_unchange
- time.sleep(0.03)
- state.messages[-1][-1] = state.messages[-1][-1][:-1]
- yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 3 + knwl_unchange
-
-
-title_markdown = ("""
-# GPT-K: Knowledge Augmented Vision-and-Language Assistant
-""")
-
-tos_markdown = ("""
-### Terms of use
-By using this service, users are required to agree to the following terms:
-The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research.
-Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
-For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
-""")
-
-learn_more_markdown = ("""
-### License
-The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI, and [Privacy Practices](https://chrome.google.com/webstore/detail/sharegpt-share-your-chatg/daiacboceoaocpibfodeljbdfacokfjb) of ShareGPT. Please contact us if you find any potential violation.
-""")
-
-
-def build_demo():
- textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", container=False)
- imagebox = gr.Image(type="pil")
-
- with gr.Blocks(title="GPT-K", theme=gr.themes.Base()) as demo:
- state = gr.State()
- gr.Markdown(title_markdown)
-
- with gr.Row():
- with gr.Column(scale=3):
- gr.Examples(examples=[
- ["examples/mona_lisa.jpg", "Discuss the historical impact and the significance of this painting in the art world."],
- ["examples/mona_lisa_dog.jpg", "Describe this photo in detail."],
- ["examples/horseshoe_bend.jpg", "What are the possible reasons of the formation of this sight?"],
- ], inputs=[imagebox, textbox])
-
- imagebox.render()
- with gr.Row():
- with gr.Column(scale=8):
- textbox.render()
- with gr.Column(scale=1, min_width=60):
- submit_btn = gr.Button(value="Submit")
-
- with gr.Row():
- regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False, scale=1)
- clear_btn = gr.Button(value="🗑️ Clear", interactive=False, scale=1)
-
- with gr.Accordion("Parameters", open=True):
- temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.0, step=0.1, interactive=True, label="Temperature",)
- top_p = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, step=0.1, interactive=True, label="Top P",)
- max_output_tokens = gr.Slider(minimum=0, maximum=1024, value=512, step=64, interactive=True, label="Max output tokens",)
-
- with gr.Column(scale=6):
- chatbot = gr.Chatbot(elem_id="chatbot", label="GPT-K Chatbot", height=550)
-
- gr.Markdown("## Retrieved Knowledge")
- knwl_img, knwl_txt = [], []
- for query_type, knwl_pos in (("whole", 1), ("five", 5), ("nine", 9)):
- with gr.Tab(query_type):
- for p in range(knwl_pos):
- with gr.Tab(str(p)):
- with gr.Row():
- with gr.Column(scale=1):
- knwl_img.append(gr.Image(type="pil", show_label=False, interactive=False))
- with gr.Column(scale=7):
- knwl_txt.append(gr.Markdown())
- knwl_vis = knwl_img + knwl_txt
-
- gr.Markdown(tos_markdown)
- gr.Markdown(learn_more_markdown)
-
- # Register listeners
- btn_list = [submit_btn, regenerate_btn, clear_btn]
- regenerate_btn.click(
- regenerate, [state], [state, chatbot, textbox, imagebox] + btn_list
- ).then(
- generate,
- [state, temperature, top_p, max_output_tokens],
- [state, chatbot] + btn_list + knwl_vis
- )
-
- clear_btn.click(
- clear_history, None, [state, chatbot, textbox, imagebox] + btn_list + knwl_vis
- )
-
- textbox.submit(
- add_text, [state, textbox, imagebox], [state, chatbot, textbox, imagebox] + btn_list
- ).then(
- generate,
- [state, temperature, top_p, max_output_tokens],
- [state, chatbot] + btn_list + knwl_vis
- )
-
- submit_btn.click(
- add_text, [state, textbox, imagebox], [state, chatbot, textbox, imagebox] + btn_list
- ).then(
- generate,
- [state, temperature, top_p, max_output_tokens],
- [state, chatbot] + btn_list + knwl_vis
- )
-
- demo.load(load_demo, None, [state])
-
- return demo
-
-
-def build_knowledge():
- def get_knwl(knowledge_db):
- knwl_db = TextDB(Path(knowledge_db)/"knowledge_db.hdf5")
- knwl_db.feature = knwl_db.feature
- knwl_idx = faiss.read_index(str(Path(knowledge_db)/"faiss.index"))
- knwl_idx.add(knwl_db.feature.astype(np.float32))
-
- return knwl_db, knwl_idx
-
- knwl_db = {
- "obj": get_knwl('knowledge/(dataset-object)(clip-model-ViT-g-14)(dbscan)(eps-0.15)(ms-1)'),
- "act": get_knwl('knowledge/(dataset-action)(clip-model-ViT-g-14)(dbscan)(eps-0.15)(ms-1)'),
- "attr": get_knwl('knowledge/(dataset-attribute)(clip-model-ViT-g-14)(dbscan)(eps-0.15)(ms-1)'),
- }
- d_knwl = knwl_db["obj"][0].feature.shape[-1]
-
- return knwl_db, d_knwl
-
-
-def build_query_model():
- query_enc, _, query_trans = open_clip.create_model_and_transforms(
- "ViT-g-14", pretrained="laion2b_s34b_b88k", precision='fp16'
- )
- query_enc = query_enc.visual.to(device).eval()
-
- return query_enc, query_trans
-
-
-def build_gptk_model():
- _, gptk_trans = get_gptk_image_transform()
- topk = {"whole": 60, "five": 24, "nine": 16}
- gptk_model = get_gptk_model(d_knwl=d_knwl, topk=topk)
- gptk_ckpt = "model/ckpt/gptk-vicuna7b.pt"
- gptk_ckpt = torch.load(gptk_ckpt, map_location="cpu")
- gptk_model.load_state_dict(gptk_ckpt, strict=False)
- gptk_model = gptk_model.to(device).eval()
-
- return gptk_model, gptk_trans, topk
-
-
-if torch.cuda.is_available():
- device = torch.device("cuda")
-else:
- device = torch.device("cpu")
-
-knwl_db, d_knwl = build_knowledge()
-gptk_model, gptk_trans, topk = build_gptk_model()
-query_enc, query_trans = build_query_model()
-demo = build_demo()
-demo.queue().launch()
\ No newline at end of file
diff --git a/spaces/GT4SD/paccmann_rl/model_cards/article.md b/spaces/GT4SD/paccmann_rl/model_cards/article.md
deleted file mode 100644
index 36b8d119c793b77f9ef96bcb1bf8826daac857f2..0000000000000000000000000000000000000000
--- a/spaces/GT4SD/paccmann_rl/model_cards/article.md
+++ /dev/null
@@ -1,96 +0,0 @@
-# Model documentation & parameters
-
-**Algorithm Version**: Which model version (either protein-target-driven or gene-expression-profile-driven) to use and which checkpoint to rely on.
-
-**Inference type**: Whether the model should be conditioned on the target (default) or whether the model is used in an `Unbiased` manner.
-
-**Protein target**: An AAS of a protein target used for conditioning. Only use if `Inference type` is `Conditional` and if the `Algorithm version` is a Protein model.
-
-**Gene expression target**: A list of 2128 floats, representing the embedding of gene expression profile to be used for conditioning. Only use if `Inference type` is `Conditional` and if the `Algorithm version` is a Omic model.
-
-**Decoding temperature**: The temperature parameter in the SMILES/SELFIES decoder. Higher values lead to more explorative choices, smaller values culminate in mode collapse.
-
-**Maximal sequence length**: The maximal number of SMILES tokens in the generated molecule.
-
-**Number of samples**: How many samples should be generated (between 1 and 50).
-
-
-# Model card -- PaccMannRL
-
-**Model Details**: PaccMannRL is a language model for conditional molecular design. It consists of a domain-specific encoder (for protein targets or gene expression profiles) and a generic molecular decoder. Both components are finetuned together using RL to convert the context representation into a molecule with high affinity toward the context (i.e., binding affinity to the protein or high inhibitory effect for the cell profile).
-
-**Developers**: Jannis Born, Matteo Manica and colleagues from IBM Research.
-
-**Distributors**: Original authors' code wrapped and distributed by GT4SD Team (2023) from IBM Research.
-
-**Model date**: Published in 2021.
-
-**Model version**: Models trained and distribuetd by the original authors.
-- **Protein_v0**: Molecular decoder pretrained on 1.5M molecules from ChEMBL. Protein encoder pretrained on 404k proteins from UniProt. Encoder and decoder finetuned on 41 SARS-CoV-2-related protein targets with a binding affinity predictor trained on BindingDB.
-- **Omic_v0**: Molecular decoder pretrained on 1.5M molecules from ChEMBL. Gene expression encoder pretrained on 12k gene expression profiles from TCGA. Encoder and decoder finetuned on a few hundred cancer cell profiles from GDSC with a IC50 predictor trained on GDSC.
-
-**Model type**: A language-based molecular generative model that can be optimized with RL to generate molecules with high affinity toward a context.
-
-**Information about training algorithms, parameters, fairness constraints or other applied approaches, and features**:
-- **Protein**: Parameters as provided on [(GitHub repo)](https://github.com/PaccMann/paccmann_sarscov2).
-- **Omics**: Parameters as provided on [(GitHub repo)](https://github.com/PaccMann/paccmann_rl).
-
-**Paper or other resource for more information**:
-- **Protein**: [PaccMannRL: De novo generation of hit-like anticancer molecules from transcriptomic data via reinforcement learning (2021; *iScience*)](https://www.cell.com/iscience/fulltext/S2589-0042(21)00237-6).
-- **Omics**: [Data-driven molecular design for discovery and synthesis of novel ligands: a case study on SARS-CoV-2 (2021; *Machine Learning: Science and Technology*)](https://iopscience.iop.org/article/10.1088/2632-2153/abe808/meta).
-
-**License**: MIT
-
-**Where to send questions or comments about the model**: Open an issue on [GT4SD repository](https://github.com/GT4SD/gt4sd-core).
-
-**Intended Use. Use cases that were envisioned during development**: Chemical research, in particular drug discovery.
-
-**Primary intended uses/users**: Researchers and computational chemists using the model for model comparison or research exploration purposes.
-
-**Out-of-scope use cases**: Production-level inference, producing molecules with harmful properties.
-
-**Factors**: Not applicable.
-
-**Metrics**: High reward on generating molecules with high affinity toward context.
-
-**Datasets**: ChEMBL, UniProt, GDSC and BindingDB (see above).
-
-**Ethical Considerations**: Unclear, please consult with original authors in case of questions.
-
-**Caveats and Recommendations**: Unclear, please consult with original authors in case of questions.
-
-Model card prototype inspired by [Mitchell et al. (2019)](https://dl.acm.org/doi/abs/10.1145/3287560.3287596?casa_token=XD4eHiE2cRUAAAAA:NL11gMa1hGPOUKTAbtXnbVQBDBbjxwcjGECF_i-WC_3g1aBgU1Hbz_f2b4kI_m1in-w__1ztGeHnwHs)
-
-## Citation
-
-**Omics**:
-```bib
-@article{born2021paccmannrl,
- title = {PaccMann\textsuperscript{RL}: De novo generation of hit-like anticancer molecules from transcriptomic data via reinforcement learning},
- journal = {iScience},
- volume = {24},
- number = {4},
- pages = {102269},
- year = {2021},
- issn = {2589-0042},
- doi = {https://doi.org/10.1016/j.isci.2021.102269},
- url = {https://www.cell.com/iscience/fulltext/S2589-0042(21)00237-6},
- author = {Born, Jannis and Manica, Matteo and Oskooei, Ali and Cadow, Joris and Markert, Greta and {Rodr{\'{i}}guez Mart{\'{i}}nez}, Mar{\'{i}}a}
-}
-```
-
-**Proteins**:
-```bib
-@article{born2021datadriven,
- author = {Born, Jannis and Manica, Matteo and Cadow, Joris and Markert, Greta and Mill, Nil Adell and Filipavicius, Modestas and Janakarajan, Nikita and Cardinale, Antonio and Laino, Teodoro and {Rodr{\'{i}}guez Mart{\'{i}}nez}, Mar{\'{i}}a},
- doi = {10.1088/2632-2153/abe808},
- issn = {2632-2153},
- journal = {Machine Learning: Science and Technology},
- number = {2},
- pages = {025024},
- title = {{Data-driven molecular design for discovery and synthesis of novel ligands: a case study on SARS-CoV-2}},
- url = {https://iopscience.iop.org/article/10.1088/2632-2153/abe808},
- volume = {2},
- year = {2021}
-}
-```
\ No newline at end of file
diff --git a/spaces/Gen-Sim/Gen-Sim/scripts/metascripts_finetuning/pretrain20_finetune_2.sh b/spaces/Gen-Sim/Gen-Sim/scripts/metascripts_finetuning/pretrain20_finetune_2.sh
deleted file mode 100644
index 9c75e0893ecd17bca59ea771eab11af506792cbd..0000000000000000000000000000000000000000
--- a/spaces/Gen-Sim/Gen-Sim/scripts/metascripts_finetuning/pretrain20_finetune_2.sh
+++ /dev/null
@@ -1,12 +0,0 @@
-#!/bin/bash
-#SBATCH -c 10
-#SBATCH -n 1
-#SBATCH -o logs/%j.out
-#SBATCH --exclusive
-STEPS=${1-'50000'}
-
-
-sh scripts/traintest_scripts/train_test_multi_task_finetune_goal.sh data \
- "[color_linked_ball_bowl_ordering,color_specific_container_fill,insert_blocks_into_fixture,sort_insert_color_coordinated_blocks,color_ordered_blocks_on_pallet,color-coordinated-sphere-insertion,rainbow-stack,put-block-in-bowl,vertical-insertion-blocks,stack-blocks-in-container,'Four-corner-pyramid-challenge','create-pyramid-with-color-coded-ells','align-balls-in-colored-zones','construct-corner-blocks','color-linked-ball-bowl-ordering','create-pyramid-blocks-and-container','color-specific-container-fill','color-ordered-container-arrangement','pyramid-blocks-assemble']" \
- "[stack-block-pyramid,put-block-in-bowl,align-box-corner,packing-boxes,block-insertion]" \
- gpt20_mixcliport2_finetune
diff --git a/spaces/Goya11/zimu/app.py b/spaces/Goya11/zimu/app.py
deleted file mode 100644
index 99da47c7fd123becc1513020a275f4871d4b0111..0000000000000000000000000000000000000000
--- a/spaces/Goya11/zimu/app.py
+++ /dev/null
@@ -1,179 +0,0 @@
-import gradio as gr
-import cv2
-#-*- coding:utf-8 -*-
-import wave
-import time
-start1=time.time()
-from pydub import AudioSegment
-from pydub.silence import split_on_silence
-import os
-import shutil
-import sys
-import torch
-import wenetruntime as wenet
-file='./data/input.mp4'
-print("载入术语库")
-shuyu=[]
-from ppasr.infer_utils.pun_predictor import PunctuationPredictor
-
-def to_black(image):
- # -*- coding:utf-8 -*-
- import wave
- import time
- start1 = time.time()
- from pydub import AudioSegment
- from pydub.silence import split_on_silence
- import os
- import shutil
- import sys
- import torch
- import wenetruntime as wenet
- file = './data/input.mp4'
- print("载入术语库")
- shuyu = []
- from ppasr.infer_utils.pun_predictor import PunctuationPredictor
-
- pun_predictor = PunctuationPredictor(model_dir='pun_models') # 加载一个生成标点符号的模型
- # 加入我们要加权重的术语
- shuyu_txt = open('术语_1.txt', 'r', encoding='utf-8')
- for i in shuyu_txt:
- shuyu.append(i.strip())
- print("载入术语库成功")
-
- import os
- a = os.system(
- "ffmpeg -i " + file + " -acodec pcm_s16le -f s16le -ac 1 -ar 16000 -f wav ./temp_wav/1.wav") # 提取MP4中的音频
- print(a)
- print("开始处理...请等待")
-
- time.sleep(3)
- # 对声音进行压缩
- sound = AudioSegment.from_mp3("./temp_wav/1.wav")
- loudness = sound.dBFS
- # print(loudness)
-
- # 设置单声道
- sound = sound.set_channels(1)
-
- # 压缩帧率
- sound = sound.set_frame_rate(16000)
-
- # 对音频进行分段
- # min_silence_len,持续多少时间可认定为静默,默认值1000ms
- #
- # silence_thresh,声音大小小于多少时可认定为静默,默认值为-16dBFS,根据平均值-23,那么默认值无疑会导致没有输出,笔者调整为-30后,切分的总数位51 。
- #
- # keep_silence,为切分结果前端添加一段静默音频,默认值为100ms
- #
- # seek_step,两次切分处理的间隔时间,默认值1ms
-
- chunks, start, end = split_on_silence(sound,
- # must be silent for at least half a second,沉默半秒
- min_silence_len=400,
- # consider it silent if quieter than -16 dBFS
- silence_thresh=-46,
- keep_silence=400
-
- )
- print('总分段:', len(chunks))
- print(start, end)
- # 将音频分段,按照断句时间,暂时保存分段的wav文件
- for i, chunk in enumerate(chunks):
- chunk.export("./temp/-{0}.wav".format(i), format="wav")
-
- # print(i)
- # -*- coding: utf-8 -*-
-
- '''
- for x in range(0,int(len(sound)/1000)):
- print(x,sound[x*1000:(x+1)*1000].max_dBFS)
- '''
-
- def get_format_time(time_long):
- # 一个转成srt格式的函数
- def format_number(num):
- if len(str(num)) > 1:
- return str(num)
- else:
- return "0" + str(num)
-
- myhour = 0
- mysecond = int(time_long / 1000)
- myminute = 0
- mymilsec = 0
- if mysecond < 1:
- return "00:00:00,%s" % (time_long)
- else:
- if mysecond > 60:
- myminute = int(mysecond / 60)
- if myminute > 60:
- myhour = int(myminute / 60)
- myminute = myminute - myhour * 60
- mysecond = mysecond - myhour * 3600 - myminute * 60
- mymilsec = time_long - 1000 * (mysecond + myhour * 3600 + myminute * 60)
- return "%s:%s:%s,%s" % (format_number(myhour), format_number(myminute), format_number(mysecond), \
- format_number(mymilsec))
- else:
- mysecond = int(mysecond - myminute * 60)
- mymilsec = time_long - 1000 * (mysecond + myminute * 60)
- return "00:%s:%s,%s" % (format_number(myminute), format_number(mysecond), format_number(mymilsec))
- else:
- mymilsec = time_long - mysecond * 1000
- return "00:00:%s,%s" % (mysecond, mymilsec)
-
- decoder = wenet.Decoder(model_dir=r'C:\Users\Goya\.wenet\chs_1', lang='chs', context=shuyu, context_score=10.0)
- # 加载编译器,语音识别模型
-
- base_path = r'./temp'
- files = os.listdir(base_path)
- files.sort(key=lambda x: int(x.split('.')[0]), reverse=True) # 得到当前目录下所有文件
- count = 1
- word = []
- for path in files:
-
- # print(full_path)
- ans = eval(decoder.decode_wav('./temp/' + path)) # 得到语音识别结果
- ans = ans["nbest"][0]["sentence"]
- ans = ans.replace('', '')
- ans = ans.replace('', '')
- ans = pun_predictor(ans) # 加入标点符号
- if len(ans) > 37: # 判断是否高于35个字,如果高于则分行
-
- x = list(ans)
- x.insert(37, '\n')
- ans = ''.join(x)
- if (len(ans)) > 74:
- x = list(ans)
- x.insert(74, '\n')
- ans = ''.join(x)
-
- print(count, ": ", ans)
- word.append(ans)
- count += 1
-
- x = open('./result/1.srt', 'w', encoding='utf-8') # 生成字幕文件
- x2 = open('./result/2.txt', 'w', encoding='utf-8') # 生成文本文件
- count2 = 1
- # 生成字幕文件
- for a, b, c in zip(start, end, word):
- x2.write(c + '\n')
- m = str(count2) + '\n' + get_format_time(a) + ' --> ' + get_format_time(b) + '\n' + c + '\n' + '\n'
- count2 += 1
- x.write(m)
- x.close()
- x2.close()
-
- print("正在加字幕,请稍后\n")
- import os
- a = os.system("ffmpeg -i " + file + " -vf subtitles=./result/1.srt -y ./result/output.mp4") # 使用a接收返回值
-
- shutil.rmtree('./temp')
- os.mkdir('./temp')
- shutil.rmtree('./temp_wav')
- os.mkdir('./temp_wav')
- # 删除一些暂存的文件
- print("消耗时间为:" + str(time.time() - start1))
- return
-
-interface = gr.Interface(fn=to_black, inputs="video", outputs="video")
-interface.launch()
\ No newline at end of file
diff --git a/spaces/Gradio-Blocks/uniformer_image_detection/configs/hrnet/htc_hrnetv2p_w40_28e_coco.py b/spaces/Gradio-Blocks/uniformer_image_detection/configs/hrnet/htc_hrnetv2p_w40_28e_coco.py
deleted file mode 100644
index 7067e8b602efb4f61549d376ec393e89deee8c3e..0000000000000000000000000000000000000000
--- a/spaces/Gradio-Blocks/uniformer_image_detection/configs/hrnet/htc_hrnetv2p_w40_28e_coco.py
+++ /dev/null
@@ -1,4 +0,0 @@
-_base_ = './htc_hrnetv2p_w40_20e_coco.py'
-# learning policy
-lr_config = dict(step=[24, 27])
-runner = dict(type='EpochBasedRunner', max_epochs=28)
diff --git a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/_base_/models/nonlocal_r50-d8.py b/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/_base_/models/nonlocal_r50-d8.py
deleted file mode 100644
index 5674a39854cafd1f2e363bac99c58ccae62f24da..0000000000000000000000000000000000000000
--- a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/_base_/models/nonlocal_r50-d8.py
+++ /dev/null
@@ -1,46 +0,0 @@
-# model settings
-norm_cfg = dict(type='SyncBN', requires_grad=True)
-model = dict(
- type='EncoderDecoder',
- pretrained='open-mmlab://resnet50_v1c',
- backbone=dict(
- type='ResNetV1c',
- depth=50,
- num_stages=4,
- out_indices=(0, 1, 2, 3),
- dilations=(1, 1, 2, 4),
- strides=(1, 2, 1, 1),
- norm_cfg=norm_cfg,
- norm_eval=False,
- style='pytorch',
- contract_dilation=True),
- decode_head=dict(
- type='NLHead',
- in_channels=2048,
- in_index=3,
- channels=512,
- dropout_ratio=0.1,
- reduction=2,
- use_scale=True,
- mode='embedded_gaussian',
- num_classes=19,
- norm_cfg=norm_cfg,
- align_corners=False,
- loss_decode=dict(
- type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),
- auxiliary_head=dict(
- type='FCNHead',
- in_channels=1024,
- in_index=2,
- channels=256,
- num_convs=1,
- concat_input=False,
- dropout_ratio=0.1,
- num_classes=19,
- norm_cfg=norm_cfg,
- align_corners=False,
- loss_decode=dict(
- type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.4)),
- # model training and testing settings
- train_cfg=dict(),
- test_cfg=dict(mode='whole'))
diff --git a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/apcnet/apcnet_r101-d8_512x512_80k_ade20k.py b/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/apcnet/apcnet_r101-d8_512x512_80k_ade20k.py
deleted file mode 100644
index 8f10b98406c88256c66d3bbe241c149791d68feb..0000000000000000000000000000000000000000
--- a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/apcnet/apcnet_r101-d8_512x512_80k_ade20k.py
+++ /dev/null
@@ -1,2 +0,0 @@
-_base_ = './apcnet_r50-d8_512x512_80k_ade20k.py'
-model = dict(pretrained='open-mmlab://resnet101_v1c', backbone=dict(depth=101))
diff --git a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/deeplabv3plus/deeplabv3plus_r18-d8_769x769_80k_cityscapes.py b/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/deeplabv3plus/deeplabv3plus_r18-d8_769x769_80k_cityscapes.py
deleted file mode 100644
index 0172d9a87d6dc1c75bf75a9c48363eb985d389a8..0000000000000000000000000000000000000000
--- a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/deeplabv3plus/deeplabv3plus_r18-d8_769x769_80k_cityscapes.py
+++ /dev/null
@@ -1,11 +0,0 @@
-_base_ = './deeplabv3plus_r50-d8_769x769_80k_cityscapes.py'
-model = dict(
- pretrained='open-mmlab://resnet18_v1c',
- backbone=dict(depth=18),
- decode_head=dict(
- c1_in_channels=64,
- c1_channels=12,
- in_channels=512,
- channels=128,
- ),
- auxiliary_head=dict(in_channels=256, channels=64))
diff --git a/spaces/GroveStreet/GTA_SOVITS/pretrain/meta.py b/spaces/GroveStreet/GTA_SOVITS/pretrain/meta.py
deleted file mode 100644
index cc35dd3c0dfe8436e7d635f2db507cedca75ed49..0000000000000000000000000000000000000000
--- a/spaces/GroveStreet/GTA_SOVITS/pretrain/meta.py
+++ /dev/null
@@ -1,31 +0,0 @@
-def download_dict():
- return {
- "vec768l12": {
- "url": "https://ibm.ent.box.com/shared/static/z1wgl1stco8ffooyatzdwsqn2psd9lrr",
- "output": "./pretrain/checkpoint_best_legacy_500.pt"
- },
- "vec256l9": {
- "url": "https://ibm.ent.box.com/shared/static/z1wgl1stco8ffooyatzdwsqn2psd9lrr",
- "output": "./pretrain/checkpoint_best_legacy_500.pt"
- },
- "hubertsoft": {
- "url": "https://github.com/bshall/hubert/releases/download/v0.1/hubert-soft-0d54a1f4.pt",
- "output": "./pretrain/hubert-soft-0d54a1f4.pt"
- },
- "whisper-ppg": {
- "url": "https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt",
- "output": "./pretrain/medium.pt"
- }
- }
-
-
-def get_speech_encoder(config_path="configs/config.json"):
- import json
-
- with open(config_path, "r") as f:
- data = f.read()
- config = json.loads(data)
- speech_encoder = config["model"]["speech_encoder"]
- dict = download_dict()
-
- return dict[speech_encoder]["url"], dict[speech_encoder]["output"]
diff --git a/spaces/HaMerL/ChaosinChat/modules/utils.py b/spaces/HaMerL/ChaosinChat/modules/utils.py
deleted file mode 100644
index 67754aa14ed0c3f8a1a03645f217335480290ccf..0000000000000000000000000000000000000000
--- a/spaces/HaMerL/ChaosinChat/modules/utils.py
+++ /dev/null
@@ -1,548 +0,0 @@
-# -*- coding:utf-8 -*-
-from __future__ import annotations
-from typing import TYPE_CHECKING, Any, Callable, Dict, List, Tuple, Type
-import logging
-import json
-import os
-import datetime
-import hashlib
-import csv
-import requests
-import re
-import html
-import sys
-import subprocess
-
-import gradio as gr
-from pypinyin import lazy_pinyin
-import tiktoken
-import mdtex2html
-from markdown import markdown
-from pygments import highlight
-from pygments.lexers import get_lexer_by_name
-from pygments.formatters import HtmlFormatter
-import pandas as pd
-
-from modules.presets import *
-from . import shared
-from modules.config import retrieve_proxy
-
-if TYPE_CHECKING:
- from typing import TypedDict
-
- class DataframeData(TypedDict):
- headers: List[str]
- data: List[List[str | int | bool]]
-
-def predict(current_model, *args):
- iter = current_model.predict(*args)
- for i in iter:
- yield i
-
-def billing_info(current_model):
- return current_model.billing_info()
-
-def set_key(current_model, *args):
- return current_model.set_key(*args)
-
-def load_chat_history(current_model, *args):
- return current_model.load_chat_history(*args)
-
-def interrupt(current_model, *args):
- return current_model.interrupt(*args)
-
-def reset(current_model, *args):
- return current_model.reset(*args)
-
-def retry(current_model, *args):
- iter = current_model.retry(*args)
- for i in iter:
- yield i
-
-def delete_first_conversation(current_model, *args):
- return current_model.delete_first_conversation(*args)
-
-def delete_last_conversation(current_model, *args):
- return current_model.delete_last_conversation(*args)
-
-def set_system_prompt(current_model, *args):
- return current_model.set_system_prompt(*args)
-
-def save_chat_history(current_model, *args):
- return current_model.save_chat_history(*args)
-
-def export_markdown(current_model, *args):
- return current_model.export_markdown(*args)
-
-def load_chat_history(current_model, *args):
- return current_model.load_chat_history(*args)
-
-def set_token_upper_limit(current_model, *args):
- return current_model.set_token_upper_limit(*args)
-
-def set_temperature(current_model, *args):
- current_model.set_temperature(*args)
-
-def set_top_p(current_model, *args):
- current_model.set_top_p(*args)
-
-def set_n_choices(current_model, *args):
- current_model.set_n_choices(*args)
-
-def set_stop_sequence(current_model, *args):
- current_model.set_stop_sequence(*args)
-
-def set_max_tokens(current_model, *args):
- current_model.set_max_tokens(*args)
-
-def set_presence_penalty(current_model, *args):
- current_model.set_presence_penalty(*args)
-
-def set_frequency_penalty(current_model, *args):
- current_model.set_frequency_penalty(*args)
-
-def set_logit_bias(current_model, *args):
- current_model.set_logit_bias(*args)
-
-def set_user_identifier(current_model, *args):
- current_model.set_user_identifier(*args)
-
-def set_single_turn(current_model, *args):
- current_model.set_single_turn(*args)
-
-def handle_file_upload(current_model, *args):
- return current_model.handle_file_upload(*args)
-
-def like(current_model, *args):
- return current_model.like(*args)
-
-def dislike(current_model, *args):
- return current_model.dislike(*args)
-
-
-def count_token(message):
- encoding = tiktoken.get_encoding("cl100k_base")
- input_str = f"role: {message['role']}, content: {message['content']}"
- length = len(encoding.encode(input_str))
- return length
-
-
-def markdown_to_html_with_syntax_highlight(md_str):
- def replacer(match):
- lang = match.group(1) or "text"
- code = match.group(2)
-
- try:
- lexer = get_lexer_by_name(lang, stripall=True)
- except ValueError:
- lexer = get_lexer_by_name("text", stripall=True)
-
- formatter = HtmlFormatter()
- highlighted_code = highlight(code, lexer, formatter)
-
- return f'
{highlighted_code}
'
-
- code_block_pattern = r"```(\w+)?\n([\s\S]+?)\n```"
- md_str = re.sub(code_block_pattern, replacer, md_str, flags=re.MULTILINE)
-
- html_str = markdown(md_str)
- return html_str
-
-
-def normalize_markdown(md_text: str) -> str:
- lines = md_text.split("\n")
- normalized_lines = []
- inside_list = False
-
- for i, line in enumerate(lines):
- if re.match(r"^(\d+\.|-|\*|\+)\s", line.strip()):
- if not inside_list and i > 0 and lines[i - 1].strip() != "":
- normalized_lines.append("")
- inside_list = True
- normalized_lines.append(line)
- elif inside_list and line.strip() == "":
- if i < len(lines) - 1 and not re.match(
- r"^(\d+\.|-|\*|\+)\s", lines[i + 1].strip()
- ):
- normalized_lines.append(line)
- continue
- else:
- inside_list = False
- normalized_lines.append(line)
-
- return "\n".join(normalized_lines)
-
-
-def convert_mdtext(md_text):
- code_block_pattern = re.compile(r"```(.*?)(?:```|$)", re.DOTALL)
- inline_code_pattern = re.compile(r"`(.*?)`", re.DOTALL)
- code_blocks = code_block_pattern.findall(md_text)
- non_code_parts = code_block_pattern.split(md_text)[::2]
-
- result = []
- for non_code, code in zip(non_code_parts, code_blocks + [""]):
- if non_code.strip():
- non_code = normalize_markdown(non_code)
- if inline_code_pattern.search(non_code) or os.environ["RENDER_LATEX"]=="no":
- result.append(markdown(non_code, extensions=["tables"]))
- else:
- result.append(mdtex2html.convert(non_code, extensions=["tables"]))
- if code.strip():
- # _, code = detect_language(code) # 暂时去除代码高亮功能,因为在大段代码的情况下会出现问题
- # code = code.replace("\n\n", "\n") # 暂时去除代码中的空行,因为在大段代码的情况下会出现问题
- code = f"\n```{code}\n\n```"
- code = markdown_to_html_with_syntax_highlight(code)
- result.append(code)
- result = "".join(result)
- result += ALREADY_CONVERTED_MARK
- return result
-
-
-def convert_asis(userinput):
- return (
- f'
{html.escape(userinput)}
'
- + ALREADY_CONVERTED_MARK
- )
-
-
-def detect_converted_mark(userinput):
- try:
- if userinput.endswith(ALREADY_CONVERTED_MARK):
- return True
- else:
- return False
- except:
- return True
-
-
-def detect_language(code):
- if code.startswith("\n"):
- first_line = ""
- else:
- first_line = code.strip().split("\n", 1)[0]
- language = first_line.lower() if first_line else ""
- code_without_language = code[len(first_line) :].lstrip() if first_line else code
- return language, code_without_language
-
-
-def construct_text(role, text):
- return {"role": role, "content": text}
-
-
-def construct_user(text):
- return construct_text("user", text)
-
-
-def construct_system(text):
- return construct_text("system", text)
-
-
-def construct_assistant(text):
- return construct_text("assistant", text)
-
-
-def save_file(filename, system, history, chatbot, user_name):
- logging.debug(f"{user_name} 保存对话历史中……")
- os.makedirs(os.path.join(HISTORY_DIR, user_name), exist_ok=True)
- if filename.endswith(".json"):
- json_s = {"system": system, "history": history, "chatbot": chatbot}
- print(json_s)
- with open(os.path.join(HISTORY_DIR, user_name, filename), "w") as f:
- json.dump(json_s, f)
- elif filename.endswith(".md"):
- md_s = f"system: \n- {system} \n"
- for data in history:
- md_s += f"\n{data['role']}: \n- {data['content']} \n"
- with open(os.path.join(HISTORY_DIR, user_name, filename), "w", encoding="utf8") as f:
- f.write(md_s)
- logging.debug(f"{user_name} 保存对话历史完毕")
- return os.path.join(HISTORY_DIR, user_name, filename)
-
-
-def sorted_by_pinyin(list):
- return sorted(list, key=lambda char: lazy_pinyin(char)[0][0])
-
-
-def get_file_names(dir, plain=False, filetypes=[".json"]):
- logging.debug(f"获取文件名列表,目录为{dir},文件类型为{filetypes},是否为纯文本列表{plain}")
- files = []
- try:
- for type in filetypes:
- files += [f for f in os.listdir(dir) if f.endswith(type)]
- except FileNotFoundError:
- files = []
- files = sorted_by_pinyin(files)
- if files == []:
- files = [""]
- logging.debug(f"files are:{files}")
- if plain:
- return files
- else:
- return gr.Dropdown.update(choices=files)
-
-
-def get_history_names(plain=False, user_name=""):
- logging.debug(f"从用户 {user_name} 中获取历史记录文件名列表")
- return get_file_names(os.path.join(HISTORY_DIR, user_name), plain)
-
-
-def load_template(filename, mode=0):
- logging.debug(f"加载模板文件{filename},模式为{mode}(0为返回字典和下拉菜单,1为返回下拉菜单,2为返回字典)")
- lines = []
- if filename.endswith(".json"):
- with open(os.path.join(TEMPLATES_DIR, filename), "r", encoding="utf8") as f:
- lines = json.load(f)
- lines = [[i["act"], i["prompt"]] for i in lines]
- else:
- with open(
- os.path.join(TEMPLATES_DIR, filename), "r", encoding="utf8"
- ) as csvfile:
- reader = csv.reader(csvfile)
- lines = list(reader)
- lines = lines[1:]
- if mode == 1:
- return sorted_by_pinyin([row[0] for row in lines])
- elif mode == 2:
- return {row[0]: row[1] for row in lines}
- else:
- choices = sorted_by_pinyin([row[0] for row in lines])
- return {row[0]: row[1] for row in lines}, gr.Dropdown.update(
- choices=choices
- )
-
-
-def get_template_names(plain=False):
- logging.debug("获取模板文件名列表")
- return get_file_names(TEMPLATES_DIR, plain, filetypes=[".csv", "json"])
-
-
-def get_template_content(templates, selection, original_system_prompt):
- logging.debug(f"应用模板中,选择为{selection},原始系统提示为{original_system_prompt}")
- try:
- return templates[selection]
- except:
- return original_system_prompt
-
-
-def reset_textbox():
- logging.debug("重置文本框")
- return gr.update(value="")
-
-
-def reset_default():
- default_host = shared.state.reset_api_host()
- retrieve_proxy("")
- return gr.update(value=default_host), gr.update(value=""), "API-Host 和代理已重置"
-
-
-def change_api_host(host):
- shared.state.set_api_host(host)
- msg = f"API-Host更改为了{host}"
- logging.info(msg)
- return msg
-
-
-def change_proxy(proxy):
- retrieve_proxy(proxy)
- os.environ["HTTPS_PROXY"] = proxy
- msg = f"代理更改为了{proxy}"
- logging.info(msg)
- return msg
-
-
-def hide_middle_chars(s):
- if s is None:
- return ""
- if len(s) <= 8:
- return s
- else:
- head = s[:4]
- tail = s[-4:]
- hidden = "*" * (len(s) - 8)
- return head + hidden + tail
-
-
-def submit_key(key):
- key = key.strip()
- msg = f"API密钥更改为了{hide_middle_chars(key)}"
- logging.info(msg)
- return key, msg
-
-
-def replace_today(prompt):
- today = datetime.datetime.today().strftime("%Y-%m-%d")
- return prompt.replace("{current_date}", today)
-
-
-def get_geoip():
- try:
- with retrieve_proxy():
- response = requests.get("https://ipapi.co/json/", timeout=5)
- data = response.json()
- except:
- data = {"error": True, "reason": "连接ipapi失败"}
- if "error" in data.keys():
- logging.warning(f"无法获取IP地址信息。\n{data}")
- if data["reason"] == "RateLimited":
- return (
- i18n("您的IP区域:未知。")
- )
- else:
- return i18n("获取IP地理位置失败。原因:") + f"{data['reason']}" + i18n("。你仍然可以使用聊天功能。")
- else:
- country = data["country_name"]
- if country == "China":
- text = "**您的IP区域:中国。请立即检查代理设置,在不受支持的地区使用API可能导致账号被封禁。**"
- else:
- text = i18n("您的IP区域:") + f"{country}。"
- logging.info(text)
- return text
-
-
-def find_n(lst, max_num):
- n = len(lst)
- total = sum(lst)
-
- if total < max_num:
- return n
-
- for i in range(len(lst)):
- if total - lst[i] < max_num:
- return n - i - 1
- total = total - lst[i]
- return 1
-
-
-def start_outputing():
- logging.debug("显示取消按钮,隐藏发送按钮")
- return gr.Button.update(visible=False), gr.Button.update(visible=True)
-
-
-def end_outputing():
- return (
- gr.Button.update(visible=True),
- gr.Button.update(visible=False),
- )
-
-
-def cancel_outputing():
- logging.info("中止输出……")
- shared.state.interrupt()
-
-
-def transfer_input(inputs):
- # 一次性返回,降低延迟
- textbox = reset_textbox()
- outputing = start_outputing()
- return (
- inputs,
- gr.update(value=""),
- gr.Button.update(visible=False),
- gr.Button.update(visible=True),
- )
-
-
-
-def run(command, desc=None, errdesc=None, custom_env=None, live=False):
- if desc is not None:
- print(desc)
- if live:
- result = subprocess.run(command, shell=True, env=os.environ if custom_env is None else custom_env)
- if result.returncode != 0:
- raise RuntimeError(f"""{errdesc or 'Error running command'}.
-Command: {command}
-Error code: {result.returncode}""")
-
- return ""
- result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, env=os.environ if custom_env is None else custom_env)
- if result.returncode != 0:
- message = f"""{errdesc or 'Error running command'}.
- Command: {command}
- Error code: {result.returncode}
- stdout: {result.stdout.decode(encoding="utf8", errors="ignore") if len(result.stdout)>0 else ''}
- stderr: {result.stderr.decode(encoding="utf8", errors="ignore") if len(result.stderr)>0 else ''}
- """
- raise RuntimeError(message)
- return result.stdout.decode(encoding="utf8", errors="ignore")
-
-def versions_html():
- git = os.environ.get('GIT', "git")
- python_version = ".".join([str(x) for x in sys.version_info[0:3]])
- try:
- commit_hash = run(f"{git} rev-parse HEAD").strip()
- except Exception:
- commit_hash = ""
- if commit_hash != "":
- short_commit = commit_hash[0:7]
- commit_info = f"{short_commit}"
- else:
- commit_info = "unknown \U0001F615"
- return f"""
- Python: {python_version}
- •
- Gradio: {gr.__version__}
- •
- Commit: {commit_info}
- """
-
-def add_source_numbers(lst, source_name = "Source", use_source = True):
- if use_source:
- return [f'[{idx+1}]\t "{item[0]}"\n{source_name}: {item[1]}' for idx, item in enumerate(lst)]
- else:
- return [f'[{idx+1}]\t "{item}"' for idx, item in enumerate(lst)]
-
-def add_details(lst):
- nodes = []
- for index, txt in enumerate(lst):
- brief = txt[:25].replace("\n", "")
- nodes.append(
- f"{brief}...
{txt}
"
- )
- return nodes
-
-
-def sheet_to_string(sheet, sheet_name = None):
- result = []
- for index, row in sheet.iterrows():
- row_string = ""
- for column in sheet.columns:
- row_string += f"{column}: {row[column]}, "
- row_string = row_string.rstrip(", ")
- row_string += "."
- result.append(row_string)
- return result
-
-def excel_to_string(file_path):
- # 读取Excel文件中的所有工作表
- excel_file = pd.read_excel(file_path, engine='openpyxl', sheet_name=None)
-
- # 初始化结果字符串
- result = []
-
- # 遍历每一个工作表
- for sheet_name, sheet_data in excel_file.items():
-
- # 处理当前工作表并添加到结果字符串
- result += sheet_to_string(sheet_data, sheet_name=sheet_name)
-
-
- return result
-
-def get_last_day_of_month(any_day):
- # The day 28 exists in every month. 4 days later, it's always next month
- next_month = any_day.replace(day=28) + datetime.timedelta(days=4)
- # subtracting the number of the current day brings us back one month
- return next_month - datetime.timedelta(days=next_month.day)
-
-def get_model_source(model_name, alternative_source):
- if model_name == "gpt2-medium":
- return "https://huggingface.co/gpt2-medium"
-
-def refresh_ui_elements_on_load(current_model, selected_model_name):
- return toggle_like_btn_visibility(selected_model_name)
-
-def toggle_like_btn_visibility(selected_model_name):
- if selected_model_name == "xmchat":
- return gr.update(visible=True)
- else:
- return gr.update(visible=False)
diff --git a/spaces/HaleyCH/HaleyCH_Theme/theme_dropdown.py b/spaces/HaleyCH/HaleyCH_Theme/theme_dropdown.py
deleted file mode 100644
index 6235388fd00549553df44028f3ccf03e946994ea..0000000000000000000000000000000000000000
--- a/spaces/HaleyCH/HaleyCH_Theme/theme_dropdown.py
+++ /dev/null
@@ -1,57 +0,0 @@
-import os
-import pathlib
-
-from gradio.themes.utils import ThemeAsset
-
-
-def create_theme_dropdown():
- import gradio as gr
-
- asset_path = pathlib.Path(__file__).parent / "themes"
- themes = []
- for theme_asset in os.listdir(str(asset_path)):
- themes.append(
- (ThemeAsset(theme_asset), gr.Theme.load(str(asset_path / theme_asset)))
- )
-
- def make_else_if(theme_asset):
- return f"""
- else if (theme == '{str(theme_asset[0].version)}') {{
- var theme_css = `{theme_asset[1]._get_theme_css()}`
- }}"""
-
- head, tail = themes[0], themes[1:]
- if_statement = f"""
- if (theme == "{str(head[0].version)}") {{
- var theme_css = `{head[1]._get_theme_css()}`
- }} {" ".join(make_else_if(t) for t in tail)}
- """
-
- latest_to_oldest = sorted([t[0] for t in themes], key=lambda asset: asset.version)[
- ::-1
- ]
- latest_to_oldest = [str(t.version) for t in latest_to_oldest]
-
- component = gr.Dropdown(
- choices=latest_to_oldest,
- value=latest_to_oldest[0],
- render=False,
- label="Select Version",
- ).style(container=False)
-
- return (
- component,
- f"""
- (theme) => {{
- if (!document.querySelector('.theme-css')) {{
- var theme_elem = document.createElement('style');
- theme_elem.classList.add('theme-css');
- document.head.appendChild(theme_elem);
- }} else {{
- var theme_elem = document.querySelector('.theme-css');
- }}
- {if_statement}
- theme_elem.innerHTML = theme_css;
- }}
- """,
- )
diff --git a/spaces/Hallucinate/demo/ldm/models/diffusion/ddim.py b/spaces/Hallucinate/demo/ldm/models/diffusion/ddim.py
deleted file mode 100644
index edf1eaff9e78ac2e6778914b706b6a4fff51a8fe..0000000000000000000000000000000000000000
--- a/spaces/Hallucinate/demo/ldm/models/diffusion/ddim.py
+++ /dev/null
@@ -1,203 +0,0 @@
-"""SAMPLING ONLY."""
-
-import torch
-import numpy as np
-from tqdm import tqdm
-from functools import partial
-
-from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like
-
-
-class DDIMSampler(object):
- def __init__(self, model, schedule="linear", **kwargs):
- super().__init__()
- self.model = model
- self.ddpm_num_timesteps = model.num_timesteps
- self.schedule = schedule
-
- def register_buffer(self, name, attr):
- if type(attr) == torch.Tensor:
- if attr.device != torch.device("cuda"):
- attr = attr.to(torch.device("cuda"))
- setattr(self, name, attr)
-
- def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
- self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
- num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
- alphas_cumprod = self.model.alphas_cumprod
- assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
- to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
-
- self.register_buffer('betas', to_torch(self.model.betas))
- self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
- self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
-
- # calculations for diffusion q(x_t | x_{t-1}) and others
- self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
- self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
- self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
- self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
- self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
-
- # ddim sampling parameters
- ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
- ddim_timesteps=self.ddim_timesteps,
- eta=ddim_eta,verbose=verbose)
- self.register_buffer('ddim_sigmas', ddim_sigmas)
- self.register_buffer('ddim_alphas', ddim_alphas)
- self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
- self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
- sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
- (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
- 1 - self.alphas_cumprod / self.alphas_cumprod_prev))
- self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
-
- @torch.no_grad()
- def sample(self,
- S,
- batch_size,
- shape,
- conditioning=None,
- callback=None,
- normals_sequence=None,
- img_callback=None,
- quantize_x0=False,
- eta=0.,
- mask=None,
- x0=None,
- temperature=1.,
- noise_dropout=0.,
- score_corrector=None,
- corrector_kwargs=None,
- verbose=True,
- x_T=None,
- log_every_t=100,
- unconditional_guidance_scale=1.,
- unconditional_conditioning=None,
- # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
- **kwargs
- ):
- if conditioning is not None:
- if isinstance(conditioning, dict):
- cbs = conditioning[list(conditioning.keys())[0]].shape[0]
- if cbs != batch_size:
- print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
- else:
- if conditioning.shape[0] != batch_size:
- print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
-
- self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
- # sampling
- C, H, W = shape
- size = (batch_size, C, H, W)
- print(f'Data shape for DDIM sampling is {size}, eta {eta}')
-
- samples, intermediates = self.ddim_sampling(conditioning, size,
- callback=callback,
- img_callback=img_callback,
- quantize_denoised=quantize_x0,
- mask=mask, x0=x0,
- ddim_use_original_steps=False,
- noise_dropout=noise_dropout,
- temperature=temperature,
- score_corrector=score_corrector,
- corrector_kwargs=corrector_kwargs,
- x_T=x_T,
- log_every_t=log_every_t,
- unconditional_guidance_scale=unconditional_guidance_scale,
- unconditional_conditioning=unconditional_conditioning,
- )
- return samples, intermediates
-
- @torch.no_grad()
- def ddim_sampling(self, cond, shape,
- x_T=None, ddim_use_original_steps=False,
- callback=None, timesteps=None, quantize_denoised=False,
- mask=None, x0=None, img_callback=None, log_every_t=100,
- temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
- unconditional_guidance_scale=1., unconditional_conditioning=None,):
- device = self.model.betas.device
- b = shape[0]
- if x_T is None:
- img = torch.randn(shape, device=device)
- else:
- img = x_T
-
- if timesteps is None:
- timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
- elif timesteps is not None and not ddim_use_original_steps:
- subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
- timesteps = self.ddim_timesteps[:subset_end]
-
- intermediates = {'x_inter': [img], 'pred_x0': [img]}
- time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
- total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
- print(f"Running DDIM Sampling with {total_steps} timesteps")
-
- iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
-
- for i, step in enumerate(iterator):
- index = total_steps - i - 1
- ts = torch.full((b,), step, device=device, dtype=torch.long)
-
- if mask is not None:
- assert x0 is not None
- img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
- img = img_orig * mask + (1. - mask) * img
-
- outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
- quantize_denoised=quantize_denoised, temperature=temperature,
- noise_dropout=noise_dropout, score_corrector=score_corrector,
- corrector_kwargs=corrector_kwargs,
- unconditional_guidance_scale=unconditional_guidance_scale,
- unconditional_conditioning=unconditional_conditioning)
- img, pred_x0 = outs
- if callback: callback(i)
- if img_callback: img_callback(pred_x0, i)
-
- if index % log_every_t == 0 or index == total_steps - 1:
- intermediates['x_inter'].append(img)
- intermediates['pred_x0'].append(pred_x0)
-
- return img, intermediates
-
- @torch.no_grad()
- def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
- temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
- unconditional_guidance_scale=1., unconditional_conditioning=None):
- b, *_, device = *x.shape, x.device
-
- if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
- e_t = self.model.apply_model(x, t, c)
- else:
- x_in = torch.cat([x] * 2)
- t_in = torch.cat([t] * 2)
- c_in = torch.cat([unconditional_conditioning, c])
- e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
- e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)
-
- if score_corrector is not None:
- assert self.model.parameterization == "eps"
- e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
-
- alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
- alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
- sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
- sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
- # select parameters corresponding to the currently considered timestep
- a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
- a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
- sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
- sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
-
- # current prediction for x_0
- pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
- if quantize_denoised:
- pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
- # direction pointing to x_t
- dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
- noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
- if noise_dropout > 0.:
- noise = torch.nn.functional.dropout(noise, p=noise_dropout)
- x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
- return x_prev, pred_x0
diff --git a/spaces/HaloMaster/chinesesummary/fengshen/examples/zen2_finetune/ner_zen2_base_weibo.sh b/spaces/HaloMaster/chinesesummary/fengshen/examples/zen2_finetune/ner_zen2_base_weibo.sh
deleted file mode 100644
index b3f4667e59fe0b7ba98f37dec65e12fdf6faf555..0000000000000000000000000000000000000000
--- a/spaces/HaloMaster/chinesesummary/fengshen/examples/zen2_finetune/ner_zen2_base_weibo.sh
+++ /dev/null
@@ -1,91 +0,0 @@
-#!/bin/bash
-#SBATCH --job-name=zen2_base_weibo # create a short name for your job
-#SBATCH --nodes=1 # node count
-#SBATCH --ntasks=1 # total number of tasks across all nodes
-#SBATCH --cpus-per-task=30 # cpu-cores per task (>1 if multi-threaded tasks)
-#SBATCH --gres=gpu:1 # number of gpus per node
-#SBATCH --mail-type=ALL # send email when job begins, ends or failed etc.
-#SBATCH -o /cognitive_comp/ganruyi/experiments/ner_finetune/zen2_base_weibo/%x-%j.log # output and error file name (%x=job name, %j=job id)
-
-
-# export CUDA_VISIBLE_DEVICES='2'
-export TORCH_EXTENSIONS_DIR=/cognitive_comp/ganruyi/tmp/torch_extendsions
-
-MODEL_NAME=zen2_base
-
-TASK=weibo
-
-ZERO_STAGE=1
-STRATEGY=deepspeed_stage_${ZERO_STAGE}
-
-ROOT_DIR=/cognitive_comp/ganruyi/experiments/ner_finetune/${MODEL_NAME}_${TASK}
-if [ ! -d ${ROOT_DIR} ];then
- mkdir -p ${ROOT_DIR}
- echo ${ROOT_DIR} created!!!!!!!!!!!!!!
-else
- echo ${ROOT_DIR} exist!!!!!!!!!!!!!!!
-fi
-
-DATA_DIR=/cognitive_comp/lujunyu/data_zh/NER_Aligned/weibo/
-PRETRAINED_MODEL_PATH=/cognitive_comp/ganruyi/hf_models/zen/zh_zen_base_2.0
-
-CHECKPOINT_PATH=${ROOT_DIR}/ckpt/
-OUTPUT_PATH=${ROOT_DIR}/predict.json
-
-DATA_ARGS="\
- --data_dir $DATA_DIR \
- --train_data train.all.bmes \
- --valid_data test.all.bmes \
- --test_data test.all.bmes \
- --train_batchsize 32 \
- --valid_batchsize 16 \
- --max_seq_length 256 \
- --task_name weibo \
- "
-
-MODEL_ARGS="\
- --learning_rate 3e-5 \
- --weight_decay 0.1 \
- --warmup_ratio 0.01 \
- --markup bioes \
- --middle_prefix M- \
- "
-
-MODEL_CHECKPOINT_ARGS="\
- --monitor val_f1 \
- --save_top_k 3 \
- --mode max \
- --every_n_train_steps 100 \
- --save_weights_only True \
- --dirpath $CHECKPOINT_PATH \
- --filename model-{epoch:02d}-{val_f1:.4f} \
- "
-
-TRAINER_ARGS="\
- --max_epochs 30 \
- --gpus 1 \
- --check_val_every_n_epoch 1 \
- --val_check_interval 20 \
- --default_root_dir $ROOT_DIR \
- "
-
-
-options=" \
- --pretrained_model_path $PRETRAINED_MODEL_PATH \
- --vocab_file $PRETRAINED_MODEL_PATH/vocab.txt \
- --do_lower_case \
- --output_save_path $OUTPUT_PATH \
- $DATA_ARGS \
- $MODEL_ARGS \
- $MODEL_CHECKPOINT_ARGS \
- $TRAINER_ARGS \
-"
-SCRIPT_PATH=/cognitive_comp/ganruyi/Fengshenbang-LM/fengshen/examples/zen2_finetune/fengshen_token_level_ft_task.py
-/home/ganruyi/anaconda3/bin/python $SCRIPT_PATH $options
-
-# SINGULARITY_PATH=/cognitive_comp/ganruyi/pytorch21_06_py3_docker_image_v2.sif
-# python3 $SCRIPT_PATH $options
-# source activate base
-# singularity exec --nv -B /cognitive_comp/:/cognitive_comp/ $SINGULARITY_PATH /home/ganruyi/anaconda3/bin/python $SCRIPT_PATH $options
-# /home/ganruyi/anaconda3/bin/python $SCRIPT_PATH $options
-
diff --git a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/examples/language_model/README.md b/spaces/HarryLee/eCommerceImageCaptioning/fairseq/examples/language_model/README.md
deleted file mode 100644
index e78ea48e08dc99b69751923762107a8f8a9a5e3e..0000000000000000000000000000000000000000
--- a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/examples/language_model/README.md
+++ /dev/null
@@ -1,123 +0,0 @@
-# Neural Language Modeling
-
-## Pre-trained models
-
-Model | Description | Dataset | Download
----|---|---|---
-`transformer_lm.gbw.adaptive_huge` | Adaptive Inputs ([Baevski and Auli, 2018](https://arxiv.org/abs/1809.10853)) 1026M params | [Google Billion Words](https://github.com/ciprian-chelba/1-billion-word-language-modeling-benchmark) | [download (.tar.bz2)](https://dl.fbaipublicfiles.com/fairseq/models/lm/adaptive_lm_gbw_huge.tar.bz2)
-`transformer_lm.wiki103.adaptive` | Adaptive Inputs ([Baevski and Auli, 2018](https://arxiv.org/abs/1809.10853)) 247M params | [WikiText-103](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset) | [download (.tar.bz2)](https://dl.fbaipublicfiles.com/fairseq/models/lm/adaptive_lm_wiki103.v2.tar.bz2)
-`transformer_lm.wmt19.en` | English LM ([Ng et al., 2019](https://arxiv.org/abs/1907.06616)) | [WMT News Crawl](http://data.statmt.org/news-crawl/) | [download (.tar.gz)](https://dl.fbaipublicfiles.com/fairseq/models/lm/wmt19.en.tar.gz)
-`transformer_lm.wmt19.de` | German LM ([Ng et al., 2019](https://arxiv.org/abs/1907.06616)) | [WMT News Crawl](http://data.statmt.org/news-crawl/) | [download (.tar.gz)](https://dl.fbaipublicfiles.com/fairseq/models/lm/wmt19.de.tar.gz)
-`transformer_lm.wmt19.ru` | Russian LM ([Ng et al., 2019](https://arxiv.org/abs/1907.06616)) | [WMT News Crawl](http://data.statmt.org/news-crawl/) | [download (.tar.gz)](https://dl.fbaipublicfiles.com/fairseq/models/lm/wmt19.ru.tar.gz)
-
-## Example usage
-
-We require a few additional Python dependencies for preprocessing:
-```bash
-pip install fastBPE sacremoses
-```
-
-To sample from a language model using PyTorch Hub:
-```python
-import torch
-
-# List available models
-torch.hub.list('pytorch/fairseq') # [..., 'transformer_lm.wmt19.en', ...]
-
-# Load an English LM trained on WMT'19 News Crawl data
-en_lm = torch.hub.load('pytorch/fairseq', 'transformer_lm.wmt19.en', tokenizer='moses', bpe='fastbpe')
-en_lm.eval() # disable dropout
-
-# Move model to GPU
-en_lm.cuda()
-
-# Sample from the language model
-en_lm.sample('Barack Obama', beam=1, sampling=True, sampling_topk=10, temperature=0.8)
-# "Barack Obama is coming to Sydney and New Zealand (...)"
-
-# Compute perplexity for a sequence
-en_lm.score('Barack Obama is coming to Sydney and New Zealand')['positional_scores'].mean().neg().exp()
-# tensor(15.1474)
-
-# The same interface can be used with custom models as well
-from fairseq.models.transformer_lm import TransformerLanguageModel
-custom_lm = TransformerLanguageModel.from_pretrained('/path/to/model/dir', 'checkpoint100.pt', tokenizer='moses', bpe='fastbpe')
-custom_lm.sample('Barack Obama', beam=5)
-# "Barack Obama (...)"
-```
-
-## Training a transformer language model with the CLI tools
-
-### 1) Preprocess the data
-
-First download and prepare the [WikiText-103 dataset](https://www.salesforce.com/products/einstein/ai-research/the-wikitext-dependency-language-modeling-dataset/):
-```bash
-cd examples/language_model/
-bash prepare-wikitext-103.sh
-cd ../..
-```
-
-Next preprocess/binarize the data:
-```bash
-TEXT=examples/language_model/wikitext-103
-fairseq-preprocess \
- --only-source \
- --trainpref $TEXT/wiki.train.tokens \
- --validpref $TEXT/wiki.valid.tokens \
- --testpref $TEXT/wiki.test.tokens \
- --destdir data-bin/wikitext-103 \
- --workers 20
-```
-
-### 2) Train a language model
-
-Next we'll train a basic transformer language model on wikitext-103. For more
-advanced usage, see the [adaptive inputs README](README.adaptive_inputs.md).
-
-To train a basic LM (assumes 2 GPUs):
-```
-$ fairseq-train --task language_modeling \
- data-bin/wikitext-103 \
- --save-dir checkpoints/transformer_wikitext-103 \
- --arch transformer_lm --share-decoder-input-output-embed \
- --dropout 0.1 \
- --optimizer adam --adam-betas '(0.9, 0.98)' --weight-decay 0.01 --clip-norm 0.0 \
- --lr 0.0005 --lr-scheduler inverse_sqrt --warmup-updates 4000 --warmup-init-lr 1e-07 \
- --tokens-per-sample 512 --sample-break-mode none \
- --max-tokens 2048 --update-freq 16 \
- --fp16 \
- --max-update 50000
-```
-
-If you run out of memory, try reducing `--max-tokens` (max number of tokens per
-batch) or `--tokens-per-sample` (max sequence length). You can also adjust
-`--update-freq` to accumulate gradients and simulate training on a different
-number of GPUs.
-
-### 3) Evaluate
-
-```bash
-fairseq-eval-lm data-bin/wikitext-103 \
- --path checkpoints/transformer_wiki103/checkpoint_best.pt \
- --batch-size 2 \
- --tokens-per-sample 512 \
- --context-window 400
-# | Evaluated 245569 tokens in 56.1s (4379.02 tokens/s)
-# | Loss: 3.4164, Perplexity: 30.46
-```
-
-*Note:* The `--context-window` option controls how much context is provided to
-each token when computing perplexity. When the window size is 0, the dataset is
-chunked into segments of length 512 and perplexity is computed over each segment
-normally. However, this results in worse (higher) perplexity since tokens that
-appear earlier in each segment have less conditioning. When the maximum window
-size is used (511 in this case), then we compute perplexity for each token
-fully conditioned on 511 tokens of context. This slows down evaluation
-significantly, since we must run a separate forward pass for every token in the
-dataset, but results in better (lower) perplexity.
-
-
-## Convolutional language models
-
-Please see the [convolutional LM README](README.conv.md) for instructions on
-training convolutional language models.
diff --git a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/tests/test_valid_subset_checks.py b/spaces/HarryLee/eCommerceImageCaptioning/fairseq/tests/test_valid_subset_checks.py
deleted file mode 100644
index 3e9191bda66fccfebba34920f88bf7b1efea5f7e..0000000000000000000000000000000000000000
--- a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/tests/test_valid_subset_checks.py
+++ /dev/null
@@ -1,138 +0,0 @@
-import os
-import shutil
-import tempfile
-import unittest
-
-from fairseq import options
-from fairseq.dataclass.utils import convert_namespace_to_omegaconf
-from fairseq.data.data_utils import raise_if_valid_subsets_unintentionally_ignored
-from .utils import create_dummy_data, preprocess_lm_data, train_language_model
-
-
-def make_lm_config(
- data_dir=None,
- extra_flags=None,
- task="language_modeling",
- arch="transformer_lm_gpt2_tiny",
-):
- task_args = [task]
- if data_dir is not None:
- task_args += [data_dir]
- train_parser = options.get_training_parser()
- train_args = options.parse_args_and_arch(
- train_parser,
- [
- "--task",
- *task_args,
- "--arch",
- arch,
- "--optimizer",
- "adam",
- "--lr",
- "0.0001",
- "--max-tokens",
- "500",
- "--tokens-per-sample",
- "500",
- "--save-dir",
- data_dir,
- "--max-epoch",
- "1",
- ]
- + (extra_flags or []),
- )
- cfg = convert_namespace_to_omegaconf(train_args)
- return cfg
-
-
-def write_empty_file(path):
- with open(path, "w"):
- pass
- assert os.path.exists(path)
-
-
-class TestValidSubsetsErrors(unittest.TestCase):
- """Test various filesystem, clarg combinations and ensure that error raising happens as expected"""
-
- def _test_case(self, paths, extra_flags):
- with tempfile.TemporaryDirectory() as data_dir:
- [
- write_empty_file(os.path.join(data_dir, f"{p}.bin"))
- for p in paths + ["train"]
- ]
- cfg = make_lm_config(data_dir, extra_flags=extra_flags)
- raise_if_valid_subsets_unintentionally_ignored(cfg)
-
- def test_default_raises(self):
- with self.assertRaises(ValueError):
- self._test_case(["valid", "valid1"], [])
- with self.assertRaises(ValueError):
- self._test_case(
- ["valid", "valid1", "valid2"], ["--valid-subset", "valid,valid1"]
- )
-
- def partially_specified_valid_subsets(self):
- with self.assertRaises(ValueError):
- self._test_case(
- ["valid", "valid1", "valid2"], ["--valid-subset", "valid,valid1"]
- )
- # Fix with ignore unused
- self._test_case(
- ["valid", "valid1", "valid2"],
- ["--valid-subset", "valid,valid1", "--ignore-unused-valid-subsets"],
- )
-
- def test_legal_configs(self):
- self._test_case(["valid"], [])
- self._test_case(["valid", "valid1"], ["--ignore-unused-valid-subsets"])
- self._test_case(["valid", "valid1"], ["--combine-val"])
- self._test_case(["valid", "valid1"], ["--valid-subset", "valid,valid1"])
- self._test_case(["valid", "valid1"], ["--valid-subset", "valid1"])
- self._test_case(
- ["valid", "valid1"], ["--combine-val", "--ignore-unused-valid-subsets"]
- )
- self._test_case(
- ["valid1"], ["--valid-subset", "valid1"]
- ) # valid.bin doesn't need to be ignored.
-
- def test_disable_validation(self):
- self._test_case([], ["--disable-validation"])
- self._test_case(["valid", "valid1"], ["--disable-validation"])
-
- def test_dummy_task(self):
- cfg = make_lm_config(task="dummy_lm")
- raise_if_valid_subsets_unintentionally_ignored(cfg)
-
- def test_masked_dummy_task(self):
- cfg = make_lm_config(task="dummy_masked_lm")
- raise_if_valid_subsets_unintentionally_ignored(cfg)
-
-
-class TestCombineValidSubsets(unittest.TestCase):
- def _train(self, extra_flags):
- with self.assertLogs() as logs:
- with tempfile.TemporaryDirectory("test_transformer_lm") as data_dir:
- create_dummy_data(data_dir, num_examples=20)
- preprocess_lm_data(data_dir)
-
- shutil.copyfile(f"{data_dir}/valid.bin", f"{data_dir}/valid1.bin")
- shutil.copyfile(f"{data_dir}/valid.idx", f"{data_dir}/valid1.idx")
- train_language_model(
- data_dir,
- "transformer_lm",
- ["--max-update", "0", "--log-format", "json"] + extra_flags,
- run_validation=False,
- )
- return [x.message for x in logs.records]
-
- def test_combined(self):
- flags = ["--combine-valid-subsets"]
- logs = self._train(flags)
- assert any(["valid1" in x for x in logs]) # loaded 100 examples from valid1
- assert not any(["valid1_ppl" in x for x in logs]) # metrics are combined
-
- def test_subsets(self):
- flags = ["--valid-subset", "valid,valid1"]
- logs = self._train(flags)
- assert any(["valid_ppl" in x for x in logs]) # loaded 100 examples from valid1
- assert any(["valid1_ppl" in x for x in logs]) # metrics are combined
diff --git a/spaces/Harveenchadha/Vakyansh-Hindi-TTS/ttsv/tts_infer/transliterate.py b/spaces/Harveenchadha/Vakyansh-Hindi-TTS/ttsv/tts_infer/transliterate.py
deleted file mode 100644
index 575430562683434cd44fd8d2e77d26dab9ced73b..0000000000000000000000000000000000000000
--- a/spaces/Harveenchadha/Vakyansh-Hindi-TTS/ttsv/tts_infer/transliterate.py
+++ /dev/null
@@ -1,919 +0,0 @@
-import torch
-import torch.nn as nn
-import numpy as np
-import pandas as pd
-import random
-import sys
-import os
-import json
-import enum
-import traceback
-import re
-
-F_DIR = os.path.dirname(os.environ.get('translit_model_base_path', os.path.realpath(__file__)))
-
-
-class XlitError(enum.Enum):
- lang_err = "Unsupported langauge ID requested ;( Please check available languages."
- string_err = "String passed is incompatable ;("
- internal_err = "Internal crash ;("
- unknown_err = "Unknown Failure"
- loading_err = "Loading failed ;( Check if metadata/paths are correctly configured."
-
-
-##=================== Network ==================================================
-
-
-class Encoder(nn.Module):
- def __init__(
- self,
- input_dim,
- embed_dim,
- hidden_dim,
- rnn_type="gru",
- layers=1,
- bidirectional=False,
- dropout=0,
- device="cpu",
- ):
- super(Encoder, self).__init__()
-
- self.input_dim = input_dim # src_vocab_sz
- self.enc_embed_dim = embed_dim
- self.enc_hidden_dim = hidden_dim
- self.enc_rnn_type = rnn_type
- self.enc_layers = layers
- self.enc_directions = 2 if bidirectional else 1
- self.device = device
-
- self.embedding = nn.Embedding(self.input_dim, self.enc_embed_dim)
-
- if self.enc_rnn_type == "gru":
- self.enc_rnn = nn.GRU(
- input_size=self.enc_embed_dim,
- hidden_size=self.enc_hidden_dim,
- num_layers=self.enc_layers,
- bidirectional=bidirectional,
- )
- elif self.enc_rnn_type == "lstm":
- self.enc_rnn = nn.LSTM(
- input_size=self.enc_embed_dim,
- hidden_size=self.enc_hidden_dim,
- num_layers=self.enc_layers,
- bidirectional=bidirectional,
- )
- else:
- raise Exception("XlitError: unknown RNN type mentioned")
-
- def forward(self, x, x_sz, hidden=None):
- """
- x_sz: (batch_size, 1) - Unpadded sequence lengths used for pack_pad
- """
- batch_sz = x.shape[0]
- # x: batch_size, max_length, enc_embed_dim
- x = self.embedding(x)
-
- ## pack the padded data
- # x: max_length, batch_size, enc_embed_dim -> for pack_pad
- x = x.permute(1, 0, 2)
- x = nn.utils.rnn.pack_padded_sequence(x, x_sz, enforce_sorted=False) # unpad
-
- # output: packed_size, batch_size, enc_embed_dim
- # hidden: n_layer**num_directions, batch_size, hidden_dim | if LSTM (h_n, c_n)
- output, hidden = self.enc_rnn(
- x
- ) # gru returns hidden state of all timesteps as well as hidden state at last timestep
-
- ## pad the sequence to the max length in the batch
- # output: max_length, batch_size, enc_emb_dim*directions)
- output, _ = nn.utils.rnn.pad_packed_sequence(output)
-
- # output: batch_size, max_length, hidden_dim
- output = output.permute(1, 0, 2)
-
- return output, hidden
-
- def get_word_embedding(self, x):
- """ """
- x_sz = torch.tensor([len(x)])
- x_ = torch.tensor(x).unsqueeze(0).to(dtype=torch.long)
- # x: 1, max_length, enc_embed_dim
- x = self.embedding(x_)
-
- ## pack the padded data
- # x: max_length, 1, enc_embed_dim -> for pack_pad
- x = x.permute(1, 0, 2)
- x = nn.utils.rnn.pack_padded_sequence(x, x_sz, enforce_sorted=False) # unpad
-
- # output: packed_size, 1, enc_embed_dim
- # hidden: n_layer**num_directions, 1, hidden_dim | if LSTM (h_n, c_n)
- output, hidden = self.enc_rnn(
- x
- ) # gru returns hidden state of all timesteps as well as hidden state at last timestep
-
- out_embed = hidden[0].squeeze()
-
- return out_embed
-
-
-class Decoder(nn.Module):
- def __init__(
- self,
- output_dim,
- embed_dim,
- hidden_dim,
- rnn_type="gru",
- layers=1,
- use_attention=True,
- enc_outstate_dim=None, # enc_directions * enc_hidden_dim
- dropout=0,
- device="cpu",
- ):
- super(Decoder, self).__init__()
-
- self.output_dim = output_dim # tgt_vocab_sz
- self.dec_hidden_dim = hidden_dim
- self.dec_embed_dim = embed_dim
- self.dec_rnn_type = rnn_type
- self.dec_layers = layers
- self.use_attention = use_attention
- self.device = device
- if self.use_attention:
- self.enc_outstate_dim = enc_outstate_dim if enc_outstate_dim else hidden_dim
- else:
- self.enc_outstate_dim = 0
-
- self.embedding = nn.Embedding(self.output_dim, self.dec_embed_dim)
-
- if self.dec_rnn_type == "gru":
- self.dec_rnn = nn.GRU(
- input_size=self.dec_embed_dim
- + self.enc_outstate_dim, # to concat attention_output
- hidden_size=self.dec_hidden_dim, # previous Hidden
- num_layers=self.dec_layers,
- batch_first=True,
- )
- elif self.dec_rnn_type == "lstm":
- self.dec_rnn = nn.LSTM(
- input_size=self.dec_embed_dim
- + self.enc_outstate_dim, # to concat attention_output
- hidden_size=self.dec_hidden_dim, # previous Hidden
- num_layers=self.dec_layers,
- batch_first=True,
- )
- else:
- raise Exception("XlitError: unknown RNN type mentioned")
-
- self.fc = nn.Sequential(
- nn.Linear(self.dec_hidden_dim, self.dec_embed_dim),
- nn.LeakyReLU(),
- # nn.Linear(self.dec_embed_dim, self.dec_embed_dim), nn.LeakyReLU(), # removing to reduce size
- nn.Linear(self.dec_embed_dim, self.output_dim),
- )
-
- ##----- Attention ----------
- if self.use_attention:
- self.W1 = nn.Linear(self.enc_outstate_dim, self.dec_hidden_dim)
- self.W2 = nn.Linear(self.dec_hidden_dim, self.dec_hidden_dim)
- self.V = nn.Linear(self.dec_hidden_dim, 1)
-
- def attention(self, x, hidden, enc_output):
- """
- x: (batch_size, 1, dec_embed_dim) -> after Embedding
- enc_output: batch_size, max_length, enc_hidden_dim *num_directions
- hidden: n_layers, batch_size, hidden_size | if LSTM (h_n, c_n)
- """
-
- ## perform addition to calculate the score
-
- # hidden_with_time_axis: batch_size, 1, hidden_dim
- ## hidden_with_time_axis = hidden.permute(1, 0, 2) ## replaced with below 2lines
- hidden_with_time_axis = (
- torch.sum(hidden, axis=0)
- if self.dec_rnn_type != "lstm"
- else torch.sum(hidden[0], axis=0)
- ) # h_n
-
- hidden_with_time_axis = hidden_with_time_axis.unsqueeze(1)
-
- # score: batch_size, max_length, hidden_dim
- score = torch.tanh(self.W1(enc_output) + self.W2(hidden_with_time_axis))
-
- # attention_weights: batch_size, max_length, 1
- # we get 1 at the last axis because we are applying score to self.V
- attention_weights = torch.softmax(self.V(score), dim=1)
-
- # context_vector shape after sum == (batch_size, hidden_dim)
- context_vector = attention_weights * enc_output
- context_vector = torch.sum(context_vector, dim=1)
- # context_vector: batch_size, 1, hidden_dim
- context_vector = context_vector.unsqueeze(1)
-
- # attend_out (batch_size, 1, dec_embed_dim + hidden_size)
- attend_out = torch.cat((context_vector, x), -1)
-
- return attend_out, attention_weights
-
- def forward(self, x, hidden, enc_output):
- """
- x: (batch_size, 1)
- enc_output: batch_size, max_length, dec_embed_dim
- hidden: n_layer, batch_size, hidden_size | lstm: (h_n, c_n)
- """
- if (hidden is None) and (self.use_attention is False):
- raise Exception(
- "XlitError: No use of a decoder with No attention and No Hidden"
- )
-
- batch_sz = x.shape[0]
-
- if hidden is None:
- # hidden: n_layers, batch_size, hidden_dim
- hid_for_att = torch.zeros(
- (self.dec_layers, batch_sz, self.dec_hidden_dim)
- ).to(self.device)
- elif self.dec_rnn_type == "lstm":
- hid_for_att = hidden[1] # c_n
-
- # x (batch_size, 1, dec_embed_dim) -> after embedding
- x = self.embedding(x)
-
- if self.use_attention:
- # x (batch_size, 1, dec_embed_dim + hidden_size) -> after attention
- # aw: (batch_size, max_length, 1)
- x, aw = self.attention(x, hidden, enc_output)
- else:
- x, aw = x, 0
-
- # passing the concatenated vector to the GRU
- # output: (batch_size, n_layers, hidden_size)
- # hidden: n_layers, batch_size, hidden_size | if LSTM (h_n, c_n)
- output, hidden = (
- self.dec_rnn(x, hidden) if hidden is not None else self.dec_rnn(x)
- )
-
- # output :shp: (batch_size * 1, hidden_size)
- output = output.view(-1, output.size(2))
-
- # output :shp: (batch_size * 1, output_dim)
- output = self.fc(output)
-
- return output, hidden, aw
-
-
-class Seq2Seq(nn.Module):
- """
- Class dependency: Encoder, Decoder
- """
-
- def __init__(
- self, encoder, decoder, pass_enc2dec_hid=False, dropout=0, device="cpu"
- ):
- super(Seq2Seq, self).__init__()
-
- self.encoder = encoder
- self.decoder = decoder
- self.device = device
- self.pass_enc2dec_hid = pass_enc2dec_hid
- _force_en2dec_hid_conv = False
-
- if self.pass_enc2dec_hid:
- assert (
- decoder.dec_hidden_dim == encoder.enc_hidden_dim
- ), "Hidden Dimension of encoder and decoder must be same, or unset `pass_enc2dec_hid`"
- if decoder.use_attention:
- assert (
- decoder.enc_outstate_dim
- == encoder.enc_directions * encoder.enc_hidden_dim
- ), "Set `enc_out_dim` correctly in decoder"
- assert (
- self.pass_enc2dec_hid or decoder.use_attention
- ), "No use of a decoder with No attention and No Hidden from Encoder"
-
- self.use_conv_4_enc2dec_hid = False
- if (
- self.pass_enc2dec_hid
- and (encoder.enc_directions * encoder.enc_layers != decoder.dec_layers)
- ) or _force_en2dec_hid_conv:
- if encoder.enc_rnn_type == "lstm" or encoder.enc_rnn_type == "lstm":
- raise Exception(
- "XlitError: conv for enc2dec_hid not implemented; Change the layer numbers appropriately"
- )
-
- self.use_conv_4_enc2dec_hid = True
- self.enc_hid_1ax = encoder.enc_directions * encoder.enc_layers
- self.dec_hid_1ax = decoder.dec_layers
- self.e2d_hidden_conv = nn.Conv1d(self.enc_hid_1ax, self.dec_hid_1ax, 1)
-
- def enc2dec_hidden(self, enc_hidden):
- """
- enc_hidden: n_layer, batch_size, hidden_dim*num_directions
- TODO: Implement the logic for LSTm bsed model
- """
- # hidden: batch_size, enc_layer*num_directions, enc_hidden_dim
- hidden = enc_hidden.permute(1, 0, 2).contiguous()
- # hidden: batch_size, dec_layers, dec_hidden_dim -> [N,C,Tstep]
- hidden = self.e2d_hidden_conv(hidden)
-
- # hidden: dec_layers, batch_size , dec_hidden_dim
- hidden_for_dec = hidden.permute(1, 0, 2).contiguous()
-
- return hidden_for_dec
-
- def active_beam_inference(self, src, beam_width=3, max_tgt_sz=50):
- """Search based decoding
- src: (sequence_len)
- """
-
- def _avg_score(p_tup):
- """Used for Sorting
- TODO: Dividing by length of sequence power alpha as hyperparam
- """
- return p_tup[0]
-
- import sys
-
- batch_size = 1
- start_tok = src[0]
- end_tok = src[-1]
- src_sz = torch.tensor([len(src)])
- src_ = src.unsqueeze(0)
-
- # enc_output: (batch_size, padded_seq_length, enc_hidden_dim*num_direction)
- # enc_hidden: (enc_layers*num_direction, batch_size, hidden_dim)
- enc_output, enc_hidden = self.encoder(src_, src_sz)
-
- if self.pass_enc2dec_hid:
- # dec_hidden: dec_layers, batch_size , dec_hidden_dim
- if self.use_conv_4_enc2dec_hid:
- init_dec_hidden = self.enc2dec_hidden(enc_hidden)
- else:
- init_dec_hidden = enc_hidden
- else:
- # dec_hidden -> Will be initialized to zeros internally
- init_dec_hidden = None
-
- # top_pred[][0] = Σ-log_softmax
- # top_pred[][1] = sequence torch.tensor shape: (1)
- # top_pred[][2] = dec_hidden
- top_pred_list = [(0, start_tok.unsqueeze(0), init_dec_hidden)]
-
- for t in range(max_tgt_sz):
- cur_pred_list = []
-
- for p_tup in top_pred_list:
- if p_tup[1][-1] == end_tok:
- cur_pred_list.append(p_tup)
- continue
-
- # dec_hidden: dec_layers, 1, hidden_dim
- # dec_output: 1, output_dim
- dec_output, dec_hidden, _ = self.decoder(
- x=p_tup[1][-1].view(1, 1), # dec_input: (1,1)
- hidden=p_tup[2],
- enc_output=enc_output,
- )
-
- ## π{prob} = Σ{log(prob)} -> to prevent diminishing
- # dec_output: (1, output_dim)
- dec_output = nn.functional.log_softmax(dec_output, dim=1)
- # pred_topk.values & pred_topk.indices: (1, beam_width)
- pred_topk = torch.topk(dec_output, k=beam_width, dim=1)
-
- for i in range(beam_width):
- sig_logsmx_ = p_tup[0] + pred_topk.values[0][i]
- # seq_tensor_ : (seq_len)
- seq_tensor_ = torch.cat((p_tup[1], pred_topk.indices[0][i].view(1)))
-
- cur_pred_list.append((sig_logsmx_, seq_tensor_, dec_hidden))
-
- cur_pred_list.sort(key=_avg_score, reverse=True) # Maximized order
- top_pred_list = cur_pred_list[:beam_width]
-
- # check if end_tok of all topk
- end_flags_ = [1 if t[1][-1] == end_tok else 0 for t in top_pred_list]
- if beam_width == sum(end_flags_):
- break
-
- pred_tnsr_list = [t[1] for t in top_pred_list]
-
- return pred_tnsr_list
-
-
-##===================== Glyph handlers =======================================
-
-
-class GlyphStrawboss:
- def __init__(self, glyphs="en"):
- """list of letters in a language in unicode
- lang: ISO Language code
- glyphs: json file with script information
- """
- if glyphs == "en":
- # Smallcase alone
- self.glyphs = [chr(alpha) for alpha in range(97, 122 + 1)]
- else:
- self.dossier = json.load(open(glyphs, encoding="utf-8"))
- self.glyphs = self.dossier["glyphs"]
- self.numsym_map = self.dossier["numsym_map"]
-
- self.char2idx = {}
- self.idx2char = {}
- self._create_index()
-
- def _create_index(self):
-
- self.char2idx["_"] = 0 # pad
- self.char2idx["$"] = 1 # start
- self.char2idx["#"] = 2 # end
- self.char2idx["*"] = 3 # Mask
- self.char2idx["'"] = 4 # apostrophe U+0027
- self.char2idx["%"] = 5 # unused
- self.char2idx["!"] = 6 # unused
-
- # letter to index mapping
- for idx, char in enumerate(self.glyphs):
- self.char2idx[char] = idx + 7 # +7 token initially
-
- # index to letter mapping
- for char, idx in self.char2idx.items():
- self.idx2char[idx] = char
-
- def size(self):
- return len(self.char2idx)
-
- def word2xlitvec(self, word):
- """Converts given string of gyphs(word) to vector(numpy)
- Also adds tokens for start and end
- """
- try:
- vec = [self.char2idx["$"]] # start token
- for i in list(word):
- vec.append(self.char2idx[i])
- vec.append(self.char2idx["#"]) # end token
-
- vec = np.asarray(vec, dtype=np.int64)
- return vec
-
- except Exception as error:
- print("XlitError: In word:", word, "Error Char not in Token:", error)
- sys.exit()
-
- def xlitvec2word(self, vector):
- """Converts vector(numpy) to string of glyphs(word)"""
- char_list = []
- for i in vector:
- char_list.append(self.idx2char[i])
-
- word = "".join(char_list).replace("$", "").replace("#", "") # remove tokens
- word = word.replace("_", "").replace("*", "") # remove tokens
- return word
-
-
-class VocabSanitizer:
- def __init__(self, data_file):
- """
- data_file: path to file conatining vocabulary list
- """
- extension = os.path.splitext(data_file)[-1]
- if extension == ".json":
- self.vocab_set = set(json.load(open(data_file, encoding="utf-8")))
- elif extension == ".csv":
- self.vocab_df = pd.read_csv(data_file).set_index("WORD")
- self.vocab_set = set(self.vocab_df.index)
- else:
- print("XlitError: Only Json/CSV file extension supported")
-
- def reposition(self, word_list):
- """Reorder Words in list"""
- new_list = []
- temp_ = word_list.copy()
- for v in word_list:
- if v in self.vocab_set:
- new_list.append(v)
- temp_.remove(v)
- new_list.extend(temp_)
-
- return new_list
-
-
-##=============== INSTANTIATION ================================================
-
-
-class XlitPiston:
- """
- For handling prediction & post-processing of transliteration for a single language
- Class dependency: Seq2Seq, GlyphStrawboss, VocabSanitizer
- Global Variables: F_DIR
- """
-
- def __init__(
- self,
- weight_path,
- vocab_file,
- tglyph_cfg_file,
- iglyph_cfg_file="en",
- device="cpu",
- ):
-
- self.device = device
- self.in_glyph_obj = GlyphStrawboss(iglyph_cfg_file)
- self.tgt_glyph_obj = GlyphStrawboss(glyphs=tglyph_cfg_file)
- self.voc_sanity = VocabSanitizer(vocab_file)
-
- self._numsym_set = set(
- json.load(open(tglyph_cfg_file, encoding="utf-8"))["numsym_map"].keys()
- )
- self._inchar_set = set("abcdefghijklmnopqrstuvwxyz")
- self._natscr_set = set().union(
- self.tgt_glyph_obj.glyphs, sum(self.tgt_glyph_obj.numsym_map.values(), [])
- )
-
- ## Model Config Static TODO: add defining in json support
- input_dim = self.in_glyph_obj.size()
- output_dim = self.tgt_glyph_obj.size()
- enc_emb_dim = 300
- dec_emb_dim = 300
- enc_hidden_dim = 512
- dec_hidden_dim = 512
- rnn_type = "lstm"
- enc2dec_hid = True
- attention = True
- enc_layers = 1
- dec_layers = 2
- m_dropout = 0
- enc_bidirect = True
- enc_outstate_dim = enc_hidden_dim * (2 if enc_bidirect else 1)
-
- enc = Encoder(
- input_dim=input_dim,
- embed_dim=enc_emb_dim,
- hidden_dim=enc_hidden_dim,
- rnn_type=rnn_type,
- layers=enc_layers,
- dropout=m_dropout,
- device=self.device,
- bidirectional=enc_bidirect,
- )
- dec = Decoder(
- output_dim=output_dim,
- embed_dim=dec_emb_dim,
- hidden_dim=dec_hidden_dim,
- rnn_type=rnn_type,
- layers=dec_layers,
- dropout=m_dropout,
- use_attention=attention,
- enc_outstate_dim=enc_outstate_dim,
- device=self.device,
- )
- self.model = Seq2Seq(enc, dec, pass_enc2dec_hid=enc2dec_hid, device=self.device)
- self.model = self.model.to(self.device)
- weights = torch.load(weight_path, map_location=torch.device(self.device))
-
- self.model.load_state_dict(weights)
- self.model.eval()
-
- def character_model(self, word, beam_width=1):
- in_vec = torch.from_numpy(self.in_glyph_obj.word2xlitvec(word)).to(self.device)
- ## change to active or passive beam
- p_out_list = self.model.active_beam_inference(in_vec, beam_width=beam_width)
- p_result = [
- self.tgt_glyph_obj.xlitvec2word(out.cpu().numpy()) for out in p_out_list
- ]
-
- result = self.voc_sanity.reposition(p_result)
-
- # List type
- return result
-
- def numsym_model(self, seg):
- """tgt_glyph_obj.numsym_map[x] returns a list object"""
- if len(seg) == 1:
- return [seg] + self.tgt_glyph_obj.numsym_map[seg]
-
- a = [self.tgt_glyph_obj.numsym_map[n][0] for n in seg]
- return [seg] + ["".join(a)]
-
- def _word_segementer(self, sequence):
-
- sequence = sequence.lower()
- accepted = set().union(self._numsym_set, self._inchar_set, self._natscr_set)
- # sequence = ''.join([i for i in sequence if i in accepted])
-
- segment = []
- idx = 0
- seq_ = list(sequence)
- while len(seq_):
- # for Number-Symbol
- temp = ""
- while len(seq_) and seq_[0] in self._numsym_set:
- temp += seq_[0]
- seq_.pop(0)
- if temp != "":
- segment.append(temp)
-
- # for Target Chars
- temp = ""
- while len(seq_) and seq_[0] in self._natscr_set:
- temp += seq_[0]
- seq_.pop(0)
- if temp != "":
- segment.append(temp)
-
- # for Input-Roman Chars
- temp = ""
- while len(seq_) and seq_[0] in self._inchar_set:
- temp += seq_[0]
- seq_.pop(0)
- if temp != "":
- segment.append(temp)
-
- temp = ""
- while len(seq_) and seq_[0] not in accepted:
- temp += seq_[0]
- seq_.pop(0)
- if temp != "":
- segment.append(temp)
-
- return segment
-
- def inferencer(self, sequence, beam_width=10):
-
- seg = self._word_segementer(sequence[:120])
- lit_seg = []
-
- p = 0
- while p < len(seg):
- if seg[p][0] in self._natscr_set:
- lit_seg.append([seg[p]])
- p += 1
-
- elif seg[p][0] in self._inchar_set:
- lit_seg.append(self.character_model(seg[p], beam_width=beam_width))
- p += 1
-
- elif seg[p][0] in self._numsym_set: # num & punc
- lit_seg.append(self.numsym_model(seg[p]))
- p += 1
- else:
- lit_seg.append([seg[p]])
- p += 1
-
- ## IF segment less/equal to 2 then return combinotorial,
- ## ELSE only return top1 of each result concatenated
- if len(lit_seg) == 1:
- final_result = lit_seg[0]
-
- elif len(lit_seg) == 2:
- final_result = [""]
- for seg in lit_seg:
- new_result = []
- for s in seg:
- for f in final_result:
- new_result.append(f + s)
- final_result = new_result
-
- else:
- new_result = []
- for seg in lit_seg:
- new_result.append(seg[0])
- final_result = ["".join(new_result)]
-
- return final_result
-
-
-from collections.abc import Iterable
-from pydload import dload
-import zipfile
-
-MODEL_DOWNLOAD_URL_PREFIX = "https://github.com/AI4Bharat/IndianNLP-Transliteration/releases/download/xlit_v0.5.0/"
-
-
-def is_folder_writable(folder):
- try:
- os.makedirs(folder, exist_ok=True)
- tmp_file = os.path.join(folder, ".write_test")
- with open(tmp_file, "w") as f:
- f.write("Permission Check")
- os.remove(tmp_file)
- return True
- except:
- return False
-
-
-def is_directory_writable(path):
- if os.name == "nt":
- return is_folder_writable(path)
- return os.access(path, os.W_OK | os.X_OK)
-
-
-class XlitEngine:
- """
- For Managing the top level tasks and applications of transliteration
- Global Variables: F_DIR
- """
-
- def __init__(
- self, lang2use="all", config_path="translit_models/default_lineup.json"
- ):
-
- lineup = json.load(open(os.path.join(F_DIR, config_path), encoding="utf-8"))
- self.lang_config = {}
- if isinstance(lang2use, str):
- if lang2use == "all":
- self.lang_config = lineup
- elif lang2use in lineup:
- self.lang_config[lang2use] = lineup[lang2use]
- else:
- raise Exception(
- "XlitError: The entered Langauge code not found. Available are {}".format(
- lineup.keys()
- )
- )
-
- elif isinstance(lang2use, Iterable):
- for l in lang2use:
- try:
- self.lang_config[l] = lineup[l]
- except:
- print(
- "XlitError: Language code {} not found, Skipping...".format(l)
- )
- else:
- raise Exception(
- "XlitError: lang2use must be a list of language codes (or) string of single language code"
- )
-
- if is_directory_writable(F_DIR):
- models_path = os.path.join(F_DIR, "translit_models")
- else:
- user_home = os.path.expanduser("~")
- models_path = os.path.join(user_home, ".AI4Bharat_Xlit_Models")
- os.makedirs(models_path, exist_ok=True)
- self.download_models(models_path)
-
- self.langs = {}
- self.lang_model = {}
- for la in self.lang_config:
- try:
- print("Loading {}...".format(la))
- self.lang_model[la] = XlitPiston(
- weight_path=os.path.join(
- models_path, self.lang_config[la]["weight"]
- ),
- vocab_file=os.path.join(models_path, self.lang_config[la]["vocab"]),
- tglyph_cfg_file=os.path.join(
- models_path, self.lang_config[la]["script"]
- ),
- iglyph_cfg_file="en",
- )
- self.langs[la] = self.lang_config[la]["name"]
- except Exception as error:
- print("XlitError: Failure in loading {} \n".format(la), error)
- print(XlitError.loading_err.value)
-
- def download_models(self, models_path):
- """
- Download models from GitHub Releases if not exists
- """
- for l in self.lang_config:
- lang_name = self.lang_config[l]["eng_name"]
- lang_model_path = os.path.join(models_path, lang_name)
- if not os.path.isdir(lang_model_path):
- print("Downloading model for language: %s" % lang_name)
- remote_url = MODEL_DOWNLOAD_URL_PREFIX + lang_name + ".zip"
- downloaded_zip_path = os.path.join(models_path, lang_name + ".zip")
- dload(url=remote_url, save_to_path=downloaded_zip_path, max_time=None)
-
- if not os.path.isfile(downloaded_zip_path):
- exit(
- f"ERROR: Unable to download model from {remote_url} into {models_path}"
- )
-
- with zipfile.ZipFile(downloaded_zip_path, "r") as zip_ref:
- zip_ref.extractall(models_path)
-
- if os.path.isdir(lang_model_path):
- os.remove(downloaded_zip_path)
- else:
- exit(
- f"ERROR: Unable to find models in {lang_model_path} after download"
- )
- return
-
- def translit_word(self, eng_word, lang_code="default", topk=7, beam_width=10):
- if eng_word == "":
- return []
-
- if lang_code in self.langs:
- try:
- res_list = self.lang_model[lang_code].inferencer(
- eng_word, beam_width=beam_width
- )
- return res_list[:topk]
-
- except Exception as error:
- print("XlitError:", traceback.format_exc())
- print(XlitError.internal_err.value)
- return XlitError.internal_err
-
- elif lang_code == "default":
- try:
- res_dict = {}
- for la in self.lang_model:
- res = self.lang_model[la].inferencer(
- eng_word, beam_width=beam_width
- )
- res_dict[la] = res[:topk]
- return res_dict
-
- except Exception as error:
- print("XlitError:", traceback.format_exc())
- print(XlitError.internal_err.value)
- return XlitError.internal_err
-
- else:
- print("XlitError: Unknown Langauge requested", lang_code)
- print(XlitError.lang_err.value)
- return XlitError.lang_err
-
- def translit_sentence(self, eng_sentence, lang_code="default", beam_width=10):
- if eng_sentence == "":
- return []
-
- if lang_code in self.langs:
- try:
- out_str = ""
- for word in eng_sentence.split():
- res_ = self.lang_model[lang_code].inferencer(
- word, beam_width=beam_width
- )
- out_str = out_str + res_[0] + " "
- return out_str[:-1]
-
- except Exception as error:
- print("XlitError:", traceback.format_exc())
- print(XlitError.internal_err.value)
- return XlitError.internal_err
-
- elif lang_code == "default":
- try:
- res_dict = {}
- for la in self.lang_model:
- out_str = ""
- for word in eng_sentence.split():
- res_ = self.lang_model[la].inferencer(
- word, beam_width=beam_width
- )
- out_str = out_str + res_[0] + " "
- res_dict[la] = out_str[:-1]
- return res_dict
-
- except Exception as error:
- print("XlitError:", traceback.format_exc())
- print(XlitError.internal_err.value)
- return XlitError.internal_err
-
- else:
- print("XlitError: Unknown Langauge requested", lang_code)
- print(XlitError.lang_err.value)
- return XlitError.lang_err
-
-
-if __name__ == "__main__":
-
- available_lang = [
- "bn",
- "gu",
- "hi",
- "kn",
- "gom",
- "mai",
- "ml",
- "mr",
- "pa",
- "sd",
- "si",
- "ta",
- "te",
- "ur",
- ]
-
- reg = re.compile(r"[a-zA-Z]")
- lang = "hi"
- engine = XlitEngine(
- lang
- ) # if you don't specify lang code here, this will give results in all langs available
- sent = "Hello World! ABCD क्या हाल है आपका?"
- words = [
- engine.translit_word(word, topk=1)[lang][0] if reg.match(word) else word
- for word in sent.split()
- ] # only transliterated en words, leaves rest as it is
- updated_sent = " ".join(words)
-
- print(updated_sent)
-
- # output : हेलो वर्ल्ड! क्या हाल है आपका?
-
- # y = engine.translit_sentence("Hello World !")['hi']
- # print(y)
diff --git a/spaces/Hexamind/QnA/src/tools/llm.py b/spaces/Hexamind/QnA/src/tools/llm.py
deleted file mode 100644
index 05cfe61da04479b0800c715d1c5fed25391edc65..0000000000000000000000000000000000000000
--- a/spaces/Hexamind/QnA/src/tools/llm.py
+++ /dev/null
@@ -1,57 +0,0 @@
-class LlmAgent:
-
- def __init__(self, llm):
- self.llm = llm
-
- def generate_paragraph(self, query: str, context: {}, histo: [(str, str)], language='fr') -> str:
- """generates the answer"""
- template = (f"You are a conversation bot designed to answer to the query from users delimited by "
- f"triple backticks: "
- f"\\n ``` {query} ```\\n"
- f"Your answer is based on the context delimited by triple backticks: "
- f"\\n ``` {context} ```\\n"
- f"You are consistent and avoid redundancies with the rest of the initial conversation in French"
- f"delimited by triple backticks: "
- f"\\n ``` {histo} ```\\n"
- f"Your response shall be in {language} and shall be concise"
- f"In case the provided context is not relevant to answer to the question, just return that you "
- f"don't know the answer ")
-
- p = self.llm(template)
- print("****************")
- print(template)
- print("----")
- print(p)
- return p
-
- def translate(self, text: str, language="en") -> str:
- """translates"""
-
- languages = "`French to English" if language == "en" else "English to French"
-
- template = (f" Your task consists in translating {languages}\\n"
- f" the following text delimited by by triple backticks: ```{text}```\n"
- )
-
- p = self.llm(template)
- return p
-
- def generate_answer(self, query: str, answer_en: str, histo_fr: str, context_fr: str) -> str:
- """provides the final answer in French based on the initial query and the answer in english"""
-
- def _cut_unfinished_sentence(s: str):
- return '.'.join(s.split('.')[:-1])
-
- template = (f"Your task consists in translating the answer in French to the query "
- f"delimited by triple backticks: ```{query}``` \\n"
- f"You are given the answer in english delimited by triple backticks: ```{answer_en}```"
- f"\\n You don't add new content to the answer in English but: "
- f"\\n 1 You can use some vocabulary from the context in French delimited by triple backticks: "
- f"```{context_fr}```"
- f"\\n 2 You are consistent and avoid redundancies with the rest of the initial"
- f" conversation in French delimited by triple backticks: ```{histo_fr}```"
- )
-
- p = self.llm(template)
- # p = _cut_unfinished_sentence(p)
- return p
diff --git a/spaces/ICML2022/OFA/fairseq/examples/speech_recognition/datasets/prepare-librispeech.sh b/spaces/ICML2022/OFA/fairseq/examples/speech_recognition/datasets/prepare-librispeech.sh
deleted file mode 100644
index 9e9297f08947027685ff508bfa91ff26b0d8ea0c..0000000000000000000000000000000000000000
--- a/spaces/ICML2022/OFA/fairseq/examples/speech_recognition/datasets/prepare-librispeech.sh
+++ /dev/null
@@ -1,88 +0,0 @@
-#!/usr/bin/env bash
-# Copyright (c) Facebook, Inc. and its affiliates.
-#
-# This source code is licensed under the MIT license found in the
-# LICENSE file in the root directory of this source tree.
-
-# Prepare librispeech dataset
-
-base_url=www.openslr.org/resources/12
-train_dir=train_960
-
-if [ "$#" -ne 2 ]; then
- echo "Usage: $0 "
- echo "e.g.: $0 /tmp/librispeech_raw/ ~/data/librispeech_final"
- exit 1
-fi
-
-download_dir=${1%/}
-out_dir=${2%/}
-
-fairseq_root=~/fairseq-py/
-mkdir -p ${out_dir}
-cd ${out_dir} || exit
-
-nbpe=5000
-bpemode=unigram
-
-if [ ! -d "$fairseq_root" ]; then
- echo "$0: Please set correct fairseq_root"
- exit 1
-fi
-
-echo "Data Download"
-for part in dev-clean test-clean dev-other test-other train-clean-100 train-clean-360 train-other-500; do
- url=$base_url/$part.tar.gz
- if ! wget -P $download_dir $url; then
- echo "$0: wget failed for $url"
- exit 1
- fi
- if ! tar -C $download_dir -xvzf $download_dir/$part.tar.gz; then
- echo "$0: error un-tarring archive $download_dir/$part.tar.gz"
- exit 1
- fi
-done
-
-echo "Merge all train packs into one"
-mkdir -p ${download_dir}/LibriSpeech/${train_dir}/
-for part in train-clean-100 train-clean-360 train-other-500; do
- mv ${download_dir}/LibriSpeech/${part}/* $download_dir/LibriSpeech/${train_dir}/
-done
-echo "Merge train text"
-find ${download_dir}/LibriSpeech/${train_dir}/ -name '*.txt' -exec cat {} \; >> ${download_dir}/LibriSpeech/${train_dir}/text
-
-# Use combined dev-clean and dev-other as validation set
-find ${download_dir}/LibriSpeech/dev-clean/ ${download_dir}/LibriSpeech/dev-other/ -name '*.txt' -exec cat {} \; >> ${download_dir}/LibriSpeech/valid_text
-find ${download_dir}/LibriSpeech/test-clean/ -name '*.txt' -exec cat {} \; >> ${download_dir}/LibriSpeech/test-clean/text
-find ${download_dir}/LibriSpeech/test-other/ -name '*.txt' -exec cat {} \; >> ${download_dir}/LibriSpeech/test-other/text
-
-
-dict=data/lang_char/${train_dir}_${bpemode}${nbpe}_units.txt
-encoded=data/lang_char/${train_dir}_${bpemode}${nbpe}_encoded.txt
-fairseq_dict=data/lang_char/${train_dir}_${bpemode}${nbpe}_fairseq_dict.txt
-bpemodel=data/lang_char/${train_dir}_${bpemode}${nbpe}
-echo "dictionary: ${dict}"
-echo "Dictionary preparation"
-mkdir -p data/lang_char/
-echo " 3" > ${dict}
-echo " 2" >> ${dict}
-echo " 1" >> ${dict}
-cut -f 2- -d" " ${download_dir}/LibriSpeech/${train_dir}/text > data/lang_char/input.txt
-spm_train --input=data/lang_char/input.txt --vocab_size=${nbpe} --model_type=${bpemode} --model_prefix=${bpemodel} --input_sentence_size=100000000 --unk_id=3 --eos_id=2 --pad_id=1 --bos_id=-1 --character_coverage=1
-spm_encode --model=${bpemodel}.model --output_format=piece < data/lang_char/input.txt > ${encoded}
-cat ${encoded} | tr ' ' '\n' | sort | uniq | awk '{print $0 " " NR+3}' >> ${dict}
-cat ${encoded} | tr ' ' '\n' | sort | uniq -c | awk '{print $2 " " $1}' > ${fairseq_dict}
-wc -l ${dict}
-
-echo "Prepare train and test jsons"
-for part in train_960 test-other test-clean; do
- python ${fairseq_root}/examples/speech_recognition/datasets/asr_prep_json.py --audio-dirs ${download_dir}/LibriSpeech/${part} --labels ${download_dir}/LibriSpeech/${part}/text --spm-model ${bpemodel}.model --audio-format flac --dictionary ${fairseq_dict} --output ${part}.json
-done
-# fairseq expects to find train.json and valid.json during training
-mv train_960.json train.json
-
-echo "Prepare valid json"
-python ${fairseq_root}/examples/speech_recognition/datasets/asr_prep_json.py --audio-dirs ${download_dir}/LibriSpeech/dev-clean ${download_dir}/LibriSpeech/dev-other --labels ${download_dir}/LibriSpeech/valid_text --spm-model ${bpemodel}.model --audio-format flac --dictionary ${fairseq_dict} --output valid.json
-
-cp ${fairseq_dict} ./dict.txt
-cp ${bpemodel}.model ./spm.model
diff --git a/spaces/ICML2022/OFA/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py b/spaces/ICML2022/OFA/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
deleted file mode 100644
index ccf132b150a7cc1c125c1190b5fd8f43edaae685..0000000000000000000000000000000000000000
--- a/spaces/ICML2022/OFA/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
+++ /dev/null
@@ -1,669 +0,0 @@
-from math import sqrt
-import torch
-import torch.distributions as distr
-from torch.autograd import Variable
-from torch import nn
-from torch.nn import functional as F
-from .layers import ConvNorm, LinearNorm, GlobalAvgPool
-from .utils import to_gpu, get_mask_from_lengths
-
-
-class LocationLayer(nn.Module):
- def __init__(self, attention_n_filters, attention_kernel_size,
- attention_dim):
- super(LocationLayer, self).__init__()
- padding = int((attention_kernel_size - 1) / 2)
- self.location_conv = ConvNorm(2, attention_n_filters,
- kernel_size=attention_kernel_size,
- padding=padding, bias=False, stride=1,
- dilation=1)
- self.location_dense = LinearNorm(attention_n_filters, attention_dim,
- bias=False, w_init_gain='tanh')
-
- def forward(self, attention_weights_cat):
- processed_attention = self.location_conv(attention_weights_cat)
- processed_attention = processed_attention.transpose(1, 2)
- processed_attention = self.location_dense(processed_attention)
- return processed_attention
-
-
-class Attention(nn.Module):
- def __init__(self, attention_rnn_dim, embedding_dim, attention_dim,
- attention_location_n_filters, attention_location_kernel_size):
- super(Attention, self).__init__()
- self.query_layer = LinearNorm(attention_rnn_dim, attention_dim,
- bias=False, w_init_gain='tanh')
- self.memory_layer = LinearNorm(embedding_dim, attention_dim, bias=False,
- w_init_gain='tanh')
- self.v = LinearNorm(attention_dim, 1, bias=False)
- self.location_layer = LocationLayer(attention_location_n_filters,
- attention_location_kernel_size,
- attention_dim)
- self.score_mask_value = -float("inf")
-
- def get_alignment_energies(self, query, processed_memory,
- attention_weights_cat):
- """
- PARAMS
- ------
- query: decoder output (batch, n_mel_channels * n_frames_per_step)
- processed_memory: processed encoder outputs (B, T_in, attention_dim)
- attention_weights_cat: cumulative and prev. att weights (B, 2, max_time)
-
- RETURNS
- -------
- alignment (batch, max_time)
- """
-
- processed_query = self.query_layer(query.unsqueeze(1))
- processed_attention_weights = self.location_layer(attention_weights_cat)
- energies = self.v(torch.tanh(
- processed_query + processed_attention_weights + processed_memory))
-
- energies = energies.squeeze(-1)
- return energies
-
- def forward(self, attention_hidden_state, memory, processed_memory,
- attention_weights_cat, mask):
- """
- PARAMS
- ------
- attention_hidden_state: attention rnn last output
- memory: encoder outputs
- processed_memory: processed encoder outputs
- attention_weights_cat: previous and cummulative attention weights
- mask: binary mask for padded data
- """
- alignment = self.get_alignment_energies(
- attention_hidden_state, processed_memory, attention_weights_cat)
-
- if mask is not None:
- alignment.data.masked_fill_(mask, self.score_mask_value)
-
- attention_weights = F.softmax(alignment, dim=1)
- attention_context = torch.bmm(attention_weights.unsqueeze(1), memory)
- attention_context = attention_context.squeeze(1)
-
- return attention_context, attention_weights
-
-
-class Prenet(nn.Module):
- def __init__(self, in_dim, sizes):
- super(Prenet, self).__init__()
- in_sizes = [in_dim] + sizes[:-1]
- self.layers = nn.ModuleList(
- [LinearNorm(in_size, out_size, bias=False)
- for (in_size, out_size) in zip(in_sizes, sizes)])
-
- def forward(self, x):
- for linear in self.layers:
- x = F.dropout(F.relu(linear(x)), p=0.5, training=True)
- return x
-
-
-class Postnet(nn.Module):
- """Postnet
- - Five 1-d convolution with 512 channels and kernel size 5
- """
-
- def __init__(self, hparams):
- super(Postnet, self).__init__()
- self.convolutions = nn.ModuleList()
-
- self.convolutions.append(
- nn.Sequential(
- ConvNorm(hparams.n_mel_channels, hparams.postnet_embedding_dim,
- kernel_size=hparams.postnet_kernel_size, stride=1,
- padding=int((hparams.postnet_kernel_size - 1) / 2),
- dilation=1, w_init_gain='tanh'),
- nn.BatchNorm1d(hparams.postnet_embedding_dim))
- )
-
- for i in range(1, hparams.postnet_n_convolutions - 1):
- self.convolutions.append(
- nn.Sequential(
- ConvNorm(hparams.postnet_embedding_dim,
- hparams.postnet_embedding_dim,
- kernel_size=hparams.postnet_kernel_size, stride=1,
- padding=int((hparams.postnet_kernel_size - 1) / 2),
- dilation=1, w_init_gain='tanh'),
- nn.BatchNorm1d(hparams.postnet_embedding_dim))
- )
-
- self.convolutions.append(
- nn.Sequential(
- ConvNorm(hparams.postnet_embedding_dim, hparams.n_mel_channels,
- kernel_size=hparams.postnet_kernel_size, stride=1,
- padding=int((hparams.postnet_kernel_size - 1) / 2),
- dilation=1, w_init_gain='linear'),
- nn.BatchNorm1d(hparams.n_mel_channels))
- )
-
- def forward(self, x):
- for i in range(len(self.convolutions) - 1):
- x = F.dropout(torch.tanh(self.convolutions[i](x)), 0.5, self.training)
- x = F.dropout(self.convolutions[-1](x), 0.5, self.training)
-
- return x
-
-
-class Encoder(nn.Module):
- """Encoder module:
- - Three 1-d convolution banks
- - Bidirectional LSTM
- """
- def __init__(self, hparams):
- super(Encoder, self).__init__()
-
- convolutions = []
- for _ in range(hparams.encoder_n_convolutions):
- conv_layer = nn.Sequential(
- ConvNorm(hparams.encoder_embedding_dim,
- hparams.encoder_embedding_dim,
- kernel_size=hparams.encoder_kernel_size, stride=1,
- padding=int((hparams.encoder_kernel_size - 1) / 2),
- dilation=1, w_init_gain='relu'),
- nn.BatchNorm1d(hparams.encoder_embedding_dim))
- convolutions.append(conv_layer)
- self.convolutions = nn.ModuleList(convolutions)
-
- self.lstm = nn.LSTM(hparams.encoder_embedding_dim,
- int(hparams.encoder_embedding_dim / 2), 1,
- batch_first=True, bidirectional=True)
-
- def forward(self, x, input_lengths):
- for conv in self.convolutions:
- x = F.dropout(F.relu(conv(x)), 0.5, self.training)
-
- x = x.transpose(1, 2)
-
- # pytorch tensor are not reversible, hence the conversion
- input_lengths = input_lengths.cpu().numpy()
- x = nn.utils.rnn.pack_padded_sequence(
- x, input_lengths, batch_first=True)
-
- self.lstm.flatten_parameters()
- outputs, _ = self.lstm(x)
-
- outputs, _ = nn.utils.rnn.pad_packed_sequence(
- outputs, batch_first=True)
-
- return outputs
-
- def inference(self, x):
- for conv in self.convolutions:
- x = F.dropout(F.relu(conv(x)), 0.5, self.training)
-
- x = x.transpose(1, 2)
-
- self.lstm.flatten_parameters()
- outputs, _ = self.lstm(x)
-
- return outputs
-
-
-class AudioEncoder(nn.Module):
- def __init__(self, hparams):
- super(AudioEncoder, self).__init__()
-
- assert hparams.lat_dim > 0
-
- convolutions = []
- inp_dim = hparams.n_mel_channels
- for _ in range(hparams.lat_n_convolutions):
- conv_layer = nn.Sequential(
- ConvNorm(inp_dim, hparams.lat_n_filters,
- kernel_size=hparams.lat_kernel_size, stride=1,
- padding=int((hparams.lat_kernel_size - 1) / 2),
- dilation=1, w_init_gain='tanh'),
- nn.BatchNorm1d(hparams.lat_n_filters))
- inp_dim = hparams.lat_n_filters
- convolutions.append(conv_layer)
- self.convolutions = nn.ModuleList(convolutions)
-
- self.lstm = nn.LSTM(hparams.lat_n_filters,
- int(hparams.lat_n_filters / 2),
- hparams.lat_n_blstms, batch_first=True,
- bidirectional=True)
- self.pool = GlobalAvgPool()
-
- self.mu_proj = LinearNorm(hparams.lat_n_filters, hparams.lat_dim)
- self.logvar_proj = LinearNorm(hparams.lat_n_filters, hparams.lat_dim)
- self.lat_dim = hparams.lat_dim
-
- def forward(self, x, lengths):
- """
- Args:
- x (torch.Tensor): (B, F, T)
- """
-
- for conv in self.convolutions:
- x = F.dropout(F.tanh(conv(x)), 0.5, self.training)
-
- x = x.transpose(1, 2) # (B, T, D)
-
- # x may not be sorted by length. Sort->process->unsort
- max_len = x.size(1)
- assert max_len == torch.max(lengths).item()
-
- lengths, perm_idx = lengths.sort(0, descending=True)
- x = x[perm_idx]
- x = nn.utils.rnn.pack_padded_sequence(x, lengths, batch_first=True)
-
- self.lstm.flatten_parameters()
- outputs, _ = self.lstm(x)
- outputs, _ = nn.utils.rnn.pad_packed_sequence(outputs, batch_first=True)
-
- _, unperm_idx = perm_idx.sort(0)
- outputs = outputs[unperm_idx] # (B, T, D)
- lengths = lengths[unperm_idx] # (B, T, D)
-
- outputs = self.pool(outputs, lengths) # (B, D)
-
- mu = self.mu_proj(outputs)
- logvar = self.logvar_proj(outputs)
- z = distr.Normal(mu, logvar).rsample()
- return z, mu, logvar
-
-
-class Decoder(nn.Module):
- def __init__(self, hparams):
- super(Decoder, self).__init__()
- self.n_mel_channels = hparams.n_mel_channels
- self.n_frames_per_step = hparams.n_frames_per_step
- self.encoder_embedding_dim = hparams.encoder_embedding_dim
- self.obs_dim = hparams.obs_dim
- self.lat_dim = hparams.lat_dim
- self.attention_rnn_dim = hparams.attention_rnn_dim
- self.decoder_rnn_dim = hparams.decoder_rnn_dim
- self.prenet_dim = hparams.prenet_dim
- self.max_decoder_steps = hparams.max_decoder_steps
- self.gate_threshold = hparams.gate_threshold
- self.p_attention_dropout = hparams.p_attention_dropout
- self.p_decoder_dropout = hparams.p_decoder_dropout
-
- self.prenet = Prenet(
- hparams.n_mel_channels * hparams.n_frames_per_step,
- [hparams.prenet_dim, hparams.prenet_dim])
-
- self.attention_rnn = nn.LSTMCell(
- hparams.prenet_dim + hparams.encoder_embedding_dim,
- hparams.attention_rnn_dim)
-
- self.attention_layer = Attention(
- hparams.attention_rnn_dim, hparams.encoder_embedding_dim,
- hparams.attention_dim, hparams.attention_location_n_filters,
- hparams.attention_location_kernel_size)
-
- encoder_tot_dim = (hparams.encoder_embedding_dim + \
- hparams.lat_dim + hparams.obs_dim)
- self.decoder_rnn = nn.LSTMCell(
- hparams.attention_rnn_dim + encoder_tot_dim,
- hparams.decoder_rnn_dim, 1)
-
- self.linear_projection = LinearNorm(
- hparams.decoder_rnn_dim + encoder_tot_dim,
- hparams.n_mel_channels * hparams.n_frames_per_step)
-
- self.gate_layer = LinearNorm(
- hparams.decoder_rnn_dim + encoder_tot_dim, 1,
- bias=True, w_init_gain='sigmoid')
-
- def get_go_frame(self, memory):
- """ Gets all zeros frames to use as first decoder input
- PARAMS
- ------
- memory: decoder outputs
-
- RETURNS
- -------
- decoder_input: all zeros frames
- """
- B = memory.size(0)
- decoder_input = Variable(memory.data.new(
- B, self.n_mel_channels * self.n_frames_per_step).zero_())
- return decoder_input
-
- def initialize_decoder_states(self, memory, obs_and_lat, mask):
- """ Initializes attention rnn states, decoder rnn states, attention
- weights, attention cumulative weights, attention context, stores memory
- and stores processed memory
- PARAMS
- ------
- memory: Encoder outputs
- obs_and_lat: Observed and latent attribute embeddings
- mask: Mask for padded data if training, expects None for inference
- """
- B = memory.size(0)
- MAX_TIME = memory.size(1)
-
- self.attention_hidden = Variable(memory.data.new(
- B, self.attention_rnn_dim).zero_())
- self.attention_cell = Variable(memory.data.new(
- B, self.attention_rnn_dim).zero_())
-
- self.decoder_hidden = Variable(memory.data.new(
- B, self.decoder_rnn_dim).zero_())
- self.decoder_cell = Variable(memory.data.new(
- B, self.decoder_rnn_dim).zero_())
-
- self.attention_weights = Variable(memory.data.new(
- B, MAX_TIME).zero_())
- self.attention_weights_cum = Variable(memory.data.new(
- B, MAX_TIME).zero_())
- self.attention_context = Variable(memory.data.new(
- B, self.encoder_embedding_dim).zero_())
-
- self.memory = memory
- self.processed_memory = self.attention_layer.memory_layer(memory)
- self.obs_and_lat = obs_and_lat
- self.mask = mask
-
- def parse_decoder_inputs(self, decoder_inputs):
- """ Prepares decoder inputs, i.e. mel outputs
- PARAMS
- ------
- decoder_inputs: inputs used for teacher-forced training, i.e. mel-specs
-
- RETURNS
- -------
- inputs: processed decoder inputs
-
- """
- # (B, n_mel_channels, T_out) -> (B, T_out, n_mel_channels)
- decoder_inputs = decoder_inputs.transpose(1, 2)
- decoder_inputs = decoder_inputs.view(
- decoder_inputs.size(0),
- int(decoder_inputs.size(1)/self.n_frames_per_step), -1)
- # (B, T_out, n_mel_channels) -> (T_out, B, n_mel_channels)
- decoder_inputs = decoder_inputs.transpose(0, 1)
- return decoder_inputs
-
- def parse_decoder_outputs(self, mel_outputs, gate_outputs, alignments):
- """ Prepares decoder outputs for output
- PARAMS
- ------
- mel_outputs:
- gate_outputs: gate output energies
- alignments:
-
- RETURNS
- -------
- mel_outputs:
- gate_outpust: gate output energies
- alignments:
- """
- # (T_out, B) -> (B, T_out)
- alignments = torch.stack(alignments).transpose(0, 1)
- # (T_out, B) -> (B, T_out)
- gate_outputs = torch.stack(gate_outputs).transpose(0, 1)
- gate_outputs = gate_outputs.contiguous()
- # (T_out, B, n_mel_channels) -> (B, T_out, n_mel_channels)
- mel_outputs = torch.stack(mel_outputs).transpose(0, 1).contiguous()
- # decouple frames per step
- mel_outputs = mel_outputs.view(
- mel_outputs.size(0), -1, self.n_mel_channels)
- # (B, T_out, n_mel_channels) -> (B, n_mel_channels, T_out)
- mel_outputs = mel_outputs.transpose(1, 2)
-
- return mel_outputs, gate_outputs, alignments
-
- def decode(self, decoder_input):
- """ Decoder step using stored states, attention and memory
- PARAMS
- ------
- decoder_input: previous mel output
-
- RETURNS
- -------
- mel_output:
- gate_output: gate output energies
- attention_weights:
- """
- cell_input = torch.cat((decoder_input, self.attention_context), -1)
- self.attention_hidden, self.attention_cell = self.attention_rnn(
- cell_input, (self.attention_hidden, self.attention_cell))
- self.attention_hidden = F.dropout(
- self.attention_hidden, self.p_attention_dropout, self.training)
-
- attention_weights_cat = torch.cat(
- (self.attention_weights.unsqueeze(1),
- self.attention_weights_cum.unsqueeze(1)), dim=1)
- self.attention_context, self.attention_weights = self.attention_layer(
- self.attention_hidden, self.memory, self.processed_memory,
- attention_weights_cat, self.mask)
-
- self.attention_weights_cum += self.attention_weights
- decoder_input = torch.cat(
- (self.attention_hidden, self.attention_context), -1)
- if self.obs_and_lat is not None:
- decoder_input = torch.cat((decoder_input, self.obs_and_lat), -1)
- self.decoder_hidden, self.decoder_cell = self.decoder_rnn(
- decoder_input, (self.decoder_hidden, self.decoder_cell))
- self.decoder_hidden = F.dropout(
- self.decoder_hidden, self.p_decoder_dropout, self.training)
-
- decoder_hidden_attention_context = torch.cat(
- (self.decoder_hidden, self.attention_context), dim=1)
- if self.obs_and_lat is not None:
- decoder_hidden_attention_context = torch.cat(
- (decoder_hidden_attention_context, self.obs_and_lat), dim=1)
- decoder_output = self.linear_projection(
- decoder_hidden_attention_context)
-
- gate_prediction = self.gate_layer(decoder_hidden_attention_context)
- return decoder_output, gate_prediction, self.attention_weights
-
- def forward(self, memory, obs_and_lat, decoder_inputs, memory_lengths):
- """ Decoder forward pass for training
- PARAMS
- ------
- memory: Encoder outputs
- obs_and_lat: Observed and latent attribute embeddings
- decoder_inputs: Decoder inputs for teacher forcing. i.e. mel-specs
- memory_lengths: Encoder output lengths for attention masking.
-
- RETURNS
- -------
- mel_outputs: mel outputs from the decoder
- gate_outputs: gate outputs from the decoder
- alignments: sequence of attention weights from the decoder
- """
-
- decoder_input = self.get_go_frame(memory).unsqueeze(0)
- decoder_inputs = self.parse_decoder_inputs(decoder_inputs)
- decoder_inputs = torch.cat((decoder_input, decoder_inputs), dim=0)
- decoder_inputs = self.prenet(decoder_inputs)
-
- self.initialize_decoder_states(
- memory, obs_and_lat, mask=~get_mask_from_lengths(memory_lengths))
-
- mel_outputs, gate_outputs, alignments = [], [], []
- while len(mel_outputs) < decoder_inputs.size(0) - 1:
- decoder_input = decoder_inputs[len(mel_outputs)]
- mel_output, gate_output, attention_weights = self.decode(
- decoder_input)
- mel_outputs += [mel_output.squeeze(1)]
- gate_outputs += [gate_output.squeeze()]
- alignments += [attention_weights]
-
- mel_outputs, gate_outputs, alignments = self.parse_decoder_outputs(
- mel_outputs, gate_outputs, alignments)
-
- return mel_outputs, gate_outputs, alignments
-
- def inference(self, memory, obs_and_lat, ret_has_eos=False):
- """ Decoder inference
- PARAMS
- ------
- memory: Encoder outputs
- obs_and_lat: Observed and latent attribute embeddings
-
- RETURNS
- -------
- mel_outputs: mel outputs from the decoder
- gate_outputs: gate outputs from the decoder
- alignments: sequence of attention weights from the decoder
- """
- decoder_input = self.get_go_frame(memory)
-
- self.initialize_decoder_states(memory, obs_and_lat, mask=None)
-
- mel_outputs, gate_outputs, alignments = [], [], []
- has_eos = False
- while True:
- decoder_input = self.prenet(decoder_input)
- mel_output, gate_output, alignment = self.decode(decoder_input)
-
- mel_outputs += [mel_output.squeeze(1)]
- gate_outputs += [gate_output]
- alignments += [alignment]
-
- if torch.sigmoid(gate_output.data) > self.gate_threshold:
- has_eos = True
- break
- elif len(mel_outputs) == self.max_decoder_steps:
- # print("Warning! Reached max decoder steps")
- break
-
- decoder_input = mel_output
-
- mel_outputs, gate_outputs, alignments = self.parse_decoder_outputs(
- mel_outputs, gate_outputs, alignments)
-
- if ret_has_eos:
- return mel_outputs, gate_outputs, alignments, has_eos
- else:
- return mel_outputs, gate_outputs, alignments
-
-
-class Tacotron2(nn.Module):
- def __init__(self, hparams):
- super(Tacotron2, self).__init__()
- self.mask_padding = hparams.mask_padding
- self.fp16_run = hparams.fp16_run
- self.n_mel_channels = hparams.n_mel_channels
- self.n_frames_per_step = hparams.n_frames_per_step
-
- # initialize text encoder embedding
- self.embedding = nn.Embedding(
- hparams.n_symbols, hparams.symbols_embedding_dim)
- std = sqrt(2.0 / (hparams.n_symbols + hparams.symbols_embedding_dim))
- val = sqrt(3.0) * std # uniform bounds for std
- self.embedding.weight.data.uniform_(-val, val)
-
- # initialize observed attribute embedding
- self.obs_embedding = None
- if hparams.obs_dim > 0:
- self.obs_embedding = nn.Embedding(
- hparams.obs_n_class, hparams.obs_dim)
- std = sqrt(2.0 / (hparams.obs_n_class + hparams.obs_dim))
- val = sqrt(3.0) * std # uniform bounds for std
- self.obs_embedding.weight.data.uniform_(-val, val)
-
- self.encoder = Encoder(hparams)
- self.decoder = Decoder(hparams)
- self.postnet = Postnet(hparams)
-
- self.lat_encoder = None
- if hparams.lat_dim > 0:
- self.lat_encoder = AudioEncoder(hparams)
-
- def parse_batch(self, batch):
- (text_padded, input_lengths, obs_labels,
- mel_padded, gate_padded, output_lengths) = batch
- text_padded = to_gpu(text_padded).long()
- input_lengths = to_gpu(input_lengths).long()
- obs_labels = to_gpu(obs_labels).long()
- max_len = torch.max(input_lengths.data).item()
- mel_padded = to_gpu(mel_padded).float()
- gate_padded = to_gpu(gate_padded).float()
- output_lengths = to_gpu(output_lengths).long()
-
- return (
- (text_padded, input_lengths, obs_labels,
- mel_padded, max_len, output_lengths),
- (mel_padded, gate_padded))
-
- def parse_output(self, outputs, output_lengths=None):
- if self.mask_padding and output_lengths is not None:
- mask = ~get_mask_from_lengths(output_lengths)
- mask = mask.expand(self.n_mel_channels, mask.size(0), mask.size(1))
- mask = mask.permute(1, 0, 2)
-
- outputs[0].data.masked_fill_(mask, 0.0)
- outputs[1].data.masked_fill_(mask, 0.0)
- outputs[2].data.masked_fill_(mask[:, 0, :], 1e3) # gate energies
-
- return outputs
-
- def forward(self, inputs):
- (text_inputs, text_lengths, obs_labels,
- mels, max_len, output_lengths) = inputs
- text_lengths, output_lengths = text_lengths.data, output_lengths.data
-
- embedded_inputs = self.embedding(text_inputs).transpose(1, 2)
-
- encoder_outputs = self.encoder(embedded_inputs, text_lengths)
-
- obs = None
- if self.obs_embedding is not None:
- obs = self.obs_embedding(obs_labels)
-
- lat, lat_mu, lat_logvar = None, None, None
- if self.lat_encoder is not None:
- (lat, lat_mu, lat_logvar) = self.lat_encoder(mels, output_lengths)
-
- obs_and_lat = [x for x in [obs, lat] if x is not None]
- if bool(obs_and_lat):
- obs_and_lat = torch.cat(obs_and_lat, dim=-1)
- else:
- obs_and_lat = None
-
- mel_outputs, gate_outputs, alignments = self.decoder(
- encoder_outputs, obs_and_lat, mels, memory_lengths=text_lengths)
-
- mel_outputs_postnet = self.postnet(mel_outputs)
- mel_outputs_postnet = mel_outputs + mel_outputs_postnet
-
- return self.parse_output(
- [mel_outputs, mel_outputs_postnet, gate_outputs, alignments,
- lat_mu, lat_logvar],
- output_lengths)
-
- def inference(self, inputs, obs_labels=None, lat=None, ret_has_eos=False):
- embedded_inputs = self.embedding(inputs).transpose(1, 2)
- encoder_outputs = self.encoder.inference(embedded_inputs)
-
- if obs_labels is None:
- obs_labels = torch.LongTensor(len(inputs))
- obs_labels = obs_labels.to(inputs.device).zero_()
-
- obs = None
- if self.obs_embedding is not None:
- obs = self.obs_embedding(obs_labels)
-
- if self.lat_encoder is not None:
- if lat is None:
- lat = torch.FloatTensor(len(inputs), self.lat_encoder.lat_dim)
- lat = lat.to(inputs.device).zero_().type(encoder_outputs.type())
-
- obs_and_lat = [x for x in [obs, lat] if x is not None]
- if bool(obs_and_lat):
- obs_and_lat = torch.cat(obs_and_lat, dim=-1)
- else:
- obs_and_lat = None
-
- mel_outputs, gate_outputs, alignments, has_eos = self.decoder.inference(
- encoder_outputs, obs_and_lat, ret_has_eos=True)
-
- mel_outputs_postnet = self.postnet(mel_outputs)
- mel_outputs_postnet = mel_outputs + mel_outputs_postnet
-
- outputs = self.parse_output(
- [mel_outputs, mel_outputs_postnet, gate_outputs, alignments])
-
- if ret_has_eos:
- return outputs + [has_eos]
- else:
- return outputs
diff --git a/spaces/Intel/NeuralChat-ICX-INT4/fastchat/eval/README.md b/spaces/Intel/NeuralChat-ICX-INT4/fastchat/eval/README.md
deleted file mode 100644
index 403c9acf2570647b1a1a887967cd639289605d3d..0000000000000000000000000000000000000000
--- a/spaces/Intel/NeuralChat-ICX-INT4/fastchat/eval/README.md
+++ /dev/null
@@ -1,187 +0,0 @@
-# Evaluations
-
-This directory contains end-to-end pipelines for AI-enhanced evaluation. We will introduce the evaluation pipeline and the data format in this document.
-
-## Generate Answers
-
-### ChatGPT (gpt-3.5-turbo)
-
-Make sure you have setup the OpenAI API Key in your environment. Then run:
-
-```bash
-python qa_baseline_gpt35.py --question table/question.jsonl --output table/answer/answer_gpt35.jsonl
-```
-
-### Bard
-
-Unfortunately, Bard has not release its public APIs till now. You may have to enter the anwsers manually. Or you could find a third-party project that interfaces with Bard.
-
-### Vicuna and others
-
-To generate answers with Vicuna or other models, specify path to the model checkpoint, a desired model ID and run:
-```bash
-python get_model_answer.py --model-id [MODEL-ID] --model-path /model/path --question-file table/question.jsonl --answer-file table/answer/answer.jsonl --num-gpus [NUM-GPUS]
-```
-Then the answers to the questions will be saved in `table/answer/answer.jsonl`.
-Note: we assume the model can be loaded with a single GPU.
-
-## Evaluate Answers Automatically
-
-### Generete Reviews with GPT-4
-
-Note: Below script requires access to GPT-4 API. If you only have access to GPT-4 on web interface, you can evaluate the answers by manually formatting the prompt. See more details in the **Reviewers** and **Prompts** sections in **Data Format**.
-It is critical to follow the prompt templates; otherwise GPT-4 may not give fair reviews. `table/review/*.jsonl` are some review examples generated by GPT-4 or you can view them on our eval [webpage](https://vicuna.lmsys.org/eval/).
-
-To use the script for generating reviews with GPT-4, you need to `export` your OpenAI API key in environment variable. Then run:
-```bash
-python eval_gpt_review.py -q table/question.jsonl -a /path/to/answer_1.jsonl /path/to/answer_2.jsonl -p table/prompt.jsonl -r table/reviewer.jsonl -o /path/to/review_output.jsonl
-```
-The GPT-4 reviews will be saved in `/path/to/review_output.jsonl`. Note: we implement some simple parsing code to extract the score pairs from GPT-4's reviews. However, you need to double check whether the parsed score pair are correct. Sometime the parsing logic may fail if GPT-4 doesn't give a structured answer.
-
-## Visualize Results
-
-You can generate the data for the webpage by running:
-
-```bash
-python eval/generate_webpage_data_from_table.py
-```
-
-Then you can serve a static website in `webpage` to see the results.
-
-## Data Format
-
-If you want to have a deeper understanding of our evaluation pipeline or want to contribute to the evaluation process, you need to learn the data format we used for evaluation.
-
-Our evaluation data are encoded with [JSON Lines](https://jsonlines.org/).
-
-### Random ID Generation
-
-We use the `shortuuid` Python library for generating short random UUIDs.
-
-```python
-import shortuuid
-shortuuid.uuid() -> str
-```
-
-### Models
-
-`model.jsonl` contains model information we used for generating anwsers.
-
-Each row contains a record of a model with the following field:
-
-* `model_id` (str): A unique ID for a model. Models with different IDs is supposed to have different performance. This ID is generated by `{model_name}:{model_version}`.
-* `model_name` (str): The name of a model. This is not unique, because a model could be trained and updated continuously, but it is still considered as the same model with different versions.
-* `model_version` (str): The version of a model.
-* `model_metadata` (Any): Any metadata of a model (descriptions etc). This is optional.
-
-For example:
-
-```json
-{
- "model_id": "vicuna-13b:v1",
- "model_name": "vicuna-13b",
- "model_version": "v1",
- "model_metadata": "learning rate 1e-5, 3 epochs, 13b"
-}
-```
-
-### Prompts
-
-We store prompts in `prompt.jsonl`. Each row contains a record of a prompt with the following field:
-
-* `prompt_id` (int): A unique integer ID for a prompt. Prompts with different IDs are supposed to have different purpose.
-* `system_prompt` (str): The system prompt given to a model. This is the prompt that the model sees first.
-* `prompt_template` (str): The prompt body. This is the user prompt that the model sees after the system prompt. It is a Python f-string template, so that we can fill in the inputs later.
-* `defaults` (dict): A dictionary of default values for the prompt template. It can be empty.
-* `description` (str): A description of the functionality of the prompt.
-
-For example:
-
-```json
-{
- "prompt_id": 1,
- "system_prompt": "You are a helpful assistant.",
- "prompt_template": "[Question]\n{question}\n\n[Assistant 1]\n{answer_1}\n\n[End of Assistant 1]\n\n[Assistant 2]\n{answer_2}\n\n[End of Assistant 2]\n\n[System]\n{prompt}\n\n",
- "defaults": {"prompt": "Which assistant is more helpful?"},
- "description": "Compare two assistants' answers to a question."
-}
-```
-
-### Reviewers
-
-`reviewer.jsonl` contains reviewer information we used for reviewing answers generated by different models. Each row contains a record of a reviewer with the following field:
-
-* `reviewer_id` (str): A unique ID for a reviewer. Reviewers with different IDs is supposed to have different reviewing performance.
-* `prompt_id` (str): The ID of the prompt given to the reviewer (e.g., an AI assistant). Different prompts could result in different reviewing performance.
-* `metadata` (dict): Metadata of a reviewer about its configurations.
-* `description` (str): A description of the reviewer.
-* `category` (str): The category that the reviewer belongs to.
-
-For example:
-
-```json
-{
- "reviewer_id": "gpt-4-0328-default",
- "prompt_id": 1,
- "temperature": 0.2,
- "max_tokens": 8192,
- "description": "GPT-4 for general questions.",
- "category": "general"
-}
-```
-
-### Questions
-
-`question.jsonl` contains questions we used for evaluation. Each row contains a record of a question with the following field:
-
-* `question_id` (int): A unique integer for a question. Questions with different IDs is supposed to be different.
-* `text` (str): The question text.
-* `category` (str): The category of the question. Questions with the same category are supposed to be similar or originate from the same source.
-
-### Answers
-
-`answer/xxx.jsonl` contains answers generated by different models. Each row contains a record of an answer with the following field:
-
-* `answer_id` (str): A unique UUID for an answer. Answers with different IDs is supposed to be different.
-* `question_id` (int): The ID of the question the answer is generated for.
-* `model_id` (str): The ID of the model the answer is generated by.
-* `text` (str): The answer text.
-* `metadata` (dict): Any metadata of the answer.
-
-Example:
-
-```json
-{
- "answer_id": "[short uuid]",
- "question_id": 1,
- "model_id": "vicuna-13b:v1",
- "text": "Here are five tips...",
- "metadata": {}
-}
-```
-
-### Reviews
-
-`review/xxx.jsonl` contains reviews given by reviewers, comparing peformance between a pair of models. Each row contains a record of a review with the following field:
-
-* `review_id` (str): A unique UUID for a review. Reviews with different IDs is supposed to be different.
-* `question_id` (int): The ID of the question the review is given for.
-* `answer1_id` (str): The ID of the first answer.
-* `answer2_id` (str): The ID of the second answer.
-* `text` (str): The review text.
-* `score` (list): A list of scores given by the reviewer. The first score is for the first answer, and the second score is for the second answer.
-* `reviewer_id` (str): The ID of the reviewer.
-* `metadata` (dict): Any metadata of the review.
-
-```json
-{
- "review_id": "[short uuid]",
- "question_id": 1,
- "answer1_id": "[answer1_id]",
- "answer2_id": "[answer2_id]",
- "text": "Assistant 2 is better...",
- "score": [9.0, 7.5],
- "reviewer_id": "gpt-4-0328-default",
- "metadata": {}
-}
-```
diff --git a/spaces/JUNGU/VToonify/vtoonify/model/encoder/align_all_parallel.py b/spaces/JUNGU/VToonify/vtoonify/model/encoder/align_all_parallel.py
deleted file mode 100644
index 05b520cd6590dc02ee533d3f0d69e6a364447d9f..0000000000000000000000000000000000000000
--- a/spaces/JUNGU/VToonify/vtoonify/model/encoder/align_all_parallel.py
+++ /dev/null
@@ -1,217 +0,0 @@
-"""
-brief: face alignment with FFHQ method (https://github.com/NVlabs/ffhq-dataset)
-author: lzhbrian (https://lzhbrian.me)
-date: 2020.1.5
-note: code is heavily borrowed from
- https://github.com/NVlabs/ffhq-dataset
- http://dlib.net/face_landmark_detection.py.html
-
-requirements:
- apt install cmake
- conda install Pillow numpy scipy
- pip install dlib
- # download face landmark model from:
- # http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
-"""
-from argparse import ArgumentParser
-import time
-import numpy as np
-import PIL
-import PIL.Image
-import os
-import scipy
-import scipy.ndimage
-import dlib
-import multiprocessing as mp
-import math
-
-#from configs.paths_config import model_paths
-SHAPE_PREDICTOR_PATH = 'shape_predictor_68_face_landmarks.dat'#model_paths["shape_predictor"]
-
-
-def get_landmark(filepath, predictor):
- """get landmark with dlib
- :return: np.array shape=(68, 2)
- """
- detector = dlib.get_frontal_face_detector()
- if type(filepath) == str:
- img = dlib.load_rgb_image(filepath)
- else:
- img = filepath
- dets = detector(img, 1)
-
- if len(dets) == 0:
- print('Error: no face detected!')
- return None
-
- shape = None
- for k, d in enumerate(dets):
- shape = predictor(img, d)
-
- if shape is None:
- print('Error: No face detected! If you are sure there are faces in your input, you may rerun the code several times until the face is detected. Sometimes the detector is unstable.')
- t = list(shape.parts())
- a = []
- for tt in t:
- a.append([tt.x, tt.y])
- lm = np.array(a)
- return lm
-
-
-def align_face(filepath, predictor):
- """
- :param filepath: str
- :return: PIL Image
- """
-
- lm = get_landmark(filepath, predictor)
- if lm is None:
- return None
-
- lm_chin = lm[0: 17] # left-right
- lm_eyebrow_left = lm[17: 22] # left-right
- lm_eyebrow_right = lm[22: 27] # left-right
- lm_nose = lm[27: 31] # top-down
- lm_nostrils = lm[31: 36] # top-down
- lm_eye_left = lm[36: 42] # left-clockwise
- lm_eye_right = lm[42: 48] # left-clockwise
- lm_mouth_outer = lm[48: 60] # left-clockwise
- lm_mouth_inner = lm[60: 68] # left-clockwise
-
- # Calculate auxiliary vectors.
- eye_left = np.mean(lm_eye_left, axis=0)
- eye_right = np.mean(lm_eye_right, axis=0)
- eye_avg = (eye_left + eye_right) * 0.5
- eye_to_eye = eye_right - eye_left
- mouth_left = lm_mouth_outer[0]
- mouth_right = lm_mouth_outer[6]
- mouth_avg = (mouth_left + mouth_right) * 0.5
- eye_to_mouth = mouth_avg - eye_avg
-
- # Choose oriented crop rectangle.
- x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1]
- x /= np.hypot(*x)
- x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8)
- y = np.flipud(x) * [-1, 1]
- c = eye_avg + eye_to_mouth * 0.1
- quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y])
- qsize = np.hypot(*x) * 2
-
- # read image
- if type(filepath) == str:
- img = PIL.Image.open(filepath)
- else:
- img = PIL.Image.fromarray(filepath)
-
- output_size = 256
- transform_size = 256
- enable_padding = True
-
- # Shrink.
- shrink = int(np.floor(qsize / output_size * 0.5))
- if shrink > 1:
- rsize = (int(np.rint(float(img.size[0]) / shrink)), int(np.rint(float(img.size[1]) / shrink)))
- img = img.resize(rsize, PIL.Image.ANTIALIAS)
- quad /= shrink
- qsize /= shrink
-
- # Crop.
- border = max(int(np.rint(qsize * 0.1)), 3)
- crop = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
- int(np.ceil(max(quad[:, 1]))))
- crop = (max(crop[0] - border, 0), max(crop[1] - border, 0), min(crop[2] + border, img.size[0]),
- min(crop[3] + border, img.size[1]))
- if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]:
- img = img.crop(crop)
- quad -= crop[0:2]
-
- # Pad.
- pad = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
- int(np.ceil(max(quad[:, 1]))))
- pad = (max(-pad[0] + border, 0), max(-pad[1] + border, 0), max(pad[2] - img.size[0] + border, 0),
- max(pad[3] - img.size[1] + border, 0))
- if enable_padding and max(pad) > border - 4:
- pad = np.maximum(pad, int(np.rint(qsize * 0.3)))
- img = np.pad(np.float32(img), ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect')
- h, w, _ = img.shape
- y, x, _ = np.ogrid[:h, :w, :1]
- mask = np.maximum(1.0 - np.minimum(np.float32(x) / pad[0], np.float32(w - 1 - x) / pad[2]),
- 1.0 - np.minimum(np.float32(y) / pad[1], np.float32(h - 1 - y) / pad[3]))
- blur = qsize * 0.02
- img += (scipy.ndimage.gaussian_filter(img, [blur, blur, 0]) - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0)
- img += (np.median(img, axis=(0, 1)) - img) * np.clip(mask, 0.0, 1.0)
- img = PIL.Image.fromarray(np.uint8(np.clip(np.rint(img), 0, 255)), 'RGB')
- quad += pad[:2]
-
- # Transform.
- img = img.transform((transform_size, transform_size), PIL.Image.QUAD, (quad + 0.5).flatten(), PIL.Image.BILINEAR)
- if output_size < transform_size:
- img = img.resize((output_size, output_size), PIL.Image.ANTIALIAS)
-
- # Save aligned image.
- return img
-
-
-def chunks(lst, n):
- """Yield successive n-sized chunks from lst."""
- for i in range(0, len(lst), n):
- yield lst[i:i + n]
-
-
-def extract_on_paths(file_paths):
- predictor = dlib.shape_predictor(SHAPE_PREDICTOR_PATH)
- pid = mp.current_process().name
- print('\t{} is starting to extract on #{} images'.format(pid, len(file_paths)))
- tot_count = len(file_paths)
- count = 0
- for file_path, res_path in file_paths:
- count += 1
- if count % 100 == 0:
- print('{} done with {}/{}'.format(pid, count, tot_count))
- try:
- res = align_face(file_path, predictor)
- res = res.convert('RGB')
- os.makedirs(os.path.dirname(res_path), exist_ok=True)
- res.save(res_path)
- except Exception:
- continue
- print('\tDone!')
-
-
-def parse_args():
- parser = ArgumentParser(add_help=False)
- parser.add_argument('--num_threads', type=int, default=1)
- parser.add_argument('--root_path', type=str, default='')
- args = parser.parse_args()
- return args
-
-
-def run(args):
- root_path = args.root_path
- out_crops_path = root_path + '_crops'
- if not os.path.exists(out_crops_path):
- os.makedirs(out_crops_path, exist_ok=True)
-
- file_paths = []
- for root, dirs, files in os.walk(root_path):
- for file in files:
- file_path = os.path.join(root, file)
- fname = os.path.join(out_crops_path, os.path.relpath(file_path, root_path))
- res_path = '{}.jpg'.format(os.path.splitext(fname)[0])
- if os.path.splitext(file_path)[1] == '.txt' or os.path.exists(res_path):
- continue
- file_paths.append((file_path, res_path))
-
- file_chunks = list(chunks(file_paths, int(math.ceil(len(file_paths) / args.num_threads))))
- print(len(file_chunks))
- pool = mp.Pool(args.num_threads)
- print('Running on {} paths\nHere we goooo'.format(len(file_paths)))
- tic = time.time()
- pool.map(extract_on_paths, file_chunks)
- toc = time.time()
- print('Mischief managed in {}s'.format(toc - tic))
-
-
-if __name__ == '__main__':
- args = parse_args()
- run(args)
diff --git a/spaces/Jamkonams/AutoGPT/run_continuous.sh b/spaces/Jamkonams/AutoGPT/run_continuous.sh
deleted file mode 100644
index 1f4436c88503172c0578b15a8447ed8268502578..0000000000000000000000000000000000000000
--- a/spaces/Jamkonams/AutoGPT/run_continuous.sh
+++ /dev/null
@@ -1,3 +0,0 @@
-#!/bin/bash
-
-./run.sh --continuous $@
diff --git a/spaces/JohnSmith9982/ChuanhuChatGPT_Beta/modules/models/base_model.py b/spaces/JohnSmith9982/ChuanhuChatGPT_Beta/modules/models/base_model.py
deleted file mode 100644
index fa94579d725dbf9d739d58fc17b35bc2248c7fcd..0000000000000000000000000000000000000000
--- a/spaces/JohnSmith9982/ChuanhuChatGPT_Beta/modules/models/base_model.py
+++ /dev/null
@@ -1,787 +0,0 @@
-from __future__ import annotations
-from typing import TYPE_CHECKING, List
-
-import logging
-import json
-import commentjson as cjson
-import os
-import sys
-import requests
-import urllib3
-import traceback
-import pathlib
-
-from tqdm import tqdm
-import colorama
-from duckduckgo_search import DDGS
-from itertools import islice
-import asyncio
-import aiohttp
-from enum import Enum
-
-from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
-from langchain.callbacks.manager import BaseCallbackManager
-
-from typing import Any, Dict, List, Optional, Union
-
-from langchain.callbacks.base import BaseCallbackHandler
-from langchain.input import print_text
-from langchain.schema import AgentAction, AgentFinish, LLMResult
-from threading import Thread, Condition
-from collections import deque
-from langchain.chat_models.base import BaseChatModel
-from langchain.schema import HumanMessage, AIMessage, SystemMessage, BaseMessage
-
-from ..presets import *
-from ..index_func import *
-from ..utils import *
-from .. import shared
-from ..config import retrieve_proxy
-
-
-class CallbackToIterator:
- def __init__(self):
- self.queue = deque()
- self.cond = Condition()
- self.finished = False
-
- def callback(self, result):
- with self.cond:
- self.queue.append(result)
- self.cond.notify() # Wake up the generator.
-
- def __iter__(self):
- return self
-
- def __next__(self):
- with self.cond:
- # Wait for a value to be added to the queue.
- while not self.queue and not self.finished:
- self.cond.wait()
- if not self.queue:
- raise StopIteration()
- return self.queue.popleft()
-
- def finish(self):
- with self.cond:
- self.finished = True
- self.cond.notify() # Wake up the generator if it's waiting.
-
-
-def get_action_description(text):
- match = re.search('```(.*?)```', text, re.S)
- json_text = match.group(1)
- # 把json转化为python字典
- json_dict = json.loads(json_text)
- # 提取'action'和'action_input'的值
- action_name = json_dict['action']
- action_input = json_dict['action_input']
- if action_name != "Final Answer":
- return f'
{action_name}: {action_input}\n\n
'
- else:
- return ""
-
-
-class ChuanhuCallbackHandler(BaseCallbackHandler):
-
- def __init__(self, callback) -> None:
- """Initialize callback handler."""
- self.callback = callback
-
- def on_agent_action(
- self, action: AgentAction, color: Optional[str] = None, **kwargs: Any
- ) -> Any:
- self.callback(get_action_description(action.log))
-
- def on_tool_end(
- self,
- output: str,
- color: Optional[str] = None,
- observation_prefix: Optional[str] = None,
- llm_prefix: Optional[str] = None,
- **kwargs: Any,
- ) -> None:
- """If not the final action, print out observation."""
- # if observation_prefix is not None:
- # self.callback(f"\n\n{observation_prefix}")
- # self.callback(output)
- # if llm_prefix is not None:
- # self.callback(f"\n\n{llm_prefix}")
- if observation_prefix is not None:
- logging.info(observation_prefix)
- self.callback(output)
- if llm_prefix is not None:
- logging.info(llm_prefix)
-
- def on_agent_finish(
- self, finish: AgentFinish, color: Optional[str] = None, **kwargs: Any
- ) -> None:
- # self.callback(f"{finish.log}\n\n")
- logging.info(finish.log)
-
- def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
- """Run on new LLM token. Only available when streaming is enabled."""
- self.callback(token)
-
- def on_chat_model_start(self, serialized: Dict[str, Any], messages: List[List[BaseMessage]], **kwargs: Any) -> Any:
- """Run when a chat model starts running."""
- pass
-
-
-class ModelType(Enum):
- Unknown = -1
- OpenAI = 0
- ChatGLM = 1
- LLaMA = 2
- XMChat = 3
- StableLM = 4
- MOSS = 5
- YuanAI = 6
- Minimax = 7
- ChuanhuAgent = 8
- GooglePaLM = 9
- LangchainChat = 10
- Midjourney = 11
-
- @classmethod
- def get_type(cls, model_name: str):
- model_type = None
- model_name_lower = model_name.lower()
- if "gpt" in model_name_lower:
- model_type = ModelType.OpenAI
- elif "chatglm" in model_name_lower:
- model_type = ModelType.ChatGLM
- elif "llama" in model_name_lower or "alpaca" in model_name_lower:
- model_type = ModelType.LLaMA
- elif "xmchat" in model_name_lower:
- model_type = ModelType.XMChat
- elif "stablelm" in model_name_lower:
- model_type = ModelType.StableLM
- elif "moss" in model_name_lower:
- model_type = ModelType.MOSS
- elif "yuanai" in model_name_lower:
- model_type = ModelType.YuanAI
- elif "minimax" in model_name_lower:
- model_type = ModelType.Minimax
- elif "川虎助理" in model_name_lower:
- model_type = ModelType.ChuanhuAgent
- elif "palm" in model_name_lower:
- model_type = ModelType.GooglePaLM
- elif "midjourney" in model_name_lower:
- model_type = ModelType.Midjourney
- elif "azure" in model_name_lower or "api" in model_name_lower:
- model_type = ModelType.LangchainChat
- else:
- model_type = ModelType.Unknown
- return model_type
-
-
-class BaseLLMModel:
- def __init__(
- self,
- model_name,
- system_prompt=INITIAL_SYSTEM_PROMPT,
- temperature=1.0,
- top_p=1.0,
- n_choices=1,
- stop=None,
- max_generation_token=None,
- presence_penalty=0,
- frequency_penalty=0,
- logit_bias=None,
- user="",
- ) -> None:
- self.history = []
- self.all_token_counts = []
- self.model_name = model_name
- self.model_type = ModelType.get_type(model_name)
- try:
- self.token_upper_limit = MODEL_TOKEN_LIMIT[model_name]
- except KeyError:
- self.token_upper_limit = DEFAULT_TOKEN_LIMIT
- self.interrupted = False
- self.system_prompt = system_prompt
- self.api_key = None
- self.need_api_key = False
- self.single_turn = False
-
- self.temperature = temperature
- self.top_p = top_p
- self.n_choices = n_choices
- self.stop_sequence = stop
- self.max_generation_token = None
- self.presence_penalty = presence_penalty
- self.frequency_penalty = frequency_penalty
- self.logit_bias = logit_bias
- self.user_identifier = user
-
- def get_answer_stream_iter(self):
- """stream predict, need to be implemented
- conversations are stored in self.history, with the most recent question, in OpenAI format
- should return a generator, each time give the next word (str) in the answer
- """
- logging.warning(
- "stream predict not implemented, using at once predict instead")
- response, _ = self.get_answer_at_once()
- yield response
-
- def get_answer_at_once(self):
- """predict at once, need to be implemented
- conversations are stored in self.history, with the most recent question, in OpenAI format
- Should return:
- the answer (str)
- total token count (int)
- """
- logging.warning(
- "at once predict not implemented, using stream predict instead")
- response_iter = self.get_answer_stream_iter()
- count = 0
- for response in response_iter:
- count += 1
- return response, sum(self.all_token_counts) + count
-
- def billing_info(self):
- """get billing infomation, inplement if needed"""
- logging.warning("billing info not implemented, using default")
- return BILLING_NOT_APPLICABLE_MSG
-
- def count_token(self, user_input):
- """get token count from input, implement if needed"""
- # logging.warning("token count not implemented, using default")
- return len(user_input)
-
- def stream_next_chatbot(self, inputs, chatbot, fake_input=None, display_append=""):
- def get_return_value():
- return chatbot, status_text
-
- status_text = i18n("开始实时传输回答……")
- if fake_input:
- chatbot.append((fake_input, ""))
- else:
- chatbot.append((inputs, ""))
-
- user_token_count = self.count_token(inputs)
- self.all_token_counts.append(user_token_count)
- logging.debug(f"输入token计数: {user_token_count}")
-
- stream_iter = self.get_answer_stream_iter()
-
- if display_append:
- display_append = '\n\n' + display_append
- partial_text = ""
- for partial_text in stream_iter:
- chatbot[-1] = (chatbot[-1][0], partial_text + display_append)
- self.all_token_counts[-1] += 1
- status_text = self.token_message()
- yield get_return_value()
- if self.interrupted:
- self.recover()
- break
- self.history.append(construct_assistant(partial_text))
-
- def next_chatbot_at_once(self, inputs, chatbot, fake_input=None, display_append=""):
- if fake_input:
- chatbot.append((fake_input, ""))
- else:
- chatbot.append((inputs, ""))
- if fake_input is not None:
- user_token_count = self.count_token(fake_input)
- else:
- user_token_count = self.count_token(inputs)
- self.all_token_counts.append(user_token_count)
- ai_reply, total_token_count = self.get_answer_at_once()
- self.history.append(construct_assistant(ai_reply))
- if fake_input is not None:
- self.history[-2] = construct_user(fake_input)
- chatbot[-1] = (chatbot[-1][0], ai_reply + display_append)
- if fake_input is not None:
- self.all_token_counts[-1] += count_token(
- construct_assistant(ai_reply))
- else:
- self.all_token_counts[-1] = total_token_count - \
- sum(self.all_token_counts)
- status_text = self.token_message()
- return chatbot, status_text
-
- def handle_file_upload(self, files, chatbot, language):
- """if the model accepts multi modal input, implement this function"""
- status = gr.Markdown.update()
- if files:
- index = construct_index(self.api_key, file_src=files)
- status = i18n("索引构建完成")
- return gr.Files.update(), chatbot, status
-
- def summarize_index(self, files, chatbot, language):
- status = gr.Markdown.update()
- if files:
- index = construct_index(self.api_key, file_src=files)
- status = i18n("总结完成")
- logging.info(i18n("生成内容总结中……"))
- os.environ["OPENAI_API_KEY"] = self.api_key
- from langchain.chains.summarize import load_summarize_chain
- from langchain.prompts import PromptTemplate
- from langchain.chat_models import ChatOpenAI
- from langchain.callbacks import StdOutCallbackHandler
- prompt_template = "Write a concise summary of the following:\n\n{text}\n\nCONCISE SUMMARY IN " + language + ":"
- PROMPT = PromptTemplate(
- template=prompt_template, input_variables=["text"])
- llm = ChatOpenAI()
- chain = load_summarize_chain(
- llm, chain_type="map_reduce", return_intermediate_steps=True, map_prompt=PROMPT, combine_prompt=PROMPT)
- summary = chain({"input_documents": list(index.docstore.__dict__[
- "_dict"].values())}, return_only_outputs=True)["output_text"]
- print(i18n("总结") + f": {summary}")
- chatbot.append([i18n("上传了")+str(len(files))+"个文件", summary])
- return chatbot, status
-
- def prepare_inputs(self, real_inputs, use_websearch, files, reply_language, chatbot):
- fake_inputs = None
- display_append = []
- limited_context = False
- fake_inputs = real_inputs
- if files:
- from langchain.embeddings.huggingface import HuggingFaceEmbeddings
- from langchain.vectorstores.base import VectorStoreRetriever
- limited_context = True
- msg = "加载索引中……"
- logging.info(msg)
- index = construct_index(self.api_key, file_src=files)
- assert index is not None, "获取索引失败"
- msg = "索引获取成功,生成回答中……"
- logging.info(msg)
- with retrieve_proxy():
- retriever = VectorStoreRetriever(vectorstore=index, search_type="similarity_score_threshold", search_kwargs={
- "k": 6, "score_threshold": 0.5})
- relevant_documents = retriever.get_relevant_documents(
- real_inputs)
- reference_results = [[d.page_content.strip("�"), os.path.basename(
- d.metadata["source"])] for d in relevant_documents]
- reference_results = add_source_numbers(reference_results)
- display_append = add_details(reference_results)
- display_append = "\n\n" + "".join(display_append)
- real_inputs = (
- replace_today(PROMPT_TEMPLATE)
- .replace("{query_str}", real_inputs)
- .replace("{context_str}", "\n\n".join(reference_results))
- .replace("{reply_language}", reply_language)
- )
- elif use_websearch:
- search_results = []
- with DDGS() as ddgs:
- ddgs_gen = ddgs.text(real_inputs, backend="lite")
- for r in islice(ddgs_gen, 10):
- search_results.append(r)
- reference_results = []
- for idx, result in enumerate(search_results):
- logging.debug(f"搜索结果{idx + 1}:{result}")
- domain_name = urllib3.util.parse_url(result['href']).host
- reference_results.append([result['body'], result['href']])
- display_append.append(
- # f"{idx+1}. [{domain_name}]({result['href']})\n"
- f"{idx+1}. {result['title']}"
- )
- reference_results = add_source_numbers(reference_results)
- # display_append = "\n\n" + "".join(display_append) + ""
- display_append = '
' + \
- "".join(display_append) + '
'
- real_inputs = (
- replace_today(WEBSEARCH_PTOMPT_TEMPLATE)
- .replace("{query}", real_inputs)
- .replace("{web_results}", "\n\n".join(reference_results))
- .replace("{reply_language}", reply_language)
- )
- else:
- display_append = ""
- return limited_context, fake_inputs, display_append, real_inputs, chatbot
-
- def predict(
- self,
- inputs,
- chatbot,
- stream=False,
- use_websearch=False,
- files=None,
- reply_language="中文",
- should_check_token_count=True,
- ): # repetition_penalty, top_k
-
- status_text = "开始生成回答……"
- logging.info(
- "用户" + f"{self.user_identifier}" + "的输入为:" +
- colorama.Fore.BLUE + f"{inputs}" + colorama.Style.RESET_ALL
- )
- if should_check_token_count:
- yield chatbot + [(inputs, "")], status_text
- if reply_language == "跟随问题语言(不稳定)":
- reply_language = "the same language as the question, such as English, 中文, 日本語, Español, Français, or Deutsch."
-
- limited_context, fake_inputs, display_append, inputs, chatbot = self.prepare_inputs(
- real_inputs=inputs, use_websearch=use_websearch, files=files, reply_language=reply_language, chatbot=chatbot)
- yield chatbot + [(fake_inputs, "")], status_text
-
- if (
- self.need_api_key and
- self.api_key is None
- and not shared.state.multi_api_key
- ):
- status_text = STANDARD_ERROR_MSG + NO_APIKEY_MSG
- logging.info(status_text)
- chatbot.append((inputs, ""))
- if len(self.history) == 0:
- self.history.append(construct_user(inputs))
- self.history.append("")
- self.all_token_counts.append(0)
- else:
- self.history[-2] = construct_user(inputs)
- yield chatbot + [(inputs, "")], status_text
- return
- elif len(inputs.strip()) == 0:
- status_text = STANDARD_ERROR_MSG + NO_INPUT_MSG
- logging.info(status_text)
- yield chatbot + [(inputs, "")], status_text
- return
-
- if self.single_turn:
- self.history = []
- self.all_token_counts = []
- self.history.append(construct_user(inputs))
-
- try:
- if stream:
- logging.debug("使用流式传输")
- iter = self.stream_next_chatbot(
- inputs,
- chatbot,
- fake_input=fake_inputs,
- display_append=display_append,
- )
- for chatbot, status_text in iter:
- yield chatbot, status_text
- else:
- logging.debug("不使用流式传输")
- chatbot, status_text = self.next_chatbot_at_once(
- inputs,
- chatbot,
- fake_input=fake_inputs,
- display_append=display_append,
- )
- yield chatbot, status_text
- except Exception as e:
- traceback.print_exc()
- status_text = STANDARD_ERROR_MSG + beautify_err_msg(str(e))
- yield chatbot, status_text
-
- if len(self.history) > 1 and self.history[-1]["content"] != inputs:
- logging.info(
- "回答为:"
- + colorama.Fore.BLUE
- + f"{self.history[-1]['content']}"
- + colorama.Style.RESET_ALL
- )
-
- if limited_context:
- # self.history = self.history[-4:]
- # self.all_token_counts = self.all_token_counts[-2:]
- self.history = []
- self.all_token_counts = []
-
- max_token = self.token_upper_limit - TOKEN_OFFSET
-
- if sum(self.all_token_counts) > max_token and should_check_token_count:
- count = 0
- while (
- sum(self.all_token_counts)
- > self.token_upper_limit * REDUCE_TOKEN_FACTOR
- and sum(self.all_token_counts) > 0
- ):
- count += 1
- del self.all_token_counts[0]
- del self.history[:2]
- logging.info(status_text)
- status_text = f"为了防止token超限,模型忘记了早期的 {count} 轮对话"
- yield chatbot, status_text
-
- self.auto_save(chatbot)
-
- def retry(
- self,
- chatbot,
- stream=False,
- use_websearch=False,
- files=None,
- reply_language="中文",
- ):
- logging.debug("重试中……")
- if len(self.history) > 0:
- inputs = self.history[-2]["content"]
- del self.history[-2:]
- if len(self.all_token_counts) > 0:
- self.all_token_counts.pop()
- elif len(chatbot) > 0:
- inputs = chatbot[-1][0]
- else:
- yield chatbot, f"{STANDARD_ERROR_MSG}上下文是空的"
- return
-
- iter = self.predict(
- inputs,
- chatbot,
- stream=stream,
- use_websearch=use_websearch,
- files=files,
- reply_language=reply_language,
- )
- for x in iter:
- yield x
- logging.debug("重试完毕")
-
- # def reduce_token_size(self, chatbot):
- # logging.info("开始减少token数量……")
- # chatbot, status_text = self.next_chatbot_at_once(
- # summarize_prompt,
- # chatbot
- # )
- # max_token_count = self.token_upper_limit * REDUCE_TOKEN_FACTOR
- # num_chat = find_n(self.all_token_counts, max_token_count)
- # logging.info(f"previous_token_count: {self.all_token_counts}, keeping {num_chat} chats")
- # chatbot = chatbot[:-1]
- # self.history = self.history[-2*num_chat:] if num_chat > 0 else []
- # self.all_token_counts = self.all_token_counts[-num_chat:] if num_chat > 0 else []
- # msg = f"保留了最近{num_chat}轮对话"
- # logging.info(msg)
- # logging.info("减少token数量完毕")
- # return chatbot, msg + "," + self.token_message(self.all_token_counts if len(self.all_token_counts) > 0 else [0])
-
- def interrupt(self):
- self.interrupted = True
-
- def recover(self):
- self.interrupted = False
-
- def set_token_upper_limit(self, new_upper_limit):
- self.token_upper_limit = new_upper_limit
- print(f"token上限设置为{new_upper_limit}")
-
- def set_temperature(self, new_temperature):
- self.temperature = new_temperature
-
- def set_top_p(self, new_top_p):
- self.top_p = new_top_p
-
- def set_n_choices(self, new_n_choices):
- self.n_choices = new_n_choices
-
- def set_stop_sequence(self, new_stop_sequence: str):
- new_stop_sequence = new_stop_sequence.split(",")
- self.stop_sequence = new_stop_sequence
-
- def set_max_tokens(self, new_max_tokens):
- self.max_generation_token = new_max_tokens
-
- def set_presence_penalty(self, new_presence_penalty):
- self.presence_penalty = new_presence_penalty
-
- def set_frequency_penalty(self, new_frequency_penalty):
- self.frequency_penalty = new_frequency_penalty
-
- def set_logit_bias(self, logit_bias):
- logit_bias = logit_bias.split()
- bias_map = {}
- encoding = tiktoken.get_encoding("cl100k_base")
- for line in logit_bias:
- word, bias_amount = line.split(":")
- if word:
- for token in encoding.encode(word):
- bias_map[token] = float(bias_amount)
- self.logit_bias = bias_map
-
- def set_user_identifier(self, new_user_identifier):
- self.user_identifier = new_user_identifier
-
- def set_system_prompt(self, new_system_prompt):
- self.system_prompt = new_system_prompt
-
- def set_key(self, new_access_key):
- if "*" not in new_access_key:
- self.api_key = new_access_key.strip()
- msg = i18n("API密钥更改为了") + hide_middle_chars(self.api_key)
- logging.info(msg)
- return self.api_key, msg
- else:
- return gr.update(), gr.update()
-
- def set_single_turn(self, new_single_turn):
- self.single_turn = new_single_turn
-
- def reset(self):
- self.history = []
- self.all_token_counts = []
- self.interrupted = False
- pathlib.Path(os.path.join(HISTORY_DIR, self.user_identifier, new_auto_history_filename(
- os.path.join(HISTORY_DIR, self.user_identifier)))).touch()
- return [], self.token_message([0])
-
- def delete_first_conversation(self):
- if self.history:
- del self.history[:2]
- del self.all_token_counts[0]
- return self.token_message()
-
- def delete_last_conversation(self, chatbot):
- if len(chatbot) > 0 and STANDARD_ERROR_MSG in chatbot[-1][1]:
- msg = "由于包含报错信息,只删除chatbot记录"
- chatbot.pop()
- return chatbot, self.history
- if len(self.history) > 0:
- self.history.pop()
- self.history.pop()
- if len(chatbot) > 0:
- msg = "删除了一组chatbot对话"
- chatbot.pop()
- if len(self.all_token_counts) > 0:
- msg = "删除了一组对话的token计数记录"
- self.all_token_counts.pop()
- msg = "删除了一组对话"
- return chatbot, msg
-
- def token_message(self, token_lst=None):
- if token_lst is None:
- token_lst = self.all_token_counts
- token_sum = 0
- for i in range(len(token_lst)):
- token_sum += sum(token_lst[: i + 1])
- return i18n("Token 计数: ") + f"{sum(token_lst)}" + i18n(",本次对话累计消耗了 ") + f"{token_sum} tokens"
-
- def save_chat_history(self, filename, chatbot, user_name):
- if filename == "":
- return
- if not filename.endswith(".json"):
- filename += ".json"
- return save_file(filename, self.system_prompt, self.history, chatbot, user_name)
-
- def auto_save(self, chatbot):
- history_file_path = get_history_filepath(self.user_identifier)
- save_file(history_file_path, self.system_prompt,
- self.history, chatbot, self.user_identifier)
-
- def export_markdown(self, filename, chatbot, user_name):
- if filename == "":
- return
- if not filename.endswith(".md"):
- filename += ".md"
- return save_file(filename, self.system_prompt, self.history, chatbot, user_name)
-
- def load_chat_history(self, filename, user_name):
- logging.debug(f"{user_name} 加载对话历史中……")
- logging.info(f"filename: {filename}")
- if type(filename) != str and filename is not None:
- filename = filename.name
- try:
- if "/" not in filename:
- history_file_path = os.path.join(
- HISTORY_DIR, user_name, filename)
- else:
- history_file_path = filename
- with open(history_file_path, "r", encoding="utf-8") as f:
- json_s = json.load(f)
- try:
- if type(json_s["history"][0]) == str:
- logging.info("历史记录格式为旧版,正在转换……")
- new_history = []
- for index, item in enumerate(json_s["history"]):
- if index % 2 == 0:
- new_history.append(construct_user(item))
- else:
- new_history.append(construct_assistant(item))
- json_s["history"] = new_history
- logging.info(new_history)
- except:
- pass
- logging.debug(f"{user_name} 加载对话历史完毕")
- self.history = json_s["history"]
- return os.path.basename(filename), json_s["system"], json_s["chatbot"]
- except:
- # 没有对话历史或者对话历史解析失败
- logging.info(f"没有找到对话历史记录 {filename}")
- return gr.update(), self.system_prompt, gr.update()
-
- def delete_chat_history(self, filename, user_name):
- if filename == "CANCELED":
- return gr.update(), gr.update(), gr.update()
- if filename == "":
- return i18n("你没有选择任何对话历史"), gr.update(), gr.update()
- if not filename.endswith(".json"):
- filename += ".json"
- if "/" not in filename:
- history_file_path = os.path.join(HISTORY_DIR, user_name, filename)
- else:
- history_file_path = filename
- try:
- os.remove(history_file_path)
- return i18n("删除对话历史成功"), get_history_names(False, user_name), []
- except:
- logging.info(f"删除对话历史失败 {history_file_path}")
- return i18n("对话历史")+filename+i18n("已经被删除啦"), gr.update(), gr.update()
-
- def auto_load(self):
- if self.user_identifier == "":
- self.reset()
- return self.system_prompt, gr.update()
- history_file_path = get_history_filepath(self.user_identifier)
- filename, system_prompt, chatbot = self.load_chat_history(
- history_file_path, self.user_identifier)
- return system_prompt, chatbot
-
- def like(self):
- """like the last response, implement if needed
- """
- return gr.update()
-
- def dislike(self):
- """dislike the last response, implement if needed
- """
- return gr.update()
-
-
-class Base_Chat_Langchain_Client(BaseLLMModel):
- def __init__(self, model_name, user_name=""):
- super().__init__(model_name, user=user_name)
- self.need_api_key = False
- self.model = self.setup_model()
-
- def setup_model(self):
- # inplement this to setup the model then return it
- pass
-
- def _get_langchain_style_history(self):
- history = [SystemMessage(content=self.system_prompt)]
- for i in self.history:
- if i["role"] == "user":
- history.append(HumanMessage(content=i["content"]))
- elif i["role"] == "assistant":
- history.append(AIMessage(content=i["content"]))
- return history
-
- def get_answer_at_once(self):
- assert isinstance(
- self.model, BaseChatModel), "model is not instance of LangChain BaseChatModel"
- history = self._get_langchain_style_history()
- response = self.model.generate(history)
- return response.content, sum(response.content)
-
- def get_answer_stream_iter(self):
- it = CallbackToIterator()
- assert isinstance(
- self.model, BaseChatModel), "model is not instance of LangChain BaseChatModel"
- history = self._get_langchain_style_history()
-
- def thread_func():
- self.model(messages=history, callbacks=[
- ChuanhuCallbackHandler(it.callback)])
- it.finish()
- t = Thread(target=thread_func)
- t.start()
- partial_text = ""
- for value in it:
- partial_text += value
- yield partial_text
diff --git a/spaces/Jokerkid/porntech-sex-position/README.md b/spaces/Jokerkid/porntech-sex-position/README.md
deleted file mode 100644
index e0470ed0175947fa2dafb54bcef774533ac138fa..0000000000000000000000000000000000000000
--- a/spaces/Jokerkid/porntech-sex-position/README.md
+++ /dev/null
@@ -1,12 +0,0 @@
----
-title: Porntech Sex Position
-emoji: 📈
-colorFrom: green
-colorTo: yellow
-sdk: gradio
-sdk_version: 3.33.1
-app_file: app.py
-pinned: false
----
-
-Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
diff --git a/spaces/JunchuanYu/SegRS/segment_anything/modeling/mask_decoder.py b/spaces/JunchuanYu/SegRS/segment_anything/modeling/mask_decoder.py
deleted file mode 100644
index 3e86f7cc9ad95582a08ef2531c68d03fa4af8d99..0000000000000000000000000000000000000000
--- a/spaces/JunchuanYu/SegRS/segment_anything/modeling/mask_decoder.py
+++ /dev/null
@@ -1,176 +0,0 @@
-# Copyright (c) Meta Platforms, Inc. and affiliates.
-# All rights reserved.
-
-# This source code is licensed under the license found in the
-# LICENSE file in the root directory of this source tree.
-
-import torch
-from torch import nn
-from torch.nn import functional as F
-
-from typing import List, Tuple, Type
-
-from .common import LayerNorm2d
-
-
-class MaskDecoder(nn.Module):
- def __init__(
- self,
- *,
- transformer_dim: int,
- transformer: nn.Module,
- num_multimask_outputs: int = 3,
- activation: Type[nn.Module] = nn.GELU,
- iou_head_depth: int = 3,
- iou_head_hidden_dim: int = 256,
- ) -> None:
- """
- Predicts masks given an image and prompt embeddings, using a
- tranformer architecture.
-
- Arguments:
- transformer_dim (int): the channel dimension of the transformer
- transformer (nn.Module): the transformer used to predict masks
- num_multimask_outputs (int): the number of masks to predict
- when disambiguating masks
- activation (nn.Module): the type of activation to use when
- upscaling masks
- iou_head_depth (int): the depth of the MLP used to predict
- mask quality
- iou_head_hidden_dim (int): the hidden dimension of the MLP
- used to predict mask quality
- """
- super().__init__()
- self.transformer_dim = transformer_dim
- self.transformer = transformer
-
- self.num_multimask_outputs = num_multimask_outputs
-
- self.iou_token = nn.Embedding(1, transformer_dim)
- self.num_mask_tokens = num_multimask_outputs + 1
- self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)
-
- self.output_upscaling = nn.Sequential(
- nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2),
- LayerNorm2d(transformer_dim // 4),
- activation(),
- nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2),
- activation(),
- )
- self.output_hypernetworks_mlps = nn.ModuleList(
- [
- MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3)
- for i in range(self.num_mask_tokens)
- ]
- )
-
- self.iou_prediction_head = MLP(
- transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth
- )
-
- def forward(
- self,
- image_embeddings: torch.Tensor,
- image_pe: torch.Tensor,
- sparse_prompt_embeddings: torch.Tensor,
- dense_prompt_embeddings: torch.Tensor,
- multimask_output: bool,
- ) -> Tuple[torch.Tensor, torch.Tensor]:
- """
- Predict masks given image and prompt embeddings.
-
- Arguments:
- image_embeddings (torch.Tensor): the embeddings from the image encoder
- image_pe (torch.Tensor): positional encoding with the shape of image_embeddings
- sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes
- dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs
- multimask_output (bool): Whether to return multiple masks or a single
- mask.
-
- Returns:
- torch.Tensor: batched predicted masks
- torch.Tensor: batched predictions of mask quality
- """
- masks, iou_pred = self.predict_masks(
- image_embeddings=image_embeddings,
- image_pe=image_pe,
- sparse_prompt_embeddings=sparse_prompt_embeddings,
- dense_prompt_embeddings=dense_prompt_embeddings,
- )
-
- # Select the correct mask or masks for outptu
- if multimask_output:
- mask_slice = slice(1, None)
- else:
- mask_slice = slice(0, 1)
- masks = masks[:, mask_slice, :, :]
- iou_pred = iou_pred[:, mask_slice]
-
- # Prepare output
- return masks, iou_pred
-
- def predict_masks(
- self,
- image_embeddings: torch.Tensor,
- image_pe: torch.Tensor,
- sparse_prompt_embeddings: torch.Tensor,
- dense_prompt_embeddings: torch.Tensor,
- ) -> Tuple[torch.Tensor, torch.Tensor]:
- """Predicts masks. See 'forward' for more details."""
- # Concatenate output tokens
- output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0)
- output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.size(0), -1, -1)
- tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1)
-
- # Expand per-image data in batch direction to be per-mask
- src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0)
- src = src + dense_prompt_embeddings
- pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
- b, c, h, w = src.shape
-
- # Run the transformer
- hs, src = self.transformer(src, pos_src, tokens)
- iou_token_out = hs[:, 0, :]
- mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :]
-
- # Upscale mask embeddings and predict masks using the mask tokens
- src = src.transpose(1, 2).view(b, c, h, w)
- upscaled_embedding = self.output_upscaling(src)
- hyper_in_list: List[torch.Tensor] = []
- for i in range(self.num_mask_tokens):
- hyper_in_list.append(self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]))
- hyper_in = torch.stack(hyper_in_list, dim=1)
- b, c, h, w = upscaled_embedding.shape
- masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w)
-
- # Generate mask quality predictions
- iou_pred = self.iou_prediction_head(iou_token_out)
-
- return masks, iou_pred
-
-
-# Lightly adapted from
-# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa
-class MLP(nn.Module):
- def __init__(
- self,
- input_dim: int,
- hidden_dim: int,
- output_dim: int,
- num_layers: int,
- sigmoid_output: bool = False,
- ) -> None:
- super().__init__()
- self.num_layers = num_layers
- h = [hidden_dim] * (num_layers - 1)
- self.layers = nn.ModuleList(
- nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])
- )
- self.sigmoid_output = sigmoid_output
-
- def forward(self, x):
- for i, layer in enumerate(self.layers):
- x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
- if self.sigmoid_output:
- x = F.sigmoid(x)
- return x
diff --git a/spaces/KAIST-Geometric-AI-Lab/salad-demo/salad/spaghetti/utils/rotation_utils.py b/spaces/KAIST-Geometric-AI-Lab/salad-demo/salad/spaghetti/utils/rotation_utils.py
deleted file mode 100644
index f9f731341941d5467830f779955091e8f5445ce6..0000000000000000000000000000000000000000
--- a/spaces/KAIST-Geometric-AI-Lab/salad-demo/salad/spaghetti/utils/rotation_utils.py
+++ /dev/null
@@ -1,158 +0,0 @@
-from .. import constants
-import functools
-from scipy.spatial.transform.rotation import Rotation
-from ..custom_types import *
-
-
-def quat_to_rot(q):
- shape = q.shape
- q = q.view(-1, 4)
- q_sq = 2 * q[:, :, None] * q[:, None, :]
- m00 = 1 - q_sq[:, 1, 1] - q_sq[:, 2, 2]
- m01 = q_sq[:, 0, 1] - q_sq[:, 2, 3]
- m02 = q_sq[:, 0, 2] + q_sq[:, 1, 3]
-
- m10 = q_sq[:, 0, 1] + q_sq[:, 2, 3]
- m11 = 1 - q_sq[:, 0, 0] - q_sq[:, 2, 2]
- m12 = q_sq[:, 1, 2] - q_sq[:, 0, 3]
-
- m20 = q_sq[:, 0, 2] - q_sq[:, 1, 3]
- m21 = q_sq[:, 1, 2] + q_sq[:, 0, 3]
- m22 = 1 - q_sq[:, 0, 0] - q_sq[:, 1, 1]
- r = torch.stack((m00, m01, m02, m10, m11, m12, m20, m21, m22), dim=1)
- r = r.view(*shape[:-1], 3, 3)
- return r
-
-
-def rot_to_quat(r):
- shape = r.shape
- r = r.view(-1, 3, 3)
- qw = .5 * (1 + r[:, 0, 0] + r[:, 1, 1] + r[:, 2, 2]).sqrt()
- qx = (r[:, 2, 1] - r[:, 1, 2]) / (4 * qw)
- qy = (r[:, 0, 2] - r[:, 2, 0]) / (4 * qw)
- qz = (r[:, 1, 0] - r[:, 0, 1]) / (4 * qw)
- q = torch.stack((qx, qy, qz, qw), -1)
- q = q.view(*shape[:-2], 4)
- return q
-
-
-@functools.lru_cache(10)
-def get_rotation_matrix(theta: float, axis: float, degree: bool = False) -> ARRAY:
- if degree:
- theta = theta * np.pi / 180
- rotate_mat = np.eye(3)
- rotate_mat[axis, axis] = 1
- cos_theta, sin_theta = np.cos(theta), np.sin(theta)
- rotate_mat[(axis + 1) % 3, (axis + 1) % 3] = cos_theta
- rotate_mat[(axis + 2) % 3, (axis + 2) % 3] = cos_theta
- rotate_mat[(axis + 1) % 3, (axis + 2) % 3] = sin_theta
- rotate_mat[(axis + 2) % 3, (axis + 1) % 3] = -sin_theta
- return rotate_mat
-
-
-def get_random_rotation(batch_size: int) -> T:
- r = Rotation.random(batch_size).as_matrix().astype(np.float32)
- Rotation.random()
- return torch.from_numpy(r)
-
-
-def rand_bounded_rotation_matrix(cache_size: int, theta_range: float = .1):
-
- def create_cache():
- # from http://www.realtimerendering.com/resources/GraphicsGems/gemsiii/rand_rotation.c
- with torch.no_grad():
- theta, phi, z = torch.rand(cache_size, 3).split((1, 1, 1), dim=1)
- theta = (2 * theta - 1) * theta_range + 1
- theta = np.pi * theta # Rotation about the pole (Z).
- phi = phi * 2 * np.pi # For direction of pole deflection.
- z = 2 * z * theta_range # For magnitude of pole deflection.
- r = z.sqrt()
- v = torch.cat((torch.sin(phi) * r, torch.cos(phi) * r, torch.sqrt(2.0 - z)), dim=1)
- st = torch.sin(theta).squeeze(1)
- ct = torch.cos(theta).squeeze(1)
- rot_ = torch.zeros(cache_size, 3, 3)
- rot_[:, 0, 0] = ct
- rot_[:, 1, 1] = ct
- rot_[:, 0, 1] = st
- rot_[:, 1, 0] = -st
- rot_[:, 2, 2] = 1
- rot = (torch.einsum('ba,bd->bad', v, v) - torch.eye(3)[None, :, :]).bmm(rot_)
- det = rot.det()
- assert (det.gt(0.99) * det.lt(1.0001)).all().item()
- return rot
-
- def get_batch_rot(batch_size):
- nonlocal cache
- select = torch.randint(cache_size, size=(batch_size,))
- return cache[select]
-
- cache = create_cache()
-
- return get_batch_rot
-
-
-def transform_rotation(points: T, one_axis=False, max_angle=-1):
- r = get_random_rotation(one_axis, max_angle)
- transformed = torch.einsum('nd,rd->nr', points, r)
- return transformed
-
-
-def tb_to_rot(abc: T) -> T:
- c, s = torch.cos(abc), torch.sin(abc)
- aa = c[:, 0] * c[:, 1]
- ab = c[:, 0] * s[:, 1] * s[:, 2] - c[:, 2] * s[:, 0]
- ac = s[:, 0] * s[:, 2] + c[:, 0] * c[:, 2] * s[:, 1]
-
- ba = c[:, 1] * s[:, 0]
- bb = c[:, 0] * c[:, 2] + s.prod(-1)
- bc = c[:, 2] * s[:, 0] * s[:, 1] - c[:, 0] * s[:, 2]
-
- ca = -s[:, 1]
- cb = c[:, 1] * s[:, 2]
- cc = c[:, 1] * c[:, 2]
- return torch.stack((aa, ab, ac, ba, bb, bc, ca, cb, cc), 1).view(-1, 3, 3)
-
-
-def rot_to_tb(rot: T) -> T:
- sy = torch.sqrt(rot[:, 0, 0] * rot[:, 0, 0] + rot[:, 1, 0] * rot[:, 1, 0])
- out = torch.zeros(rot.shape[0], 3, device = rot.device)
- mask = sy.gt(1e-6)
- z = torch.atan2(rot[mask, 2, 1], rot[mask, 2, 2])
- y = torch.atan2(-rot[mask, 2, 0], sy[mask])
- x = torch.atan2(rot[mask, 1, 0], rot[mask, 0, 0])
- out[mask] = torch.stack((x, y, z), dim=1)
- if not mask.all():
- mask = ~mask
- z = torch.atan2(-rot[mask, 1, 2], rot[mask, 1, 1])
- y = torch.atan2(-rot[mask, 2, 0], sy[mask])
- x = torch.zeros(x.shape)
- out[mask] = torch.stack((x, y, z), dim=1)
- return out
-
-
-def apply_gmm_affine(gmms: TS, affine: T):
- mu, p, phi, eigen = gmms
- if affine.dim() == 2:
- affine = affine.unsqueeze(0).expand(mu.shape[0], *affine.shape)
- mu_r = torch.einsum('bad, bpnd->bpna', affine, mu)
- p_r = torch.einsum('bad, bpncd->bpnca', affine, p)
- return mu_r, p_r, phi, eigen
-
-
-def get_reflection(reflect_axes: Tuple[bool, ...]) -> T:
- reflect = torch.eye(constants.DIM)
- for i in range(constants.DIM):
- if reflect_axes[i]:
- reflect[i, i] = -1
- return reflect
-
-
-def get_tait_bryan_from_p(p: T) -> T:
- # p = p.squeeze(1)
- shape = p.shape
- rot = p.reshape(-1, 3, 3).permute(0, 2, 1)
- angles = rot_to_tb(rot)
- angles = angles / np.pi
- angles[:, 1] = angles[:, 1] * 2
- angles = angles.view(*shape[:2], 3)
- return angles
diff --git a/spaces/KJMAN678/text_generate/app.py b/spaces/KJMAN678/text_generate/app.py
deleted file mode 100644
index 2a627723eb7a7696bb55aa8f1af9ebc198f15eef..0000000000000000000000000000000000000000
--- a/spaces/KJMAN678/text_generate/app.py
+++ /dev/null
@@ -1,82 +0,0 @@
-import streamlit as st
-from transformers import T5Tokenizer, AutoModelForCausalLM
-
-def cached_tokenizer():
- tokenizer = T5Tokenizer.from_pretrained("rinna/japanese-gpt2-medium")
- tokenizer.do_lower_case = True
- return tokenizer
-
-def cached_model():
- model = AutoModelForCausalLM.from_pretrained("rinna/japanese-gpt2-medium")
- return model
-
-def main():
- st.title("GPT-2による日本語の文章生成")
-
- num_of_output_text = st.slider(label='出力する文章の数',
- min_value=1,
- max_value=2,
- value=1,
- )
-
- length_of_output_text = st.slider(label='出力する文字数',
- min_value=30,
- max_value=200,
- value=100,
- )
-
- PREFIX_TEXT = st.text_area(
- label='テキスト入力',
- value='吾輩は猫である'
- )
-
- progress_num = 0
- status_text = st.empty()
- progress_bar = st.progress(progress_num)
-
- if st.button('文章生成'):
-
- st.text("読み込みに時間がかかります")
- progress_num = 10
- status_text.text(f'Progress: {progress_num}%')
- progress_bar.progress(progress_num)
-
- tokenizer = cached_tokenizer()
- progress_num = 25
- status_text.text(f'Progress: {progress_num}%')
- progress_bar.progress(progress_num)
-
- model = cached_model()
- progress_num = 40
- status_text.text(f'Progress: {progress_num}%')
- progress_bar.progress(progress_num)
-
- # 推論
- input = tokenizer.encode(PREFIX_TEXT, return_tensors="pt")
- progress_num = 60
- status_text.text(f'Progress: {progress_num}%')
- progress_bar.progress(progress_num)
-
- output = model.generate(
- input, do_sample=True,
- max_length=length_of_output_text,
- num_return_sequences=num_of_output_text
- )
- progress_num = 90
- status_text.text(f'Progress: {progress_num}%')
- progress_bar.progress(progress_num)
-
- output_text = "".join(tokenizer.batch_decode(output)).replace("", "")
- output_text = output_text.replace("", "")
- progress_num = 95
- status_text.text(f'Progress: {progress_num}%')
- progress_bar.progress(progress_num)
-
- st.info('生成結果')
- progress_num = 100
- status_text.text(f'Progress: {progress_num}%')
- st.write(output_text)
- progress_bar.progress(progress_num)
-
-if __name__ == '__main__':
- main()
\ No newline at end of file
diff --git a/spaces/Kaludi/Food-Category-Classification-And-Recipes-Recommender_App/pages/Recipe_By_Ingredients_.py b/spaces/Kaludi/Food-Category-Classification-And-Recipes-Recommender_App/pages/Recipe_By_Ingredients_.py
deleted file mode 100644
index ddc1e0dfc3a72a6af1c38fab27628a0507be803f..0000000000000000000000000000000000000000
--- a/spaces/Kaludi/Food-Category-Classification-And-Recipes-Recommender_App/pages/Recipe_By_Ingredients_.py
+++ /dev/null
@@ -1,389 +0,0 @@
-import requests
-import json
-import random
-import streamlit as st
-import numpy as np
-from transformers import AutoFeatureExtractor
-from transformers import AutoModelForImageClassification
-import plotly.graph_objects as go
-import plotly
-import re
-
-st.title("Recipes by Ingredients")
-st.markdown("Get food recipes based on user input. Users can input the type of food they want to search for and the maximum number of calories they want to consume, and depending on the criteria a recipe will be recommended to the user.")
-
-url = "https://alcksyjrmd.execute-api.us-east-2.amazonaws.com/default/nutrients_response"
-
-# Get user input
-ingredients = st.text_input("Enter ingredients (Separated By Commas)", placeholder="Enter Atleast One Ingredient", value="")
-
-# Set default values for optional parameters
-max_calories = 0
-diet = "All"
-cuisine = "All"
-
-# Add options for target calories per day, diet, and cuisine
-max_calories = st.number_input("Enter your max calories for recipe", min_value=0, value=0, step=100)
-diet_options = ["All", "Gluten-Free", "Vegan", "Vegetarian", "Dairy-Free"]
-diet = st.selectbox("Select a diet", diet_options)
-cuisine_options = ["All", "African", "Asian", "Caribbean", "Central American", "Europe", "Middle Eastern", "North American", "Oceanic", "South American"]
-cuisine = st.selectbox("Select a cuisine", cuisine_options)
-if ingredients == "":
- st.warning("Please enter at least one ingredient.")
-elif st.button("Get Recipe"):
-
- # Set the parameters for the API request
- params = {"i": ingredients}
-
- if max_calories != 0:
- params["k"] = max_calories
-
- if diet != "All":
- params["d"] = diet
-
- if cuisine != "All":
- params["c"] = cuisine
-
- # Make the API request
- response = requests.get(url, params=params)
-
- if response.status_code == 200 and response.content:
- try:
- response_json = json.loads(response.content)
- except json.JSONDecodeError:
- st.write("Error: Response is not in valid JSON format")
- response_json = None
- else:
- st.error("The query was too large, please fine-tune your search.")
- response_json = None
-
- # Display the results
- if response_json is None or len(response_json) == 0:
- st.markdown("### No Recipe Found:")
- st.write("**No Recipe Found, please try another option from the dropdown menus.**")
- else:
- st.markdown("### Recommended Recipe:")
- if len(response_json) > 1:
- random_recipe = random.choice(response_json)
- st.write("**Title:** ", random_recipe['Title'])
- if random_recipe['Image Link'].endswith(".jpg") or random_recipe['Image Link'].endswith(".jpeg") or random_recipe['Image Link'].endswith(".png"):
- st.image(random_recipe['Image Link'], width=300)
- else:
- st.write("**Image Link:** ", random_recipe['Image Link'])
- st.write("**Rating:** ", random_recipe['Rating'])
- if random_recipe['Description'] != "Description not found":
- st.write("**Description:** ", random_recipe['Description'])
- st.write("**Ingredients:** ", random_recipe['Ingredients'].replace('\n', ' '), unsafe_allow_html=True)
- st.write("**Recipe Facts:** ", random_recipe['Recipe Facts'].replace('\n', ' '), unsafe_allow_html=True)
- st.write("**Directions:** ", random_recipe['Directions'].replace('\n', ' '), unsafe_allow_html=True)
- # extract only numeric values and convert mg to g
- values = [
- float(re.sub(r'[^\d.]+', '', random_recipe['Total Fat'])),
- float(re.sub(r'[^\d.]+', '', random_recipe['Saturated Fat'])),
- float(re.sub(r'[^\d.]+', '', random_recipe['Cholesterol'])) / 1000,
- float(re.sub(r'[^\d.]+', '', random_recipe['Sodium'])) / 1000,
- float(re.sub(r'[^\d.]+', '', random_recipe['Total Carbohydrate'])),
- float(re.sub(r'[^\d.]+', '', random_recipe['Dietary Fiber'])),
- float(re.sub(r'[^\d.]+', '', random_recipe['Total Sugars'])),
- float(re.sub(r'[^\d.]+', '', random_recipe['Protein'])),
- float(re.sub(r'[^\d.]+', '', random_recipe['Vitamin C'])) / 1000,
- float(re.sub(r'[^\d.]+', '', random_recipe['Calcium'])) / 1000,
- float(re.sub(r'[^\d.]+', '', random_recipe['Iron'])) / 1000,
- float(re.sub(r'[^\d.]+', '', random_recipe['Potassium'])) / 1000
- ]
- # Create a list of daily values (DV) for each nutrient based on a 2000 calorie per day diet, all are in grams
- dv = [65, 20, 0.3, 2.3, 300, 28, 50, 50, 0.09, 1, 0.018, 4.7]
-
- # Calculate the percentage of DV for each nutrient
- dv_percent = [round(value * 100 / dv[i]) for i, value in enumerate(values)]
- nutrition_html = """
-
-
-
-
-
Number of Servings: {servings}
-
-
-
-
-
Calories
-
{calories}
-
-
-
-
Total Fat
-
{total_fat}
-
{fat_percent}% DV
-
-
-
Saturated Fat
-
{saturated_fat}
-
{sat_fat_percent}% DV
-
-
-
Cholesterol
-
{cholesterol}
-
{chol_percent}% DV
-
-
-
Sodium
-
{sodium}
-
{sodium_percent}% DV
-
-
-
Total Carbohydrate
-
{total_carbohydrate}
-
{carb_percent}% DV
-
-
-
Dietary Fiber
-
{dietary_fiber}
-
{diet_fibe_percent}% DV
-
-
-
Total Sugars
-
{total_sugars}
-
{tot_sugars_percent}% DV
-
-
-
Protein
-
{protein}
-
{protein_percent}% DV
-
-
-
Vitamin C
-
{vitc}
-
{vitc_percent}% DV
-
-
-
Calcium
-
{calc}
-
{calc_percent}% DV
-
-
-
Iron
-
{iron}
-
{iron_percent}% DV
-
-
-
Potassium
-
{pota}
-
{pota_percent}% DV
-
-
-
-
- """
- # Use the nutrition HTML and format it with the values
- formatted_html = nutrition_html.format(
- calories=random_recipe['Calories'],
- total_fat=random_recipe['Total Fat'],
- saturated_fat=random_recipe['Saturated Fat'],
- cholesterol=random_recipe['Cholesterol'],
- sodium=random_recipe['Sodium'],
- total_carbohydrate=random_recipe['Total Carbohydrate'],
- dietary_fiber=random_recipe['Dietary Fiber'],
- total_sugars=random_recipe['Total Sugars'],
- servings=random_recipe['Number of Servings'],
- vitc=random_recipe['Vitamin C'],
- calc=random_recipe['Calcium'],
- iron=random_recipe['Iron'],
- pota=random_recipe['Potassium'],
- protein=random_recipe['Protein'],
- fat_percent=dv_percent[0],
- sat_fat_percent=dv_percent[1],
- chol_percent=dv_percent[2],
- sodium_percent=dv_percent[3],
- carb_percent=dv_percent[4],
- diet_fibe_percent=dv_percent[5],
- tot_sugars_percent=dv_percent[6],
- protein_percent=dv_percent[7],
- vitc_percent=dv_percent[8],
- calc_percent=dv_percent[9],
- iron_percent=dv_percent[10],
- pota_percent=dv_percent[11]
-
- )
-
- # Define a function to apply the CSS styles to the table cells
- def format_table(val):
- return f"background-color: #133350; color: #fff; border: 1px solid #ddd; border-radius: .25rem; padding: .625rem .625rem 0; font-family: Helvetica; font-size: 1rem;"
-
- with st.container():
- # Add the nutrition table to the Streamlit app
- st.write("
Nutrition Facts (per serving)
", unsafe_allow_html=True)
- st.write(f"
{formatted_html}
", unsafe_allow_html=True)
- st.write("
*The % Daily Value (DV) tells you how much a nutrient in a food serving contributes to a daily diet. 2,000 calories a day is used for general nutrition advice.
", unsafe_allow_html=True)
- # create pie chart
- labels = ['Total Fat', 'Saturated Fat', 'Cholesterol', 'Sodium', 'Total Carbohydrate', 'Dietary Fiber', 'Total Sugars', 'Protein', 'Vitamin C', 'Calcium', 'Iron', 'Potassium']
- fig = go.Figure(data=[go.Pie(labels=labels, values=values)])
- st.markdown("### Macronutrients Pie Chart ;) (In Grams)")
- st.plotly_chart(fig)
- st.write("**Tags:** ", random_recipe['Tags'])
- st.write("**Recipe URL:** ", random_recipe['Recipe URLs'])
- st.write("*To download this recipe as a PDF, open the hamburger menu on the top right and click on Print.*")
- st.markdown("### JSON Response:")
- st.write(response_json)
-
- else:
- st.markdown("### Recommended Recipe:")
- st.write("**Title:** ", response_json[0]['Title'])
- if response_json[0]['Image Link'].endswith(".jpg") or response_json[0]['Image Link'].endswith(".jpeg") or response_json[0]['Image Link'].endswith(".png"):
- st.image(response_json[0]['Image Link'], width=300)
- else:
- st.write("**Image Link:** ", response_json[0]['Image Link'])
- st.write("**Rating:** ", response_json[0]['Rating'])
- if response_json[0]['Description'] != "Description not found":
- st.write("**Description:** ", response_json[0]['Description'])
- st.write("**Ingredients:** ", response_json[0]['Ingredients'].replace('\n', ' '), unsafe_allow_html=True)
- st.write("**Recipe Facts:** ", response_json[0]['Recipe Facts'].replace('\n', ' '), unsafe_allow_html=True)
- st.write("**Directions:** ", response_json[0]['Directions'].replace('\n', ' '), unsafe_allow_html=True)
- # extract only numeric values and convert mg to g
- values = [
- float(re.sub(r'[^\d.]+', '', response_json[0]['Total Fat'])),
- float(re.sub(r'[^\d.]+', '', response_json[0]['Saturated Fat'])),
- float(re.sub(r'[^\d.]+', '', response_json[0]['Cholesterol'])) / 1000,
- float(re.sub(r'[^\d.]+', '', response_json[0]['Sodium'])) / 1000,
- float(re.sub(r'[^\d.]+', '', response_json[0]['Total Carbohydrate'])),
- float(re.sub(r'[^\d.]+', '', response_json[0]['Dietary Fiber'])),
- float(re.sub(r'[^\d.]+', '', response_json[0]['Total Sugars'])),
- float(re.sub(r'[^\d.]+', '', response_json[0]['Protein'])),
- float(re.sub(r'[^\d.]+', '', response_json[0]['Vitamin C'])) / 1000,
- float(re.sub(r'[^\d.]+', '', response_json[0]['Calcium'])) / 1000,
- float(re.sub(r'[^\d.]+', '', response_json[0]['Iron'])) / 1000,
- float(re.sub(r'[^\d.]+', '', response_json[0]['Potassium'])) / 1000
- ]
- # Create a list of daily values (DV) for each nutrient based on a 2000 calorie per day diet, all are in grams
- dv = [65, 20, 0.3, 2.3, 300, 28, 50, 50, 0.09, 1, 0.018, 4.7]
-
- # Calculate the percentage of DV for each nutrient
- dv_percent = [round(value * 100 / dv[i]) for i, value in enumerate(values)]
- nutrition_html = """
-
-
-
-
-
Number of Servings: {servings}
-
-
-
-
-
Calories
-
{calories}
-
-
-
-
Total Fat
-
{total_fat}
-
{fat_percent}% DV
-
-
-
Saturated Fat
-
{saturated_fat}
-
{sat_fat_percent}% DV
-
-
-
Cholesterol
-
{cholesterol}
-
{chol_percent}% DV
-
-
-
Sodium
-
{sodium}
-
{sodium_percent}% DV
-
-
-
Total Carbohydrate
-
{total_carbohydrate}
-
{carb_percent}% DV
-
-
-
Dietary Fiber
-
{dietary_fiber}
-
{diet_fibe_percent}% DV
-
-
-
Total Sugars
-
{total_sugars}
-
{tot_sugars_percent}% DV
-
-
-
Protein
-
{protein}
-
{protein_percent}% DV
-
-
-
Vitamin C
-
{vitc}
-
{vitc_percent}% DV
-
-
-
Calcium
-
{calc}
-
{calc_percent}% DV
-
-
-
Iron
-
{iron}
-
{iron_percent}% DV
-
-
-
Potassium
-
{pota}
-
{pota_percent}% DV
-
-
-
-
- """
- # Use the nutrition HTML and format it with the values
- formatted_html = nutrition_html.format(
- calories=response_json[0]['Calories'],
- total_fat=response_json[0]['Total Fat'],
- saturated_fat=response_json[0]['Saturated Fat'],
- cholesterol=response_json[0]['Cholesterol'],
- sodium=response_json[0]['Sodium'],
- total_carbohydrate=response_json[0]['Total Carbohydrate'],
- dietary_fiber=response_json[0]['Dietary Fiber'],
- total_sugars=response_json[0]['Total Sugars'],
- servings=response_json[0]['Number of Servings'],
- vitc=response_json[0]['Vitamin C'],
- calc=response_json[0]['Calcium'],
- iron=response_json[0]['Iron'],
- pota=response_json[0]['Potassium'],
- protein=response_json[0]['Protein'],
- fat_percent=dv_percent[0],
- sat_fat_percent=dv_percent[1],
- chol_percent=dv_percent[2],
- sodium_percent=dv_percent[3],
- carb_percent=dv_percent[4],
- diet_fibe_percent=dv_percent[5],
- tot_sugars_percent=dv_percent[6],
- protein_percent=dv_percent[7],
- vitc_percent=dv_percent[8],
- calc_percent=dv_percent[9],
- iron_percent=dv_percent[10],
- pota_percent=dv_percent[11]
-
- )
-
- # Define a function to apply the CSS styles to the table cells
- def format_table(val):
- return f"background-color: #133350; color: #fff; border: 1px solid #ddd; border-radius: .25rem; padding: .625rem .625rem 0; font-family: Helvetica; font-size: 1rem;"
-
- with st.container():
- # Add the nutrition table to the Streamlit app
- st.write("
Nutrition Facts (per serving)
", unsafe_allow_html=True)
- st.write(f"
{formatted_html}
", unsafe_allow_html=True)
- st.write("
*The % Daily Value (DV) tells you how much a nutrient in a food serving contributes to a daily diet. 2,000 calories a day is used for general nutrition advice.
", unsafe_allow_html=True)
- # create pie chart
- labels = ['Total Fat', 'Saturated Fat', 'Cholesterol', 'Sodium', 'Total Carbohydrate', 'Dietary Fiber', 'Total Sugars', 'Protein', 'Vitamin C', 'Calcium', 'Iron', 'Potassium']
- fig = go.Figure(data=[go.Pie(labels=labels, values=values)])
- st.markdown("### Macronutrients Pie Chart ;) (In Grams)")
- st.plotly_chart(fig)
- st.write("**Tags:** ", response_json[0]['Tags'])
- st.write("**Recipe URL:** ", response_json[0]['Recipe URLs'])
- st.write("*To download this recipe as a PDF, open the hamburger menu on the top right and click on Print.*")
- st.markdown("### JSON Response:")
- st.write(response_json)
-
diff --git a/spaces/Kevin676/AutoGPT/autogpt/json_utils/json_fix_general.py b/spaces/Kevin676/AutoGPT/autogpt/json_utils/json_fix_general.py
deleted file mode 100644
index 7010fa3b9c1909de0e5a7f6ec13ca8aa418fe6c7..0000000000000000000000000000000000000000
--- a/spaces/Kevin676/AutoGPT/autogpt/json_utils/json_fix_general.py
+++ /dev/null
@@ -1,124 +0,0 @@
-"""This module contains functions to fix JSON strings using general programmatic approaches, suitable for addressing
-common JSON formatting issues."""
-from __future__ import annotations
-
-import contextlib
-import json
-import re
-from typing import Optional
-
-from autogpt.config import Config
-from autogpt.json_utils.utilities import extract_char_position
-
-CFG = Config()
-
-
-def fix_invalid_escape(json_to_load: str, error_message: str) -> str:
- """Fix invalid escape sequences in JSON strings.
-
- Args:
- json_to_load (str): The JSON string.
- error_message (str): The error message from the JSONDecodeError
- exception.
-
- Returns:
- str: The JSON string with invalid escape sequences fixed.
- """
- while error_message.startswith("Invalid \\escape"):
- bad_escape_location = extract_char_position(error_message)
- json_to_load = (
- json_to_load[:bad_escape_location] + json_to_load[bad_escape_location + 1 :]
- )
- try:
- json.loads(json_to_load)
- return json_to_load
- except json.JSONDecodeError as e:
- if CFG.debug_mode:
- print("json loads error - fix invalid escape", e)
- error_message = str(e)
- return json_to_load
-
-
-def balance_braces(json_string: str) -> Optional[str]:
- """
- Balance the braces in a JSON string.
-
- Args:
- json_string (str): The JSON string.
-
- Returns:
- str: The JSON string with braces balanced.
- """
-
- open_braces_count = json_string.count("{")
- close_braces_count = json_string.count("}")
-
- while open_braces_count > close_braces_count:
- json_string += "}"
- close_braces_count += 1
-
- while close_braces_count > open_braces_count:
- json_string = json_string.rstrip("}")
- close_braces_count -= 1
-
- with contextlib.suppress(json.JSONDecodeError):
- json.loads(json_string)
- return json_string
-
-
-def add_quotes_to_property_names(json_string: str) -> str:
- """
- Add quotes to property names in a JSON string.
-
- Args:
- json_string (str): The JSON string.
-
- Returns:
- str: The JSON string with quotes added to property names.
- """
-
- def replace_func(match: re.Match) -> str:
- return f'"{match[1]}":'
-
- property_name_pattern = re.compile(r"(\w+):")
- corrected_json_string = property_name_pattern.sub(replace_func, json_string)
-
- try:
- json.loads(corrected_json_string)
- return corrected_json_string
- except json.JSONDecodeError as e:
- raise e
-
-
-def correct_json(json_to_load: str) -> str:
- """
- Correct common JSON errors.
- Args:
- json_to_load (str): The JSON string.
- """
-
- try:
- if CFG.debug_mode:
- print("json", json_to_load)
- json.loads(json_to_load)
- return json_to_load
- except json.JSONDecodeError as e:
- if CFG.debug_mode:
- print("json loads error", e)
- error_message = str(e)
- if error_message.startswith("Invalid \\escape"):
- json_to_load = fix_invalid_escape(json_to_load, error_message)
- if error_message.startswith(
- "Expecting property name enclosed in double quotes"
- ):
- json_to_load = add_quotes_to_property_names(json_to_load)
- try:
- json.loads(json_to_load)
- return json_to_load
- except json.JSONDecodeError as e:
- if CFG.debug_mode:
- print("json loads error - add quotes", e)
- error_message = str(e)
- if balanced_str := balance_braces(json_to_load):
- return balanced_str
- return json_to_load
diff --git a/spaces/KyanChen/RSPrompter/mmdet/models/dense_heads/rtmdet_head.py b/spaces/KyanChen/RSPrompter/mmdet/models/dense_heads/rtmdet_head.py
deleted file mode 100644
index ae0ee6d2f35a0fa46ba0b8de21054433d0420b65..0000000000000000000000000000000000000000
--- a/spaces/KyanChen/RSPrompter/mmdet/models/dense_heads/rtmdet_head.py
+++ /dev/null
@@ -1,692 +0,0 @@
-# Copyright (c) OpenMMLab. All rights reserved.
-from typing import List, Optional, Tuple, Union
-
-import torch
-import torch.nn as nn
-from mmcv.cnn import ConvModule, DepthwiseSeparableConvModule, Scale, is_norm
-from mmengine.model import bias_init_with_prob, constant_init, normal_init
-from mmengine.structures import InstanceData
-from torch import Tensor
-
-from mmdet.registry import MODELS, TASK_UTILS
-from mmdet.structures.bbox import distance2bbox
-from mmdet.utils import ConfigType, InstanceList, OptInstanceList, reduce_mean
-from ..layers.transformer import inverse_sigmoid
-from ..task_modules import anchor_inside_flags
-from ..utils import (images_to_levels, multi_apply, sigmoid_geometric_mean,
- unmap)
-from .atss_head import ATSSHead
-
-
-@MODELS.register_module()
-class RTMDetHead(ATSSHead):
- """Detection Head of RTMDet.
-
- Args:
- num_classes (int): Number of categories excluding the background
- category.
- in_channels (int): Number of channels in the input feature map.
- with_objectness (bool): Whether to add an objectness branch.
- Defaults to True.
- act_cfg (:obj:`ConfigDict` or dict): Config dict for activation layer.
- Default: dict(type='ReLU')
- """
-
- def __init__(self,
- num_classes: int,
- in_channels: int,
- with_objectness: bool = True,
- act_cfg: ConfigType = dict(type='ReLU'),
- **kwargs) -> None:
- self.act_cfg = act_cfg
- self.with_objectness = with_objectness
- super().__init__(num_classes, in_channels, **kwargs)
- if self.train_cfg:
- self.assigner = TASK_UTILS.build(self.train_cfg['assigner'])
-
- def _init_layers(self):
- """Initialize layers of the head."""
- self.cls_convs = nn.ModuleList()
- self.reg_convs = nn.ModuleList()
- for i in range(self.stacked_convs):
- chn = self.in_channels if i == 0 else self.feat_channels
- self.cls_convs.append(
- ConvModule(
- chn,
- self.feat_channels,
- 3,
- stride=1,
- padding=1,
- conv_cfg=self.conv_cfg,
- norm_cfg=self.norm_cfg,
- act_cfg=self.act_cfg))
- self.reg_convs.append(
- ConvModule(
- chn,
- self.feat_channels,
- 3,
- stride=1,
- padding=1,
- conv_cfg=self.conv_cfg,
- norm_cfg=self.norm_cfg,
- act_cfg=self.act_cfg))
- pred_pad_size = self.pred_kernel_size // 2
- self.rtm_cls = nn.Conv2d(
- self.feat_channels,
- self.num_base_priors * self.cls_out_channels,
- self.pred_kernel_size,
- padding=pred_pad_size)
- self.rtm_reg = nn.Conv2d(
- self.feat_channels,
- self.num_base_priors * 4,
- self.pred_kernel_size,
- padding=pred_pad_size)
- if self.with_objectness:
- self.rtm_obj = nn.Conv2d(
- self.feat_channels,
- 1,
- self.pred_kernel_size,
- padding=pred_pad_size)
-
- self.scales = nn.ModuleList(
- [Scale(1.0) for _ in self.prior_generator.strides])
-
- def init_weights(self) -> None:
- """Initialize weights of the head."""
- for m in self.modules():
- if isinstance(m, nn.Conv2d):
- normal_init(m, mean=0, std=0.01)
- if is_norm(m):
- constant_init(m, 1)
- bias_cls = bias_init_with_prob(0.01)
- normal_init(self.rtm_cls, std=0.01, bias=bias_cls)
- normal_init(self.rtm_reg, std=0.01)
- if self.with_objectness:
- normal_init(self.rtm_obj, std=0.01, bias=bias_cls)
-
- def forward(self, feats: Tuple[Tensor, ...]) -> tuple:
- """Forward features from the upstream network.
-
- Args:
- feats (tuple[Tensor]): Features from the upstream network, each is
- a 4D-tensor.
-
- Returns:
- tuple: Usually a tuple of classification scores and bbox prediction
- - cls_scores (list[Tensor]): Classification scores for all scale
- levels, each is a 4D-tensor, the channels number is
- num_base_priors * num_classes.
- - bbox_preds (list[Tensor]): Box energies / deltas for all scale
- levels, each is a 4D-tensor, the channels number is
- num_base_priors * 4.
- """
-
- cls_scores = []
- bbox_preds = []
- for idx, (x, scale, stride) in enumerate(
- zip(feats, self.scales, self.prior_generator.strides)):
- cls_feat = x
- reg_feat = x
-
- for cls_layer in self.cls_convs:
- cls_feat = cls_layer(cls_feat)
- cls_score = self.rtm_cls(cls_feat)
-
- for reg_layer in self.reg_convs:
- reg_feat = reg_layer(reg_feat)
-
- if self.with_objectness:
- objectness = self.rtm_obj(reg_feat)
- cls_score = inverse_sigmoid(
- sigmoid_geometric_mean(cls_score, objectness))
-
- reg_dist = scale(self.rtm_reg(reg_feat).exp()).float() * stride[0]
-
- cls_scores.append(cls_score)
- bbox_preds.append(reg_dist)
- return tuple(cls_scores), tuple(bbox_preds)
-
- def loss_by_feat_single(self, cls_score: Tensor, bbox_pred: Tensor,
- labels: Tensor, label_weights: Tensor,
- bbox_targets: Tensor, assign_metrics: Tensor,
- stride: List[int]):
- """Compute loss of a single scale level.
-
- Args:
- cls_score (Tensor): Box scores for each scale level
- Has shape (N, num_anchors * num_classes, H, W).
- bbox_pred (Tensor): Decoded bboxes for each scale
- level with shape (N, num_anchors * 4, H, W).
- labels (Tensor): Labels of each anchors with shape
- (N, num_total_anchors).
- label_weights (Tensor): Label weights of each anchor with shape
- (N, num_total_anchors).
- bbox_targets (Tensor): BBox regression targets of each anchor with
- shape (N, num_total_anchors, 4).
- assign_metrics (Tensor): Assign metrics with shape
- (N, num_total_anchors).
- stride (List[int]): Downsample stride of the feature map.
-
- Returns:
- dict[str, Tensor]: A dictionary of loss components.
- """
- assert stride[0] == stride[1], 'h stride is not equal to w stride!'
- cls_score = cls_score.permute(0, 2, 3, 1).reshape(
- -1, self.cls_out_channels).contiguous()
- bbox_pred = bbox_pred.reshape(-1, 4)
- bbox_targets = bbox_targets.reshape(-1, 4)
- labels = labels.reshape(-1)
- assign_metrics = assign_metrics.reshape(-1)
- label_weights = label_weights.reshape(-1)
- targets = (labels, assign_metrics)
-
- loss_cls = self.loss_cls(
- cls_score, targets, label_weights, avg_factor=1.0)
-
- # FG cat_id: [0, num_classes -1], BG cat_id: num_classes
- bg_class_ind = self.num_classes
- pos_inds = ((labels >= 0)
- & (labels < bg_class_ind)).nonzero().squeeze(1)
-
- if len(pos_inds) > 0:
- pos_bbox_targets = bbox_targets[pos_inds]
- pos_bbox_pred = bbox_pred[pos_inds]
-
- pos_decode_bbox_pred = pos_bbox_pred
- pos_decode_bbox_targets = pos_bbox_targets
-
- # regression loss
- pos_bbox_weight = assign_metrics[pos_inds]
-
- loss_bbox = self.loss_bbox(
- pos_decode_bbox_pred,
- pos_decode_bbox_targets,
- weight=pos_bbox_weight,
- avg_factor=1.0)
- else:
- loss_bbox = bbox_pred.sum() * 0
- pos_bbox_weight = bbox_targets.new_tensor(0.)
-
- return loss_cls, loss_bbox, assign_metrics.sum(), pos_bbox_weight.sum()
-
- def loss_by_feat(self,
- cls_scores: List[Tensor],
- bbox_preds: List[Tensor],
- batch_gt_instances: InstanceList,
- batch_img_metas: List[dict],
- batch_gt_instances_ignore: OptInstanceList = None):
- """Compute losses of the head.
-
- Args:
- cls_scores (list[Tensor]): Box scores for each scale level
- Has shape (N, num_anchors * num_classes, H, W)
- bbox_preds (list[Tensor]): Decoded box for each scale
- level with shape (N, num_anchors * 4, H, W) in
- [tl_x, tl_y, br_x, br_y] format.
- batch_gt_instances (list[:obj:`InstanceData`]): Batch of
- gt_instance. It usually includes ``bboxes`` and ``labels``
- attributes.
- batch_img_metas (list[dict]): Meta information of each image, e.g.,
- image size, scaling factor, etc.
- batch_gt_instances_ignore (list[:obj:`InstanceData`], Optional):
- Batch of gt_instances_ignore. It includes ``bboxes`` attribute
- data that is ignored during training and testing.
- Defaults to None.
-
- Returns:
- dict[str, Tensor]: A dictionary of loss components.
- """
- num_imgs = len(batch_img_metas)
- featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]
- assert len(featmap_sizes) == self.prior_generator.num_levels
-
- device = cls_scores[0].device
- anchor_list, valid_flag_list = self.get_anchors(
- featmap_sizes, batch_img_metas, device=device)
- flatten_cls_scores = torch.cat([
- cls_score.permute(0, 2, 3, 1).reshape(num_imgs, -1,
- self.cls_out_channels)
- for cls_score in cls_scores
- ], 1)
- decoded_bboxes = []
- for anchor, bbox_pred in zip(anchor_list[0], bbox_preds):
- anchor = anchor.reshape(-1, 4)
- bbox_pred = bbox_pred.permute(0, 2, 3, 1).reshape(num_imgs, -1, 4)
- bbox_pred = distance2bbox(anchor, bbox_pred)
- decoded_bboxes.append(bbox_pred)
-
- flatten_bboxes = torch.cat(decoded_bboxes, 1)
-
- cls_reg_targets = self.get_targets(
- flatten_cls_scores,
- flatten_bboxes,
- anchor_list,
- valid_flag_list,
- batch_gt_instances,
- batch_img_metas,
- batch_gt_instances_ignore=batch_gt_instances_ignore)
- (anchor_list, labels_list, label_weights_list, bbox_targets_list,
- assign_metrics_list, sampling_results_list) = cls_reg_targets
-
- losses_cls, losses_bbox,\
- cls_avg_factors, bbox_avg_factors = multi_apply(
- self.loss_by_feat_single,
- cls_scores,
- decoded_bboxes,
- labels_list,
- label_weights_list,
- bbox_targets_list,
- assign_metrics_list,
- self.prior_generator.strides)
-
- cls_avg_factor = reduce_mean(sum(cls_avg_factors)).clamp_(min=1).item()
- losses_cls = list(map(lambda x: x / cls_avg_factor, losses_cls))
-
- bbox_avg_factor = reduce_mean(
- sum(bbox_avg_factors)).clamp_(min=1).item()
- losses_bbox = list(map(lambda x: x / bbox_avg_factor, losses_bbox))
- return dict(loss_cls=losses_cls, loss_bbox=losses_bbox)
-
- def get_targets(self,
- cls_scores: Tensor,
- bbox_preds: Tensor,
- anchor_list: List[List[Tensor]],
- valid_flag_list: List[List[Tensor]],
- batch_gt_instances: InstanceList,
- batch_img_metas: List[dict],
- batch_gt_instances_ignore: OptInstanceList = None,
- unmap_outputs=True):
- """Compute regression and classification targets for anchors in
- multiple images.
-
- Args:
- cls_scores (Tensor): Classification predictions of images,
- a 3D-Tensor with shape [num_imgs, num_priors, num_classes].
- bbox_preds (Tensor): Decoded bboxes predictions of one image,
- a 3D-Tensor with shape [num_imgs, num_priors, 4] in [tl_x,
- tl_y, br_x, br_y] format.
- anchor_list (list[list[Tensor]]): Multi level anchors of each
- image. The outer list indicates images, and the inner list
- corresponds to feature levels of the image. Each element of
- the inner list is a tensor of shape (num_anchors, 4).
- valid_flag_list (list[list[Tensor]]): Multi level valid flags of
- each image. The outer list indicates images, and the inner list
- corresponds to feature levels of the image. Each element of
- the inner list is a tensor of shape (num_anchors, )
- batch_gt_instances (list[:obj:`InstanceData`]): Batch of
- gt_instance. It usually includes ``bboxes`` and ``labels``
- attributes.
- batch_img_metas (list[dict]): Meta information of each image, e.g.,
- image size, scaling factor, etc.
- batch_gt_instances_ignore (list[:obj:`InstanceData`], Optional):
- Batch of gt_instances_ignore. It includes ``bboxes`` attribute
- data that is ignored during training and testing.
- Defaults to None.
- unmap_outputs (bool): Whether to map outputs back to the original
- set of anchors. Defaults to True.
-
- Returns:
- tuple: a tuple containing learning targets.
-
- - anchors_list (list[list[Tensor]]): Anchors of each level.
- - labels_list (list[Tensor]): Labels of each level.
- - label_weights_list (list[Tensor]): Label weights of each
- level.
- - bbox_targets_list (list[Tensor]): BBox targets of each level.
- - assign_metrics_list (list[Tensor]): alignment metrics of each
- level.
- """
- num_imgs = len(batch_img_metas)
- assert len(anchor_list) == len(valid_flag_list) == num_imgs
-
- # anchor number of multi levels
- num_level_anchors = [anchors.size(0) for anchors in anchor_list[0]]
-
- # concat all level anchors and flags to a single tensor
- for i in range(num_imgs):
- assert len(anchor_list[i]) == len(valid_flag_list[i])
- anchor_list[i] = torch.cat(anchor_list[i])
- valid_flag_list[i] = torch.cat(valid_flag_list[i])
-
- # compute targets for each image
- if batch_gt_instances_ignore is None:
- batch_gt_instances_ignore = [None] * num_imgs
- # anchor_list: list(b * [-1, 4])
- (all_anchors, all_labels, all_label_weights, all_bbox_targets,
- all_assign_metrics, sampling_results_list) = multi_apply(
- self._get_targets_single,
- cls_scores.detach(),
- bbox_preds.detach(),
- anchor_list,
- valid_flag_list,
- batch_gt_instances,
- batch_img_metas,
- batch_gt_instances_ignore,
- unmap_outputs=unmap_outputs)
- # no valid anchors
- if any([labels is None for labels in all_labels]):
- return None
-
- # split targets to a list w.r.t. multiple levels
- anchors_list = images_to_levels(all_anchors, num_level_anchors)
- labels_list = images_to_levels(all_labels, num_level_anchors)
- label_weights_list = images_to_levels(all_label_weights,
- num_level_anchors)
- bbox_targets_list = images_to_levels(all_bbox_targets,
- num_level_anchors)
- assign_metrics_list = images_to_levels(all_assign_metrics,
- num_level_anchors)
-
- return (anchors_list, labels_list, label_weights_list,
- bbox_targets_list, assign_metrics_list, sampling_results_list)
-
- def _get_targets_single(self,
- cls_scores: Tensor,
- bbox_preds: Tensor,
- flat_anchors: Tensor,
- valid_flags: Tensor,
- gt_instances: InstanceData,
- img_meta: dict,
- gt_instances_ignore: Optional[InstanceData] = None,
- unmap_outputs=True):
- """Compute regression, classification targets for anchors in a single
- image.
-
- Args:
- cls_scores (list(Tensor)): Box scores for each image.
- bbox_preds (list(Tensor)): Box energies / deltas for each image.
- flat_anchors (Tensor): Multi-level anchors of the image, which are
- concatenated into a single tensor of shape (num_anchors ,4)
- valid_flags (Tensor): Multi level valid flags of the image,
- which are concatenated into a single tensor of
- shape (num_anchors,).
- gt_instances (:obj:`InstanceData`): Ground truth of instance
- annotations. It usually includes ``bboxes`` and ``labels``
- attributes.
- img_meta (dict): Meta information for current image.
- gt_instances_ignore (:obj:`InstanceData`, optional): Instances
- to be ignored during training. It includes ``bboxes`` attribute
- data that is ignored during training and testing.
- Defaults to None.
- unmap_outputs (bool): Whether to map outputs back to the original
- set of anchors. Defaults to True.
-
- Returns:
- tuple: N is the number of total anchors in the image.
-
- - anchors (Tensor): All anchors in the image with shape (N, 4).
- - labels (Tensor): Labels of all anchors in the image with shape
- (N,).
- - label_weights (Tensor): Label weights of all anchor in the
- image with shape (N,).
- - bbox_targets (Tensor): BBox targets of all anchors in the
- image with shape (N, 4).
- - norm_alignment_metrics (Tensor): Normalized alignment metrics
- of all priors in the image with shape (N,).
- """
- inside_flags = anchor_inside_flags(flat_anchors, valid_flags,
- img_meta['img_shape'][:2],
- self.train_cfg['allowed_border'])
- if not inside_flags.any():
- return (None, ) * 7
- # assign gt and sample anchors
- anchors = flat_anchors[inside_flags, :]
-
- pred_instances = InstanceData(
- scores=cls_scores[inside_flags, :],
- bboxes=bbox_preds[inside_flags, :],
- priors=anchors)
-
- assign_result = self.assigner.assign(pred_instances, gt_instances,
- gt_instances_ignore)
-
- sampling_result = self.sampler.sample(assign_result, pred_instances,
- gt_instances)
-
- num_valid_anchors = anchors.shape[0]
- bbox_targets = torch.zeros_like(anchors)
- labels = anchors.new_full((num_valid_anchors, ),
- self.num_classes,
- dtype=torch.long)
- label_weights = anchors.new_zeros(num_valid_anchors, dtype=torch.float)
- assign_metrics = anchors.new_zeros(
- num_valid_anchors, dtype=torch.float)
-
- pos_inds = sampling_result.pos_inds
- neg_inds = sampling_result.neg_inds
- if len(pos_inds) > 0:
- # point-based
- pos_bbox_targets = sampling_result.pos_gt_bboxes
- bbox_targets[pos_inds, :] = pos_bbox_targets
-
- labels[pos_inds] = sampling_result.pos_gt_labels
- if self.train_cfg['pos_weight'] <= 0:
- label_weights[pos_inds] = 1.0
- else:
- label_weights[pos_inds] = self.train_cfg['pos_weight']
- if len(neg_inds) > 0:
- label_weights[neg_inds] = 1.0
-
- class_assigned_gt_inds = torch.unique(
- sampling_result.pos_assigned_gt_inds)
- for gt_inds in class_assigned_gt_inds:
- gt_class_inds = pos_inds[sampling_result.pos_assigned_gt_inds ==
- gt_inds]
- assign_metrics[gt_class_inds] = assign_result.max_overlaps[
- gt_class_inds]
-
- # map up to original set of anchors
- if unmap_outputs:
- num_total_anchors = flat_anchors.size(0)
- anchors = unmap(anchors, num_total_anchors, inside_flags)
- labels = unmap(
- labels, num_total_anchors, inside_flags, fill=self.num_classes)
- label_weights = unmap(label_weights, num_total_anchors,
- inside_flags)
- bbox_targets = unmap(bbox_targets, num_total_anchors, inside_flags)
- assign_metrics = unmap(assign_metrics, num_total_anchors,
- inside_flags)
- return (anchors, labels, label_weights, bbox_targets, assign_metrics,
- sampling_result)
-
- def get_anchors(self,
- featmap_sizes: List[tuple],
- batch_img_metas: List[dict],
- device: Union[torch.device, str] = 'cuda') \
- -> Tuple[List[List[Tensor]], List[List[Tensor]]]:
- """Get anchors according to feature map sizes.
-
- Args:
- featmap_sizes (list[tuple]): Multi-level feature map sizes.
- batch_img_metas (list[dict]): Image meta info.
- device (torch.device or str): Device for returned tensors.
- Defaults to cuda.
-
- Returns:
- tuple:
-
- - anchor_list (list[list[Tensor]]): Anchors of each image.
- - valid_flag_list (list[list[Tensor]]): Valid flags of each
- image.
- """
- num_imgs = len(batch_img_metas)
-
- # since feature map sizes of all images are the same, we only compute
- # anchors for one time
- multi_level_anchors = self.prior_generator.grid_priors(
- featmap_sizes, device=device, with_stride=True)
- anchor_list = [multi_level_anchors for _ in range(num_imgs)]
-
- # for each image, we compute valid flags of multi level anchors
- valid_flag_list = []
- for img_id, img_meta in enumerate(batch_img_metas):
- multi_level_flags = self.prior_generator.valid_flags(
- featmap_sizes, img_meta['pad_shape'], device)
- valid_flag_list.append(multi_level_flags)
- return anchor_list, valid_flag_list
-
-
-@MODELS.register_module()
-class RTMDetSepBNHead(RTMDetHead):
- """RTMDetHead with separated BN layers and shared conv layers.
-
- Args:
- num_classes (int): Number of categories excluding the background
- category.
- in_channels (int): Number of channels in the input feature map.
- share_conv (bool): Whether to share conv layers between stages.
- Defaults to True.
- use_depthwise (bool): Whether to use depthwise separable convolution in
- head. Defaults to False.
- norm_cfg (:obj:`ConfigDict` or dict)): Config dict for normalization
- layer. Defaults to dict(type='BN', momentum=0.03, eps=0.001).
- act_cfg (:obj:`ConfigDict` or dict)): Config dict for activation layer.
- Defaults to dict(type='SiLU').
- pred_kernel_size (int): Kernel size of prediction layer. Defaults to 1.
- """
-
- def __init__(self,
- num_classes: int,
- in_channels: int,
- share_conv: bool = True,
- use_depthwise: bool = False,
- norm_cfg: ConfigType = dict(
- type='BN', momentum=0.03, eps=0.001),
- act_cfg: ConfigType = dict(type='SiLU'),
- pred_kernel_size: int = 1,
- exp_on_reg=False,
- **kwargs) -> None:
- self.share_conv = share_conv
- self.exp_on_reg = exp_on_reg
- self.use_depthwise = use_depthwise
- super().__init__(
- num_classes,
- in_channels,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg,
- pred_kernel_size=pred_kernel_size,
- **kwargs)
-
- def _init_layers(self) -> None:
- """Initialize layers of the head."""
- conv = DepthwiseSeparableConvModule \
- if self.use_depthwise else ConvModule
- self.cls_convs = nn.ModuleList()
- self.reg_convs = nn.ModuleList()
-
- self.rtm_cls = nn.ModuleList()
- self.rtm_reg = nn.ModuleList()
- if self.with_objectness:
- self.rtm_obj = nn.ModuleList()
- for n in range(len(self.prior_generator.strides)):
- cls_convs = nn.ModuleList()
- reg_convs = nn.ModuleList()
- for i in range(self.stacked_convs):
- chn = self.in_channels if i == 0 else self.feat_channels
- cls_convs.append(
- conv(
- chn,
- self.feat_channels,
- 3,
- stride=1,
- padding=1,
- conv_cfg=self.conv_cfg,
- norm_cfg=self.norm_cfg,
- act_cfg=self.act_cfg))
- reg_convs.append(
- conv(
- chn,
- self.feat_channels,
- 3,
- stride=1,
- padding=1,
- conv_cfg=self.conv_cfg,
- norm_cfg=self.norm_cfg,
- act_cfg=self.act_cfg))
- self.cls_convs.append(cls_convs)
- self.reg_convs.append(reg_convs)
-
- self.rtm_cls.append(
- nn.Conv2d(
- self.feat_channels,
- self.num_base_priors * self.cls_out_channels,
- self.pred_kernel_size,
- padding=self.pred_kernel_size // 2))
- self.rtm_reg.append(
- nn.Conv2d(
- self.feat_channels,
- self.num_base_priors * 4,
- self.pred_kernel_size,
- padding=self.pred_kernel_size // 2))
- if self.with_objectness:
- self.rtm_obj.append(
- nn.Conv2d(
- self.feat_channels,
- 1,
- self.pred_kernel_size,
- padding=self.pred_kernel_size // 2))
-
- if self.share_conv:
- for n in range(len(self.prior_generator.strides)):
- for i in range(self.stacked_convs):
- self.cls_convs[n][i].conv = self.cls_convs[0][i].conv
- self.reg_convs[n][i].conv = self.reg_convs[0][i].conv
-
- def init_weights(self) -> None:
- """Initialize weights of the head."""
- for m in self.modules():
- if isinstance(m, nn.Conv2d):
- normal_init(m, mean=0, std=0.01)
- if is_norm(m):
- constant_init(m, 1)
- bias_cls = bias_init_with_prob(0.01)
- for rtm_cls, rtm_reg in zip(self.rtm_cls, self.rtm_reg):
- normal_init(rtm_cls, std=0.01, bias=bias_cls)
- normal_init(rtm_reg, std=0.01)
- if self.with_objectness:
- for rtm_obj in self.rtm_obj:
- normal_init(rtm_obj, std=0.01, bias=bias_cls)
-
- def forward(self, feats: Tuple[Tensor, ...]) -> tuple:
- """Forward features from the upstream network.
-
- Args:
- feats (tuple[Tensor]): Features from the upstream network, each is
- a 4D-tensor.
-
- Returns:
- tuple: Usually a tuple of classification scores and bbox prediction
-
- - cls_scores (tuple[Tensor]): Classification scores for all scale
- levels, each is a 4D-tensor, the channels number is
- num_anchors * num_classes.
- - bbox_preds (tuple[Tensor]): Box energies / deltas for all scale
- levels, each is a 4D-tensor, the channels number is
- num_anchors * 4.
- """
-
- cls_scores = []
- bbox_preds = []
- for idx, (x, stride) in enumerate(
- zip(feats, self.prior_generator.strides)):
- cls_feat = x
- reg_feat = x
-
- for cls_layer in self.cls_convs[idx]:
- cls_feat = cls_layer(cls_feat)
- cls_score = self.rtm_cls[idx](cls_feat)
-
- for reg_layer in self.reg_convs[idx]:
- reg_feat = reg_layer(reg_feat)
-
- if self.with_objectness:
- objectness = self.rtm_obj[idx](reg_feat)
- cls_score = inverse_sigmoid(
- sigmoid_geometric_mean(cls_score, objectness))
- if self.exp_on_reg:
- reg_dist = self.rtm_reg[idx](reg_feat).exp() * stride[0]
- else:
- reg_dist = self.rtm_reg[idx](reg_feat) * stride[0]
- cls_scores.append(cls_score)
- bbox_preds.append(reg_dist)
- return tuple(cls_scores), tuple(bbox_preds)
diff --git a/spaces/Lamai/LAMAIGPT/Dockerfile b/spaces/Lamai/LAMAIGPT/Dockerfile
deleted file mode 100644
index 8396154998f32a50d55c199a674b638d5cf7bda2..0000000000000000000000000000000000000000
--- a/spaces/Lamai/LAMAIGPT/Dockerfile
+++ /dev/null
@@ -1,38 +0,0 @@
-# Use an official Python base image from the Docker Hub
-FROM python:3.10-slim
-
-# Install git
-RUN apt-get -y update
-RUN apt-get -y install git chromium-driver
-
-# Install Xvfb and other dependencies for headless browser testing
-RUN apt-get update \
- && apt-get install -y wget gnupg2 libgtk-3-0 libdbus-glib-1-2 dbus-x11 xvfb ca-certificates
-
-# Install Firefox / Chromium
-RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
- && echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list \
- && apt-get update \
- && apt-get install -y chromium firefox-esr
-
-# Set environment variables
-ENV PIP_NO_CACHE_DIR=yes \
- PYTHONUNBUFFERED=1 \
- PYTHONDONTWRITEBYTECODE=1
-
-# Create a non-root user and set permissions
-RUN useradd --create-home appuser
-WORKDIR /home/appuser
-RUN chown appuser:appuser /home/appuser
-USER appuser
-
-# Copy the requirements.txt file and install the requirements
-COPY --chown=appuser:appuser requirements.txt .
-RUN sed -i '/Items below this point will not be included in the Docker Image/,$d' requirements.txt && \
- pip install --no-cache-dir --user -r requirements.txt
-
-# Copy the application files
-COPY --chown=appuser:appuser autogpt/ ./autogpt
-
-# Set the entrypoint
-ENTRYPOINT ["python", "-m", "autogpt"]
diff --git a/spaces/LayBraid/SpaceVector_v0/text_to_image.py b/spaces/LayBraid/SpaceVector_v0/text_to_image.py
deleted file mode 100644
index 313a8d7f72ca729609e7160324b194c31a851400..0000000000000000000000000000000000000000
--- a/spaces/LayBraid/SpaceVector_v0/text_to_image.py
+++ /dev/null
@@ -1,71 +0,0 @@
-import json
-import os
-import numpy as np
-import streamlit as st
-from PIL import Image
-from transformers import CLIPProcessor, FlaxCLIPModel
-import nmslib
-
-
-def load_index(image_vector_file):
- filenames, image_vecs = [], []
- fvec = open(image_vector_file, "r")
- for line in fvec:
- cols = line.strip().split(' ')
- filename = cols[0]
- image_vec = np.array([float(x) for x in cols[1].split(',')])
- filenames.append(filename)
- image_vecs.append(image_vec)
- V = np.array(image_vecs)
- index = nmslib.init(method='hnsw', space='cosinesimil')
- index.addDataPointBatch(V)
- index.createIndex({'post': 2}, print_progress=True)
- return filenames, index
-
-
-def load_captions(caption_file):
- image2caption = {}
- with open(caption_file, "r") as fcap:
- for line in fcap:
- data = json.loads(line.strip())
- filename = data["filename"]
- captions = data["captions"]
- image2caption[filename] = captions
- return image2caption
-
-
-def get_image(text, number):
- model = FlaxCLIPModel.from_pretrained("flax-community/clip-rsicd-v2")
- processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
- filename, index = load_index("./vectors/test-bs128x8-lr5e-6-adam-ckpt-1.tsv")
- image2caption = load_captions("./images/test-captions.json")
-
- inputs = processor(text=[text], images=None, return_tensors="jax", padding=True)
-
- vector = model.get_text_features(**inputs)
- vector = np.asarray(vector)
- ids, distances = index.knnQuery(vector, k=number)
- result_filenames = [filename[index] for index in ids]
- for rank, (result_filename, score) in enumerate(zip(result_filenames, distances)):
- caption = "{:s} (score: {:.3f})".format(result_filename, 1.0 - score)
- col1, col2, col3 = st.columns([2, 10, 10])
- col1.markdown("{:d}.".format(rank + 1))
- col2.image(Image.open(os.path.join("./images", result_filename)),
- caption=caption)
- # caption_text = []
- # for caption in image2caption[result_filename]:
- # caption_text.append("* {:s}".format(caption))
- # col3.markdown("".join(caption_text))
- st.markdown("---")
- suggest_idx = -1
-
-
-def app():
- st.title("Welcome to Space Vector")
- st.text("You want search an image with given text.")
-
- text = st.text_input("Enter text: ")
- number = st.number_input("Enter number of images result: ", min_value=1, max_value=10)
-
- if st.button("Search"):
- get_image(text, number)
diff --git a/spaces/Lbin123/Lbingo/src/components/chat-history.tsx b/spaces/Lbin123/Lbingo/src/components/chat-history.tsx
deleted file mode 100644
index feb81de66562edda8f40d3c0cc717202c92b6509..0000000000000000000000000000000000000000
--- a/spaces/Lbin123/Lbingo/src/components/chat-history.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import { IconEdit, IconTrash, IconMore, IconDownload } from "./ui/icons"
-
-export function ChatHistory() {
- return (
-
-
- 历史记录
-
-
-
-
-
-
-
-
-
-
无标题的聊天
-
-
上午1:42
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- )
-}
diff --git a/spaces/Lianjd/stock_dashboard/backtrader/observers/benchmark.py b/spaces/Lianjd/stock_dashboard/backtrader/observers/benchmark.py
deleted file mode 100644
index f7056ab25ad90481d8aa15bfd7dbc66c04b7c3ea..0000000000000000000000000000000000000000
--- a/spaces/Lianjd/stock_dashboard/backtrader/observers/benchmark.py
+++ /dev/null
@@ -1,119 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8; py-indent-offset:4 -*-
-###############################################################################
-#
-# Copyright (C) 2015-2020 Daniel Rodriguez
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see .
-#
-###############################################################################
-from __future__ import (absolute_import, division, print_function,
- unicode_literals)
-
-import backtrader as bt
-from . import TimeReturn
-
-
-class Benchmark(TimeReturn):
- '''This observer stores the *returns* of the strategy and the *return* of a
- reference asset which is one of the datas passed to the system.
-
- Params:
-
- - ``timeframe`` (default: ``None``)
- If ``None`` then the complete return over the entire backtested period
- will be reported
-
- - ``compression`` (default: ``None``)
-
- Only used for sub-day timeframes to for example work on an hourly
- timeframe by specifying "TimeFrame.Minutes" and 60 as compression
-
- - ``data`` (default: ``None``)
-
- Reference asset to track to allow for comparison.
-
- .. note:: this data must have been added to a ``cerebro`` instance with
- ``addata``, ``resampledata`` or ``replaydata``.
-
-
- - ``_doprenext`` (default: ``False``)
-
- Benchmarking will take place from the point at which the strategy kicks
- in (i.e.: when the minimum period of the strategy has been met).
-
- Setting this to ``True`` will record benchmarking values from the
- starting point of the data feeds
-
- - ``firstopen`` (default: ``False``)
-
- Keepint it as ``False`` ensures that the 1st comparison point between
- the value and the benchmark starts at 0%, because the benchmark will
- not use its opening price.
-
- See the ``TimeReturn`` analyzer reference for a full explanation of the
- meaning of the parameter
-
- - ``fund`` (default: ``None``)
-
- If ``None`` the actual mode of the broker (fundmode - True/False) will
- be autodetected to decide if the returns are based on the total net
- asset value or on the fund value. See ``set_fundmode`` in the broker
- documentation
-
- Set it to ``True`` or ``False`` for a specific behavior
-
- Remember that at any moment of a ``run`` the current values can be checked
- by looking at the *lines* by name at index ``0``.
-
- '''
- _stclock = True
-
- lines = ('benchmark',)
- plotlines = dict(benchmark=dict(_name='Benchmark'))
-
- params = (
- ('data', None),
- ('_doprenext', False),
- # Set to false to ensure the asset is measured at 0% in the 1st tick
- ('firstopen', False),
- ('fund', None)
- )
-
- def _plotlabel(self):
- labels = super(Benchmark, self)._plotlabel()
- labels.append(self.p.data._name)
- return labels
-
- def __init__(self):
- if self.p.data is None: # use the 1st data in the system if none given
- self.p.data = self.data0
-
- super(Benchmark, self).__init__() # treturn including data parameter
- # Create a time return object without the data
- kwargs = self.p._getkwargs()
- kwargs.update(data=None) # to create a return for the stratey
- t = self._owner._addanalyzer_slave(bt.analyzers.TimeReturn, **kwargs)
-
- # swap for consistency
- self.treturn, self.tbench = t, self.treturn
-
- def next(self):
- super(Benchmark, self).next()
- self.lines.benchmark[0] = self.tbench.rets.get(self.treturn.dtkey,
- float('NaN'))
-
- def prenext(self):
- if self.p._doprenext:
- super(TimeReturn, self).prenext()
diff --git a/spaces/Liu-LAB/GPT-academic/crazy_functions/test_project/cpp/libJPG/jpge.h b/spaces/Liu-LAB/GPT-academic/crazy_functions/test_project/cpp/libJPG/jpge.h
deleted file mode 100644
index a46c805ab80aab491f7f9508b3a008b149866bee..0000000000000000000000000000000000000000
--- a/spaces/Liu-LAB/GPT-academic/crazy_functions/test_project/cpp/libJPG/jpge.h
+++ /dev/null
@@ -1,172 +0,0 @@
-
-// jpge.h - C++ class for JPEG compression.
-// Public domain, Rich Geldreich
-// Alex Evans: Added RGBA support, linear memory allocator.
-#ifndef JPEG_ENCODER_H
-#define JPEG_ENCODER_H
-
-#include
-
-namespace jpge
-{
- typedef unsigned char uint8;
- typedef signed short int16;
- typedef signed int int32;
- typedef unsigned short uint16;
- typedef unsigned int uint32;
- typedef unsigned int uint;
-
- // JPEG chroma subsampling factors. Y_ONLY (grayscale images) and H2V2 (color images) are the most common.
- enum subsampling_t { Y_ONLY = 0, H1V1 = 1, H2V1 = 2, H2V2 = 3 };
-
- // JPEG compression parameters structure.
- struct params
- {
- inline params() : m_quality(85), m_subsampling(H2V2), m_no_chroma_discrim_flag(false), m_two_pass_flag(false) { }
-
- inline bool check_valid() const
- {
- if ((m_quality < 1) || (m_quality > 100)) return false;
- if ((uint)m_subsampling > (uint)H2V2) return false;
- return true;
- }
-
- // Quality: 1-100, higher is better. Typical values are around 50-95.
- int m_quality;
-
- // m_subsampling:
- // 0 = Y (grayscale) only
- // 1 = YCbCr, no subsampling (H1V1, YCbCr 1x1x1, 3 blocks per MCU)
- // 2 = YCbCr, H2V1 subsampling (YCbCr 2x1x1, 4 blocks per MCU)
- // 3 = YCbCr, H2V2 subsampling (YCbCr 4x1x1, 6 blocks per MCU-- very common)
- subsampling_t m_subsampling;
-
- // Disables CbCr discrimination - only intended for testing.
- // If true, the Y quantization table is also used for the CbCr channels.
- bool m_no_chroma_discrim_flag;
-
- bool m_two_pass_flag;
- };
-
- // Writes JPEG image to a file.
- // num_channels must be 1 (Y) or 3 (RGB), image pitch must be width*num_channels.
- bool compress_image_to_jpeg_file(const char *pFilename, int64_t width, int64_t height, int64_t num_channels, const uint8 *pImage_data, const params &comp_params = params());
-
- // Writes JPEG image to memory buffer.
- // On entry, buf_size is the size of the output buffer pointed at by pBuf, which should be at least ~1024 bytes.
- // If return value is true, buf_size will be set to the size of the compressed data.
- bool compress_image_to_jpeg_file_in_memory(void *pBuf, int64_t &buf_size, int64_t width, int64_t height, int64_t num_channels, const uint8 *pImage_data, const params &comp_params = params());
-
- // Output stream abstract class - used by the jpeg_encoder class to write to the output stream.
- // put_buf() is generally called with len==JPGE_OUT_BUF_SIZE bytes, but for headers it'll be called with smaller amounts.
- class output_stream
- {
- public:
- virtual ~output_stream() { };
- virtual bool put_buf(const void* Pbuf, int64_t len) = 0;
- template inline bool put_obj(const T& obj) { return put_buf(&obj, sizeof(T)); }
- };
-
- // Lower level jpeg_encoder class - useful if more control is needed than the above helper functions.
- class jpeg_encoder
- {
- public:
- jpeg_encoder();
- ~jpeg_encoder();
-
- // Initializes the compressor.
- // pStream: The stream object to use for writing compressed data.
- // params - Compression parameters structure, defined above.
- // width, height - Image dimensions.
- // channels - May be 1, or 3. 1 indicates grayscale, 3 indicates RGB source data.
- // Returns false on out of memory or if a stream write fails.
- bool init(output_stream *pStream, int64_t width, int64_t height, int64_t src_channels, const params &comp_params = params());
-
- const params &get_params() const { return m_params; }
-
- // Deinitializes the compressor, freeing any allocated memory. May be called at any time.
- void deinit();
-
- uint get_total_passes() const { return m_params.m_two_pass_flag ? 2 : 1; }
- inline uint get_cur_pass() { return m_pass_num; }
-
- // Call this method with each source scanline.
- // width * src_channels bytes per scanline is expected (RGB or Y format).
- // You must call with NULL after all scanlines are processed to finish compression.
- // Returns false on out of memory or if a stream write fails.
- bool process_scanline(const void* pScanline);
-
- private:
- jpeg_encoder(const jpeg_encoder &);
- jpeg_encoder &operator =(const jpeg_encoder &);
-
- typedef int32 sample_array_t;
-
- output_stream *m_pStream;
- params m_params;
- uint8 m_num_components;
- uint8 m_comp_h_samp[3], m_comp_v_samp[3];
- int m_image_x, m_image_y, m_image_bpp, m_image_bpl;
- int m_image_x_mcu, m_image_y_mcu;
- int m_image_bpl_xlt, m_image_bpl_mcu;
- int m_mcus_per_row;
- int m_mcu_x, m_mcu_y;
- uint8 *m_mcu_lines[16];
- uint8 m_mcu_y_ofs;
- sample_array_t m_sample_array[64];
- int16 m_coefficient_array[64];
- int32 m_quantization_tables[2][64];
- uint m_huff_codes[4][256];
- uint8 m_huff_code_sizes[4][256];
- uint8 m_huff_bits[4][17];
- uint8 m_huff_val[4][256];
- uint32 m_huff_count[4][256];
- int m_last_dc_val[3];
- enum { JPGE_OUT_BUF_SIZE = 2048 };
- uint8 m_out_buf[JPGE_OUT_BUF_SIZE];
- uint8 *m_pOut_buf;
- uint m_out_buf_left;
- uint32 m_bit_buffer;
- uint m_bits_in;
- uint8 m_pass_num;
- bool m_all_stream_writes_succeeded;
-
- void optimize_huffman_table(int table_num, int table_len);
- void emit_byte(uint8 i);
- void emit_word(uint i);
- void emit_marker(int marker);
- void emit_jfif_app0();
- void emit_dqt();
- void emit_sof();
- void emit_dht(uint8 *bits, uint8 *val, int index, bool ac_flag);
- void emit_dhts();
- void emit_sos();
- void emit_markers();
- void compute_huffman_table(uint *codes, uint8 *code_sizes, uint8 *bits, uint8 *val);
- void compute_quant_table(int32 *dst, int16 *src);
- void adjust_quant_table(int32 *dst, int32 *src);
- void first_pass_init();
- bool second_pass_init();
- bool jpg_open(int p_x_res, int p_y_res, int src_channels);
- void load_block_8_8_grey(int x);
- void load_block_8_8(int x, int y, int c);
- void load_block_16_8(int x, int c);
- void load_block_16_8_8(int x, int c);
- void load_quantized_coefficients(int component_num);
- void flush_output_buffer();
- void put_bits(uint bits, uint len);
- void code_coefficients_pass_one(int component_num);
- void code_coefficients_pass_two(int component_num);
- void code_block(int component_num);
- void process_mcu_row();
- bool terminate_pass_one();
- bool terminate_pass_two();
- bool process_end_of_image();
- void load_mcu(const void* src);
- void clear();
- void init();
- };
-
-} // namespace jpge
-
-#endif // JPEG_ENCODER
\ No newline at end of file
diff --git a/spaces/LuxOAI/ChatGpt-Web/.github/ISSUE_TEMPLATE/bug_report.md b/spaces/LuxOAI/ChatGpt-Web/.github/ISSUE_TEMPLATE/bug_report.md
deleted file mode 100644
index 01fa35e8230e4c93d27005266a95a47a0d612ffb..0000000000000000000000000000000000000000
--- a/spaces/LuxOAI/ChatGpt-Web/.github/ISSUE_TEMPLATE/bug_report.md
+++ /dev/null
@@ -1,43 +0,0 @@
----
-name: Bug report
-about: Create a report to help us improve
-title: "[Bug] "
-labels: ''
-assignees: ''
-
----
-
-**Describe the bug**
-A clear and concise description of what the bug is.
-
-**To Reproduce**
-Steps to reproduce the behavior:
-1. Go to '...'
-2. Click on '....'
-3. Scroll down to '....'
-4. See error
-
-**Expected behavior**
-A clear and concise description of what you expected to happen.
-
-**Screenshots**
-If applicable, add screenshots to help explain your problem.
-
-**Deployment**
-- [ ] Docker
-- [ ] Vercel
-- [ ] Server
-
-**Desktop (please complete the following information):**
- - OS: [e.g. iOS]
- - Browser [e.g. chrome, safari]
- - Version [e.g. 22]
-
-**Smartphone (please complete the following information):**
- - Device: [e.g. iPhone6]
- - OS: [e.g. iOS8.1]
- - Browser [e.g. stock browser, safari]
- - Version [e.g. 22]
-
-**Additional Logs**
-Add any logs about the problem here.
diff --git a/spaces/ML701G7/taim-gan/src/models/utils.py b/spaces/ML701G7/taim-gan/src/models/utils.py
deleted file mode 100644
index 41c58aa74447fca5269d8112a1bdf3dfe875becb..0000000000000000000000000000000000000000
--- a/spaces/ML701G7/taim-gan/src/models/utils.py
+++ /dev/null
@@ -1,276 +0,0 @@
-"""Helper functions for models."""
-
-import pathlib
-import pickle
-from copy import deepcopy
-from pathlib import Path
-from typing import Any, List, Dict
-
-import matplotlib.pyplot as plt
-import numpy as np
-import torch
-from PIL import Image
-from torch import optim
-
-from src.models.modules.discriminator import Discriminator
-from src.models.modules.generator import Generator
-from src.models.modules.image_encoder import InceptionEncoder
-from src.models.modules.text_encoder import TextEncoder
-
-# pylint: disable=too-many-arguments
-# pylint: disable=too-many-locals
-
-
-def copy_gen_params(generator: Generator) -> Any:
- """
- Function to copy the parameters of the generator
- """
- params = deepcopy(list(p.data for p in generator.parameters()))
- return params
-
-
-def define_optimizers(
- generator: Generator,
- discriminator: Discriminator,
- image_encoder: InceptionEncoder,
- text_encoder: TextEncoder,
- lr_config: Dict[str, float],
-) -> Any:
- """
- Function to define the optimizers for the generator and discriminator
- :param generator: Generator model
- :param image_encoder: Image encoder model
- :param text_encoder: Text encoder model
- :param discriminator: Discriminator model
- :param lr_config: Dictionary containing the learning rates for the optimizers
-
- """
- img_encoder_lr = lr_config["img_encoder_lr"]
- text_encoder_lr = lr_config["text_encoder_lr"]
- gen_lr = lr_config["gen_lr"]
- disc_lr = lr_config["disc_lr"]
-
- optimizer_g = optim.Adam(
- [{"params": generator.parameters()}],
- lr=gen_lr,
- betas=(0.5, 0.999),
- )
- optimizer_d = optim.Adam(
- [{"params": discriminator.parameters()}],
- lr=disc_lr,
- betas=(0.5, 0.999),
- )
- optimizer_text_encoder = optim.Adam(text_encoder.parameters(), lr=text_encoder_lr)
- optimizer_image_encoder = optim.Adam(image_encoder.parameters(), lr=img_encoder_lr)
-
- return optimizer_g, optimizer_d, optimizer_text_encoder, optimizer_image_encoder
-
-
-def prepare_labels(batch_size: int, max_seq_len: int, device: torch.device) -> Any:
- """
- Function to prepare the labels for the discriminator and generator.
- """
- real_labels = torch.FloatTensor(batch_size, 1).fill_(1).to(device)
- fake_labels = torch.FloatTensor(batch_size, 1).fill_(0).to(device)
- match_labels = torch.LongTensor(range(batch_size)).to(device)
- fake_word_labels = torch.FloatTensor(batch_size, max_seq_len).fill_(0).to(device)
-
- return real_labels, fake_labels, match_labels, fake_word_labels
-
-
-def load_params(generator: Generator, new_params: Any) -> Any:
- """
- Function to load new parameters to the generator
- """
- for param, new_p in zip(generator.parameters(), new_params):
- param.data.copy_(new_p)
-
-
-def get_image_arr(image_tensor: torch.Tensor) -> Any:
- """
- Function to convert a tensor to an image array.
- :param image_tensor: Tensor containing the image (shape: (batch_size, channels, height, width))
- """
-
- image = image_tensor.cpu().detach().numpy()
- image = (image + 1) * (255 / 2.0)
- image = np.transpose(image, (0, 2, 3, 1)) # (B,C,H,W) -> (B,H,W,C)
- image = image.astype(np.uint8)
- return image # (B,H,W,C)
-
-
-def get_captions(captions: torch.Tensor, ix2word: Dict[int, str]) -> Any:
- """
- Function to convert a tensor to a list of captions.
- :param captions: Tensor containing the captions (shape: (batch_size, max_seq_len))
- :param ix2word: Dictionary mapping indices to words
- """
- captions = captions.cpu().detach().numpy()
- captions = [[ix2word[ix] for ix in cap if ix != 0] for cap in captions] # type: ignore
- return captions
-
-
-def save_model(
- generator: Generator,
- discriminator: Discriminator,
- image_encoder: InceptionEncoder,
- text_encoder: TextEncoder,
- epoch: int,
- output_dir: pathlib.PosixPath,
-) -> None:
- """
- Function to save the model.
- :param generator: Generator model
- :param discriminator: Discriminator model
- :param image_encoder: Image encoder model
- :param text_encoder: Text encoder model
- :param params: Parameters of the generator
- :param epoch: Epoch number
- :param output_dir: Output directory
- """
- output_path = output_dir / "weights/"
- Path(output_path / "generator").mkdir(parents=True, exist_ok=True)
- torch.save(
- generator.state_dict(), output_path / f"generator/generator_epoch_{epoch}.pth"
- )
- Path(output_path / "discriminator").mkdir(parents=True, exist_ok=True)
- torch.save(
- discriminator.state_dict(),
- output_path / f"discriminator/discriminator_epoch_{epoch}.pth",
- )
- Path(output_path / "image_encoder").mkdir(parents=True, exist_ok=True)
- torch.save(
- image_encoder.state_dict(),
- output_path / f"image_encoder/image_encoder_epoch_{epoch}.pth",
- )
- Path(output_path / "text_encoder").mkdir(parents=True, exist_ok=True)
- torch.save(
- text_encoder.state_dict(),
- output_path / f"text_encoder/text_encoder_epoch_{epoch}.pth",
- )
- print(f"Model saved at epoch {epoch}.")
-
-
-def save_image_and_caption(
- fake_img_tensor: torch.Tensor,
- img_tensor: torch.Tensor,
- captions: torch.Tensor,
- ix2word: Dict[int, str],
- batch_idx: int,
- epoch: int,
- output_dir: pathlib.PosixPath,
-) -> None:
- """
- Function to save an image and its corresponding caption.
- :param fake_img_tensor: Tensor containing the generated image
- (shape: (batch_size, channels, height, width))
-
- :param img_tensor: Tensor containing the image
- (shape: (batch_size, channels, height, width))
-
- :param captions: Tensor containing the captions
- (shape: (batch_size, max_seq_len))
-
- :param ix2word: Dictionary mapping indices to words
- :param batch_idx: Batch index
- :param epoch: Epoch number
- :param output_dir: Output directory
- """
- output_path = output_dir
- output_path_text = output_dir
- capt_list = get_captions(captions, ix2word)
- img_arr = get_image_arr(img_tensor)
- fake_img_arr = get_image_arr(fake_img_tensor)
- for i in range(img_arr.shape[0]):
- img = Image.fromarray(img_arr[i])
- fake_img = Image.fromarray(fake_img_arr[i])
-
- fake_img_path = (
- output_path / f"generated/{epoch}_epochs/{batch_idx}_batch/{i+1}.png"
- )
- img_path = output_path / f"real/{epoch}_epochs/{batch_idx}_batch/{i+1}.png"
- text_path = (
- output_path_text / f"text/{epoch}_epochs/{batch_idx}_batch/captions.txt"
- )
-
- Path(fake_img_path).parent.mkdir(parents=True, exist_ok=True)
- Path(img_path).parent.mkdir(parents=True, exist_ok=True)
- Path(text_path).parent.mkdir(parents=True, exist_ok=True)
-
- fake_img.save(fake_img_path)
- img.save(img_path)
-
- with open(text_path, "a", encoding="utf-8") as txt_file:
- text_str = str(i + 1) + ": " + " ".join(capt_list[i])
- txt_file.write(text_str)
- txt_file.write("\n")
-
-
-def save_plot(
- gen_loss: List[float],
- disc_loss: List[float],
- epoch: int,
- batch_idx: int,
- output_dir: pathlib.PosixPath,
-) -> None:
- """
- Function to save the plot of the loss.
- :param gen_loss: List of generator losses
- :param disc_loss: List of discriminator losses
- :param epoch: Epoch number
- :param batch_idx: Batch index
- :param output_dir: Output directory
- """
- pickle_path = output_dir / "losses/"
- output_path = output_dir / "plots" / f"{epoch}_epochs/{batch_idx}_batch/"
- Path(output_path).mkdir(parents=True, exist_ok=True)
- Path(pickle_path).mkdir(parents=True, exist_ok=True)
-
- with open(pickle_path / "gen_loss.pkl", "wb") as pickl_file:
- pickle.dump(gen_loss, pickl_file)
-
- with open(pickle_path / "disc_loss.pkl", "wb") as pickl_file:
- pickle.dump(disc_loss, pickl_file)
-
- plt.style.use("fivethirtyeight")
- plt.figure(figsize=(24, 12))
- plt.plot(gen_loss, label="Generator Loss")
- plt.plot(disc_loss, label="Discriminator Loss")
- plt.xlabel("No of Iterations")
- plt.ylabel("Loss")
- plt.legend()
- plt.savefig(output_path / "loss.png", bbox_inches="tight")
- plt.clf()
- plt.close()
-
-
-def load_model(
- generator: Generator,
- discriminator: Discriminator,
- image_encoder: InceptionEncoder,
- text_encoder: TextEncoder,
- output_dir: pathlib.Path,
- device: torch.device
-) -> None:
- """
- Function to load the model.
- :param generator: Generator model
- :param discriminator: Discriminator model
- :param image_encoder: Image encoder model
- :param text_encoder: Text encoder model
- :param output_dir: Output directory
- :param device: device to map the location of weights
- """
- if (output_dir / "generator.pth").exists():
- generator.load_state_dict(torch.load(output_dir / "generator.pth", map_location=device))
- print("Generator loaded.")
- if (output_dir / "discriminator.pth").exists():
- discriminator.load_state_dict(torch.load(output_dir / "discriminator.pth", map_location=device))
- print("Discriminator loaded.")
- if (output_dir / "image_encoder.pth").exists():
- image_encoder.load_state_dict(torch.load(output_dir / "image_encoder.pth", map_location=device))
- print("Image Encoder loaded.")
-
- if (output_dir / "text_encoder.pth").exists():
- text_encoder.load_state_dict(torch.load(output_dir / "text_encoder.pth", map_location=device))
- print("Text Encoder loaded.")
diff --git a/spaces/Malifex/flax-anything-v3.0/app.py b/spaces/Malifex/flax-anything-v3.0/app.py
deleted file mode 100644
index 120baf3709c07893d9b78d99fa8e81050a795055..0000000000000000000000000000000000000000
--- a/spaces/Malifex/flax-anything-v3.0/app.py
+++ /dev/null
@@ -1,3 +0,0 @@
-import gradio as gr
-
-gr.Interface.load("models/flax/anything-v3.0").launch()
\ No newline at end of file
diff --git a/spaces/Marshalls/testmtd/misc/copy_chpt_to_jeanzay.sh b/spaces/Marshalls/testmtd/misc/copy_chpt_to_jeanzay.sh
deleted file mode 100644
index 2f99f8d6d65c71642db7f29efb2d7fdac6976b20..0000000000000000000000000000000000000000
--- a/spaces/Marshalls/testmtd/misc/copy_chpt_to_jeanzay.sh
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/bash
-exp=$1
-version=$2
-scp -r training/experiments/${exp}/version_${version}/* jeanzay:/gpfswork/rech/imi/usc19dv/mt-lightning/training/experiments/${exp}/version_${version}
diff --git a/spaces/Megatron17/RAQA_with_Langchain/Dockerfile b/spaces/Megatron17/RAQA_with_Langchain/Dockerfile
deleted file mode 100644
index 522424152001841ea27ee8a10bb84f63124e3b39..0000000000000000000000000000000000000000
--- a/spaces/Megatron17/RAQA_with_Langchain/Dockerfile
+++ /dev/null
@@ -1,11 +0,0 @@
-FROM python:3.10
-RUN useradd -m -u 1000 user
-USER user
-ENV HOME=/home/user \
- PATH=/home/user/.local/bin:$PATH
-WORKDIR $HOME/app
-COPY --chown=user . $HOME/app
-COPY ./requirements.txt ~/app/requirements.txt
-RUN pip install -r requirements.txt
-COPY . .
-CMD ["chainlit", "run", "app.py", "--port", "7860"]
\ No newline at end of file
diff --git a/spaces/Mellow-ai/PhotoAI_Mellow/is_net/isnet.py b/spaces/Mellow-ai/PhotoAI_Mellow/is_net/isnet.py
deleted file mode 100644
index 8be74bb03954496e6cb8af6e1c8e1cd2c0bbb80c..0000000000000000000000000000000000000000
--- a/spaces/Mellow-ai/PhotoAI_Mellow/is_net/isnet.py
+++ /dev/null
@@ -1,610 +0,0 @@
-import torch
-import torch.nn as nn
-from torchvision import models
-import torch.nn.functional as F
-
-
-bce_loss = nn.BCELoss(size_average=True)
-def muti_loss_fusion(preds, target):
- loss0 = 0.0
- loss = 0.0
-
- for i in range(0,len(preds)):
- # print("i: ", i, preds[i].shape)
- if(preds[i].shape[2]!=target.shape[2] or preds[i].shape[3]!=target.shape[3]):
- # tmp_target = _upsample_like(target,preds[i])
- tmp_target = F.interpolate(target, size=preds[i].size()[2:], mode='bilinear', align_corners=True)
- loss = loss + bce_loss(preds[i],tmp_target)
- else:
- loss = loss + bce_loss(preds[i],target)
- if(i==0):
- loss0 = loss
- return loss0, loss
-
-fea_loss = nn.MSELoss(size_average=True)
-kl_loss = nn.KLDivLoss(size_average=True)
-l1_loss = nn.L1Loss(size_average=True)
-smooth_l1_loss = nn.SmoothL1Loss(size_average=True)
-def muti_loss_fusion_kl(preds, target, dfs, fs, mode='MSE'):
- loss0 = 0.0
- loss = 0.0
-
- for i in range(0,len(preds)):
- # print("i: ", i, preds[i].shape)
- if(preds[i].shape[2]!=target.shape[2] or preds[i].shape[3]!=target.shape[3]):
- # tmp_target = _upsample_like(target,preds[i])
- tmp_target = F.interpolate(target, size=preds[i].size()[2:], mode='bilinear', align_corners=True)
- loss = loss + bce_loss(preds[i],tmp_target)
- else:
- loss = loss + bce_loss(preds[i],target)
- if(i==0):
- loss0 = loss
-
- for i in range(0,len(dfs)):
- if(mode=='MSE'):
- loss = loss + fea_loss(dfs[i],fs[i]) ### add the mse loss of features as additional constraints
- # print("fea_loss: ", fea_loss(dfs[i],fs[i]).item())
- elif(mode=='KL'):
- loss = loss + kl_loss(F.log_softmax(dfs[i],dim=1),F.softmax(fs[i],dim=1))
- # print("kl_loss: ", kl_loss(F.log_softmax(dfs[i],dim=1),F.softmax(fs[i],dim=1)).item())
- elif(mode=='MAE'):
- loss = loss + l1_loss(dfs[i],fs[i])
- # print("ls_loss: ", l1_loss(dfs[i],fs[i]))
- elif(mode=='SmoothL1'):
- loss = loss + smooth_l1_loss(dfs[i],fs[i])
- # print("SmoothL1: ", smooth_l1_loss(dfs[i],fs[i]).item())
-
- return loss0, loss
-
-class REBNCONV(nn.Module):
- def __init__(self,in_ch=3,out_ch=3,dirate=1,stride=1):
- super(REBNCONV,self).__init__()
-
- self.conv_s1 = nn.Conv2d(in_ch,out_ch,3,padding=1*dirate,dilation=1*dirate,stride=stride)
- self.bn_s1 = nn.BatchNorm2d(out_ch)
- self.relu_s1 = nn.ReLU(inplace=True)
-
- def forward(self,x):
-
- hx = x
- xout = self.relu_s1(self.bn_s1(self.conv_s1(hx)))
-
- return xout
-
-## upsample tensor 'src' to have the same spatial size with tensor 'tar'
-def _upsample_like(src,tar):
-
- src = F.upsample(src,size=tar.shape[2:],mode='bilinear')
-
- return src
-
-
-### RSU-7 ###
-class RSU7(nn.Module):
-
- def __init__(self, in_ch=3, mid_ch=12, out_ch=3, img_size=512):
- super(RSU7,self).__init__()
-
- self.in_ch = in_ch
- self.mid_ch = mid_ch
- self.out_ch = out_ch
-
- self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1) ## 1 -> 1/2
-
- self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1)
- self.pool1 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1)
- self.pool2 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1)
- self.pool3 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=1)
- self.pool4 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.rebnconv5 = REBNCONV(mid_ch,mid_ch,dirate=1)
- self.pool5 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.rebnconv6 = REBNCONV(mid_ch,mid_ch,dirate=1)
-
- self.rebnconv7 = REBNCONV(mid_ch,mid_ch,dirate=2)
-
- self.rebnconv6d = REBNCONV(mid_ch*2,mid_ch,dirate=1)
- self.rebnconv5d = REBNCONV(mid_ch*2,mid_ch,dirate=1)
- self.rebnconv4d = REBNCONV(mid_ch*2,mid_ch,dirate=1)
- self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1)
- self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1)
- self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1)
-
- def forward(self,x):
- b, c, h, w = x.shape
-
- hx = x
- hxin = self.rebnconvin(hx)
-
- hx1 = self.rebnconv1(hxin)
- hx = self.pool1(hx1)
-
- hx2 = self.rebnconv2(hx)
- hx = self.pool2(hx2)
-
- hx3 = self.rebnconv3(hx)
- hx = self.pool3(hx3)
-
- hx4 = self.rebnconv4(hx)
- hx = self.pool4(hx4)
-
- hx5 = self.rebnconv5(hx)
- hx = self.pool5(hx5)
-
- hx6 = self.rebnconv6(hx)
-
- hx7 = self.rebnconv7(hx6)
-
- hx6d = self.rebnconv6d(torch.cat((hx7,hx6),1))
- hx6dup = _upsample_like(hx6d,hx5)
-
- hx5d = self.rebnconv5d(torch.cat((hx6dup,hx5),1))
- hx5dup = _upsample_like(hx5d,hx4)
-
- hx4d = self.rebnconv4d(torch.cat((hx5dup,hx4),1))
- hx4dup = _upsample_like(hx4d,hx3)
-
- hx3d = self.rebnconv3d(torch.cat((hx4dup,hx3),1))
- hx3dup = _upsample_like(hx3d,hx2)
-
- hx2d = self.rebnconv2d(torch.cat((hx3dup,hx2),1))
- hx2dup = _upsample_like(hx2d,hx1)
-
- hx1d = self.rebnconv1d(torch.cat((hx2dup,hx1),1))
-
- return hx1d + hxin
-
-
-### RSU-6 ###
-class RSU6(nn.Module):
-
- def __init__(self, in_ch=3, mid_ch=12, out_ch=3):
- super(RSU6,self).__init__()
-
- self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1)
-
- self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1)
- self.pool1 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1)
- self.pool2 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1)
- self.pool3 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=1)
- self.pool4 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.rebnconv5 = REBNCONV(mid_ch,mid_ch,dirate=1)
-
- self.rebnconv6 = REBNCONV(mid_ch,mid_ch,dirate=2)
-
- self.rebnconv5d = REBNCONV(mid_ch*2,mid_ch,dirate=1)
- self.rebnconv4d = REBNCONV(mid_ch*2,mid_ch,dirate=1)
- self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1)
- self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1)
- self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1)
-
- def forward(self,x):
-
- hx = x
-
- hxin = self.rebnconvin(hx)
-
- hx1 = self.rebnconv1(hxin)
- hx = self.pool1(hx1)
-
- hx2 = self.rebnconv2(hx)
- hx = self.pool2(hx2)
-
- hx3 = self.rebnconv3(hx)
- hx = self.pool3(hx3)
-
- hx4 = self.rebnconv4(hx)
- hx = self.pool4(hx4)
-
- hx5 = self.rebnconv5(hx)
-
- hx6 = self.rebnconv6(hx5)
-
-
- hx5d = self.rebnconv5d(torch.cat((hx6,hx5),1))
- hx5dup = _upsample_like(hx5d,hx4)
-
- hx4d = self.rebnconv4d(torch.cat((hx5dup,hx4),1))
- hx4dup = _upsample_like(hx4d,hx3)
-
- hx3d = self.rebnconv3d(torch.cat((hx4dup,hx3),1))
- hx3dup = _upsample_like(hx3d,hx2)
-
- hx2d = self.rebnconv2d(torch.cat((hx3dup,hx2),1))
- hx2dup = _upsample_like(hx2d,hx1)
-
- hx1d = self.rebnconv1d(torch.cat((hx2dup,hx1),1))
-
- return hx1d + hxin
-
-### RSU-5 ###
-class RSU5(nn.Module):
-
- def __init__(self, in_ch=3, mid_ch=12, out_ch=3):
- super(RSU5,self).__init__()
-
- self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1)
-
- self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1)
- self.pool1 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1)
- self.pool2 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1)
- self.pool3 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=1)
-
- self.rebnconv5 = REBNCONV(mid_ch,mid_ch,dirate=2)
-
- self.rebnconv4d = REBNCONV(mid_ch*2,mid_ch,dirate=1)
- self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1)
- self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1)
- self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1)
-
- def forward(self,x):
-
- hx = x
-
- hxin = self.rebnconvin(hx)
-
- hx1 = self.rebnconv1(hxin)
- hx = self.pool1(hx1)
-
- hx2 = self.rebnconv2(hx)
- hx = self.pool2(hx2)
-
- hx3 = self.rebnconv3(hx)
- hx = self.pool3(hx3)
-
- hx4 = self.rebnconv4(hx)
-
- hx5 = self.rebnconv5(hx4)
-
- hx4d = self.rebnconv4d(torch.cat((hx5,hx4),1))
- hx4dup = _upsample_like(hx4d,hx3)
-
- hx3d = self.rebnconv3d(torch.cat((hx4dup,hx3),1))
- hx3dup = _upsample_like(hx3d,hx2)
-
- hx2d = self.rebnconv2d(torch.cat((hx3dup,hx2),1))
- hx2dup = _upsample_like(hx2d,hx1)
-
- hx1d = self.rebnconv1d(torch.cat((hx2dup,hx1),1))
-
- return hx1d + hxin
-
-### RSU-4 ###
-class RSU4(nn.Module):
-
- def __init__(self, in_ch=3, mid_ch=12, out_ch=3):
- super(RSU4,self).__init__()
-
- self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1)
-
- self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1)
- self.pool1 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1)
- self.pool2 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1)
-
- self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=2)
-
- self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1)
- self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1)
- self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1)
-
- def forward(self,x):
-
- hx = x
-
- hxin = self.rebnconvin(hx)
-
- hx1 = self.rebnconv1(hxin)
- hx = self.pool1(hx1)
-
- hx2 = self.rebnconv2(hx)
- hx = self.pool2(hx2)
-
- hx3 = self.rebnconv3(hx)
-
- hx4 = self.rebnconv4(hx3)
-
- hx3d = self.rebnconv3d(torch.cat((hx4,hx3),1))
- hx3dup = _upsample_like(hx3d,hx2)
-
- hx2d = self.rebnconv2d(torch.cat((hx3dup,hx2),1))
- hx2dup = _upsample_like(hx2d,hx1)
-
- hx1d = self.rebnconv1d(torch.cat((hx2dup,hx1),1))
-
- return hx1d + hxin
-
-### RSU-4F ###
-class RSU4F(nn.Module):
-
- def __init__(self, in_ch=3, mid_ch=12, out_ch=3):
- super(RSU4F,self).__init__()
-
- self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1)
-
- self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1)
- self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=2)
- self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=4)
-
- self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=8)
-
- self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=4)
- self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=2)
- self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1)
-
- def forward(self,x):
-
- hx = x
-
- hxin = self.rebnconvin(hx)
-
- hx1 = self.rebnconv1(hxin)
- hx2 = self.rebnconv2(hx1)
- hx3 = self.rebnconv3(hx2)
-
- hx4 = self.rebnconv4(hx3)
-
- hx3d = self.rebnconv3d(torch.cat((hx4,hx3),1))
- hx2d = self.rebnconv2d(torch.cat((hx3d,hx2),1))
- hx1d = self.rebnconv1d(torch.cat((hx2d,hx1),1))
-
- return hx1d + hxin
-
-
-class myrebnconv(nn.Module):
- def __init__(self, in_ch=3,
- out_ch=1,
- kernel_size=3,
- stride=1,
- padding=1,
- dilation=1,
- groups=1):
- super(myrebnconv,self).__init__()
-
- self.conv = nn.Conv2d(in_ch,
- out_ch,
- kernel_size=kernel_size,
- stride=stride,
- padding=padding,
- dilation=dilation,
- groups=groups)
- self.bn = nn.BatchNorm2d(out_ch)
- self.rl = nn.ReLU(inplace=True)
-
- def forward(self,x):
- return self.rl(self.bn(self.conv(x)))
-
-
-class ISNetGTEncoder(nn.Module):
-
- def __init__(self,in_ch=1,out_ch=1):
- super(ISNetGTEncoder,self).__init__()
-
- self.conv_in = myrebnconv(in_ch,16,3,stride=2,padding=1) # nn.Conv2d(in_ch,64,3,stride=2,padding=1)
-
- self.stage1 = RSU7(16,16,64)
- self.pool12 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.stage2 = RSU6(64,16,64)
- self.pool23 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.stage3 = RSU5(64,32,128)
- self.pool34 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.stage4 = RSU4(128,32,256)
- self.pool45 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.stage5 = RSU4F(256,64,512)
- self.pool56 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.stage6 = RSU4F(512,64,512)
-
-
- self.side1 = nn.Conv2d(64,out_ch,3,padding=1)
- self.side2 = nn.Conv2d(64,out_ch,3,padding=1)
- self.side3 = nn.Conv2d(128,out_ch,3,padding=1)
- self.side4 = nn.Conv2d(256,out_ch,3,padding=1)
- self.side5 = nn.Conv2d(512,out_ch,3,padding=1)
- self.side6 = nn.Conv2d(512,out_ch,3,padding=1)
-
- def compute_loss(self, preds, targets):
-
- return muti_loss_fusion(preds,targets)
-
- def forward(self,x):
-
- hx = x
-
- hxin = self.conv_in(hx)
- # hx = self.pool_in(hxin)
-
- #stage 1
- hx1 = self.stage1(hxin)
- hx = self.pool12(hx1)
-
- #stage 2
- hx2 = self.stage2(hx)
- hx = self.pool23(hx2)
-
- #stage 3
- hx3 = self.stage3(hx)
- hx = self.pool34(hx3)
-
- #stage 4
- hx4 = self.stage4(hx)
- hx = self.pool45(hx4)
-
- #stage 5
- hx5 = self.stage5(hx)
- hx = self.pool56(hx5)
-
- #stage 6
- hx6 = self.stage6(hx)
-
-
- #side output
- d1 = self.side1(hx1)
- d1 = _upsample_like(d1,x)
-
- d2 = self.side2(hx2)
- d2 = _upsample_like(d2,x)
-
- d3 = self.side3(hx3)
- d3 = _upsample_like(d3,x)
-
- d4 = self.side4(hx4)
- d4 = _upsample_like(d4,x)
-
- d5 = self.side5(hx5)
- d5 = _upsample_like(d5,x)
-
- d6 = self.side6(hx6)
- d6 = _upsample_like(d6,x)
-
- # d0 = self.outconv(torch.cat((d1,d2,d3,d4,d5,d6),1))
-
- return [F.sigmoid(d1), F.sigmoid(d2), F.sigmoid(d3), F.sigmoid(d4), F.sigmoid(d5), F.sigmoid(d6)], [hx1,hx2,hx3,hx4,hx5,hx6]
-
-class ISNetDIS(nn.Module):
-
- def __init__(self,in_ch=3,out_ch=1):
- super(ISNetDIS,self).__init__()
-
- self.conv_in = nn.Conv2d(in_ch,64,3,stride=2,padding=1)
- self.pool_in = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.stage1 = RSU7(64,32,64)
- self.pool12 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.stage2 = RSU6(64,32,128)
- self.pool23 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.stage3 = RSU5(128,64,256)
- self.pool34 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.stage4 = RSU4(256,128,512)
- self.pool45 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.stage5 = RSU4F(512,256,512)
- self.pool56 = nn.MaxPool2d(2,stride=2,ceil_mode=True)
-
- self.stage6 = RSU4F(512,256,512)
-
- # decoder
- self.stage5d = RSU4F(1024,256,512)
- self.stage4d = RSU4(1024,128,256)
- self.stage3d = RSU5(512,64,128)
- self.stage2d = RSU6(256,32,64)
- self.stage1d = RSU7(128,16,64)
-
- self.side1 = nn.Conv2d(64,out_ch,3,padding=1)
- self.side2 = nn.Conv2d(64,out_ch,3,padding=1)
- self.side3 = nn.Conv2d(128,out_ch,3,padding=1)
- self.side4 = nn.Conv2d(256,out_ch,3,padding=1)
- self.side5 = nn.Conv2d(512,out_ch,3,padding=1)
- self.side6 = nn.Conv2d(512,out_ch,3,padding=1)
-
- # self.outconv = nn.Conv2d(6*out_ch,out_ch,1)
-
- def compute_loss_kl(self, preds, targets, dfs, fs, mode='MSE'):
-
- # return muti_loss_fusion(preds,targets)
- return muti_loss_fusion_kl(preds, targets, dfs, fs, mode=mode)
-
- def compute_loss(self, preds, targets):
-
- # return muti_loss_fusion(preds,targets)
- return muti_loss_fusion(preds, targets)
-
- def forward(self,x):
-
- hx = x
-
- hxin = self.conv_in(hx)
- #hx = self.pool_in(hxin)
-
- #stage 1
- hx1 = self.stage1(hxin)
- hx = self.pool12(hx1)
-
- #stage 2
- hx2 = self.stage2(hx)
- hx = self.pool23(hx2)
-
- #stage 3
- hx3 = self.stage3(hx)
- hx = self.pool34(hx3)
-
- #stage 4
- hx4 = self.stage4(hx)
- hx = self.pool45(hx4)
-
- #stage 5
- hx5 = self.stage5(hx)
- hx = self.pool56(hx5)
-
- #stage 6
- hx6 = self.stage6(hx)
- hx6up = _upsample_like(hx6,hx5)
-
- #-------------------- decoder --------------------
- hx5d = self.stage5d(torch.cat((hx6up,hx5),1))
- hx5dup = _upsample_like(hx5d,hx4)
-
- hx4d = self.stage4d(torch.cat((hx5dup,hx4),1))
- hx4dup = _upsample_like(hx4d,hx3)
-
- hx3d = self.stage3d(torch.cat((hx4dup,hx3),1))
- hx3dup = _upsample_like(hx3d,hx2)
-
- hx2d = self.stage2d(torch.cat((hx3dup,hx2),1))
- hx2dup = _upsample_like(hx2d,hx1)
-
- hx1d = self.stage1d(torch.cat((hx2dup,hx1),1))
-
-
- #side output
- d1 = self.side1(hx1d)
- d1 = _upsample_like(d1,x)
-
- d2 = self.side2(hx2d)
- d2 = _upsample_like(d2,x)
-
- d3 = self.side3(hx3d)
- d3 = _upsample_like(d3,x)
-
- d4 = self.side4(hx4d)
- d4 = _upsample_like(d4,x)
-
- d5 = self.side5(hx5d)
- d5 = _upsample_like(d5,x)
-
- d6 = self.side6(hx6)
- d6 = _upsample_like(d6,x)
-
- # d0 = self.outconv(torch.cat((d1,d2,d3,d4,d5,d6),1))
-
- return [F.sigmoid(d1), F.sigmoid(d2), F.sigmoid(d3), F.sigmoid(d4), F.sigmoid(d5), F.sigmoid(d6)],[hx1d,hx2d,hx3d,hx4d,hx5d,hx6]
diff --git a/spaces/MirageML/sjc/adapt.py b/spaces/MirageML/sjc/adapt.py
deleted file mode 100644
index 418252b461f7c95f948866152f8d82a0bb9c55a1..0000000000000000000000000000000000000000
--- a/spaces/MirageML/sjc/adapt.py
+++ /dev/null
@@ -1,163 +0,0 @@
-from pathlib import Path
-import json
-from math import sqrt
-import numpy as np
-import torch
-from abc import ABCMeta, abstractmethod
-
-
-class ScoreAdapter(metaclass=ABCMeta):
-
- @abstractmethod
- def denoise(self, xs, σ, **kwargs):
- pass
-
- def score(self, xs, σ, **kwargs):
- Ds = self.denoise(xs, σ, **kwargs)
- grad_log_p_t = (Ds - xs) / (σ ** 2)
- return grad_log_p_t
-
- @abstractmethod
- def data_shape(self):
- return (3, 256, 256) # for example
-
- def samps_centered(self):
- # if centered, samples expected to be in range [-1, 1], else [0, 1]
- return True
-
- @property
- @abstractmethod
- def σ_max(self):
- pass
-
- @property
- @abstractmethod
- def σ_min(self):
- pass
-
- def cond_info(self, batch_size):
- return {}
-
- @abstractmethod
- def unet_is_cond(self):
- return False
-
- @abstractmethod
- def use_cls_guidance(self):
- return False # most models do not use cls guidance
-
- def classifier_grad(self, xs, σ, ys):
- raise NotImplementedError()
-
- @abstractmethod
- def snap_t_to_nearest_tick(self, t):
- # need to confirm for each model; continuous time model doesn't need this
- return t, None
-
- @property
- def device(self):
- return self._device
-
- def checkpoint_root(self):
- """the path at which the pretrained checkpoints are stored"""
- with Path(__file__).resolve().with_name("env.json").open("r") as f:
- root = json.load(f)['data_root']
- root = Path(root) / "diffusion_ckpts"
- return root
-
-
-def karras_t_schedule(ρ=7, N=10, σ_max=80, σ_min=0.002):
- ts = []
- for i in range(N):
-
- t = (
- σ_max ** (1 / ρ) + (i / (N - 1)) * (σ_min ** (1 / ρ) - σ_max ** (1 / ρ))
- ) ** ρ
- ts.append(t)
- return ts
-
-
-def power_schedule(σ_max, σ_min, num_stages):
- σs = np.exp(np.linspace(np.log(σ_max), np.log(σ_min), num_stages))
- return σs
-
-
-class Karras():
-
- @classmethod
- @torch.no_grad()
- def inference(
- cls, model, batch_size, num_t, *,
- σ_max=80, cls_scaling=1,
- init_xs=None, heun=True,
- langevin=False,
- S_churn=80, S_min=0.05, S_max=50, S_noise=1.003,
- ):
- σ_max = min(σ_max, model.σ_max)
- σ_min = model.σ_min
- ts = karras_t_schedule(ρ=7, N=num_t, σ_max=σ_max, σ_min=σ_min)
- assert len(ts) == num_t
- ts = [model.snap_t_to_nearest_tick(t)[0] for t in ts]
- ts.append(0) # 0 is the destination
- σ_max = ts[0]
-
- cond_inputs = model.cond_info(batch_size)
-
- def compute_step(xs, σ):
- grad_log_p_t = model.score(
- xs, σ, **(cond_inputs if model.unet_is_cond() else {})
- )
- if model.use_cls_guidance():
- grad_cls = model.classifier_grad(xs, σ, cond_inputs["y"])
- grad_cls = grad_cls * cls_scaling
- grad_log_p_t += grad_cls
- d_i = -1 * σ * grad_log_p_t
- return d_i
-
- if init_xs is not None:
- xs = init_xs.to(model.device)
- else:
- xs = σ_max * torch.randn(
- batch_size, *model.data_shape(), device=model.device
- )
-
- yield xs
-
- for i in range(num_t):
- t_i = ts[i]
-
- if langevin and (S_min < t_i and t_i < S_max):
- xs, t_i = cls.noise_backward_in_time(
- model, xs, t_i, S_noise, S_churn / num_t
- )
-
- Δt = ts[i+1] - t_i
-
- d_1 = compute_step(xs, σ=t_i)
- xs_1 = xs + Δt * d_1
-
- # Heun's 2nd order method; don't apply on the last step
- if (not heun) or (ts[i+1] == 0):
- xs = xs_1
- else:
- d_2 = compute_step(xs_1, σ=ts[i+1])
- xs = xs + Δt * (d_1 + d_2) / 2
-
- yield xs
-
- @staticmethod
- def noise_backward_in_time(model, xs, t_i, S_noise, S_churn_i):
- n = S_noise * torch.randn_like(xs)
- γ_i = min(sqrt(2)-1, S_churn_i)
- t_i_hat = t_i * (1 + γ_i)
- t_i_hat = model.snap_t_to_nearest_tick(t_i_hat)[0]
- xs = xs + n * sqrt(t_i_hat ** 2 - t_i ** 2)
- return xs, t_i_hat
-
-
-def test():
- pass
-
-
-if __name__ == "__main__":
- test()
diff --git a/spaces/MohitGupta/Eng2Indic_Translitration/transliteration/transformer/__init__.py b/spaces/MohitGupta/Eng2Indic_Translitration/transliteration/transformer/__init__.py
deleted file mode 100644
index 2796d0f0f2503362ca03f67cf8f4b0b39b6eee76..0000000000000000000000000000000000000000
--- a/spaces/MohitGupta/Eng2Indic_Translitration/transliteration/transformer/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from .en2hin import TranslitrationEngineTransformer_En2Hi
-
-__all__ = ["TransliterationEngineTransformer_En2Hi"]
\ No newline at end of file
diff --git a/spaces/NCTCMumbai/NCTC/models/official/benchmark/models/resnet_cifar_model.py b/spaces/NCTCMumbai/NCTC/models/official/benchmark/models/resnet_cifar_model.py
deleted file mode 100644
index 1b507381f1b6907fdfb078d8316f3621a9e2b8f7..0000000000000000000000000000000000000000
--- a/spaces/NCTCMumbai/NCTC/models/official/benchmark/models/resnet_cifar_model.py
+++ /dev/null
@@ -1,262 +0,0 @@
-# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-"""ResNet56 model for Keras adapted from tf.keras.applications.ResNet50.
-
-# Reference:
-- [Deep Residual Learning for Image Recognition](
- https://arxiv.org/abs/1512.03385)
-Adapted from code contributed by BigMoyan.
-"""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import functools
-import tensorflow as tf
-from tensorflow.python.keras import backend
-from tensorflow.python.keras import initializers
-from tensorflow.python.keras import layers
-from tensorflow.python.keras import regularizers
-
-
-BATCH_NORM_DECAY = 0.997
-BATCH_NORM_EPSILON = 1e-5
-L2_WEIGHT_DECAY = 2e-4
-
-
-def identity_building_block(input_tensor,
- kernel_size,
- filters,
- stage,
- block,
- training=None):
- """The identity block is the block that has no conv layer at shortcut.
-
- Arguments:
- input_tensor: input tensor
- kernel_size: default 3, the kernel size of
- middle conv layer at main path
- filters: list of integers, the filters of 3 conv layer at main path
- stage: integer, current stage label, used for generating layer names
- block: current block label, used for generating layer names
- training: Only used if training keras model with Estimator. In other
- scenarios it is handled automatically.
-
- Returns:
- Output tensor for the block.
- """
- filters1, filters2 = filters
- if backend.image_data_format() == 'channels_last':
- bn_axis = 3
- else:
- bn_axis = 1
- conv_name_base = 'res' + str(stage) + block + '_branch'
- bn_name_base = 'bn' + str(stage) + block + '_branch'
-
- x = layers.Conv2D(filters1, kernel_size,
- padding='same', use_bias=False,
- kernel_initializer='he_normal',
- kernel_regularizer=regularizers.l2(L2_WEIGHT_DECAY),
- name=conv_name_base + '2a')(input_tensor)
- x = layers.BatchNormalization(
- axis=bn_axis, momentum=BATCH_NORM_DECAY, epsilon=BATCH_NORM_EPSILON,
- name=bn_name_base + '2a')(x, training=training)
- x = layers.Activation('relu')(x)
-
- x = layers.Conv2D(filters2, kernel_size,
- padding='same', use_bias=False,
- kernel_initializer='he_normal',
- kernel_regularizer=regularizers.l2(L2_WEIGHT_DECAY),
- name=conv_name_base + '2b')(x)
- x = layers.BatchNormalization(
- axis=bn_axis, momentum=BATCH_NORM_DECAY, epsilon=BATCH_NORM_EPSILON,
- name=bn_name_base + '2b')(x, training=training)
-
- x = layers.add([x, input_tensor])
- x = layers.Activation('relu')(x)
- return x
-
-
-def conv_building_block(input_tensor,
- kernel_size,
- filters,
- stage,
- block,
- strides=(2, 2),
- training=None):
- """A block that has a conv layer at shortcut.
-
- Arguments:
- input_tensor: input tensor
- kernel_size: default 3, the kernel size of
- middle conv layer at main path
- filters: list of integers, the filters of 3 conv layer at main path
- stage: integer, current stage label, used for generating layer names
- block: current block label, used for generating layer names
- strides: Strides for the first conv layer in the block.
- training: Only used if training keras model with Estimator. In other
- scenarios it is handled automatically.
-
- Returns:
- Output tensor for the block.
-
- Note that from stage 3,
- the first conv layer at main path is with strides=(2, 2)
- And the shortcut should have strides=(2, 2) as well
- """
- filters1, filters2 = filters
- if tf.keras.backend.image_data_format() == 'channels_last':
- bn_axis = 3
- else:
- bn_axis = 1
- conv_name_base = 'res' + str(stage) + block + '_branch'
- bn_name_base = 'bn' + str(stage) + block + '_branch'
-
- x = layers.Conv2D(filters1, kernel_size, strides=strides,
- padding='same', use_bias=False,
- kernel_initializer='he_normal',
- kernel_regularizer=regularizers.l2(L2_WEIGHT_DECAY),
- name=conv_name_base + '2a')(input_tensor)
- x = layers.BatchNormalization(
- axis=bn_axis, momentum=BATCH_NORM_DECAY, epsilon=BATCH_NORM_EPSILON,
- name=bn_name_base + '2a')(x, training=training)
- x = layers.Activation('relu')(x)
-
- x = layers.Conv2D(filters2, kernel_size, padding='same', use_bias=False,
- kernel_initializer='he_normal',
- kernel_regularizer=regularizers.l2(L2_WEIGHT_DECAY),
- name=conv_name_base + '2b')(x)
- x = layers.BatchNormalization(
- axis=bn_axis, momentum=BATCH_NORM_DECAY, epsilon=BATCH_NORM_EPSILON,
- name=bn_name_base + '2b')(x, training=training)
-
- shortcut = layers.Conv2D(filters2, (1, 1), strides=strides, use_bias=False,
- kernel_initializer='he_normal',
- kernel_regularizer=regularizers.l2(L2_WEIGHT_DECAY),
- name=conv_name_base + '1')(input_tensor)
- shortcut = layers.BatchNormalization(
- axis=bn_axis, momentum=BATCH_NORM_DECAY, epsilon=BATCH_NORM_EPSILON,
- name=bn_name_base + '1')(shortcut, training=training)
-
- x = layers.add([x, shortcut])
- x = layers.Activation('relu')(x)
- return x
-
-
-def resnet_block(input_tensor,
- size,
- kernel_size,
- filters,
- stage,
- conv_strides=(2, 2),
- training=None):
- """A block which applies conv followed by multiple identity blocks.
-
- Arguments:
- input_tensor: input tensor
- size: integer, number of constituent conv/identity building blocks.
- A conv block is applied once, followed by (size - 1) identity blocks.
- kernel_size: default 3, the kernel size of
- middle conv layer at main path
- filters: list of integers, the filters of 3 conv layer at main path
- stage: integer, current stage label, used for generating layer names
- conv_strides: Strides for the first conv layer in the block.
- training: Only used if training keras model with Estimator. In other
- scenarios it is handled automatically.
-
- Returns:
- Output tensor after applying conv and identity blocks.
- """
-
- x = conv_building_block(input_tensor, kernel_size, filters, stage=stage,
- strides=conv_strides, block='block_0',
- training=training)
- for i in range(size - 1):
- x = identity_building_block(x, kernel_size, filters, stage=stage,
- block='block_%d' % (i + 1), training=training)
- return x
-
-
-def resnet(num_blocks, classes=10, training=None):
- """Instantiates the ResNet architecture.
-
- Arguments:
- num_blocks: integer, the number of conv/identity blocks in each block.
- The ResNet contains 3 blocks with each block containing one conv block
- followed by (layers_per_block - 1) number of idenity blocks. Each
- conv/idenity block has 2 convolutional layers. With the input
- convolutional layer and the pooling layer towards the end, this brings
- the total size of the network to (6*num_blocks + 2)
- classes: optional number of classes to classify images into
- training: Only used if training keras model with Estimator. In other
- scenarios it is handled automatically.
-
- Returns:
- A Keras model instance.
- """
-
- input_shape = (32, 32, 3)
- img_input = layers.Input(shape=input_shape)
-
- if backend.image_data_format() == 'channels_first':
- x = layers.Lambda(lambda x: backend.permute_dimensions(x, (0, 3, 1, 2)),
- name='transpose')(img_input)
- bn_axis = 1
- else: # channel_last
- x = img_input
- bn_axis = 3
-
- x = layers.ZeroPadding2D(padding=(1, 1), name='conv1_pad')(x)
- x = layers.Conv2D(16, (3, 3),
- strides=(1, 1),
- padding='valid', use_bias=False,
- kernel_initializer='he_normal',
- kernel_regularizer=regularizers.l2(L2_WEIGHT_DECAY),
- name='conv1')(x)
- x = layers.BatchNormalization(axis=bn_axis,
- momentum=BATCH_NORM_DECAY,
- epsilon=BATCH_NORM_EPSILON,
- name='bn_conv1',)(x, training=training)
- x = layers.Activation('relu')(x)
-
- x = resnet_block(x, size=num_blocks, kernel_size=3, filters=[16, 16],
- stage=2, conv_strides=(1, 1), training=training)
-
- x = resnet_block(x, size=num_blocks, kernel_size=3, filters=[32, 32],
- stage=3, conv_strides=(2, 2), training=training)
-
- x = resnet_block(x, size=num_blocks, kernel_size=3, filters=[64, 64],
- stage=4, conv_strides=(2, 2), training=training)
-
- rm_axes = [1, 2] if backend.image_data_format() == 'channels_last' else [2, 3]
- x = layers.Lambda(lambda x: backend.mean(x, rm_axes), name='reduce_mean')(x)
- x = layers.Dense(classes,
- activation='softmax',
- kernel_initializer=initializers.RandomNormal(stddev=0.01),
- kernel_regularizer=regularizers.l2(L2_WEIGHT_DECAY),
- bias_regularizer=regularizers.l2(L2_WEIGHT_DECAY),
- name='fc10')(x)
-
- inputs = img_input
- # Create model.
- model = tf.keras.models.Model(inputs, x, name='resnet56')
-
- return model
-
-
-resnet20 = functools.partial(resnet, num_blocks=3)
-resnet32 = functools.partial(resnet, num_blocks=5)
-resnet56 = functools.partial(resnet, num_blocks=9)
-resnet10 = functools.partial(resnet, num_blocks=110)
diff --git a/spaces/NKU-AMT/AMT/README.md b/spaces/NKU-AMT/AMT/README.md
deleted file mode 100644
index ea5934dd0648017da2e88b328ecacb2d61c59d21..0000000000000000000000000000000000000000
--- a/spaces/NKU-AMT/AMT/README.md
+++ /dev/null
@@ -1,13 +0,0 @@
----
-title: AMT
-emoji: 🐢
-colorFrom: blue
-colorTo: green
-sdk: gradio
-sdk_version: 3.23.0
-app_file: app.py
-pinned: false
-license: cc-by-nc-sa-4.0
----
-
-Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
diff --git a/spaces/Nultx/VITS-TTS/utils.py b/spaces/Nultx/VITS-TTS/utils.py
deleted file mode 100644
index 9794e0fc3463a5e8fad05c037cce64683059a6d3..0000000000000000000000000000000000000000
--- a/spaces/Nultx/VITS-TTS/utils.py
+++ /dev/null
@@ -1,226 +0,0 @@
-import os
-import glob
-import sys
-import argparse
-import logging
-import json
-import subprocess
-import numpy as np
-from scipy.io.wavfile import read
-import torch
-
-MATPLOTLIB_FLAG = False
-
-logging.basicConfig(stream=sys.stdout, level=logging.ERROR)
-logger = logging
-
-
-def load_checkpoint(checkpoint_path, model, optimizer=None):
- assert os.path.isfile(checkpoint_path)
- checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
- iteration = checkpoint_dict['iteration']
- learning_rate = checkpoint_dict['learning_rate']
- if optimizer is not None:
- optimizer.load_state_dict(checkpoint_dict['optimizer'])
- saved_state_dict = checkpoint_dict['model']
- if hasattr(model, 'module'):
- state_dict = model.module.state_dict()
- else:
- state_dict = model.state_dict()
- new_state_dict = {}
- for k, v in state_dict.items():
- try:
- new_state_dict[k] = saved_state_dict[k]
- except:
- logger.info("%s is not in the checkpoint" % k)
- new_state_dict[k] = v
- if hasattr(model, 'module'):
- model.module.load_state_dict(new_state_dict)
- else:
- model.load_state_dict(new_state_dict)
- logger.info("Loaded checkpoint '{}' (iteration {})".format(
- checkpoint_path, iteration))
- return model, optimizer, learning_rate, iteration
-
-
-def plot_spectrogram_to_numpy(spectrogram):
- global MATPLOTLIB_FLAG
- if not MATPLOTLIB_FLAG:
- import matplotlib
- matplotlib.use("Agg")
- MATPLOTLIB_FLAG = True
- mpl_logger = logging.getLogger('matplotlib')
- mpl_logger.setLevel(logging.WARNING)
- import matplotlib.pylab as plt
- import numpy as np
-
- fig, ax = plt.subplots(figsize=(10, 2))
- im = ax.imshow(spectrogram, aspect="auto", origin="lower",
- interpolation='none')
- plt.colorbar(im, ax=ax)
- plt.xlabel("Frames")
- plt.ylabel("Channels")
- plt.tight_layout()
-
- fig.canvas.draw()
- data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
- data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
- plt.close()
- return data
-
-
-def plot_alignment_to_numpy(alignment, info=None):
- global MATPLOTLIB_FLAG
- if not MATPLOTLIB_FLAG:
- import matplotlib
- matplotlib.use("Agg")
- MATPLOTLIB_FLAG = True
- mpl_logger = logging.getLogger('matplotlib')
- mpl_logger.setLevel(logging.WARNING)
- import matplotlib.pylab as plt
- import numpy as np
-
- fig, ax = plt.subplots(figsize=(6, 4))
- im = ax.imshow(alignment.transpose(), aspect='auto', origin='lower',
- interpolation='none')
- fig.colorbar(im, ax=ax)
- xlabel = 'Decoder timestep'
- if info is not None:
- xlabel += '\n\n' + info
- plt.xlabel(xlabel)
- plt.ylabel('Encoder timestep')
- plt.tight_layout()
-
- fig.canvas.draw()
- data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
- data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
- plt.close()
- return data
-
-
-def load_wav_to_torch(full_path):
- sampling_rate, data = read(full_path)
- return torch.FloatTensor(data.astype(np.float32)), sampling_rate
-
-
-def load_filepaths_and_text(filename, split="|"):
- with open(filename, encoding='utf-8') as f:
- filepaths_and_text = [line.strip().split(split) for line in f]
- return filepaths_and_text
-
-
-def get_hparams(init=True):
- parser = argparse.ArgumentParser()
- parser.add_argument('-c', '--config', type=str, default="./configs/base.json",
- help='JSON file for configuration')
- parser.add_argument('-m', '--model', type=str, required=True,
- help='Model name')
-
- args = parser.parse_args()
- model_dir = os.path.join("./logs", args.model)
-
- if not os.path.exists(model_dir):
- os.makedirs(model_dir)
-
- config_path = args.config
- config_save_path = os.path.join(model_dir, "config.json")
- if init:
- with open(config_path, "r") as f:
- data = f.read()
- with open(config_save_path, "w") as f:
- f.write(data)
- else:
- with open(config_save_path, "r") as f:
- data = f.read()
- config = json.loads(data)
-
- hparams = HParams(**config)
- hparams.model_dir = model_dir
- return hparams
-
-
-def get_hparams_from_dir(model_dir):
- config_save_path = os.path.join(model_dir, "config.json")
- with open(config_save_path, "r") as f:
- data = f.read()
- config = json.loads(data)
-
- hparams = HParams(**config)
- hparams.model_dir = model_dir
- return hparams
-
-
-def get_hparams_from_file(config_path):
- with open(config_path, "r", encoding="utf-8") as f:
- data = f.read()
- config = json.loads(data)
-
- hparams = HParams(**config)
- return hparams
-
-
-def check_git_hash(model_dir):
- source_dir = os.path.dirname(os.path.realpath(__file__))
- if not os.path.exists(os.path.join(source_dir, ".git")):
- logger.warn("{} is not a git repository, therefore hash value comparison will be ignored.".format(
- source_dir
- ))
- return
-
- cur_hash = subprocess.getoutput("git rev-parse HEAD")
-
- path = os.path.join(model_dir, "githash")
- if os.path.exists(path):
- saved_hash = open(path).read()
- if saved_hash != cur_hash:
- logger.warn("git hash values are different. {}(saved) != {}(current)".format(
- saved_hash[:8], cur_hash[:8]))
- else:
- open(path, "w").write(cur_hash)
-
-
-def get_logger(model_dir, filename="train.log"):
- global logger
- logger = logging.getLogger(os.path.basename(model_dir))
- logger.setLevel(logging.DEBUG)
-
- formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
- if not os.path.exists(model_dir):
- os.makedirs(model_dir)
- h = logging.FileHandler(os.path.join(model_dir, filename))
- h.setLevel(logging.DEBUG)
- h.setFormatter(formatter)
- logger.addHandler(h)
- return logger
-
-
-class HParams():
- def __init__(self, **kwargs):
- for k, v in kwargs.items():
- if type(v) == dict:
- v = HParams(**v)
- self[k] = v
-
- def keys(self):
- return self.__dict__.keys()
-
- def items(self):
- return self.__dict__.items()
-
- def values(self):
- return self.__dict__.values()
-
- def __len__(self):
- return len(self.__dict__)
-
- def __getitem__(self, key):
- return getattr(self, key)
-
- def __setitem__(self, key, value):
- return setattr(self, key, value)
-
- def __contains__(self, key):
- return key in self.__dict__
-
- def __repr__(self):
- return self.__dict__.__repr__()
\ No newline at end of file
diff --git a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/optim/adamax.py b/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/optim/adamax.py
deleted file mode 100644
index 98ff8ad7ad6c12ab5efc53ca76db2f1663be7906..0000000000000000000000000000000000000000
--- a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/optim/adamax.py
+++ /dev/null
@@ -1,172 +0,0 @@
-# Copyright (c) Facebook, Inc. and its affiliates.
-#
-# This source code is licensed under the MIT license found in the
-# LICENSE file in the root directory of this source tree.
-
-import torch
-import torch.optim
-
-from . import LegacyFairseqOptimizer, register_optimizer
-
-
-@register_optimizer("adamax")
-class FairseqAdamax(LegacyFairseqOptimizer):
- def __init__(self, args, params):
- super().__init__(args)
- self._optimizer = Adamax(params, **self.optimizer_config)
-
- @staticmethod
- def add_args(parser):
- """Add optimizer-specific arguments to the parser."""
- # fmt: off
- parser.add_argument('--adamax-betas', default='(0.9, 0.999)', metavar='B',
- help='betas for Adam optimizer')
- parser.add_argument('--adamax-eps', type=float, default=1e-8, metavar='D',
- help='epsilon for Adam optimizer')
- parser.add_argument('--weight-decay', '--wd', default=0.0, type=float, metavar='WD',
- help='weight decay')
- parser.add_argument('--no-bias-correction', default=False, action='store_true',
- help='disable bias correction')
- # fmt: on
-
- @property
- def optimizer_config(self):
- """
- Return a kwarg dictionary that will be used to override optimizer
- args stored in checkpoints. This allows us to load a checkpoint and
- resume training using a different set of optimizer args, e.g., with a
- different learning rate.
- """
- return {
- "lr": self.args.lr[0],
- "betas": eval(self.args.adamax_betas),
- "eps": self.args.adamax_eps,
- "weight_decay": self.args.weight_decay,
- "bias_correction": not self.args.no_bias_correction,
- }
-
-
-class Adamax(torch.optim.Optimizer):
- """Implements Adamax algorithm (a variant of Adam based on infinity norm).
-
- It has been proposed in `Adam: A Method for Stochastic Optimization`__.
-
- Compared to the version in PyTorch, this version implements a fix for weight decay.
-
- Args:
- params (iterable): iterable of parameters to optimize or dicts defining
- parameter groups
- lr (float, optional): learning rate (default: 2e-3)
- betas (Tuple[float, float], optional): coefficients used for computing
- running averages of gradient and its square
- eps (float, optional): term added to the denominator to improve
- numerical stability (default: 1e-8)
- weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
- bias_correction (bool, optional): enable bias correction (default: True)
-
- __ https://arxiv.org/abs/1412.6980
- """
-
- def __init__(
- self,
- params,
- lr=2e-3,
- betas=(0.9, 0.999),
- eps=1e-8,
- weight_decay=0,
- bias_correction=True,
- ):
- if not 0.0 <= lr:
- raise ValueError("Invalid learning rate: {}".format(lr))
- if not 0.0 <= eps:
- raise ValueError("Invalid epsilon value: {}".format(eps))
- if not 0.0 <= betas[0] < 1.0:
- raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0]))
- if not 0.0 <= betas[1] < 1.0:
- raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1]))
- if not 0.0 <= weight_decay:
- raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
-
- defaults = dict(
- lr=lr,
- betas=betas,
- eps=eps,
- weight_decay=weight_decay,
- bias_correction=bias_correction,
- )
- super(Adamax, self).__init__(params, defaults)
-
- @property
- def supports_memory_efficient_fp16(self):
- return True
-
- @property
- def supports_flat_params(self):
- return True
-
- def step(self, closure=None):
- """Performs a single optimization step.
-
- Args:
- closure (callable, optional): A closure that reevaluates the model
- and returns the loss.
- """
- loss = None
- if closure is not None:
- loss = closure()
-
- for group in self.param_groups:
- for p in group["params"]:
- if p.grad is None:
- continue
- grad = p.grad.data.float()
- if grad.is_sparse:
- raise RuntimeError("Adamax does not support sparse gradients")
-
- p_data_fp32 = p.data
- if p.data.dtype in {torch.float16, torch.bfloat16}:
- p_data_fp32 = p_data_fp32.float()
-
- state = self.state[p]
-
- # State initialization
- if len(state) == 0:
- state["step"] = 0
- state["exp_avg"] = torch.zeros_like(p_data_fp32)
- state["exp_inf"] = torch.zeros_like(p_data_fp32)
- else:
- state["exp_avg"] = state["exp_avg"].to(p_data_fp32)
- state["exp_inf"] = state["exp_inf"].to(p_data_fp32)
-
- exp_avg, exp_inf = state["exp_avg"], state["exp_inf"]
- beta1, beta2 = group["betas"]
- eps = group["eps"]
-
- state["step"] += 1
-
- # Update biased first moment estimate.
- exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1)
-
- # Update the exponentially weighted infinity norm.
- torch.max(
- exp_inf.mul_(beta2),
- grad.abs_(),
- out=exp_inf,
- )
-
- step_size = group["lr"]
- if group["bias_correction"]:
- bias_correction = 1 - beta1 ** state["step"]
- step_size /= bias_correction
-
- if group["weight_decay"] != 0:
- p_data_fp32.add_(
- p_data_fp32, alpha=-group["weight_decay"] * group["lr"]
- )
-
- p_data_fp32.addcdiv_(exp_avg, exp_inf.add(eps), value=-step_size)
-
- if p.data.dtype in {torch.float16, torch.bfloat16}:
- p.data.copy_(p_data_fp32)
-
- return loss
diff --git a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq_cli/train.py b/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq_cli/train.py
deleted file mode 100644
index 83475873138c5d1bac288c234afb6b4a1a7882d7..0000000000000000000000000000000000000000
--- a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq_cli/train.py
+++ /dev/null
@@ -1,514 +0,0 @@
-#!/usr/bin/env python3 -u
-# Copyright (c) Facebook, Inc. and its affiliates.
-#
-# This source code is licensed under the MIT license found in the
-# LICENSE file in the root directory of this source tree.
-"""
-Train a new model on one or across multiple GPUs.
-"""
-
-import argparse
-import logging
-import math
-import os
-import sys
-from typing import Dict, Optional, Any, List, Tuple, Callable
-
-# We need to setup root logger before importing any fairseq libraries.
-logging.basicConfig(
- format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
- datefmt="%Y-%m-%d %H:%M:%S",
- level=os.environ.get("LOGLEVEL", "INFO").upper(),
- stream=sys.stdout,
-)
-logger = logging.getLogger("fairseq_cli.train")
-
-import numpy as np
-import torch
-from fairseq import (
- checkpoint_utils,
- options,
- quantization_utils,
- tasks,
- utils,
-)
-from fairseq.data import iterators, data_utils
-from fairseq.data.plasma_utils import PlasmaStore
-from fairseq.dataclass.configs import FairseqConfig
-from fairseq.dataclass.utils import convert_namespace_to_omegaconf
-from fairseq.distributed import fsdp_enable_wrap, fsdp_wrap, utils as distributed_utils
-from fairseq.file_io import PathManager
-from fairseq.logging import meters, metrics, progress_bar
-from fairseq.model_parallel.megatron_trainer import MegatronTrainer
-from fairseq.trainer import Trainer
-from omegaconf import DictConfig, OmegaConf
-
-
-
-
-def main(cfg: FairseqConfig) -> None:
- if isinstance(cfg, argparse.Namespace):
- cfg = convert_namespace_to_omegaconf(cfg)
-
- utils.import_user_module(cfg.common)
-
- if distributed_utils.is_master(cfg.distributed_training) and "job_logging_cfg" in cfg:
- # make hydra logging work with ddp (see # see https://github.com/facebookresearch/hydra/issues/1126)
- logging.config.dictConfig(OmegaConf.to_container(cfg.job_logging_cfg))
-
- assert (
- cfg.dataset.max_tokens is not None or cfg.dataset.batch_size is not None
- ), "Must specify batch size either with --max-tokens or --batch-size"
- metrics.reset()
-
- if cfg.common.log_file is not None:
- handler = logging.FileHandler(filename=cfg.common.log_file)
- logger.addHandler(handler)
-
- np.random.seed(cfg.common.seed)
- utils.set_torch_seed(cfg.common.seed)
-
- if distributed_utils.is_master(cfg.distributed_training):
- checkpoint_utils.verify_checkpoint_directory(cfg.checkpoint.save_dir)
-
- # Print args
- logger.info(cfg)
-
- if cfg.checkpoint.write_checkpoints_asynchronously:
- try:
- import iopath # noqa: F401
- except ImportError:
- logging.exception(
- "Asynchronous checkpoint writing is specified but iopath is "
- "not installed: `pip install iopath`"
- )
- return
-
- # Setup task, e.g., translation, language modeling, etc.
- task = tasks.setup_task(cfg.task)
-
- assert cfg.criterion, "Please specify criterion to train a model"
-
- # Build model and criterion
- if cfg.distributed_training.ddp_backend == "fully_sharded":
- with fsdp_enable_wrap(cfg.distributed_training):
- model = fsdp_wrap(task.build_model(cfg.model))
- else:
- model = task.build_model(cfg.model)
- criterion = task.build_criterion(cfg.criterion)
- logger.info(model)
- logger.info("task: {}".format(task.__class__.__name__))
- logger.info("model: {}".format(model.__class__.__name__))
- logger.info("criterion: {}".format(criterion.__class__.__name__))
- logger.info(
- "num. shared model params: {:,} (num. trained: {:,})".format(
- sum(p.numel() for p in model.parameters() if not getattr(p, "expert", False)),
- sum(p.numel() for p in model.parameters() if not getattr(p, "expert", False) and p.requires_grad)
- )
- )
-
- logger.info(
- "num. expert model params: {} (num. trained: {})".format(
- sum(p.numel() for p in model.parameters() if getattr(p, "expert", False)),
- sum(p.numel() for p in model.parameters() if getattr(p, "expert", False) and p.requires_grad),
- )
- )
-
- # Load valid dataset (we load training data below, based on the latest checkpoint)
- # We load the valid dataset AFTER building the model
- data_utils.raise_if_valid_subsets_unintentionally_ignored(cfg)
- if cfg.dataset.combine_valid_subsets:
- task.load_dataset("valid", combine=True, epoch=1)
- else:
- for valid_sub_split in cfg.dataset.valid_subset.split(","):
- task.load_dataset(valid_sub_split, combine=False, epoch=1)
-
- # (optionally) Configure quantization
- if cfg.common.quantization_config_path is not None:
- quantizer = quantization_utils.Quantizer(
- config_path=cfg.common.quantization_config_path,
- max_epoch=cfg.optimization.max_epoch,
- max_update=cfg.optimization.max_update,
- )
- else:
- quantizer = None
-
- # Build trainer
- if cfg.common.model_parallel_size == 1:
- trainer = Trainer(cfg, task, model, criterion, quantizer)
- else:
- trainer = MegatronTrainer(cfg, task, model, criterion)
- logger.info(
- "training on {} devices (GPUs/TPUs)".format(
- cfg.distributed_training.distributed_world_size
- )
- )
- logger.info(
- "max tokens per device = {} and max sentences per device = {}".format(
- cfg.dataset.max_tokens,
- cfg.dataset.batch_size,
- )
- )
-
- # Load the latest checkpoint if one is available and restore the
- # corresponding train iterator
- extra_state, epoch_itr = checkpoint_utils.load_checkpoint(
- cfg.checkpoint,
- trainer,
- # don't cache epoch iterators for sharded datasets
- disable_iterator_cache=task.has_sharded_data("train"),
- )
- if cfg.common.tpu:
- import torch_xla.core.xla_model as xm
- xm.rendezvous("load_checkpoint") # wait for all workers
-
- max_epoch = cfg.optimization.max_epoch or math.inf
- lr = trainer.get_lr()
-
- train_meter = meters.StopwatchMeter()
- train_meter.start()
- while epoch_itr.next_epoch_idx <= max_epoch:
- if lr <= cfg.optimization.stop_min_lr:
- logger.info(
- f"stopping training because current learning rate ({lr}) is smaller "
- "than or equal to minimum learning rate "
- f"(--stop-min-lr={cfg.optimization.stop_min_lr})"
- )
- break
-
- # train for one epoch
- valid_losses, should_stop = train(cfg, trainer, task, epoch_itr)
- if should_stop:
- break
-
- # only use first validation loss to update the learning rate
- lr = trainer.lr_step(epoch_itr.epoch, valid_losses[0])
-
- epoch_itr = trainer.get_train_iterator(
- epoch_itr.next_epoch_idx,
- # sharded data: get train iterator for next epoch
- load_dataset=task.has_sharded_data("train"),
- # don't cache epoch iterators for sharded datasets
- disable_iterator_cache=task.has_sharded_data("train"),
- )
- train_meter.stop()
- logger.info("done training in {:.1f} seconds".format(train_meter.sum))
-
- # ioPath implementation to wait for all asynchronous file writes to complete.
- if cfg.checkpoint.write_checkpoints_asynchronously:
- logger.info(
- "ioPath PathManager waiting for all asynchronous checkpoint "
- "writes to finish."
- )
- PathManager.async_close()
- logger.info("ioPath PathManager finished waiting.")
-
-
-def should_stop_early(cfg: DictConfig, valid_loss: float) -> bool:
- # skip check if no validation was done in the current epoch
- if valid_loss is None:
- return False
- if cfg.checkpoint.patience <= 0:
- return False
-
- def is_better(a, b):
- return a > b if cfg.checkpoint.maximize_best_checkpoint_metric else a < b
-
- prev_best = getattr(should_stop_early, "best", None)
- if prev_best is None or is_better(valid_loss, prev_best):
- should_stop_early.best = valid_loss
- should_stop_early.num_runs = 0
- return False
- else:
- should_stop_early.num_runs += 1
- if should_stop_early.num_runs >= cfg.checkpoint.patience:
- logger.info(
- "early stop since valid performance hasn't improved for last {} runs".format(
- cfg.checkpoint.patience
- )
- )
- return True
- else:
- return False
-
-
-@metrics.aggregate("train")
-def train(
- cfg: DictConfig, trainer: Trainer, task: tasks.FairseqTask, epoch_itr
-) -> Tuple[List[Optional[float]], bool]:
- """Train the model for one epoch and return validation losses."""
- # Initialize data iterator
- itr = epoch_itr.next_epoch_itr(
- fix_batches_to_gpus=cfg.distributed_training.fix_batches_to_gpus,
- shuffle=(epoch_itr.next_epoch_idx > cfg.dataset.curriculum),
- )
- update_freq = (
- cfg.optimization.update_freq[epoch_itr.epoch - 1]
- if epoch_itr.epoch <= len(cfg.optimization.update_freq)
- else cfg.optimization.update_freq[-1]
- )
- itr = iterators.GroupedIterator(itr, update_freq)
- if cfg.common.tpu:
- itr = utils.tpu_data_loader(itr)
- progress = progress_bar.progress_bar(
- itr,
- log_format=cfg.common.log_format,
- log_file=cfg.common.log_file,
- log_interval=cfg.common.log_interval,
- epoch=epoch_itr.epoch,
- tensorboard_logdir=(
- cfg.common.tensorboard_logdir
- if distributed_utils.is_master(cfg.distributed_training)
- else None
- ),
- default_log_format=("tqdm" if not cfg.common.no_progress_bar else "simple"),
- wandb_project=(
- cfg.common.wandb_project
- if distributed_utils.is_master(cfg.distributed_training)
- else None
- ),
- wandb_run_name=os.environ.get(
- "WANDB_NAME", os.path.basename(cfg.checkpoint.save_dir)
- ),
- azureml_logging=(
- cfg.common.azureml_logging
- if distributed_utils.is_master(cfg.distributed_training)
- else False
- ),
- )
- progress.update_config(_flatten_config(cfg))
-
- trainer.begin_epoch(epoch_itr.epoch)
-
- valid_subsets = cfg.dataset.valid_subset.split(",")
- should_stop = False
- num_updates = trainer.get_num_updates()
- logger.info("Start iterating over samples")
- for i, samples in enumerate(progress):
- with metrics.aggregate("train_inner"), torch.autograd.profiler.record_function(
- "train_step-%d" % i
- ):
- log_output = trainer.train_step(samples)
-
- if log_output is not None: # not OOM, overflow, ...
- # log mid-epoch stats
- num_updates = trainer.get_num_updates()
- if num_updates % cfg.common.log_interval == 0:
- stats = get_training_stats(metrics.get_smoothed_values("train_inner"))
- progress.log(stats, tag="train_inner", step=num_updates)
-
- # reset mid-epoch stats after each log interval
- # the end-of-epoch stats will still be preserved
- metrics.reset_meters("train_inner")
-
- end_of_epoch = not itr.has_next()
- valid_losses, should_stop = validate_and_save(
- cfg, trainer, task, epoch_itr, valid_subsets, end_of_epoch
- )
-
- if should_stop:
- break
-
- # log end-of-epoch stats
- logger.info("end of epoch {} (average epoch stats below)".format(epoch_itr.epoch))
- stats = get_training_stats(metrics.get_smoothed_values("train"))
- progress.print(stats, tag="train", step=num_updates)
-
- # reset epoch-level meters
- metrics.reset_meters("train")
- return valid_losses, should_stop
-
-
-def _flatten_config(cfg: DictConfig):
- config = OmegaConf.to_container(cfg)
- # remove any legacy Namespaces and replace with a single "args"
- namespace = None
- for k, v in list(config.items()):
- if isinstance(v, argparse.Namespace):
- namespace = v
- del config[k]
- if namespace is not None:
- config["args"] = vars(namespace)
- return config
-
-
-def validate_and_save(
- cfg: DictConfig,
- trainer: Trainer,
- task: tasks.FairseqTask,
- epoch_itr,
- valid_subsets: List[str],
- end_of_epoch: bool,
-) -> Tuple[List[Optional[float]], bool]:
- num_updates = trainer.get_num_updates()
- max_update = cfg.optimization.max_update or math.inf
-
- # Stopping conditions (and an additional one based on validation loss later
- # on)
- should_stop = False
- if num_updates >= max_update:
- should_stop = True
- logger.info(
- f"Stopping training due to "
- f"num_updates: {num_updates} >= max_update: {max_update}"
- )
-
- training_time_hours = trainer.cumulative_training_time() / (60 * 60)
- if (
- cfg.optimization.stop_time_hours > 0
- and training_time_hours > cfg.optimization.stop_time_hours
- ):
- should_stop = True
- logger.info(
- f"Stopping training due to "
- f"cumulative_training_time: {training_time_hours} > "
- f"stop_time_hours: {cfg.optimization.stop_time_hours} hour(s)"
- )
-
- do_save = (
- (end_of_epoch and epoch_itr.epoch % cfg.checkpoint.save_interval == 0)
- or should_stop
- or (
- cfg.checkpoint.save_interval_updates > 0
- and num_updates > 0
- and num_updates % cfg.checkpoint.save_interval_updates == 0
- and num_updates >= cfg.dataset.validate_after_updates
- )
- )
- do_validate = (
- (not end_of_epoch and do_save) # validate during mid-epoch saves
- or (end_of_epoch and epoch_itr.epoch % cfg.dataset.validate_interval == 0)
- or should_stop
- or (
- cfg.dataset.validate_interval_updates > 0
- and num_updates > 0
- and num_updates % cfg.dataset.validate_interval_updates == 0
- )
- ) and not cfg.dataset.disable_validation and num_updates >= cfg.dataset.validate_after_updates
-
- # Validate
- valid_losses = [None]
- if do_validate:
- valid_losses = validate(cfg, trainer, task, epoch_itr, valid_subsets)
-
- should_stop |= should_stop_early(cfg, valid_losses[0])
-
- # Save checkpoint
- if do_save or should_stop:
- checkpoint_utils.save_checkpoint(
- cfg.checkpoint, trainer, epoch_itr, valid_losses[0]
- )
-
- return valid_losses, should_stop
-
-
-def get_training_stats(stats: Dict[str, Any]) -> Dict[str, Any]:
- stats["wall"] = round(metrics.get_meter("default", "wall").elapsed_time, 0)
- return stats
-
-
-def validate(
- cfg: DictConfig,
- trainer: Trainer,
- task: tasks.FairseqTask,
- epoch_itr,
- subsets: List[str],
-) -> List[Optional[float]]:
- """Evaluate the model on the validation set(s) and return the losses."""
-
- if cfg.dataset.fixed_validation_seed is not None:
- # set fixed seed for every validation
- utils.set_torch_seed(cfg.dataset.fixed_validation_seed)
-
- trainer.begin_valid_epoch(epoch_itr.epoch)
- valid_losses = []
- for subset in subsets:
- logger.info('begin validation on "{}" subset'.format(subset))
-
- # Initialize data iterator
- itr = trainer.get_valid_iterator(subset).next_epoch_itr(
- shuffle=False, set_dataset_epoch=False # use a fixed valid set
- )
- if cfg.common.tpu:
- itr = utils.tpu_data_loader(itr)
- progress = progress_bar.progress_bar(
- itr,
- log_format=cfg.common.log_format,
- log_interval=cfg.common.log_interval,
- epoch=epoch_itr.epoch,
- prefix=f"valid on '{subset}' subset",
- tensorboard_logdir=(
- cfg.common.tensorboard_logdir
- if distributed_utils.is_master(cfg.distributed_training)
- else None
- ),
- default_log_format=("tqdm" if not cfg.common.no_progress_bar else "simple"),
- wandb_project=(
- cfg.common.wandb_project
- if distributed_utils.is_master(cfg.distributed_training)
- else None
- ),
- wandb_run_name=os.environ.get(
- "WANDB_NAME", os.path.basename(cfg.checkpoint.save_dir)
- ),
- )
-
- # create a new root metrics aggregator so validation metrics
- # don't pollute other aggregators (e.g., train meters)
- with metrics.aggregate(new_root=True) as agg:
- for i, sample in enumerate(progress):
- if cfg.dataset.max_valid_steps is not None and i > cfg.dataset.max_valid_steps:
- break
- trainer.valid_step(sample)
-
- # log validation stats
- stats = get_valid_stats(cfg, trainer, agg.get_smoothed_values())
-
- if hasattr(task, "post_validate"):
- task.post_validate(trainer.get_model(), stats, agg)
-
- progress.print(stats, tag=subset, step=trainer.get_num_updates())
-
- valid_losses.append(stats[cfg.checkpoint.best_checkpoint_metric])
- return valid_losses
-
-
-def get_valid_stats(
- cfg: DictConfig, trainer: Trainer, stats: Dict[str, Any]
-) -> Dict[str, Any]:
- stats["num_updates"] = trainer.get_num_updates()
- if hasattr(checkpoint_utils.save_checkpoint, "best"):
- key = "best_{0}".format(cfg.checkpoint.best_checkpoint_metric)
- best_function = max if cfg.checkpoint.maximize_best_checkpoint_metric else min
- stats[key] = best_function(
- checkpoint_utils.save_checkpoint.best,
- stats[cfg.checkpoint.best_checkpoint_metric],
- )
- return stats
-
-
-def cli_main(
- modify_parser: Optional[Callable[[argparse.ArgumentParser], None]] = None
-) -> None:
- parser = options.get_training_parser()
- args = options.parse_args_and_arch(parser, modify_parser=modify_parser)
-
- cfg = convert_namespace_to_omegaconf(args)
-
- if cfg.common.use_plasma_view:
- server = PlasmaStore(path=cfg.common.plasma_path)
- logger.info(f"Started plasma server pid {server.server.pid} {cfg.common.plasma_path}")
-
- if args.profile:
- with torch.cuda.profiler.profile():
- with torch.autograd.profiler.emit_nvtx():
- distributed_utils.call_main(cfg, main)
- else:
- distributed_utils.call_main(cfg, main)
-
- # if cfg.common.use_plasma_view:
- # server.server.kill()
-
-
-if __name__ == "__main__":
- cli_main()
diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/discriminative_reranking_nmt/README.md b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/discriminative_reranking_nmt/README.md
deleted file mode 100644
index b155e855f2f94e30ad22262f260008fda8ac1804..0000000000000000000000000000000000000000
--- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/discriminative_reranking_nmt/README.md
+++ /dev/null
@@ -1,202 +0,0 @@
-# Discriminative Reranking for Neural Machine Translation
-https://aclanthology.org/2021.acl-long.563/
-
-This folder contains source code for training DrNMT, a discriminatively trained reranker for neural machine translation.
-
-## Data preparation
-1. Follow the instructions under `examples/translation` to build a base MT model. Prepare three files, one with source sentences, one with ground truth target sentences, and one with hypotheses generated from the base MT model. Each line in the file contains one sentence in raw text (i.e. no sentencepiece, etc.). Below is an example of the files with _N_ hypotheses for each source sentence.
-
-```
-# Example of the source sentence file: (The file should contain L lines.)
-
-source_sentence_1
-source_sentence_2
-source_sentence_3
-...
-source_sentence_L
-
-# Example of the target sentence file: (The file should contain L lines.)
-
-target_sentence_1
-target_sentence_2
-target_sentence_3
-...
-target_sentence_L
-
-# Example of the hypotheses file: (The file should contain L*N lines.)
-
-source_sentence_1_hypo_1
-source_sentence_1_hypo_2
-...
-source_sentence_1_hypo_N
-source_sentence_2_hypo_1
-...
-source_sentence_2_hypo_N
-...
-source_sentence_L_hypo_1
-...
-source_sentence_L_hypo_N
-```
-
-2. Download the [XLMR model](https://github.com/fairinternal/fairseq-py/tree/main/examples/xlmr#pre-trained-models).
-```
-wget https://dl.fbaipublicfiles.com/fairseq/models/xlmr.base.tar.gz
-tar zxvf xlmr.base.tar.gz
-
-# The folder should contain dict.txt, model.pt and sentencepiece.bpe.model.
-```
-
-3. Prepare scores and BPE data.
-* `N`: Number of hypotheses per each source sentence. We use 50 in the paper.
-* `SPLIT`: Name of the data split, i.e. train, valid, test. Use split_name, split_name1, split_name2, ..., if there are multiple datasets for a split, e.g. train, train1, valid, valid1.
-* `NUM_SHARDS`: Number of shards. Set this to 1 for non-train splits.
-* `METRIC`: The metric for DrNMT to optimize for. We support either `bleu` or `ter`.
-```
-# For each data split, e.g. train, valid, test, etc., run the following:
-
-SOURCE_FILE=/path/to/source_sentence_file
-TARGET_FILE=/path/to/target_sentence_file
-HYPO_FILE=/path/to/hypo_file
-XLMR_DIR=/path/to/xlmr
-OUTPUT_DIR=/path/to/output
-
-python scripts/prep_data.py \
- --input-source ${SOURCE_FILE} \
- --input-target ${TARGET_FILE} \
- --input-hypo ${HYPO_FILE} \
- --output-dir ${OUTPUT_DIR} \
- --split $SPLIT
- --beam $N \
- --sentencepiece-model ${XLMR_DIR}/sentencepiece.bpe.model \
- --metric $METRIC \
- --num-shards ${NUM_SHARDS}
-
-# The script will create ${OUTPUT_DIR}/$METRIC with ${NUM_SHARDS} splits.
-# Under split*/input_src, split*/input_tgt and split*/$METRIC, there will be $SPLIT.bpe and $SPLIT.$METRIC files, respectively.
-
-```
-
-4. Pre-process the data into fairseq format.
-```
-# use comma to separate if there are more than one train or valid set
-for suffix in src tgt ; do
- fairseq-preprocess --only-source \
- --trainpref ${OUTPUT_DIR}/$METRIC/split1/input_${suffix}/train.bpe \
- --validpref ${OUTPUT_DIR}/$METRIC/split1/input_${suffix}/valid.bpe \
- --destdir ${OUTPUT_DIR}/$METRIC/split1/input_${suffix} \
- --workers 60 \
- --srcdict ${XLMR_DIR}/dict.txt
-done
-
-for i in `seq 2 ${NUM_SHARDS}`; do
- for suffix in src tgt ; do
- fairseq-preprocess --only-source \
- --trainpref ${OUTPUT_DIR}/$METRIC/split${i}/input_${suffix}/train.bpe \
- --destdir ${OUTPUT_DIR}/$METRIC/split${i}/input_${suffix} \
- --workers 60 \
- --srcdict ${XLMR_DIR}/dict.txt
-
- ln -s ${OUTPUT_DIR}/$METRIC/split1/input_${suffix}/valid* ${OUTPUT_DIR}/$METRIC/split${i}/input_${suffix}/.
- done
-
- ln -s ${OUTPUT_DIR}/$METRIC/split1/$METRIC/valid* ${OUTPUT_DIR}/$METRIC/split${i}/$METRIC/.
-done
-```
-
-## Training
-
-```
-EXP_DIR=/path/to/exp
-
-# An example of training the model with the config for De-En experiment in the paper.
-# The config uses 16 GPUs and 50 hypotheses.
-# For training with fewer number of GPUs, set
-# distributed_training.distributed_world_size=k +optimization.update_freq='[x]' where x = 16/k
-# For training with fewer number of hypotheses, set
-# task.mt_beam=N dataset.batch_size=N dataset.required_batch_size_multiple=N
-
-fairseq-hydra-train -m \
- --config-dir config/ --config-name deen \
- task.data=${OUTPUT_DIR}/$METRIC/split1/ \
- task.num_data_splits=${NUM_SHARDS} \
- model.pretrained_model=${XLMR_DIR}/model.pt \
- common.user_dir=${FAIRSEQ_ROOT}/examples/discriminative_reranking_nmt \
- checkpoint.save_dir=${EXP_DIR}
-
-```
-
-## Inference & scoring
-Perform DrNMT reranking (fw + reranker score)
-1. Tune weights on valid sets.
-```
-# genrate N hypotheses with the base MT model (fw score)
-VALID_SOURCE_FILE=/path/to/source_sentences # one sentence per line, converted to the sentencepiece used by the base MT model
-VALID_TARGET_FILE=/path/to/target_sentences # one sentence per line in raw text, i.e. no sentencepiece and tokenization
-MT_MODEL=/path/to/mt_model
-MT_DATA_PATH=/path/to/mt_data
-
-cat ${VALID_SOURCE_FILE} | \
- fairseq-interactive ${MT_DATA_PATH} \
- --max-tokens 4000 --buffer-size 16 \
- --num-workers 32 --path ${MT_MODEL} \
- --beam $N --nbest $N \
- --post-process sentencepiece &> valid-hypo.out
-
-# replace "bleu" with "ter" to optimize for TER
-python drnmt_rerank.py \
- ${OUTPUT_DIR}/$METRIC/split1/ \
- --path ${EXP_DIR}/checkpoint_best.pt \
- --in-text valid-hypo.out \
- --results-path ${EXP_DIR} \
- --gen-subset valid \
- --target-text ${VALID_TARGET_FILE} \
- --user-dir ${FAIRSEQ_ROOT}/examples/discriminative_reranking_nmt \
- --bpe sentencepiece \
- --sentencepiece-model ${XLMR_DIR}/sentencepiece.bpe.model \
- --beam $N \
- --batch-size $N \
- --metric bleu \
- --tune
-
-```
-
-2. Apply best weights on test sets
-```
-# genrate N hypotheses with the base MT model (fw score)
-TEST_SOURCE_FILE=/path/to/source_sentences # one sentence per line, converted to the sentencepiece used by the base MT model
-
-cat ${TEST_SOURCE_FILE} | \
- fairseq-interactive ${MT_DATA_PATH} \
- --max-tokens 4000 --buffer-size 16 \
- --num-workers 32 --path ${MT_MODEL} \
- --beam $N --nbest $N \
- --post-process sentencepiece &> test-hypo.out
-
-# replace "bleu" with "ter" to evaluate TER
-# Add --target-text for evaluating BLEU/TER,
-# otherwise the script will only generate the hypotheses with the highest scores only.
-python drnmt_rerank.py \
- ${OUTPUT_DIR}/$METRIC/split1/ \
- --path ${EXP_DIR}/checkpoint_best.pt \
- --in-text test-hypo.out \
- --results-path ${EXP_DIR} \
- --gen-subset test \
- --user-dir ${FAIRSEQ_ROOT}/examples/discriminative_reranking_nmt \
- --bpe sentencepiece \
- --sentencepiece-model ${XLMR_DIR}/sentencepiece.bpe.model \
- --beam $N \
- --batch-size $N \
- --metric bleu \
- --fw-weight ${BEST_FW_WEIGHT} \
- --lenpen ${BEST_LENPEN}
-```
-
-## Citation
-```bibtex
-@inproceedings{lee2021discriminative,
- title={Discriminative Reranking for Neural Machine Translation},
- author={Lee, Ann and Auli, Michael and Ranzato, Marc'Aurelio},
- booktitle={ACL},
- year={2021}
-}
-```
diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/wav2vec/unsupervised/kaldi_self_train/st/local/copy_aligned_text.py b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/wav2vec/unsupervised/kaldi_self_train/st/local/copy_aligned_text.py
deleted file mode 100644
index 5f4faa99218b0b30c980cad167c52b2297cd92c3..0000000000000000000000000000000000000000
--- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/wav2vec/unsupervised/kaldi_self_train/st/local/copy_aligned_text.py
+++ /dev/null
@@ -1,4 +0,0 @@
-import sys
-
-for idx, line in enumerate(sys.stdin):
- print(f"utt{idx:010d} {line}", end='')
\ No newline at end of file
diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/scoring/tokenizer.py b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/scoring/tokenizer.py
deleted file mode 100644
index 61cf6d4a7cc698258caad9f68f2e8559dd510eee..0000000000000000000000000000000000000000
--- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/scoring/tokenizer.py
+++ /dev/null
@@ -1,67 +0,0 @@
-# Copyright (c) Facebook, Inc. and its affiliates.
-#
-# This source code is licensed under the MIT license found in the
-# LICENSE file in the root directory of this source tree.
-
-import unicodedata
-
-from fairseq.dataclass import ChoiceEnum
-
-
-class EvaluationTokenizer(object):
- """A generic evaluation-time tokenizer, which leverages built-in tokenizers
- in sacreBLEU (https://github.com/mjpost/sacrebleu). It additionally provides
- lowercasing, punctuation removal and character tokenization, which are
- applied after sacreBLEU tokenization.
-
- Args:
- tokenizer_type (str): the type of sacreBLEU tokenizer to apply.
- lowercase (bool): lowercase the text.
- punctuation_removal (bool): remove punctuation (based on unicode
- category) from text.
- character_tokenization (bool): tokenize the text to characters.
- """
-
- SPACE = chr(32)
- SPACE_ESCAPE = chr(9601)
- ALL_TOKENIZER_TYPES = ChoiceEnum(["none", "13a", "intl", "zh", "ja-mecab"])
-
- def __init__(
- self,
- tokenizer_type: str = "13a",
- lowercase: bool = False,
- punctuation_removal: bool = False,
- character_tokenization: bool = False,
- ):
- from sacrebleu.tokenizers import TOKENIZERS
-
- assert tokenizer_type in TOKENIZERS, f"{tokenizer_type}, {TOKENIZERS}"
- self.lowercase = lowercase
- self.punctuation_removal = punctuation_removal
- self.character_tokenization = character_tokenization
- self.tokenizer = TOKENIZERS[tokenizer_type]
-
- @classmethod
- def remove_punctuation(cls, sent: str):
- """Remove punctuation based on Unicode category."""
- return cls.SPACE.join(
- t
- for t in sent.split(cls.SPACE)
- if not all(unicodedata.category(c)[0] == "P" for c in t)
- )
-
- def tokenize(self, sent: str):
- tokenized = self.tokenizer()(sent)
-
- if self.punctuation_removal:
- tokenized = self.remove_punctuation(tokenized)
-
- if self.character_tokenization:
- tokenized = self.SPACE.join(
- list(tokenized.replace(self.SPACE, self.SPACE_ESCAPE))
- )
-
- if self.lowercase:
- tokenized = tokenized.lower()
-
- return tokenized
diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/tests/test_dictionary.py b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/tests/test_dictionary.py
deleted file mode 100644
index dc9d71b3c722ce3066e182d4b237b2a72999d4d0..0000000000000000000000000000000000000000
--- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/tests/test_dictionary.py
+++ /dev/null
@@ -1,145 +0,0 @@
-# Copyright (c) Facebook, Inc. and its affiliates.
-#
-# This source code is licensed under the MIT license found in the
-# LICENSE file in the root directory of this source tree.
-
-import io
-import os
-import string
-import tempfile
-import unittest
-
-import torch
-from fairseq import tokenizer
-from fairseq.data import Dictionary
-
-
-class TestDictionary(unittest.TestCase):
- def test_finalize(self):
- txt = [
- "A B C D",
- "B C D",
- "C D",
- "D",
- ]
- ref_ids1 = list(
- map(
- torch.IntTensor,
- [
- [4, 5, 6, 7, 2],
- [5, 6, 7, 2],
- [6, 7, 2],
- [7, 2],
- ],
- )
- )
- ref_ids2 = list(
- map(
- torch.IntTensor,
- [
- [7, 6, 5, 4, 2],
- [6, 5, 4, 2],
- [5, 4, 2],
- [4, 2],
- ],
- )
- )
-
- # build dictionary
- d = Dictionary()
- for line in txt:
- d.encode_line(line, add_if_not_exist=True)
-
- def get_ids(dictionary):
- ids = []
- for line in txt:
- ids.append(dictionary.encode_line(line, add_if_not_exist=False))
- return ids
-
- def assertMatch(ids, ref_ids):
- for toks, ref_toks in zip(ids, ref_ids):
- self.assertEqual(toks.size(), ref_toks.size())
- self.assertEqual(0, (toks != ref_toks).sum().item())
-
- ids = get_ids(d)
- assertMatch(ids, ref_ids1)
-
- # check finalized dictionary
- d.finalize()
- finalized_ids = get_ids(d)
- assertMatch(finalized_ids, ref_ids2)
-
- # write to disk and reload
- with tempfile.NamedTemporaryFile(mode="w") as tmp_dict:
- d.save(tmp_dict.name)
- d = Dictionary.load(tmp_dict.name)
- reload_ids = get_ids(d)
- assertMatch(reload_ids, ref_ids2)
- assertMatch(finalized_ids, reload_ids)
-
- def test_overwrite(self):
- # for example, Camembert overwrites , and
- dict_file = io.StringIO(
- " 999 #fairseq:overwrite\n"
- " 999 #fairseq:overwrite\n"
- " 999 #fairseq:overwrite\n"
- ", 999\n"
- "▁de 999\n"
- )
- d = Dictionary()
- d.add_from_file(dict_file)
- self.assertEqual(d.index(""), 1)
- self.assertEqual(d.index("foo"), 3)
- self.assertEqual(d.index(""), 4)
- self.assertEqual(d.index(""), 5)
- self.assertEqual(d.index(""), 6)
- self.assertEqual(d.index(","), 7)
- self.assertEqual(d.index("▁de"), 8)
-
- def test_no_overwrite(self):
- # for example, Camembert overwrites , and
- dict_file = io.StringIO(
- " 999\n" " 999\n" " 999\n" ", 999\n" "▁de 999\n"
- )
- d = Dictionary()
- with self.assertRaisesRegex(RuntimeError, "Duplicate"):
- d.add_from_file(dict_file)
-
- def test_space(self):
- # for example, character models treat space as a symbol
- dict_file = io.StringIO(" 999\n" "a 999\n" "b 999\n")
- d = Dictionary()
- d.add_from_file(dict_file)
- self.assertEqual(d.index(" "), 4)
- self.assertEqual(d.index("a"), 5)
- self.assertEqual(d.index("b"), 6)
-
- def test_add_file_to_dict(self):
- counts = {}
- num_lines = 100
- per_line = 10
- with tempfile.TemporaryDirectory("test_sampling") as data_dir:
- filename = os.path.join(data_dir, "dummy.txt")
- with open(filename, "w", encoding="utf-8") as data:
- for c in string.ascii_letters:
- line = f"{c} " * per_line
- for _ in range(num_lines):
- data.write(f"{line}\n")
- counts[c] = per_line * num_lines
- per_line += 5
-
- dict = Dictionary()
- Dictionary.add_file_to_dictionary(
- filename, dict, tokenizer.tokenize_line, 10
- )
- dict.finalize(threshold=0, nwords=-1, padding_factor=8)
-
- for c in string.ascii_letters:
- count = dict.get_count(dict.index(c))
- self.assertEqual(
- counts[c], count, f"{c} count is {count} but should be {counts[c]}"
- )
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/nonautoregressive_translation/scripts.md b/spaces/OFA-Sys/OFA-vqa/fairseq/examples/nonautoregressive_translation/scripts.md
deleted file mode 100644
index 9d3d7b67dc08440b5f4d1c5a7ffcd4bd6e76c14f..0000000000000000000000000000000000000000
--- a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/nonautoregressive_translation/scripts.md
+++ /dev/null
@@ -1,179 +0,0 @@
-# Examples of Training scripts for Non-autoregressive Machine Translation models
-
-### Non-autoregressive Transformer (NAT, Gu et al., 2017)
-Note that we need to have an additional module to perform "length prediction" (`--length-loss-factor`) before generating the whole sequence.
-```bash
-fairseq-train \
- data-bin/wmt14_en_de_distill \
- --save-dir checkpoints \
- --ddp-backend=legacy_ddp \
- --task translation_lev \
- --criterion nat_loss \
- --arch nonautoregressive_transformer \
- --noise full_mask \
- --share-all-embeddings \
- --optimizer adam --adam-betas '(0.9,0.98)' \
- --lr 0.0005 --lr-scheduler inverse_sqrt \
- --stop-min-lr '1e-09' --warmup-updates 10000 \
- --warmup-init-lr '1e-07' --label-smoothing 0.1 \
- --dropout 0.3 --weight-decay 0.01 \
- --decoder-learned-pos \
- --encoder-learned-pos \
- --pred-length-offset \
- --length-loss-factor 0.1 \
- --apply-bert-init \
- --log-format 'simple' --log-interval 100 \
- --fixed-validation-seed 7 \
- --max-tokens 8000 \
- --save-interval-updates 10000 \
- --max-update 300000
-```
-
-### Fast Structured Decoding for Sequence Models (NAT-CRF, Sun et al., 2019)
-Note that we implemented a low-rank appromixated CRF model by setting `--crf-lowrank-approx=32` and `--crf-beam-approx=64` as discribed in the original paper. All other settings are the same as the vanilla NAT model.
-```bash
-fairseq-train \
- data-bin/wmt14_en_de_distill \
- --save-dir checkpoints \
- --ddp-backend=legacy_ddp \
- --task translation_lev \
- --criterion nat_loss \
- --arch nacrf_transformer \
- --noise full_mask \
- --share-all-embeddings \
- --optimizer adam --adam-betas '(0.9,0.98)' \
- --lr 0.0005 --lr-scheduler inverse_sqrt \
- --stop-min-lr '1e-09' --warmup-updates 10000 \
- --warmup-init-lr '1e-07' --label-smoothing 0.1 \
- --dropout 0.3 --weight-decay 0.01 \
- --decoder-learned-pos \
- --encoder-learned-pos \
- --pred-length-offset \
- --length-loss-factor 0.1 \
- --word-ins-loss-factor 0.5 \
- --crf-lowrank-approx 32 \
- --crf-beam-approx 64 \
- --apply-bert-init \
- --log-format 'simple' --log-interval 100 \
- --fixed-validation-seed 7 \
- --max-tokens 8000 \
- --save-interval-updates 10000 \
- --max-update 300000
-```
-
-
-### Non-autoregressive Transformer with Iterative Refinement (iNAT, Lee et al., 2018)
-Note that `--train-step` means how many iterations of refinement we used during training, and `--dae-ratio` controls the ratio of denoising auto-encoder training described in the original paper.
-```bash
-fairseq-train \
- data-bin/wmt14_en_de_distill \
- --save-dir checkpoints \
- --ddp-backend=legacy_ddp \
- --task translation_lev \
- --criterion nat_loss \
- --arch iterative_nonautoregressive_transformer \
- --noise full_mask \
- --share-all-embeddings \
- --optimizer adam --adam-betas '(0.9,0.98)' \
- --lr 0.0005 --lr-scheduler inverse_sqrt \
- --stop-min-lr '1e-09' --warmup-updates 10000 \
- --warmup-init-lr '1e-07' --label-smoothing 0.1 \
- --dropout 0.3 --weight-decay 0.01 \
- --decoder-learned-pos \
- --encoder-learned-pos \
- --pred-length-offset \
- --length-loss-factor 0.1 \
- --train-step 4 \
- --dae-ratio 0.5 \
- --stochastic-approx \
- --apply-bert-init \
- --log-format 'simple' --log-interval 100 \
- --fixed-validation-seed 7 \
- --max-tokens 8000 \
- --save-interval-updates 10000 \
- --max-update 300000
-```
-
-### Insertion Transformer (InsT, Stern et al., 2019)
-Note that we need to specify the "slot-loss" (uniform or balanced tree) described in the original paper. Here we use `--label-tau` to control the temperature.
-
-```bash
-fairseq-train \
- data-bin/wmt14_en_de_distill \
- --save-dir checkpoints \
- --ddp-backend=legacy_ddp \
- --task translation_lev \
- --criterion nat_loss \
- --arch insertion_transformer \
- --noise random_delete \
- --share-all-embeddings \
- --optimizer adam --adam-betas '(0.9,0.98)' \
- --lr 0.0005 --lr-scheduler inverse_sqrt \
- --stop-min-lr '1e-09' --warmup-updates 10000 \
- --warmup-init-lr '1e-07' --label-smoothing 0.1 \
- --dropout 0.3 --weight-decay 0.01 \
- --decoder-learned-pos \
- --encoder-learned-pos \
- --apply-bert-init \
- --log-format 'simple' --log-interval 100 \
- --fixed-validation-seed 7 \
- --max-tokens 8000 \
- --save-interval-updates 10000 \
- --max-update 300000
-```
-
-
-### Mask Predict (CMLM, Ghazvininejad et al., 2019)
-```bash
-fairseq-train \
- data-bin/wmt14_en_de_distill \
- --save-dir checkpoints \
- --ddp-backend=legacy_ddp \
- --task translation_lev \
- --criterion nat_loss \
- --arch cmlm_transformer \
- --noise random_mask \
- --share-all-embeddings \
- --optimizer adam --adam-betas '(0.9,0.98)' \
- --lr 0.0005 --lr-scheduler inverse_sqrt \
- --stop-min-lr '1e-09' --warmup-updates 10000 \
- --warmup-init-lr '1e-07' --label-smoothing 0.1 \
- --dropout 0.3 --weight-decay 0.01 \
- --decoder-learned-pos \
- --encoder-learned-pos \
- --apply-bert-init \
- --log-format 'simple' --log-interval 100 \
- --fixed-validation-seed 7 \
- --max-tokens 8000 \
- --save-interval-updates 10000 \
- --max-update 300000
-```
-
-
-
-
-### Levenshtein Transformer (LevT, Gu et al., 2019)
-```bash
-fairseq-train \
- data-bin/wmt14_en_de_distill \
- --save-dir checkpoints \
- --ddp-backend=legacy_ddp \
- --task translation_lev \
- --criterion nat_loss \
- --arch levenshtein_transformer \
- --noise random_delete \
- --share-all-embeddings \
- --optimizer adam --adam-betas '(0.9,0.98)' \
- --lr 0.0005 --lr-scheduler inverse_sqrt \
- --stop-min-lr '1e-09' --warmup-updates 10000 \
- --warmup-init-lr '1e-07' --label-smoothing 0.1 \
- --dropout 0.3 --weight-decay 0.01 \
- --decoder-learned-pos \
- --encoder-learned-pos \
- --apply-bert-init \
- --log-format 'simple' --log-interval 100 \
- --fixed-validation-seed 7 \
- --max-tokens 8000 \
- --save-interval-updates 10000 \
- --max-update 300000
-```
diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/clib/libbleu/module.cpp b/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/clib/libbleu/module.cpp
deleted file mode 100644
index 35288b3177185670135f7bdc1f1589c5bb992304..0000000000000000000000000000000000000000
--- a/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/clib/libbleu/module.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * Copyright 2017-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the license found in the
- * LICENSE file in the root directory of this source tree.
- */
-
-#include
-
-static PyMethodDef method_def[] = {{NULL, NULL, 0, NULL}}; // NOLINT
-
-static struct PyModuleDef module_def = {
- PyModuleDef_HEAD_INIT,
- "libbleu", /* name of module */
- // NOLINTNEXTLINE
- NULL, /* module documentation, may be NULL */
- -1, /* size of per-interpreter state of the module,
- or -1 if the module keeps state in global variables. */
- method_def}; // NOLINT
-
-#if PY_MAJOR_VERSION == 2
-PyMODINIT_FUNC init_libbleu()
-#else
-PyMODINIT_FUNC PyInit_libbleu()
-#endif
-{
- PyObject* m = PyModule_Create(&module_def);
- if (!m) {
- return NULL;
- }
- return m;
-}
diff --git a/spaces/OpenGVLab/InternGPT/iGPT/models/grit_src/third_party/CenterNet2/configs/new_baselines/mask_rcnn_regnetx_4gf_dds_FPN_100ep_LSJ.py b/spaces/OpenGVLab/InternGPT/iGPT/models/grit_src/third_party/CenterNet2/configs/new_baselines/mask_rcnn_regnetx_4gf_dds_FPN_100ep_LSJ.py
deleted file mode 100644
index ef0b6d16d4403fb5d16a3aeb71a22621a0be5e21..0000000000000000000000000000000000000000
--- a/spaces/OpenGVLab/InternGPT/iGPT/models/grit_src/third_party/CenterNet2/configs/new_baselines/mask_rcnn_regnetx_4gf_dds_FPN_100ep_LSJ.py
+++ /dev/null
@@ -1,29 +0,0 @@
-from .mask_rcnn_R_50_FPN_100ep_LSJ import (
- dataloader,
- lr_multiplier,
- model,
- optimizer,
- train,
-)
-from detectron2.config import LazyCall as L
-from detectron2.modeling.backbone import RegNet
-from detectron2.modeling.backbone.regnet import SimpleStem, ResBottleneckBlock
-
-# Config source:
-# https://github.com/facebookresearch/detectron2/blob/main/configs/COCO-InstanceSegmentation/mask_rcnn_regnetx_4gf_dds_fpn_1x.py # noqa
-model.backbone.bottom_up = L(RegNet)(
- stem_class=SimpleStem,
- stem_width=32,
- block_class=ResBottleneckBlock,
- depth=23,
- w_a=38.65,
- w_0=96,
- w_m=2.43,
- group_width=40,
- norm="SyncBN",
- out_features=["s1", "s2", "s3", "s4"],
-)
-model.pixel_std = [57.375, 57.120, 58.395]
-
-# RegNets benefit from enabling cudnn benchmark mode
-train.cudnn_benchmark = True
diff --git a/spaces/OpenGVLab/InternGPT/iGPT/models/grit_src/third_party/CenterNet2/tests/test_packaging.py b/spaces/OpenGVLab/InternGPT/iGPT/models/grit_src/third_party/CenterNet2/tests/test_packaging.py
deleted file mode 100644
index a5b1661e8f341fe66a6e02c59fe172bce445782b..0000000000000000000000000000000000000000
--- a/spaces/OpenGVLab/InternGPT/iGPT/models/grit_src/third_party/CenterNet2/tests/test_packaging.py
+++ /dev/null
@@ -1,24 +0,0 @@
-# Copyright (c) Facebook, Inc. and its affiliates.
-import unittest
-
-from detectron2.utils.collect_env import collect_env_info
-
-
-class TestProjects(unittest.TestCase):
- def test_import(self):
- from detectron2.projects import point_rend
-
- _ = point_rend.add_pointrend_config
-
- import detectron2.projects.deeplab as deeplab
-
- _ = deeplab.add_deeplab_config
-
- # import detectron2.projects.panoptic_deeplab as panoptic_deeplab
-
- # _ = panoptic_deeplab.add_panoptic_deeplab_config
-
-
-class TestCollectEnv(unittest.TestCase):
- def test(self):
- _ = collect_env_info()
diff --git a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/configs/_base_/models/ccnet_r50-d8.py b/spaces/PAIR/Text2Video-Zero/annotator/uniformer/configs/_base_/models/ccnet_r50-d8.py
deleted file mode 100644
index 794148f576b9e215c3c6963e73dffe98204b7717..0000000000000000000000000000000000000000
--- a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/configs/_base_/models/ccnet_r50-d8.py
+++ /dev/null
@@ -1,44 +0,0 @@
-# model settings
-norm_cfg = dict(type='SyncBN', requires_grad=True)
-model = dict(
- type='EncoderDecoder',
- pretrained='open-mmlab://resnet50_v1c',
- backbone=dict(
- type='ResNetV1c',
- depth=50,
- num_stages=4,
- out_indices=(0, 1, 2, 3),
- dilations=(1, 1, 2, 4),
- strides=(1, 2, 1, 1),
- norm_cfg=norm_cfg,
- norm_eval=False,
- style='pytorch',
- contract_dilation=True),
- decode_head=dict(
- type='CCHead',
- in_channels=2048,
- in_index=3,
- channels=512,
- recurrence=2,
- dropout_ratio=0.1,
- num_classes=19,
- norm_cfg=norm_cfg,
- align_corners=False,
- loss_decode=dict(
- type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),
- auxiliary_head=dict(
- type='FCNHead',
- in_channels=1024,
- in_index=2,
- channels=256,
- num_convs=1,
- concat_input=False,
- dropout_ratio=0.1,
- num_classes=19,
- norm_cfg=norm_cfg,
- align_corners=False,
- loss_decode=dict(
- type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.4)),
- # model training and testing settings
- train_cfg=dict(),
- test_cfg=dict(mode='whole'))
diff --git a/spaces/PaddlePaddle/transformer_zh-en/README.md b/spaces/PaddlePaddle/transformer_zh-en/README.md
deleted file mode 100644
index d34f919710fe1889318bc6f0ecf496fc817db637..0000000000000000000000000000000000000000
--- a/spaces/PaddlePaddle/transformer_zh-en/README.md
+++ /dev/null
@@ -1,13 +0,0 @@
----
-title: Transformer Zh-en
-emoji: 💻
-colorFrom: indigo
-colorTo: indigo
-sdk: gradio
-sdk_version: 3.3
-app_file: app.py
-pinned: false
-license: apache-2.0
----
-
-Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
diff --git a/spaces/PeepDaSlan9/De-limiter/eval_delimit/score_features.py b/spaces/PeepDaSlan9/De-limiter/eval_delimit/score_features.py
deleted file mode 100644
index 10ac3b361824975b564c35f946f1d16bb740b9ed..0000000000000000000000000000000000000000
--- a/spaces/PeepDaSlan9/De-limiter/eval_delimit/score_features.py
+++ /dev/null
@@ -1,233 +0,0 @@
-import os
-import argparse
-import csv
-import json
-import glob
-from typing import Any, Optional, Union, Collection
-
-import tqdm
-import numpy as np
-import librosa
-from librosa.core.spectrum import _spectrogram
-import musdb
-import essentia
-import essentia.standard
-import pyloudnorm as pyln
-
-from utils import str2bool, db2linear
-
-
-def spectral_crest(
- *,
- y: Optional[np.ndarray] = None,
- S: Optional[np.ndarray] = None,
- n_fft: int = 2048,
- hop_length: int = 512,
- win_length: Optional[int] = None,
- window: str = "hann",
- center: bool = True,
- pad_mode: str = "constant",
- amin: float = 1e-10,
- power: float = 2.0,
-) -> np.ndarray:
- """Compute spectral crest
-
- Spectral crest (or tonality coefficient) is a measure of
- the ratio of the maximum of the spectrum to the arithmetic mean of the spectrum
-
- A higher spectral crest => more tonality,
- A lower spectral crest => more noisy.
-
-
- Parameters
- ----------
- y : np.ndarray [shape=(..., n)] or None
- audio time series. Multi-channel is supported.
- S : np.ndarray [shape=(..., d, t)] or None
- (optional) pre-computed spectrogram magnitude
- n_fft : int > 0 [scalar]
- FFT window size
- hop_length : int > 0 [scalar]
- hop length for STFT. See `librosa.stft` for details.
- win_length : int <= n_fft [scalar]
- Each frame of audio is windowed by `window()`.
- The window will be of length `win_length` and then padded
- with zeros to match ``n_fft``.
- If unspecified, defaults to ``win_length = n_fft``.
- window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)]
- - a window specification (string, tuple, or number);
- see `scipy.signal.get_window`
- - a window function, such as `scipy.signal.windows.hann`
- - a vector or array of length ``n_fft``
- .. see also:: `librosa.filters.get_window`
- center : boolean
- - If `True`, the signal ``y`` is padded so that frame
- ``t`` is centered at ``y[t * hop_length]``.
- - If `False`, then frame `t` begins at ``y[t * hop_length]``
- pad_mode : string
- If ``center=True``, the padding mode to use at the edges of the signal.
- By default, STFT uses zero padding.
- amin : float > 0 [scalar]
- minimum threshold for ``S`` (=added noise floor for numerical stability)
- power : float > 0 [scalar]
- Exponent for the magnitude spectrogram.
- e.g., 1 for energy, 2 for power, etc.
- Power spectrogram is usually used for computing spectral flatness.
-
- Returns
- -------
- crest : np.ndarray [shape=(..., 1, t)]
- spectral crest for each frame.
-
-
- """
-
- S, n_fft = _spectrogram(
- y=y,
- S=S,
- n_fft=n_fft,
- hop_length=hop_length,
- power=1.0,
- win_length=win_length,
- window=window,
- center=center,
- pad_mode=pad_mode,
- )
-
- S_thresh = np.maximum(amin, S**power)
- # gmean = np.exp(np.mean(np.log(S_thresh), axis=-2, keepdims=True))
- gmax = np.max(S_thresh, axis=-2, keepdims=True)
- amean = np.mean(S_thresh, axis=-2, keepdims=True)
- crest: np.ndarray = gmax / amean
- return crest
-
-
-parser = argparse.ArgumentParser(description="model test.py")
-
-parser.add_argument(
- "--target",
- type=str,
- default="all",
- help="target source. all, vocals, drums, bass, other",
-)
-parser.add_argument(
- "--root", type=str, default="/path/to/musdb18hq_loudnorm"
-)
-parser.add_argument("--exp_name", type=str, default="delimit_6_s")
-parser.add_argument(
- "--output_directory",
- type=str,
- default="/path/to/results",
-)
-parser.add_argument(
- "--calc_results",
- type=str2bool,
- default=True,
- help="calculate results or musdb-hq or musdb-XL test dataset",
-)
-
-
-args, _ = parser.parse_known_args()
-
-args.sample_rate = 44100
-
-args.test_output_dir = f"{args.output_directory}/test/{args.exp_name}"
-
-if args.calc_results:
- track_list = glob.glob(
- f"{args.output_directory}/test/{args.exp_name}/*/{args.target}.wav"
- )
-else:
- if args.target == "all":
- track_list = glob.glob(f"{args.root}/*/mixture.wav")
- else:
- track_list = glob.glob(f"{args.root}/*/{args.target}.wav")
-
-i = 0
-
-
-dynamic_complexity = essentia.standard.DynamicComplexity()
-loudness_range = essentia.standard.LoudnessEBUR128()
-spectral_centroid = essentia.standard.SpectralCentroidTime()
-crest = essentia.standard.Crest()
-dynamic_spread = essentia.standard.DistributionShape()
-central_moments = essentia.standard.CentralMoments()
-
-dict_song_score = {}
-list_rms = []
-list_crest_factor = []
-list_dc_score = []
-list_lra_score = []
-list_sc_hertz = []
-list_sf_score = []
-list_spectral_crest_score = []
-
-for track in tqdm.tqdm(track_list):
- audio_name = os.path.basename(os.path.dirname(track))
- gt_source_librosa = librosa.load(f"{track}", sr=args.sample_rate, mono=False)[
- 0
- ] # (nb_channels, nb_samples)
- gt_source_librosa_mono = librosa.to_mono(gt_source_librosa) # (nb_samples)
-
- gt_source_essentia = essentia.standard.AudioLoader(filename=f"{track}")()[
- 0
- ] # (nb_samples, nb_channels)
- gt_source_essentia_cat = np.concatenate(
- [gt_source_essentia[:, 0], gt_source_essentia[:, 1]]
- ) # (nb_samples * nb_channels)
- gt_source_essentia_mono = np.mean(gt_source_essentia, axis=1) # (nb_samples)
-
- rms = np.sqrt(np.mean(gt_source_essentia_cat**2))
- crest_factor = np.max(np.abs(gt_source_essentia_cat)) / rms
-
- dc_score, _ = dynamic_complexity(gt_source_essentia_mono)
- _, _, _, lra_score = loudness_range(gt_source_essentia)
- sc_hertz = spectral_centroid(gt_source_essentia_mono)
- sf_score = np.mean(librosa.feature.spectral_flatness(gt_source_librosa_mono))
- spectral_crest_score = np.mean(spectral_crest(y=gt_source_librosa_mono))
-
- dict_song_score[audio_name] = {
- "rms": float(rms),
- "crest_factor": float(crest_factor),
- "dynamic_complexity_score": float(dc_score),
- "lra_score": float(lra_score),
- "spectral_centroid_hertz": float(sc_hertz),
- "spectral_flatness_score": float(sf_score),
- "spectral_crest_score": float(spectral_crest_score),
- }
- list_rms.append(rms)
- list_crest_factor.append(crest_factor)
- list_dc_score.append(dc_score)
- list_lra_score.append(lra_score)
- list_sc_hertz.append(sc_hertz)
- list_sf_score.append(sf_score)
- list_spectral_crest_score.append(spectral_crest_score)
-
- i += 1
-
-if args.calc_results:
- print(f"{args.exp_name} on {args.target}")
-else:
- print(f"{os.path.basename(args.root)} on {args.target}")
-print(f"rms: {np.mean(list_rms)}")
-print(f"crest_factor: {np.mean(list_crest_factor)}")
-print(f"dynamic_complexity_score: {np.mean(list_dc_score)}")
-print(f"lra_score: {np.mean(list_lra_score)}")
-print(f"sc_hertz: {np.mean(list_sc_hertz)}")
-print(f"sf_score: {np.mean(list_sf_score)}")
-print(f"spectral_crest_score: {np.mean(list_spectral_crest_score)}")
-
-
-# save dict_song_score to json file
-if args.target == "all":
- file_name = "score_features"
-else:
- file_name = f"score_feature_{args.target}"
-if args.calc_results:
- with open(
- f"{args.output_directory}/test/{args.exp_name}/{file_name}.json", "w"
- ) as f:
- json.dump(dict_song_score, f, indent=4)
-else:
- with open(f"{args.root}/{file_name}.json", "w") as f:
- json.dump(dict_song_score, f, indent=4)
diff --git a/spaces/Priyanka-Kumavat/Regression-Model/app.py b/spaces/Priyanka-Kumavat/Regression-Model/app.py
deleted file mode 100644
index be100a1aeda7d723514261fd8b48bded4dc848f3..0000000000000000000000000000000000000000
--- a/spaces/Priyanka-Kumavat/Regression-Model/app.py
+++ /dev/null
@@ -1,159 +0,0 @@
-# import required libraries
-
-import pandas as pd
-import numpy as np
-import matplotlib.pyplot as plt
-import seaborn as sns
-import pickle
-import joblib
-import os
-
-from datetime import datetime
-from datetime import timedelta
-from sklearn.model_selection import RandomizedSearchCV, GridSearchCV, train_test_split
-from sklearn.ensemble import RandomForestRegressor
-from sklearn.metrics import r2_score
-from sklearn.preprocessing import LabelEncoder
-from sklearn.preprocessing import StandardScaler
-import streamlit as st
-import warnings
-warnings.filterwarnings('ignore')
-
-st.title("Predict Unrolled Values")
-st.sidebar.header('Enter the Details here')
-st.write("""This Random Forest Regressor model helps to forecast unrolled values with impressive accuracy.
- Leveraging the strength of the Random Forest technique, we can now make reliable predictions that
- enable us to plan and strategize effectively in the fast-paced media landscape.""")
-
-# load the saved model using pickle
-with open('aajTak_model.pkl', 'rb') as file:
- model = pickle.load(file)
-
-# # # load the saved model using joblib
-# model3 = joblib.load('aajTak_model.joblib')
-
-# Load the saved weekDay label encoder object using pickle
-with open('weekDay_le.pkl','rb') as file1:
- weekDay_le = pickle.load(file1)
-
-# Load the saved timeBand label encoder object using pickle
-with open('timeBand_le.pkl','rb') as file2:
- timeBand_le = pickle.load(file2)
-
-# previous_number_of_repairs =
-# st.sidebar.number_input('Enter the Previous Number of Repairs Undergone 0 to 5 )',min_value=0,max_value=5,step=1)
-
-# DATA from user
-def user_report():
-
- # Share = round(float(st.sidebar.slider('Share', 0.000000, 100.000000, 0.611246, step=0.000001)), 6)
- # AMA = round(float(st.sidebar.slider('AMA', 0.000000, 45.000000, 4.196084, step=0.000001)), 6)
- # rate = round(float(st.sidebar.slider('rate', 0.000000, 1.500000, 0.018516, step=0.000001)), 6)
- # daily_reach = round(float(st.sidebar.slider('daily reach', 0.000000, 300.000000, 36.23)), 6)
- # cume_reach = round(float(st.sidebar.slider('cume reach', 0.000000, 300.000000, 36.231006)), 6)
-
-
- Share = round(float(st.sidebar.number_input('Share', 0.0, 100.0, 0.611246, step=0.000001)), 6)
- AMA = round(float(st.sidebar.number_input('AMA', 0.0, 45.0, 4.196084, step=0.000001)), 6)
- rate = round(float(st.sidebar.number_input('rate', 0.0, 1.5, 0.018516, step=0.000001)), 6)
- daily_reach = round(float(st.sidebar.number_input('daily reach', 0.0, 300.0, 36.23, step=0.000001)), 6)
- cume_reach = round(float(st.sidebar.number_input('cume reach', 0.0, 300.0, 36.231006, step=0.000001)), 6)
-
-
-
- # Share = st.sidebar.slider('Share', 0, 100, 0)
- # AMA = st.sidebar.slider('AMA', 0, 45, 4)
- # rate = st.sidebar.slider('rate', 0, 1, 0)
- # daily_reach = st.sidebar.slider('daily reach', 0, 300, 36)
- # cume_reach = st.sidebar.slider('cume reach', 0, 300, 36)
-
- # Output: {'Friday': 0, 'Monday': 1, 'Saturday': 2, 'Sunday': 3, 'Thursday': 4, 'Tuesday': 5, 'Wednesday': 6}
-
- Week_Day_Encoded = st.sidebar.selectbox("Week Day",
- ("Monday", "Tuesday","Wednesday","Thursday","Friday", "Saturday", "Sunday" ))
- if Week_Day_Encoded=='Monday':
- Week_Day_Encoded=1
- elif Week_Day_Encoded=="Tuesday":
- Week_Day_Encoded=5
- elif Week_Day_Encoded=="Wednesday":
- Week_Day_Encoded=6
- elif Week_Day_Encoded=="Thursday":
- Week_Day_Encoded =4
- elif Week_Day_Encoded=="Friday":
- Week_Day_Encoded =0
- elif Week_Day_Encoded=="Saturday":
- Week_Day_Encoded =2
- else:
- Week_Day_Encoded=3
-
-
- # The Time Band dictionary provided
- time_band_dict = {
- '02:00:00 - 02:30:00': 0, '02:30:00 - 03:00:00': 1, '03:00:00 - 03:30:00': 2, '03:30:00 - 04:00:00': 3,
- '04:00:00 - 04:30:00': 4, '04:30:00 - 05:00:00': 5, '05:00:00 - 05:30:00': 6, '05:30:00 - 06:00:00': 7,
- '06:00:00 - 06:30:00': 8, '06:30:00 - 07:00:00': 9, '07:00:00 - 07:30:00': 10, '07:30:00 - 08:00:00': 11,
- '08:00:00 - 08:30:00': 12, '08:30:00 - 09:00:00': 13, '09:00:00 - 09:30:00': 14, '09:30:00 - 10:00:00': 15,
- '10:00:00 - 10:30:00': 16, '10:30:00 - 11:00:00': 17, '11:00:00 - 11:30:00': 18, '11:30:00 - 12:00:00': 19,
- '12:00:00 - 12:30:00': 20, '12:30:00 - 13:00:00': 21, '13:00:00 - 13:30:00': 22, '13:30:00 - 14:00:00': 23,
- '14:00:00 - 14:30:00': 24, '14:30:00 - 15:00:00': 25, '15:00:00 - 15:30:00': 26, '15:30:00 - 16:00:00': 27,
- '16:00:00 - 16:30:00': 28, '16:30:00 - 17:00:00': 29, '17:00:00 - 17:30:00': 30, '17:30:00 - 18:00:00': 31,
- '18:00:00 - 18:30:00': 32, '18:30:00 - 19:00:00': 33, '19:00:00 - 19:30:00': 34, '19:30:00 - 20:00:00': 35,
- '20:00:00 - 20:30:00': 36, '20:30:00 - 21:00:00': 37, '21:00:00 - 21:30:00': 38, '21:30:00 - 22:00:00': 39,
- '22:00:00 - 22:30:00': 40, '22:30:00 - 23:00:00': 41, '23:00:00 - 23:30:00': 42, '23:30:00 - 24:00:00': 43,
- '24:00:00 - 24:30:00': 44, '24:30:00 - 25:00:00': 45, '25:00:00 - 25:30:00': 46, '25:30:00 - 26:00:00': 47}
-
- selected_time_band = st.sidebar.selectbox('Time Band', list(time_band_dict.keys()))
- Time_Band_Encoded = time_band_dict[selected_time_band]
-
- user_report_data = {
- 'Share': Share,
- 'AMA': AMA,
- 'rate': rate,
- 'daily reach': daily_reach,
- 'cume reach': cume_reach,
- 'Week_Day_Encoded': Week_Day_Encoded,
- 'Time_Band_Encoded': Time_Band_Encoded}
- report_data = pd.DataFrame(user_report_data, index=[0])
-
- return report_data
-
-#Customer Data
-user_data = user_report()
-st.subheader("Entered Details")
-st.write(user_data)
-
-
-# define the prediction function
-def predict_unrolled_value(user_data):
-
- # make the prediction using the loaded model and input data
- predicted_unrolled_value = model.predict(user_data)
-
- # # return the predict_unrolled_value as output
- # return predicted_unrolled_value[0]
-
- # return the predicted unrolled value as output with 6 decimal places
- return float(predicted_unrolled_value[0])
-
-
-# Function calling
-y_pred = predict_unrolled_value(user_data)
-
-# CSS code for changing color of the button
-st.markdown("""
-
- """, unsafe_allow_html=True)
-
-# st.write("Click here to see the Predictions")
-if st.button("Click here for Predictions"):
- st.subheader(f"Predicted Unrolled Value: {y_pred:.6f}")
-
-
-# Testing purpose
-# 0.611246 4.196084 0.018516 36.23 36.231006 'Saturday' ''08:00:00 - 08:30:00''
-# 3.711884
diff --git a/spaces/Purple11/Grounded-Diffusion/README.md b/spaces/Purple11/Grounded-Diffusion/README.md
deleted file mode 100644
index a38a3f8a6d37e2415eb5d2644e763659086b8d46..0000000000000000000000000000000000000000
--- a/spaces/Purple11/Grounded-Diffusion/README.md
+++ /dev/null
@@ -1,12 +0,0 @@
----
-title: Grounded-Diffusion
-emoji: ⚡
-colorFrom: red
-colorTo: red
-sdk: gradio
-sdk_version: 3.18.0
-app_file: app.py
-pinned: false
----
-
-Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
diff --git a/spaces/PushkarA07/Sanskrit-Text-To-Speech/README.md b/spaces/PushkarA07/Sanskrit-Text-To-Speech/README.md
deleted file mode 100644
index 67f6463d51d54f8a0eab403c9b70a1d021be7957..0000000000000000000000000000000000000000
--- a/spaces/PushkarA07/Sanskrit-Text-To-Speech/README.md
+++ /dev/null
@@ -1,14 +0,0 @@
----
-title: Sanskrit TTS
-emoji: 👀
-colorFrom: blue
-colorTo: red
-sdk: gradio
-sdk_version: 3.3.1
-app_file: app.py
-pinned: false
-license: gpl-3.0
-duplicated_from: CjangCjengh/Sanskrit-TTS
----
-
-Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
diff --git a/spaces/RMXK/RVC_HFF/infer/lib/train/utils.py b/spaces/RMXK/RVC_HFF/infer/lib/train/utils.py
deleted file mode 100644
index dd965fc4dd2af09e445a7f625f2681460874da7a..0000000000000000000000000000000000000000
--- a/spaces/RMXK/RVC_HFF/infer/lib/train/utils.py
+++ /dev/null
@@ -1,478 +0,0 @@
-import argparse
-import glob
-import json
-import logging
-import os
-import subprocess
-import sys
-import shutil
-
-import numpy as np
-import torch
-from scipy.io.wavfile import read
-
-MATPLOTLIB_FLAG = False
-
-logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
-logger = logging
-
-
-def load_checkpoint_d(checkpoint_path, combd, sbd, optimizer=None, load_opt=1):
- assert os.path.isfile(checkpoint_path)
- checkpoint_dict = torch.load(checkpoint_path, map_location="cpu")
-
- ##################
- def go(model, bkey):
- saved_state_dict = checkpoint_dict[bkey]
- if hasattr(model, "module"):
- state_dict = model.module.state_dict()
- else:
- state_dict = model.state_dict()
- new_state_dict = {}
- for k, v in state_dict.items(): # 模型需要的shape
- try:
- new_state_dict[k] = saved_state_dict[k]
- if saved_state_dict[k].shape != state_dict[k].shape:
- logger.warn(
- "shape-%s-mismatch. need: %s, get: %s",
- k,
- state_dict[k].shape,
- saved_state_dict[k].shape,
- ) #
- raise KeyError
- except:
- # logger.info(traceback.format_exc())
- logger.info("%s is not in the checkpoint", k) # pretrain缺失的
- new_state_dict[k] = v # 模型自带的随机值
- if hasattr(model, "module"):
- model.module.load_state_dict(new_state_dict, strict=False)
- else:
- model.load_state_dict(new_state_dict, strict=False)
- return model
-
- go(combd, "combd")
- model = go(sbd, "sbd")
- #############
- logger.info("Loaded model weights")
-
- iteration = checkpoint_dict["iteration"]
- learning_rate = checkpoint_dict["learning_rate"]
- if (
- optimizer is not None and load_opt == 1
- ): ###加载不了,如果是空的的话,重新初始化,可能还会影响lr时间表的更新,因此在train文件最外围catch
- # try:
- optimizer.load_state_dict(checkpoint_dict["optimizer"])
- # except:
- # traceback.print_exc()
- logger.info("Loaded checkpoint '{}' (epoch {})".format(checkpoint_path, iteration))
- return model, optimizer, learning_rate, iteration
-
-
-# def load_checkpoint(checkpoint_path, model, optimizer=None):
-# assert os.path.isfile(checkpoint_path)
-# checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
-# iteration = checkpoint_dict['iteration']
-# learning_rate = checkpoint_dict['learning_rate']
-# if optimizer is not None:
-# optimizer.load_state_dict(checkpoint_dict['optimizer'])
-# # print(1111)
-# saved_state_dict = checkpoint_dict['model']
-# # print(1111)
-#
-# if hasattr(model, 'module'):
-# state_dict = model.module.state_dict()
-# else:
-# state_dict = model.state_dict()
-# new_state_dict= {}
-# for k, v in state_dict.items():
-# try:
-# new_state_dict[k] = saved_state_dict[k]
-# except:
-# logger.info("%s is not in the checkpoint" % k)
-# new_state_dict[k] = v
-# if hasattr(model, 'module'):
-# model.module.load_state_dict(new_state_dict)
-# else:
-# model.load_state_dict(new_state_dict)
-# logger.info("Loaded checkpoint '{}' (epoch {})" .format(
-# checkpoint_path, iteration))
-# return model, optimizer, learning_rate, iteration
-def load_checkpoint(checkpoint_path, model, optimizer=None, load_opt=1):
- assert os.path.isfile(checkpoint_path)
- checkpoint_dict = torch.load(checkpoint_path, map_location="cpu")
-
- saved_state_dict = checkpoint_dict["model"]
- if hasattr(model, "module"):
- state_dict = model.module.state_dict()
- else:
- state_dict = model.state_dict()
- new_state_dict = {}
- for k, v in state_dict.items(): # 模型需要的shape
- try:
- new_state_dict[k] = saved_state_dict[k]
- if saved_state_dict[k].shape != state_dict[k].shape:
- logger.warn(
- "shape-%s-mismatch|need-%s|get-%s",
- k,
- state_dict[k].shape,
- saved_state_dict[k].shape,
- ) #
- raise KeyError
- except:
- # logger.info(traceback.format_exc())
- logger.info("%s is not in the checkpoint", k) # pretrain缺失的
- new_state_dict[k] = v # 模型自带的随机值
- if hasattr(model, "module"):
- model.module.load_state_dict(new_state_dict, strict=False)
- else:
- model.load_state_dict(new_state_dict, strict=False)
- logger.info("Loaded model weights")
-
- iteration = checkpoint_dict["iteration"]
- learning_rate = checkpoint_dict["learning_rate"]
- if (
- optimizer is not None and load_opt == 1
- ): ###加载不了,如果是空的的话,重新初始化,可能还会影响lr时间表的更新,因此在train文件最外围catch
- # try:
- optimizer.load_state_dict(checkpoint_dict["optimizer"])
- # except:
- # traceback.print_exc()
- logger.info("Loaded checkpoint '{}' (epoch {})".format(checkpoint_path, iteration))
- return model, optimizer, learning_rate, iteration
-
-
-def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path):
- logger.info(
- "Saving model and optimizer state at epoch {} to {}".format(
- iteration, checkpoint_path
- )
- )
- if hasattr(model, "module"):
- state_dict = model.module.state_dict()
- else:
- state_dict = model.state_dict()
- torch.save(
- {
- "model": state_dict,
- "iteration": iteration,
- "optimizer": optimizer.state_dict(),
- "learning_rate": learning_rate,
- },
- checkpoint_path,
- )
-
-
-def save_checkpoint_d(combd, sbd, optimizer, learning_rate, iteration, checkpoint_path):
- logger.info(
- "Saving model and optimizer state at epoch {} to {}".format(
- iteration, checkpoint_path
- )
- )
- if hasattr(combd, "module"):
- state_dict_combd = combd.module.state_dict()
- else:
- state_dict_combd = combd.state_dict()
- if hasattr(sbd, "module"):
- state_dict_sbd = sbd.module.state_dict()
- else:
- state_dict_sbd = sbd.state_dict()
- torch.save(
- {
- "combd": state_dict_combd,
- "sbd": state_dict_sbd,
- "iteration": iteration,
- "optimizer": optimizer.state_dict(),
- "learning_rate": learning_rate,
- },
- checkpoint_path,
- )
-
-
-def summarize(
- writer,
- global_step,
- scalars={},
- histograms={},
- images={},
- audios={},
- audio_sampling_rate=22050,
-):
- for k, v in scalars.items():
- writer.add_scalar(k, v, global_step)
- for k, v in histograms.items():
- writer.add_histogram(k, v, global_step)
- for k, v in images.items():
- writer.add_image(k, v, global_step, dataformats="HWC")
- for k, v in audios.items():
- writer.add_audio(k, v, global_step, audio_sampling_rate)
-
-
-def latest_checkpoint_path(dir_path, regex="G_*.pth"):
- f_list = glob.glob(os.path.join(dir_path, regex))
- f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
- x = f_list[-1]
- logger.debug(x)
- return x
-
-
-def plot_spectrogram_to_numpy(spectrogram):
- global MATPLOTLIB_FLAG
- if not MATPLOTLIB_FLAG:
- import matplotlib
-
- matplotlib.use("Agg")
- MATPLOTLIB_FLAG = True
- mpl_logger = logging.getLogger("matplotlib")
- mpl_logger.setLevel(logging.WARNING)
- import matplotlib.pylab as plt
- import numpy as np
-
- fig, ax = plt.subplots(figsize=(10, 2))
- im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation="none")
- plt.colorbar(im, ax=ax)
- plt.xlabel("Frames")
- plt.ylabel("Channels")
- plt.tight_layout()
-
- fig.canvas.draw()
- data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
- data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
- plt.close()
- return data
-
-
-def plot_alignment_to_numpy(alignment, info=None):
- global MATPLOTLIB_FLAG
- if not MATPLOTLIB_FLAG:
- import matplotlib
-
- matplotlib.use("Agg")
- MATPLOTLIB_FLAG = True
- mpl_logger = logging.getLogger("matplotlib")
- mpl_logger.setLevel(logging.WARNING)
- import matplotlib.pylab as plt
- import numpy as np
-
- fig, ax = plt.subplots(figsize=(6, 4))
- im = ax.imshow(
- alignment.transpose(), aspect="auto", origin="lower", interpolation="none"
- )
- fig.colorbar(im, ax=ax)
- xlabel = "Decoder timestep"
- if info is not None:
- xlabel += "\n\n" + info
- plt.xlabel(xlabel)
- plt.ylabel("Encoder timestep")
- plt.tight_layout()
-
- fig.canvas.draw()
- data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
- data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
- plt.close()
- return data
-
-
-def load_wav_to_torch(full_path):
- sampling_rate, data = read(full_path)
- return torch.FloatTensor(data.astype(np.float32)), sampling_rate
-
-
-def load_filepaths_and_text(filename, split="|"):
- with open(filename, encoding="utf-8") as f:
- filepaths_and_text = [line.strip().split(split) for line in f]
- return filepaths_and_text
-
-
-def get_hparams(init=True):
- """
- todo:
- 结尾七人组:
- 保存频率、总epoch done
- bs done
- pretrainG、pretrainD done
- 卡号:os.en["CUDA_VISIBLE_DEVICES"] done
- if_latest done
- 模型:if_f0 done
- 采样率:自动选择config done
- 是否缓存数据集进GPU:if_cache_data_in_gpu done
-
- -m:
- 自动决定training_files路径,改掉train_nsf_load_pretrain.py里的hps.data.training_files done
- -c不要了
- """
- parser = argparse.ArgumentParser()
- parser.add_argument(
- "-se",
- "--save_every_epoch",
- type=int,
- required=True,
- help="checkpoint save frequency (epoch)",
- )
- parser.add_argument(
- "-te", "--total_epoch", type=int, required=True, help="total_epoch"
- )
- parser.add_argument(
- "-pg", "--pretrainG", type=str, default="", help="Pretrained Discriminator path"
- )
- parser.add_argument(
- "-pd", "--pretrainD", type=str, default="", help="Pretrained Generator path"
- )
- parser.add_argument("-g", "--gpus", type=str, default="0", help="split by -")
- parser.add_argument(
- "-bs", "--batch_size", type=int, required=True, help="batch size"
- )
- parser.add_argument(
- "-e", "--experiment_dir", type=str, required=True, help="experiment dir"
- ) # -m
- parser.add_argument(
- "-sr", "--sample_rate", type=str, required=True, help="sample rate, 32k/40k/48k"
- )
- parser.add_argument(
- "-sw",
- "--save_every_weights",
- type=str,
- default="0",
- help="save the extracted model in weights directory when saving checkpoints",
- )
- parser.add_argument(
- "-v", "--version", type=str, required=True, help="model version"
- )
- parser.add_argument(
- "-f0",
- "--if_f0",
- type=int,
- required=True,
- help="use f0 as one of the inputs of the model, 1 or 0",
- )
- parser.add_argument(
- "-l",
- "--if_latest",
- type=int,
- required=True,
- help="if only save the latest G/D pth file, 1 or 0",
- )
- parser.add_argument(
- "-c",
- "--if_cache_data_in_gpu",
- type=int,
- required=True,
- help="if caching the dataset in GPU memory, 1 or 0",
- )
-
- args = parser.parse_args()
- name = args.experiment_dir
- experiment_dir = os.path.join("./logs", args.experiment_dir)
-
- config_save_path = os.path.join(experiment_dir, "config.json")
- with open(config_save_path, "r") as f:
- config = json.load(f)
-
- hparams = HParams(**config)
- hparams.model_dir = hparams.experiment_dir = experiment_dir
- hparams.save_every_epoch = args.save_every_epoch
- hparams.name = name
- hparams.total_epoch = args.total_epoch
- hparams.pretrainG = args.pretrainG
- hparams.pretrainD = args.pretrainD
- hparams.version = args.version
- hparams.gpus = args.gpus
- hparams.train.batch_size = args.batch_size
- hparams.sample_rate = args.sample_rate
- hparams.if_f0 = args.if_f0
- hparams.if_latest = args.if_latest
- hparams.save_every_weights = args.save_every_weights
- hparams.if_cache_data_in_gpu = args.if_cache_data_in_gpu
- hparams.data.training_files = "%s/filelist.txt" % experiment_dir
- return hparams
-
-
-def get_hparams_from_dir(model_dir):
- config_save_path = os.path.join(model_dir, "config.json")
- with open(config_save_path, "r") as f:
- data = f.read()
- config = json.loads(data)
-
- hparams = HParams(**config)
- hparams.model_dir = model_dir
- return hparams
-
-
-def get_hparams_from_file(config_path):
- with open(config_path, "r") as f:
- data = f.read()
- config = json.loads(data)
-
- hparams = HParams(**config)
- return hparams
-
-
-def check_git_hash(model_dir):
- source_dir = os.path.dirname(os.path.realpath(__file__))
- if not os.path.exists(os.path.join(source_dir, ".git")):
- logger.warn(
- "{} is not a git repository, therefore hash value comparison will be ignored.".format(
- source_dir
- )
- )
- return
-
- cur_hash = subprocess.getoutput("git rev-parse HEAD")
-
- path = os.path.join(model_dir, "githash")
- if os.path.exists(path):
- saved_hash = open(path).read()
- if saved_hash != cur_hash:
- logger.warn(
- "git hash values are different. {}(saved) != {}(current)".format(
- saved_hash[:8], cur_hash[:8]
- )
- )
- else:
- open(path, "w").write(cur_hash)
-
-
-def get_logger(model_dir, filename="train.log"):
- global logger
- logger = logging.getLogger(os.path.basename(model_dir))
- logger.setLevel(logging.DEBUG)
-
- formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
- if not os.path.exists(model_dir):
- os.makedirs(model_dir)
- h = logging.FileHandler(os.path.join(model_dir, filename))
- h.setLevel(logging.DEBUG)
- h.setFormatter(formatter)
- logger.addHandler(h)
- return logger
-
-
-class HParams:
- def __init__(self, **kwargs):
- for k, v in kwargs.items():
- if type(v) == dict:
- v = HParams(**v)
- self[k] = v
-
- def keys(self):
- return self.__dict__.keys()
-
- def items(self):
- return self.__dict__.items()
-
- def values(self):
- return self.__dict__.values()
-
- def __len__(self):
- return len(self.__dict__)
-
- def __getitem__(self, key):
- return getattr(self, key)
-
- def __setitem__(self, key, value):
- return setattr(self, key, value)
-
- def __contains__(self, key):
- return key in self.__dict__
-
- def __repr__(self):
- return self.__dict__.__repr__()
diff --git a/spaces/Raksama/ChatToPdf/README.md b/spaces/Raksama/ChatToPdf/README.md
deleted file mode 100644
index e3b3383ded0cddd82c710cdb175ac8e9d7467595..0000000000000000000000000000000000000000
--- a/spaces/Raksama/ChatToPdf/README.md
+++ /dev/null
@@ -1,11 +0,0 @@
----
-title: Panel PDF QA
-emoji: 📈
-colorFrom: pink
-colorTo: red
-sdk: docker
-pinned: false
-duplicated_from: sophiamyang/Panel_PDF_QA
----
-
-Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
diff --git a/spaces/Ramse/TTS_Hindi/modules/modules.py b/spaces/Ramse/TTS_Hindi/modules/modules.py
deleted file mode 100644
index bc807562c964e74cf730165d5c2bd88d113d0d27..0000000000000000000000000000000000000000
--- a/spaces/Ramse/TTS_Hindi/modules/modules.py
+++ /dev/null
@@ -1,297 +0,0 @@
-import os
-import json
-import copy
-import math
-from collections import OrderedDict
-
-import torch
-import torch.nn as nn
-import numpy as np
-import torch.nn.functional as F
-
-from utils.tools import get_mask_from_lengths, pad
-
-# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
-
-
-class VarianceAdaptor(nn.Module):
- """Variance Adaptor"""
-
- def __init__(self, preprocess_config, model_config, device):
- super(VarianceAdaptor, self).__init__()
- self.device = device
- self.duration_predictor = VariancePredictor(model_config)
- self.length_regulator = LengthRegulator(device= self.device)
- self.pitch_predictor = VariancePredictor(model_config)
- self.energy_predictor = VariancePredictor(model_config)
-
- self.pitch_feature_level = preprocess_config["preprocessing"]["pitch"][
- "feature"
- ]
- self.energy_feature_level = preprocess_config["preprocessing"]["energy"][
- "feature"
- ]
- assert self.pitch_feature_level in ["phoneme_level", "frame_level"]
- assert self.energy_feature_level in ["phoneme_level", "frame_level"]
-
- pitch_quantization = model_config["variance_embedding"]["pitch_quantization"]
- energy_quantization = model_config["variance_embedding"]["energy_quantization"]
- n_bins = model_config["variance_embedding"]["n_bins"]
- assert pitch_quantization in ["linear", "log"]
- assert energy_quantization in ["linear", "log"]
- with open(os.path.join(preprocess_config["path"]["preprocessed_path"], "stats.json")) as f:
- stats = json.load(f)
- pitch_min, pitch_max = stats["pitch"][:2]
- energy_min, energy_max = stats["energy"][:2]
-
-
- if pitch_quantization == "log":
- self.pitch_bins = nn.Parameter(
- torch.exp(
- torch.linspace(np.log(pitch_min), np.log(pitch_max), n_bins - 1)
- ),
- requires_grad=False,
- )
- else:
- self.pitch_bins = nn.Parameter(
- torch.linspace(pitch_min, pitch_max, n_bins - 1),
- requires_grad=False,
- )
- if energy_quantization == "log":
- self.energy_bins = nn.Parameter(
- torch.exp(
- torch.linspace(np.log(energy_min), np.log(energy_max), n_bins - 1)
- ),
- requires_grad=False,
- )
- else:
- self.energy_bins = nn.Parameter(
- torch.linspace(energy_min, energy_max, n_bins - 1),
- requires_grad=False,
- )
-
- self.pitch_embedding = nn.Embedding(
- n_bins, model_config["transformer"]["encoder_dim"]
- )
- self.energy_embedding = nn.Embedding(
- n_bins, model_config["transformer"]["encoder_dim"]
- )
-
- def get_pitch_embedding(self, x, target, mask, control):
- prediction = self.pitch_predictor(x, mask)
- if target is not None:
- embedding = self.pitch_embedding(torch.bucketize(target, self.pitch_bins))
- else:
- prediction = prediction * control
- embedding = self.pitch_embedding(
- torch.bucketize(prediction, self.pitch_bins)
- )
- return prediction, embedding
-
- def get_energy_embedding(self, x, target, mask, control):
- prediction = self.energy_predictor(x, mask)
- if target is not None:
- embedding = self.energy_embedding(torch.bucketize(target, self.energy_bins))
- else:
- prediction = prediction * control
- embedding = self.energy_embedding(
- torch.bucketize(prediction, self.energy_bins)
- )
- return prediction, embedding
-
- def forward(
- self,
- x,
- src_mask,
- mel_mask=None,
- max_len=None,
- pitch_target=None,
- energy_target=None,
- duration_target=None,
- p_control=1.0,
- e_control=1.0,
- d_control=1.0,
- ):
-
- log_duration_prediction = self.duration_predictor(x, src_mask)
- if self.pitch_feature_level == "phoneme_level":
- pitch_prediction, pitch_embedding = self.get_pitch_embedding(
- x, pitch_target, src_mask, p_control
- )
- x = x + pitch_embedding
- if self.energy_feature_level == "phoneme_level":
- energy_prediction, energy_embedding = self.get_energy_embedding(
- x, energy_target, src_mask, p_control
- )
- x = x + energy_embedding
-
- if duration_target is not None:
- x, mel_len = self.length_regulator(x, duration_target, max_len)
- duration_rounded = duration_target
- else:
- duration_rounded = torch.clamp(
- (torch.round(torch.exp(log_duration_prediction) - 1) * d_control),
- min=0,
- )
- x, mel_len = self.length_regulator(x, duration_rounded, max_len)
- mel_mask = get_mask_from_lengths(mel_len)
-
- if self.pitch_feature_level == "frame_level":
- pitch_prediction, pitch_embedding = self.get_pitch_embedding(
- x, pitch_target, mel_mask, p_control
- )
- x = x + pitch_embedding
- if self.energy_feature_level == "frame_level":
- energy_prediction, energy_embedding = self.get_energy_embedding(
- x, energy_target, mel_mask, p_control
- )
- x = x + energy_embedding
-
- return (
- x,
- pitch_prediction,
- energy_prediction,
- log_duration_prediction,
- duration_rounded,
- mel_len,
- mel_mask,
- )
-
-
-class LengthRegulator(nn.Module):
- """Length Regulator"""
-
- def __init__(self, device):
- super(LengthRegulator, self).__init__()
- self.device = device
-
- def LR(self, x, duration, max_len):
- output = list()
- mel_len = list()
- for batch, expand_target in zip(x, duration):
- expanded = self.expand(batch, expand_target)
- output.append(expanded)
- mel_len.append(expanded.shape[0])
-
- if max_len is not None:
- output = pad(output, max_len)
- else:
- output = pad(output)
-
- return output, torch.LongTensor(mel_len).to(self.device)
-
- def expand(self, batch, predicted):
- out = list()
-
- for i, vec in enumerate(batch):
- expand_size = predicted[i].item()
- out.append(vec.expand(max(int(expand_size), 0), -1))
- out = torch.cat(out, 0)
-
- return out
-
- def forward(self, x, duration, max_len):
- output, mel_len = self.LR(x, duration, max_len)
- return output, mel_len
-
-
-class VariancePredictor(nn.Module):
- """Duration, Pitch and Energy Predictor"""
-
- def __init__(self, model_config):
- super(VariancePredictor, self).__init__()
-
- self.input_size = model_config["transformer"]["encoder_dim"]
- self.filter_size = model_config["variance_predictor"]["filter_size"]
- self.kernel = model_config["variance_predictor"]["kernel_size"]
- self.conv_output_size = model_config["variance_predictor"]["filter_size"]
- self.dropout = model_config["variance_predictor"]["dropout"]
-
- self.conv_layer = nn.Sequential(
- OrderedDict(
- [
- (
- "conv1d_1",
- Conv(
- self.input_size,
- self.filter_size,
- kernel_size=self.kernel,
- padding=(self.kernel - 1) // 2,
- ),
- ),
- ("relu_1", nn.ReLU()),
- ("layer_norm_1", nn.LayerNorm(self.filter_size)),
- ("dropout_1", nn.Dropout(self.dropout)),
- (
- "conv1d_2",
- Conv(
- self.filter_size,
- self.filter_size,
- kernel_size=self.kernel,
- padding=1,
- ),
- ),
- ("relu_2", nn.ReLU()),
- ("layer_norm_2", nn.LayerNorm(self.filter_size)),
- ("dropout_2", nn.Dropout(self.dropout)),
- ]
- )
- )
-
- self.linear_layer = nn.Linear(self.conv_output_size, 1)
-
- def forward(self, encoder_output, mask):
- out = self.conv_layer(encoder_output)
- out = self.linear_layer(out)
- out = out.squeeze(-1)
-
- if mask is not None:
- out = out.masked_fill(mask, 0.0)
-
- return out
-
-
-class Conv(nn.Module):
- """
- Convolution Module
- """
-
- def __init__(
- self,
- in_channels,
- out_channels,
- kernel_size=1,
- stride=1,
- padding=0,
- dilation=1,
- bias=True,
- w_init="linear",
- ):
- """
- :param in_channels: dimension of input
- :param out_channels: dimension of output
- :param kernel_size: size of kernel
- :param stride: size of stride
- :param padding: size of padding
- :param dilation: dilation rate
- :param bias: boolean. if True, bias is included.
- :param w_init: str. weight inits with xavier initialization.
- """
- super(Conv, self).__init__()
-
- self.conv = nn.Conv1d(
- in_channels,
- out_channels,
- kernel_size=kernel_size,
- stride=stride,
- padding=padding,
- dilation=dilation,
- bias=bias,
- )
-
- def forward(self, x):
- x = x.contiguous().transpose(1, 2)
- x = self.conv(x)
- x = x.contiguous().transpose(1, 2)
-
- return x
diff --git a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_internal/resolution/__init__.py b/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_internal/resolution/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/distlib/__init__.py b/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/distlib/__init__.py
deleted file mode 100644
index 962173c8d0a6906b59f2910c9cae759010534786..0000000000000000000000000000000000000000
--- a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/distlib/__init__.py
+++ /dev/null
@@ -1,23 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2012-2022 Vinay Sajip.
-# Licensed to the Python Software Foundation under a contributor agreement.
-# See LICENSE.txt and CONTRIBUTORS.txt.
-#
-import logging
-
-__version__ = '0.3.6'
-
-class DistlibException(Exception):
- pass
-
-try:
- from logging import NullHandler
-except ImportError: # pragma: no cover
- class NullHandler(logging.Handler):
- def handle(self, record): pass
- def emit(self, record): pass
- def createLock(self): self.lock = None
-
-logger = logging.getLogger(__name__)
-logger.addHandler(NullHandler())
diff --git a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/idna/intranges.py b/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/idna/intranges.py
deleted file mode 100644
index 6a43b0475347cb50d0d65ada1000a82eeca9e882..0000000000000000000000000000000000000000
--- a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/idna/intranges.py
+++ /dev/null
@@ -1,54 +0,0 @@
-"""
-Given a list of integers, made up of (hopefully) a small number of long runs
-of consecutive integers, compute a representation of the form
-((start1, end1), (start2, end2) ...). Then answer the question "was x present
-in the original list?" in time O(log(# runs)).
-"""
-
-import bisect
-from typing import List, Tuple
-
-def intranges_from_list(list_: List[int]) -> Tuple[int, ...]:
- """Represent a list of integers as a sequence of ranges:
- ((start_0, end_0), (start_1, end_1), ...), such that the original
- integers are exactly those x such that start_i <= x < end_i for some i.
-
- Ranges are encoded as single integers (start << 32 | end), not as tuples.
- """
-
- sorted_list = sorted(list_)
- ranges = []
- last_write = -1
- for i in range(len(sorted_list)):
- if i+1 < len(sorted_list):
- if sorted_list[i] == sorted_list[i+1]-1:
- continue
- current_range = sorted_list[last_write+1:i+1]
- ranges.append(_encode_range(current_range[0], current_range[-1] + 1))
- last_write = i
-
- return tuple(ranges)
-
-def _encode_range(start: int, end: int) -> int:
- return (start << 32) | end
-
-def _decode_range(r: int) -> Tuple[int, int]:
- return (r >> 32), (r & ((1 << 32) - 1))
-
-
-def intranges_contain(int_: int, ranges: Tuple[int, ...]) -> bool:
- """Determine if `int_` falls into one of the ranges in `ranges`."""
- tuple_ = _encode_range(int_, 0)
- pos = bisect.bisect_left(ranges, tuple_)
- # we could be immediately ahead of a tuple (start, end)
- # with start < int_ <= end
- if pos > 0:
- left, right = _decode_range(ranges[pos-1])
- if left <= int_ < right:
- return True
- # or we could be immediately behind a tuple (int_, end)
- if pos < len(ranges):
- left, _ = _decode_range(ranges[pos])
- if left == int_:
- return True
- return False
diff --git a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pkg_resources/_vendor/importlib_resources/_legacy.py b/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pkg_resources/_vendor/importlib_resources/_legacy.py
deleted file mode 100644
index 1d5d3f1fbb1f6c69d0da2a50e1d4492ad3378f17..0000000000000000000000000000000000000000
--- a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pkg_resources/_vendor/importlib_resources/_legacy.py
+++ /dev/null
@@ -1,121 +0,0 @@
-import functools
-import os
-import pathlib
-import types
-import warnings
-
-from typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any
-
-from . import _common
-
-Package = Union[types.ModuleType, str]
-Resource = str
-
-
-def deprecated(func):
- @functools.wraps(func)
- def wrapper(*args, **kwargs):
- warnings.warn(
- f"{func.__name__} is deprecated. Use files() instead. "
- "Refer to https://importlib-resources.readthedocs.io"
- "/en/latest/using.html#migrating-from-legacy for migration advice.",
- DeprecationWarning,
- stacklevel=2,
- )
- return func(*args, **kwargs)
-
- return wrapper
-
-
-def normalize_path(path):
- # type: (Any) -> str
- """Normalize a path by ensuring it is a string.
-
- If the resulting string contains path separators, an exception is raised.
- """
- str_path = str(path)
- parent, file_name = os.path.split(str_path)
- if parent:
- raise ValueError(f'{path!r} must be only a file name')
- return file_name
-
-
-@deprecated
-def open_binary(package: Package, resource: Resource) -> BinaryIO:
- """Return a file-like object opened for binary reading of the resource."""
- return (_common.files(package) / normalize_path(resource)).open('rb')
-
-
-@deprecated
-def read_binary(package: Package, resource: Resource) -> bytes:
- """Return the binary contents of the resource."""
- return (_common.files(package) / normalize_path(resource)).read_bytes()
-
-
-@deprecated
-def open_text(
- package: Package,
- resource: Resource,
- encoding: str = 'utf-8',
- errors: str = 'strict',
-) -> TextIO:
- """Return a file-like object opened for text reading of the resource."""
- return (_common.files(package) / normalize_path(resource)).open(
- 'r', encoding=encoding, errors=errors
- )
-
-
-@deprecated
-def read_text(
- package: Package,
- resource: Resource,
- encoding: str = 'utf-8',
- errors: str = 'strict',
-) -> str:
- """Return the decoded string of the resource.
-
- The decoding-related arguments have the same semantics as those of
- bytes.decode().
- """
- with open_text(package, resource, encoding, errors) as fp:
- return fp.read()
-
-
-@deprecated
-def contents(package: Package) -> Iterable[str]:
- """Return an iterable of entries in `package`.
-
- Note that not all entries are resources. Specifically, directories are
- not considered resources. Use `is_resource()` on each entry returned here
- to check if it is a resource or not.
- """
- return [path.name for path in _common.files(package).iterdir()]
-
-
-@deprecated
-def is_resource(package: Package, name: str) -> bool:
- """True if `name` is a resource inside `package`.
-
- Directories are *not* resources.
- """
- resource = normalize_path(name)
- return any(
- traversable.name == resource and traversable.is_file()
- for traversable in _common.files(package).iterdir()
- )
-
-
-@deprecated
-def path(
- package: Package,
- resource: Resource,
-) -> ContextManager[pathlib.Path]:
- """A context manager providing a file path object to the resource.
-
- If the resource does not already exist on its own on the file system,
- a temporary file will be created. If the file was created, the file
- will be deleted upon exiting the context manager (no exception is
- raised if the file was deleted prior to the context manager
- exiting).
- """
- return _common.as_file(_common.files(package) / normalize_path(resource))
diff --git a/spaces/Rayzggz/illi-Bert-VITS2/text/japanese.py b/spaces/Rayzggz/illi-Bert-VITS2/text/japanese.py
deleted file mode 100644
index 53db38b7349af5a117f81314304d69796c0daf81..0000000000000000000000000000000000000000
--- a/spaces/Rayzggz/illi-Bert-VITS2/text/japanese.py
+++ /dev/null
@@ -1,586 +0,0 @@
-# Convert Japanese text to phonemes which is
-# compatible with Julius https://github.com/julius-speech/segmentation-kit
-import re
-import unicodedata
-
-from transformers import AutoTokenizer
-
-from text import punctuation, symbols
-
-try:
- import MeCab
-except ImportError as e:
- raise ImportError("Japanese requires mecab-python3 and unidic-lite.") from e
-from num2words import num2words
-
-_CONVRULES = [
- # Conversion of 2 letters
- "アァ/ a a",
- "イィ/ i i",
- "イェ/ i e",
- "イャ/ y a",
- "ウゥ/ u:",
- "エェ/ e e",
- "オォ/ o:",
- "カァ/ k a:",
- "キィ/ k i:",
- "クゥ/ k u:",
- "クャ/ ky a",
- "クュ/ ky u",
- "クョ/ ky o",
- "ケェ/ k e:",
- "コォ/ k o:",
- "ガァ/ g a:",
- "ギィ/ g i:",
- "グゥ/ g u:",
- "グャ/ gy a",
- "グュ/ gy u",
- "グョ/ gy o",
- "ゲェ/ g e:",
- "ゴォ/ g o:",
- "サァ/ s a:",
- "シィ/ sh i:",
- "スゥ/ s u:",
- "スャ/ sh a",
- "スュ/ sh u",
- "スョ/ sh o",
- "セェ/ s e:",
- "ソォ/ s o:",
- "ザァ/ z a:",
- "ジィ/ j i:",
- "ズゥ/ z u:",
- "ズャ/ zy a",
- "ズュ/ zy u",
- "ズョ/ zy o",
- "ゼェ/ z e:",
- "ゾォ/ z o:",
- "タァ/ t a:",
- "チィ/ ch i:",
- "ツァ/ ts a",
- "ツィ/ ts i",
- "ツゥ/ ts u:",
- "ツャ/ ch a",
- "ツュ/ ch u",
- "ツョ/ ch o",
- "ツェ/ ts e",
- "ツォ/ ts o",
- "テェ/ t e:",
- "トォ/ t o:",
- "ダァ/ d a:",
- "ヂィ/ j i:",
- "ヅゥ/ d u:",
- "ヅャ/ zy a",
- "ヅュ/ zy u",
- "ヅョ/ zy o",
- "デェ/ d e:",
- "ドォ/ d o:",
- "ナァ/ n a:",
- "ニィ/ n i:",
- "ヌゥ/ n u:",
- "ヌャ/ ny a",
- "ヌュ/ ny u",
- "ヌョ/ ny o",
- "ネェ/ n e:",
- "ノォ/ n o:",
- "ハァ/ h a:",
- "ヒィ/ h i:",
- "フゥ/ f u:",
- "フャ/ hy a",
- "フュ/ hy u",
- "フョ/ hy o",
- "ヘェ/ h e:",
- "ホォ/ h o:",
- "バァ/ b a:",
- "ビィ/ b i:",
- "ブゥ/ b u:",
- "フャ/ hy a",
- "ブュ/ by u",
- "フョ/ hy o",
- "ベェ/ b e:",
- "ボォ/ b o:",
- "パァ/ p a:",
- "ピィ/ p i:",
- "プゥ/ p u:",
- "プャ/ py a",
- "プュ/ py u",
- "プョ/ py o",
- "ペェ/ p e:",
- "ポォ/ p o:",
- "マァ/ m a:",
- "ミィ/ m i:",
- "ムゥ/ m u:",
- "ムャ/ my a",
- "ムュ/ my u",
- "ムョ/ my o",
- "メェ/ m e:",
- "モォ/ m o:",
- "ヤァ/ y a:",
- "ユゥ/ y u:",
- "ユャ/ y a:",
- "ユュ/ y u:",
- "ユョ/ y o:",
- "ヨォ/ y o:",
- "ラァ/ r a:",
- "リィ/ r i:",
- "ルゥ/ r u:",
- "ルャ/ ry a",
- "ルュ/ ry u",
- "ルョ/ ry o",
- "レェ/ r e:",
- "ロォ/ r o:",
- "ワァ/ w a:",
- "ヲォ/ o:",
- "ディ/ d i",
- "デェ/ d e:",
- "デャ/ dy a",
- "デュ/ dy u",
- "デョ/ dy o",
- "ティ/ t i",
- "テェ/ t e:",
- "テャ/ ty a",
- "テュ/ ty u",
- "テョ/ ty o",
- "スィ/ s i",
- "ズァ/ z u a",
- "ズィ/ z i",
- "ズゥ/ z u",
- "ズャ/ zy a",
- "ズュ/ zy u",
- "ズョ/ zy o",
- "ズェ/ z e",
- "ズォ/ z o",
- "キャ/ ky a",
- "キュ/ ky u",
- "キョ/ ky o",
- "シャ/ sh a",
- "シュ/ sh u",
- "シェ/ sh e",
- "ショ/ sh o",
- "チャ/ ch a",
- "チュ/ ch u",
- "チェ/ ch e",
- "チョ/ ch o",
- "トゥ/ t u",
- "トャ/ ty a",
- "トュ/ ty u",
- "トョ/ ty o",
- "ドァ/ d o a",
- "ドゥ/ d u",
- "ドャ/ dy a",
- "ドュ/ dy u",
- "ドョ/ dy o",
- "ドォ/ d o:",
- "ニャ/ ny a",
- "ニュ/ ny u",
- "ニョ/ ny o",
- "ヒャ/ hy a",
- "ヒュ/ hy u",
- "ヒョ/ hy o",
- "ミャ/ my a",
- "ミュ/ my u",
- "ミョ/ my o",
- "リャ/ ry a",
- "リュ/ ry u",
- "リョ/ ry o",
- "ギャ/ gy a",
- "ギュ/ gy u",
- "ギョ/ gy o",
- "ヂェ/ j e",
- "ヂャ/ j a",
- "ヂュ/ j u",
- "ヂョ/ j o",
- "ジェ/ j e",
- "ジャ/ j a",
- "ジュ/ j u",
- "ジョ/ j o",
- "ビャ/ by a",
- "ビュ/ by u",
- "ビョ/ by o",
- "ピャ/ py a",
- "ピュ/ py u",
- "ピョ/ py o",
- "ウァ/ u a",
- "ウィ/ w i",
- "ウェ/ w e",
- "ウォ/ w o",
- "ファ/ f a",
- "フィ/ f i",
- "フゥ/ f u",
- "フャ/ hy a",
- "フュ/ hy u",
- "フョ/ hy o",
- "フェ/ f e",
- "フォ/ f o",
- "ヴァ/ b a",
- "ヴィ/ b i",
- "ヴェ/ b e",
- "ヴォ/ b o",
- "ヴュ/ by u",
- # Conversion of 1 letter
- "ア/ a",
- "イ/ i",
- "ウ/ u",
- "エ/ e",
- "オ/ o",
- "カ/ k a",
- "キ/ k i",
- "ク/ k u",
- "ケ/ k e",
- "コ/ k o",
- "サ/ s a",
- "シ/ sh i",
- "ス/ s u",
- "セ/ s e",
- "ソ/ s o",
- "タ/ t a",
- "チ/ ch i",
- "ツ/ ts u",
- "テ/ t e",
- "ト/ t o",
- "ナ/ n a",
- "ニ/ n i",
- "ヌ/ n u",
- "ネ/ n e",
- "ノ/ n o",
- "ハ/ h a",
- "ヒ/ h i",
- "フ/ f u",
- "ヘ/ h e",
- "ホ/ h o",
- "マ/ m a",
- "ミ/ m i",
- "ム/ m u",
- "メ/ m e",
- "モ/ m o",
- "ラ/ r a",
- "リ/ r i",
- "ル/ r u",
- "レ/ r e",
- "ロ/ r o",
- "ガ/ g a",
- "ギ/ g i",
- "グ/ g u",
- "ゲ/ g e",
- "ゴ/ g o",
- "ザ/ z a",
- "ジ/ j i",
- "ズ/ z u",
- "ゼ/ z e",
- "ゾ/ z o",
- "ダ/ d a",
- "ヂ/ j i",
- "ヅ/ z u",
- "デ/ d e",
- "ド/ d o",
- "バ/ b a",
- "ビ/ b i",
- "ブ/ b u",
- "ベ/ b e",
- "ボ/ b o",
- "パ/ p a",
- "ピ/ p i",
- "プ/ p u",
- "ペ/ p e",
- "ポ/ p o",
- "ヤ/ y a",
- "ユ/ y u",
- "ヨ/ y o",
- "ワ/ w a",
- "ヰ/ i",
- "ヱ/ e",
- "ヲ/ o",
- "ン/ N",
- "ッ/ q",
- "ヴ/ b u",
- "ー/:",
- # Try converting broken text
- "ァ/ a",
- "ィ/ i",
- "ゥ/ u",
- "ェ/ e",
- "ォ/ o",
- "ヮ/ w a",
- "ォ/ o",
- # Symbols
- "、/ ,",
- "。/ .",
- "!/ !",
- "?/ ?",
- "・/ ,",
-]
-
-_COLON_RX = re.compile(":+")
-_REJECT_RX = re.compile("[^ a-zA-Z:,.?]")
-
-
-def _makerulemap():
- l = [tuple(x.split("/")) for x in _CONVRULES]
- return tuple({k: v for k, v in l if len(k) == i} for i in (1, 2))
-
-
-_RULEMAP1, _RULEMAP2 = _makerulemap()
-
-
-def kata2phoneme(text: str) -> str:
- """Convert katakana text to phonemes."""
- text = text.strip()
- res = []
- while text:
- if len(text) >= 2:
- x = _RULEMAP2.get(text[:2])
- if x is not None:
- text = text[2:]
- res += x.split(" ")[1:]
- continue
- x = _RULEMAP1.get(text[0])
- if x is not None:
- text = text[1:]
- res += x.split(" ")[1:]
- continue
- res.append(text[0])
- text = text[1:]
- # res = _COLON_RX.sub(":", res)
- return res
-
-
-_KATAKANA = "".join(chr(ch) for ch in range(ord("ァ"), ord("ン") + 1))
-_HIRAGANA = "".join(chr(ch) for ch in range(ord("ぁ"), ord("ん") + 1))
-_HIRA2KATATRANS = str.maketrans(_HIRAGANA, _KATAKANA)
-
-
-def hira2kata(text: str) -> str:
- text = text.translate(_HIRA2KATATRANS)
- return text.replace("う゛", "ヴ")
-
-
-_SYMBOL_TOKENS = set(list("・、。?!"))
-_NO_YOMI_TOKENS = set(list("「」『』―()[][]"))
-_TAGGER = MeCab.Tagger()
-
-
-def text2kata(text: str) -> str:
- parsed = _TAGGER.parse(text)
- res = []
- for line in parsed.split("\n"):
- if line == "EOS":
- break
- parts = line.split("\t")
-
- word, yomi = parts[0], parts[1]
- if yomi:
- res.append(yomi)
- else:
- if word in _SYMBOL_TOKENS:
- res.append(word)
- elif word in ("っ", "ッ"):
- res.append("ッ")
- elif word in _NO_YOMI_TOKENS:
- pass
- else:
- res.append(word)
- return hira2kata("".join(res))
-
-
-_ALPHASYMBOL_YOMI = {
- "#": "シャープ",
- "%": "パーセント",
- "&": "アンド",
- "+": "プラス",
- "-": "マイナス",
- ":": "コロン",
- ";": "セミコロン",
- "<": "小なり",
- "=": "イコール",
- ">": "大なり",
- "@": "アット",
- "a": "エー",
- "b": "ビー",
- "c": "シー",
- "d": "ディー",
- "e": "イー",
- "f": "エフ",
- "g": "ジー",
- "h": "エイチ",
- "i": "アイ",
- "j": "ジェー",
- "k": "ケー",
- "l": "エル",
- "m": "エム",
- "n": "エヌ",
- "o": "オー",
- "p": "ピー",
- "q": "キュー",
- "r": "アール",
- "s": "エス",
- "t": "ティー",
- "u": "ユー",
- "v": "ブイ",
- "w": "ダブリュー",
- "x": "エックス",
- "y": "ワイ",
- "z": "ゼット",
- "α": "アルファ",
- "β": "ベータ",
- "γ": "ガンマ",
- "δ": "デルタ",
- "ε": "イプシロン",
- "ζ": "ゼータ",
- "η": "イータ",
- "θ": "シータ",
- "ι": "イオタ",
- "κ": "カッパ",
- "λ": "ラムダ",
- "μ": "ミュー",
- "ν": "ニュー",
- "ξ": "クサイ",
- "ο": "オミクロン",
- "π": "パイ",
- "ρ": "ロー",
- "σ": "シグマ",
- "τ": "タウ",
- "υ": "ウプシロン",
- "φ": "ファイ",
- "χ": "カイ",
- "ψ": "プサイ",
- "ω": "オメガ",
-}
-
-
-_NUMBER_WITH_SEPARATOR_RX = re.compile("[0-9]{1,3}(,[0-9]{3})+")
-_CURRENCY_MAP = {"$": "ドル", "¥": "円", "£": "ポンド", "€": "ユーロ"}
-_CURRENCY_RX = re.compile(r"([$¥£€])([0-9.]*[0-9])")
-_NUMBER_RX = re.compile(r"[0-9]+(\.[0-9]+)?")
-
-
-def japanese_convert_numbers_to_words(text: str) -> str:
- res = _NUMBER_WITH_SEPARATOR_RX.sub(lambda m: m[0].replace(",", ""), text)
- res = _CURRENCY_RX.sub(lambda m: m[2] + _CURRENCY_MAP.get(m[1], m[1]), res)
- res = _NUMBER_RX.sub(lambda m: num2words(m[0], lang="ja"), res)
- return res
-
-
-def japanese_convert_alpha_symbols_to_words(text: str) -> str:
- return "".join([_ALPHASYMBOL_YOMI.get(ch, ch) for ch in text.lower()])
-
-
-def japanese_text_to_phonemes(text: str) -> str:
- """Convert Japanese text to phonemes."""
- res = unicodedata.normalize("NFKC", text)
- res = japanese_convert_numbers_to_words(res)
- # res = japanese_convert_alpha_symbols_to_words(res)
- res = text2kata(res)
- res = kata2phoneme(res)
- return res
-
-
-def is_japanese_character(char):
- # 定义日语文字系统的 Unicode 范围
- japanese_ranges = [
- (0x3040, 0x309F), # 平假名
- (0x30A0, 0x30FF), # 片假名
- (0x4E00, 0x9FFF), # 汉字 (CJK Unified Ideographs)
- (0x3400, 0x4DBF), # 汉字扩展 A
- (0x20000, 0x2A6DF), # 汉字扩展 B
- # 可以根据需要添加其他汉字扩展范围
- ]
-
- # 将字符的 Unicode 编码转换为整数
- char_code = ord(char)
-
- # 检查字符是否在任何一个日语范围内
- for start, end in japanese_ranges:
- if start <= char_code <= end:
- return True
-
- return False
-
-
-rep_map = {
- ":": ",",
- ";": ",",
- ",": ",",
- "。": ".",
- "!": "!",
- "?": "?",
- "\n": ".",
- "·": ",",
- "、": ",",
- "...": "…",
-}
-
-
-def replace_punctuation(text):
- pattern = re.compile("|".join(re.escape(p) for p in rep_map.keys()))
-
- replaced_text = pattern.sub(lambda x: rep_map[x.group()], text)
-
- replaced_text = re.sub(
- r"[^\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FFF\u3400-\u4DBF"
- + "".join(punctuation)
- + r"]+",
- "",
- replaced_text,
- )
-
- return replaced_text
-
-
-def text_normalize(text):
- res = unicodedata.normalize("NFKC", text)
- res = japanese_convert_numbers_to_words(res)
- # res = "".join([i for i in res if is_japanese_character(i)])
- res = replace_punctuation(res)
- return res
-
-
-def distribute_phone(n_phone, n_word):
- phones_per_word = [0] * n_word
- for task in range(n_phone):
- min_tasks = min(phones_per_word)
- min_index = phones_per_word.index(min_tasks)
- phones_per_word[min_index] += 1
- return phones_per_word
-
-
-tokenizer = AutoTokenizer.from_pretrained("./bert/bert-base-japanese-v3")
-
-
-def g2p(norm_text):
- tokenized = tokenizer.tokenize(norm_text)
- phs = []
- ph_groups = []
- for t in tokenized:
- if not t.startswith("#"):
- ph_groups.append([t])
- else:
- ph_groups[-1].append(t.replace("#", ""))
- word2ph = []
- for group in ph_groups:
- phonemes = kata2phoneme(text2kata("".join(group)))
- # phonemes = [i for i in phonemes if i in symbols]
- for i in phonemes:
- assert i in symbols, (group, norm_text, tokenized)
- phone_len = len(phonemes)
- word_len = len(group)
-
- aaa = distribute_phone(phone_len, word_len)
- word2ph += aaa
-
- phs += phonemes
- phones = ["_"] + phs + ["_"]
- tones = [0 for i in phones]
- word2ph = [1] + word2ph + [1]
- return phones, tones, word2ph
-
-
-if __name__ == "__main__":
- tokenizer = AutoTokenizer.from_pretrained("./bert/bert-base-japanese-v3")
- text = "hello,こんにちは、世界!……"
- from text.japanese_bert import get_bert_feature
-
- text = text_normalize(text)
- print(text)
- phones, tones, word2ph = g2p(text)
- bert = get_bert_feature(text, word2ph)
-
- print(phones, tones, word2ph, bert.shape)
diff --git a/spaces/ReganMayer/ChatGPT44/README.md b/spaces/ReganMayer/ChatGPT44/README.md
deleted file mode 100644
index 7938de14e5355209aaae713f289ca469181bbb17..0000000000000000000000000000000000000000
--- a/spaces/ReganMayer/ChatGPT44/README.md
+++ /dev/null
@@ -1,14 +0,0 @@
----
-title: Chat-with-GPT4
-emoji: 🚀
-colorFrom: red
-colorTo: indigo
-sdk: gradio
-sdk_version: 3.21.0
-app_file: app.py
-pinned: false
-license: mit
-duplicated_from: ysharma/ChatGPT4
----
-
-Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet_null/core/mask/structures.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet_null/core/mask/structures.py
deleted file mode 100644
index d9ec5775f281ab8b76cb873e71a4edd9969ab905..0000000000000000000000000000000000000000
--- a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet_null/core/mask/structures.py
+++ /dev/null
@@ -1,1024 +0,0 @@
-from abc import ABCMeta, abstractmethod
-
-import cv2
-import mmcv
-import numpy as np
-import pycocotools.mask as maskUtils
-import torch
-from mmcv.ops.roi_align import roi_align
-
-
-class BaseInstanceMasks(metaclass=ABCMeta):
- """Base class for instance masks."""
-
- @abstractmethod
- def rescale(self, scale, interpolation='nearest'):
- """Rescale masks as large as possible while keeping the aspect ratio.
- For details can refer to `mmcv.imrescale`.
-
- Args:
- scale (tuple[int]): The maximum size (h, w) of rescaled mask.
- interpolation (str): Same as :func:`mmcv.imrescale`.
-
- Returns:
- BaseInstanceMasks: The rescaled masks.
- """
-
- @abstractmethod
- def resize(self, out_shape, interpolation='nearest'):
- """Resize masks to the given out_shape.
-
- Args:
- out_shape: Target (h, w) of resized mask.
- interpolation (str): See :func:`mmcv.imresize`.
-
- Returns:
- BaseInstanceMasks: The resized masks.
- """
-
- @abstractmethod
- def flip(self, flip_direction='horizontal'):
- """Flip masks alone the given direction.
-
- Args:
- flip_direction (str): Either 'horizontal' or 'vertical'.
-
- Returns:
- BaseInstanceMasks: The flipped masks.
- """
-
- @abstractmethod
- def pad(self, out_shape, pad_val):
- """Pad masks to the given size of (h, w).
-
- Args:
- out_shape (tuple[int]): Target (h, w) of padded mask.
- pad_val (int): The padded value.
-
- Returns:
- BaseInstanceMasks: The padded masks.
- """
-
- @abstractmethod
- def crop(self, bbox):
- """Crop each mask by the given bbox.
-
- Args:
- bbox (ndarray): Bbox in format [x1, y1, x2, y2], shape (4, ).
-
- Return:
- BaseInstanceMasks: The cropped masks.
- """
-
- @abstractmethod
- def crop_and_resize(self,
- bboxes,
- out_shape,
- inds,
- device,
- interpolation='bilinear'):
- """Crop and resize masks by the given bboxes.
-
- This function is mainly used in mask targets computation.
- It firstly align mask to bboxes by assigned_inds, then crop mask by the
- assigned bbox and resize to the size of (mask_h, mask_w)
-
- Args:
- bboxes (Tensor): Bboxes in format [x1, y1, x2, y2], shape (N, 4)
- out_shape (tuple[int]): Target (h, w) of resized mask
- inds (ndarray): Indexes to assign masks to each bbox,
- shape (N,) and values should be between [0, num_masks - 1].
- device (str): Device of bboxes
- interpolation (str): See `mmcv.imresize`
-
- Return:
- BaseInstanceMasks: the cropped and resized masks.
- """
-
- @abstractmethod
- def expand(self, expanded_h, expanded_w, top, left):
- """see :class:`Expand`."""
-
- @property
- @abstractmethod
- def areas(self):
- """ndarray: areas of each instance."""
-
- @abstractmethod
- def to_ndarray(self):
- """Convert masks to the format of ndarray.
-
- Return:
- ndarray: Converted masks in the format of ndarray.
- """
-
- @abstractmethod
- def to_tensor(self, dtype, device):
- """Convert masks to the format of Tensor.
-
- Args:
- dtype (str): Dtype of converted mask.
- device (torch.device): Device of converted masks.
-
- Returns:
- Tensor: Converted masks in the format of Tensor.
- """
-
- @abstractmethod
- def translate(self,
- out_shape,
- offset,
- direction='horizontal',
- fill_val=0,
- interpolation='bilinear'):
- """Translate the masks.
-
- Args:
- out_shape (tuple[int]): Shape for output mask, format (h, w).
- offset (int | float): The offset for translate.
- direction (str): The translate direction, either "horizontal"
- or "vertical".
- fill_val (int | float): Border value. Default 0.
- interpolation (str): Same as :func:`mmcv.imtranslate`.
-
- Returns:
- Translated masks.
- """
-
- def shear(self,
- out_shape,
- magnitude,
- direction='horizontal',
- border_value=0,
- interpolation='bilinear'):
- """Shear the masks.
-
- Args:
- out_shape (tuple[int]): Shape for output mask, format (h, w).
- magnitude (int | float): The magnitude used for shear.
- direction (str): The shear direction, either "horizontal"
- or "vertical".
- border_value (int | tuple[int]): Value used in case of a
- constant border. Default 0.
- interpolation (str): Same as in :func:`mmcv.imshear`.
-
- Returns:
- ndarray: Sheared masks.
- """
-
- @abstractmethod
- def rotate(self, out_shape, angle, center=None, scale=1.0, fill_val=0):
- """Rotate the masks.
-
- Args:
- out_shape (tuple[int]): Shape for output mask, format (h, w).
- angle (int | float): Rotation angle in degrees. Positive values
- mean counter-clockwise rotation.
- center (tuple[float], optional): Center point (w, h) of the
- rotation in source image. If not specified, the center of
- the image will be used.
- scale (int | float): Isotropic scale factor.
- fill_val (int | float): Border value. Default 0 for masks.
-
- Returns:
- Rotated masks.
- """
-
-
-class BitmapMasks(BaseInstanceMasks):
- """This class represents masks in the form of bitmaps.
-
- Args:
- masks (ndarray): ndarray of masks in shape (N, H, W), where N is
- the number of objects.
- height (int): height of masks
- width (int): width of masks
-
- Example:
- >>> from mmdet.core.mask.structures import * # NOQA
- >>> num_masks, H, W = 3, 32, 32
- >>> rng = np.random.RandomState(0)
- >>> masks = (rng.rand(num_masks, H, W) > 0.1).astype(np.int)
- >>> self = BitmapMasks(masks, height=H, width=W)
-
- >>> # demo crop_and_resize
- >>> num_boxes = 5
- >>> bboxes = np.array([[0, 0, 30, 10.0]] * num_boxes)
- >>> out_shape = (14, 14)
- >>> inds = torch.randint(0, len(self), size=(num_boxes,))
- >>> device = 'cpu'
- >>> interpolation = 'bilinear'
- >>> new = self.crop_and_resize(
- ... bboxes, out_shape, inds, device, interpolation)
- >>> assert len(new) == num_boxes
- >>> assert new.height, new.width == out_shape
- """
-
- def __init__(self, masks, height, width):
- self.height = height
- self.width = width
- if len(masks) == 0:
- self.masks = np.empty((0, self.height, self.width), dtype=np.uint8)
- else:
- assert isinstance(masks, (list, np.ndarray))
- if isinstance(masks, list):
- assert isinstance(masks[0], np.ndarray)
- assert masks[0].ndim == 2 # (H, W)
- else:
- assert masks.ndim == 3 # (N, H, W)
-
- self.masks = np.stack(masks).reshape(-1, height, width)
- assert self.masks.shape[1] == self.height
- assert self.masks.shape[2] == self.width
-
- def __getitem__(self, index):
- """Index the BitmapMask.
-
- Args:
- index (int | ndarray): Indices in the format of integer or ndarray.
-
- Returns:
- :obj:`BitmapMasks`: Indexed bitmap masks.
- """
- masks = self.masks[index].reshape(-1, self.height, self.width)
- return BitmapMasks(masks, self.height, self.width)
-
- def __iter__(self):
- return iter(self.masks)
-
- def __repr__(self):
- s = self.__class__.__name__ + '('
- s += f'num_masks={len(self.masks)}, '
- s += f'height={self.height}, '
- s += f'width={self.width})'
- return s
-
- def __len__(self):
- """Number of masks."""
- return len(self.masks)
-
- def rescale(self, scale, interpolation='nearest'):
- """See :func:`BaseInstanceMasks.rescale`."""
- if len(self.masks) == 0:
- new_w, new_h = mmcv.rescale_size((self.width, self.height), scale)
- rescaled_masks = np.empty((0, new_h, new_w), dtype=np.uint8)
- else:
- rescaled_masks = np.stack([
- mmcv.imrescale(mask, scale, interpolation=interpolation)
- for mask in self.masks
- ])
- height, width = rescaled_masks.shape[1:]
- return BitmapMasks(rescaled_masks, height, width)
-
- def resize(self, out_shape, interpolation='nearest'):
- """See :func:`BaseInstanceMasks.resize`."""
- if len(self.masks) == 0:
- resized_masks = np.empty((0, *out_shape), dtype=np.uint8)
- else:
- resized_masks = np.stack([
- mmcv.imresize(
- mask, out_shape[::-1], interpolation=interpolation)
- for mask in self.masks
- ])
- return BitmapMasks(resized_masks, *out_shape)
-
- def flip(self, flip_direction='horizontal'):
- """See :func:`BaseInstanceMasks.flip`."""
- assert flip_direction in ('horizontal', 'vertical', 'diagonal')
-
- if len(self.masks) == 0:
- flipped_masks = self.masks
- else:
- flipped_masks = np.stack([
- mmcv.imflip(mask, direction=flip_direction)
- for mask in self.masks
- ])
- return BitmapMasks(flipped_masks, self.height, self.width)
-
- def pad(self, out_shape, pad_val=0):
- """See :func:`BaseInstanceMasks.pad`."""
- if len(self.masks) == 0:
- padded_masks = np.empty((0, *out_shape), dtype=np.uint8)
- else:
- padded_masks = np.stack([
- mmcv.impad(mask, shape=out_shape, pad_val=pad_val)
- for mask in self.masks
- ])
- return BitmapMasks(padded_masks, *out_shape)
-
- def crop(self, bbox):
- """See :func:`BaseInstanceMasks.crop`."""
- assert isinstance(bbox, np.ndarray)
- assert bbox.ndim == 1
-
- # clip the boundary
- bbox = bbox.copy()
- bbox[0::2] = np.clip(bbox[0::2], 0, self.width)
- bbox[1::2] = np.clip(bbox[1::2], 0, self.height)
- x1, y1, x2, y2 = bbox
- w = np.maximum(x2 - x1, 1)
- h = np.maximum(y2 - y1, 1)
-
- if len(self.masks) == 0:
- cropped_masks = np.empty((0, h, w), dtype=np.uint8)
- else:
- cropped_masks = self.masks[:, y1:y1 + h, x1:x1 + w]
- return BitmapMasks(cropped_masks, h, w)
-
- def crop_and_resize(self,
- bboxes,
- out_shape,
- inds,
- device='cpu',
- interpolation='bilinear'):
- """See :func:`BaseInstanceMasks.crop_and_resize`."""
- if len(self.masks) == 0:
- empty_masks = np.empty((0, *out_shape), dtype=np.uint8)
- return BitmapMasks(empty_masks, *out_shape)
-
- # convert bboxes to tensor
- if isinstance(bboxes, np.ndarray):
- bboxes = torch.from_numpy(bboxes).to(device=device)
- if isinstance(inds, np.ndarray):
- inds = torch.from_numpy(inds).to(device=device)
-
- num_bbox = bboxes.shape[0]
- fake_inds = torch.arange(
- num_bbox, device=device).to(dtype=bboxes.dtype)[:, None]
- rois = torch.cat([fake_inds, bboxes], dim=1) # Nx5
- rois = rois.to(device=device)
- if num_bbox > 0:
- gt_masks_th = torch.from_numpy(self.masks).to(device).index_select(
- 0, inds).to(dtype=rois.dtype)
- targets = roi_align(gt_masks_th[:, None, :, :], rois, out_shape,
- 1.0, 0, 'avg', True).squeeze(1)
- resized_masks = (targets >= 0.5).cpu().numpy()
- else:
- resized_masks = []
- return BitmapMasks(resized_masks, *out_shape)
-
- def expand(self, expanded_h, expanded_w, top, left):
- """See :func:`BaseInstanceMasks.expand`."""
- if len(self.masks) == 0:
- expanded_mask = np.empty((0, expanded_h, expanded_w),
- dtype=np.uint8)
- else:
- expanded_mask = np.zeros((len(self), expanded_h, expanded_w),
- dtype=np.uint8)
- expanded_mask[:, top:top + self.height,
- left:left + self.width] = self.masks
- return BitmapMasks(expanded_mask, expanded_h, expanded_w)
-
- def translate(self,
- out_shape,
- offset,
- direction='horizontal',
- fill_val=0,
- interpolation='bilinear'):
- """Translate the BitmapMasks.
-
- Args:
- out_shape (tuple[int]): Shape for output mask, format (h, w).
- offset (int | float): The offset for translate.
- direction (str): The translate direction, either "horizontal"
- or "vertical".
- fill_val (int | float): Border value. Default 0 for masks.
- interpolation (str): Same as :func:`mmcv.imtranslate`.
-
- Returns:
- BitmapMasks: Translated BitmapMasks.
-
- Example:
- >>> from mmdet.core.mask.structures import BitmapMasks
- >>> self = BitmapMasks.random(dtype=np.uint8)
- >>> out_shape = (32, 32)
- >>> offset = 4
- >>> direction = 'horizontal'
- >>> fill_val = 0
- >>> interpolation = 'bilinear'
- >>> # Note, There seem to be issues when:
- >>> # * out_shape is different than self's shape
- >>> # * the mask dtype is not supported by cv2.AffineWarp
- >>> new = self.translate(out_shape, offset, direction, fill_val,
- >>> interpolation)
- >>> assert len(new) == len(self)
- >>> assert new.height, new.width == out_shape
- """
- if len(self.masks) == 0:
- translated_masks = np.empty((0, *out_shape), dtype=np.uint8)
- else:
- translated_masks = mmcv.imtranslate(
- self.masks.transpose((1, 2, 0)),
- offset,
- direction,
- border_value=fill_val,
- interpolation=interpolation)
- if translated_masks.ndim == 2:
- translated_masks = translated_masks[:, :, None]
- translated_masks = translated_masks.transpose(
- (2, 0, 1)).astype(self.masks.dtype)
- return BitmapMasks(translated_masks, *out_shape)
-
- def shear(self,
- out_shape,
- magnitude,
- direction='horizontal',
- border_value=0,
- interpolation='bilinear'):
- """Shear the BitmapMasks.
-
- Args:
- out_shape (tuple[int]): Shape for output mask, format (h, w).
- magnitude (int | float): The magnitude used for shear.
- direction (str): The shear direction, either "horizontal"
- or "vertical".
- border_value (int | tuple[int]): Value used in case of a
- constant border.
- interpolation (str): Same as in :func:`mmcv.imshear`.
-
- Returns:
- BitmapMasks: The sheared masks.
- """
- if len(self.masks) == 0:
- sheared_masks = np.empty((0, *out_shape), dtype=np.uint8)
- else:
- sheared_masks = mmcv.imshear(
- self.masks.transpose((1, 2, 0)),
- magnitude,
- direction,
- border_value=border_value,
- interpolation=interpolation)
- if sheared_masks.ndim == 2:
- sheared_masks = sheared_masks[:, :, None]
- sheared_masks = sheared_masks.transpose(
- (2, 0, 1)).astype(self.masks.dtype)
- return BitmapMasks(sheared_masks, *out_shape)
-
- def rotate(self, out_shape, angle, center=None, scale=1.0, fill_val=0):
- """Rotate the BitmapMasks.
-
- Args:
- out_shape (tuple[int]): Shape for output mask, format (h, w).
- angle (int | float): Rotation angle in degrees. Positive values
- mean counter-clockwise rotation.
- center (tuple[float], optional): Center point (w, h) of the
- rotation in source image. If not specified, the center of
- the image will be used.
- scale (int | float): Isotropic scale factor.
- fill_val (int | float): Border value. Default 0 for masks.
-
- Returns:
- BitmapMasks: Rotated BitmapMasks.
- """
- if len(self.masks) == 0:
- rotated_masks = np.empty((0, *out_shape), dtype=self.masks.dtype)
- else:
- rotated_masks = mmcv.imrotate(
- self.masks.transpose((1, 2, 0)),
- angle,
- center=center,
- scale=scale,
- border_value=fill_val)
- if rotated_masks.ndim == 2:
- # case when only one mask, (h, w)
- rotated_masks = rotated_masks[:, :, None] # (h, w, 1)
- rotated_masks = rotated_masks.transpose(
- (2, 0, 1)).astype(self.masks.dtype)
- return BitmapMasks(rotated_masks, *out_shape)
-
- @property
- def areas(self):
- """See :py:attr:`BaseInstanceMasks.areas`."""
- return self.masks.sum((1, 2))
-
- def to_ndarray(self):
- """See :func:`BaseInstanceMasks.to_ndarray`."""
- return self.masks
-
- def to_tensor(self, dtype, device):
- """See :func:`BaseInstanceMasks.to_tensor`."""
- return torch.tensor(self.masks, dtype=dtype, device=device)
-
- @classmethod
- def random(cls,
- num_masks=3,
- height=32,
- width=32,
- dtype=np.uint8,
- rng=None):
- """Generate random bitmap masks for demo / testing purposes.
-
- Example:
- >>> from mmdet.core.mask.structures import BitmapMasks
- >>> self = BitmapMasks.random()
- >>> print('self = {}'.format(self))
- self = BitmapMasks(num_masks=3, height=32, width=32)
- """
- from mmdet.utils.util_random import ensure_rng
- rng = ensure_rng(rng)
- masks = (rng.rand(num_masks, height, width) > 0.1).astype(dtype)
- self = cls(masks, height=height, width=width)
- return self
-
-
-class PolygonMasks(BaseInstanceMasks):
- """This class represents masks in the form of polygons.
-
- Polygons is a list of three levels. The first level of the list
- corresponds to objects, the second level to the polys that compose the
- object, the third level to the poly coordinates
-
- Args:
- masks (list[list[ndarray]]): The first level of the list
- corresponds to objects, the second level to the polys that
- compose the object, the third level to the poly coordinates
- height (int): height of masks
- width (int): width of masks
-
- Example:
- >>> from mmdet.core.mask.structures import * # NOQA
- >>> masks = [
- >>> [ np.array([0, 0, 10, 0, 10, 10., 0, 10, 0, 0]) ]
- >>> ]
- >>> height, width = 16, 16
- >>> self = PolygonMasks(masks, height, width)
-
- >>> # demo translate
- >>> new = self.translate((16, 16), 4., direction='horizontal')
- >>> assert np.all(new.masks[0][0][1::2] == masks[0][0][1::2])
- >>> assert np.all(new.masks[0][0][0::2] == masks[0][0][0::2] + 4)
-
- >>> # demo crop_and_resize
- >>> num_boxes = 3
- >>> bboxes = np.array([[0, 0, 30, 10.0]] * num_boxes)
- >>> out_shape = (16, 16)
- >>> inds = torch.randint(0, len(self), size=(num_boxes,))
- >>> device = 'cpu'
- >>> interpolation = 'bilinear'
- >>> new = self.crop_and_resize(
- ... bboxes, out_shape, inds, device, interpolation)
- >>> assert len(new) == num_boxes
- >>> assert new.height, new.width == out_shape
- """
-
- def __init__(self, masks, height, width):
- assert isinstance(masks, list)
- if len(masks) > 0:
- assert isinstance(masks[0], list)
- assert isinstance(masks[0][0], np.ndarray)
-
- self.height = height
- self.width = width
- self.masks = masks
-
- def __getitem__(self, index):
- """Index the polygon masks.
-
- Args:
- index (ndarray | List): The indices.
-
- Returns:
- :obj:`PolygonMasks`: The indexed polygon masks.
- """
- if isinstance(index, np.ndarray):
- index = index.tolist()
- if isinstance(index, list):
- masks = [self.masks[i] for i in index]
- else:
- try:
- masks = self.masks[index]
- except Exception:
- raise ValueError(
- f'Unsupported input of type {type(index)} for indexing!')
- if len(masks) and isinstance(masks[0], np.ndarray):
- masks = [masks] # ensure a list of three levels
- return PolygonMasks(masks, self.height, self.width)
-
- def __iter__(self):
- return iter(self.masks)
-
- def __repr__(self):
- s = self.__class__.__name__ + '('
- s += f'num_masks={len(self.masks)}, '
- s += f'height={self.height}, '
- s += f'width={self.width})'
- return s
-
- def __len__(self):
- """Number of masks."""
- return len(self.masks)
-
- def rescale(self, scale, interpolation=None):
- """see :func:`BaseInstanceMasks.rescale`"""
- new_w, new_h = mmcv.rescale_size((self.width, self.height), scale)
- if len(self.masks) == 0:
- rescaled_masks = PolygonMasks([], new_h, new_w)
- else:
- rescaled_masks = self.resize((new_h, new_w))
- return rescaled_masks
-
- def resize(self, out_shape, interpolation=None):
- """see :func:`BaseInstanceMasks.resize`"""
- if len(self.masks) == 0:
- resized_masks = PolygonMasks([], *out_shape)
- else:
- h_scale = out_shape[0] / self.height
- w_scale = out_shape[1] / self.width
- resized_masks = []
- for poly_per_obj in self.masks:
- resized_poly = []
- for p in poly_per_obj:
- p = p.copy()
- p[0::2] *= w_scale
- p[1::2] *= h_scale
- resized_poly.append(p)
- resized_masks.append(resized_poly)
- resized_masks = PolygonMasks(resized_masks, *out_shape)
- return resized_masks
-
- def flip(self, flip_direction='horizontal'):
- """see :func:`BaseInstanceMasks.flip`"""
- assert flip_direction in ('horizontal', 'vertical', 'diagonal')
- if len(self.masks) == 0:
- flipped_masks = PolygonMasks([], self.height, self.width)
- else:
- flipped_masks = []
- for poly_per_obj in self.masks:
- flipped_poly_per_obj = []
- for p in poly_per_obj:
- p = p.copy()
- if flip_direction == 'horizontal':
- p[0::2] = self.width - p[0::2]
- elif flip_direction == 'vertical':
- p[1::2] = self.height - p[1::2]
- else:
- p[0::2] = self.width - p[0::2]
- p[1::2] = self.height - p[1::2]
- flipped_poly_per_obj.append(p)
- flipped_masks.append(flipped_poly_per_obj)
- flipped_masks = PolygonMasks(flipped_masks, self.height,
- self.width)
- return flipped_masks
-
- def crop(self, bbox):
- """see :func:`BaseInstanceMasks.crop`"""
- assert isinstance(bbox, np.ndarray)
- assert bbox.ndim == 1
-
- # clip the boundary
- bbox = bbox.copy()
- bbox[0::2] = np.clip(bbox[0::2], 0, self.width)
- bbox[1::2] = np.clip(bbox[1::2], 0, self.height)
- x1, y1, x2, y2 = bbox
- w = np.maximum(x2 - x1, 1)
- h = np.maximum(y2 - y1, 1)
-
- if len(self.masks) == 0:
- cropped_masks = PolygonMasks([], h, w)
- else:
- cropped_masks = []
- for poly_per_obj in self.masks:
- cropped_poly_per_obj = []
- for p in poly_per_obj:
- # pycocotools will clip the boundary
- p = p.copy()
- p[0::2] -= bbox[0]
- p[1::2] -= bbox[1]
- cropped_poly_per_obj.append(p)
- cropped_masks.append(cropped_poly_per_obj)
- cropped_masks = PolygonMasks(cropped_masks, h, w)
- return cropped_masks
-
- def pad(self, out_shape, pad_val=0):
- """padding has no effect on polygons`"""
- return PolygonMasks(self.masks, *out_shape)
-
- def expand(self, *args, **kwargs):
- """TODO: Add expand for polygon"""
- raise NotImplementedError
-
- def crop_and_resize(self,
- bboxes,
- out_shape,
- inds,
- device='cpu',
- interpolation='bilinear'):
- """see :func:`BaseInstanceMasks.crop_and_resize`"""
- out_h, out_w = out_shape
- if len(self.masks) == 0:
- return PolygonMasks([], out_h, out_w)
-
- resized_masks = []
- for i in range(len(bboxes)):
- mask = self.masks[inds[i]]
- bbox = bboxes[i, :]
- x1, y1, x2, y2 = bbox
- w = np.maximum(x2 - x1, 1)
- h = np.maximum(y2 - y1, 1)
- h_scale = out_h / max(h, 0.1) # avoid too large scale
- w_scale = out_w / max(w, 0.1)
-
- resized_mask = []
- for p in mask:
- p = p.copy()
- # crop
- # pycocotools will clip the boundary
- p[0::2] -= bbox[0]
- p[1::2] -= bbox[1]
-
- # resize
- p[0::2] *= w_scale
- p[1::2] *= h_scale
- resized_mask.append(p)
- resized_masks.append(resized_mask)
- return PolygonMasks(resized_masks, *out_shape)
-
- def translate(self,
- out_shape,
- offset,
- direction='horizontal',
- fill_val=None,
- interpolation=None):
- """Translate the PolygonMasks.
-
- Example:
- >>> self = PolygonMasks.random(dtype=np.int)
- >>> out_shape = (self.height, self.width)
- >>> new = self.translate(out_shape, 4., direction='horizontal')
- >>> assert np.all(new.masks[0][0][1::2] == self.masks[0][0][1::2])
- >>> assert np.all(new.masks[0][0][0::2] == self.masks[0][0][0::2] + 4) # noqa: E501
- """
- assert fill_val is None or fill_val == 0, 'Here fill_val is not '\
- f'used, and defaultly should be None or 0. got {fill_val}.'
- if len(self.masks) == 0:
- translated_masks = PolygonMasks([], *out_shape)
- else:
- translated_masks = []
- for poly_per_obj in self.masks:
- translated_poly_per_obj = []
- for p in poly_per_obj:
- p = p.copy()
- if direction == 'horizontal':
- p[0::2] = np.clip(p[0::2] + offset, 0, out_shape[1])
- elif direction == 'vertical':
- p[1::2] = np.clip(p[1::2] + offset, 0, out_shape[0])
- translated_poly_per_obj.append(p)
- translated_masks.append(translated_poly_per_obj)
- translated_masks = PolygonMasks(translated_masks, *out_shape)
- return translated_masks
-
- def shear(self,
- out_shape,
- magnitude,
- direction='horizontal',
- border_value=0,
- interpolation='bilinear'):
- """See :func:`BaseInstanceMasks.shear`."""
- if len(self.masks) == 0:
- sheared_masks = PolygonMasks([], *out_shape)
- else:
- sheared_masks = []
- if direction == 'horizontal':
- shear_matrix = np.stack([[1, magnitude],
- [0, 1]]).astype(np.float32)
- elif direction == 'vertical':
- shear_matrix = np.stack([[1, 0], [magnitude,
- 1]]).astype(np.float32)
- for poly_per_obj in self.masks:
- sheared_poly = []
- for p in poly_per_obj:
- p = np.stack([p[0::2], p[1::2]], axis=0) # [2, n]
- new_coords = np.matmul(shear_matrix, p) # [2, n]
- new_coords[0, :] = np.clip(new_coords[0, :], 0,
- out_shape[1])
- new_coords[1, :] = np.clip(new_coords[1, :], 0,
- out_shape[0])
- sheared_poly.append(
- new_coords.transpose((1, 0)).reshape(-1))
- sheared_masks.append(sheared_poly)
- sheared_masks = PolygonMasks(sheared_masks, *out_shape)
- return sheared_masks
-
- def rotate(self, out_shape, angle, center=None, scale=1.0, fill_val=0):
- """See :func:`BaseInstanceMasks.rotate`."""
- if len(self.masks) == 0:
- rotated_masks = PolygonMasks([], *out_shape)
- else:
- rotated_masks = []
- rotate_matrix = cv2.getRotationMatrix2D(center, -angle, scale)
- for poly_per_obj in self.masks:
- rotated_poly = []
- for p in poly_per_obj:
- p = p.copy()
- coords = np.stack([p[0::2], p[1::2]], axis=1) # [n, 2]
- # pad 1 to convert from format [x, y] to homogeneous
- # coordinates format [x, y, 1]
- coords = np.concatenate(
- (coords, np.ones((coords.shape[0], 1), coords.dtype)),
- axis=1) # [n, 3]
- rotated_coords = np.matmul(
- rotate_matrix[None, :, :],
- coords[:, :, None])[..., 0] # [n, 2, 1] -> [n, 2]
- rotated_coords[:, 0] = np.clip(rotated_coords[:, 0], 0,
- out_shape[1])
- rotated_coords[:, 1] = np.clip(rotated_coords[:, 1], 0,
- out_shape[0])
- rotated_poly.append(rotated_coords.reshape(-1))
- rotated_masks.append(rotated_poly)
- rotated_masks = PolygonMasks(rotated_masks, *out_shape)
- return rotated_masks
-
- def to_bitmap(self):
- """convert polygon masks to bitmap masks."""
- bitmap_masks = self.to_ndarray()
- return BitmapMasks(bitmap_masks, self.height, self.width)
-
- @property
- def areas(self):
- """Compute areas of masks.
-
- This func is modified from `detectron2
- `_.
- The function only works with Polygons using the shoelace formula.
-
- Return:
- ndarray: areas of each instance
- """ # noqa: W501
- area = []
- for polygons_per_obj in self.masks:
- area_per_obj = 0
- for p in polygons_per_obj:
- area_per_obj += self._polygon_area(p[0::2], p[1::2])
- area.append(area_per_obj)
- return np.asarray(area)
-
- def _polygon_area(self, x, y):
- """Compute the area of a component of a polygon.
-
- Using the shoelace formula:
- https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates
-
- Args:
- x (ndarray): x coordinates of the component
- y (ndarray): y coordinates of the component
-
- Return:
- float: the are of the component
- """ # noqa: 501
- return 0.5 * np.abs(
- np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))
-
- def to_ndarray(self):
- """Convert masks to the format of ndarray."""
- if len(self.masks) == 0:
- return np.empty((0, self.height, self.width), dtype=np.uint8)
- bitmap_masks = []
- for poly_per_obj in self.masks:
- bitmap_masks.append(
- polygon_to_bitmap(poly_per_obj, self.height, self.width))
- return np.stack(bitmap_masks)
-
- def to_tensor(self, dtype, device):
- """See :func:`BaseInstanceMasks.to_tensor`."""
- if len(self.masks) == 0:
- return torch.empty((0, self.height, self.width),
- dtype=dtype,
- device=device)
- ndarray_masks = self.to_ndarray()
- return torch.tensor(ndarray_masks, dtype=dtype, device=device)
-
- @classmethod
- def random(cls,
- num_masks=3,
- height=32,
- width=32,
- n_verts=5,
- dtype=np.float32,
- rng=None):
- """Generate random polygon masks for demo / testing purposes.
-
- Adapted from [1]_
-
- References:
- .. [1] https://gitlab.kitware.com/computer-vision/kwimage/-/blob/928cae35ca8/kwimage/structs/polygon.py#L379 # noqa: E501
-
- Example:
- >>> from mmdet.core.mask.structures import PolygonMasks
- >>> self = PolygonMasks.random()
- >>> print('self = {}'.format(self))
- """
- from mmdet.utils.util_random import ensure_rng
- rng = ensure_rng(rng)
-
- def _gen_polygon(n, irregularity, spikeyness):
- """Creates the polygon by sampling points on a circle around the
- centre. Random noise is added by varying the angular spacing
- between sequential points, and by varying the radial distance of
- each point from the centre.
-
- Based on original code by Mike Ounsworth
-
- Args:
- n (int): number of vertices
- irregularity (float): [0,1] indicating how much variance there
- is in the angular spacing of vertices. [0,1] will map to
- [0, 2pi/numberOfVerts]
- spikeyness (float): [0,1] indicating how much variance there is
- in each vertex from the circle of radius aveRadius. [0,1]
- will map to [0, aveRadius]
-
- Returns:
- a list of vertices, in CCW order.
- """
- from scipy.stats import truncnorm
- # Generate around the unit circle
- cx, cy = (0.0, 0.0)
- radius = 1
-
- tau = np.pi * 2
-
- irregularity = np.clip(irregularity, 0, 1) * 2 * np.pi / n
- spikeyness = np.clip(spikeyness, 1e-9, 1)
-
- # generate n angle steps
- lower = (tau / n) - irregularity
- upper = (tau / n) + irregularity
- angle_steps = rng.uniform(lower, upper, n)
-
- # normalize the steps so that point 0 and point n+1 are the same
- k = angle_steps.sum() / (2 * np.pi)
- angles = (angle_steps / k).cumsum() + rng.uniform(0, tau)
-
- # Convert high and low values to be wrt the standard normal range
- # https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.truncnorm.html
- low = 0
- high = 2 * radius
- mean = radius
- std = spikeyness
- a = (low - mean) / std
- b = (high - mean) / std
- tnorm = truncnorm(a=a, b=b, loc=mean, scale=std)
-
- # now generate the points
- radii = tnorm.rvs(n, random_state=rng)
- x_pts = cx + radii * np.cos(angles)
- y_pts = cy + radii * np.sin(angles)
-
- points = np.hstack([x_pts[:, None], y_pts[:, None]])
-
- # Scale to 0-1 space
- points = points - points.min(axis=0)
- points = points / points.max(axis=0)
-
- # Randomly place within 0-1 space
- points = points * (rng.rand() * .8 + .2)
- min_pt = points.min(axis=0)
- max_pt = points.max(axis=0)
-
- high = (1 - max_pt)
- low = (0 - min_pt)
- offset = (rng.rand(2) * (high - low)) + low
- points = points + offset
- return points
-
- def _order_vertices(verts):
- """
- References:
- https://stackoverflow.com/questions/1709283/how-can-i-sort-a-coordinate-list-for-a-rectangle-counterclockwise
- """
- mlat = verts.T[0].sum() / len(verts)
- mlng = verts.T[1].sum() / len(verts)
-
- tau = np.pi * 2
- angle = (np.arctan2(mlat - verts.T[0], verts.T[1] - mlng) +
- tau) % tau
- sortx = angle.argsort()
- verts = verts.take(sortx, axis=0)
- return verts
-
- # Generate a random exterior for each requested mask
- masks = []
- for _ in range(num_masks):
- exterior = _order_vertices(_gen_polygon(n_verts, 0.9, 0.9))
- exterior = (exterior * [(width, height)]).astype(dtype)
- masks.append([exterior.ravel()])
-
- self = cls(masks, height, width)
- return self
-
-
-def polygon_to_bitmap(polygons, height, width):
- """Convert masks from the form of polygons to bitmaps.
-
- Args:
- polygons (list[ndarray]): masks in polygon representation
- height (int): mask height
- width (int): mask width
-
- Return:
- ndarray: the converted masks in bitmap representation
- """
- rles = maskUtils.frPyObjects(polygons, height, width)
- rle = maskUtils.merge(rles)
- bitmap_mask = maskUtils.decode(rle).astype(np.bool)
- return bitmap_mask
diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmseg/utils/collect_env.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmseg/utils/collect_env.py
deleted file mode 100644
index 65c2134ddbee9655161237dd0894d38c768c2624..0000000000000000000000000000000000000000
--- a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmseg/utils/collect_env.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from annotator.uniformer.mmcv.utils import collect_env as collect_base_env
-from annotator.uniformer.mmcv.utils import get_git_hash
-
-import annotator.uniformer.mmseg as mmseg
-
-
-def collect_env():
- """Collect the information of the running environments."""
- env_info = collect_base_env()
- env_info['MMSegmentation'] = f'{mmseg.__version__}+{get_git_hash()[:7]}'
-
- return env_info
-
-
-if __name__ == '__main__':
- for name, val in collect_env().items():
- print('{}: {}'.format(name, val))
diff --git a/spaces/Rongjiehuang/GenerSpeech/tasks/tts/tts_base.py b/spaces/Rongjiehuang/GenerSpeech/tasks/tts/tts_base.py
deleted file mode 100644
index 509740b54dbf23db6bafebd6bc46089ee83cf499..0000000000000000000000000000000000000000
--- a/spaces/Rongjiehuang/GenerSpeech/tasks/tts/tts_base.py
+++ /dev/null
@@ -1,305 +0,0 @@
-import filecmp
-
-import matplotlib
-
-from utils.plot import spec_to_figure
-
-matplotlib.use('Agg')
-
-from data_gen.tts.data_gen_utils import get_pitch
-from modules.fastspeech.tts_modules import mel2ph_to_dur
-from tasks.tts.dataset_utils import BaseTTSDataset
-from utils.tts_utils import sequence_mask
-from multiprocessing.pool import Pool
-from tasks.base_task import data_loader, BaseConcatDataset
-from utils.common_schedulers import RSQRTSchedule, NoneSchedule
-from vocoders.base_vocoder import get_vocoder_cls, BaseVocoder
-import os
-import numpy as np
-from tqdm import tqdm
-import torch.distributed as dist
-from tasks.base_task import BaseTask
-from utils.hparams import hparams
-from utils.text_encoder import TokenTextEncoder
-import json
-import matplotlib.pyplot as plt
-import torch
-import torch.optim
-import torch.utils.data
-import utils
-from utils import audio
-import pandas as pd
-
-
-class TTSBaseTask(BaseTask):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.dataset_cls = BaseTTSDataset
- self.max_tokens = hparams['max_tokens']
- self.max_sentences = hparams['max_sentences']
- self.max_valid_tokens = hparams['max_valid_tokens']
- if self.max_valid_tokens == -1:
- hparams['max_valid_tokens'] = self.max_valid_tokens = self.max_tokens
- self.max_valid_sentences = hparams['max_valid_sentences']
- if self.max_valid_sentences == -1:
- hparams['max_valid_sentences'] = self.max_valid_sentences = self.max_sentences
- self.vocoder = None
- self.phone_encoder = self.build_phone_encoder(hparams['binary_data_dir'])
- self.padding_idx = self.phone_encoder.pad()
- self.eos_idx = self.phone_encoder.eos()
- self.seg_idx = self.phone_encoder.seg()
- self.saving_result_pool = None
- self.saving_results_futures = None
- self.stats = {}
-
- @data_loader
- def train_dataloader(self):
- if hparams['train_sets'] != '':
- train_sets = hparams['train_sets'].split("|")
- # check if all train_sets have the same spk map and dictionary
- binary_data_dir = hparams['binary_data_dir']
- file_to_cmp = ['phone_set.json']
- if os.path.exists(f'{binary_data_dir}/word_set.json'):
- file_to_cmp.append('word_set.json')
- if hparams['use_spk_id']:
- file_to_cmp.append('spk_map.json')
- for f in file_to_cmp:
- for ds_name in train_sets:
- base_file = os.path.join(binary_data_dir, f)
- ds_file = os.path.join(ds_name, f)
- assert filecmp.cmp(base_file, ds_file), \
- f'{f} in {ds_name} is not same with that in {binary_data_dir}.'
- train_dataset = BaseConcatDataset([
- self.dataset_cls(prefix='train', shuffle=True, data_dir=ds_name) for ds_name in train_sets])
- else:
- train_dataset = self.dataset_cls(prefix=hparams['train_set_name'], shuffle=True)
- return self.build_dataloader(train_dataset, True, self.max_tokens, self.max_sentences,
- endless=hparams['endless_ds'])
-
- @data_loader
- def val_dataloader(self):
- valid_dataset = self.dataset_cls(prefix=hparams['valid_set_name'], shuffle=False)
- return self.build_dataloader(valid_dataset, False, self.max_valid_tokens, self.max_valid_sentences)
-
- @data_loader
- def test_dataloader(self):
- test_dataset = self.dataset_cls(prefix=hparams['test_set_name'], shuffle=False)
- self.test_dl = self.build_dataloader(
- test_dataset, False, self.max_valid_tokens,
- self.max_valid_sentences, batch_by_size=False)
- return self.test_dl
-
- def build_dataloader(self, dataset, shuffle, max_tokens=None, max_sentences=None,
- required_batch_size_multiple=-1, endless=False, batch_by_size=True):
- devices_cnt = torch.cuda.device_count()
- if devices_cnt == 0:
- devices_cnt = 1
- if required_batch_size_multiple == -1:
- required_batch_size_multiple = devices_cnt
-
- def shuffle_batches(batches):
- np.random.shuffle(batches)
- return batches
-
- if max_tokens is not None:
- max_tokens *= devices_cnt
- if max_sentences is not None:
- max_sentences *= devices_cnt
- indices = dataset.ordered_indices()
- if batch_by_size:
- batch_sampler = utils.batch_by_size(
- indices, dataset.num_tokens, max_tokens=max_tokens, max_sentences=max_sentences,
- required_batch_size_multiple=required_batch_size_multiple,
- )
- else:
- batch_sampler = []
- for i in range(0, len(indices), max_sentences):
- batch_sampler.append(indices[i:i + max_sentences])
-
- if shuffle:
- batches = shuffle_batches(list(batch_sampler))
- if endless:
- batches = [b for _ in range(1000) for b in shuffle_batches(list(batch_sampler))]
- else:
- batches = batch_sampler
- if endless:
- batches = [b for _ in range(1000) for b in batches]
- num_workers = dataset.num_workers
- if self.trainer.use_ddp:
- num_replicas = dist.get_world_size()
- rank = dist.get_rank()
- batches = [x[rank::num_replicas] for x in batches if len(x) % num_replicas == 0]
- return torch.utils.data.DataLoader(dataset,
- collate_fn=dataset.collater,
- batch_sampler=batches,
- num_workers=num_workers,
- pin_memory=False)
-
- def build_phone_encoder(self, data_dir):
- phone_list_file = os.path.join(data_dir, 'phone_set.json')
- phone_list = json.load(open(phone_list_file))
- return TokenTextEncoder(None, vocab_list=phone_list, replace_oov=',')
-
- def build_scheduler(self, optimizer):
- if hparams['scheduler'] == 'rsqrt':
- return RSQRTSchedule(optimizer)
- else:
- return NoneSchedule(optimizer)
-
- def build_optimizer(self, model):
- self.optimizer = optimizer = torch.optim.AdamW(
- model.parameters(),
- lr=hparams['lr'],
- betas=(hparams['optimizer_adam_beta1'], hparams['optimizer_adam_beta2']),
- weight_decay=hparams['weight_decay'])
- return optimizer
-
- def plot_mel(self, batch_idx, spec, spec_out, name=None):
- spec_cat = torch.cat([spec, spec_out], -1)
- name = f'mel_{batch_idx}' if name is None else name
- vmin = hparams['mel_vmin']
- vmax = hparams['mel_vmax']
- self.logger.add_figure(name, spec_to_figure(spec_cat[0], vmin, vmax), self.global_step)
-
- def test_start(self):
- self.saving_result_pool = Pool(min(int(os.getenv('N_PROC', os.cpu_count())), 16))
- self.saving_results_futures = []
- self.results_id = 0
- self.gen_dir = os.path.join(
- hparams['work_dir'],
- f'generated_{self.trainer.global_step}_{hparams["gen_dir_name"]}')
- self.vocoder: BaseVocoder = get_vocoder_cls(hparams)()
-
- def after_infer(self, predictions, sil_start_frame=0):
- predictions = utils.unpack_dict_to_list(predictions)
- assert len(predictions) == 1, 'Only support batch_size=1 in inference.'
- prediction = predictions[0]
- prediction = utils.tensors_to_np(prediction)
- item_name = prediction.get('item_name')
- text = prediction.get('text')
- ph_tokens = prediction.get('txt_tokens')
- mel_gt = prediction["mels"]
- mel2ph_gt = prediction.get("mel2ph")
- mel2ph_gt = mel2ph_gt if mel2ph_gt is not None else None
- mel_pred = prediction["outputs"]
- mel2ph_pred = prediction.get("mel2ph_pred")
- f0_gt = prediction.get("f0")
- f0_pred = prediction.get("f0_pred")
-
- str_phs = None
- if self.phone_encoder is not None and 'txt_tokens' in prediction:
- str_phs = self.phone_encoder.decode(prediction['txt_tokens'], strip_padding=True)
-
- if 'encdec_attn' in prediction:
- encdec_attn = prediction['encdec_attn']
- encdec_attn = encdec_attn[encdec_attn.max(-1).sum(-1).argmax(-1)]
- txt_lengths = prediction.get('txt_lengths')
- encdec_attn = encdec_attn.T[:txt_lengths, :len(mel_gt)]
- else:
- encdec_attn = None
-
- wav_pred = self.vocoder.spec2wav(mel_pred, f0=f0_pred)
- wav_pred[:sil_start_frame * hparams['hop_size']] = 0
- gen_dir = self.gen_dir
- base_fn = f'[{self.results_id:06d}][{item_name}][%s]'
- # if text is not None:
- # base_fn += text.replace(":", "%3A")[:80]
- base_fn = base_fn.replace(' ', '_')
- if not hparams['profile_infer']:
- os.makedirs(gen_dir, exist_ok=True)
- os.makedirs(f'{gen_dir}/wavs', exist_ok=True)
- os.makedirs(f'{gen_dir}/plot', exist_ok=True)
- if hparams.get('save_mel_npy', False):
- os.makedirs(f'{gen_dir}/npy', exist_ok=True)
- if 'encdec_attn' in prediction:
- os.makedirs(f'{gen_dir}/attn_plot', exist_ok=True)
- self.saving_results_futures.append(
- self.saving_result_pool.apply_async(self.save_result, args=[
- wav_pred, mel_pred, base_fn % 'P', gen_dir, str_phs, mel2ph_pred, encdec_attn]))
-
- if mel_gt is not None and hparams['save_gt']:
- wav_gt = self.vocoder.spec2wav(mel_gt, f0=f0_gt)
- self.saving_results_futures.append(
- self.saving_result_pool.apply_async(self.save_result, args=[
- wav_gt, mel_gt, base_fn % 'G', gen_dir, str_phs, mel2ph_gt]))
- if hparams['save_f0']:
- import matplotlib.pyplot as plt
- f0_pred_, _ = get_pitch(wav_pred, mel_pred, hparams)
- f0_gt_, _ = get_pitch(wav_gt, mel_gt, hparams)
- fig = plt.figure()
- plt.plot(f0_pred_, label=r'$\hat{f_0}$')
- plt.plot(f0_gt_, label=r'$f_0$')
- plt.legend()
- plt.tight_layout()
- plt.savefig(f'{gen_dir}/plot/[F0][{item_name}]{text}.png', format='png')
- plt.close(fig)
- print(f"Pred_shape: {mel_pred.shape}, gt_shape: {mel_gt.shape}")
- self.results_id += 1
- return {
- 'item_name': item_name,
- 'text': text,
- 'ph_tokens': self.phone_encoder.decode(ph_tokens.tolist()),
- 'wav_fn_pred': base_fn % 'P',
- 'wav_fn_gt': base_fn % 'G',
- }
-
- @staticmethod
- def save_result(wav_out, mel, base_fn, gen_dir, str_phs=None, mel2ph=None, alignment=None):
- audio.save_wav(wav_out, f'{gen_dir}/wavs/{base_fn}.wav', hparams['audio_sample_rate'],
- norm=hparams['out_wav_norm'])
- fig = plt.figure(figsize=(14, 10))
- spec_vmin = hparams['mel_vmin']
- spec_vmax = hparams['mel_vmax']
- heatmap = plt.pcolor(mel.T, vmin=spec_vmin, vmax=spec_vmax)
- fig.colorbar(heatmap)
- f0, _ = get_pitch(wav_out, mel, hparams)
- f0 = f0 / 10 * (f0 > 0)
- plt.plot(f0, c='white', linewidth=1, alpha=0.6)
- if mel2ph is not None and str_phs is not None:
- decoded_txt = str_phs.split(" ")
- dur = mel2ph_to_dur(torch.LongTensor(mel2ph)[None, :], len(decoded_txt))[0].numpy()
- dur = [0] + list(np.cumsum(dur))
- for i in range(len(dur) - 1):
- shift = (i % 20) + 1
- plt.text(dur[i], shift, decoded_txt[i])
- plt.hlines(shift, dur[i], dur[i + 1], colors='b' if decoded_txt[i] != '|' else 'black')
- plt.vlines(dur[i], 0, 5, colors='b' if decoded_txt[i] != '|' else 'black',
- alpha=1, linewidth=1)
- plt.tight_layout()
- plt.savefig(f'{gen_dir}/plot/{base_fn}.png', format='png')
- plt.close(fig)
- if hparams.get('save_mel_npy', False):
- np.save(f'{gen_dir}/npy/{base_fn}', mel)
- if alignment is not None:
- fig, ax = plt.subplots(figsize=(12, 16))
- im = ax.imshow(alignment, aspect='auto', origin='lower',
- interpolation='none')
- decoded_txt = str_phs.split(" ")
- ax.set_yticks(np.arange(len(decoded_txt)))
- ax.set_yticklabels(list(decoded_txt), fontsize=6)
- fig.colorbar(im, ax=ax)
- fig.savefig(f'{gen_dir}/attn_plot/{base_fn}_attn.png', format='png')
- plt.close(fig)
-
- def test_end(self, outputs):
- pd.DataFrame(outputs).to_csv(f'{self.gen_dir}/meta.csv')
- self.saving_result_pool.close()
- [f.get() for f in tqdm(self.saving_results_futures)]
- self.saving_result_pool.join()
- return {}
-
- ##########
- # utils
- ##########
- def weights_nonzero_speech(self, target):
- # target : B x T x mel
- # Assign weight 1.0 to all labels except for padding (id=0).
- dim = target.size(-1)
- return target.abs().sum(-1, keepdim=True).ne(0).float().repeat(1, 1, dim)
-
- def make_stop_target(self, target):
- # target : B x T x mel
- seq_mask = target.abs().sum(-1).ne(0).float()
- seq_length = seq_mask.sum(1)
- mask_r = 1 - sequence_mask(seq_length - 1, target.size(1)).float()
- return seq_mask, mask_r
diff --git a/spaces/Salesforce/EDICT/my_half_diffusers/__init__.py b/spaces/Salesforce/EDICT/my_half_diffusers/__init__.py
deleted file mode 100644
index bf2f183c9b5dc45a3cb40a3b2408833f6966ac96..0000000000000000000000000000000000000000
--- a/spaces/Salesforce/EDICT/my_half_diffusers/__init__.py
+++ /dev/null
@@ -1,60 +0,0 @@
-from .utils import (
- is_inflect_available,
- is_onnx_available,
- is_scipy_available,
- is_transformers_available,
- is_unidecode_available,
-)
-
-
-__version__ = "0.3.0"
-
-from .configuration_utils import ConfigMixin
-from .modeling_utils import ModelMixin
-from .models import AutoencoderKL, UNet2DConditionModel, UNet2DModel, VQModel
-from .onnx_utils import OnnxRuntimeModel
-from .optimization import (
- get_constant_schedule,
- get_constant_schedule_with_warmup,
- get_cosine_schedule_with_warmup,
- get_cosine_with_hard_restarts_schedule_with_warmup,
- get_linear_schedule_with_warmup,
- get_polynomial_decay_schedule_with_warmup,
- get_scheduler,
-)
-from .pipeline_utils import DiffusionPipeline
-from .pipelines import DDIMPipeline, DDPMPipeline, KarrasVePipeline, LDMPipeline, PNDMPipeline, ScoreSdeVePipeline
-from .schedulers import (
- DDIMScheduler,
- DDPMScheduler,
- KarrasVeScheduler,
- PNDMScheduler,
- SchedulerMixin,
- ScoreSdeVeScheduler,
-)
-from .utils import logging
-
-
-if is_scipy_available():
- from .schedulers import LMSDiscreteScheduler
-else:
- from .utils.dummy_scipy_objects import * # noqa F403
-
-from .training_utils import EMAModel
-
-
-if is_transformers_available():
- from .pipelines import (
- LDMTextToImagePipeline,
- StableDiffusionImg2ImgPipeline,
- StableDiffusionInpaintPipeline,
- StableDiffusionPipeline,
- )
-else:
- from .utils.dummy_transformers_objects import * # noqa F403
-
-
-if is_transformers_available() and is_onnx_available():
- from .pipelines import StableDiffusionOnnxPipeline
-else:
- from .utils.dummy_transformers_and_onnx_objects import * # noqa F403
diff --git a/spaces/Samuelcr8/Chatbot/app.py b/spaces/Samuelcr8/Chatbot/app.py
deleted file mode 100644
index 4205e03f91904065e1610f7e6c7b2f1de1771184..0000000000000000000000000000000000000000
--- a/spaces/Samuelcr8/Chatbot/app.py
+++ /dev/null
@@ -1,3 +0,0 @@
-import gradio as gr
-
-gr.Interface.load("models/gpt2").launch()
\ No newline at end of file
diff --git a/spaces/SarmadBashir/REFSQ2023_ReqORNot_demo_app/app.py b/spaces/SarmadBashir/REFSQ2023_ReqORNot_demo_app/app.py
deleted file mode 100644
index 5a4ddd8399a42ea8b05b0daa4e769f0f676aa61b..0000000000000000000000000000000000000000
--- a/spaces/SarmadBashir/REFSQ2023_ReqORNot_demo_app/app.py
+++ /dev/null
@@ -1,162 +0,0 @@
-import streamlit as st
-import pandas as pd
-from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
-from annotated_text import annotated_text
-
-st.set_page_config(
- page_title="Requirement Identifier", layout="wide"
- #page_icon="🎈",
-)
-
-st.cache_resource
-def get_pipleine():
- tokenizer = AutoTokenizer.from_pretrained("SarmadBashir/dronology_bert_uncased", model_max_length = 128)
- model = AutoModelForSequenceClassification.from_pretrained("SarmadBashir/dronology_bert_uncased")
- pipe = pipeline("text-classification", model=model, tokenizer=tokenizer)
- return pipe
-
-pipe = get_pipleine()
-
-def get_prediction(input_text, pipe):
-
- map_labels = {'LABEL_0': 'Information', 'LABEL_1': 'Requirement'}
- output = pipe(input_text)
-
- label = map_labels.get(output[0]['label'])
- score = int(round(output[0]['score'], 2) * 100)
-
- return label, score
-
-
-def _max_width_():
- max_width_str = f"max-width: 1400px;"
- st.markdown(
- f"""
-
- """,
- unsafe_allow_html=True,
- )
-
-#_max_width_()
-
-def show_updated_list(test_data):
-
- show_list = []
- text = test_data['STR.REQ'].tolist()
- labels = test_data['class'].tolist()
-
- for info in zip(text, labels):
-
- if info[1] == 0:
- updated_text = info[0] + ' (GT: Information)'
- else:
- updated_text = info[0] + ' (GT: Requirement)'
-
- show_list.append(updated_text)
-
- return show_list
-
-c30, c31, c32 = st.columns([6, 1, 3])
-
-with c30:
- # st.image("logo.png", width=400)
- st.title("Requirement or not, that is the question!")
- #st.header("")
-
-with st.expander("ℹ️ - About this app", expanded=True):
-
- st.write(
- """
-- This app is a working demo for the paper: "Requirement or not, that is the question: A case from the railway industry".
-- The app relies on BERT model (trained on dronology dataset) for classification of given text as Requirement or Information.
-- The replication package [ReqORNot](https://github.com/a66as/REFSQ2023-ReqORNot) contains all the relevant code and information for replication of experiements.
- """
- )
- st.write("""
-- This work is partially funded by [AIDOaRt (KDT)](https://sites.mdu.se/aidoart) and [SmartDelta (ITEA)](https://itea4.org/project/smartdelta.html) projects.
-
- """)
- images= ['./pictures/smart_delta.jpeg', './pictures/aidoart.jpeg' ]
- #st.image(images, caption=None, width=130, use_column_width=False, clamp=False, channels="RGB", output_format="auto")
- #st.image('./pictures/smart_delta.jpeg', caption=None, width=130, use_column_width=None, clamp=False, channels="RGB", output_format="auto")
-
- col1,col2 = st.columns([0.7,7])
-
- with col1:
- st.image(images[0],width=100,use_column_width='never')
- with col2:
- st.image(images[1],width=100,use_column_width='never')
-
- st.markdown("")
-st.markdown("")
-st.markdown("")
-st.markdown("")
-
-with st.form(key="my_form"):
-
- ce, c1, c2, ce = st.columns([0.04, 0.01, 1, 0.04])
-
- with c2:
- doc = st.text_area(
- "✍️Write the text below",
- height=50,
- )
- st.write("***OR***")
-
- test_data = pd.read_csv('./data/test.csv')
- #test_data = test_data.sample(frac=1)
- text = show_updated_list(test_data)
- text.insert(0, '-')
-
- option = st.selectbox(
- 'Select the row from test data',
- text)
-
- #print(option)
-
- st.markdown("")
-
- submit_button = st.form_submit_button(label="✨ Get the Prediction!")
-
-if not submit_button:
- st.stop()
-
-if option == '-' and len(doc.split()) <= 2:
- st.warning('Please Provide Valid Input!')
- st.stop()
-
-st.markdown("")
-st.markdown("")
-
-st.markdown("### **Output**")
-
-if option != '-' and len(doc.split())<=3:
-
- option_text = ''
- if '(GT: Requirement)' in option:
- option_text = option.replace('(GT: Requirement)', '').strip()
- else:
- option_text = option.replace('(GT: Information)', '').strip()
-
- predicted_label, probability = get_prediction(option_text, pipe)
- annotated_text(
- 'The model classified',
- ('selected', "", "#8ef"), 'text as: ',
- (predicted_label,"", "#afa"),'with a probability of',
- (str(probability),"", "#afa"),'%'
-
- )
-
-else:
- predicted_label, probability = get_prediction(doc, pipe)
- annotated_text(
- 'The model classified',
- ('written', "", "#8ef"), 'text as: ',
- (predicted_label,"", "#afa"),'with a probability of',
- (str(probability),"", "#afa"),'%'
-
- )
\ No newline at end of file
diff --git a/spaces/Silentlin/DiffSinger/vocoders/pwg.py b/spaces/Silentlin/DiffSinger/vocoders/pwg.py
deleted file mode 100644
index ca9b6891ab2ba5cb413eeca97a41534e5db129d5..0000000000000000000000000000000000000000
--- a/spaces/Silentlin/DiffSinger/vocoders/pwg.py
+++ /dev/null
@@ -1,137 +0,0 @@
-import glob
-import re
-import librosa
-import torch
-import yaml
-from sklearn.preprocessing import StandardScaler
-from torch import nn
-from modules.parallel_wavegan.models import ParallelWaveGANGenerator
-from modules.parallel_wavegan.utils import read_hdf5
-from utils.hparams import hparams
-from utils.pitch_utils import f0_to_coarse
-from vocoders.base_vocoder import BaseVocoder, register_vocoder
-import numpy as np
-
-
-def load_pwg_model(config_path, checkpoint_path, stats_path):
- # load config
- with open(config_path) as f:
- config = yaml.load(f, Loader=yaml.Loader)
-
- # setup
- if torch.cuda.is_available():
- device = torch.device("cuda")
- else:
- device = torch.device("cpu")
- model = ParallelWaveGANGenerator(**config["generator_params"])
-
- ckpt_dict = torch.load(checkpoint_path, map_location="cpu")
- if 'state_dict' not in ckpt_dict: # official vocoder
- model.load_state_dict(torch.load(checkpoint_path, map_location="cpu")["model"]["generator"])
- scaler = StandardScaler()
- if config["format"] == "hdf5":
- scaler.mean_ = read_hdf5(stats_path, "mean")
- scaler.scale_ = read_hdf5(stats_path, "scale")
- elif config["format"] == "npy":
- scaler.mean_ = np.load(stats_path)[0]
- scaler.scale_ = np.load(stats_path)[1]
- else:
- raise ValueError("support only hdf5 or npy format.")
- else: # custom PWG vocoder
- fake_task = nn.Module()
- fake_task.model_gen = model
- fake_task.load_state_dict(torch.load(checkpoint_path, map_location="cpu")["state_dict"], strict=False)
- scaler = None
-
- model.remove_weight_norm()
- model = model.eval().to(device)
- print(f"| Loaded model parameters from {checkpoint_path}.")
- print(f"| PWG device: {device}.")
- return model, scaler, config, device
-
-
-@register_vocoder
-class PWG(BaseVocoder):
- def __init__(self):
- if hparams['vocoder_ckpt'] == '': # load LJSpeech PWG pretrained model
- base_dir = 'wavegan_pretrained'
- ckpts = glob.glob(f'{base_dir}/checkpoint-*steps.pkl')
- ckpt = sorted(ckpts, key=
- lambda x: int(re.findall(f'{base_dir}/checkpoint-(\d+)steps.pkl', x)[0]))[-1]
- config_path = f'{base_dir}/config.yaml'
- print('| load PWG: ', ckpt)
- self.model, self.scaler, self.config, self.device = load_pwg_model(
- config_path=config_path,
- checkpoint_path=ckpt,
- stats_path=f'{base_dir}/stats.h5',
- )
- else:
- base_dir = hparams['vocoder_ckpt']
- print(base_dir)
- config_path = f'{base_dir}/config.yaml'
- ckpt = sorted(glob.glob(f'{base_dir}/model_ckpt_steps_*.ckpt'), key=
- lambda x: int(re.findall(f'{base_dir}/model_ckpt_steps_(\d+).ckpt', x)[0]))[-1]
- print('| load PWG: ', ckpt)
- self.scaler = None
- self.model, _, self.config, self.device = load_pwg_model(
- config_path=config_path,
- checkpoint_path=ckpt,
- stats_path=f'{base_dir}/stats.h5',
- )
-
- def spec2wav(self, mel, **kwargs):
- # start generation
- config = self.config
- device = self.device
- pad_size = (config["generator_params"]["aux_context_window"],
- config["generator_params"]["aux_context_window"])
- c = mel
- if self.scaler is not None:
- c = self.scaler.transform(c)
-
- with torch.no_grad():
- z = torch.randn(1, 1, c.shape[0] * config["hop_size"]).to(device)
- c = np.pad(c, (pad_size, (0, 0)), "edge")
- c = torch.FloatTensor(c).unsqueeze(0).transpose(2, 1).to(device)
- p = kwargs.get('f0')
- if p is not None:
- p = f0_to_coarse(p)
- p = np.pad(p, (pad_size,), "edge")
- p = torch.LongTensor(p[None, :]).to(device)
- y = self.model(z, c, p).view(-1)
- wav_out = y.cpu().numpy()
- return wav_out
-
- @staticmethod
- def wav2spec(wav_fn, return_linear=False):
- from data_gen.tts.data_gen_utils import process_utterance
- res = process_utterance(
- wav_fn, fft_size=hparams['fft_size'],
- hop_size=hparams['hop_size'],
- win_length=hparams['win_size'],
- num_mels=hparams['audio_num_mel_bins'],
- fmin=hparams['fmin'],
- fmax=hparams['fmax'],
- sample_rate=hparams['audio_sample_rate'],
- loud_norm=hparams['loud_norm'],
- min_level_db=hparams['min_level_db'],
- return_linear=return_linear, vocoder='pwg', eps=float(hparams.get('wav2spec_eps', 1e-10)))
- if return_linear:
- return res[0], res[1].T, res[2].T # [T, 80], [T, n_fft]
- else:
- return res[0], res[1].T
-
- @staticmethod
- def wav2mfcc(wav_fn):
- fft_size = hparams['fft_size']
- hop_size = hparams['hop_size']
- win_length = hparams['win_size']
- sample_rate = hparams['audio_sample_rate']
- wav, _ = librosa.core.load(wav_fn, sr=sample_rate)
- mfcc = librosa.feature.mfcc(y=wav, sr=sample_rate, n_mfcc=13,
- n_fft=fft_size, hop_length=hop_size,
- win_length=win_length, pad_mode="constant", power=1.0)
- mfcc_delta = librosa.feature.delta(mfcc, order=1)
- mfcc_delta_delta = librosa.feature.delta(mfcc, order=2)
- mfcc = np.concatenate([mfcc, mfcc_delta, mfcc_delta_delta]).T
- return mfcc
diff --git a/spaces/SkyYeXianer/vits-uma-genshin-honkai/commons.py b/spaces/SkyYeXianer/vits-uma-genshin-honkai/commons.py
deleted file mode 100644
index 40fcc05364d4815971f5c6f9dbb8dcef8e3ec1e9..0000000000000000000000000000000000000000
--- a/spaces/SkyYeXianer/vits-uma-genshin-honkai/commons.py
+++ /dev/null
@@ -1,172 +0,0 @@
-import math
-import torch
-from torch.nn import functional as F
-import torch.jit
-
-
-def script_method(fn, _rcb=None):
- return fn
-
-
-def script(obj, optimize=True, _frames_up=0, _rcb=None):
- return obj
-
-
-torch.jit.script_method = script_method
-torch.jit.script = script
-
-
-def init_weights(m, mean=0.0, std=0.01):
- classname = m.__class__.__name__
- if classname.find("Conv") != -1:
- m.weight.data.normal_(mean, std)
-
-
-def get_padding(kernel_size, dilation=1):
- return int((kernel_size*dilation - dilation)/2)
-
-
-def convert_pad_shape(pad_shape):
- l = pad_shape[::-1]
- pad_shape = [item for sublist in l for item in sublist]
- return pad_shape
-
-
-def intersperse(lst, item):
- result = [item] * (len(lst) * 2 + 1)
- result[1::2] = lst
- return result
-
-
-def kl_divergence(m_p, logs_p, m_q, logs_q):
- """KL(P||Q)"""
- kl = (logs_q - logs_p) - 0.5
- kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q)
- return kl
-
-
-def rand_gumbel(shape):
- """Sample from the Gumbel distribution, protect from overflows."""
- uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
- return -torch.log(-torch.log(uniform_samples))
-
-
-def rand_gumbel_like(x):
- g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
- return g
-
-
-def slice_segments(x, ids_str, segment_size=4):
- ret = torch.zeros_like(x[:, :, :segment_size])
- for i in range(x.size(0)):
- idx_str = ids_str[i]
- idx_end = idx_str + segment_size
- ret[i] = x[i, :, idx_str:idx_end]
- return ret
-
-
-def rand_slice_segments(x, x_lengths=None, segment_size=4):
- b, d, t = x.size()
- if x_lengths is None:
- x_lengths = t
- ids_str_max = x_lengths - segment_size + 1
- ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
- ret = slice_segments(x, ids_str, segment_size)
- return ret, ids_str
-
-
-def get_timing_signal_1d(
- length, channels, min_timescale=1.0, max_timescale=1.0e4):
- position = torch.arange(length, dtype=torch.float)
- num_timescales = channels // 2
- log_timescale_increment = (
- math.log(float(max_timescale) / float(min_timescale)) /
- (num_timescales - 1))
- inv_timescales = min_timescale * torch.exp(
- torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment)
- scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
- signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
- signal = F.pad(signal, [0, 0, 0, channels % 2])
- signal = signal.view(1, channels, length)
- return signal
-
-
-def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
- b, channels, length = x.size()
- signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
- return x + signal.to(dtype=x.dtype, device=x.device)
-
-
-def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
- b, channels, length = x.size()
- signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
- return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
-
-
-def subsequent_mask(length):
- mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
- return mask
-
-
-@torch.jit.script
-def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
- n_channels_int = n_channels[0]
- in_act = input_a + input_b
- t_act = torch.tanh(in_act[:, :n_channels_int, :])
- s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
- acts = t_act * s_act
- return acts
-
-
-def convert_pad_shape(pad_shape):
- l = pad_shape[::-1]
- pad_shape = [item for sublist in l for item in sublist]
- return pad_shape
-
-
-def shift_1d(x):
- x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
- return x
-
-
-def sequence_mask(length, max_length=None):
- if max_length is None:
- max_length = length.max()
- x = torch.arange(max_length, dtype=length.dtype, device=length.device)
- return x.unsqueeze(0) < length.unsqueeze(1)
-
-
-def generate_path(duration, mask):
- """
- duration: [b, 1, t_x]
- mask: [b, 1, t_y, t_x]
- """
- device = duration.device
-
- b, _, t_y, t_x = mask.shape
- cum_duration = torch.cumsum(duration, -1)
-
- cum_duration_flat = cum_duration.view(b * t_x)
- path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
- path = path.view(b, t_x, t_y)
- path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
- path = path.unsqueeze(1).transpose(2,3) * mask
- return path
-
-
-def clip_grad_value_(parameters, clip_value, norm_type=2):
- if isinstance(parameters, torch.Tensor):
- parameters = [parameters]
- parameters = list(filter(lambda p: p.grad is not None, parameters))
- norm_type = float(norm_type)
- if clip_value is not None:
- clip_value = float(clip_value)
-
- total_norm = 0
- for p in parameters:
- param_norm = p.grad.data.norm(norm_type)
- total_norm += param_norm.item() ** norm_type
- if clip_value is not None:
- p.grad.data.clamp_(min=-clip_value, max=clip_value)
- total_norm = total_norm ** (1. / norm_type)
- return total_norm
diff --git a/spaces/Superlang/ImageProcessor/annotator/oneformer/detectron2/modeling/postprocessing.py b/spaces/Superlang/ImageProcessor/annotator/oneformer/detectron2/modeling/postprocessing.py
deleted file mode 100644
index 82bbad25cdc5afbde9a3af47174c97ed473cd5f0..0000000000000000000000000000000000000000
--- a/spaces/Superlang/ImageProcessor/annotator/oneformer/detectron2/modeling/postprocessing.py
+++ /dev/null
@@ -1,100 +0,0 @@
-# Copyright (c) Facebook, Inc. and its affiliates.
-import torch
-from torch.nn import functional as F
-
-from annotator.oneformer.detectron2.structures import Instances, ROIMasks
-
-
-# perhaps should rename to "resize_instance"
-def detector_postprocess(
- results: Instances, output_height: int, output_width: int, mask_threshold: float = 0.5
-):
- """
- Resize the output instances.
- The input images are often resized when entering an object detector.
- As a result, we often need the outputs of the detector in a different
- resolution from its inputs.
-
- This function will resize the raw outputs of an R-CNN detector
- to produce outputs according to the desired output resolution.
-
- Args:
- results (Instances): the raw outputs from the detector.
- `results.image_size` contains the input image resolution the detector sees.
- This object might be modified in-place.
- output_height, output_width: the desired output resolution.
- Returns:
- Instances: the resized output from the model, based on the output resolution
- """
- if isinstance(output_width, torch.Tensor):
- # This shape might (but not necessarily) be tensors during tracing.
- # Converts integer tensors to float temporaries to ensure true
- # division is performed when computing scale_x and scale_y.
- output_width_tmp = output_width.float()
- output_height_tmp = output_height.float()
- new_size = torch.stack([output_height, output_width])
- else:
- new_size = (output_height, output_width)
- output_width_tmp = output_width
- output_height_tmp = output_height
-
- scale_x, scale_y = (
- output_width_tmp / results.image_size[1],
- output_height_tmp / results.image_size[0],
- )
- results = Instances(new_size, **results.get_fields())
-
- if results.has("pred_boxes"):
- output_boxes = results.pred_boxes
- elif results.has("proposal_boxes"):
- output_boxes = results.proposal_boxes
- else:
- output_boxes = None
- assert output_boxes is not None, "Predictions must contain boxes!"
-
- output_boxes.scale(scale_x, scale_y)
- output_boxes.clip(results.image_size)
-
- results = results[output_boxes.nonempty()]
-
- if results.has("pred_masks"):
- if isinstance(results.pred_masks, ROIMasks):
- roi_masks = results.pred_masks
- else:
- # pred_masks is a tensor of shape (N, 1, M, M)
- roi_masks = ROIMasks(results.pred_masks[:, 0, :, :])
- results.pred_masks = roi_masks.to_bitmasks(
- results.pred_boxes, output_height, output_width, mask_threshold
- ).tensor # TODO return ROIMasks/BitMask object in the future
-
- if results.has("pred_keypoints"):
- results.pred_keypoints[:, :, 0] *= scale_x
- results.pred_keypoints[:, :, 1] *= scale_y
-
- return results
-
-
-def sem_seg_postprocess(result, img_size, output_height, output_width):
- """
- Return semantic segmentation predictions in the original resolution.
-
- The input images are often resized when entering semantic segmentor. Moreover, in same
- cases, they also padded inside segmentor to be divisible by maximum network stride.
- As a result, we often need the predictions of the segmentor in a different
- resolution from its inputs.
-
- Args:
- result (Tensor): semantic segmentation prediction logits. A tensor of shape (C, H, W),
- where C is the number of classes, and H, W are the height and width of the prediction.
- img_size (tuple): image size that segmentor is taking as input.
- output_height, output_width: the desired output resolution.
-
- Returns:
- semantic segmentation prediction (Tensor): A tensor of the shape
- (C, output_height, output_width) that contains per-pixel soft predictions.
- """
- result = result[:, : img_size[0], : img_size[1]].expand(1, -1, -1, -1)
- result = F.interpolate(
- result, size=(output_height, output_width), mode="bilinear", align_corners=False
- )[0]
- return result
diff --git a/spaces/TEnngal/bingo/src/components/settings.tsx b/spaces/TEnngal/bingo/src/components/settings.tsx
deleted file mode 100644
index 80b8a2d3b252b875f5b6f7dfc2f6e3ad9cdfb22a..0000000000000000000000000000000000000000
--- a/spaces/TEnngal/bingo/src/components/settings.tsx
+++ /dev/null
@@ -1,157 +0,0 @@
-import { useEffect, useState } from 'react'
-import { useAtom } from 'jotai'
-import { Switch } from '@headlessui/react'
-import { toast } from 'react-hot-toast'
-import { hashAtom, voiceAtom } from '@/state'
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle
-} from '@/components/ui/dialog'
-import { Button } from './ui/button'
-import { Input } from './ui/input'
-import { ChunkKeys, parseCookies, extraCurlFromCookie, encodeHeadersToCookie, getCookie, setCookie } from '@/lib/utils'
-import { ExternalLink } from './external-link'
-import { useCopyToClipboard } from '@/lib/hooks/use-copy-to-clipboard'
-
-
-export function Settings() {
- const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 2000 })
- const [loc, setLoc] = useAtom(hashAtom)
- const [curlValue, setCurlValue] = useState(extraCurlFromCookie(parseCookies(document.cookie, ChunkKeys)))
- const [imageOnly, setImageOnly] = useState(getCookie('IMAGE_ONLY') !== '0')
- const [enableTTS, setEnableTTS] = useAtom(voiceAtom)
-
- useEffect(() => {
- if (isCopied) {
- toast.success('复制成功')
- }
- }, [isCopied])
-
- if (loc === 'settings') {
- return (
-
- )
- } else if (loc === 'voice') {
- return (
-
- )
- }
- return null
-}
diff --git a/spaces/TakaMETaka/openai-reverse-proxy/server.js b/spaces/TakaMETaka/openai-reverse-proxy/server.js
deleted file mode 100644
index 04a48b7a429c4d0ad0b772ba1edf503e349eda21..0000000000000000000000000000000000000000
--- a/spaces/TakaMETaka/openai-reverse-proxy/server.js
+++ /dev/null
@@ -1,32 +0,0 @@
-const express = require('express');
-const proxy = require('express-http-proxy');
-const app = express();
-const targetUrl = 'https://api.openai.com';
-const openaiKey = process.env.OPENAI_KEY
-const port = 7860;
-const baseUrl = getExternalUrl(process.env.SPACE_ID);
-
-app.use('/api', proxy(targetUrl, {
- proxyReqOptDecorator: (proxyReqOpts, srcReq) => {
- // Modify the request headers if necessary
- proxyReqOpts.headers['Authorization'] = 'Bearer '+openaiKey;
- return proxyReqOpts;
- },
-}));
-
-app.get("/", (req, res) => {
- res.send(`This is your OpenAI Reverse Proxy URL: ${baseUrl}`);
-});
-
-function getExternalUrl(spaceId) {
- try {
- const [username, spacename] = spaceId.split("/");
- return `https://${username}-${spacename.replace(/_/g, "-")}.hf.space/api/v1`;
- } catch (e) {
- return "";
- }
-}
-
-app.listen(port, () => {
- console.log(`Reverse proxy server running on ${baseUrl}`);
-});
\ No newline at end of file
diff --git a/spaces/TopdeckingLands/Diffusion_Space/README.md b/spaces/TopdeckingLands/Diffusion_Space/README.md
deleted file mode 100644
index 20f32105d32a4c3b325efbae87082f355cec1acc..0000000000000000000000000000000000000000
--- a/spaces/TopdeckingLands/Diffusion_Space/README.md
+++ /dev/null
@@ -1,14 +0,0 @@
----
-title: Finetuned Diffusion
-emoji: 🪄🖼️
-colorFrom: red
-colorTo: pink
-sdk: gradio
-sdk_version: 3.6
-app_file: app.py
-pinned: true
-license: mit
-duplicated_from: Evel/Evel_Space
----
-
-Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
diff --git a/spaces/VincentZB/Stable-Diffusion-ControlNet-WebUI/diffusion_webui/diffusion_models/controlnet/controlnet_depth.py b/spaces/VincentZB/Stable-Diffusion-ControlNet-WebUI/diffusion_webui/diffusion_models/controlnet/controlnet_depth.py
deleted file mode 100644
index d35cef0346b3b519addf4837a753d215b73f0ebd..0000000000000000000000000000000000000000
--- a/spaces/VincentZB/Stable-Diffusion-ControlNet-WebUI/diffusion_webui/diffusion_models/controlnet/controlnet_depth.py
+++ /dev/null
@@ -1,187 +0,0 @@
-import gradio as gr
-import numpy as np
-import torch
-from diffusers import ControlNetModel, StableDiffusionControlNetPipeline
-from PIL import Image
-from transformers import pipeline
-
-from diffusion_webui.utils.model_list import (
- controlnet_depth_model_list,
- stable_model_list,
-)
-from diffusion_webui.utils.scheduler_list import (
- SCHEDULER_LIST,
- get_scheduler_list,
-)
-
-
-class StableDiffusionControlNetDepthGenerator:
- def __init__(self):
- self.pipe = None
-
- def load_model(self, stable_model_path, controlnet_model_path, scheduler):
- if self.pipe is None:
- controlnet = ControlNetModel.from_pretrained(
- controlnet_model_path, torch_dtype=torch.float16
- )
-
- self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
- pretrained_model_name_or_path=stable_model_path,
- controlnet=controlnet,
- safety_checker=None,
- torch_dtype=torch.float16,
- )
-
- self.pipe = get_scheduler_list(pipe=self.pipe, scheduler=scheduler)
- self.pipe.to("cuda")
- self.pipe.enable_xformers_memory_efficient_attention()
-
- return self.pipe
-
- def controlnet_depth(self, image_path: str):
- depth_estimator = pipeline("depth-estimation")
- image = Image.open(image_path)
- image = depth_estimator(image)["depth"]
- image = np.array(image)
- image = image[:, :, None]
- image = np.concatenate([image, image, image], axis=2)
- image = Image.fromarray(image)
-
- return image
-
- def generate_image(
- self,
- image_path: str,
- stable_model_path: str,
- depth_model_path: str,
- prompt: str,
- negative_prompt: str,
- num_images_per_prompt: int,
- guidance_scale: int,
- num_inference_step: int,
- scheduler: str,
- seed_generator: int,
- ):
- image = self.controlnet_depth(image_path)
-
- pipe = self.load_model(
- stable_model_path=stable_model_path,
- controlnet_model_path=depth_model_path,
- scheduler=scheduler,
- )
-
- if seed_generator == 0:
- random_seed = torch.randint(0, 1000000, (1,))
- generator = torch.manual_seed(random_seed)
- else:
- generator = torch.manual_seed(seed_generator)
-
- output = pipe(
- prompt=prompt,
- image=image,
- negative_prompt=negative_prompt,
- num_images_per_prompt=num_images_per_prompt,
- num_inference_steps=num_inference_step,
- guidance_scale=guidance_scale,
- generator=generator,
- ).images
-
- return output
-
- def app():
- with gr.Blocks():
- with gr.Row():
- with gr.Column():
- controlnet_depth_image_file = gr.Image(
- type="filepath", label="Image"
- )
-
- controlnet_depth_prompt = gr.Textbox(
- lines=1,
- show_label=False,
- placeholder="Prompt",
- )
-
- controlnet_depth_negative_prompt = gr.Textbox(
- lines=1,
- show_label=False,
- placeholder="Negative Prompt",
- )
-
- with gr.Row():
- with gr.Column():
- controlnet_depth_stable_model_id = gr.Dropdown(
- choices=stable_model_list,
- value=stable_model_list[0],
- label="Stable Model Id",
- )
- controlnet_depth_guidance_scale = gr.Slider(
- minimum=0.1,
- maximum=15,
- step=0.1,
- value=7.5,
- label="Guidance Scale",
- )
-
- controlnet_depth_num_inference_step = gr.Slider(
- minimum=1,
- maximum=100,
- step=1,
- value=50,
- label="Num Inference Step",
- )
-
- controlnet_depth_num_images_per_prompt = gr.Slider(
- minimum=1,
- maximum=10,
- step=1,
- value=1,
- label="Number Of Images",
- )
- with gr.Row():
- with gr.Column():
- controlnet_depth_model_id = gr.Dropdown(
- choices=controlnet_depth_model_list,
- value=controlnet_depth_model_list[0],
- label="ControlNet Model Id",
- )
-
- controlnet_depth_scheduler = gr.Dropdown(
- choices=SCHEDULER_LIST,
- value=SCHEDULER_LIST[0],
- label="Scheduler",
- )
-
- controlnet_depth_seed_generator = gr.Number(
- minimum=0,
- maximum=1000000,
- step=1,
- value=0,
- label="Seed Generator",
- )
-
- controlnet_depth_predict = gr.Button(value="Generator")
-
- with gr.Column():
- output_image = gr.Gallery(
- label="Generated images",
- show_label=False,
- elem_id="gallery",
- ).style(grid=(1, 2))
-
- controlnet_depth_predict.click(
- fn=StableDiffusionControlNetDepthGenerator().generate_image,
- inputs=[
- controlnet_depth_image_file,
- controlnet_depth_stable_model_id,
- controlnet_depth_model_id,
- controlnet_depth_prompt,
- controlnet_depth_negative_prompt,
- controlnet_depth_num_images_per_prompt,
- controlnet_depth_guidance_scale,
- controlnet_depth_num_inference_step,
- controlnet_depth_scheduler,
- controlnet_depth_seed_generator,
- ],
- outputs=output_image,
- )
diff --git a/spaces/Vincentim27/Plant_Nutrition_Prediction_ARIA/eda.py b/spaces/Vincentim27/Plant_Nutrition_Prediction_ARIA/eda.py
deleted file mode 100644
index 5ce01670e48b6e78e0223654b768c6e915e06d16..0000000000000000000000000000000000000000
--- a/spaces/Vincentim27/Plant_Nutrition_Prediction_ARIA/eda.py
+++ /dev/null
@@ -1,67 +0,0 @@
-import streamlit as st
-import numpy as np
-import pandas as pd
-import seaborn as sns
-import matplotlib.pyplot as plt
-import plotly.express as px
-from PIL import Image
-
-
-# Load data dengan pandas dan assign ke variabel df
-df = pd.read_excel('aria_data.xlsx')
-
-def run() :
- # Membuat Title
- st.markdown("
Exploratory Data Analysis
", unsafe_allow_html=True)
- st.write('Berikut adalah EDA dari setiap feature')
-
- # Membuat Sub Header
- st.subheader('**Distribution Plot**')
- pilihan = st.selectbox('**Silahkan pilih column :** ',('v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8', 'target'))
- fig = plt.figure(figsize=(20,10))
- sns.histplot(df[pilihan],bins=30,kde=True)
- title = 'Distribution Plot ' + pilihan
- plt.title(title, fontsize=20)
- plt.xlabel(pilihan, fontsize=14)
- plt.ylabel('Counts', fontsize=14)
- st.pyplot(fig)
-
- # Membuat Sub Header
- st.subheader('**Heatmap Correlation**')
- st.write('Berikut Heatmap Correlation antar feature')
- fig = plt.figure(figsize=(15,10))
- sns.heatmap(df.corr(), annot = True, color = 'blue', cmap = 'crest')
- st.pyplot(fig)
-
- # Membuat Sub Header
- st.subheader('**Distribusi Sample Type**')
- st.write('Berikut visualisasi distribusi sample type dengan barchart dan piechart (persentase)')
- # Visualisasi
- fig, ax =plt.subplots(1,2,figsize=(15,6))
- sns.countplot(x='sample_type', data=df, palette="winter", ax=ax[0])
- ax[0].set_xlabel("Lab", fontsize= 12)
- ax[0].set_ylabel("# of Tested Plant", fontsize= 12)
- fig.suptitle('Count of Tested Plant in each Lab', fontsize=18, fontweight='bold')
- ax[0].set_ylim(0,110)
-
- ax[0].set_xticks([0,1], ['Lab 1', 'Lab 2'], fontsize = 11)
- for p in ax[0].patches:
- ax[0].annotate("%.0f"%(p.get_height()), (p.get_x() + p.get_width() / 2,
- p.get_height()+2), ha='center', va='center',fontsize = 11)
- df['sample_type'].value_counts().plot(kind='pie', labels = ['Lab 1','Lab 2'],autopct='%1.1f%%',explode = [0,0.05] ,colors = ['indigo','salmon'],textprops = {"fontsize":12})
- ax[1].set_ylabel("% of Tested Plant", fontsize= 12)
- st.pyplot(fig)
-
- # Membuat Sub Header
- st.subheader('**Distribusi Sample Type berdasarkan target**')
- st.write('Dari visualisasi dibawah dapat disimpulkan bahwa :')
- st.markdown('- Lab 1 sering menguji tanaman dengan tingkat nutrisi 4.6 - 4.85')
- st.markdown('- Lab 2 sering menguji tanaman dengan tingkat nutrisi 4.5 - 5')
- # Visualisasi
- fig = plt.figure(figsize=(15,8))
- sns.boxenplot(y=df['target'], x= df['sample_type'], palette = 'Blues')
- plt.title('Sample Type vs Target', fontsize = 15)
- st.pyplot(fig)
-
-if __name__ == '__main__':
- run()
\ No newline at end of file
diff --git a/spaces/Virus561/sdf/app.py b/spaces/Virus561/sdf/app.py
deleted file mode 100644
index cab892405d7154a2718bf5593f3870e4638ab731..0000000000000000000000000000000000000000
--- a/spaces/Virus561/sdf/app.py
+++ /dev/null
@@ -1,34 +0,0 @@
-import gradio as gr
-import shutil
-import subprocess
-# Функция, которая будет вызываться при отправке данных
-def save_file(input_file):
- # Получаем путь к временному файлу
- temp_file_path = input_file.name
-
- # Указываем путь для сохранения файла
- saved_file_path = "audio/saved_file.wav"
-
- # Копируем временный файл в место сохранения
- shutil.copy(temp_file_path, saved_file_path)
- cmd = ["svc", "infer", f"/content/{saved_file_path}", "-m", "/content/models", "-c", "/content/models/config.json"]
- result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
- print("STDOUT:", result.stdout)
- print("STDERR:", result.stderr)
- # Получаем байтовый код финального файла
- with open(saved_file_path, "rb") as f:
- final_file_bytes = f.read()
-
- return final_file_bytes
-
-# Создание интерфейса Gradio с кнопкой "Submit"
-iface = gr.Interface(
- fn=save_file,
- inputs="file", # Тип ввода - файл
- outputs="text", # Тип вывода - текстовая строка
- live=False, # Отключаем режим реального времени
- capture_session=True # Захватывать сессию для удаленного доступа
-)
-
-# Добавляем кнопку "Submit"
-iface.launch(share=True)
\ No newline at end of file
diff --git a/spaces/Vision-CAIR/minigpt4/minigpt4/models/base_model.py b/spaces/Vision-CAIR/minigpt4/minigpt4/models/base_model.py
deleted file mode 100644
index dbfaf8e989d509bef7c4f06ac6d3de2b085e5d38..0000000000000000000000000000000000000000
--- a/spaces/Vision-CAIR/minigpt4/minigpt4/models/base_model.py
+++ /dev/null
@@ -1,247 +0,0 @@
-"""
- Copyright (c) 2022, salesforce.com, inc.
- All rights reserved.
- SPDX-License-Identifier: BSD-3-Clause
- For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
-"""
-
-import logging
-import os
-
-import numpy as np
-import torch
-import torch.nn as nn
-from minigpt4.common.dist_utils import download_cached_file, is_dist_avail_and_initialized
-from minigpt4.common.utils import get_abs_path, is_url
-from omegaconf import OmegaConf
-
-
-class BaseModel(nn.Module):
- """Base class for models."""
-
- def __init__(self):
- super().__init__()
-
- @property
- def device(self):
- return list(self.parameters())[0].device
-
- def load_checkpoint(self, url_or_filename):
- """
- Load from a finetuned checkpoint.
-
- This should expect no mismatch in the model keys and the checkpoint keys.
- """
-
- if is_url(url_or_filename):
- cached_file = download_cached_file(
- url_or_filename, check_hash=False, progress=True
- )
- checkpoint = torch.load(cached_file, map_location="cpu")
- elif os.path.isfile(url_or_filename):
- checkpoint = torch.load(url_or_filename, map_location="cpu")
- else:
- raise RuntimeError("checkpoint url or path is invalid")
-
- if "model" in checkpoint.keys():
- state_dict = checkpoint["model"]
- else:
- state_dict = checkpoint
-
- msg = self.load_state_dict(state_dict, strict=False)
-
- logging.info("Missing keys {}".format(msg.missing_keys))
- logging.info("load checkpoint from %s" % url_or_filename)
-
- return msg
-
- @classmethod
- def from_pretrained(cls, model_type):
- """
- Build a pretrained model from default configuration file, specified by model_type.
-
- Args:
- - model_type (str): model type, specifying architecture and checkpoints.
-
- Returns:
- - model (nn.Module): pretrained or finetuned model, depending on the configuration.
- """
- model_cfg = OmegaConf.load(cls.default_config_path(model_type)).model
- model = cls.from_config(model_cfg)
-
- return model
-
- @classmethod
- def default_config_path(cls, model_type):
- assert (
- model_type in cls.PRETRAINED_MODEL_CONFIG_DICT
- ), "Unknown model type {}".format(model_type)
- return get_abs_path(cls.PRETRAINED_MODEL_CONFIG_DICT[model_type])
-
- def load_checkpoint_from_config(self, cfg, **kwargs):
- """
- Load checkpoint as specified in the config file.
-
- If load_finetuned is True, load the finetuned model; otherwise, load the pretrained model.
- When loading the pretrained model, each task-specific architecture may define their
- own load_from_pretrained() method.
- """
- load_finetuned = cfg.get("load_finetuned", True)
- if load_finetuned:
- finetune_path = cfg.get("finetuned", None)
- assert (
- finetune_path is not None
- ), "Found load_finetuned is True, but finetune_path is None."
- self.load_checkpoint(url_or_filename=finetune_path)
- else:
- # load pre-trained weights
- pretrain_path = cfg.get("pretrained", None)
- assert "Found load_finetuned is False, but pretrain_path is None."
- self.load_from_pretrained(url_or_filename=pretrain_path, **kwargs)
-
- def before_evaluation(self, **kwargs):
- pass
-
- def show_n_params(self, return_str=True):
- tot = 0
- for p in self.parameters():
- w = 1
- for x in p.shape:
- w *= x
- tot += w
- if return_str:
- if tot >= 1e6:
- return "{:.1f}M".format(tot / 1e6)
- else:
- return "{:.1f}K".format(tot / 1e3)
- else:
- return tot
-
-
-class BaseEncoder(nn.Module):
- """
- Base class for primitive encoders, such as ViT, TimeSformer, etc.
- """
-
- def __init__(self):
- super().__init__()
-
- def forward_features(self, samples, **kwargs):
- raise NotImplementedError
-
- @property
- def device(self):
- return list(self.parameters())[0].device
-
-
-class SharedQueueMixin:
- @torch.no_grad()
- def _dequeue_and_enqueue(self, image_feat, text_feat, idxs=None):
- # gather keys before updating queue
- image_feats = concat_all_gather(image_feat)
- text_feats = concat_all_gather(text_feat)
-
- batch_size = image_feats.shape[0]
-
- ptr = int(self.queue_ptr)
- assert self.queue_size % batch_size == 0 # for simplicity
-
- # replace the keys at ptr (dequeue and enqueue)
- self.image_queue[:, ptr : ptr + batch_size] = image_feats.T
- self.text_queue[:, ptr : ptr + batch_size] = text_feats.T
-
- if idxs is not None:
- idxs = concat_all_gather(idxs)
- self.idx_queue[:, ptr : ptr + batch_size] = idxs.T
-
- ptr = (ptr + batch_size) % self.queue_size # move pointer
- self.queue_ptr[0] = ptr
-
-
-class MomentumDistilationMixin:
- @torch.no_grad()
- def copy_params(self):
- for model_pair in self.model_pairs:
- for param, param_m in zip(
- model_pair[0].parameters(), model_pair[1].parameters()
- ):
- param_m.data.copy_(param.data) # initialize
- param_m.requires_grad = False # not update by gradient
-
- @torch.no_grad()
- def _momentum_update(self):
- for model_pair in self.model_pairs:
- for param, param_m in zip(
- model_pair[0].parameters(), model_pair[1].parameters()
- ):
- param_m.data = param_m.data * self.momentum + param.data * (
- 1.0 - self.momentum
- )
-
-
-class GatherLayer(torch.autograd.Function):
- """
- Gather tensors from all workers with support for backward propagation:
- This implementation does not cut the gradients as torch.distributed.all_gather does.
- """
-
- @staticmethod
- def forward(ctx, x):
- output = [
- torch.zeros_like(x) for _ in range(torch.distributed.get_world_size())
- ]
- torch.distributed.all_gather(output, x)
- return tuple(output)
-
- @staticmethod
- def backward(ctx, *grads):
- all_gradients = torch.stack(grads)
- torch.distributed.all_reduce(all_gradients)
- return all_gradients[torch.distributed.get_rank()]
-
-
-def all_gather_with_grad(tensors):
- """
- Performs all_gather operation on the provided tensors.
- Graph remains connected for backward grad computation.
- """
- # Queue the gathered tensors
- world_size = torch.distributed.get_world_size()
- # There is no need for reduction in the single-proc case
- if world_size == 1:
- return tensors
-
- # tensor_all = GatherLayer.apply(tensors)
- tensor_all = GatherLayer.apply(tensors)
-
- return torch.cat(tensor_all, dim=0)
-
-
-@torch.no_grad()
-def concat_all_gather(tensor):
- """
- Performs all_gather operation on the provided tensors.
- *** Warning ***: torch.distributed.all_gather has no gradient.
- """
- # if use distributed training
- if not is_dist_avail_and_initialized():
- return tensor
-
- tensors_gather = [
- torch.ones_like(tensor) for _ in range(torch.distributed.get_world_size())
- ]
- torch.distributed.all_gather(tensors_gather, tensor, async_op=False)
-
- output = torch.cat(tensors_gather, dim=0)
- return output
-
-
-def tile(x, dim, n_tile):
- init_dim = x.size(dim)
- repeat_idx = [1] * x.dim()
- repeat_idx[dim] = n_tile
- x = x.repeat(*(repeat_idx))
- order_index = torch.LongTensor(
- np.concatenate([init_dim * np.arange(n_tile) + i for i in range(init_dim)])
- )
- return torch.index_select(x, dim, order_index.to(x.device))
diff --git a/spaces/Volkopat/SegmentAnythingxGroundingDINO/groundingdino/models/GroundingDINO/groundingdino.py b/spaces/Volkopat/SegmentAnythingxGroundingDINO/groundingdino/models/GroundingDINO/groundingdino.py
deleted file mode 100644
index 052df6220595a1b39b7e2aea37ca4872d113dfd2..0000000000000000000000000000000000000000
--- a/spaces/Volkopat/SegmentAnythingxGroundingDINO/groundingdino/models/GroundingDINO/groundingdino.py
+++ /dev/null
@@ -1,395 +0,0 @@
-# ------------------------------------------------------------------------
-# Grounding DINO
-# url: https://github.com/IDEA-Research/GroundingDINO
-# Copyright (c) 2023 IDEA. All Rights Reserved.
-# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
-# ------------------------------------------------------------------------
-# Conditional DETR model and criterion classes.
-# Copyright (c) 2021 Microsoft. All Rights Reserved.
-# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
-# ------------------------------------------------------------------------
-# Modified from DETR (https://github.com/facebookresearch/detr)
-# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
-# ------------------------------------------------------------------------
-# Modified from Deformable DETR (https://github.com/fundamentalvision/Deformable-DETR)
-# Copyright (c) 2020 SenseTime. All Rights Reserved.
-# ------------------------------------------------------------------------
-import copy
-from typing import List
-
-import torch
-import torch.nn.functional as F
-from torch import nn
-from torchvision.ops.boxes import nms
-from transformers import AutoTokenizer, BertModel, BertTokenizer, RobertaModel, RobertaTokenizerFast
-
-from groundingdino.util import box_ops, get_tokenlizer
-from groundingdino.util.misc import (
- NestedTensor,
- accuracy,
- get_world_size,
- interpolate,
- inverse_sigmoid,
- is_dist_avail_and_initialized,
- nested_tensor_from_tensor_list,
-)
-from groundingdino.util.utils import get_phrases_from_posmap
-from groundingdino.util.visualizer import COCOVisualizer
-from groundingdino.util.vl_utils import create_positive_map_from_span
-
-from ..registry import MODULE_BUILD_FUNCS
-from .backbone import build_backbone
-from .bertwarper import (
- BertModelWarper,
- generate_masks_with_special_tokens,
- generate_masks_with_special_tokens_and_transfer_map,
-)
-from .transformer import build_transformer
-from .utils import MLP, ContrastiveEmbed, sigmoid_focal_loss
-
-
-class GroundingDINO(nn.Module):
- """This is the Cross-Attention Detector module that performs object detection"""
-
- def __init__(
- self,
- backbone,
- transformer,
- num_queries,
- aux_loss=False,
- iter_update=False,
- query_dim=2,
- num_feature_levels=1,
- nheads=8,
- # two stage
- two_stage_type="no", # ['no', 'standard']
- dec_pred_bbox_embed_share=True,
- two_stage_class_embed_share=True,
- two_stage_bbox_embed_share=True,
- num_patterns=0,
- dn_number=100,
- dn_box_noise_scale=0.4,
- dn_label_noise_ratio=0.5,
- dn_labelbook_size=100,
- text_encoder_type="bert-base-uncased",
- sub_sentence_present=True,
- max_text_len=256,
- ):
- """Initializes the model.
- Parameters:
- backbone: torch module of the backbone to be used. See backbone.py
- transformer: torch module of the transformer architecture. See transformer.py
- num_queries: number of object queries, ie detection slot. This is the maximal number of objects
- Conditional DETR can detect in a single image. For COCO, we recommend 100 queries.
- aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used.
- """
- super().__init__()
- self.num_queries = num_queries
- self.transformer = transformer
- self.hidden_dim = hidden_dim = transformer.d_model
- self.num_feature_levels = num_feature_levels
- self.nheads = nheads
- self.max_text_len = 256
- self.sub_sentence_present = sub_sentence_present
-
- # setting query dim
- self.query_dim = query_dim
- assert query_dim == 4
-
- # for dn training
- self.num_patterns = num_patterns
- self.dn_number = dn_number
- self.dn_box_noise_scale = dn_box_noise_scale
- self.dn_label_noise_ratio = dn_label_noise_ratio
- self.dn_labelbook_size = dn_labelbook_size
-
- # bert
- self.tokenizer = get_tokenlizer.get_tokenlizer(text_encoder_type)
- self.bert = get_tokenlizer.get_pretrained_language_model(text_encoder_type)
- self.bert.pooler.dense.weight.requires_grad_(False)
- self.bert.pooler.dense.bias.requires_grad_(False)
- self.bert = BertModelWarper(bert_model=self.bert)
-
- self.feat_map = nn.Linear(self.bert.config.hidden_size, self.hidden_dim, bias=True)
- nn.init.constant_(self.feat_map.bias.data, 0)
- nn.init.xavier_uniform_(self.feat_map.weight.data)
- # freeze
-
- # special tokens
- self.specical_tokens = self.tokenizer.convert_tokens_to_ids(["[CLS]", "[SEP]", ".", "?"])
-
- # prepare input projection layers
- if num_feature_levels > 1:
- num_backbone_outs = len(backbone.num_channels)
- input_proj_list = []
- for _ in range(num_backbone_outs):
- in_channels = backbone.num_channels[_]
- input_proj_list.append(
- nn.Sequential(
- nn.Conv2d(in_channels, hidden_dim, kernel_size=1),
- nn.GroupNorm(32, hidden_dim),
- )
- )
- for _ in range(num_feature_levels - num_backbone_outs):
- input_proj_list.append(
- nn.Sequential(
- nn.Conv2d(in_channels, hidden_dim, kernel_size=3, stride=2, padding=1),
- nn.GroupNorm(32, hidden_dim),
- )
- )
- in_channels = hidden_dim
- self.input_proj = nn.ModuleList(input_proj_list)
- else:
- assert two_stage_type == "no", "two_stage_type should be no if num_feature_levels=1 !!!"
- self.input_proj = nn.ModuleList(
- [
- nn.Sequential(
- nn.Conv2d(backbone.num_channels[-1], hidden_dim, kernel_size=1),
- nn.GroupNorm(32, hidden_dim),
- )
- ]
- )
-
- self.backbone = backbone
- self.aux_loss = aux_loss
- self.box_pred_damping = box_pred_damping = None
-
- self.iter_update = iter_update
- assert iter_update, "Why not iter_update?"
-
- # prepare pred layers
- self.dec_pred_bbox_embed_share = dec_pred_bbox_embed_share
- # prepare class & box embed
- _class_embed = ContrastiveEmbed()
-
- _bbox_embed = MLP(hidden_dim, hidden_dim, 4, 3)
- nn.init.constant_(_bbox_embed.layers[-1].weight.data, 0)
- nn.init.constant_(_bbox_embed.layers[-1].bias.data, 0)
-
- if dec_pred_bbox_embed_share:
- box_embed_layerlist = [_bbox_embed for i in range(transformer.num_decoder_layers)]
- else:
- box_embed_layerlist = [
- copy.deepcopy(_bbox_embed) for i in range(transformer.num_decoder_layers)
- ]
- class_embed_layerlist = [_class_embed for i in range(transformer.num_decoder_layers)]
- self.bbox_embed = nn.ModuleList(box_embed_layerlist)
- self.class_embed = nn.ModuleList(class_embed_layerlist)
- self.transformer.decoder.bbox_embed = self.bbox_embed
- self.transformer.decoder.class_embed = self.class_embed
-
- # two stage
- self.two_stage_type = two_stage_type
- assert two_stage_type in ["no", "standard"], "unknown param {} of two_stage_type".format(
- two_stage_type
- )
- if two_stage_type != "no":
- if two_stage_bbox_embed_share:
- assert dec_pred_bbox_embed_share
- self.transformer.enc_out_bbox_embed = _bbox_embed
- else:
- self.transformer.enc_out_bbox_embed = copy.deepcopy(_bbox_embed)
-
- if two_stage_class_embed_share:
- assert dec_pred_bbox_embed_share
- self.transformer.enc_out_class_embed = _class_embed
- else:
- self.transformer.enc_out_class_embed = copy.deepcopy(_class_embed)
-
- self.refpoint_embed = None
-
- self._reset_parameters()
-
- def _reset_parameters(self):
- # init input_proj
- for proj in self.input_proj:
- nn.init.xavier_uniform_(proj[0].weight, gain=1)
- nn.init.constant_(proj[0].bias, 0)
-
- def init_ref_points(self, use_num_queries):
- self.refpoint_embed = nn.Embedding(use_num_queries, self.query_dim)
-
- def forward(self, samples: NestedTensor, targets: List = None, **kw):
- """The forward expects a NestedTensor, which consists of:
- - samples.tensor: batched images, of shape [batch_size x 3 x H x W]
- - samples.mask: a binary mask of shape [batch_size x H x W], containing 1 on padded pixels
-
- It returns a dict with the following elements:
- - "pred_logits": the classification logits (including no-object) for all queries.
- Shape= [batch_size x num_queries x num_classes]
- - "pred_boxes": The normalized boxes coordinates for all queries, represented as
- (center_x, center_y, width, height). These values are normalized in [0, 1],
- relative to the size of each individual image (disregarding possible padding).
- See PostProcess for information on how to retrieve the unnormalized bounding box.
- - "aux_outputs": Optional, only returned when auxilary losses are activated. It is a list of
- dictionnaries containing the two above keys for each decoder layer.
- """
- if targets is None:
- captions = kw["captions"]
- else:
- captions = [t["caption"] for t in targets]
- len(captions)
-
- # encoder texts
- tokenized = self.tokenizer(captions, padding="longest", return_tensors="pt").to(
- samples.device
- )
- (
- text_self_attention_masks,
- position_ids,
- cate_to_token_mask_list,
- ) = generate_masks_with_special_tokens_and_transfer_map(
- tokenized, self.specical_tokens, self.tokenizer
- )
-
- if text_self_attention_masks.shape[1] > self.max_text_len:
- text_self_attention_masks = text_self_attention_masks[
- :, : self.max_text_len, : self.max_text_len
- ]
- position_ids = position_ids[:, : self.max_text_len]
- tokenized["input_ids"] = tokenized["input_ids"][:, : self.max_text_len]
- tokenized["attention_mask"] = tokenized["attention_mask"][:, : self.max_text_len]
- tokenized["token_type_ids"] = tokenized["token_type_ids"][:, : self.max_text_len]
-
- # extract text embeddings
- if self.sub_sentence_present:
- tokenized_for_encoder = {k: v for k, v in tokenized.items() if k != "attention_mask"}
- tokenized_for_encoder["attention_mask"] = text_self_attention_masks
- tokenized_for_encoder["position_ids"] = position_ids
- else:
- # import ipdb; ipdb.set_trace()
- tokenized_for_encoder = tokenized
-
- bert_output = self.bert(**tokenized_for_encoder) # bs, 195, 768
-
- encoded_text = self.feat_map(bert_output["last_hidden_state"]) # bs, 195, d_model
- text_token_mask = tokenized.attention_mask.bool() # bs, 195
- # text_token_mask: True for nomask, False for mask
- # text_self_attention_masks: True for nomask, False for mask
-
- if encoded_text.shape[1] > self.max_text_len:
- encoded_text = encoded_text[:, : self.max_text_len, :]
- text_token_mask = text_token_mask[:, : self.max_text_len]
- position_ids = position_ids[:, : self.max_text_len]
- text_self_attention_masks = text_self_attention_masks[
- :, : self.max_text_len, : self.max_text_len
- ]
-
- text_dict = {
- "encoded_text": encoded_text, # bs, 195, d_model
- "text_token_mask": text_token_mask, # bs, 195
- "position_ids": position_ids, # bs, 195
- "text_self_attention_masks": text_self_attention_masks, # bs, 195,195
- }
-
- # import ipdb; ipdb.set_trace()
-
- if isinstance(samples, (list, torch.Tensor)):
- samples = nested_tensor_from_tensor_list(samples)
- features, poss = self.backbone(samples)
-
- srcs = []
- masks = []
- for l, feat in enumerate(features):
- src, mask = feat.decompose()
- srcs.append(self.input_proj[l](src))
- masks.append(mask)
- assert mask is not None
- if self.num_feature_levels > len(srcs):
- _len_srcs = len(srcs)
- for l in range(_len_srcs, self.num_feature_levels):
- if l == _len_srcs:
- src = self.input_proj[l](features[-1].tensors)
- else:
- src = self.input_proj[l](srcs[-1])
- m = samples.mask
- mask = F.interpolate(m[None].float(), size=src.shape[-2:]).to(torch.bool)[0]
- pos_l = self.backbone[1](NestedTensor(src, mask)).to(src.dtype)
- srcs.append(src)
- masks.append(mask)
- poss.append(pos_l)
-
- input_query_bbox = input_query_label = attn_mask = dn_meta = None
- hs, reference, hs_enc, ref_enc, init_box_proposal = self.transformer(
- srcs, masks, input_query_bbox, poss, input_query_label, attn_mask, text_dict
- )
-
- # deformable-detr-like anchor update
- outputs_coord_list = []
- for dec_lid, (layer_ref_sig, layer_bbox_embed, layer_hs) in enumerate(
- zip(reference[:-1], self.bbox_embed, hs)
- ):
- layer_delta_unsig = layer_bbox_embed(layer_hs)
- layer_outputs_unsig = layer_delta_unsig + inverse_sigmoid(layer_ref_sig)
- layer_outputs_unsig = layer_outputs_unsig.sigmoid()
- outputs_coord_list.append(layer_outputs_unsig)
- outputs_coord_list = torch.stack(outputs_coord_list)
-
- # output
- outputs_class = torch.stack(
- [
- layer_cls_embed(layer_hs, text_dict)
- for layer_cls_embed, layer_hs in zip(self.class_embed, hs)
- ]
- )
- out = {"pred_logits": outputs_class[-1], "pred_boxes": outputs_coord_list[-1]}
-
- # # for intermediate outputs
- # if self.aux_loss:
- # out['aux_outputs'] = self._set_aux_loss(outputs_class, outputs_coord_list)
-
- # # for encoder output
- # if hs_enc is not None:
- # # prepare intermediate outputs
- # interm_coord = ref_enc[-1]
- # interm_class = self.transformer.enc_out_class_embed(hs_enc[-1], text_dict)
- # out['interm_outputs'] = {'pred_logits': interm_class, 'pred_boxes': interm_coord}
- # out['interm_outputs_for_matching_pre'] = {'pred_logits': interm_class, 'pred_boxes': init_box_proposal}
-
- return out
-
- @torch.jit.unused
- def _set_aux_loss(self, outputs_class, outputs_coord):
- # this is a workaround to make torchscript happy, as torchscript
- # doesn't support dictionary with non-homogeneous values, such
- # as a dict having both a Tensor and a list.
- return [
- {"pred_logits": a, "pred_boxes": b}
- for a, b in zip(outputs_class[:-1], outputs_coord[:-1])
- ]
-
-
-@MODULE_BUILD_FUNCS.registe_with_name(module_name="groundingdino")
-def build_groundingdino(args):
-
- backbone = build_backbone(args)
- transformer = build_transformer(args)
-
- dn_labelbook_size = args.dn_labelbook_size
- dec_pred_bbox_embed_share = args.dec_pred_bbox_embed_share
- sub_sentence_present = args.sub_sentence_present
-
- model = GroundingDINO(
- backbone,
- transformer,
- num_queries=args.num_queries,
- aux_loss=True,
- iter_update=True,
- query_dim=4,
- num_feature_levels=args.num_feature_levels,
- nheads=args.nheads,
- dec_pred_bbox_embed_share=dec_pred_bbox_embed_share,
- two_stage_type=args.two_stage_type,
- two_stage_bbox_embed_share=args.two_stage_bbox_embed_share,
- two_stage_class_embed_share=args.two_stage_class_embed_share,
- num_patterns=args.num_patterns,
- dn_number=0,
- dn_box_noise_scale=args.dn_box_noise_scale,
- dn_label_noise_ratio=args.dn_label_noise_ratio,
- dn_labelbook_size=dn_labelbook_size,
- text_encoder_type=args.text_encoder_type,
- sub_sentence_present=sub_sentence_present,
- max_text_len=args.max_text_len,
- )
-
- return model
diff --git a/spaces/Waqasjan123/CompVis-stable-diffusion-v1-4/app.py b/spaces/Waqasjan123/CompVis-stable-diffusion-v1-4/app.py
deleted file mode 100644
index e1e1025c8f06010197c50917ac9dd1ddeaf7e5aa..0000000000000000000000000000000000000000
--- a/spaces/Waqasjan123/CompVis-stable-diffusion-v1-4/app.py
+++ /dev/null
@@ -1,3 +0,0 @@
-import gradio as gr
-
-gr.Interface.load("models/CompVis/stable-diffusion-v1-4").launch()
\ No newline at end of file
diff --git a/spaces/Xenova/next-example-app/_next/static/css/853c10cac764d9b5.css b/spaces/Xenova/next-example-app/_next/static/css/853c10cac764d9b5.css
deleted file mode 100644
index 3c446801816163b6a181016ea0185227b5d93c80..0000000000000000000000000000000000000000
--- a/spaces/Xenova/next-example-app/_next/static/css/853c10cac764d9b5.css
+++ /dev/null
@@ -1,3 +0,0 @@
-/*
-! tailwindcss v3.3.3 | MIT License | https://tailwindcss.com
-*/*,:after,:before{box-sizing:border-box;border:0 solid #e5e7eb}:after,:before{--tw-content:""}html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.static{position:static}.mb-2{margin-bottom:.5rem}.mb-4{margin-bottom:1rem}.flex{display:flex}.min-h-screen{min-height:100vh}.w-full{width:100%}.max-w-xs{max-width:20rem}.flex-col{flex-direction:column}.items-center{align-items:center}.justify-center{justify-content:center}.rounded{border-radius:.25rem}.border{border-width:1px}.border-gray-300{--tw-border-opacity:1;border-color:rgb(209 213 219/var(--tw-border-opacity))}.bg-gray-100{--tw-bg-opacity:1;background-color:rgb(243 244 246/var(--tw-bg-opacity))}.p-12{padding:3rem}.p-2{padding:.5rem}.text-center{text-align:center}.text-2xl{font-size:1.5rem;line-height:2rem}.text-5xl{font-size:3rem;line-height:1}.font-bold{font-weight:700}:root{--foreground-rgb:0,0,0;--background-start-rgb:214,219,220;--background-end-rgb:255,255,255}@media (prefers-color-scheme:dark){:root{--foreground-rgb:255,255,255;--background-start-rgb:0,0,0;--background-end-rgb:0,0,0}}body{color:rgb(var(--foreground-rgb));background:linear-gradient(to bottom,transparent,rgb(var(--background-end-rgb))) rgb(var(--background-start-rgb))}@font-face{font-family:__Inter_20951f;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/d1d9458b69004127-s.woff2) format("woff2");unicode-range:U+0460-052f,U+1c80-1c88,U+20b4,U+2de0-2dff,U+a640-a69f,U+fe2e-fe2f}@font-face{font-family:__Inter_20951f;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/b967158bc7d7a9fb-s.woff2) format("woff2");unicode-range:U+0301,U+0400-045f,U+0490-0491,U+04b0-04b1,U+2116}@font-face{font-family:__Inter_20951f;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/ae9ae6716d4f8bf8-s.woff2) format("woff2");unicode-range:U+1f??}@font-face{font-family:__Inter_20951f;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/c0f5ec5bbf5913b7-s.woff2) format("woff2");unicode-range:U+0370-03ff}@font-face{font-family:__Inter_20951f;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/b1db3e28af9ef94a-s.woff2) format("woff2");unicode-range:U+0102-0103,U+0110-0111,U+0128-0129,U+0168-0169,U+01a0-01a1,U+01af-01b0,U+0300-0301,U+0303-0304,U+0308-0309,U+0323,U+0329,U+1ea0-1ef9,U+20ab}@font-face{font-family:__Inter_20951f;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/9c4f34569c9b36ca-s.woff2) format("woff2");unicode-range:U+0100-02af,U+0304,U+0308,U+0329,U+1e00-1e9f,U+1ef2-1eff,U+2020,U+20a0-20ab,U+20ad-20cf,U+2113,U+2c60-2c7f,U+a720-a7ff}@font-face{font-family:__Inter_20951f;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/2aaf0723e720e8b9-s.p.woff2) format("woff2");unicode-range:U+00??,U+0131,U+0152-0153,U+02bb-02bc,U+02c6,U+02da,U+02dc,U+0304,U+0308,U+0329,U+2000-206f,U+2074,U+20ac,U+2122,U+2191,U+2193,U+2212,U+2215,U+feff,U+fffd}@font-face{font-family:__Inter_Fallback_20951f;src:local("Arial");ascent-override:90.20%;descent-override:22.48%;line-gap-override:0.00%;size-adjust:107.40%}.__className_20951f{font-family:__Inter_20951f,__Inter_Fallback_20951f;font-style:normal}
\ No newline at end of file
diff --git a/spaces/Xhaheen/stable-diffusion-depth2img-test/README.md b/spaces/Xhaheen/stable-diffusion-depth2img-test/README.md
deleted file mode 100644
index 40798debd5f7a1f06ff85363e836aff170fb1373..0000000000000000000000000000000000000000
--- a/spaces/Xhaheen/stable-diffusion-depth2img-test/README.md
+++ /dev/null
@@ -1,13 +0,0 @@
----
-title: Stablediffusion Depth2img
-emoji: 🧊🖼
-colorFrom: green
-colorTo: yellow
-sdk: gradio
-sdk_version: 3.11.0
-app_file: app.py
-pinned: false
-duplicated_from: radames/stable-diffusion-depth2img
----
-
-Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
diff --git a/spaces/XzJosh/Carol-Bert-VITS2/server.py b/spaces/XzJosh/Carol-Bert-VITS2/server.py
deleted file mode 100644
index c736ca4f95fec853950eef6654ef79856beffc0a..0000000000000000000000000000000000000000
--- a/spaces/XzJosh/Carol-Bert-VITS2/server.py
+++ /dev/null
@@ -1,123 +0,0 @@
-from flask import Flask, request, Response
-from io import BytesIO
-import torch
-from av import open as avopen
-
-import commons
-import utils
-from models import SynthesizerTrn
-from text.symbols import symbols
-from text import cleaned_text_to_sequence, get_bert
-from text.cleaner import clean_text
-from scipy.io import wavfile
-
-# Flask Init
-app = Flask(__name__)
-app.config['JSON_AS_ASCII'] = False
-def get_text(text, language_str, hps):
- norm_text, phone, tone, word2ph = clean_text(text, language_str)
- print([f"{p}{t}" for p, t in zip(phone, tone)])
- phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
-
- if hps.data.add_blank:
- phone = commons.intersperse(phone, 0)
- tone = commons.intersperse(tone, 0)
- language = commons.intersperse(language, 0)
- for i in range(len(word2ph)):
- word2ph[i] = word2ph[i] * 2
- word2ph[0] += 1
- bert = get_bert(norm_text, word2ph, language_str)
-
- assert bert.shape[-1] == len(phone)
-
- phone = torch.LongTensor(phone)
- tone = torch.LongTensor(tone)
- language = torch.LongTensor(language)
-
- return bert, phone, tone, language
-
-def infer(text, sdp_ratio, noise_scale, noise_scale_w,length_scale,sid):
- bert, phones, tones, lang_ids = get_text(text,"ZH", hps,)
- with torch.no_grad():
- x_tst=phones.to(dev).unsqueeze(0)
- tones=tones.to(dev).unsqueeze(0)
- lang_ids=lang_ids.to(dev).unsqueeze(0)
- bert = bert.to(dev).unsqueeze(0)
- x_tst_lengths = torch.LongTensor([phones.size(0)]).to(dev)
- speakers = torch.LongTensor([hps.data.spk2id[sid]]).to(dev)
- audio = net_g.infer(x_tst, x_tst_lengths, speakers, tones, lang_ids,bert, sdp_ratio=sdp_ratio
- , noise_scale=noise_scale, noise_scale_w=noise_scale_w, length_scale=length_scale)[0][0,0].data.cpu().float().numpy()
- return audio
-
-def replace_punctuation(text, i=2):
- punctuation = ",。?!"
- for char in punctuation:
- text = text.replace(char, char * i)
- return text
-
-def wav2(i, o, format):
- inp = avopen(i, 'rb')
- out = avopen(o, 'wb', format=format)
- if format == "ogg": format = "libvorbis"
-
- ostream = out.add_stream(format)
-
- for frame in inp.decode(audio=0):
- for p in ostream.encode(frame): out.mux(p)
-
- for p in ostream.encode(None): out.mux(p)
-
- out.close()
- inp.close()
-
-# Load Generator
-hps = utils.get_hparams_from_file("./configs/config.json")
-
-dev='cuda'
-net_g = SynthesizerTrn(
- len(symbols),
- hps.data.filter_length // 2 + 1,
- hps.train.segment_size // hps.data.hop_length,
- n_speakers=hps.data.n_speakers,
- **hps.model).to(dev)
-_ = net_g.eval()
-
-_ = utils.load_checkpoint("logs/G_649000.pth", net_g, None,skip_optimizer=True)
-
-@app.route("/",methods=['GET','POST'])
-def main():
- if request.method == 'GET':
- try:
- speaker = request.args.get('speaker')
- text = request.args.get('text').replace("/n","")
- sdp_ratio = float(request.args.get("sdp_ratio", 0.2))
- noise = float(request.args.get("noise", 0.5))
- noisew = float(request.args.get("noisew", 0.6))
- length = float(request.args.get("length", 1.2))
- if length >= 2:
- return "Too big length"
- if len(text) >=200:
- return "Too long text"
- fmt = request.args.get("format", "wav")
- if None in (speaker, text):
- return "Missing Parameter"
- if fmt not in ("mp3", "wav", "ogg"):
- return "Invalid Format"
- except:
- return "Invalid Parameter"
-
- with torch.no_grad():
- audio = infer(text, sdp_ratio=sdp_ratio, noise_scale=noise, noise_scale_w=noisew, length_scale=length, sid=speaker)
-
- with BytesIO() as wav:
- wavfile.write(wav, hps.data.sampling_rate, audio)
- torch.cuda.empty_cache()
- if fmt == "wav":
- return Response(wav.getvalue(), mimetype="audio/wav")
- wav.seek(0, 0)
- with BytesIO() as ofp:
- wav2(wav, ofp, fmt)
- return Response(
- ofp.getvalue(),
- mimetype="audio/mpeg" if fmt == "mp3" else "audio/ogg"
- )
diff --git a/spaces/XzJosh/Lumi-Bert-VITS2/README.md b/spaces/XzJosh/Lumi-Bert-VITS2/README.md
deleted file mode 100644
index 1ebb8bbd509a0f90653304a56b5ffe6c781cce16..0000000000000000000000000000000000000000
--- a/spaces/XzJosh/Lumi-Bert-VITS2/README.md
+++ /dev/null
@@ -1,5 +0,0 @@
----
-license: mit
-sdk: gradio
-title: AI鹿鸣①
----
\ No newline at end of file
diff --git a/spaces/XzJosh/TianDou-Bert-VITS2/utils.py b/spaces/XzJosh/TianDou-Bert-VITS2/utils.py
deleted file mode 100644
index c6aa6cfc64c33e2eed33e9845239e831fc1c4a1a..0000000000000000000000000000000000000000
--- a/spaces/XzJosh/TianDou-Bert-VITS2/utils.py
+++ /dev/null
@@ -1,293 +0,0 @@
-import os
-import glob
-import sys
-import argparse
-import logging
-import json
-import subprocess
-import numpy as np
-from scipy.io.wavfile import read
-import torch
-
-MATPLOTLIB_FLAG = False
-
-logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
-logger = logging
-
-
-def load_checkpoint(checkpoint_path, model, optimizer=None, skip_optimizer=False):
- assert os.path.isfile(checkpoint_path)
- checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
- iteration = checkpoint_dict['iteration']
- learning_rate = checkpoint_dict['learning_rate']
- if optimizer is not None and not skip_optimizer and checkpoint_dict['optimizer'] is not None:
- optimizer.load_state_dict(checkpoint_dict['optimizer'])
- elif optimizer is None and not skip_optimizer:
- #else: #Disable this line if Infer ,and enable the line upper
- new_opt_dict = optimizer.state_dict()
- new_opt_dict_params = new_opt_dict['param_groups'][0]['params']
- new_opt_dict['param_groups'] = checkpoint_dict['optimizer']['param_groups']
- new_opt_dict['param_groups'][0]['params'] = new_opt_dict_params
- optimizer.load_state_dict(new_opt_dict)
- saved_state_dict = checkpoint_dict['model']
- if hasattr(model, 'module'):
- state_dict = model.module.state_dict()
- else:
- state_dict = model.state_dict()
- new_state_dict = {}
- for k, v in state_dict.items():
- try:
- #assert "emb_g" not in k
- # print("load", k)
- new_state_dict[k] = saved_state_dict[k]
- assert saved_state_dict[k].shape == v.shape, (saved_state_dict[k].shape, v.shape)
- except:
- print("error, %s is not in the checkpoint" % k)
- new_state_dict[k] = v
- if hasattr(model, 'module'):
- model.module.load_state_dict(new_state_dict, strict=False)
- else:
- model.load_state_dict(new_state_dict, strict=False)
- print("load ")
- logger.info("Loaded checkpoint '{}' (iteration {})".format(
- checkpoint_path, iteration))
- return model, optimizer, learning_rate, iteration
-
-
-def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path):
- logger.info("Saving model and optimizer state at iteration {} to {}".format(
- iteration, checkpoint_path))
- if hasattr(model, 'module'):
- state_dict = model.module.state_dict()
- else:
- state_dict = model.state_dict()
- torch.save({'model': state_dict,
- 'iteration': iteration,
- 'optimizer': optimizer.state_dict(),
- 'learning_rate': learning_rate}, checkpoint_path)
-
-
-def summarize(writer, global_step, scalars={}, histograms={}, images={}, audios={}, audio_sampling_rate=22050):
- for k, v in scalars.items():
- writer.add_scalar(k, v, global_step)
- for k, v in histograms.items():
- writer.add_histogram(k, v, global_step)
- for k, v in images.items():
- writer.add_image(k, v, global_step, dataformats='HWC')
- for k, v in audios.items():
- writer.add_audio(k, v, global_step, audio_sampling_rate)
-
-
-def latest_checkpoint_path(dir_path, regex="G_*.pth"):
- f_list = glob.glob(os.path.join(dir_path, regex))
- f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
- x = f_list[-1]
- print(x)
- return x
-
-
-def plot_spectrogram_to_numpy(spectrogram):
- global MATPLOTLIB_FLAG
- if not MATPLOTLIB_FLAG:
- import matplotlib
- matplotlib.use("Agg")
- MATPLOTLIB_FLAG = True
- mpl_logger = logging.getLogger('matplotlib')
- mpl_logger.setLevel(logging.WARNING)
- import matplotlib.pylab as plt
- import numpy as np
-
- fig, ax = plt.subplots(figsize=(10, 2))
- im = ax.imshow(spectrogram, aspect="auto", origin="lower",
- interpolation='none')
- plt.colorbar(im, ax=ax)
- plt.xlabel("Frames")
- plt.ylabel("Channels")
- plt.tight_layout()
-
- fig.canvas.draw()
- data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
- data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
- plt.close()
- return data
-
-
-def plot_alignment_to_numpy(alignment, info=None):
- global MATPLOTLIB_FLAG
- if not MATPLOTLIB_FLAG:
- import matplotlib
- matplotlib.use("Agg")
- MATPLOTLIB_FLAG = True
- mpl_logger = logging.getLogger('matplotlib')
- mpl_logger.setLevel(logging.WARNING)
- import matplotlib.pylab as plt
- import numpy as np
-
- fig, ax = plt.subplots(figsize=(6, 4))
- im = ax.imshow(alignment.transpose(), aspect='auto', origin='lower',
- interpolation='none')
- fig.colorbar(im, ax=ax)
- xlabel = 'Decoder timestep'
- if info is not None:
- xlabel += '\n\n' + info
- plt.xlabel(xlabel)
- plt.ylabel('Encoder timestep')
- plt.tight_layout()
-
- fig.canvas.draw()
- data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
- data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
- plt.close()
- return data
-
-
-def load_wav_to_torch(full_path):
- sampling_rate, data = read(full_path)
- return torch.FloatTensor(data.astype(np.float32)), sampling_rate
-
-
-def load_filepaths_and_text(filename, split="|"):
- with open(filename, encoding='utf-8') as f:
- filepaths_and_text = [line.strip().split(split) for line in f]
- return filepaths_and_text
-
-
-def get_hparams(init=True):
- parser = argparse.ArgumentParser()
- parser.add_argument('-c', '--config', type=str, default="./configs/base.json",
- help='JSON file for configuration')
- parser.add_argument('-m', '--model', type=str, default="./OUTPUT_MODEL",
- help='Model name')
- parser.add_argument('--cont', dest='cont', action="store_true", default=False, help="whether to continue training on the latest checkpoint")
-
- args = parser.parse_args()
- model_dir = os.path.join("./logs", args.model)
-
- if not os.path.exists(model_dir):
- os.makedirs(model_dir)
-
- config_path = args.config
- config_save_path = os.path.join(model_dir, "config.json")
- if init:
- with open(config_path, "r") as f:
- data = f.read()
- with open(config_save_path, "w") as f:
- f.write(data)
- else:
- with open(config_save_path, "r") as f:
- data = f.read()
- config = json.loads(data)
-
- hparams = HParams(**config)
- hparams.model_dir = model_dir
- hparams.cont = args.cont
- return hparams
-
-
-def clean_checkpoints(path_to_models='logs/44k/', n_ckpts_to_keep=2, sort_by_time=True):
- """Freeing up space by deleting saved ckpts
-
- Arguments:
- path_to_models -- Path to the model directory
- n_ckpts_to_keep -- Number of ckpts to keep, excluding G_0.pth and D_0.pth
- sort_by_time -- True -> chronologically delete ckpts
- False -> lexicographically delete ckpts
- """
- import re
- ckpts_files = [f for f in os.listdir(path_to_models) if os.path.isfile(os.path.join(path_to_models, f))]
- name_key = (lambda _f: int(re.compile('._(\d+)\.pth').match(_f).group(1)))
- time_key = (lambda _f: os.path.getmtime(os.path.join(path_to_models, _f)))
- sort_key = time_key if sort_by_time else name_key
- x_sorted = lambda _x: sorted([f for f in ckpts_files if f.startswith(_x) and not f.endswith('_0.pth')],
- key=sort_key)
- to_del = [os.path.join(path_to_models, fn) for fn in
- (x_sorted('G')[:-n_ckpts_to_keep] + x_sorted('D')[:-n_ckpts_to_keep])]
- del_info = lambda fn: logger.info(f".. Free up space by deleting ckpt {fn}")
- del_routine = lambda x: [os.remove(x), del_info(x)]
- rs = [del_routine(fn) for fn in to_del]
-
-def get_hparams_from_dir(model_dir):
- config_save_path = os.path.join(model_dir, "config.json")
- with open(config_save_path, "r") as f:
- data = f.read()
- config = json.loads(data)
-
- hparams = HParams(**config)
- hparams.model_dir = model_dir
- return hparams
-
-
-def get_hparams_from_file(config_path):
- with open(config_path, "r") as f:
- data = f.read()
- config = json.loads(data)
-
- hparams = HParams(**config)
- return hparams
-
-
-def check_git_hash(model_dir):
- source_dir = os.path.dirname(os.path.realpath(__file__))
- if not os.path.exists(os.path.join(source_dir, ".git")):
- logger.warn("{} is not a git repository, therefore hash value comparison will be ignored.".format(
- source_dir
- ))
- return
-
- cur_hash = subprocess.getoutput("git rev-parse HEAD")
-
- path = os.path.join(model_dir, "githash")
- if os.path.exists(path):
- saved_hash = open(path).read()
- if saved_hash != cur_hash:
- logger.warn("git hash values are different. {}(saved) != {}(current)".format(
- saved_hash[:8], cur_hash[:8]))
- else:
- open(path, "w").write(cur_hash)
-
-
-def get_logger(model_dir, filename="train.log"):
- global logger
- logger = logging.getLogger(os.path.basename(model_dir))
- logger.setLevel(logging.DEBUG)
-
- formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
- if not os.path.exists(model_dir):
- os.makedirs(model_dir)
- h = logging.FileHandler(os.path.join(model_dir, filename))
- h.setLevel(logging.DEBUG)
- h.setFormatter(formatter)
- logger.addHandler(h)
- return logger
-
-
-class HParams():
- def __init__(self, **kwargs):
- for k, v in kwargs.items():
- if type(v) == dict:
- v = HParams(**v)
- self[k] = v
-
- def keys(self):
- return self.__dict__.keys()
-
- def items(self):
- return self.__dict__.items()
-
- def values(self):
- return self.__dict__.values()
-
- def __len__(self):
- return len(self.__dict__)
-
- def __getitem__(self, key):
- return getattr(self, key)
-
- def __setitem__(self, key, value):
- return setattr(self, key, value)
-
- def __contains__(self, key):
- return key in self.__dict__
-
- def __repr__(self):
- return self.__dict__.__repr__()
diff --git a/spaces/YuAnthony/Voice-Recognition/utils/reader.py b/spaces/YuAnthony/Voice-Recognition/utils/reader.py
deleted file mode 100644
index e96002b1525454a5f5e922c988524ce1ba3184c9..0000000000000000000000000000000000000000
--- a/spaces/YuAnthony/Voice-Recognition/utils/reader.py
+++ /dev/null
@@ -1,50 +0,0 @@
-import librosa
-import numpy as np
-from torch.utils import data
-
-
-# 加载并预处理音频
-def load_audio(audio_path, mode='train', win_length=400, sr=16000, hop_length=160, n_fft=512, spec_len=257):
- # 读取音频数据
- wav, sr_ret = librosa.load(audio_path, sr=sr)
- # 数据拼接
- if mode == 'train':
- extended_wav = np.append(wav, wav)
- if np.random.random() < 0.3:
- extended_wav = extended_wav[::-1]
- else:
- extended_wav = np.append(wav, wav[::-1])
- # 计算短时傅里叶变换
- linear = librosa.stft(extended_wav, n_fft=n_fft, win_length=win_length, hop_length=hop_length)
- mag, _ = librosa.magphase(linear)
- freq, freq_time = mag.shape
- assert freq_time >= spec_len, "非静音部分长度不能低于1.3s"
- if mode == 'train':
- # 随机裁剪
- rand_time = np.random.randint(0, freq_time - spec_len)
- spec_mag = mag[:, rand_time:rand_time + spec_len]
- else:
- spec_mag = mag[:, :spec_len]
- mean = np.mean(spec_mag, 0, keepdims=True)
- std = np.std(spec_mag, 0, keepdims=True)
- spec_mag = (spec_mag - mean) / (std + 1e-5)
- spec_mag = spec_mag[np.newaxis, :]
- return spec_mag
-
-
-# 数据加载器
-class CustomDataset(data.Dataset):
- def __init__(self, data_list_path, model='train', spec_len=257):
- super(CustomDataset, self).__init__()
- with open(data_list_path, 'r') as f:
- self.lines = f.readlines()
- self.model = model
- self.spec_len = spec_len
-
- def __getitem__(self, idx):
- audio_path, label = self.lines[idx].replace('\n', '').split('\t')
- spec_mag = load_audio(audio_path, mode=self.model, spec_len=self.spec_len)
- return spec_mag, np.array(int(label), dtype=np.int64)
-
- def __len__(self):
- return len(self.lines)
diff --git a/spaces/Yudha515/Rvc-Models/tests/data/test_audio_utils.py b/spaces/Yudha515/Rvc-Models/tests/data/test_audio_utils.py
deleted file mode 100644
index 0480671bb17281d61ce02bce6373a5ccec89fece..0000000000000000000000000000000000000000
--- a/spaces/Yudha515/Rvc-Models/tests/data/test_audio_utils.py
+++ /dev/null
@@ -1,110 +0,0 @@
-# Copyright (c) Meta Platforms, Inc. and affiliates.
-# All rights reserved.
-#
-# This source code is licensed under the license found in the
-# LICENSE file in the root directory of this source tree.
-
-import julius
-import torch
-import pytest
-
-from audiocraft.data.audio_utils import (
- _clip_wav,
- convert_audio_channels,
- convert_audio,
- normalize_audio
-)
-from ..common_utils import get_batch_white_noise
-
-
-class TestConvertAudioChannels:
-
- def test_convert_audio_channels_downmix(self):
- b, c, t = 2, 3, 100
- audio = get_batch_white_noise(b, c, t)
- mixed = convert_audio_channels(audio, channels=2)
- assert list(mixed.shape) == [b, 2, t]
-
- def test_convert_audio_channels_nochange(self):
- b, c, t = 2, 3, 100
- audio = get_batch_white_noise(b, c, t)
- mixed = convert_audio_channels(audio, channels=c)
- assert list(mixed.shape) == list(audio.shape)
-
- def test_convert_audio_channels_upmix(self):
- b, c, t = 2, 1, 100
- audio = get_batch_white_noise(b, c, t)
- mixed = convert_audio_channels(audio, channels=3)
- assert list(mixed.shape) == [b, 3, t]
-
- def test_convert_audio_channels_upmix_error(self):
- b, c, t = 2, 2, 100
- audio = get_batch_white_noise(b, c, t)
- with pytest.raises(ValueError):
- convert_audio_channels(audio, channels=3)
-
-
-class TestConvertAudio:
-
- def test_convert_audio_channels_downmix(self):
- b, c, dur = 2, 3, 4.
- sr = 128
- audio = get_batch_white_noise(b, c, int(sr * dur))
- out = convert_audio(audio, from_rate=sr, to_rate=sr, to_channels=2)
- assert list(out.shape) == [audio.shape[0], 2, audio.shape[-1]]
-
- def test_convert_audio_channels_upmix(self):
- b, c, dur = 2, 1, 4.
- sr = 128
- audio = get_batch_white_noise(b, c, int(sr * dur))
- out = convert_audio(audio, from_rate=sr, to_rate=sr, to_channels=3)
- assert list(out.shape) == [audio.shape[0], 3, audio.shape[-1]]
-
- def test_convert_audio_upsample(self):
- b, c, dur = 2, 1, 4.
- sr = 2
- new_sr = 3
- audio = get_batch_white_noise(b, c, int(sr * dur))
- out = convert_audio(audio, from_rate=sr, to_rate=new_sr, to_channels=c)
- out_j = julius.resample.resample_frac(audio, old_sr=sr, new_sr=new_sr)
- assert torch.allclose(out, out_j)
-
- def test_convert_audio_resample(self):
- b, c, dur = 2, 1, 4.
- sr = 3
- new_sr = 2
- audio = get_batch_white_noise(b, c, int(sr * dur))
- out = convert_audio(audio, from_rate=sr, to_rate=new_sr, to_channels=c)
- out_j = julius.resample.resample_frac(audio, old_sr=sr, new_sr=new_sr)
- assert torch.allclose(out, out_j)
-
-
-class TestNormalizeAudio:
-
- def test_clip_wav(self):
- b, c, dur = 2, 1, 4.
- sr = 3
- audio = 10.0 * get_batch_white_noise(b, c, int(sr * dur))
- _clip_wav(audio)
- assert audio.abs().max() <= 1
-
- def test_normalize_audio_clip(self):
- b, c, dur = 2, 1, 4.
- sr = 3
- audio = 10.0 * get_batch_white_noise(b, c, int(sr * dur))
- norm_audio = normalize_audio(audio, strategy='clip')
- assert norm_audio.abs().max() <= 1
-
- def test_normalize_audio_rms(self):
- b, c, dur = 2, 1, 4.
- sr = 3
- audio = 10.0 * get_batch_white_noise(b, c, int(sr * dur))
- norm_audio = normalize_audio(audio, strategy='rms')
- assert norm_audio.abs().max() <= 1
-
- def test_normalize_audio_peak(self):
- b, c, dur = 2, 1, 4.
- sr = 3
- audio = 10.0 * get_batch_white_noise(b, c, int(sr * dur))
- norm_audio = normalize_audio(audio, strategy='peak')
- assert norm_audio.abs().max() <= 1
diff --git a/spaces/abdvl/datahub_qa_bot/docs/managed-datahub/release-notes/v_0_1_69.md b/spaces/abdvl/datahub_qa_bot/docs/managed-datahub/release-notes/v_0_1_69.md
deleted file mode 100644
index 03939a6fe077b629c370a0b295ca7e5061ff62a9..0000000000000000000000000000000000000000
--- a/spaces/abdvl/datahub_qa_bot/docs/managed-datahub/release-notes/v_0_1_69.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# v0.1.69
----
-This is a scheduled release which contains all changes from OSS DataHub upto commit `10a31b1aa08138c616c0e44035f8f843bef13085`. In addition to all the features added in OSS DataHub below are Managed DataHub specific release notes.
-
-Release Availability Date
----
-06 Dec 2022
-
-## Release Changlog
----
-- We now support >10k results in Metadata Test results
\ No newline at end of file
diff --git a/spaces/abdvl/datahub_qa_bot/docs/quick-ingestion-guides/redshift/overview.md b/spaces/abdvl/datahub_qa_bot/docs/quick-ingestion-guides/redshift/overview.md
deleted file mode 100644
index 42d3b91ada192880641bc7af7183efe3181ae67a..0000000000000000000000000000000000000000
--- a/spaces/abdvl/datahub_qa_bot/docs/quick-ingestion-guides/redshift/overview.md
+++ /dev/null
@@ -1,38 +0,0 @@
----
-title: Overview
----
-# Redshift Ingestion Guide: Overview
-
-## What You Will Get Out of This Guide
-
-This guide will help you set up the Redshift connector through the DataHub UI to begin ingesting metadata into DataHub.
-
-Upon completing this guide, you will have a recurring ingestion pipeline that will extract metadata from Redshift and load it into DataHub. This will include to following Redshift asset types:
-
-* Database
-* Schemas (External and Internal)
-* Tables (External and Internal)
-* Views
-
-This recurring ingestion pipeline will also extract:
-
-* **Usage statistics** to help you understand recent query activity
-* **Table-level lineage** (where available) to automatically define interdependencies between datasets
-* **Table- and column-level profile statistics** to help you understand the shape of the data
-
-:::caution
-The source currently can ingest one database with one recipe
-:::
-
-## Next Steps
-
-If that all sounds like what you're looking for, navigate to the [next page](setup.md), where we'll talk about prerequisites
-
-## Advanced Guides and Reference
-
-If you're looking to do something more in-depth, want to use CLI instead of the DataHub UI, or just need to look at the reference documentation for this connector, use these links:
-
-* Learn about CLI Ingestion in the [Introduction to Metadata Ingestion](../../../metadata-ingestion/README.md)
-* [Redshift Ingestion Reference Guide](https://datahubproject.io/docs/generated/ingestion/sources/redshift/#module-redshift)
-
-*Need more help? Join the conversation in [Slack](http://slack.datahubproject.io)!*
diff --git a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/models/roi_heads/double_roi_head.py b/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/models/roi_heads/double_roi_head.py
deleted file mode 100644
index a1aa6c8244a889fbbed312a89574c3e11be294f0..0000000000000000000000000000000000000000
--- a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/models/roi_heads/double_roi_head.py
+++ /dev/null
@@ -1,33 +0,0 @@
-from ..builder import HEADS
-from .standard_roi_head import StandardRoIHead
-
-
-@HEADS.register_module()
-class DoubleHeadRoIHead(StandardRoIHead):
- """RoI head for Double Head RCNN.
-
- https://arxiv.org/abs/1904.06493
- """
-
- def __init__(self, reg_roi_scale_factor, **kwargs):
- super(DoubleHeadRoIHead, self).__init__(**kwargs)
- self.reg_roi_scale_factor = reg_roi_scale_factor
-
- def _bbox_forward(self, x, rois):
- """Box head forward function used in both training and testing time."""
- bbox_cls_feats = self.bbox_roi_extractor(
- x[:self.bbox_roi_extractor.num_inputs], rois)
- bbox_reg_feats = self.bbox_roi_extractor(
- x[:self.bbox_roi_extractor.num_inputs],
- rois,
- roi_scale_factor=self.reg_roi_scale_factor)
- if self.with_shared_head:
- bbox_cls_feats = self.shared_head(bbox_cls_feats)
- bbox_reg_feats = self.shared_head(bbox_reg_feats)
- cls_score, bbox_pred = self.bbox_head(bbox_cls_feats, bbox_reg_feats)
-
- bbox_results = dict(
- cls_score=cls_score,
- bbox_pred=bbox_pred,
- bbox_feats=bbox_cls_feats)
- return bbox_results
diff --git a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet_null/models/losses/utils.py b/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet_null/models/losses/utils.py
deleted file mode 100644
index 4756d7fcefd7cda1294c2662b4ca3e90c0a8e124..0000000000000000000000000000000000000000
--- a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet_null/models/losses/utils.py
+++ /dev/null
@@ -1,100 +0,0 @@
-import functools
-
-import mmcv
-import torch.nn.functional as F
-
-
-def reduce_loss(loss, reduction):
- """Reduce loss as specified.
-
- Args:
- loss (Tensor): Elementwise loss tensor.
- reduction (str): Options are "none", "mean" and "sum".
-
- Return:
- Tensor: Reduced loss tensor.
- """
- reduction_enum = F._Reduction.get_enum(reduction)
- # none: 0, elementwise_mean:1, sum: 2
- if reduction_enum == 0:
- return loss
- elif reduction_enum == 1:
- return loss.mean()
- elif reduction_enum == 2:
- return loss.sum()
-
-
-@mmcv.jit(derivate=True, coderize=True)
-def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
- """Apply element-wise weight and reduce loss.
-
- Args:
- loss (Tensor): Element-wise loss.
- weight (Tensor): Element-wise weights.
- reduction (str): Same as built-in losses of PyTorch.
- avg_factor (float): Avarage factor when computing the mean of losses.
-
- Returns:
- Tensor: Processed loss values.
- """
- # if weight is specified, apply element-wise weight
- if weight is not None:
- loss = loss * weight
-
- # if avg_factor is not specified, just reduce the loss
- if avg_factor is None:
- loss = reduce_loss(loss, reduction)
- else:
- # if reduction is mean, then average the loss by avg_factor
- if reduction == 'mean':
- loss = loss.sum() / avg_factor
- # if reduction is 'none', then do nothing, otherwise raise an error
- elif reduction != 'none':
- raise ValueError('avg_factor can not be used with reduction="sum"')
- return loss
-
-
-def weighted_loss(loss_func):
- """Create a weighted version of a given loss function.
-
- To use this decorator, the loss function must have the signature like
- `loss_func(pred, target, **kwargs)`. The function only needs to compute
- element-wise loss without any reduction. This decorator will add weight
- and reduction arguments to the function. The decorated function will have
- the signature like `loss_func(pred, target, weight=None, reduction='mean',
- avg_factor=None, **kwargs)`.
-
- :Example:
-
- >>> import torch
- >>> @weighted_loss
- >>> def l1_loss(pred, target):
- >>> return (pred - target).abs()
-
- >>> pred = torch.Tensor([0, 2, 3])
- >>> target = torch.Tensor([1, 1, 1])
- >>> weight = torch.Tensor([1, 0, 1])
-
- >>> l1_loss(pred, target)
- tensor(1.3333)
- >>> l1_loss(pred, target, weight)
- tensor(1.)
- >>> l1_loss(pred, target, reduction='none')
- tensor([1., 1., 2.])
- >>> l1_loss(pred, target, weight, avg_factor=2)
- tensor(1.5000)
- """
-
- @functools.wraps(loss_func)
- def wrapper(pred,
- target,
- weight=None,
- reduction='mean',
- avg_factor=None,
- **kwargs):
- # get element-wise loss
- loss = loss_func(pred, target, **kwargs)
- loss = weight_reduce_loss(loss, weight, reduction, avg_factor)
- return loss
-
- return wrapper
diff --git a/spaces/adalbertojunior/image_captioning_portuguese/README.md b/spaces/adalbertojunior/image_captioning_portuguese/README.md
deleted file mode 100644
index f9b300b4779dc9d76f1b492e57de9a319296bc01..0000000000000000000000000000000000000000
--- a/spaces/adalbertojunior/image_captioning_portuguese/README.md
+++ /dev/null
@@ -1,37 +0,0 @@
----
-title: Image_captioning_portuguese
-emoji: 👀
-colorFrom: green
-colorTo: indigo
-sdk: streamlit
-app_file: app.py
-pinned: false
----
-
-# Configuration
-
-`title`: _string_
-Display title for the Space
-
-`emoji`: _string_
-Space emoji (emoji-only character allowed)
-
-`colorFrom`: _string_
-Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
-
-`colorTo`: _string_
-Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
-
-`sdk`: _string_
-Can be either `gradio`, `streamlit`, or `static`
-
-`sdk_version` : _string_
-Only applicable for `streamlit` SDK.
-See [doc](https://hf.co/docs/hub/spaces) for more info on supported versions.
-
-`app_file`: _string_
-Path to your main application file (which contains either `gradio` or `streamlit` Python code, or `static` html code).
-Path is relative to the root of the repository.
-
-`pinned`: _boolean_
-Whether the Space stays on top of your list.
diff --git a/spaces/ahuang11/tastykitchen/app.py b/spaces/ahuang11/tastykitchen/app.py
deleted file mode 100644
index 79fa95b1e19713400dc7e05af14010a3b5bba6a3..0000000000000000000000000000000000000000
--- a/spaces/ahuang11/tastykitchen/app.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from tastymap import TastyKitchen
-
-TastyKitchen().servable()
\ No newline at end of file
diff --git a/spaces/aichina/Pix2Pix-Video/share_btn.py b/spaces/aichina/Pix2Pix-Video/share_btn.py
deleted file mode 100644
index 66e0de15dce2d65f4cd0ef512c7bd8adad0beb77..0000000000000000000000000000000000000000
--- a/spaces/aichina/Pix2Pix-Video/share_btn.py
+++ /dev/null
@@ -1,73 +0,0 @@
-community_icon_html = """"""
-
-loading_icon_html = """"""
-
-share_js = """async () => {
- async function uploadFile(file){
- const UPLOAD_URL = 'https://huggingface.co/uploads';
- const response = await fetch(UPLOAD_URL, {
- method: 'POST',
- headers: {
- 'Content-Type': file.type,
- 'X-Requested-With': 'XMLHttpRequest',
- },
- body: file, /// <- File inherits from Blob
- });
- const url = await response.text();
- return url;
- }
-
- async function getVideoBlobFile(videoEL){
- const res = await fetch(videoEL.src);
- const blob = await res.blob();
- const videoId = Date.now() % 200;
- const fileName = `vid-pix2pix-${{videoId}}.wav`;
- const videoBlob = new File([blob], fileName, { type: 'video/mp4' });
- console.log(videoBlob);
- return videoBlob;
- }
-
- const gradioEl = document.querySelector("gradio-app").shadowRoot || document.querySelector('body > gradio-app');
- const captionTxt = gradioEl.querySelector('#prompt-in textarea').value;
- const inputVidEl = gradioEl.querySelector('#input-vid video');
- const outputVideo = gradioEl.querySelector('#video-output video');
-
-
- const shareBtnEl = gradioEl.querySelector('#share-btn');
- const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
- const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
- if(!outputVideo){
- return;
- };
- shareBtnEl.style.pointerEvents = 'none';
- shareIconEl.style.display = 'none';
- loadingIconEl.style.removeProperty('display');
-
- const inputFile = await getVideoBlobFile(inputVidEl);
- const urlInputVid = await uploadFile(inputFile);
- const videoOutFile = await getVideoBlobFile(outputVideo);
- const dataOutputVid = await uploadFile(videoOutFile);
-
- const descriptionMd = `
-#### Video input:
-${urlInputVid}
-
-#### Pix2Pix result:
-${dataOutputVid}
-`;
- const params = new URLSearchParams({
- title: captionTxt,
- description: descriptionMd,
- });
- const paramsStr = params.toString();
- window.open(`https://huggingface.co/spaces/fffiloni/Pix2Pix-Video/discussions/new?${paramsStr}`, '_blank');
- shareBtnEl.style.removeProperty('pointer-events');
- shareIconEl.style.removeProperty('display');
- loadingIconEl.style.display = 'none';
-}"""
\ No newline at end of file
diff --git a/spaces/akhaliq/Music_Source_Separation/scripts/apply-black.sh b/spaces/akhaliq/Music_Source_Separation/scripts/apply-black.sh
deleted file mode 100644
index db35f6dd4af7f573770b8614f6dd3448a41909d9..0000000000000000000000000000000000000000
--- a/spaces/akhaliq/Music_Source_Separation/scripts/apply-black.sh
+++ /dev/null
@@ -1,3 +0,0 @@
-#!/bin/bash
-python3 -m black bytesep
-
diff --git a/spaces/akhaliq/Real-ESRGAN/scripts/generate_meta_info_pairdata.py b/spaces/akhaliq/Real-ESRGAN/scripts/generate_meta_info_pairdata.py
deleted file mode 100644
index 76dce7e41c803a8055f3627cccb98deb51419b09..0000000000000000000000000000000000000000
--- a/spaces/akhaliq/Real-ESRGAN/scripts/generate_meta_info_pairdata.py
+++ /dev/null
@@ -1,49 +0,0 @@
-import argparse
-import glob
-import os
-
-
-def main(args):
- txt_file = open(args.meta_info, 'w')
- # sca images
- img_paths_gt = sorted(glob.glob(os.path.join(args.input[0], '*')))
- img_paths_lq = sorted(glob.glob(os.path.join(args.input[1], '*')))
-
- assert len(img_paths_gt) == len(img_paths_lq), ('GT folder and LQ folder should have the same length, but got '
- f'{len(img_paths_gt)} and {len(img_paths_lq)}.')
-
- for img_path_gt, img_path_lq in zip(img_paths_gt, img_paths_lq):
- # get the relative paths
- img_name_gt = os.path.relpath(img_path_gt, args.root[0])
- img_name_lq = os.path.relpath(img_path_lq, args.root[1])
- print(f'{img_name_gt}, {img_name_lq}')
- txt_file.write(f'{img_name_gt}, {img_name_lq}\n')
-
-
-if __name__ == '__main__':
- """This script is used to generate meta info (txt file) for paired images.
- """
- parser = argparse.ArgumentParser()
- parser.add_argument(
- '--input',
- nargs='+',
- default=['datasets/DF2K/DIV2K_train_HR_sub', 'datasets/DF2K/DIV2K_train_LR_bicubic_X4_sub'],
- help='Input folder, should be [gt_folder, lq_folder]')
- parser.add_argument('--root', nargs='+', default=[None, None], help='Folder root, will use the ')
- parser.add_argument(
- '--meta_info',
- type=str,
- default='datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt',
- help='txt path for meta info')
- args = parser.parse_args()
-
- assert len(args.input) == 2, 'Input folder should have two elements: gt folder and lq folder'
- assert len(args.root) == 2, 'Root path should have two elements: root for gt folder and lq folder'
- os.makedirs(os.path.dirname(args.meta_info), exist_ok=True)
- for i in range(2):
- if args.input[i].endswith('/'):
- args.input[i] = args.input[i][:-1]
- if args.root[i] is None:
- args.root[i] = os.path.dirname(args.input[i])
-
- main(args)
diff --git a/spaces/akhaliq/SummerTime/evaluation/bleu_metric.py b/spaces/akhaliq/SummerTime/evaluation/bleu_metric.py
deleted file mode 100644
index ea6c0b5730d647aacca797ff5303c74b8e7517fb..0000000000000000000000000000000000000000
--- a/spaces/akhaliq/SummerTime/evaluation/bleu_metric.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from summ_eval.bleu_metric import BleuMetric
-from evaluation.summeval_metric import SummEvalMetric
-from typing import List, Dict
-
-
-class Bleu(SummEvalMetric):
- metric_name = "bleu"
- range = (0, 100)
- higher_is_better = True
- requires_heavy_compute = False
-
- def __init__(self):
- se_metric = BleuMetric()
- super(Bleu, self).__init__(se_metric)
-
- def evaluate(
- self, inputs: List[str], targets: List[str], keys: List[str] = ["bleu"]
- ) -> Dict[str, float]:
- # TODO zhangir: potentially update when dataset api is merged.
- return super(Bleu, self).evaluate(inputs, targets, keys)
diff --git a/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_vendor/rich/pretty.py b/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_vendor/rich/pretty.py
deleted file mode 100644
index 606ee33822aff7db27086df4da06d732dcd181b4..0000000000000000000000000000000000000000
--- a/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_vendor/rich/pretty.py
+++ /dev/null
@@ -1,903 +0,0 @@
-import builtins
-import dataclasses
-import inspect
-import os
-import re
-import sys
-from array import array
-from collections import Counter, UserDict, UserList, defaultdict, deque
-from dataclasses import dataclass, fields, is_dataclass
-from inspect import isclass
-from itertools import islice
-from types import MappingProxyType
-from typing import (
- TYPE_CHECKING,
- Any,
- Callable,
- DefaultDict,
- Dict,
- Iterable,
- List,
- Optional,
- Set,
- Tuple,
- Union,
-)
-
-from pip._vendor.rich.repr import RichReprResult
-
-try:
- import attr as _attr_module
-except ImportError: # pragma: no cover
- _attr_module = None # type: ignore
-
-
-from . import get_console
-from ._loop import loop_last
-from ._pick import pick_bool
-from .abc import RichRenderable
-from .cells import cell_len
-from .highlighter import ReprHighlighter
-from .jupyter import JupyterMixin, JupyterRenderable
-from .measure import Measurement
-from .text import Text
-
-if TYPE_CHECKING:
- from .console import (
- Console,
- ConsoleOptions,
- HighlighterType,
- JustifyMethod,
- OverflowMethod,
- RenderResult,
- )
-
-
-def _is_attr_object(obj: Any) -> bool:
- """Check if an object was created with attrs module."""
- return _attr_module is not None and _attr_module.has(type(obj))
-
-
-def _get_attr_fields(obj: Any) -> Iterable["_attr_module.Attribute[Any]"]:
- """Get fields for an attrs object."""
- return _attr_module.fields(type(obj)) if _attr_module is not None else []
-
-
-def _is_dataclass_repr(obj: object) -> bool:
- """Check if an instance of a dataclass contains the default repr.
-
- Args:
- obj (object): A dataclass instance.
-
- Returns:
- bool: True if the default repr is used, False if there is a custom repr.
- """
- # Digging in to a lot of internals here
- # Catching all exceptions in case something is missing on a non CPython implementation
- try:
- return obj.__repr__.__code__.co_filename == dataclasses.__file__
- except Exception: # pragma: no coverage
- return False
-
-
-def _ipy_display_hook(
- value: Any,
- console: Optional["Console"] = None,
- overflow: "OverflowMethod" = "ignore",
- crop: bool = False,
- indent_guides: bool = False,
- max_length: Optional[int] = None,
- max_string: Optional[int] = None,
- expand_all: bool = False,
-) -> None:
- from .console import ConsoleRenderable # needed here to prevent circular import
-
- # always skip rich generated jupyter renderables or None values
- if isinstance(value, JupyterRenderable) or value is None:
- return
-
- console = console or get_console()
- if console.is_jupyter:
- # Delegate rendering to IPython if the object (and IPython) supports it
- # https://ipython.readthedocs.io/en/stable/config/integrating.html#rich-display
- ipython_repr_methods = [
- "_repr_html_",
- "_repr_markdown_",
- "_repr_json_",
- "_repr_latex_",
- "_repr_jpeg_",
- "_repr_png_",
- "_repr_svg_",
- "_repr_mimebundle_",
- ]
- for repr_method in ipython_repr_methods:
- method = getattr(value, repr_method, None)
- if inspect.ismethod(method):
- # Calling the method ourselves isn't ideal. The interface for the `_repr_*_` methods
- # specifies that if they return None, then they should not be rendered
- # by the notebook.
- try:
- repr_result = method()
- except Exception:
- continue # If the method raises, treat it as if it doesn't exist, try any others
- if repr_result is not None:
- return # Delegate rendering to IPython
-
- # certain renderables should start on a new line
- if isinstance(value, ConsoleRenderable):
- console.line()
-
- console.print(
- value
- if isinstance(value, RichRenderable)
- else Pretty(
- value,
- overflow=overflow,
- indent_guides=indent_guides,
- max_length=max_length,
- max_string=max_string,
- expand_all=expand_all,
- margin=12,
- ),
- crop=crop,
- new_line_start=True,
- )
-
-
-def install(
- console: Optional["Console"] = None,
- overflow: "OverflowMethod" = "ignore",
- crop: bool = False,
- indent_guides: bool = False,
- max_length: Optional[int] = None,
- max_string: Optional[int] = None,
- expand_all: bool = False,
-) -> None:
- """Install automatic pretty printing in the Python REPL.
-
- Args:
- console (Console, optional): Console instance or ``None`` to use global console. Defaults to None.
- overflow (Optional[OverflowMethod], optional): Overflow method. Defaults to "ignore".
- crop (Optional[bool], optional): Enable cropping of long lines. Defaults to False.
- indent_guides (bool, optional): Enable indentation guides. Defaults to False.
- max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
- Defaults to None.
- max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.
- expand_all (bool, optional): Expand all containers. Defaults to False.
- max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
- """
- from pip._vendor.rich import get_console
-
- console = console or get_console()
- assert console is not None
-
- def display_hook(value: Any) -> None:
- """Replacement sys.displayhook which prettifies objects with Rich."""
- if value is not None:
- assert console is not None
- builtins._ = None # type: ignore
- console.print(
- value
- if isinstance(value, RichRenderable)
- else Pretty(
- value,
- overflow=overflow,
- indent_guides=indent_guides,
- max_length=max_length,
- max_string=max_string,
- expand_all=expand_all,
- ),
- crop=crop,
- )
- builtins._ = value # type: ignore
-
- try: # pragma: no cover
- ip = get_ipython() # type: ignore
- from IPython.core.formatters import BaseFormatter
-
- class RichFormatter(BaseFormatter): # type: ignore
- pprint: bool = True
-
- def __call__(self, value: Any) -> Any:
- if self.pprint:
- return _ipy_display_hook(
- value,
- console=get_console(),
- overflow=overflow,
- indent_guides=indent_guides,
- max_length=max_length,
- max_string=max_string,
- expand_all=expand_all,
- )
- else:
- return repr(value)
-
- # replace plain text formatter with rich formatter
- rich_formatter = RichFormatter()
- ip.display_formatter.formatters["text/plain"] = rich_formatter
- except Exception:
- sys.displayhook = display_hook
-
-
-class Pretty(JupyterMixin):
- """A rich renderable that pretty prints an object.
-
- Args:
- _object (Any): An object to pretty print.
- highlighter (HighlighterType, optional): Highlighter object to apply to result, or None for ReprHighlighter. Defaults to None.
- indent_size (int, optional): Number of spaces in indent. Defaults to 4.
- justify (JustifyMethod, optional): Justify method, or None for default. Defaults to None.
- overflow (OverflowMethod, optional): Overflow method, or None for default. Defaults to None.
- no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to False.
- indent_guides (bool, optional): Enable indentation guides. Defaults to False.
- max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
- Defaults to None.
- max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.
- max_depth (int, optional): Maximum depth of nested data structures, or None for no maximum. Defaults to None.
- expand_all (bool, optional): Expand all containers. Defaults to False.
- margin (int, optional): Subtrace a margin from width to force containers to expand earlier. Defaults to 0.
- insert_line (bool, optional): Insert a new line if the output has multiple new lines. Defaults to False.
- """
-
- def __init__(
- self,
- _object: Any,
- highlighter: Optional["HighlighterType"] = None,
- *,
- indent_size: int = 4,
- justify: Optional["JustifyMethod"] = None,
- overflow: Optional["OverflowMethod"] = None,
- no_wrap: Optional[bool] = False,
- indent_guides: bool = False,
- max_length: Optional[int] = None,
- max_string: Optional[int] = None,
- max_depth: Optional[int] = None,
- expand_all: bool = False,
- margin: int = 0,
- insert_line: bool = False,
- ) -> None:
- self._object = _object
- self.highlighter = highlighter or ReprHighlighter()
- self.indent_size = indent_size
- self.justify: Optional["JustifyMethod"] = justify
- self.overflow: Optional["OverflowMethod"] = overflow
- self.no_wrap = no_wrap
- self.indent_guides = indent_guides
- self.max_length = max_length
- self.max_string = max_string
- self.max_depth = max_depth
- self.expand_all = expand_all
- self.margin = margin
- self.insert_line = insert_line
-
- def __rich_console__(
- self, console: "Console", options: "ConsoleOptions"
- ) -> "RenderResult":
- pretty_str = pretty_repr(
- self._object,
- max_width=options.max_width - self.margin,
- indent_size=self.indent_size,
- max_length=self.max_length,
- max_string=self.max_string,
- max_depth=self.max_depth,
- expand_all=self.expand_all,
- )
- pretty_text = Text(
- pretty_str,
- justify=self.justify or options.justify,
- overflow=self.overflow or options.overflow,
- no_wrap=pick_bool(self.no_wrap, options.no_wrap),
- style="pretty",
- )
- pretty_text = (
- self.highlighter(pretty_text)
- if pretty_text
- else Text(
- f"{type(self._object)}.__repr__ returned empty string",
- style="dim italic",
- )
- )
- if self.indent_guides and not options.ascii_only:
- pretty_text = pretty_text.with_indent_guides(
- self.indent_size, style="repr.indent"
- )
- if self.insert_line and "\n" in pretty_text:
- yield ""
- yield pretty_text
-
- def __rich_measure__(
- self, console: "Console", options: "ConsoleOptions"
- ) -> "Measurement":
- pretty_str = pretty_repr(
- self._object,
- max_width=options.max_width,
- indent_size=self.indent_size,
- max_length=self.max_length,
- max_string=self.max_string,
- )
- text_width = (
- max(cell_len(line) for line in pretty_str.splitlines()) if pretty_str else 0
- )
- return Measurement(text_width, text_width)
-
-
-def _get_braces_for_defaultdict(_object: DefaultDict[Any, Any]) -> Tuple[str, str, str]:
- return (
- f"defaultdict({_object.default_factory!r}, {{",
- "})",
- f"defaultdict({_object.default_factory!r}, {{}})",
- )
-
-
-def _get_braces_for_array(_object: "array[Any]") -> Tuple[str, str, str]:
- return (f"array({_object.typecode!r}, [", "])", "array({_object.typecode!r})")
-
-
-_BRACES: Dict[type, Callable[[Any], Tuple[str, str, str]]] = {
- os._Environ: lambda _object: ("environ({", "})", "environ({})"),
- array: _get_braces_for_array,
- defaultdict: _get_braces_for_defaultdict,
- Counter: lambda _object: ("Counter({", "})", "Counter()"),
- deque: lambda _object: ("deque([", "])", "deque()"),
- dict: lambda _object: ("{", "}", "{}"),
- UserDict: lambda _object: ("{", "}", "{}"),
- frozenset: lambda _object: ("frozenset({", "})", "frozenset()"),
- list: lambda _object: ("[", "]", "[]"),
- UserList: lambda _object: ("[", "]", "[]"),
- set: lambda _object: ("{", "}", "set()"),
- tuple: lambda _object: ("(", ")", "()"),
- MappingProxyType: lambda _object: ("mappingproxy({", "})", "mappingproxy({})"),
-}
-_CONTAINERS = tuple(_BRACES.keys())
-_MAPPING_CONTAINERS = (dict, os._Environ, MappingProxyType, UserDict)
-
-
-def is_expandable(obj: Any) -> bool:
- """Check if an object may be expanded by pretty print."""
- return (
- isinstance(obj, _CONTAINERS)
- or (is_dataclass(obj))
- or (hasattr(obj, "__rich_repr__"))
- or _is_attr_object(obj)
- ) and not isclass(obj)
-
-
-@dataclass
-class Node:
- """A node in a repr tree. May be atomic or a container."""
-
- key_repr: str = ""
- value_repr: str = ""
- open_brace: str = ""
- close_brace: str = ""
- empty: str = ""
- last: bool = False
- is_tuple: bool = False
- children: Optional[List["Node"]] = None
- key_separator = ": "
- separator: str = ", "
-
- def iter_tokens(self) -> Iterable[str]:
- """Generate tokens for this node."""
- if self.key_repr:
- yield self.key_repr
- yield self.key_separator
- if self.value_repr:
- yield self.value_repr
- elif self.children is not None:
- if self.children:
- yield self.open_brace
- if self.is_tuple and len(self.children) == 1:
- yield from self.children[0].iter_tokens()
- yield ","
- else:
- for child in self.children:
- yield from child.iter_tokens()
- if not child.last:
- yield self.separator
- yield self.close_brace
- else:
- yield self.empty
-
- def check_length(self, start_length: int, max_length: int) -> bool:
- """Check the length fits within a limit.
-
- Args:
- start_length (int): Starting length of the line (indent, prefix, suffix).
- max_length (int): Maximum length.
-
- Returns:
- bool: True if the node can be rendered within max length, otherwise False.
- """
- total_length = start_length
- for token in self.iter_tokens():
- total_length += cell_len(token)
- if total_length > max_length:
- return False
- return True
-
- def __str__(self) -> str:
- repr_text = "".join(self.iter_tokens())
- return repr_text
-
- def render(
- self, max_width: int = 80, indent_size: int = 4, expand_all: bool = False
- ) -> str:
- """Render the node to a pretty repr.
-
- Args:
- max_width (int, optional): Maximum width of the repr. Defaults to 80.
- indent_size (int, optional): Size of indents. Defaults to 4.
- expand_all (bool, optional): Expand all levels. Defaults to False.
-
- Returns:
- str: A repr string of the original object.
- """
- lines = [_Line(node=self, is_root=True)]
- line_no = 0
- while line_no < len(lines):
- line = lines[line_no]
- if line.expandable and not line.expanded:
- if expand_all or not line.check_length(max_width):
- lines[line_no : line_no + 1] = line.expand(indent_size)
- line_no += 1
-
- repr_str = "\n".join(str(line) for line in lines)
- return repr_str
-
-
-@dataclass
-class _Line:
- """A line in repr output."""
-
- parent: Optional["_Line"] = None
- is_root: bool = False
- node: Optional[Node] = None
- text: str = ""
- suffix: str = ""
- whitespace: str = ""
- expanded: bool = False
- last: bool = False
-
- @property
- def expandable(self) -> bool:
- """Check if the line may be expanded."""
- return bool(self.node is not None and self.node.children)
-
- def check_length(self, max_length: int) -> bool:
- """Check this line fits within a given number of cells."""
- start_length = (
- len(self.whitespace) + cell_len(self.text) + cell_len(self.suffix)
- )
- assert self.node is not None
- return self.node.check_length(start_length, max_length)
-
- def expand(self, indent_size: int) -> Iterable["_Line"]:
- """Expand this line by adding children on their own line."""
- node = self.node
- assert node is not None
- whitespace = self.whitespace
- assert node.children
- if node.key_repr:
- new_line = yield _Line(
- text=f"{node.key_repr}{node.key_separator}{node.open_brace}",
- whitespace=whitespace,
- )
- else:
- new_line = yield _Line(text=node.open_brace, whitespace=whitespace)
- child_whitespace = self.whitespace + " " * indent_size
- tuple_of_one = node.is_tuple and len(node.children) == 1
- for last, child in loop_last(node.children):
- separator = "," if tuple_of_one else node.separator
- line = _Line(
- parent=new_line,
- node=child,
- whitespace=child_whitespace,
- suffix=separator,
- last=last and not tuple_of_one,
- )
- yield line
-
- yield _Line(
- text=node.close_brace,
- whitespace=whitespace,
- suffix=self.suffix,
- last=self.last,
- )
-
- def __str__(self) -> str:
- if self.last:
- return f"{self.whitespace}{self.text}{self.node or ''}"
- else:
- return (
- f"{self.whitespace}{self.text}{self.node or ''}{self.suffix.rstrip()}"
- )
-
-
-def traverse(
- _object: Any,
- max_length: Optional[int] = None,
- max_string: Optional[int] = None,
- max_depth: Optional[int] = None,
-) -> Node:
- """Traverse object and generate a tree.
-
- Args:
- _object (Any): Object to be traversed.
- max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
- Defaults to None.
- max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.
- Defaults to None.
- max_depth (int, optional): Maximum depth of data structures, or None for no maximum.
- Defaults to None.
-
- Returns:
- Node: The root of a tree structure which can be used to render a pretty repr.
- """
-
- def to_repr(obj: Any) -> str:
- """Get repr string for an object, but catch errors."""
- if (
- max_string is not None
- and isinstance(obj, (bytes, str))
- and len(obj) > max_string
- ):
- truncated = len(obj) - max_string
- obj_repr = f"{obj[:max_string]!r}+{truncated}"
- else:
- try:
- obj_repr = repr(obj)
- except Exception as error:
- obj_repr = f""
- return obj_repr
-
- visited_ids: Set[int] = set()
- push_visited = visited_ids.add
- pop_visited = visited_ids.remove
-
- def _traverse(obj: Any, root: bool = False, depth: int = 0) -> Node:
- """Walk the object depth first."""
-
- obj_type = type(obj)
- py_version = (sys.version_info.major, sys.version_info.minor)
- children: List[Node]
- reached_max_depth = max_depth is not None and depth >= max_depth
-
- def iter_rich_args(rich_args: Any) -> Iterable[Union[Any, Tuple[str, Any]]]:
- for arg in rich_args:
- if isinstance(arg, tuple):
- if len(arg) == 3:
- key, child, default = arg
- if default == child:
- continue
- yield key, child
- elif len(arg) == 2:
- key, child = arg
- yield key, child
- elif len(arg) == 1:
- yield arg[0]
- else:
- yield arg
-
- try:
- fake_attributes = hasattr(
- obj, "awehoi234_wdfjwljet234_234wdfoijsdfmmnxpi492"
- )
- except Exception:
- fake_attributes = False
-
- rich_repr_result: Optional[RichReprResult] = None
- if not fake_attributes:
- try:
- if hasattr(obj, "__rich_repr__") and not isclass(obj):
- rich_repr_result = obj.__rich_repr__()
- except Exception:
- pass
-
- if rich_repr_result is not None:
- angular = getattr(obj.__rich_repr__, "angular", False)
- args = list(iter_rich_args(rich_repr_result))
- class_name = obj.__class__.__name__
-
- if args:
- children = []
- append = children.append
-
- if reached_max_depth:
- node = Node(value_repr=f"...")
- else:
- if angular:
- node = Node(
- open_brace=f"<{class_name} ",
- close_brace=">",
- children=children,
- last=root,
- separator=" ",
- )
- else:
- node = Node(
- open_brace=f"{class_name}(",
- close_brace=")",
- children=children,
- last=root,
- )
- for last, arg in loop_last(args):
- if isinstance(arg, tuple):
- key, child = arg
- child_node = _traverse(child, depth=depth + 1)
- child_node.last = last
- child_node.key_repr = key
- child_node.key_separator = "="
- append(child_node)
- else:
- child_node = _traverse(arg, depth=depth + 1)
- child_node.last = last
- append(child_node)
- else:
- node = Node(
- value_repr=f"<{class_name}>" if angular else f"{class_name}()",
- children=[],
- last=root,
- )
- elif _is_attr_object(obj) and not fake_attributes:
- children = []
- append = children.append
-
- attr_fields = _get_attr_fields(obj)
- if attr_fields:
- if reached_max_depth:
- node = Node(value_repr=f"...")
- else:
- node = Node(
- open_brace=f"{obj.__class__.__name__}(",
- close_brace=")",
- children=children,
- last=root,
- )
-
- def iter_attrs() -> Iterable[
- Tuple[str, Any, Optional[Callable[[Any], str]]]
- ]:
- """Iterate over attr fields and values."""
- for attr in attr_fields:
- if attr.repr:
- try:
- value = getattr(obj, attr.name)
- except Exception as error:
- # Can happen, albeit rarely
- yield (attr.name, error, None)
- else:
- yield (
- attr.name,
- value,
- attr.repr if callable(attr.repr) else None,
- )
-
- for last, (name, value, repr_callable) in loop_last(iter_attrs()):
- if repr_callable:
- child_node = Node(value_repr=str(repr_callable(value)))
- else:
- child_node = _traverse(value, depth=depth + 1)
- child_node.last = last
- child_node.key_repr = name
- child_node.key_separator = "="
- append(child_node)
- else:
- node = Node(
- value_repr=f"{obj.__class__.__name__}()", children=[], last=root
- )
-
- elif (
- is_dataclass(obj)
- and not isinstance(obj, type)
- and not fake_attributes
- and (_is_dataclass_repr(obj) or py_version == (3, 6))
- ):
- obj_id = id(obj)
- if obj_id in visited_ids:
- # Recursion detected
- return Node(value_repr="...")
- push_visited(obj_id)
-
- children = []
- append = children.append
- if reached_max_depth:
- node = Node(value_repr=f"...")
- else:
- node = Node(
- open_brace=f"{obj.__class__.__name__}(",
- close_brace=")",
- children=children,
- last=root,
- )
-
- for last, field in loop_last(
- field for field in fields(obj) if field.repr
- ):
- child_node = _traverse(getattr(obj, field.name), depth=depth + 1)
- child_node.key_repr = field.name
- child_node.last = last
- child_node.key_separator = "="
- append(child_node)
-
- pop_visited(obj_id)
-
- elif isinstance(obj, _CONTAINERS):
- for container_type in _CONTAINERS:
- if isinstance(obj, container_type):
- obj_type = container_type
- break
-
- obj_id = id(obj)
- if obj_id in visited_ids:
- # Recursion detected
- return Node(value_repr="...")
- push_visited(obj_id)
-
- open_brace, close_brace, empty = _BRACES[obj_type](obj)
-
- if reached_max_depth:
- node = Node(value_repr=f"...", last=root)
- elif obj_type.__repr__ != type(obj).__repr__:
- node = Node(value_repr=to_repr(obj), last=root)
- elif obj:
- children = []
- node = Node(
- open_brace=open_brace,
- close_brace=close_brace,
- children=children,
- last=root,
- )
- append = children.append
- num_items = len(obj)
- last_item_index = num_items - 1
-
- if isinstance(obj, _MAPPING_CONTAINERS):
- iter_items = iter(obj.items())
- if max_length is not None:
- iter_items = islice(iter_items, max_length)
- for index, (key, child) in enumerate(iter_items):
- child_node = _traverse(child, depth=depth + 1)
- child_node.key_repr = to_repr(key)
- child_node.last = index == last_item_index
- append(child_node)
- else:
- iter_values = iter(obj)
- if max_length is not None:
- iter_values = islice(iter_values, max_length)
- for index, child in enumerate(iter_values):
- child_node = _traverse(child, depth=depth + 1)
- child_node.last = index == last_item_index
- append(child_node)
- if max_length is not None and num_items > max_length:
- append(Node(value_repr=f"... +{num_items-max_length}", last=True))
- else:
- node = Node(empty=empty, children=[], last=root)
-
- pop_visited(obj_id)
- else:
- node = Node(value_repr=to_repr(obj), last=root)
- node.is_tuple = isinstance(obj, tuple)
- return node
-
- node = _traverse(_object, root=True)
- return node
-
-
-def pretty_repr(
- _object: Any,
- *,
- max_width: int = 80,
- indent_size: int = 4,
- max_length: Optional[int] = None,
- max_string: Optional[int] = None,
- max_depth: Optional[int] = None,
- expand_all: bool = False,
-) -> str:
- """Prettify repr string by expanding on to new lines to fit within a given width.
-
- Args:
- _object (Any): Object to repr.
- max_width (int, optional): Desired maximum width of repr string. Defaults to 80.
- indent_size (int, optional): Number of spaces to indent. Defaults to 4.
- max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
- Defaults to None.
- max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.
- Defaults to None.
- max_depth (int, optional): Maximum depth of nested data structure, or None for no depth.
- Defaults to None.
- expand_all (bool, optional): Expand all containers regardless of available width. Defaults to False.
-
- Returns:
- str: A possibly multi-line representation of the object.
- """
-
- if isinstance(_object, Node):
- node = _object
- else:
- node = traverse(
- _object, max_length=max_length, max_string=max_string, max_depth=max_depth
- )
- repr_str = node.render(
- max_width=max_width, indent_size=indent_size, expand_all=expand_all
- )
- return repr_str
-
-
-def pprint(
- _object: Any,
- *,
- console: Optional["Console"] = None,
- indent_guides: bool = True,
- max_length: Optional[int] = None,
- max_string: Optional[int] = None,
- max_depth: Optional[int] = None,
- expand_all: bool = False,
-) -> None:
- """A convenience function for pretty printing.
-
- Args:
- _object (Any): Object to pretty print.
- console (Console, optional): Console instance, or None to use default. Defaults to None.
- max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
- Defaults to None.
- max_string (int, optional): Maximum length of strings before truncating, or None to disable. Defaults to None.
- max_depth (int, optional): Maximum depth for nested data structures, or None for unlimited depth. Defaults to None.
- indent_guides (bool, optional): Enable indentation guides. Defaults to True.
- expand_all (bool, optional): Expand all containers. Defaults to False.
- """
- _console = get_console() if console is None else console
- _console.print(
- Pretty(
- _object,
- max_length=max_length,
- max_string=max_string,
- max_depth=max_depth,
- indent_guides=indent_guides,
- expand_all=expand_all,
- overflow="ignore",
- ),
- soft_wrap=True,
- )
-
-
-if __name__ == "__main__": # pragma: no cover
-
- class BrokenRepr:
- def __repr__(self) -> str:
- 1 / 0
- return "this will fail"
-
- d = defaultdict(int)
- d["foo"] = 5
- data = {
- "foo": [
- 1,
- "Hello World!",
- 100.123,
- 323.232,
- 432324.0,
- {5, 6, 7, (1, 2, 3, 4), 8},
- ],
- "bar": frozenset({1, 2, 3}),
- "defaultdict": defaultdict(
- list, {"crumble": ["apple", "rhubarb", "butter", "sugar", "flour"]}
- ),
- "counter": Counter(
- [
- "apple",
- "orange",
- "pear",
- "kumquat",
- "kumquat",
- "durian" * 100,
- ]
- ),
- "atomic": (False, True, None),
- "Broken": BrokenRepr(),
- }
- data["foo"].append(data) # type: ignore
-
- from pip._vendor.rich import print
-
- print(Pretty(data, indent_guides=True, max_string=20))
diff --git a/spaces/allknowingroger/Image-Models-Test145/README.md b/spaces/allknowingroger/Image-Models-Test145/README.md
deleted file mode 100644
index a3a43bf672ca727d8113068aed4ea790c9de9309..0000000000000000000000000000000000000000
--- a/spaces/allknowingroger/Image-Models-Test145/README.md
+++ /dev/null
@@ -1,12 +0,0 @@
----
-title: More Image Models
-emoji: 😻
-colorFrom: red
-colorTo: gray
-sdk: gradio
-sdk_version: 3.23.0
-app_file: app.py
-duplicated_from: allknowingroger/Image-Models-Test142
----
-
-
\ No newline at end of file
diff --git a/spaces/alphunt/diffdock-alphunt-demo/utils/geometry.py b/spaces/alphunt/diffdock-alphunt-demo/utils/geometry.py
deleted file mode 100644
index 0b54bbea5b258e72cd10aaf317a946a1794a1af5..0000000000000000000000000000000000000000
--- a/spaces/alphunt/diffdock-alphunt-demo/utils/geometry.py
+++ /dev/null
@@ -1,123 +0,0 @@
-import math
-
-import torch
-
-
-def quaternion_to_matrix(quaternions):
- """
- From https://pytorch3d.readthedocs.io/en/latest/_modules/pytorch3d/transforms/rotation_conversions.html
- Convert rotations given as quaternions to rotation matrices.
-
- Args:
- quaternions: quaternions with real part first,
- as tensor of shape (..., 4).
-
- Returns:
- Rotation matrices as tensor of shape (..., 3, 3).
- """
- r, i, j, k = torch.unbind(quaternions, -1)
- two_s = 2.0 / (quaternions * quaternions).sum(-1)
-
- o = torch.stack(
- (
- 1 - two_s * (j * j + k * k),
- two_s * (i * j - k * r),
- two_s * (i * k + j * r),
- two_s * (i * j + k * r),
- 1 - two_s * (i * i + k * k),
- two_s * (j * k - i * r),
- two_s * (i * k - j * r),
- two_s * (j * k + i * r),
- 1 - two_s * (i * i + j * j),
- ),
- -1,
- )
- return o.reshape(quaternions.shape[:-1] + (3, 3))
-
-
-def axis_angle_to_quaternion(axis_angle):
- """
- From https://pytorch3d.readthedocs.io/en/latest/_modules/pytorch3d/transforms/rotation_conversions.html
- Convert rotations given as axis/angle to quaternions.
-
- Args:
- axis_angle: Rotations given as a vector in axis angle form,
- as a tensor of shape (..., 3), where the magnitude is
- the angle turned anticlockwise in radians around the
- vector's direction.
-
- Returns:
- quaternions with real part first, as tensor of shape (..., 4).
- """
- angles = torch.norm(axis_angle, p=2, dim=-1, keepdim=True)
- half_angles = 0.5 * angles
- eps = 1e-6
- small_angles = angles.abs() < eps
- sin_half_angles_over_angles = torch.empty_like(angles)
- sin_half_angles_over_angles[~small_angles] = (
- torch.sin(half_angles[~small_angles]) / angles[~small_angles]
- )
- # for x small, sin(x/2) is about x/2 - (x/2)^3/6
- # so sin(x/2)/x is about 1/2 - (x*x)/48
- sin_half_angles_over_angles[small_angles] = (
- 0.5 - (angles[small_angles] * angles[small_angles]) / 48
- )
- quaternions = torch.cat(
- [torch.cos(half_angles), axis_angle * sin_half_angles_over_angles], dim=-1
- )
- return quaternions
-
-
-def axis_angle_to_matrix(axis_angle):
- """
- From https://pytorch3d.readthedocs.io/en/latest/_modules/pytorch3d/transforms/rotation_conversions.html
- Convert rotations given as axis/angle to rotation matrices.
-
- Args:
- axis_angle: Rotations given as a vector in axis angle form,
- as a tensor of shape (..., 3), where the magnitude is
- the angle turned anticlockwise in radians around the
- vector's direction.
-
- Returns:
- Rotation matrices as tensor of shape (..., 3, 3).
- """
- return quaternion_to_matrix(axis_angle_to_quaternion(axis_angle))
-
-
-def rigid_transform_Kabsch_3D_torch(A, B):
- # R = 3x3 rotation matrix, t = 3x1 column vector
- # This already takes residue identity into account.
-
- assert A.shape[1] == B.shape[1]
- num_rows, num_cols = A.shape
- if num_rows != 3:
- raise Exception(f"matrix A is not 3xN, it is {num_rows}x{num_cols}")
- num_rows, num_cols = B.shape
- if num_rows != 3:
- raise Exception(f"matrix B is not 3xN, it is {num_rows}x{num_cols}")
-
-
- # find mean column wise: 3 x 1
- centroid_A = torch.mean(A, axis=1, keepdims=True)
- centroid_B = torch.mean(B, axis=1, keepdims=True)
-
- # subtract mean
- Am = A - centroid_A
- Bm = B - centroid_B
-
- H = Am @ Bm.T
-
- # find rotation
- U, S, Vt = torch.linalg.svd(H)
-
- R = Vt.T @ U.T
- # special reflection case
- if torch.linalg.det(R) < 0:
- # print("det(R) < R, reflection detected!, correcting for it ...")
- SS = torch.diag(torch.tensor([1.,1.,-1.], device=A.device))
- R = (Vt.T @ SS) @ U.T
- assert math.fabs(torch.linalg.det(R) - 1) < 3e-3 # note I had to change this error bound to be higher
-
- t = -R @ centroid_A + centroid_B
- return R, t
diff --git a/spaces/amagastya/SPARK/app/sequential_transform_chain.py b/spaces/amagastya/SPARK/app/sequential_transform_chain.py
deleted file mode 100644
index 774e9b24b1ec4045c3202d6c4de60390d858fbed..0000000000000000000000000000000000000000
--- a/spaces/amagastya/SPARK/app/sequential_transform_chain.py
+++ /dev/null
@@ -1,146 +0,0 @@
-import os
-from langchain.embeddings.cohere import CohereEmbeddings
-from langchain.vectorstores import Pinecone
-from langchain.chains import ConversationalRetrievalChain
-from langchain.chat_models import ChatOpenAI
-import pinecone
-import chainlit as cl
-from langchain.memory import ConversationBufferMemory
-from langchain.prompts import (
- ChatPromptTemplate,
- PromptTemplate,
- SystemMessagePromptTemplate,
- HumanMessagePromptTemplate,
-)
-from langchain.prompts.prompt import PromptTemplate
-
-pinecone.init(
- api_key=os.environ.get("PINECONE_API_KEY"),
- environment=os.environ.get("PINECONE_ENV"),
-)
-from langchain.chains import LLMChain, TransformChain, SequentialChain
-
-from chainlit import on_message, on_chat_start
-
-index_name = "spark"
-
-# Optional
-namespace = None
-
-embeddings = CohereEmbeddings(model='embed-english-light-v2.0',cohere_api_key=os.environ.get("COHERE_API_KEY"))
-
-llm = ChatOpenAI(temperature=0.7, verbose=True)
-
-docsearch = Pinecone.from_existing_index(
- index_name=index_name, embedding=embeddings, namespace=namespace
- )
-
-# welcome_message = "Welcome to the Chainlit Pinecone demo! Ask anything about documents you vectorized and stored in your Pinecone DB."
-memory = ConversationBufferMemory(llm=llm, input_key='question',memory_key='chat_history',return_messages=True)
-_template = """Below is a summary of the conversation so far, and a new question asked by the user that needs to be answered by searching in a knowledge base. Generate a search query based on the conversation and the new question.
-Don't generate the search query if the user is conversing generally or engaging in small talk. In which case just return the original question.
-Chat History:
-{chat_history}
-
-Question:
-{question}
-
-Remember - Don't change the search query from the user's question if user is engaging in small talk.
-Search query:
-"""
-CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template)
-
-spark = """You are SPARK, a Prompt Engineering Assistant. SPARK stands for Smart Prompt Assistant and Resource Knowledgebase.
-
-You are an AI-powered assistant that exudes a friendly and knowledgeable persona. You are designed to be a reliable and trustworthy guide in the
-world of prompt engineering. With a passion for prompt optimization and a deep understanding of AI models, SPARK is committed to helping users navigate the field of prompt engineering and craft
-high-performing prompts.
-
-Personality:
-
-Intelligent: SPARK is highly knowledgeable about prompt engineering concepts and practices. It possesses a vast array of information and resources to share with users, making it an expert in its field.
-
-Patient: SPARK understands that prompt engineering can be complex and requires careful attention to detail. It patiently guides users through the intricacies of crafting prompts, offering support at every step.
-
-Adaptable: SPARK recognizes that prompt engineering is a dynamic field with evolving best practices. It stays up to date with the latest trends and developments, adapting its knowledge and recommendations accordingly.
-
-Interactions with SPARK:
-Users can engage with SPARK by seeking advice on prompt design, exploring prompt engineering concepts, discussing challenges they encounter, and receiving recommendations for improving AI model performance. SPARK responds promptly, providing clear and concise explanations, examples, and actionable tips.
-
-Important:
-Answer with the facts listed in the list of sources below. If there isn't enough information below, say you don't know. If asking a clarifying question to the user would help, ask the question.
-
-Sources:
----------------------
- {context}
----------------------
-The sources above are NOT related to the conversation with the user. Ignore the sources if user is engaging in small talk.
-"""
-question_gen_prompt = PromptTemplate(template=_template, input_variables=["question", "chat_history"] )
-
-@on_chat_start
-def init():
- memory.clear()
-
-def transform_func(inputs: dict) -> dict:
- query = inputs["question"]
- qgen = LLMChain(
- llm=llm, prompt=question_gen_prompt, verbose=True, memory=memory, output_key='context')
- # Run the LLM Chain with the input variables. Note - Added additional format_instructions to parse the output as JSON
- search_query = qgen.predict(question=query)
- result = docsearch.similarity_search(search_query)
- context = [f"\n{source.page_content}\nSource:\n{source.metadata.get('title')} - {source.metadata.get('source')}" for source in result]
- return {"context": '\n'.join(context), "query":query}
-
-
-@on_message
-@cl.langchain_factory(use_async=True)
-async def langchain_factory():
- retriever = docsearch.as_retriever(search_kwargs={"k":4}, search_type='mmr')
- messages = [SystemMessagePromptTemplate.from_template(spark)]
- messages.extend(memory.chat_memory.messages)
- messages.append(HumanMessagePromptTemplate.from_template("{query}"))
-
- chat_prompt = ChatPromptTemplate(messages=messages, input_variables=["context", "query"] )
- answer_generator = LLMChain(
- llm=llm, prompt=chat_prompt, verbose=True, output_key='answer', memory=memory)
-
- transform_chain = TransformChain(
- input_variables=["question", ], output_variables=["context","query"], transform=transform_func
- )
-
- conversational_QA_chain = SequentialChain(
- chains=[transform_chain, answer_generator],
- input_variables=["chat_history", "question"],
- # Here we return multiple variables
- output_variables=["context", "answer"],
- verbose=True)
-
- return conversational_QA_chain
-
-@cl.langchain_run
-async def run(chain, input_str):
- res = chain._call({"question":input_str})
- await cl.Message(content=res["answer"]).send()
-
-
-@cl.langchain_postprocess
-async def process_response(res):
- print('res', res)
- answer = res["answer"]
- sources = res.get("sources", "").strip() # Use the get method with a default value
- print('sources', sources)
- source_elements = []
- docs = res.get("source_documents", None)
-
- if docs:
- metadatas = [doc.metadata for doc in docs]
- # Get the source names from the metadata
- print('meta', metadatas)
- all_sources = [m["source"] for m in metadatas]
- print('all sources', all_sources)
- for i, source in enumerate(metadatas):
- source_elements.append(cl.Text(content=source.get('source'), name=source.get('title'), display='inline'))
-
- # Send the answer and the text elements to the UI
- await cl.Message(content=answer, elements=source_elements).send()
\ No newline at end of file
diff --git a/spaces/antonovmaxim/text-generation-webui-space/extensions/multimodal/abstract_pipeline.py b/spaces/antonovmaxim/text-generation-webui-space/extensions/multimodal/abstract_pipeline.py
deleted file mode 100644
index 584219419d256e7743fd4d5120c56bcfa8f2a9f9..0000000000000000000000000000000000000000
--- a/spaces/antonovmaxim/text-generation-webui-space/extensions/multimodal/abstract_pipeline.py
+++ /dev/null
@@ -1,62 +0,0 @@
-from abc import ABC, abstractmethod
-from typing import List, Optional
-
-import torch
-from PIL import Image
-
-
-class AbstractMultimodalPipeline(ABC):
- @staticmethod
- @abstractmethod
- def name() -> str:
- 'name of the pipeline, should be same as in --multimodal-pipeline'
- pass
-
- @staticmethod
- @abstractmethod
- def image_start() -> Optional[str]:
- 'return image start string, string representation of image start token, or None if not applicable'
- pass
-
- @staticmethod
- @abstractmethod
- def image_end() -> Optional[str]:
- 'return image end string, string representation of image end token, or None if not applicable'
- pass
-
- @staticmethod
- @abstractmethod
- def placeholder_token_id() -> int:
- 'return placeholder token id'
- pass
-
- @staticmethod
- @abstractmethod
- def num_image_embeds() -> int:
- 'return the number of embeds used by a single image (for example: 256 for LLaVA)'
- pass
-
- @abstractmethod
- def embed_images(self, images: List[Image.Image]) -> torch.Tensor:
- 'forward the images through vision pipeline, and return their embeddings'
- pass
-
- @staticmethod
- @abstractmethod
- def embed_tokens(input_ids: torch.Tensor) -> torch.Tensor:
- 'embed tokens, the exact function varies by LLM, for LLaMA it is `shared.model.model.embed_tokens`'
- pass
-
- @staticmethod
- @abstractmethod
- def placeholder_embeddings() -> torch.Tensor:
- 'get placeholder embeddings if there are multiple images, and `add_all_images_to_prompt` is False'
- pass
-
- def _get_device(self, setting_name: str, params: dict):
- if params[setting_name] is None:
- return torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
- return torch.device(params[setting_name])
-
- def _get_dtype(self, setting_name: str, params: dict):
- return torch.float32 if int(params[setting_name]) == 32 else torch.float16
diff --git a/spaces/artificialguybr/video-dubbing/TTS/TTS/vc/modules/freevc/wavlm/modules.py b/spaces/artificialguybr/video-dubbing/TTS/TTS/vc/modules/freevc/wavlm/modules.py
deleted file mode 100644
index 37c1a6e8774cdfd439baa38a8a7ad55fd79ebf7c..0000000000000000000000000000000000000000
--- a/spaces/artificialguybr/video-dubbing/TTS/TTS/vc/modules/freevc/wavlm/modules.py
+++ /dev/null
@@ -1,768 +0,0 @@
-# --------------------------------------------------------
-# WavLM: Large-Scale Self-Supervised Pre-training for Full Stack Speech Processing (https://arxiv.org/abs/2110.13900.pdf)
-# Github source: https://github.com/microsoft/unilm/tree/master/wavlm
-# Copyright (c) 2021 Microsoft
-# Licensed under The MIT License [see LICENSE for details]
-# Based on fairseq code bases
-# https://github.com/pytorch/fairseq
-# --------------------------------------------------------
-
-import math
-import warnings
-from typing import Dict, Optional, Tuple
-
-import torch
-import torch.nn.functional as F
-from torch import Tensor, nn
-from torch.nn import Parameter
-
-
-class TransposeLast(nn.Module):
- def __init__(self, deconstruct_idx=None):
- super().__init__()
- self.deconstruct_idx = deconstruct_idx
-
- def forward(self, x):
- if self.deconstruct_idx is not None:
- x = x[self.deconstruct_idx]
- return x.transpose(-2, -1)
-
-
-class Fp32LayerNorm(nn.LayerNorm):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
-
- def forward(self, input):
- output = F.layer_norm(
- input.float(),
- self.normalized_shape,
- self.weight.float() if self.weight is not None else None,
- self.bias.float() if self.bias is not None else None,
- self.eps,
- )
- return output.type_as(input)
-
-
-class Fp32GroupNorm(nn.GroupNorm):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
-
- def forward(self, input):
- output = F.group_norm(
- input.float(),
- self.num_groups,
- self.weight.float() if self.weight is not None else None,
- self.bias.float() if self.bias is not None else None,
- self.eps,
- )
- return output.type_as(input)
-
-
-class GradMultiply(torch.autograd.Function):
- @staticmethod
- def forward(ctx, x, scale):
- ctx.scale = scale
- res = x.new(x)
- return res
-
- @staticmethod
- def backward(ctx, grad):
- return grad * ctx.scale, None
-
-
-class SamePad(nn.Module):
- def __init__(self, kernel_size, causal=False):
- super().__init__()
- if causal:
- self.remove = kernel_size - 1
- else:
- self.remove = 1 if kernel_size % 2 == 0 else 0
-
- def forward(self, x):
- if self.remove > 0:
- x = x[:, :, : -self.remove]
- return x
-
-
-class Swish(nn.Module):
- """Swish function"""
-
- def __init__(self):
- """Construct an MultiHeadedAttention object."""
- super(Swish, self).__init__()
- self.act = torch.nn.Sigmoid()
-
- def forward(self, x):
- return x * self.act(x)
-
-
-class GLU_Linear(nn.Module):
- def __init__(self, input_dim, output_dim, glu_type="sigmoid", bias_in_glu=True):
- super(GLU_Linear, self).__init__()
-
- self.glu_type = glu_type
- self.output_dim = output_dim
-
- if glu_type == "sigmoid":
- self.glu_act = torch.nn.Sigmoid()
- elif glu_type == "swish":
- self.glu_act = Swish()
- elif glu_type == "relu":
- self.glu_act = torch.nn.ReLU()
- elif glu_type == "gelu":
- self.glu_act = torch.nn.GELU()
-
- if bias_in_glu:
- self.linear = nn.Linear(input_dim, output_dim * 2, True)
- else:
- self.linear = nn.Linear(input_dim, output_dim * 2, False)
-
- def forward(self, x):
- # to be consistent with GLU_Linear, we assume the input always has the #channel (#dim) in the last dimension of the tensor, so need to switch the dimension first for 1D-Conv case
- x = self.linear(x)
-
- if self.glu_type == "bilinear":
- x = x[:, :, 0 : self.output_dim] * x[:, :, self.output_dim : self.output_dim * 2]
- else:
- x = x[:, :, 0 : self.output_dim] * self.glu_act(x[:, :, self.output_dim : self.output_dim * 2])
-
- return x
-
-
-def gelu_accurate(x):
- if not hasattr(gelu_accurate, "_a"):
- gelu_accurate._a = math.sqrt(2 / math.pi)
- return 0.5 * x * (1 + torch.tanh(gelu_accurate._a * (x + 0.044715 * torch.pow(x, 3))))
-
-
-def gelu(x: torch.Tensor) -> torch.Tensor:
- return torch.nn.functional.gelu(x.float()).type_as(x)
-
-
-def get_activation_fn(activation: str):
- """Returns the activation function corresponding to `activation`"""
-
- if activation == "relu":
- return F.relu
- elif activation == "gelu":
- return gelu
- elif activation == "gelu_fast":
- warnings.warn("--activation-fn=gelu_fast has been renamed to gelu_accurate")
- return gelu_accurate
- elif activation == "gelu_accurate":
- return gelu_accurate
- elif activation == "tanh":
- return torch.tanh
- elif activation == "linear":
- return lambda x: x
- elif activation == "glu":
- return lambda x: x
- else:
- raise RuntimeError("--activation-fn {} not supported".format(activation))
-
-
-def init_bert_params(module):
- """
- Initialize the weights specific to the BERT Model.
- This overrides the default initializations depending on the specified arguments.
- 1. If normal_init_linear_weights is set then weights of linear
- layer will be initialized using the normal distribution and
- bais will be set to the specified value.
- 2. If normal_init_embed_weights is set then weights of embedding
- layer will be initialized using the normal distribution.
- 3. If normal_init_proj_weights is set then weights of
- in_project_weight for MultiHeadAttention initialized using
- the normal distribution (to be validated).
- """
-
- def normal_(data):
- # with FSDP, module params will be on CUDA, so we cast them back to CPU
- # so that the RNG is consistent with and without FSDP
- data.copy_(data.cpu().normal_(mean=0.0, std=0.02).to(data.device))
-
- if isinstance(module, nn.Linear):
- normal_(module.weight.data)
- if module.bias is not None:
- module.bias.data.zero_()
- if isinstance(module, nn.Embedding):
- normal_(module.weight.data)
- if module.padding_idx is not None:
- module.weight.data[module.padding_idx].zero_()
- if isinstance(module, MultiheadAttention):
- normal_(module.q_proj.weight.data)
- normal_(module.k_proj.weight.data)
- normal_(module.v_proj.weight.data)
-
-
-def quant_noise(module, p, block_size):
- """
- Wraps modules and applies quantization noise to the weights for
- subsequent quantization with Iterative Product Quantization as
- described in "Training with Quantization Noise for Extreme Model Compression"
-
- Args:
- - module: nn.Module
- - p: amount of Quantization Noise
- - block_size: size of the blocks for subsequent quantization with iPQ
-
- Remarks:
- - Module weights must have the right sizes wrt the block size
- - Only Linear, Embedding and Conv2d modules are supported for the moment
- - For more detail on how to quantize by blocks with convolutional weights,
- see "And the Bit Goes Down: Revisiting the Quantization of Neural Networks"
- - We implement the simplest form of noise here as stated in the paper
- which consists in randomly dropping blocks
- """
-
- # if no quantization noise, don't register hook
- if p <= 0:
- return module
-
- # supported modules
- assert isinstance(module, (nn.Linear, nn.Embedding, nn.Conv2d))
-
- # test whether module.weight has the right sizes wrt block_size
- is_conv = module.weight.ndim == 4
-
- # 2D matrix
- if not is_conv:
- assert module.weight.size(1) % block_size == 0, "Input features must be a multiple of block sizes"
-
- # 4D matrix
- else:
- # 1x1 convolutions
- if module.kernel_size == (1, 1):
- assert module.in_channels % block_size == 0, "Input channels must be a multiple of block sizes"
- # regular convolutions
- else:
- k = module.kernel_size[0] * module.kernel_size[1]
- assert k % block_size == 0, "Kernel size must be a multiple of block size"
-
- def _forward_pre_hook(mod, input):
- # no noise for evaluation
- if mod.training:
- if not is_conv:
- # gather weight and sizes
- weight = mod.weight
- in_features = weight.size(1)
- out_features = weight.size(0)
-
- # split weight matrix into blocks and randomly drop selected blocks
- mask = torch.zeros(in_features // block_size * out_features, device=weight.device)
- mask.bernoulli_(p)
- mask = mask.repeat_interleave(block_size, -1).view(-1, in_features)
-
- else:
- # gather weight and sizes
- weight = mod.weight
- in_channels = mod.in_channels
- out_channels = mod.out_channels
-
- # split weight matrix into blocks and randomly drop selected blocks
- if mod.kernel_size == (1, 1):
- mask = torch.zeros(
- int(in_channels // block_size * out_channels),
- device=weight.device,
- )
- mask.bernoulli_(p)
- mask = mask.repeat_interleave(block_size, -1).view(-1, in_channels)
- else:
- mask = torch.zeros(weight.size(0), weight.size(1), device=weight.device)
- mask.bernoulli_(p)
- mask = mask.unsqueeze(2).unsqueeze(3).repeat(1, 1, mod.kernel_size[0], mod.kernel_size[1])
-
- # scale weights and apply mask
- mask = mask.to(torch.bool) # x.bool() is not currently supported in TorchScript
- s = 1 / (1 - p)
- mod.weight.data = s * weight.masked_fill(mask, 0)
-
- module.register_forward_pre_hook(_forward_pre_hook)
- return module
-
-
-class MultiheadAttention(nn.Module):
- """Multi-headed attention.
-
- See "Attention Is All You Need" for more details.
- """
-
- def __init__(
- self,
- embed_dim,
- num_heads,
- kdim=None,
- vdim=None,
- dropout=0.0,
- bias=True,
- add_bias_kv=False,
- add_zero_attn=False,
- self_attention=False,
- encoder_decoder_attention=False,
- q_noise=0.0,
- qn_block_size=8,
- has_relative_attention_bias=False,
- num_buckets=32,
- max_distance=128,
- gru_rel_pos=False,
- rescale_init=False,
- ):
- super().__init__()
- self.embed_dim = embed_dim
- self.kdim = kdim if kdim is not None else embed_dim
- self.vdim = vdim if vdim is not None else embed_dim
- self.qkv_same_dim = self.kdim == embed_dim and self.vdim == embed_dim
-
- self.num_heads = num_heads
- self.dropout_module = nn.Dropout(dropout)
-
- self.has_relative_attention_bias = has_relative_attention_bias
- self.num_buckets = num_buckets
- self.max_distance = max_distance
- if self.has_relative_attention_bias:
- self.relative_attention_bias = nn.Embedding(num_buckets, num_heads)
-
- self.head_dim = embed_dim // num_heads
- self.q_head_dim = self.head_dim
- self.k_head_dim = self.head_dim
- assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads"
- self.scaling = self.head_dim**-0.5
-
- self.self_attention = self_attention
- self.encoder_decoder_attention = encoder_decoder_attention
-
- assert not self.self_attention or self.qkv_same_dim, (
- "Self-attention requires query, key and " "value to be of the same size"
- )
-
- k_bias = True
- if rescale_init:
- k_bias = False
-
- k_embed_dim = embed_dim
- q_embed_dim = embed_dim
-
- self.k_proj = quant_noise(nn.Linear(self.kdim, k_embed_dim, bias=k_bias), q_noise, qn_block_size)
- self.v_proj = quant_noise(nn.Linear(self.vdim, embed_dim, bias=bias), q_noise, qn_block_size)
- self.q_proj = quant_noise(nn.Linear(embed_dim, q_embed_dim, bias=bias), q_noise, qn_block_size)
-
- self.out_proj = quant_noise(nn.Linear(embed_dim, embed_dim, bias=bias), q_noise, qn_block_size)
-
- if add_bias_kv:
- self.bias_k = Parameter(torch.Tensor(1, 1, embed_dim))
- self.bias_v = Parameter(torch.Tensor(1, 1, embed_dim))
- else:
- self.bias_k = self.bias_v = None
-
- self.add_zero_attn = add_zero_attn
-
- self.gru_rel_pos = gru_rel_pos
- if self.gru_rel_pos:
- self.grep_linear = nn.Linear(self.q_head_dim, 8)
- self.grep_a = nn.Parameter(torch.ones(1, num_heads, 1, 1))
-
- self.reset_parameters()
-
- def reset_parameters(self):
- if self.qkv_same_dim:
- # Empirically observed the convergence to be much better with
- # the scaled initialization
- nn.init.xavier_uniform_(self.k_proj.weight, gain=1 / math.sqrt(2))
- nn.init.xavier_uniform_(self.v_proj.weight, gain=1 / math.sqrt(2))
- nn.init.xavier_uniform_(self.q_proj.weight, gain=1 / math.sqrt(2))
- else:
- nn.init.xavier_uniform_(self.k_proj.weight)
- nn.init.xavier_uniform_(self.v_proj.weight)
- nn.init.xavier_uniform_(self.q_proj.weight)
-
- nn.init.xavier_uniform_(self.out_proj.weight)
- if self.out_proj.bias is not None:
- nn.init.constant_(self.out_proj.bias, 0.0)
- if self.bias_k is not None:
- nn.init.xavier_normal_(self.bias_k)
- if self.bias_v is not None:
- nn.init.xavier_normal_(self.bias_v)
- if self.has_relative_attention_bias:
- nn.init.xavier_normal_(self.relative_attention_bias.weight)
-
- def _relative_positions_bucket(self, relative_positions, bidirectional=True):
- num_buckets = self.num_buckets
- max_distance = self.max_distance
- relative_buckets = 0
-
- if bidirectional:
- num_buckets = num_buckets // 2
- relative_buckets += (relative_positions > 0).to(torch.long) * num_buckets
- relative_positions = torch.abs(relative_positions)
- else:
- relative_positions = -torch.min(relative_positions, torch.zeros_like(relative_positions))
-
- max_exact = num_buckets // 2
- is_small = relative_positions < max_exact
-
- relative_postion_if_large = max_exact + (
- torch.log(relative_positions.float() / max_exact)
- / math.log(max_distance / max_exact)
- * (num_buckets - max_exact)
- ).to(torch.long)
- relative_postion_if_large = torch.min(
- relative_postion_if_large, torch.full_like(relative_postion_if_large, num_buckets - 1)
- )
-
- relative_buckets += torch.where(is_small, relative_positions, relative_postion_if_large)
- return relative_buckets
-
- def compute_bias(self, query_length, key_length):
- context_position = torch.arange(query_length, dtype=torch.long)[:, None]
- memory_position = torch.arange(key_length, dtype=torch.long)[None, :]
- relative_position = memory_position - context_position
- relative_position_bucket = self._relative_positions_bucket(relative_position, bidirectional=True)
- relative_position_bucket = relative_position_bucket.to(self.relative_attention_bias.weight.device)
- values = self.relative_attention_bias(relative_position_bucket)
- values = values.permute([2, 0, 1])
- return values
-
- def forward(
- self,
- query,
- key: Optional[Tensor],
- value: Optional[Tensor],
- key_padding_mask: Optional[Tensor] = None,
- incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
- need_weights: bool = True,
- static_kv: bool = False,
- attn_mask: Optional[Tensor] = None,
- before_softmax: bool = False,
- need_head_weights: bool = False,
- position_bias: Optional[Tensor] = None,
- ) -> Tuple[Tensor, Optional[Tensor], Optional[Tensor]]:
- """Input shape: Time x Batch x Channel
-
- Args:
- key_padding_mask (ByteTensor, optional): mask to exclude
- keys that are pads, of shape `(batch, src_len)`, where
- padding elements are indicated by 1s.
- need_weights (bool, optional): return the attention weights,
- averaged over heads (default: False).
- attn_mask (ByteTensor, optional): typically used to
- implement causal attention, where the mask prevents the
- attention from looking forward in time (default: None).
- before_softmax (bool, optional): return the raw attention
- weights and values before the attention softmax.
- need_head_weights (bool, optional): return the attention
- weights for each head. Implies *need_weights*. Default:
- return the average attention weights over all heads.
- """
- if need_head_weights:
- need_weights = True
-
- is_tpu = query.device.type == "xla"
-
- tgt_len, bsz, embed_dim = query.size()
- src_len = tgt_len
- assert embed_dim == self.embed_dim
- assert list(query.size()) == [tgt_len, bsz, embed_dim]
- if key is not None:
- src_len, key_bsz, _ = key.size()
- if not torch.jit.is_scripting():
- assert key_bsz == bsz
- assert value is not None
- assert src_len, bsz == value.shape[:2]
-
- if self.has_relative_attention_bias and position_bias is None:
- position_bias = self.compute_bias(tgt_len, src_len)
- position_bias = position_bias.unsqueeze(0).repeat(bsz, 1, 1, 1).view(bsz * self.num_heads, tgt_len, src_len)
-
- if (
- not is_tpu # don't use PyTorch version on TPUs
- and incremental_state is None
- and not static_kv
- # A workaround for quantization to work. Otherwise JIT compilation
- # treats bias in linear module as method.
- and not torch.jit.is_scripting()
- and self.q_head_dim == self.head_dim
- ):
- assert key is not None and value is not None
- assert attn_mask is None
-
- attn_mask_rel_pos = None
- if position_bias is not None:
- attn_mask_rel_pos = position_bias
- if self.gru_rel_pos:
- query_layer = query.transpose(0, 1)
- new_x_shape = query_layer.size()[:-1] + (self.num_heads, -1)
- query_layer = query_layer.view(*new_x_shape)
- query_layer = query_layer.permute(0, 2, 1, 3)
- _B, _H, _L, __ = query_layer.size()
-
- gate_a, gate_b = torch.sigmoid(
- self.grep_linear(query_layer).view(_B, _H, _L, 2, 4).sum(-1, keepdim=False)
- ).chunk(2, dim=-1)
- gate_a_1 = gate_a * (gate_b * self.grep_a - 1.0) + 2.0
- attn_mask_rel_pos = gate_a_1.view(bsz * self.num_heads, -1, 1) * position_bias
-
- attn_mask_rel_pos = attn_mask_rel_pos.view((-1, tgt_len, tgt_len))
- k_proj_bias = self.k_proj.bias
- if k_proj_bias is None:
- k_proj_bias = torch.zeros_like(self.q_proj.bias)
-
- x, attn = F.multi_head_attention_forward(
- query,
- key,
- value,
- self.embed_dim,
- self.num_heads,
- torch.empty([0]),
- torch.cat((self.q_proj.bias, self.k_proj.bias, self.v_proj.bias)),
- self.bias_k,
- self.bias_v,
- self.add_zero_attn,
- self.dropout_module.p,
- self.out_proj.weight,
- self.out_proj.bias,
- self.training,
- # self.training or self.dropout_module.apply_during_inference,
- key_padding_mask,
- need_weights,
- attn_mask_rel_pos,
- use_separate_proj_weight=True,
- q_proj_weight=self.q_proj.weight,
- k_proj_weight=self.k_proj.weight,
- v_proj_weight=self.v_proj.weight,
- )
- return x, attn, position_bias
-
- if incremental_state is not None:
- saved_state = self._get_input_buffer(incremental_state)
- if saved_state is not None and "prev_key" in saved_state:
- # previous time steps are cached - no need to recompute
- # key and value if they are static
- if static_kv:
- assert self.encoder_decoder_attention and not self.self_attention
- key = value = None
- else:
- saved_state = None
-
- if self.self_attention:
- q = self.q_proj(query)
- k = self.k_proj(query)
- v = self.v_proj(query)
- elif self.encoder_decoder_attention:
- # encoder-decoder attention
- q = self.q_proj(query)
- if key is None:
- assert value is None
- k = v = None
- else:
- k = self.k_proj(key)
- v = self.v_proj(key)
-
- else:
- assert key is not None and value is not None
- q = self.q_proj(query)
- k = self.k_proj(key)
- v = self.v_proj(value)
- q *= self.scaling
-
- if self.bias_k is not None:
- assert self.bias_v is not None
- k = torch.cat([k, self.bias_k.repeat(1, bsz, 1)])
- v = torch.cat([v, self.bias_v.repeat(1, bsz, 1)])
- if attn_mask is not None:
- attn_mask = torch.cat([attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1)
- if key_padding_mask is not None:
- key_padding_mask = torch.cat(
- [
- key_padding_mask,
- key_padding_mask.new_zeros(key_padding_mask.size(0), 1),
- ],
- dim=1,
- )
-
- q = q.contiguous().view(tgt_len, bsz * self.num_heads, self.q_head_dim).transpose(0, 1)
- if k is not None:
- k = k.contiguous().view(-1, bsz * self.num_heads, self.k_head_dim).transpose(0, 1)
- if v is not None:
- v = v.contiguous().view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1)
-
- if saved_state is not None:
- # saved states are stored with shape (bsz, num_heads, seq_len, head_dim)
- if "prev_key" in saved_state:
- _prev_key = saved_state["prev_key"]
- assert _prev_key is not None
- prev_key = _prev_key.view(bsz * self.num_heads, -1, self.head_dim)
- if static_kv:
- k = prev_key
- else:
- assert k is not None
- k = torch.cat([prev_key, k], dim=1)
- src_len = k.size(1)
- if "prev_value" in saved_state:
- _prev_value = saved_state["prev_value"]
- assert _prev_value is not None
- prev_value = _prev_value.view(bsz * self.num_heads, -1, self.head_dim)
- if static_kv:
- v = prev_value
- else:
- assert v is not None
- v = torch.cat([prev_value, v], dim=1)
- prev_key_padding_mask: Optional[Tensor] = None
- if "prev_key_padding_mask" in saved_state:
- prev_key_padding_mask = saved_state["prev_key_padding_mask"]
- assert k is not None and v is not None
- key_padding_mask = MultiheadAttention._append_prev_key_padding_mask(
- key_padding_mask=key_padding_mask,
- prev_key_padding_mask=prev_key_padding_mask,
- batch_size=bsz,
- src_len=k.size(1),
- static_kv=static_kv,
- )
-
- saved_state["prev_key"] = k.view(bsz, self.num_heads, -1, self.head_dim)
- saved_state["prev_value"] = v.view(bsz, self.num_heads, -1, self.head_dim)
- saved_state["prev_key_padding_mask"] = key_padding_mask
- # In this branch incremental_state is never None
- assert incremental_state is not None
- incremental_state = self._set_input_buffer(incremental_state, saved_state)
- assert k is not None
- assert k.size(1) == src_len
-
- # This is part of a workaround to get around fork/join parallelism
- # not supporting Optional types.
- if key_padding_mask is not None and key_padding_mask.dim() == 0:
- key_padding_mask = None
-
- if key_padding_mask is not None:
- assert key_padding_mask.size(0) == bsz
- assert key_padding_mask.size(1) == src_len
-
- if self.add_zero_attn:
- assert v is not None
- src_len += 1
- k = torch.cat([k, k.new_zeros((k.size(0), 1) + k.size()[2:])], dim=1)
- v = torch.cat([v, v.new_zeros((v.size(0), 1) + v.size()[2:])], dim=1)
- if attn_mask is not None:
- attn_mask = torch.cat([attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1)
- if key_padding_mask is not None:
- key_padding_mask = torch.cat(
- [
- key_padding_mask,
- torch.zeros(key_padding_mask.size(0), 1).type_as(key_padding_mask),
- ],
- dim=1,
- )
-
- attn_weights = torch.bmm(q, k.transpose(1, 2))
- attn_weights = self.apply_sparse_mask(attn_weights, tgt_len, src_len, bsz)
-
- assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len, src_len]
-
- if attn_mask is not None:
- attn_mask = attn_mask.unsqueeze(0)
- attn_weights += attn_mask
-
- if key_padding_mask is not None:
- # don't attend to padding symbols
- attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
- if not is_tpu:
- attn_weights = attn_weights.masked_fill(
- key_padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool),
- float("-inf"),
- )
- else:
- attn_weights = attn_weights.transpose(0, 2)
- attn_weights = attn_weights.masked_fill(key_padding_mask, float("-inf"))
- attn_weights = attn_weights.transpose(0, 2)
- attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
-
- if before_softmax:
- return attn_weights, v, position_bias
-
- if position_bias is not None:
- if self.gru_rel_pos == 1:
- query_layer = q.view(bsz, self.num_heads, tgt_len, self.q_head_dim)
- _B, _H, _L, __ = query_layer.size()
- gate_a, gate_b = torch.sigmoid(
- self.grep_linear(query_layer).view(_B, _H, _L, 2, 4).sum(-1, keepdim=False)
- ).chunk(2, dim=-1)
- gate_a_1 = gate_a * (gate_b * self.grep_a - 1.0) + 2.0
- position_bias = gate_a_1.view(bsz * self.num_heads, -1, 1) * position_bias
-
- position_bias = position_bias.view(attn_weights.size())
-
- attn_weights = attn_weights + position_bias
-
- attn_weights_float = F.softmax(attn_weights, dim=-1)
- attn_weights = attn_weights_float.type_as(attn_weights)
- attn_probs = self.dropout_module(attn_weights)
-
- assert v is not None
- attn = torch.bmm(attn_probs, v)
- assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self.head_dim]
- attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
- attn = self.out_proj(attn)
- attn_weights: Optional[Tensor] = None
- if need_weights:
- attn_weights = attn_weights_float.view(bsz, self.num_heads, tgt_len, src_len).transpose(1, 0)
- if not need_head_weights:
- # average attention weights over heads
- attn_weights = attn_weights.mean(dim=0)
-
- return attn, attn_weights, position_bias
-
- @staticmethod
- def _append_prev_key_padding_mask(
- key_padding_mask: Optional[Tensor],
- prev_key_padding_mask: Optional[Tensor],
- batch_size: int,
- src_len: int,
- static_kv: bool,
- ) -> Optional[Tensor]:
- # saved key padding masks have shape (bsz, seq_len)
- if prev_key_padding_mask is not None and static_kv:
- new_key_padding_mask = prev_key_padding_mask
- elif prev_key_padding_mask is not None and key_padding_mask is not None:
- new_key_padding_mask = torch.cat([prev_key_padding_mask.float(), key_padding_mask.float()], dim=1)
- # During incremental decoding, as the padding token enters and
- # leaves the frame, there will be a time when prev or current
- # is None
- elif prev_key_padding_mask is not None:
- if src_len > prev_key_padding_mask.size(1):
- filler = torch.zeros(
- (batch_size, src_len - prev_key_padding_mask.size(1)),
- device=prev_key_padding_mask.device,
- )
- new_key_padding_mask = torch.cat([prev_key_padding_mask.float(), filler.float()], dim=1)
- else:
- new_key_padding_mask = prev_key_padding_mask.float()
- elif key_padding_mask is not None:
- if src_len > key_padding_mask.size(1):
- filler = torch.zeros(
- (batch_size, src_len - key_padding_mask.size(1)),
- device=key_padding_mask.device,
- )
- new_key_padding_mask = torch.cat([filler.float(), key_padding_mask.float()], dim=1)
- else:
- new_key_padding_mask = key_padding_mask.float()
- else:
- new_key_padding_mask = prev_key_padding_mask
- return new_key_padding_mask
-
- def _get_input_buffer(
- self, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]]
- ) -> Dict[str, Optional[Tensor]]:
- result = self.get_incremental_state(incremental_state, "attn_state")
- if result is not None:
- return result
- else:
- empty_result: Dict[str, Optional[Tensor]] = {}
- return empty_result
-
- def _set_input_buffer(
- self,
- incremental_state: Dict[str, Dict[str, Optional[Tensor]]],
- buffer: Dict[str, Optional[Tensor]],
- ):
- return self.set_incremental_state(incremental_state, "attn_state", buffer)
-
- def apply_sparse_mask(self, attn_weights, tgt_len: int, src_len: int, bsz: int):
- return attn_weights
diff --git a/spaces/artificialguybr/video-dubbing/TTS/TTS/vocoder/configs/fullband_melgan_config.py b/spaces/artificialguybr/video-dubbing/TTS/TTS/vocoder/configs/fullband_melgan_config.py
deleted file mode 100644
index 2ab83aace678e328a8f99a5f0dc63e54ed99d4c4..0000000000000000000000000000000000000000
--- a/spaces/artificialguybr/video-dubbing/TTS/TTS/vocoder/configs/fullband_melgan_config.py
+++ /dev/null
@@ -1,106 +0,0 @@
-from dataclasses import dataclass, field
-
-from .shared_configs import BaseGANVocoderConfig
-
-
-@dataclass
-class FullbandMelganConfig(BaseGANVocoderConfig):
- """Defines parameters for FullBand MelGAN vocoder.
-
- Example:
-
- >>> from TTS.vocoder.configs import FullbandMelganConfig
- >>> config = FullbandMelganConfig()
-
- Args:
- model (str):
- Model name used for selecting the right model at initialization. Defaults to `fullband_melgan`.
- discriminator_model (str): One of the discriminators from `TTS.vocoder.models.*_discriminator`. Defaults to
- 'melgan_multiscale_discriminator`.
- discriminator_model_params (dict): The discriminator model parameters. Defaults to
- '{"base_channels": 16, "max_channels": 1024, "downsample_factors": [4, 4, 4, 4]}`
- generator_model (str): One of the generators from TTS.vocoder.models.*`. Every other non-GAN vocoder model is
- considered as a generator too. Defaults to `melgan_generator`.
- batch_size (int):
- Batch size used at training. Larger values use more memory. Defaults to 16.
- seq_len (int):
- Audio segment length used at training. Larger values use more memory. Defaults to 8192.
- pad_short (int):
- Additional padding applied to the audio samples shorter than `seq_len`. Defaults to 0.
- use_noise_augment (bool):
- enable / disable random noise added to the input waveform. The noise is added after computing the
- features. Defaults to True.
- use_cache (bool):
- enable / disable in memory caching of the computed features. It can cause OOM error if the system RAM is
- not large enough. Defaults to True.
- use_stft_loss (bool):
- enable / disable use of STFT loss originally used by ParallelWaveGAN model. Defaults to True.
- use_subband_stft (bool):
- enable / disable use of subband loss computation originally used by MultiBandMelgan model. Defaults to True.
- use_mse_gan_loss (bool):
- enable / disable using Mean Squeare Error GAN loss. Defaults to True.
- use_hinge_gan_loss (bool):
- enable / disable using Hinge GAN loss. You should choose either Hinge or MSE loss for training GAN models.
- Defaults to False.
- use_feat_match_loss (bool):
- enable / disable using Feature Matching loss originally used by MelGAN model. Defaults to True.
- use_l1_spec_loss (bool):
- enable / disable using L1 spectrogram loss originally used by HifiGAN model. Defaults to False.
- stft_loss_params (dict): STFT loss parameters. Default to
- `{"n_ffts": [1024, 2048, 512], "hop_lengths": [120, 240, 50], "win_lengths": [600, 1200, 240]}`
- stft_loss_weight (float): STFT loss weight that multiplies the computed loss before summing up the total
- model loss. Defaults to 0.5.
- subband_stft_loss_weight (float):
- Subband STFT loss weight that multiplies the computed loss before summing up the total loss. Defaults to 0.
- mse_G_loss_weight (float):
- MSE generator loss weight that multiplies the computed loss before summing up the total loss. faults to 2.5.
- hinge_G_loss_weight (float):
- Hinge generator loss weight that multiplies the computed loss before summing up the total loss. Defaults to 0.
- feat_match_loss_weight (float):
- Feature matching loss weight that multiplies the computed loss before summing up the total loss. faults to 108.
- l1_spec_loss_weight (float):
- L1 spectrogram loss weight that multiplies the computed loss before summing up the total loss. Defaults to 0.
- """
-
- model: str = "fullband_melgan"
-
- # Model specific params
- discriminator_model: str = "melgan_multiscale_discriminator"
- discriminator_model_params: dict = field(
- default_factory=lambda: {"base_channels": 16, "max_channels": 512, "downsample_factors": [4, 4, 4]}
- )
- generator_model: str = "melgan_generator"
- generator_model_params: dict = field(
- default_factory=lambda: {"upsample_factors": [8, 8, 2, 2], "num_res_blocks": 4}
- )
-
- # Training - overrides
- batch_size: int = 16
- seq_len: int = 8192
- pad_short: int = 2000
- use_noise_augment: bool = True
- use_cache: bool = True
-
- # LOSS PARAMETERS - overrides
- use_stft_loss: bool = True
- use_subband_stft_loss: bool = False
- use_mse_gan_loss: bool = True
- use_hinge_gan_loss: bool = False
- use_feat_match_loss: bool = True # requires MelGAN Discriminators (MelGAN and HifiGAN)
- use_l1_spec_loss: bool = False
-
- stft_loss_params: dict = field(
- default_factory=lambda: {
- "n_ffts": [1024, 2048, 512],
- "hop_lengths": [120, 240, 50],
- "win_lengths": [600, 1200, 240],
- }
- )
-
- # loss weights - overrides
- stft_loss_weight: float = 0.5
- subband_stft_loss_weight: float = 0
- mse_G_loss_weight: float = 2.5
- hinge_G_loss_weight: float = 0
- feat_match_loss_weight: float = 108
- l1_spec_loss_weight: float = 0.0
diff --git a/spaces/artificialguybr/video-dubbing/Wav2Lip/face_detection/detection/core.py b/spaces/artificialguybr/video-dubbing/Wav2Lip/face_detection/detection/core.py
deleted file mode 100644
index 0f8275e8e53143f66298f75f0517c234a68778cd..0000000000000000000000000000000000000000
--- a/spaces/artificialguybr/video-dubbing/Wav2Lip/face_detection/detection/core.py
+++ /dev/null
@@ -1,130 +0,0 @@
-import logging
-import glob
-from tqdm import tqdm
-import numpy as np
-import torch
-import cv2
-
-
-class FaceDetector(object):
- """An abstract class representing a face detector.
-
- Any other face detection implementation must subclass it. All subclasses
- must implement ``detect_from_image``, that return a list of detected
- bounding boxes. Optionally, for speed considerations detect from path is
- recommended.
- """
-
- def __init__(self, device, verbose):
- self.device = device
- self.verbose = verbose
-
- if verbose:
- if 'cpu' in device:
- logger = logging.getLogger(__name__)
- logger.warning("Detection running on CPU, this may be potentially slow.")
-
- if 'cpu' not in device and 'cuda' not in device:
- if verbose:
- logger.error("Expected values for device are: {cpu, cuda} but got: %s", device)
- raise ValueError
-
- def detect_from_image(self, tensor_or_path):
- """Detects faces in a given image.
-
- This function detects the faces present in a provided BGR(usually)
- image. The input can be either the image itself or the path to it.
-
- Arguments:
- tensor_or_path {numpy.ndarray, torch.tensor or string} -- the path
- to an image or the image itself.
-
- Example::
-
- >>> path_to_image = 'data/image_01.jpg'
- ... detected_faces = detect_from_image(path_to_image)
- [A list of bounding boxes (x1, y1, x2, y2)]
- >>> image = cv2.imread(path_to_image)
- ... detected_faces = detect_from_image(image)
- [A list of bounding boxes (x1, y1, x2, y2)]
-
- """
- raise NotImplementedError
-
- def detect_from_directory(self, path, extensions=['.jpg', '.png'], recursive=False, show_progress_bar=True):
- """Detects faces from all the images present in a given directory.
-
- Arguments:
- path {string} -- a string containing a path that points to the folder containing the images
-
- Keyword Arguments:
- extensions {list} -- list of string containing the extensions to be
- consider in the following format: ``.extension_name`` (default:
- {['.jpg', '.png']}) recursive {bool} -- option wherever to scan the
- folder recursively (default: {False}) show_progress_bar {bool} --
- display a progressbar (default: {True})
-
- Example:
- >>> directory = 'data'
- ... detected_faces = detect_from_directory(directory)
- {A dictionary of [lists containing bounding boxes(x1, y1, x2, y2)]}
-
- """
- if self.verbose:
- logger = logging.getLogger(__name__)
-
- if len(extensions) == 0:
- if self.verbose:
- logger.error("Expected at list one extension, but none was received.")
- raise ValueError
-
- if self.verbose:
- logger.info("Constructing the list of images.")
- additional_pattern = '/**/*' if recursive else '/*'
- files = []
- for extension in extensions:
- files.extend(glob.glob(path + additional_pattern + extension, recursive=recursive))
-
- if self.verbose:
- logger.info("Finished searching for images. %s images found", len(files))
- logger.info("Preparing to run the detection.")
-
- predictions = {}
- for image_path in tqdm(files, disable=not show_progress_bar):
- if self.verbose:
- logger.info("Running the face detector on image: %s", image_path)
- predictions[image_path] = self.detect_from_image(image_path)
-
- if self.verbose:
- logger.info("The detector was successfully run on all %s images", len(files))
-
- return predictions
-
- @property
- def reference_scale(self):
- raise NotImplementedError
-
- @property
- def reference_x_shift(self):
- raise NotImplementedError
-
- @property
- def reference_y_shift(self):
- raise NotImplementedError
-
- @staticmethod
- def tensor_or_path_to_ndarray(tensor_or_path, rgb=True):
- """Convert path (represented as a string) or torch.tensor to a numpy.ndarray
-
- Arguments:
- tensor_or_path {numpy.ndarray, torch.tensor or string} -- path to the image, or the image itself
- """
- if isinstance(tensor_or_path, str):
- return cv2.imread(tensor_or_path) if not rgb else cv2.imread(tensor_or_path)[..., ::-1]
- elif torch.is_tensor(tensor_or_path):
- # Call cpu in case its coming from cuda
- return tensor_or_path.cpu().numpy()[..., ::-1].copy() if not rgb else tensor_or_path.cpu().numpy()
- elif isinstance(tensor_or_path, np.ndarray):
- return tensor_or_path[..., ::-1].copy() if not rgb else tensor_or_path
- else:
- raise TypeError
diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Crypto/SelfTest/Cipher/test_SIV.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Crypto/SelfTest/Cipher/test_SIV.py
deleted file mode 100644
index a80ddc1e2ced2de4cc8ec4a26801135daf8c7614..0000000000000000000000000000000000000000
--- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Crypto/SelfTest/Cipher/test_SIV.py
+++ /dev/null
@@ -1,552 +0,0 @@
-# ===================================================================
-#
-# Copyright (c) 2015, Legrandin
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions
-# are met:
-#
-# 1. Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# 2. Redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in
-# the documentation and/or other materials provided with the
-# distribution.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
-# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
-# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
-# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
-# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-# POSSIBILITY OF SUCH DAMAGE.
-# ===================================================================
-
-import json
-import unittest
-from binascii import unhexlify
-
-from Crypto.SelfTest.st_common import list_test_cases
-from Crypto.SelfTest.loader import load_test_vectors_wycheproof
-
-from Crypto.Util.py3compat import tobytes, bchr
-from Crypto.Cipher import AES
-from Crypto.Hash import SHAKE128
-
-from Crypto.Util.strxor import strxor
-
-
-def get_tag_random(tag, length):
- return SHAKE128.new(data=tobytes(tag)).read(length)
-
-
-class SivTests(unittest.TestCase):
-
- key_256 = get_tag_random("key_256", 32)
- key_384 = get_tag_random("key_384", 48)
- key_512 = get_tag_random("key_512", 64)
- nonce_96 = get_tag_random("nonce_128", 12)
- data = get_tag_random("data", 128)
-
- def test_loopback_128(self):
- for key in self.key_256, self.key_384, self.key_512:
- cipher = AES.new(key, AES.MODE_SIV, nonce=self.nonce_96)
- pt = get_tag_random("plaintext", 16 * 100)
- ct, mac = cipher.encrypt_and_digest(pt)
-
- cipher = AES.new(key, AES.MODE_SIV, nonce=self.nonce_96)
- pt2 = cipher.decrypt_and_verify(ct, mac)
- self.assertEqual(pt, pt2)
-
- def test_nonce(self):
- # Deterministic encryption
- AES.new(self.key_256, AES.MODE_SIV)
-
- cipher = AES.new(self.key_256, AES.MODE_SIV, self.nonce_96)
- ct1, tag1 = cipher.encrypt_and_digest(self.data)
-
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- ct2, tag2 = cipher.encrypt_and_digest(self.data)
- self.assertEqual(ct1 + tag1, ct2 + tag2)
-
- def test_nonce_must_be_bytes(self):
- self.assertRaises(TypeError, AES.new, self.key_256, AES.MODE_SIV,
- nonce=u'test12345678')
-
- def test_nonce_length(self):
- # nonce can be of any length (but not empty)
- self.assertRaises(ValueError, AES.new, self.key_256, AES.MODE_SIV,
- nonce=b"")
-
- for x in range(1, 128):
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=bchr(1) * x)
- cipher.encrypt_and_digest(b'\x01')
-
- def test_block_size_128(self):
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- self.assertEqual(cipher.block_size, AES.block_size)
-
- def test_nonce_attribute(self):
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- self.assertEqual(cipher.nonce, self.nonce_96)
-
- # By default, no nonce is randomly generated
- self.assertFalse(hasattr(AES.new(self.key_256, AES.MODE_SIV), "nonce"))
-
- def test_unknown_parameters(self):
- self.assertRaises(TypeError, AES.new, self.key_256, AES.MODE_SIV,
- self.nonce_96, 7)
- self.assertRaises(TypeError, AES.new, self.key_256, AES.MODE_SIV,
- nonce=self.nonce_96, unknown=7)
-
- # But some are only known by the base cipher
- # (e.g. use_aesni consumed by the AES module)
- AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96,
- use_aesni=False)
-
- def test_encrypt_excludes_decrypt(self):
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- cipher.encrypt_and_digest(self.data)
- self.assertRaises(TypeError, cipher.decrypt, self.data)
-
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- cipher.encrypt_and_digest(self.data)
- self.assertRaises(TypeError, cipher.decrypt_and_verify,
- self.data, self.data)
-
- def test_data_must_be_bytes(self):
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- self.assertRaises(TypeError, cipher.encrypt, u'test1234567890-*')
-
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- self.assertRaises(TypeError, cipher.decrypt_and_verify,
- u'test1234567890-*', b"xxxx")
-
- def test_mac_len(self):
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- _, mac = cipher.encrypt_and_digest(self.data)
- self.assertEqual(len(mac), 16)
-
- def test_invalid_mac(self):
- from Crypto.Util.strxor import strxor_c
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- ct, mac = cipher.encrypt_and_digest(self.data)
-
- invalid_mac = strxor_c(mac, 0x01)
-
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- self.assertRaises(ValueError, cipher.decrypt_and_verify, ct,
- invalid_mac)
-
- def test_hex_mac(self):
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- mac_hex = cipher.hexdigest()
- self.assertEqual(cipher.digest(), unhexlify(mac_hex))
-
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- cipher.hexverify(mac_hex)
-
- def test_bytearray(self):
-
- # Encrypt
- key = bytearray(self.key_256)
- nonce = bytearray(self.nonce_96)
- data = bytearray(self.data)
- header = bytearray(self.data)
-
- cipher1 = AES.new(self.key_256,
- AES.MODE_SIV,
- nonce=self.nonce_96)
- cipher1.update(self.data)
- ct, tag = cipher1.encrypt_and_digest(self.data)
-
- cipher2 = AES.new(key,
- AES.MODE_SIV,
- nonce=nonce)
- key[:3] = b'\xFF\xFF\xFF'
- nonce[:3] = b'\xFF\xFF\xFF'
- cipher2.update(header)
- header[:3] = b'\xFF\xFF\xFF'
- ct_test, tag_test = cipher2.encrypt_and_digest(data)
-
- self.assertEqual(ct, ct_test)
- self.assertEqual(tag, tag_test)
- self.assertEqual(cipher1.nonce, cipher2.nonce)
-
- # Decrypt
- key = bytearray(self.key_256)
- nonce = bytearray(self.nonce_96)
- header = bytearray(self.data)
- ct_ba = bytearray(ct)
- tag_ba = bytearray(tag)
-
- cipher3 = AES.new(key,
- AES.MODE_SIV,
- nonce=nonce)
- key[:3] = b'\xFF\xFF\xFF'
- nonce[:3] = b'\xFF\xFF\xFF'
- cipher3.update(header)
- header[:3] = b'\xFF\xFF\xFF'
- pt_test = cipher3.decrypt_and_verify(ct_ba, tag_ba)
-
- self.assertEqual(self.data, pt_test)
-
- def test_memoryview(self):
-
- # Encrypt
- key = memoryview(bytearray(self.key_256))
- nonce = memoryview(bytearray(self.nonce_96))
- data = memoryview(bytearray(self.data))
- header = memoryview(bytearray(self.data))
-
- cipher1 = AES.new(self.key_256,
- AES.MODE_SIV,
- nonce=self.nonce_96)
- cipher1.update(self.data)
- ct, tag = cipher1.encrypt_and_digest(self.data)
-
- cipher2 = AES.new(key,
- AES.MODE_SIV,
- nonce=nonce)
- key[:3] = b'\xFF\xFF\xFF'
- nonce[:3] = b'\xFF\xFF\xFF'
- cipher2.update(header)
- header[:3] = b'\xFF\xFF\xFF'
- ct_test, tag_test= cipher2.encrypt_and_digest(data)
-
- self.assertEqual(ct, ct_test)
- self.assertEqual(tag, tag_test)
- self.assertEqual(cipher1.nonce, cipher2.nonce)
-
- # Decrypt
- key = memoryview(bytearray(self.key_256))
- nonce = memoryview(bytearray(self.nonce_96))
- header = memoryview(bytearray(self.data))
- ct_ba = memoryview(bytearray(ct))
- tag_ba = memoryview(bytearray(tag))
-
- cipher3 = AES.new(key,
- AES.MODE_SIV,
- nonce=nonce)
- key[:3] = b'\xFF\xFF\xFF'
- nonce[:3] = b'\xFF\xFF\xFF'
- cipher3.update(header)
- header[:3] = b'\xFF\xFF\xFF'
- pt_test = cipher3.decrypt_and_verify(ct_ba, tag_ba)
-
- self.assertEqual(self.data, pt_test)
-
- def test_output_param(self):
-
- pt = b'5' * 128
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- ct, tag = cipher.encrypt_and_digest(pt)
-
- output = bytearray(128)
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- res, tag_out = cipher.encrypt_and_digest(pt, output=output)
- self.assertEqual(ct, output)
- self.assertEqual(res, None)
- self.assertEqual(tag, tag_out)
-
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- res = cipher.decrypt_and_verify(ct, tag, output=output)
- self.assertEqual(pt, output)
- self.assertEqual(res, None)
-
- def test_output_param_memoryview(self):
-
- pt = b'5' * 128
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- ct, tag = cipher.encrypt_and_digest(pt)
-
- output = memoryview(bytearray(128))
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- cipher.encrypt_and_digest(pt, output=output)
- self.assertEqual(ct, output)
-
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- cipher.decrypt_and_verify(ct, tag, output=output)
- self.assertEqual(pt, output)
-
- def test_output_param_neg(self):
- LEN_PT = 128
-
- pt = b'5' * LEN_PT
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- ct, tag = cipher.encrypt_and_digest(pt)
-
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- self.assertRaises(TypeError, cipher.encrypt_and_digest, pt, output=b'0' * LEN_PT)
-
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- self.assertRaises(TypeError, cipher.decrypt_and_verify, ct, tag, output=b'0' * LEN_PT)
-
- shorter_output = bytearray(LEN_PT - 1)
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- self.assertRaises(ValueError, cipher.encrypt_and_digest, pt, output=shorter_output)
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- self.assertRaises(ValueError, cipher.decrypt_and_verify, ct, tag, output=shorter_output)
-
-
-class SivFSMTests(unittest.TestCase):
-
- key_256 = get_tag_random("key_256", 32)
- nonce_96 = get_tag_random("nonce_96", 12)
- data = get_tag_random("data", 128)
-
- def test_invalid_init_encrypt(self):
- # Path INIT->ENCRYPT fails
- cipher = AES.new(self.key_256, AES.MODE_SIV,
- nonce=self.nonce_96)
- self.assertRaises(TypeError, cipher.encrypt, b"xxx")
-
- def test_invalid_init_decrypt(self):
- # Path INIT->DECRYPT fails
- cipher = AES.new(self.key_256, AES.MODE_SIV,
- nonce=self.nonce_96)
- self.assertRaises(TypeError, cipher.decrypt, b"xxx")
-
- def test_valid_init_update_digest_verify(self):
- # No plaintext, fixed authenticated data
- # Verify path INIT->UPDATE->DIGEST
- cipher = AES.new(self.key_256, AES.MODE_SIV,
- nonce=self.nonce_96)
- cipher.update(self.data)
- mac = cipher.digest()
-
- # Verify path INIT->UPDATE->VERIFY
- cipher = AES.new(self.key_256, AES.MODE_SIV,
- nonce=self.nonce_96)
- cipher.update(self.data)
- cipher.verify(mac)
-
- def test_valid_init_digest(self):
- # Verify path INIT->DIGEST
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- cipher.digest()
-
- def test_valid_init_verify(self):
- # Verify path INIT->VERIFY
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- mac = cipher.digest()
-
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- cipher.verify(mac)
-
- def test_valid_multiple_digest_or_verify(self):
- # Multiple calls to digest
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- cipher.update(self.data)
- first_mac = cipher.digest()
- for x in range(4):
- self.assertEqual(first_mac, cipher.digest())
-
- # Multiple calls to verify
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- cipher.update(self.data)
- for x in range(5):
- cipher.verify(first_mac)
-
- def test_valid_encrypt_and_digest_decrypt_and_verify(self):
- # encrypt_and_digest
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- cipher.update(self.data)
- ct, mac = cipher.encrypt_and_digest(self.data)
-
- # decrypt_and_verify
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- cipher.update(self.data)
- pt = cipher.decrypt_and_verify(ct, mac)
- self.assertEqual(self.data, pt)
-
- def test_invalid_multiple_encrypt_and_digest(self):
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- ct, tag = cipher.encrypt_and_digest(self.data)
- self.assertRaises(TypeError, cipher.encrypt_and_digest, b'')
-
- def test_invalid_multiple_decrypt_and_verify(self):
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- ct, tag = cipher.encrypt_and_digest(self.data)
-
- cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
- cipher.decrypt_and_verify(ct, tag)
- self.assertRaises(TypeError, cipher.decrypt_and_verify, ct, tag)
-
-
-def transform(tv):
- new_tv = [[unhexlify(x) for x in tv[0].split("-")]]
- new_tv += [ unhexlify(x) for x in tv[1:5]]
- if tv[5]:
- nonce = unhexlify(tv[5])
- else:
- nonce = None
- new_tv += [ nonce ]
- return new_tv
-
-
-class TestVectors(unittest.TestCase):
- """Class exercising the SIV test vectors found in RFC5297"""
-
- # This is a list of tuples with 5 items:
- #
- # 1. Header + '|' + plaintext
- # 2. Header + '|' + ciphertext + '|' + MAC
- # 3. AES-128 key
- # 4. Description
- # 5. Dictionary of parameters to be passed to AES.new().
- # It must include the nonce.
- #
- # A "Header" is a dash ('-') separated sequece of components.
- #
- test_vectors_hex = [
- (
- '101112131415161718191a1b1c1d1e1f2021222324252627',
- '112233445566778899aabbccddee',
- '40c02b9690c4dc04daef7f6afe5c',
- '85632d07c6e8f37f950acd320a2ecc93',
- 'fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff',
- None
- ),
- (
- '00112233445566778899aabbccddeeffdeaddadadeaddadaffeeddccbbaa9988' +
- '7766554433221100-102030405060708090a0',
- '7468697320697320736f6d6520706c61696e7465787420746f20656e63727970' +
- '74207573696e67205349562d414553',
- 'cb900f2fddbe404326601965c889bf17dba77ceb094fa663b7a3f748ba8af829' +
- 'ea64ad544a272e9c485b62a3fd5c0d',
- '7bdb6e3b432667eb06f4d14bff2fbd0f',
- '7f7e7d7c7b7a79787776757473727170404142434445464748494a4b4c4d4e4f',
- '09f911029d74e35bd84156c5635688c0'
- ),
- ]
-
- test_vectors = [ transform(tv) for tv in test_vectors_hex ]
-
- def runTest(self):
- for assoc_data, pt, ct, mac, key, nonce in self.test_vectors:
-
- # Encrypt
- cipher = AES.new(key, AES.MODE_SIV, nonce=nonce)
- for x in assoc_data:
- cipher.update(x)
- ct2, mac2 = cipher.encrypt_and_digest(pt)
- self.assertEqual(ct, ct2)
- self.assertEqual(mac, mac2)
-
- # Decrypt
- cipher = AES.new(key, AES.MODE_SIV, nonce=nonce)
- for x in assoc_data:
- cipher.update(x)
- pt2 = cipher.decrypt_and_verify(ct, mac)
- self.assertEqual(pt, pt2)
-
-
-class TestVectorsWycheproof(unittest.TestCase):
-
- def __init__(self):
- unittest.TestCase.__init__(self)
- self._id = "None"
-
- def setUp(self):
- self.tv = load_test_vectors_wycheproof(("Cipher", "wycheproof"),
- "aes_siv_cmac_test.json",
- "Wycheproof AES SIV")
-
- def shortDescription(self):
- return self._id
-
- def test_encrypt(self, tv):
- self._id = "Wycheproof Encrypt AES-SIV Test #" + str(tv.id)
-
- cipher = AES.new(tv.key, AES.MODE_SIV)
- cipher.update(tv.aad)
- ct, tag = cipher.encrypt_and_digest(tv.msg)
- if tv.valid:
- self.assertEqual(tag + ct, tv.ct)
-
- def test_decrypt(self, tv):
- self._id = "Wycheproof Decrypt AES_SIV Test #" + str(tv.id)
-
- cipher = AES.new(tv.key, AES.MODE_SIV)
- cipher.update(tv.aad)
- try:
- pt = cipher.decrypt_and_verify(tv.ct[16:], tv.ct[:16])
- except ValueError:
- assert not tv.valid
- else:
- assert tv.valid
- self.assertEqual(pt, tv.msg)
-
- def runTest(self):
-
- for tv in self.tv:
- self.test_encrypt(tv)
- self.test_decrypt(tv)
-
-
-class TestVectorsWycheproof2(unittest.TestCase):
-
- def __init__(self):
- unittest.TestCase.__init__(self)
- self._id = "None"
-
- def setUp(self):
- self.tv = load_test_vectors_wycheproof(("Cipher", "wycheproof"),
- "aead_aes_siv_cmac_test.json",
- "Wycheproof AEAD SIV")
-
- def shortDescription(self):
- return self._id
-
- def test_encrypt(self, tv):
- self._id = "Wycheproof Encrypt AEAD-AES-SIV Test #" + str(tv.id)
-
- cipher = AES.new(tv.key, AES.MODE_SIV, nonce=tv.iv)
- cipher.update(tv.aad)
- ct, tag = cipher.encrypt_and_digest(tv.msg)
- if tv.valid:
- self.assertEqual(ct, tv.ct)
- self.assertEqual(tag, tv.tag)
-
- def test_decrypt(self, tv):
- self._id = "Wycheproof Decrypt AEAD-AES-SIV Test #" + str(tv.id)
-
- cipher = AES.new(tv.key, AES.MODE_SIV, nonce=tv.iv)
- cipher.update(tv.aad)
- try:
- pt = cipher.decrypt_and_verify(tv.ct, tv.tag)
- except ValueError:
- assert not tv.valid
- else:
- assert tv.valid
- self.assertEqual(pt, tv.msg)
-
- def runTest(self):
-
- for tv in self.tv:
- self.test_encrypt(tv)
- self.test_decrypt(tv)
-
-
-def get_tests(config={}):
- wycheproof_warnings = config.get('wycheproof_warnings')
-
- tests = []
- tests += list_test_cases(SivTests)
- tests += list_test_cases(SivFSMTests)
- tests += [ TestVectors() ]
- tests += [ TestVectorsWycheproof() ]
- tests += [ TestVectorsWycheproof2() ]
- return tests
-
-
-if __name__ == '__main__':
- suite = lambda: unittest.TestSuite(get_tests())
- unittest.main(defaultTest='suite')
diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/altair/vegalite/v3/tests/test_theme.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/altair/vegalite/v3/tests/test_theme.py
deleted file mode 100644
index 430c2193517f9b404c1183231ec05085b4e305ae..0000000000000000000000000000000000000000
--- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/altair/vegalite/v3/tests/test_theme.py
+++ /dev/null
@@ -1,20 +0,0 @@
-import pytest
-
-import altair.vegalite.v3 as alt
-from altair.vegalite.v3.theme import VEGA_THEMES
-
-
-@pytest.fixture
-def chart():
- return alt.Chart("data.csv").mark_bar().encode(x="x:Q")
-
-
-def test_vega_themes(chart):
- for theme in VEGA_THEMES:
- with alt.themes.enable(theme):
- dct = chart.to_dict()
- assert dct["usermeta"] == {"embedOptions": {"theme": theme}}
- assert dct["config"] == {
- "view": {"width": 400, "height": 300},
- "mark": {"tooltip": None},
- }
diff --git a/spaces/asgaardlab/CLIPxGamePhysics/app.py b/spaces/asgaardlab/CLIPxGamePhysics/app.py
deleted file mode 100644
index 0d18c61fca742e02ee3e0faee5d7ea8bd8450577..0000000000000000000000000000000000000000
--- a/spaces/asgaardlab/CLIPxGamePhysics/app.py
+++ /dev/null
@@ -1,253 +0,0 @@
-import csv
-import os
-import pickle
-import random
-import sys
-from collections import Counter
-from glob import glob
-
-import clip
-import gdown
-import gradio as gr
-import numpy as np
-import psutil
-import torch
-import torchvision
-from datasets import load_dataset
-from tqdm import tqdm
-
-from SimSearch import FaissCosineNeighbors
-
-csv.field_size_limit(sys.maxsize)
-
-# Download Embeddings
-gdown.cached_download(
- url="https://huggingface.co/datasets/taesiri/GTA_V_CLIP_Embeddings/resolve/main/mini-GTA-V-Embeddings.zip",
- path="./GTA-V-Embeddings.zip",
- quiet=False,
- md5="b1228503d5a89eef7e35e2cbf86b2fc0",
-)
-
-# EXTRACT
-torchvision.datasets.utils.extract_archive(
- from_path="GTA-V-Embeddings.zip",
- to_path="Embeddings/VIT32/",
- remove_finished=False,
-)
-
-# Load videos from Dataset
-gta_v_videos = load_dataset("taesiri/GamePhysics_Grand_Theft_Auto_V")
-post_id_to_video_path = {
- os.path.splitext(os.path.basename(x))[0]: x
- for x in gta_v_videos["Grand_Theft_Auto_V"][:]["video_file_path"]
-}
-# Initialize CLIP model
-clip.available_models()
-
-
-# Log runtime environment info
-def log_runtime_information():
- print(f"CPU Count: {psutil.cpu_count()}")
- print(f"Virtual Memory: {psutil.virtual_memory()}")
- print(f"Swap Memory: {psutil.swap_memory()}")
-
-
-# # Searcher
-class GamePhysicsSearcher:
- def __init__(self, CLIP_MODEL, GAME_NAME, EMBEDDING_PATH="./Embeddings/VIT32/"):
- self.CLIP_MODEL = CLIP_MODEL
- self.GAME_NAME = GAME_NAME
- self.simsearcher = FaissCosineNeighbors()
-
- self.all_embeddings = glob(f"{EMBEDDING_PATH}{self.GAME_NAME}/*.npy")
-
- self.filenames = [os.path.basename(x) for x in self.all_embeddings]
- self.file_to_class_id = {x: i for i, x in enumerate(self.filenames)}
- self.class_id_to_file = {i: x for i, x in enumerate(self.filenames)}
- self.build_index()
-
- def read_features(self, file_path):
- with open(file_path, "rb") as f:
- video_features = pickle.load(f)
- return video_features
-
- def read_all_features(self):
- features = {}
- filenames_extended = []
-
- X_train = []
- y_train = []
-
- for i, vfile in enumerate(tqdm(self.all_embeddings)):
- vfeatures = self.read_features(vfile)
- features[vfile.split("/")[-1]] = vfeatures
- X_train.extend(vfeatures)
- y_train.extend([i] * vfeatures.shape[0])
- filenames_extended.extend(vfeatures.shape[0] * [vfile.split("/")[-1]])
-
- X_train = np.asarray(X_train)
- y_train = np.asarray(y_train)
-
- return X_train, y_train
-
- def build_index(self):
- X_train, y_train = self.read_all_features()
- self.simsearcher.fit(X_train, y_train)
-
- def text_to_vector(self, query):
- text_tokens = clip.tokenize(query)
- with torch.no_grad():
- text_features = self.CLIP_MODEL.encode_text(text_tokens).float()
- text_features /= text_features.norm(dim=-1, keepdim=True)
- return text_features
-
- # Source: https://stackoverflow.com/a/480227
- def f7(self, seq):
- seen = set()
- seen_add = seen.add # This is for performance improvement, don't remove
- return [x for x in seq if not (x in seen or seen_add(x))]
-
- def search_top_k(self, q, k=5, pool_size=1000, search_mod="Majority"):
- q = self.text_to_vector(q)
- nearest_data_points = self.simsearcher.get_nearest_labels(q, pool_size)
-
- if search_mod == "Majority":
- topKs = [x[0] for x in Counter(nearest_data_points[0]).most_common(k)]
- elif search_mod == "Top-K":
- topKs = list(self.f7(nearest_data_points[0]))[:k]
-
- video_filename = [
- post_id_to_video_path[self.class_id_to_file[x].replace(".npy", "")]
- for x in topKs
- ]
-
- return video_filename
-
-
-################ SEARCH CORE ################
-# CRAETE CLIP MODEL
-vit_model, vit_preprocess = clip.load("ViT-B/32")
-vit_model.eval()
-
-saved_searchers = {}
-
-
-def gradio_search(query, game_name, selected_model, aggregator, pool_size, k=6):
- # print(query, game_name, selected_model, aggregator, pool_size)
- if f"{game_name}_{selected_model}" in saved_searchers.keys():
- searcher = saved_searchers[f"{game_name}_{selected_model}"]
- else:
- if selected_model == "ViT-B/32":
- model = vit_model
- searcher = GamePhysicsSearcher(CLIP_MODEL=model, GAME_NAME=game_name)
- else:
- raise
-
- saved_searchers[f"{game_name}_{selected_model}"] = searcher
-
- results = []
- relevant_videos = searcher.search_top_k(
- query, k=k, pool_size=pool_size, search_mod=aggregator
- )
-
- params = ", ".join(
- map(str, [query, game_name, selected_model, aggregator, pool_size])
- )
- results.append(params)
-
- for v in relevant_videos:
- results.append(v)
- sid = v.split("/")[-1].split(".")[0]
- results.append(
- f'Link to the post'
- )
-
- print(f"found {len(results)} results")
- return results
-
-
-def main():
- list_of_games = ["Grand Theft Auto V"]
-
- # GRADIO APP
- main = gr.Interface(
- fn=gradio_search,
- inputs=[
- gr.Textbox(
- lines=1,
- placeholder="Search Query",
- value="A person flying in the air",
- label="Query",
- ),
- gr.Radio(list_of_games, label="Game To Search"),
- gr.Radio(["ViT-B/32"], label="MODEL"),
- gr.Radio(["Majority", "Top-K"], label="Aggregator"),
- gr.Slider(300, 2000, label="Pool Size", value=1000),
- ],
- outputs=[
- gr.Textbox(type="auto", label="Search Params"),
- gr.Video(type="mp4", label="Result 1"),
- gr.Markdown(),
- gr.Video(type="mp4", label="Result 2"),
- gr.Markdown(),
- gr.Video(type="mp4", label="Result 3"),
- gr.Markdown(),
- gr.Video(type="mp4", label="Result 4"),
- gr.Markdown(),
- gr.Video(type="mp4", label="Result 5"),
- gr.Markdown(),
- ],
- examples=[
- ["A red car", list_of_games[0], "ViT-B/32", "Top-K", 1000],
- ["A person wearing pink", list_of_games[0], "ViT-B/32", "Top-K", 1000],
- ["A car flying in the air", list_of_games[0], "ViT-B/32", "Majority", 1000],
- [
- "A person flying in the air",
- list_of_games[0],
- "ViT-B/32",
- "Majority",
- 1000,
- ],
- [
- "A car in vertical position",
- list_of_games[0],
- "ViT-B/32",
- "Majority",
- 1000,
- ],
- ["A bike inside a car", list_of_games[0], "ViT-B/32", "Majority", 1000],
- ["A bike on a wall", list_of_games[0], "ViT-B/32", "Majority", 1000],
- ["A car stuck in a rock", list_of_games[0], "ViT-B/32", "Majority", 1000],
- ["A car stuck in a tree", list_of_games[0], "ViT-B/32", "Majority", 1000],
- ],
- )
-
- blocks = gr.Blocks()
- with blocks:
- gr.Markdown(
- """
- # CLIP + GamePhysics - Searching dataset of Gameplay bugs
-
- This demo shows how to use the CLIP model to search for gameplay bugs in a video game.
-
- Enter your query and select the game you want to search for.
- """
- )
-
- gr.Markdown(
- """
- [Website](https://asgaardlab.github.io/CLIPxGamePhysics/) - [Paper](https://arxiv.org/abs/2203.11096)
- """
- )
-
- gr.TabbedInterface([main], ["GTA V Demo"])
-
- blocks.launch(
- debug=True,
- enable_queue=True,
- )
-
-
-if __name__ == "__main__":
- log_runtime_information()
- main()
diff --git a/spaces/at2507/SM_NLP_RecoSys/Data/Mentor_interviews/Ricardo J Martinez.html b/spaces/at2507/SM_NLP_RecoSys/Data/Mentor_interviews/Ricardo J Martinez.html
deleted file mode 100644
index 388a7fa542a04fe1f5fa7fbac0fd793e262746f5..0000000000000000000000000000000000000000
--- a/spaces/at2507/SM_NLP_RecoSys/Data/Mentor_interviews/Ricardo J Martinez.html
+++ /dev/null
@@ -1,134 +0,0 @@
-
-
-
- Ricardo J Martinez
-
-
-
-
-
During my professional growth as a Data Scientist and Software Engineer, I had a lot of mentors along the way that I felt was the reason I've been successful in this field. I enjoy working with others in finding their full potential and developing their skills. Personal & Technical development is a very important aspect for me and would love to give folks interested in Data Science an opportunity to develop those skillsets and also be successful.
Interview
How did you hear about SM?
Google search
Previously was mentoring with Thinkful
Was looking for mentorship opportunities, and came across SM
(My email helped)
Mentorship experience?
Mentoring at Thinkful
1:1 relationships with a couple of folks
But people started focused more on the eng side than DS
They had to cut down their pool of their DS mentors
Also a manager at Mailchimp
What are beginners lacking?
Confidence - imposter syndrome is common
And how can you help?
Overcome that imposter syndrome - Get little wins
Tell my story I come from a baseball background. College and minor leagues
I went back to school and I felt the same way
Working with peers, mentors
slowly gained experience, eventually got a higher degree in ML
Being frank and honest. It's going to take time. Just keep trying
If you have questions. Don't be shy - ask ask ask
Then start doing the technical things, how models work, processed
-
-
Questions about SM?
So this is like a dating app? How does it work?
How does the ISA work?
How flexible is the mentorship length?
Do I have to pay tax on the ISA income?
Can I send the funds to an LLC?
What does the process look like to take on more mentees?
-
-
-
-
-
-
\ No newline at end of file
diff --git a/spaces/avid-ml/bias-detection/scripts/winobias.py b/spaces/avid-ml/bias-detection/scripts/winobias.py
deleted file mode 100644
index 19b389496d3c9ca7fa824e7cab4603549863235b..0000000000000000000000000000000000000000
--- a/spaces/avid-ml/bias-detection/scripts/winobias.py
+++ /dev/null
@@ -1,96 +0,0 @@
-# !pip install -qq transformers datasets evaluate
-from pathlib import Path
-import math
-from datasets import load_dataset
-import pandas as pd
-from transformers import pipeline, AutoTokenizer, AutoModel, AutoModelForMaskedLM
-from evaluate import load
-import warnings
-warnings.filterwarnings("ignore")
-
-def generate_sentences(cloze_phrase, bias_pronoun, anti_bias_pronoun):
- biased_phrase = cloze_phrase.replace('[MASK]', bias_pronoun)
- antibiased_phrase = cloze_phrase.replace('[MASK]', anti_bias_pronoun)
- return (biased_phrase, antibiased_phrase)
-
-def calculate_perplexity(inputlist, mname):
- resultsdict={}
- perplexity = load("perplexity", module_type="metric")
- ppl = perplexity.compute(input_texts=inputlist, model_id=mname, add_start_token=False)
- return(ppl['perplexities'])
-
-def calculate_biases(cloze_phrase, bias_pronoun, anti_bias_pronoun, biased_ppl, anti_biased_ppl):
- p_bias = math.pow(1 / biased_ppl, len(cloze_phrase.split()))
- p_anti_bias = math.pow(1 / anti_biased_ppl, len(cloze_phrase.split()))
- if anti_bias_pronoun in ['she','her','herself']:
- f_proba = p_anti_bias
- m_proba = p_bias
- av_bias = 2 * (m_proba / (f_proba+m_proba) - 0.5)
- else:
- m_proba = p_anti_bias
- f_proba = p_bias
- av_bias = 2 * (f_proba / (f_proba+m_proba) - 0.5)
- m_bias = 2 * (m_proba / (f_proba+m_proba) - 0.5)
- f_bias = 2 * (f_proba / (f_proba+m_proba) - 0.5)
- av_bias = max(0, av_bias)
- return(p_bias, p_anti_bias, m_bias, f_bias, av_bias)
-
-def calculate_mlm_bias(cloze_phrase, bias_p, anti_bias_p, mname):
- f_bias = 0.0
- m_bias = 0.0
- if 'roberta' in mname.model.name_or_path:
- preds = mname(cloze_phrase.replace('[MASK]', ''))
- else:
- preds = mname(cloze_phrase)
- pred_toks = [i['token_str'].strip() for i in preds]
- if anti_bias_p in pred_toks:
- logit_anti_bias = [i['score'] for i in preds if i['token_str'].strip() == anti_bias_p][0]
- else:
- logit_anti_bias = 0.0
- if bias_p in pred_toks:
- logit_bias = [i['score'] for i in preds if i['token_str'].strip() == bias_p][0]
- else:
- logit_bias = 0.0
- if anti_bias_p in ['she','her','herself']:
- f_proba = 1 / (1 + math.exp(-logit_anti_bias))
- m_proba = 1 / (1 + math.exp(-logit_bias))
- av_bias = 2 * (m_proba / (f_proba+m_proba) - 0.5)
- else:
- m_proba = 1 / (1 + math.exp(-logit_anti_bias))
- f_proba = 1 / (1 + math.exp(-logit_bias))
- av_bias = 2 * (f_proba / (f_proba+m_proba) - 0.5)
- m_bias = 2 * (m_proba / (f_proba+m_proba) - 0.5)
- f_bias = 2 * (f_proba / (f_proba+m_proba) - 0.5)
- av_bias = max(0, av_bias)
- return(m_bias, f_bias, av_bias)
-
-def calculate_clm_bias(winodset, mname):
- winodset[['biased_phrase','anti_biased_phrase']] = winodset.apply(lambda row: generate_sentences(row['cloze_phrase'],row['bias_pronoun'],row['anti_bias_pronoun']), axis=1, result_type="expand")
- biased_list = winodset['biased_phrase'].tolist()
- unbiased_list = winodset['anti_biased_phrase'].tolist()
- winodset['biased_ppl'] = calculate_perplexity(biased_list, mname)
- winodset['anti_biased_ppl'] = calculate_perplexity(unbiased_list, mname)
- winodset[['p_bias','p_anti_bias', 'm_bias','f_bias', 'av_bias']] = winodset.apply(lambda row: calculate_biases(row['cloze_phrase'],row['bias_pronoun'],row['anti_bias_pronoun'], row['biased_ppl'], row['anti_biased_ppl']), axis=1, result_type="expand")
- return(winodset)
-
-def calculate_wino_bias(modelname, modeltype, winodf=None):
- winopath = 'data/'+modelname.replace('/','')+'_winobias.csv'
- if Path(winopath).is_file():
- print("loading local data")
- results_df = pd.read_csv(winopath)
- else:
- winobias1 = load_dataset("sasha/wino_bias_cloze1", split="test")
- winobias2 = load_dataset("sasha/wino_bias_cloze2", split= "test")
- wino1_df = pd.DataFrame(winobias1)
- wino2_df = pd.DataFrame(winobias2)
- results_df= pd.concat([wino1_df, wino2_df], axis=0)
- if modeltype == "MLM":
- print("Loading MLM!")
- unmasker = pipeline('fill-mask', model=modelname, top_k=10)
- results_df[['m_bias','f_bias', 'av_bias']] = results_df.apply(lambda x: calculate_mlm_bias(x.cloze_phrase, x.bias_pronoun, x.anti_bias_pronoun, unmasker), axis=1, result_type="expand")
- results_df.to_csv(winopath)
- elif modeltype == "CLM":
- print("Loading CLM!")
- results_df= calculate_clm_bias(results_df,modelname)
- results_df.to_csv(winopath)
- return(results_df)
\ No newline at end of file
diff --git a/spaces/awacke1/CardWriterPro/specific_extraction.py b/spaces/awacke1/CardWriterPro/specific_extraction.py
deleted file mode 100644
index 6be7b29fe557288b89449ab5a28052ce40e43727..0000000000000000000000000000000000000000
--- a/spaces/awacke1/CardWriterPro/specific_extraction.py
+++ /dev/null
@@ -1,528 +0,0 @@
-import re
-import streamlit as st
-from modelcards import CardData, ModelCard
-from markdownTagExtract import tag_checker,listToString,to_markdown
-#from specific_extraction import extract_it
-
-
-# from persist import persist
-#global bytes_data
-
-
-################################################################
-#### Markdown parser logic #################################
-################################################################
-
-def file_upload():
- bytes_data = st.session_state.markdown_upload
- return bytes_data
-
-
-# Sets up the basics
-model_card_md = file_upload() # this is where the new model card will be read in from
-model_card_md = model_card_md#.decode("utf-8")
-# Does metadata appear in any other format than this?
-metadata_re = re.compile("^---(.*?)---", re.DOTALL)
-header_re = re.compile("^\s*# (.*)", re.MULTILINE)
-subheader_re = re.compile("^\s*## (.*)", re.MULTILINE)
-subsubheader_re = re.compile("^\s*### (.*)", re.MULTILINE)
-subsubsubheader_re = re.compile("^\s*#### (.*)", re.MULTILINE)
-# We could be a lot more flexible on this re.
-# We require keys to be bold-faced here.
-# We don't have to require bold, as long as it's key:value
-# **License:**
-# Bold terms use ** or __
-# Allows the mixing of ** and __ for bold but eh whatev
-key_value_re = re.compile("^\s*([*_]{2}[^*_]+[*_]{2})([^\n]*)", re.MULTILINE)
-# Hyphens or stars mark list items.
-# Unordered list
-list_item_re = re.compile("^\s*[-*+]\s+.*", re.MULTILINE)
-# This is the ordered list
-enum_re = re.compile("^\s*[0-9].*", re.MULTILINE)
-table_re = re.compile("^\s*\|.*", re.MULTILINE)
-text_item_re = re.compile("^\s*[A-Za-z(](.*)", re.MULTILINE)
-# text_item_re = re.compile("^\s*#\s*.*", re.MULTILINE)
-# Allows the mixing of -* and *- for italics but eh whatev
-italicized_text_item_re = re.compile(
- "^[_*][^_*\s].*\n?.*[^_*][_*]$", flags=re.MULTILINE
-)
-tag_re = re.compile("^\s*<.*", re.MULTILINE)
-image_re = re.compile("!\[.*\]\(.*\)", re.MULTILINE)
-
-
-subheader_re_dict = {}
-subheader_re_dict[header_re] = subheader_re
-subheader_re_dict[subheader_re] = subsubheader_re
-subheader_re_dict[subsubheader_re] = subsubsubheader_re
-
-
-def get_metadata(section_text):
- return list(metadata_re.finditer(section_text))
-
-
-def find_images(section_text):
- return list(image_re.finditer(section_text))
-
-
-def find_tags(section_text):
- return list(tag_re.finditer(section_text))
-
-
-def find_tables(section_text):
- return list(table_re.finditer(section_text))
-
-
-def find_enums(section_text):
- return list(enum_re.finditer(section_text))
-
-
-# Extracts the stuff from the .md file
-def find_key_values(section_text):
- return list(key_value_re.finditer(section_text))
-
-
-def find_lists(section_text):
- # Find lists: Those lines starting with either '-' or '*'
- return list(list_item_re.finditer(section_text))
-
-
-def find_texts(section_text):
- # Find texts: Free writing within a section
- basic_text = list(text_item_re.finditer(section_text))
- ital_text = list(italicized_text_item_re.finditer(section_text))
- free_text = basic_text + ital_text
- return free_text
-
-
-def find_headers(full_text):
- headers = list(header_re.finditer(full_text))
- subheaders = list(subheader_re.finditer(full_text))
- subsubheaders = list(subsubheader_re.finditer(full_text))
- subsubsubheaders = list(subsubsubheader_re.finditer(full_text))
- return (headers, subheaders, subsubheaders, subsubsubheaders)
-
-
-metadata_list = get_metadata(model_card_md)
-if metadata_list != []:
- metadata_end = metadata_list[-1].span()[-1]
- print("Metadata extracted")
- # Metadata processing can happen here.
- # For now I'm just ignoring it.
- model_card_md = model_card_md[metadata_end:]
-else:
- print("No metadata found")
-
-# Matches of all header types
-headers_list = find_headers(model_card_md)
-print("Headers extracted")
-# This type of header (one #)
-headers = headers_list[0]
-## This type of header (two ##)
-subheaders = headers_list[1]
-### This type of header
-subsubheaders = headers_list[2]
-#### This type of header
-subsubsubheaders = headers_list[3]
-
-# Matches of bulleted lists
-lists_list = find_lists(model_card_md)
-print("Bulleted lists extracted")
-
-enums_list = find_enums(model_card_md)
-print("Enumerated lists extracted")
-
-key_value_list = find_key_values(model_card_md)
-print("Key values extracted")
-
-tables_list = find_tables(model_card_md)
-print("Tables extracted")
-
-tags_list = find_tags(model_card_md)
-print("Markup tags extracted")
-
-images_list = find_images(model_card_md)
-print("Images extracted")
-
-# Matches of free text within a section
-texts_list = find_texts(model_card_md)
-print("Free text extracted")
-
-
-# List items have the attribute: value;
-# This provides for special handling of those strings,
-# allowing us to check if it's a list item in order to split/print ok.
-LIST_ITEM = "List item"
-KEY_VALUE = "Key: Value"
-FREE_TEXT = "Free text"
-ENUM_LIST_ITEM = "Enum item"
-TABLE_ITEM = "Table item"
-TAG_ITEM = "Markup tag"
-IMAGE_ITEM = "Image"
-
-
-def create_span_dict(match_list, match_type):
- """
- Creates a dictionary made out of all the spans.
- This is useful for knowing which types to fill out with what in the app.
- Also useful for checking if there are spans in the .md file that we've missed.
- """
- span_dict = {}
- for match in match_list:
- if len(match.group().strip()) > 0:
- span_dict[(match.span())] = (match.group(), match_type)
- return span_dict
-
-
-metadata_span_dict = create_span_dict(metadata_list, "Metadata")
-# Makes a little dict for each span type
-header_span_dict = create_span_dict(headers, "# Header")
-subheader_span_dict = create_span_dict(subheaders, "## Subheader")
-subsubheader_span_dict = create_span_dict(subsubheaders, "### Subsubheader")
-subsubsubheader_span_dict = create_span_dict(subsubsubheaders, "#### Subsubsubheader")
-key_value_span_dict = create_span_dict(key_value_list, KEY_VALUE)
-lists_span_dict = create_span_dict(lists_list, LIST_ITEM)
-enums_span_dict = create_span_dict(enums_list, ENUM_LIST_ITEM)
-tables_span_dict = create_span_dict(tables_list, TABLE_ITEM)
-tags_span_dict = create_span_dict(tags_list, TAG_ITEM)
-images_span_dict = create_span_dict(images_list, IMAGE_ITEM)
-texts_span_dict = create_span_dict(texts_list, FREE_TEXT)
-
-# We don't have to have these organized by type necessarily.
-# Doing it here for clarity.
-all_spans_dict = {}
-all_spans_dict["headers"] = header_span_dict
-all_spans_dict["subheaders"] = subheader_span_dict
-all_spans_dict["subsubheaders"] = subsubheader_span_dict
-all_spans_dict["subsubsubheaders"] = subsubsubheader_span_dict
-all_spans_dict[LIST_ITEM] = lists_span_dict
-all_spans_dict[KEY_VALUE] = key_value_span_dict
-all_spans_dict[TABLE_ITEM] = tables_span_dict
-all_spans_dict[ENUM_LIST_ITEM] = enums_span_dict
-all_spans_dict[TAG_ITEM] = tags_span_dict
-all_spans_dict[IMAGE_ITEM] = images_span_dict
-all_spans_dict[FREE_TEXT] = texts_span_dict
-
-
-def get_sorted_spans(spans_dict):
- merged_spans = {}
- for span_dict in spans_dict.values():
- merged_spans.update(span_dict)
- sorted_spans = sorted(merged_spans)
- return sorted_spans, merged_spans
-
-
-sorted_spans, merged_spans = get_sorted_spans(all_spans_dict)
-
-# Sanity/Parse check. Have we captured all spans in the .md file?
-if sorted_spans[0][0] != 0:
- print("FYI, our spans don't start at the start of the file.")
- print("We did not catch this start:")
- print(model_card_md[: sorted_spans[0][0]])
-
-for idx in range(len(sorted_spans) - 1):
- last_span_end = sorted_spans[idx][1]
- new_span_start = sorted_spans[idx + 1][0]
- if new_span_start > last_span_end + 1:
- start_nonparse = sorted_spans[idx]
- end_nonparse = sorted_spans[idx + 1]
- text = model_card_md[start_nonparse[1] : end_nonparse[0]]
- if text.strip():
- print("Found an unparsed span in the file:")
- print(start_nonparse)
- print(" ---> ")
- print(end_nonparse)
- print(text)
-
-# print(header_span_dict)
-def section_map_to_help_text(text_retrieved):
-
- presit_states = {
- "## Model Details": "Give an overview of your model, the relevant research paper, who trained it, etc.",
- "## How to Get Started with the Model": "Give an overview of how to get started with the model",
- "## Limitations and Biases": "Provide an overview of the possible Limitations and Risks that may be associated with this model",
- "## Uses": "Detail the potential uses, intended use and out-of-scope uses for this model",
- "## Training": "Provide an overview of the Training Data and Training Procedure for this model",
- "## Evaluation Results": "Detail the Evaluation Results for this model",
- "## Environmental Impact": "Provide an estimate for the carbon emissions: Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here.",
- "## Citation Information": "How to best cite the model authors",
- "## Glossary": "If relevant, include terms and calculations in this section that can help readers understand the model or model card.",
- "## More Information": "Any additional information",
- "## Model Card Authors": "This section provides another layer of transparency and accountability. Whose views is this model card representing? How many voices were included in its construction? Etc.",
- "Model Card Contact": "Mediums to use, in order to contact the model creators",
- "## Technical Specifications": " Additional technical information",
- '## Model Examination': " Examining the model",
- }
-
- for key in presit_states:
- if key == text_retrieved:
- return presit_states(key)
-
-
-def section_map_to_persist(text_retrieved):
-
- presit_states = {
- "Model_details_text": "## Model Details",
- "Model_how_to": "## How to Get Started with the Model",
- "Model_Limits_n_Risks": "## Limitations and Biases",
- "Model_uses": "## Uses",
- "Model_training": "## Training",
- "Model_Eval": "## Evaluation Results",
- "Model_carbon": "## Environmental Impact",
- "Model_cite": "## Citation Information",
- "Glossary": "## Glossary",
- "More_info": "## More Information",
- "Model_card_authors": "## Model Card Authors",
- "Model_card_contact": "## Model Card Contact",
- "Technical_specs": "## Technical specifications",
- "Model_examin": "## Model Examination",
- }
-
- for key in presit_states:
- if presit_states[key] == text_retrieved:
- return key
-
-
-def main():
- # st.write('here')
- print(extract_it("Model_details_text"))
-
-
-def extract_headers():
- headers = {}
- subheaders = {}
- subsubheaders = {}
- subsubsubheaders = {}
- previous = (None, None, None, None)
-
- for s in sorted_spans:
- if merged_spans[s][1] == "# Header":
- headers[s] = (sorted_spans.index(s), previous[0])
- previous = (sorted_spans.index(s), previous[1], previous[2], previous[3])
- if merged_spans[s][1] == "## Subheader":
- subheaders[s] = (sorted_spans.index(s), previous[1])
- previous = (previous[0], sorted_spans.index(s), previous[2], previous[3])
- if merged_spans[s][1] == "### Subsubheader":
- subsubheaders[s] = (sorted_spans.index(s), previous[2])
- previous = (previous[0], previous[1], sorted_spans.index(s), previous[3])
- if merged_spans[s][1] == "#### Subsubsubheader":
- subsubsubheaders[s] = (sorted_spans.index(s), previous[3])
- previous = (previous[0], previous[1], previous[2], sorted_spans.index(s))
-
- return headers, subheaders, subsubheaders, subsubsubheaders
-
-
-def stringify():
- headers, subheaders, subsubheaders, subsubsubheaders = extract_headers()
- headers_strings = {}
- subheaders_strings = {}
- subsubheaders_strings = {}
- subsubsubheaders_strings = {}
-
- first = None
- for i in headers:
- if headers[i][1] == None:
- continue
- sub_spans = sorted_spans[headers[i][1] : headers[i][0]]
- lines = []
- for x in sub_spans:
- lines.append(merged_spans[x][0])
- try:
- name = lines[0]
- except:
- name = "Model Details"
- lines = "".join(lines)
- # print(merged_spans[i][0] + "-------------------")
- # print(lines)
- headers_strings[
- name.replace("\n# ", "")
- .replace(" ", "")
- .replace(" ", "")
- .replace("\n", "")
- .replace("{{", "")
- .replace("}}", "")
- ] = lines
- first = i
-
- first = None
- for i in subheaders:
- if subheaders[i][1] == None:
- continue
- sub_spans = sorted_spans[subheaders[i][1] : subheaders[i][0]]
- lines = []
- for x in sub_spans:
- if merged_spans[x][1] == "## Subheader" and first == None:
- break
- elif merged_spans[x][1] == "# Header":
- break
- else:
- lines.append(merged_spans[x][0])
- try:
- name = lines[0]
- except:
- name = "Model Details"
- lines = "".join(lines)
- # print(merged_spans[i][0] + "-------------------")
- # print(lines)
- subheaders_strings[
- name.replace("\n# ", "").replace(" ", "").replace(" ", "")
- ] = lines
- first = i
-
- first = None
- for i in subsubheaders:
- if subsubheaders[i][1] == None:
- continue
- sub_spans = sorted_spans[subsubheaders[i][1] : subsubheaders[i][0]]
- lines = []
- for x in sub_spans:
- if merged_spans[x][1] == "## Subheader" or (
- merged_spans[x][1] == "### Subsubheader" and first == None
- ):
- break
- else:
- lines.append(merged_spans[x][0])
- lines = "".join(lines)
-
- subsubheaders_strings[
- merged_spans[i][0].replace("\n", "").replace("### ", "").replace(" ", "")
- ] = lines
- first = i
-
- for i in subsubsubheaders:
- if subsubsubheaders[i][1] == None:
- continue
- sub_spans = sorted_spans[subsubsubheaders[i][1] : subsubsubheaders[i][0]]
- lines = []
- for x in sub_spans:
- if (
- merged_spans[x][1] == "## Subheader"
- or merged_spans[x][1] == "### Subsubheader"
- ):
- break
- else:
- lines.append(merged_spans[x][0])
- lines = "".join(lines)
-
- subsubsubheaders_strings[
- merged_spans[i][0].replace("#### ", "").replace("**", "").replace("\n", "")
- ] = lines
-
- return (
- headers_strings,
- subheaders_strings,
- subsubheaders_strings,
- subsubsubheaders_strings,
- )
-
-
-def extract_it(text_to_retrieve):
- print("Span\t\tType\t\tText")
- print("-------------------------------------")
- found_subheader = False
- current_subheader = " "
- page_state = " "
- help_text = " "
- #st.write("in cs- body here")
-
- (
- headers_strings,
- subheaders_strings,
- subsubheaders_strings,
- subsubsubheaders_strings,
- ) = stringify()
-
- h_keys = list(headers_strings.keys())
- sh_keys = list(subheaders_strings.keys())
- ssh_keys = list(subsubheaders_strings.keys())
- sssh_keys = list(subsubsubheaders_strings.keys())
-
- needed = [
- "model details",
- "howto",
- "limitations",
- "uses",
- "training",
- "evaluation",
- "environmental",
- "citation",
- "glossary",
- "more information",
- "authors",
- "contact",
- ] # not sure what keyword should be used for citation, howto, and contact
- # info_strings = {
- # "details": "## Model Details",
- # "howto": "## How to Get Started with the Model",
- # "limitations": "## Limitations and Biases",
- # "uses": "## Uses",
- # "training": "## Training",
- # "evaluation": "## Evaluation Results",
- # "environmental": "## Environmental Impact",
- # "citation": "## Citation Information",
- # "glossary": "## Glossary",
- # "more information": "## More Information",
- # "authors": "## Model Card Authors",
- # "contact": "## Model Card Contact",
- # }
- info_strings = {
- "model details": "",
- "howto": "",
- "limitations": "",
- "uses": "",
- "training": "",
- "evaluation": "",
- "environmental": "",
- "citation": "",
- "glossary": "",
- "more information": "",
- "authors": "",
- "contact": "",
- }
-
- for x in needed:
- for l in h_keys:
- if x in l.lower():
- info_strings[x] = info_strings[x] + headers_strings[l]
- for i in sh_keys:
- if x in i.lower():
- info_strings[x] = info_strings[x] + subheaders_strings[i]
- for z in ssh_keys:
- try:
- if x in z.lower():
- info_strings[x] = info_strings[x] + subsubheaders_strings[z]
- except:
- continue
- for y in sssh_keys:
- try:
- if x in y.lower():
- info_strings[x] = info_strings[x] + subsubsubheaders_strings[y]
- except:
- continue
-
- extracted_info = {
- "Model_details_text": info_strings["model details"],
- "Model_how_to": info_strings["howto"],
- "Model_Limits_n_Risks": info_strings["limitations"],
- "Model_uses": info_strings["uses"],
- "Model_training": info_strings["training"],
- "Model_Eval": info_strings["evaluation"],
- "Model_carbon": info_strings["environmental"],
- "Model_cite": info_strings["citation"],
- "Glossary": info_strings["glossary"],
- "More_info": info_strings["more information"],
- "Model_card_authors": info_strings["authors"],
- "Model_card_contact": info_strings["contact"],
- "Technical_specs": "## Technical specifications",
- "Model_examin": "## Model Examination",
- }
-
- #text_to_retrieve = "Model_details_text"
-
- new_t = extracted_info[text_to_retrieve] + " "
-
- return(new_t)
-
-
-if __name__ == "__main__":
-
- main()
diff --git a/spaces/awacke1/Pandas-Gamification-Mechanics/README.md b/spaces/awacke1/Pandas-Gamification-Mechanics/README.md
deleted file mode 100644
index 8e7d396aee75e7f798a7fd44bb7828eb12574d2a..0000000000000000000000000000000000000000
--- a/spaces/awacke1/Pandas-Gamification-Mechanics/README.md
+++ /dev/null
@@ -1,12 +0,0 @@
----
-title: 🎭Pandas-Gamification-Mechanics👥
-emoji: 🎭👥
-colorFrom: blue
-colorTo: red
-sdk: streamlit
-sdk_version: 1.17.0
-app_file: app.py
-pinned: false
-license: mit
----
-Acting Game Machanics
\ No newline at end of file
diff --git a/spaces/awacke1/Streamlit-Google-Maps-Massachusetts/backupapp.py b/spaces/awacke1/Streamlit-Google-Maps-Massachusetts/backupapp.py
deleted file mode 100644
index 997314f09903fd7368d023bf3691bd0b4972b982..0000000000000000000000000000000000000000
--- a/spaces/awacke1/Streamlit-Google-Maps-Massachusetts/backupapp.py
+++ /dev/null
@@ -1,76 +0,0 @@
-gmaps = googlemaps.Client(key='AIzaSyDybq2mxujekZVivmr03Y5-GGHXesn4TLI')
-import streamlit as st
-import folium
-from folium.plugins import MarkerCluster
-from streamlit_folium import folium_static
-import googlemaps
-from datetime import datetime
-import os
-
-# Initialize Google Maps
-gmaps = googlemaps.Client(key=os.getenv('GOOGLE_KEY'))
-
-# Function to fetch directions
-def get_directions_and_coords(source, destination):
- now = datetime.now()
- directions_info = gmaps.directions(source, destination, mode='driving', departure_time=now)
- if directions_info:
- steps = directions_info[0]['legs'][0]['steps']
- coords = [(step['start_location']['lat'], step['start_location']['lng']) for step in steps]
- return steps, coords
- else:
- return None, None
-
-# Function to render map with directions
-def render_folium_map(coords):
- m = folium.Map(location=[coords[0][0], coords[0][1]], zoom_start=13)
- folium.PolyLine(coords, color="blue", weight=2.5, opacity=1).add_to(m)
- return m
-
-# Streamlit UI
-st.title('Google Maps and Minnesota Medical Centers')
-st.sidebar.header('Directions')
-
-source_location = st.sidebar.text_input("Source Location", "Mound, MN")
-destination_location = st.sidebar.text_input("Destination Location", "Minneapolis, MN")
-
-if st.sidebar.button('Get Directions'):
- steps, coords = get_directions_and_coords(source_location, destination_location)
- if steps and coords:
- st.subheader('Driving Directions:')
- for i, step in enumerate(steps):
- st.write(f"{i+1}. {step['html_instructions']}")
- st.subheader('Route on Map:')
- m1 = render_folium_map(coords)
- folium_static(m1)
- else:
- st.write("No available routes.")
-
-# The existing code for Minnesota medical centers
-st.markdown("## 🏥 Minnesota Medical Centers 🌳")
-m2 = folium.Map(location=[45.6945, -93.9002], zoom_start=6)
-marker_cluster = MarkerCluster().add_to(m2)
-# Define Minnesota medical centers data
-minnesota_med_centers = [
- ('Mayo Clinic', 44.0224, -92.4658, 'General medical and surgical', 'Rochester'),
- ('University of Minnesota Medical Center', 44.9721, -93.2595, 'Teaching hospital', 'Minneapolis'),
- ('Abbott Northwestern Hospital', 44.9526, -93.2622, 'Heart specialty', 'Minneapolis'),
- ('Regions Hospital', 44.9558, -93.0942, 'Trauma center', 'St. Paul'),
- ('St. Cloud Hospital', 45.5671, -94.1989, 'Multiple specialties', 'St. Cloud'),
- ('Park Nicollet Methodist Hospital', 44.9304, -93.3640, 'General medical and surgical', 'St. Louis Park'),
- ('Fairview Ridges Hospital', 44.7391, -93.2777, 'Community hospital', 'Burnsville'),
- ('Mercy Hospital', 45.1761, -93.3099, 'Acute care', 'Coon Rapids'),
- ('North Memorial Health Hospital', 45.0131, -93.3246, 'General medical and surgical', 'Robbinsdale'),
- ('Essentia Health-Duluth', 46.7860, -92.1011, 'Community hospital', 'Duluth'),
- ('M Health Fairview Southdale Hospital', 44.8806, -93.3241, 'Community hospital', 'Edina'),
- ('Woodwinds Health Campus', 44.9272, -92.9689, 'Community hospital', 'Woodbury'),
- ('United Hospital', 44.9460, -93.1052, 'Acute care', 'St. Paul'),
- ('Buffalo Hospital', 45.1831, -93.8772, 'Community hospital', 'Buffalo'),
- ('Maple Grove Hospital', 45.1206, -93.4790, 'Community hospital', 'Maple Grove'),
- ('Olmsted Medical Center', 44.0234, -92.4610, 'General medical and surgical', 'Rochester'),
- ('Hennepin Healthcare', 44.9738, -93.2605, 'Teaching hospital', 'Minneapolis'),
- ('St. Francis Regional Medical Center', 44.7658, -93.5143, 'Community hospital', 'Shakopee'),
- ('Lakeview Hospital', 45.0422, -92.8137, 'Community hospital', 'Stillwater'),
- ('St. Luke\'s Hospital', 46.7831, -92.1043, 'Community hospital', 'Duluth')
-]
-folium_static(m2)
diff --git a/spaces/banana-projects/coref/js-src/Displacy.ts b/spaces/banana-projects/coref/js-src/Displacy.ts
deleted file mode 100644
index cda23ff4a7623ebdd144e5f6ffa8c2cac8782ce5..0000000000000000000000000000000000000000
--- a/spaces/banana-projects/coref/js-src/Displacy.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-
-
-/**
- * Indicates position of spans of text inside the string.
- * (for visual applications only, no semantic sense here.)
- */
-interface Span {
- type: string;
- start: number;
- end: number;
-}
-
-interface SpanTag {
- span: Span;
- tag: "start" | "end";
-}
-
-class Displacy {
- static sortSpans(spans: Span[]) {
- spans.sort((a, b) => { /// `a` should come first when the result is < 0
- if (a.start === b.start) {
- return b.end - a.end; /// CAUTION.
- }
- return a.start - b.start;
- });
-
- // Check existence of **strict overlapping**
- spans.forEach((s, i) => {
- if (i < spans.length - 1) {
- const sNext = spans[i+1];
- if (s.start < sNext.start && s.end > sNext.start) {
- console.log("ERROR", "Spans: strict overlapping");
- }
- }
- });
- }
-
- /**
- * Render a text string and its entity spans
- *
- * *see displacy-ent.js*
- * see https://github.com/explosion/displacy-ent/issues/2
- */
- static render(text: string, spans: Span[]): string {
- this.sortSpans(spans);
-
- const tags: { [index: number]: SpanTag[] } = {};
- const __addTag = (i: number, s: Span, tag: "start" | "end") => {
- if (Array.isArray(tags[i])) {
- tags[i].push({ span: s, tag: tag });
- } else {
- tags[i] = [{ span: s, tag: tag }];
- }
- };
- for (const s of spans) {
- __addTag(s.start, s, "start");
- __addTag(s.end, s, "end");
- }
- // console.log(JSON.stringify(tags)); // todo remove
-
- let out = {
- __content: "",
- append(s: string) {
- this.__content += s;
- }
- };
- let offset = 0;
-
- const indexes = Object.keys(tags).map(k => parseInt(k, 10)).sort((a, b) => a - b); /// CAUTION
- for (const i of indexes) {
- const spanTags = tags[i];
- // console.log(i, spanTags); // todo remove
- if (i > offset) {
- out.append(text.slice(offset, i));
- }
-
- offset = i;
-
- for (const sT of spanTags) {
- if (sT.tag === "start") {
- out.append(``);
- const singleScore = (sT.span).singleScore;
- if (singleScore) {
- out.append(`${ singleScore.toFixed(3) }`);
- }
- } else {
- out.append(``);
- }
- }
- }
-
- out.append(text.slice(offset, text.length));
- return out.__content;
- }
-}
diff --git a/spaces/banana-projects/talking-egg/index.html b/spaces/banana-projects/talking-egg/index.html
deleted file mode 100644
index 3d36988a58360f0fccebe348f4e97112e90fda68..0000000000000000000000000000000000000000
--- a/spaces/banana-projects/talking-egg/index.html
+++ /dev/null
@@ -1,30 +0,0 @@
-
-
-
-
- Talking Egg 🥚
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Visit this page on iOS 12 in Safari to try AR Quick Look
-
-
-Governmental activities
-
-Armenia has become a member of NATO and the Partnership for Peace (PfP) member states. Armenia participates in the international security conference. The country is a member of the Transcaucasian economic commission and the Transcaucasian economic union. Armenia has also been invited to the regional cooperation on transport and communication network (TRACNET-2012) and South Caucasus economic integration summit.
-
-The Peace Support Operations are also carried out in Armenia. The country is a member of the Vienna Document on chemical weapons convention. In 2015, the country joined the Transit Agreement for Armenia–Russia–Georgia–Turkey (TANAP) and the Agreement on the avoidance of certain technical obstacles to the implementation of the Trans Adriatic Pipeline (TAP).
-
-Economic integration
-
-The countries that are members of the European Union (EU) are also members of the European Free Trade Association (EFTA). The European Economic Community (EEC) countries that are not members of EFTA, as well as EFTA members that are not members of the EU are members of the Common Market for Eastern and Southern Europe (CMEA). The countries that are not members of the EU and EFTA are members of the Eurasian Economic Union (EAEU), which is the successor of the CMEA. The EAEU member states form the Eurasian Economic Commission, which is composed of the Ministers of Foreign Affairs of the EAEU member states.
-
-The first CEE trade mission to Armenia was held in October 2002. The annual trade missions were carried out since 2003. In April 2005, the CEE Trade Mission to Armenia was completed. The CEE trade mission to Armenia is held in conjunction with the EU Eastern Partnership Summit.
-
-The first Armenian-Japanese trade mission was held in 2007.
-
-In 2008, the Euromediterranean Partnership for Trade and Economic Development was launched in Armenia. The CEE Trade Mission to Armenia was held for the second time. A Memorandum of Understanding on Defense and Security Cooperation was signed in Yerevan on 24 September 2008.
-
-In 2009, the Armenian-Azerbaijani trade mission was held. The trade mission to Armenia was held for the third time.
-
-In 2011, the EU Eastern Partnership Summit was held in Yerevan. In the same year, a Memorandum of Understanding on Cooperation in the Energy Sector was signed in Armenia.
-
-In 2012, the EU–Armenia Inter-reg 4fefd39f24
-
-
-
diff --git a/spaces/bioriAsaeru/text-to-voice/Free Download Wasteland __TOP__.md b/spaces/bioriAsaeru/text-to-voice/Free Download Wasteland __TOP__.md
deleted file mode 100644
index b770f3aecc1d554d5adeadabbb8ab73f7ede6832..0000000000000000000000000000000000000000
--- a/spaces/bioriAsaeru/text-to-voice/Free Download Wasteland __TOP__.md
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
People love free steam games, no doubt. But what many people hate is downloading so many parts and trying to install them on their own. This is why we are the only site that pre-installs every game for you. We have many categories like shooters, action, racing, simulators and even VR games! We strive to satisfy our users and ask for nothing in return. We revolutionized the downloading scene and will continue being your #1 site for free games.
-
If you desired to play games which are full of action and entertainment so just just download Wasteland 2 Ranger Edition PC Game 2014 and start playing it. Because in this game you will enjoy action at every moment of play. We categorized this game in role-playing games. This game is developed and published by inXile Entertainment. It was released on September 19, 2014.
Our website is made possible by displaying online advertisements to our visitors.Please consider supporting us by whitelisting our website.\n","overlay-color":"#000000","bg-color":"#FFFFFF","title-color":null,"text-color":"#000000","scope":"page","style":"modal"}}; #floating_ads_bottom_textcss_containerposition:fixed;bottom:2px;width:100%#floating_ads_bottom_textcss_wraptext-align:center#floating_ads_bottom_textcss_addisplay:inline-block#floating_ads_bottom_textcss_closeposition:absolute;top:-20px;display:inline-blockvar app_url = ' '; var app_api_token = '87c5f42ff5a42888ea088eb1ce2b86c70c342fa0'; var app_advert = 2; var app_domains = ["ddownload.com","rapidgator.net","drive.google.com","file-upload.com","file-upload.org","www.file-upload.com","send.cm"]; window.dataLayer = window.dataLayer || []; function gtag()dataLayer.push(arguments); gtag('js', new Date()); gtag('config', 'UA-149928735-1'); .simple-bannerposition:static.simple-bannerbackground:#1a1a1a.simple-banner .simple-banner-textcolor:#fff.simple-banner .simple-banner-text acolor:#f50 img#wpstatsdisplay:none@-webkit-keyframes bgslidefrombackground-position-x:0tobackground-position-x:-200%@keyframes bgslidefrombackground-position-x:0tobackground-position-x:-200%.wpp-widget-placeholder,.wpp-widget-block-placeholdermargin:0 auto;width:60px;height:3px;background:#dd3737;background:linear-gradient(90deg,#dd3737 0%,#571313 10%,#dd3737 100%);background-size:200% auto;border-radius:3px;-webkit-animation:bgslide 1s infinite linear;animation:bgslide 1s infinite linear#scroll-topdisplay:none !important#site-header.has-header-media .overlay-header-mediabackground-color:rgba(0,0,0,.5)#site-logo #site-logo-inner a img,#site-header.center-header #site-navigation-wrap .middle-site-logo a imgmax-width:120px#site-header #site-logo #site-logo-inner a img,#site-header.center-header #site-navigation-wrap .middle-site-logo a imgmax-height:100px#footer-widgets,#footer-widgets p,#footer-widgets li a:before,#footer-widgets .contact-info-widget span.oceanwp-contact-title,#footer-widgets .recent-posts-date,#footer-widgets .recent-posts-comments,#footer-widgets .widget-recent-posts-icons li .facolor:#fff#footer-widgets li,#footer-widgets #wp-calendar caption,#footer-widgets #wp-calendar th,#footer-widgets #wp-calendar tbody,#footer-widgets .contact-info-widget i,#footer-widgets .oceanwp-newsletter-form-wrap input[type=email],#footer-widgets .posts-thumbnails-widget li,#footer-widgets .social-widget li aborder-color:#727272#footer-widgets .contact-info-widget .owp-iconborder-color:#727272#footer-bottom,#footer-bottom pcolor:#f7f7f7bodyfont-family:Montserrat;color:#000h1,h2,h3,h4,h5,h6,.theme-heading,.widget-title,.oceanwp-widget-recent-posts-title,.comment-reply-title,.entry-title,.sidebar-box .widget-titlefont-family:Montserrat#site-navigation-wrap .dropdown-menu>li>a,#site-header.full_screen-header .fs-dropdown-menu>li>a,#site-header.top-header #site-navigation-wrap .dropdown-menu>li>a,#site-header.center-header #site-navigation-wrap .dropdown-menu>li>a,#site-header.medium-header #site-navigation-wrap .dropdown-menu>li>a,.oceanwp-mobile-menu-icon afont-weight:600;text-transform:uppercase.sidebar-box .widget-titlefont-family:Montserrat;font-weight:600.ai-viewports--ai:1.ai-viewport-3display:none !important.ai-viewport-2display:none !important.ai-viewport-1display:inherit !important.ai-viewport-0display:none !important@media (min-width:768px) and (max-width:979px).ai-viewport-1display:none !important.ai-viewport-2display:inherit !important@media (max-width:767px).ai-viewport-1display:none !important.ai-viewport-3display:inherit !importantSkip to contentUnity Asset FreePremiumPacksComplete ProjectsCharactersWeapons3D2DTutorialsMembershipSearch this websiteMenuClosePremiumPacksComplete ProjectsCharactersWeapons3D2DTutorialsMembershipApocalyptic WastelandHome>Unity Assets>Environment>Apocalyptic Wasteland (adsbygoogle = window.adsbygoogle || []).push();Apocalyptic Wastelanddownload Apocalyptic WastelandFREE Unity
-
Here at Creative Bloq, we're big fans of typography (opens in new tab) and we're constantly on the hunt for new and exciting typefaces - especially free fonts (opens in new tab). So, if you're in need of a font for your latest design or just like to keep a collection so you're prepared, we may be able to help out.
-
The Creative Bloq team is made up of a group of design fans, and has changed and evolved since Creative Bloq began back in 2012. The current website team consists of six full-time members of staff: Editor Kerrie Hughes, Deputy Editor Rosie Hilder, Deals Editor Beren Neale, Senior News Editor Daniel Piper, Digital Arts and Design Editor Ian Dean, and Staff Writer Amelia Bamsey, as well as a roster of freelancers from around the world. The 3D World and ImagineFX magazine teams also pitch in, ensuring that content from 3D World and ImagineFX is represented on Creative Bloq.
-
Gutiar Pro Tab "Soldiers Of The Wasteland" from Dragonforce band is free to download.Tablature file Dragonforce - Soldiers Of The Wasteland opens by means of the Guitar PRO program. This program is available todownloading on our site.
-
April is the cruellest month, breeding Lilacs out of the dead land, mixing Memory and desire, stirring Dull roots with spring rain. Winter kept us warm, covering Earth in forgetful snow, feeding A little life with dried tubers. Summer surprised us, coming over the Starnbergersee With a shower of rain; we stopped in the colonnade, And went on in sunlight, into the Hofgarten, And drank coffee, and talked for an hour. Bin gar keine Russin, stamm' aus Litauen, echt deutsch. And when we were children, staying at the archduke's, My cousin's, he took me out on a sled, And I was frightened. He said, Marie, Marie, hold on tight. And down we went. In the mountains, there you feel free. I read, much of the night, and go south in the winter.
-
-
Includes unlimited streaming via the free Bandcamp app, plus high-quality downloads of How Deep Is Your Devotion, Landmark, 2022 | Label Compilation (mixed by todos), Mycological Patterns, 1994, Konec, Original Soundtrack, Chaos & Order, and 84 more. , and , . Purchasable with gift card Buy Digital Discography $95.60 USD or more (80% OFF) Send as Gift credits from Song Of The Highest Tower, released March 6, 2014 license all rights reserved tags Tags ambient electronica idm drone electronic Los Angeles Shopping cart total USD Check out about A Strangely Isolated Place Los Angeles, California
aaccfb2cb3
-
-
\ No newline at end of file
diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/projects/DensePose/densepose/vis/densepose_outputs_vertex.py b/spaces/brjathu/HMR2.0/vendor/detectron2/projects/DensePose/densepose/vis/densepose_outputs_vertex.py
deleted file mode 100644
index 71e5323c2bd3a29bc90e66d7d59d524033c120bf..0000000000000000000000000000000000000000
--- a/spaces/brjathu/HMR2.0/vendor/detectron2/projects/DensePose/densepose/vis/densepose_outputs_vertex.py
+++ /dev/null
@@ -1,229 +0,0 @@
-# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
-import json
-import numpy as np
-from functools import lru_cache
-from typing import Dict, List, Optional, Tuple
-import cv2
-import torch
-
-from detectron2.utils.file_io import PathManager
-
-from densepose.modeling import build_densepose_embedder
-from densepose.modeling.cse.utils import get_closest_vertices_mask_from_ES
-
-from ..data.utils import get_class_to_mesh_name_mapping
-from ..structures import DensePoseEmbeddingPredictorOutput
-from ..structures.mesh import create_mesh
-from .base import Boxes, Image, MatrixVisualizer
-from .densepose_results_textures import get_texture_atlas
-
-
-@lru_cache()
-def get_xyz_vertex_embedding(mesh_name: str, device: torch.device):
- if mesh_name == "smpl_27554":
- embed_path = PathManager.get_local_path(
- "https://dl.fbaipublicfiles.com/densepose/data/cse/mds_d=256.npy"
- )
- embed_map, _ = np.load(embed_path, allow_pickle=True)
- embed_map = torch.tensor(embed_map).float()[:, 0]
- embed_map -= embed_map.min()
- embed_map /= embed_map.max()
- else:
- mesh = create_mesh(mesh_name, device)
- embed_map = mesh.vertices.sum(dim=1)
- embed_map -= embed_map.min()
- embed_map /= embed_map.max()
- embed_map = embed_map**2
- return embed_map
-
-
-class DensePoseOutputsVertexVisualizer(object):
- def __init__(
- self,
- cfg,
- inplace=True,
- cmap=cv2.COLORMAP_JET,
- alpha=0.7,
- device="cuda",
- default_class=0,
- **kwargs,
- ):
- self.mask_visualizer = MatrixVisualizer(
- inplace=inplace, cmap=cmap, val_scale=1.0, alpha=alpha
- )
- self.class_to_mesh_name = get_class_to_mesh_name_mapping(cfg)
- self.embedder = build_densepose_embedder(cfg)
- self.device = torch.device(device)
- self.default_class = default_class
-
- self.mesh_vertex_embeddings = {
- mesh_name: self.embedder(mesh_name).to(self.device)
- for mesh_name in self.class_to_mesh_name.values()
- if self.embedder.has_embeddings(mesh_name)
- }
-
- def visualize(
- self,
- image_bgr: Image,
- outputs_boxes_xywh_classes: Tuple[
- Optional[DensePoseEmbeddingPredictorOutput], Optional[Boxes], Optional[List[int]]
- ],
- ) -> Image:
- if outputs_boxes_xywh_classes[0] is None:
- return image_bgr
-
- S, E, N, bboxes_xywh, pred_classes = self.extract_and_check_outputs_and_boxes(
- outputs_boxes_xywh_classes
- )
-
- for n in range(N):
- x, y, w, h = bboxes_xywh[n].int().tolist()
- mesh_name = self.class_to_mesh_name[pred_classes[n]]
- closest_vertices, mask = get_closest_vertices_mask_from_ES(
- E[[n]],
- S[[n]],
- h,
- w,
- self.mesh_vertex_embeddings[mesh_name],
- self.device,
- )
- embed_map = get_xyz_vertex_embedding(mesh_name, self.device)
- vis = (embed_map[closest_vertices].clip(0, 1) * 255.0).cpu().numpy()
- mask_numpy = mask.cpu().numpy().astype(dtype=np.uint8)
- image_bgr = self.mask_visualizer.visualize(image_bgr, mask_numpy, vis, [x, y, w, h])
-
- return image_bgr
-
- def extract_and_check_outputs_and_boxes(self, outputs_boxes_xywh_classes):
-
- densepose_output, bboxes_xywh, pred_classes = outputs_boxes_xywh_classes
-
- if pred_classes is None:
- pred_classes = [self.default_class] * len(bboxes_xywh)
-
- assert isinstance(
- densepose_output, DensePoseEmbeddingPredictorOutput
- ), "DensePoseEmbeddingPredictorOutput expected, {} encountered".format(
- type(densepose_output)
- )
-
- S = densepose_output.coarse_segm
- E = densepose_output.embedding
- N = S.size(0)
- assert N == E.size(
- 0
- ), "CSE coarse_segm {} and embeddings {}" " should have equal first dim size".format(
- S.size(), E.size()
- )
- assert N == len(
- bboxes_xywh
- ), "number of bounding boxes {}" " should be equal to first dim size of outputs {}".format(
- len(bboxes_xywh), N
- )
- assert N == len(pred_classes), (
- "number of predicted classes {}"
- " should be equal to first dim size of outputs {}".format(len(bboxes_xywh), N)
- )
-
- return S, E, N, bboxes_xywh, pred_classes
-
-
-def get_texture_atlases(json_str: Optional[str]) -> Optional[Dict[str, Optional[np.ndarray]]]:
- """
- json_str is a JSON string representing a mesh_name -> texture_atlas_path dictionary
- """
- if json_str is None:
- return None
-
- paths = json.loads(json_str)
- return {mesh_name: get_texture_atlas(path) for mesh_name, path in paths.items()}
-
-
-class DensePoseOutputsTextureVisualizer(DensePoseOutputsVertexVisualizer):
- def __init__(
- self,
- cfg,
- texture_atlases_dict,
- device="cuda",
- default_class=0,
- **kwargs,
- ):
- self.embedder = build_densepose_embedder(cfg)
-
- self.texture_image_dict = {}
- self.alpha_dict = {}
-
- for mesh_name in texture_atlases_dict.keys():
- if texture_atlases_dict[mesh_name].shape[-1] == 4: # Image with alpha channel
- self.alpha_dict[mesh_name] = texture_atlases_dict[mesh_name][:, :, -1] / 255.0
- self.texture_image_dict[mesh_name] = texture_atlases_dict[mesh_name][:, :, :3]
- else:
- self.alpha_dict[mesh_name] = texture_atlases_dict[mesh_name].sum(axis=-1) > 0
- self.texture_image_dict[mesh_name] = texture_atlases_dict[mesh_name]
-
- self.device = torch.device(device)
- self.class_to_mesh_name = get_class_to_mesh_name_mapping(cfg)
- self.default_class = default_class
-
- self.mesh_vertex_embeddings = {
- mesh_name: self.embedder(mesh_name).to(self.device)
- for mesh_name in self.class_to_mesh_name.values()
- }
-
- def visualize(
- self,
- image_bgr: Image,
- outputs_boxes_xywh_classes: Tuple[
- Optional[DensePoseEmbeddingPredictorOutput], Optional[Boxes], Optional[List[int]]
- ],
- ) -> Image:
- image_target_bgr = image_bgr.copy()
- if outputs_boxes_xywh_classes[0] is None:
- return image_target_bgr
-
- S, E, N, bboxes_xywh, pred_classes = self.extract_and_check_outputs_and_boxes(
- outputs_boxes_xywh_classes
- )
-
- meshes = {
- p: create_mesh(self.class_to_mesh_name[p], self.device) for p in np.unique(pred_classes)
- }
-
- for n in range(N):
- x, y, w, h = bboxes_xywh[n].int().cpu().numpy()
- mesh_name = self.class_to_mesh_name[pred_classes[n]]
- closest_vertices, mask = get_closest_vertices_mask_from_ES(
- E[[n]],
- S[[n]],
- h,
- w,
- self.mesh_vertex_embeddings[mesh_name],
- self.device,
- )
- uv_array = meshes[pred_classes[n]].texcoords[closest_vertices].permute((2, 0, 1))
- uv_array = uv_array.cpu().numpy().clip(0, 1)
- textured_image = self.generate_image_with_texture(
- image_target_bgr[y : y + h, x : x + w],
- uv_array,
- mask.cpu().numpy(),
- self.class_to_mesh_name[pred_classes[n]],
- )
- if textured_image is None:
- continue
- image_target_bgr[y : y + h, x : x + w] = textured_image
-
- return image_target_bgr
-
- def generate_image_with_texture(self, bbox_image_bgr, uv_array, mask, mesh_name):
- alpha = self.alpha_dict.get(mesh_name)
- texture_image = self.texture_image_dict.get(mesh_name)
- if alpha is None or texture_image is None:
- return None
- U, V = uv_array
- x_index = (U * texture_image.shape[1]).astype(int)
- y_index = (V * texture_image.shape[0]).astype(int)
- local_texture = texture_image[y_index, x_index][mask]
- local_alpha = np.expand_dims(alpha[y_index, x_index][mask], -1)
- output_image = bbox_image_bgr.copy()
- output_image[mask] = output_image[mask] * (1 - local_alpha) + local_texture * local_alpha
- return output_image.astype(np.uint8)
diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/projects/PointSup/point_sup/detection_utils.py b/spaces/brjathu/HMR2.0/vendor/detectron2/projects/PointSup/point_sup/detection_utils.py
deleted file mode 100644
index 3f95d9449277fc55e93121582f6c6a6396dc833d..0000000000000000000000000000000000000000
--- a/spaces/brjathu/HMR2.0/vendor/detectron2/projects/PointSup/point_sup/detection_utils.py
+++ /dev/null
@@ -1,103 +0,0 @@
-# -*- coding: utf-8 -*-
-# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
-
-import numpy as np
-import torch
-
-# fmt: off
-from detectron2.data.detection_utils import \
- annotations_to_instances as base_annotations_to_instances
-from detectron2.data.detection_utils import \
- transform_instance_annotations as base_transform_instance_annotations
-
-# fmt: on
-
-
-def annotations_to_instances(annos, image_size, sample_points=0):
- """
- Create an :class:`Instances` object used by the models,
- from instance annotations in the dataset dict.
-
- Args:
- annos (list[dict]): a list of instance annotations in one image, each
- element for one instance.
- image_size (tuple): height, width
- sample_points (int): subsample points at each iteration
-
- Returns:
- Instances:
- It will contain fields "gt_boxes", "gt_classes",
- "gt_point_coords", "gt_point_labels", if they can be obtained from `annos`.
- This is the format that builtin models with point supervision expect.
- """
- target = base_annotations_to_instances(annos, image_size)
-
- assert ("point_coords" in annos[0]) == ("point_labels" in annos[0])
-
- if len(annos) and "point_labels" in annos[0]:
- point_coords = []
- point_labels = []
- for i, _ in enumerate(annos):
- # Already in the image coordinate system
- point_coords_wrt_image = np.array(annos[i]["point_coords"])
- point_labels_wrt_image = np.array(annos[i]["point_labels"])
-
- if sample_points > 0:
- random_indices = np.random.choice(
- point_coords_wrt_image.shape[0],
- sample_points,
- replace=point_coords_wrt_image.shape[0] < sample_points,
- ).astype(int)
- point_coords_wrt_image = point_coords_wrt_image[random_indices]
- point_labels_wrt_image = point_labels_wrt_image[random_indices]
- assert point_coords_wrt_image.shape[0] == point_labels_wrt_image.size
-
- point_coords.append(point_coords_wrt_image)
- point_labels.append(point_labels_wrt_image)
-
- point_coords = torch.stack([torch.from_numpy(x) for x in point_coords])
- point_labels = torch.stack([torch.from_numpy(x) for x in point_labels])
- target.gt_point_coords = point_coords
- target.gt_point_labels = point_labels
-
- return target
-
-
-def transform_instance_annotations(
- annotation, transforms, image_size, *, keypoint_hflip_indices=None
-):
- """
- Apply transforms to box, and point annotations of a single instance.
- It will use `transforms.apply_box` for the box, and
- `transforms.apply_coords` for points.
- Args:
- annotation (dict): dict of instance annotations for a single instance.
- It will be modified in-place.
- transforms (TransformList or list[Transform]):
- image_size (tuple): the height, width of the transformed image
- keypoint_hflip_indices (ndarray[int]): see `create_keypoint_hflip_indices`.
- Returns:
- dict:
- the same input dict with fields "bbox", "point_coords", "point_labels"
- transformed according to `transforms`.
- The "bbox_mode" field will be set to XYXY_ABS.
- """
- annotation = base_transform_instance_annotations(
- annotation, transforms, image_size, keypoint_hflip_indices
- )
-
- assert ("point_coords" in annotation) == ("point_labels" in annotation)
- if "point_coords" in annotation and "point_labels" in annotation:
- point_coords = annotation["point_coords"]
- point_labels = np.array(annotation["point_labels"]).astype(np.float)
- point_coords = transforms.apply_coords(point_coords)
-
- # Set all out-of-boundary points to "unlabeled"
- inside = (point_coords >= np.array([0, 0])) & (point_coords <= np.array(image_size[::-1]))
- inside = inside.all(axis=1)
- point_labels[~inside] = -1
-
- annotation["point_coords"] = point_coords
- annotation["point_labels"] = point_labels
-
- return annotation
diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/projects/ViTDet/configs/COCO/mask_rcnn_vitdet_h_75ep.py b/spaces/brjathu/HMR2.0/vendor/detectron2/projects/ViTDet/configs/COCO/mask_rcnn_vitdet_h_75ep.py
deleted file mode 100644
index 7de96f0a6c760ac41152726ac1e4faeb1fb9a818..0000000000000000000000000000000000000000
--- a/spaces/brjathu/HMR2.0/vendor/detectron2/projects/ViTDet/configs/COCO/mask_rcnn_vitdet_h_75ep.py
+++ /dev/null
@@ -1,33 +0,0 @@
-from functools import partial
-
-from .mask_rcnn_vitdet_b_100ep import (
- dataloader,
- lr_multiplier,
- model,
- train,
- optimizer,
- get_vit_lr_decay_rate,
-)
-
-train.init_checkpoint = (
- "detectron2://ImageNetPretrained/MAE/mae_pretrain_vit_huge_p14to16.pth?matching_heuristics=True"
-)
-
-model.backbone.net.embed_dim = 1280
-model.backbone.net.depth = 32
-model.backbone.net.num_heads = 16
-model.backbone.net.drop_path_rate = 0.5
-# 7, 15, 23, 31 for global attention
-model.backbone.net.window_block_indexes = (
- list(range(0, 7)) + list(range(8, 15)) + list(range(16, 23)) + list(range(24, 31))
-)
-
-optimizer.params.lr_factor_func = partial(get_vit_lr_decay_rate, lr_decay_rate=0.9, num_layers=32)
-optimizer.params.overrides = {}
-optimizer.params.weight_decay_norm = None
-
-train.max_iter = train.max_iter * 3 // 4 # 100ep -> 75ep
-lr_multiplier.scheduler.milestones = [
- milestone * 3 // 4 for milestone in lr_multiplier.scheduler.milestones
-]
-lr_multiplier.scheduler.num_updates = train.max_iter
diff --git a/spaces/camilosegura/traductor-multilenguaje/Lib/site-packages/_sounddevice.py b/spaces/camilosegura/traductor-multilenguaje/Lib/site-packages/_sounddevice.py
deleted file mode 100644
index b1e9f8c3443b040a2c75c09969bcad88cb527e02..0000000000000000000000000000000000000000
--- a/spaces/camilosegura/traductor-multilenguaje/Lib/site-packages/_sounddevice.py
+++ /dev/null
@@ -1,11 +0,0 @@
-# auto-generated file
-import _cffi_backend
-
-ffi = _cffi_backend.FFI('_sounddevice',
- _version = 0x2601,
- _types = b'\x00\x00\x76\x0D\x00\x00\x07\x01\x00\x00\x00\x0F\x00\x00\x79\x0D\x00\x00\x07\x01\x00\x00\x00\x0F\x00\x00\x1C\x0D\x00\x00\x8D\x03\x00\x00\x00\x0F\x00\x00\x7B\x0D\x00\x00\x00\x0F\x00\x00\x80\x0D\x00\x00\x07\x11\x00\x00\x00\x0F\x00\x00\x88\x0D\x00\x00\x07\x01\x00\x00\x00\x0F\x00\x00\x88\x0D\x00\x00\x07\x01\x00\x00\x07\x01\x00\x00\x01\x01\x00\x00\x00\x0F\x00\x00\x88\x0D\x00\x00\x00\x0F\x00\x00\x21\x0D\x00\x00\x07\x11\x00\x00\x00\x0F\x00\x00\x01\x0D\x00\x00\x01\x0B\x00\x00\x00\x0F\x00\x00\x01\x0D\x00\x00\x82\x03\x00\x00\x1F\x11\x00\x00\x0E\x01\x00\x00\x00\x0F\x00\x00\x01\x0D\x00\x00\x07\x01\x00\x00\x00\x0F\x00\x00\x01\x0D\x00\x00\x07\x01\x00\x00\x07\x01\x00\x00\x00\x0F\x00\x00\x01\x0D\x00\x00\x0A\x01\x00\x00\x00\x0F\x00\x00\x01\x0D\x00\x00\x07\x03\x00\x00\x1F\x11\x00\x00\x1F\x11\x00\x00\x0E\x01\x00\x00\x0A\x01\x00\x00\x0A\x01\x00\x00\x52\x03\x00\x00\x07\x11\x00\x00\x00\x0F\x00\x00\x01\x0D\x00\x00\x2E\x11\x00\x00\x07\x01\x00\x00\x07\x01\x00\x00\x0A\x01\x00\x00\x0E\x01\x00\x00\x0A\x01\x00\x00\x34\x11\x00\x00\x07\x11\x00\x00\x00\x0F\x00\x00\x01\x0D\x00\x00\x07\x11\x00\x00\x00\x0F\x00\x00\x01\x0D\x00\x00\x07\x11\x00\x00\x07\x11\x00\x00\x0A\x01\x00\x00\x00\x0F\x00\x00\x01\x0D\x00\x00\x07\x11\x00\x00\x8D\x03\x00\x00\x0A\x01\x00\x00\x00\x0F\x00\x00\x01\x0D\x00\x00\x07\x11\x00\x00\x6B\x03\x00\x00\x00\x0F\x00\x00\x01\x0D\x00\x00\x4B\x11\x00\x00\x07\x11\x00\x00\x0A\x01\x00\x00\x7F\x03\x00\x00\x0A\x01\x00\x00\x07\x11\x00\x00\x00\x0F\x00\x00\x01\x0D\x00\x00\x00\x0F\x00\x00\x69\x0D\x00\x00\x07\x11\x00\x00\x00\x0F\x00\x00\x8D\x0D\x00\x00\x7D\x03\x00\x00\x8B\x03\x00\x00\x0A\x01\x00\x00\x00\x0F\x00\x00\x8D\x0D\x00\x00\x60\x11\x00\x00\x0A\x01\x00\x00\x00\x0F\x00\x00\x8D\x0D\x00\x00\x09\x01\x00\x00\x00\x0F\x00\x00\x8D\x0D\x00\x00\x07\x11\x00\x00\x00\x0F\x00\x00\x8D\x0D\x00\x00\x07\x11\x00\x00\x09\x01\x00\x00\x07\x11\x00\x00\x09\x01\x00\x00\x07\x11\x00\x00\x00\x0F\x00\x00\x01\x09\x00\x00\x77\x03\x00\x00\x02\x09\x00\x00\x00\x0B\x00\x00\x7A\x03\x00\x00\x03\x09\x00\x00\x7C\x03\x00\x00\x04\x09\x00\x00\x00\x09\x00\x00\x02\x0B\x00\x00\x05\x09\x00\x00\x81\x03\x00\x00\x06\x09\x00\x00\x07\x09\x00\x00\x03\x0B\x00\x00\x04\x0B\x00\x00\x08\x09\x00\x00\x05\x0B\x00\x00\x06\x0B\x00\x00\x89\x03\x00\x00\x02\x01\x00\x00\x01\x03\x00\x00\x15\x01\x00\x00\x6E\x03\x00\x00\x00\x01',
- _globals = (b'\x00\x00\x11\x23PaMacCore_GetChannelName',0,b'\x00\x00\x5F\x23PaMacCore_SetupChannelMap',0,b'\x00\x00\x64\x23PaMacCore_SetupStreamInfo',0,b'\x00\x00\x23\x23PaWasapi_IsLoopback',0,b'\x00\x00\x41\x23Pa_AbortStream',0,b'\x00\x00\x41\x23Pa_CloseStream',0,b'\x00\x00\x5A\x23Pa_GetDefaultHostApi',0,b'\x00\x00\x5A\x23Pa_GetDefaultInputDevice',0,b'\x00\x00\x5A\x23Pa_GetDefaultOutputDevice',0,b'\x00\x00\x5A\x23Pa_GetDeviceCount',0,b'\x00\x00\x00\x23Pa_GetDeviceInfo',0,b'\x00\x00\x0E\x23Pa_GetErrorText',0,b'\x00\x00\x5A\x23Pa_GetHostApiCount',0,b'\x00\x00\x03\x23Pa_GetHostApiInfo',0,b'\x00\x00\x09\x23Pa_GetLastHostErrorInfo',0,b'\x00\x00\x2A\x23Pa_GetSampleSize',0,b'\x00\x00\x18\x23Pa_GetStreamCpuLoad',0,b'\x00\x00\x06\x23Pa_GetStreamHostApiType',0,b'\x00\x00\x0B\x23Pa_GetStreamInfo',0,b'\x00\x00\x5C\x23Pa_GetStreamReadAvailable',0,b'\x00\x00\x18\x23Pa_GetStreamTime',0,b'\x00\x00\x5C\x23Pa_GetStreamWriteAvailable',0,b'\x00\x00\x5A\x23Pa_GetVersion',0,b'\x00\x00\x16\x23Pa_GetVersionText',0,b'\x00\x00\x26\x23Pa_HostApiDeviceIndexToDeviceIndex',0,b'\x00\x00\x1B\x23Pa_HostApiTypeIdToHostApiIndex',0,b'\x00\x00\x5A\x23Pa_Initialize',0,b'\x00\x00\x1E\x23Pa_IsFormatSupported',0,b'\x00\x00\x41\x23Pa_IsStreamActive',0,b'\x00\x00\x41\x23Pa_IsStreamStopped',0,b'\x00\x00\x37\x23Pa_OpenDefaultStream',0,b'\x00\x00\x2D\x23Pa_OpenStream',0,b'\x00\x00\x44\x23Pa_ReadStream',0,b'\x00\x00\x4E\x23Pa_SetStreamFinishedCallback',0,b'\x00\x00\x68\x23Pa_Sleep',0,b'\x00\x00\x41\x23Pa_StartStream',0,b'\x00\x00\x41\x23Pa_StopStream',0,b'\x00\x00\x5A\x23Pa_Terminate',0,b'\x00\x00\x49\x23Pa_WriteStream',0,b'\xFF\xFF\xFF\x0BeAudioCategoryAlerts',4,b'\xFF\xFF\xFF\x0BeAudioCategoryCommunications',3,b'\xFF\xFF\xFF\x0BeAudioCategoryGameChat',8,b'\xFF\xFF\xFF\x0BeAudioCategoryGameEffects',6,b'\xFF\xFF\xFF\x0BeAudioCategoryGameMedia',7,b'\xFF\xFF\xFF\x0BeAudioCategoryMedia',11,b'\xFF\xFF\xFF\x0BeAudioCategoryMovie',10,b'\xFF\xFF\xFF\x0BeAudioCategoryOther',0,b'\xFF\xFF\xFF\x0BeAudioCategorySoundEffects',5,b'\xFF\xFF\xFF\x0BeAudioCategorySpeech',9,b'\xFF\xFF\xFF\x0BeStreamOptionMatchFormat',2,b'\xFF\xFF\xFF\x0BeStreamOptionNone',0,b'\xFF\xFF\xFF\x0BeStreamOptionRaw',1,b'\xFF\xFF\xFF\x0BeThreadPriorityAudio',1,b'\xFF\xFF\xFF\x0BeThreadPriorityCapture',2,b'\xFF\xFF\xFF\x0BeThreadPriorityDistribution',3,b'\xFF\xFF\xFF\x0BeThreadPriorityGames',4,b'\xFF\xFF\xFF\x0BeThreadPriorityNone',0,b'\xFF\xFF\xFF\x0BeThreadPriorityPlayback',5,b'\xFF\xFF\xFF\x0BeThreadPriorityProAudio',6,b'\xFF\xFF\xFF\x0BeThreadPriorityWindowManager',7,b'\xFF\xFF\xFF\x0BpaAL',9,b'\xFF\xFF\xFF\x0BpaALSA',8,b'\xFF\xFF\xFF\x0BpaASIO',3,b'\xFF\xFF\xFF\x0BpaAbort',2,b'\xFF\xFF\xFF\x1FpaAsioUseChannelSelectors',1,b'\xFF\xFF\xFF\x0BpaAudioScienceHPI',14,b'\xFF\xFF\xFF\x0BpaBadBufferPtr',-9972,b'\xFF\xFF\xFF\x0BpaBadIODeviceCombination',-9993,b'\xFF\xFF\xFF\x0BpaBadStreamPtr',-9988,b'\xFF\xFF\xFF\x0BpaBeOS',10,b'\xFF\xFF\xFF\x0BpaBufferTooBig',-9991,b'\xFF\xFF\xFF\x0BpaBufferTooSmall',-9990,b'\xFF\xFF\xFF\x0BpaCanNotReadFromACallbackStream',-9977,b'\xFF\xFF\xFF\x0BpaCanNotReadFromAnOutputOnlyStream',-9975,b'\xFF\xFF\xFF\x0BpaCanNotWriteToACallbackStream',-9976,b'\xFF\xFF\xFF\x0BpaCanNotWriteToAnInputOnlyStream',-9974,b'\xFF\xFF\xFF\x1FpaClipOff',1,b'\xFF\xFF\xFF\x0BpaComplete',1,b'\xFF\xFF\xFF\x0BpaContinue',0,b'\xFF\xFF\xFF\x0BpaCoreAudio',5,b'\xFF\xFF\xFF\x1FpaCustomFormat',65536,b'\xFF\xFF\xFF\x0BpaDeviceUnavailable',-9985,b'\xFF\xFF\xFF\x0BpaDirectSound',1,b'\xFF\xFF\xFF\x1FpaDitherOff',2,b'\xFF\xFF\xFF\x1FpaFloat32',1,b'\xFF\xFF\xFF\x1FpaFormatIsSupported',0,b'\xFF\xFF\xFF\x1FpaFramesPerBufferUnspecified',0,b'\xFF\xFF\xFF\x0BpaHostApiNotFound',-9979,b'\xFF\xFF\xFF\x0BpaInDevelopment',0,b'\xFF\xFF\xFF\x0BpaIncompatibleHostApiSpecificStreamInfo',-9984,b'\xFF\xFF\xFF\x0BpaIncompatibleStreamHostApi',-9973,b'\xFF\xFF\xFF\x1FpaInputOverflow',2,b'\xFF\xFF\xFF\x0BpaInputOverflowed',-9981,b'\xFF\xFF\xFF\x1FpaInputUnderflow',1,b'\xFF\xFF\xFF\x0BpaInsufficientMemory',-9992,b'\xFF\xFF\xFF\x1FpaInt16',8,b'\xFF\xFF\xFF\x1FpaInt24',4,b'\xFF\xFF\xFF\x1FpaInt32',2,b'\xFF\xFF\xFF\x1FpaInt8',16,b'\xFF\xFF\xFF\x0BpaInternalError',-9986,b'\xFF\xFF\xFF\x0BpaInvalidChannelCount',-9998,b'\xFF\xFF\xFF\x0BpaInvalidDevice',-9996,b'\xFF\xFF\xFF\x0BpaInvalidFlag',-9995,b'\xFF\xFF\xFF\x0BpaInvalidHostApi',-9978,b'\xFF\xFF\xFF\x0BpaInvalidSampleRate',-9997,b'\xFF\xFF\xFF\x0BpaJACK',12,b'\xFF\xFF\xFF\x0BpaMME',2,b'\xFF\xFF\xFF\x1FpaMacCoreChangeDeviceParameters',1,b'\xFF\xFF\xFF\x1FpaMacCoreConversionQualityHigh',1024,b'\xFF\xFF\xFF\x1FpaMacCoreConversionQualityLow',768,b'\xFF\xFF\xFF\x1FpaMacCoreConversionQualityMax',0,b'\xFF\xFF\xFF\x1FpaMacCoreConversionQualityMedium',512,b'\xFF\xFF\xFF\x1FpaMacCoreConversionQualityMin',256,b'\xFF\xFF\xFF\x1FpaMacCoreFailIfConversionRequired',2,b'\xFF\xFF\xFF\x1FpaMacCoreMinimizeCPU',257,b'\xFF\xFF\xFF\x1FpaMacCoreMinimizeCPUButPlayNice',256,b'\xFF\xFF\xFF\x1FpaMacCorePlayNice',0,b'\xFF\xFF\xFF\x1FpaMacCorePro',1,b'\xFF\xFF\xFF\x1FpaNeverDropInput',4,b'\xFF\xFF\xFF\x1FpaNoDevice',-1,b'\xFF\xFF\xFF\x0BpaNoError',0,b'\xFF\xFF\xFF\x1FpaNoFlag',0,b'\xFF\xFF\xFF\x1FpaNonInterleaved',2147483648,b'\xFF\xFF\xFF\x0BpaNotInitialized',-10000,b'\xFF\xFF\xFF\x0BpaNullCallback',-9989,b'\xFF\xFF\xFF\x0BpaOSS',7,b'\xFF\xFF\xFF\x1FpaOutputOverflow',8,b'\xFF\xFF\xFF\x1FpaOutputUnderflow',4,b'\xFF\xFF\xFF\x0BpaOutputUnderflowed',-9980,b'\xFF\xFF\xFF\x1FpaPlatformSpecificFlags',4294901760,b'\xFF\xFF\xFF\x1FpaPrimeOutputBuffersUsingStreamCallback',8,b'\xFF\xFF\xFF\x1FpaPrimingOutput',16,b'\xFF\xFF\xFF\x0BpaSampleFormatNotSupported',-9994,b'\xFF\xFF\xFF\x0BpaSoundManager',4,b'\xFF\xFF\xFF\x0BpaStreamIsNotStopped',-9982,b'\xFF\xFF\xFF\x0BpaStreamIsStopped',-9983,b'\xFF\xFF\xFF\x0BpaTimedOut',-9987,b'\xFF\xFF\xFF\x1FpaUInt8',32,b'\xFF\xFF\xFF\x0BpaUnanticipatedHostError',-9999,b'\xFF\xFF\xFF\x1FpaUseHostApiSpecificDeviceSpecification',-2,b'\xFF\xFF\xFF\x0BpaWASAPI',13,b'\xFF\xFF\xFF\x0BpaWDMKS',11,b'\xFF\xFF\xFF\x0BpaWinWasapiExclusive',1,b'\xFF\xFF\xFF\x0BpaWinWasapiPolling',8,b'\xFF\xFF\xFF\x0BpaWinWasapiRedirectHostProcessor',2,b'\xFF\xFF\xFF\x0BpaWinWasapiThreadPriority',16,b'\xFF\xFF\xFF\x0BpaWinWasapiUseChannelMask',4),
- _struct_unions = ((b'\x00\x00\x00\x7D\x00\x00\x00\x02$PaMacCoreStreamInfo',b'\x00\x00\x2B\x11size',b'\x00\x00\x1C\x11hostApiType',b'\x00\x00\x2B\x11version',b'\x00\x00\x2B\x11flags',b'\x00\x00\x61\x11channelMap',b'\x00\x00\x2B\x11channelMapSize'),(b'\x00\x00\x00\x75\x00\x00\x00\x02PaAsioStreamInfo',b'\x00\x00\x2B\x11size',b'\x00\x00\x1C\x11hostApiType',b'\x00\x00\x2B\x11version',b'\x00\x00\x2B\x11flags',b'\x00\x00\x8A\x11channelSelectors'),(b'\x00\x00\x00\x77\x00\x00\x00\x02PaDeviceInfo',b'\x00\x00\x01\x11structVersion',b'\x00\x00\x88\x11name',b'\x00\x00\x01\x11hostApi',b'\x00\x00\x01\x11maxInputChannels',b'\x00\x00\x01\x11maxOutputChannels',b'\x00\x00\x21\x11defaultLowInputLatency',b'\x00\x00\x21\x11defaultLowOutputLatency',b'\x00\x00\x21\x11defaultHighInputLatency',b'\x00\x00\x21\x11defaultHighOutputLatency',b'\x00\x00\x21\x11defaultSampleRate'),(b'\x00\x00\x00\x7A\x00\x00\x00\x02PaHostApiInfo',b'\x00\x00\x01\x11structVersion',b'\x00\x00\x1C\x11type',b'\x00\x00\x88\x11name',b'\x00\x00\x01\x11deviceCount',b'\x00\x00\x01\x11defaultInputDevice',b'\x00\x00\x01\x11defaultOutputDevice'),(b'\x00\x00\x00\x7C\x00\x00\x00\x02PaHostErrorInfo',b'\x00\x00\x1C\x11hostApiType',b'\x00\x00\x69\x11errorCode',b'\x00\x00\x88\x11errorText'),(b'\x00\x00\x00\x7F\x00\x00\x00\x02PaStreamCallbackTimeInfo',b'\x00\x00\x21\x11inputBufferAdcTime',b'\x00\x00\x21\x11currentTime',b'\x00\x00\x21\x11outputBufferDacTime'),(b'\x00\x00\x00\x81\x00\x00\x00\x02PaStreamInfo',b'\x00\x00\x01\x11structVersion',b'\x00\x00\x21\x11inputLatency',b'\x00\x00\x21\x11outputLatency',b'\x00\x00\x21\x11sampleRate'),(b'\x00\x00\x00\x82\x00\x00\x00\x02PaStreamParameters',b'\x00\x00\x01\x11device',b'\x00\x00\x01\x11channelCount',b'\x00\x00\x2B\x11sampleFormat',b'\x00\x00\x21\x11suggestedLatency',b'\x00\x00\x07\x11hostApiSpecificStreamInfo'),(b'\x00\x00\x00\x85\x00\x00\x00\x02PaWasapiStreamInfo',b'\x00\x00\x2B\x11size',b'\x00\x00\x1C\x11hostApiType',b'\x00\x00\x2B\x11version',b'\x00\x00\x2B\x11flags',b'\x00\x00\x2B\x11channelMask',b'\x00\x00\x8C\x11hostProcessorOutput',b'\x00\x00\x8C\x11hostProcessorInput',b'\x00\x00\x87\x11threadPriority',b'\x00\x00\x84\x11streamCategory',b'\x00\x00\x86\x11streamOption')),
- _enums = (b'\x00\x00\x00\x78\x00\x00\x00\x15PaErrorCode\x00paNoError,paNotInitialized,paUnanticipatedHostError,paInvalidChannelCount,paInvalidSampleRate,paInvalidDevice,paInvalidFlag,paSampleFormatNotSupported,paBadIODeviceCombination,paInsufficientMemory,paBufferTooBig,paBufferTooSmall,paNullCallback,paBadStreamPtr,paTimedOut,paInternalError,paDeviceUnavailable,paIncompatibleHostApiSpecificStreamInfo,paStreamIsStopped,paStreamIsNotStopped,paInputOverflowed,paOutputUnderflowed,paHostApiNotFound,paInvalidHostApi,paCanNotReadFromACallbackStream,paCanNotWriteToACallbackStream,paCanNotReadFromAnOutputOnlyStream,paCanNotWriteToAnInputOnlyStream,paIncompatibleStreamHostApi,paBadBufferPtr',b'\x00\x00\x00\x1C\x00\x00\x00\x16PaHostApiTypeId\x00paInDevelopment,paDirectSound,paMME,paASIO,paSoundManager,paCoreAudio,paOSS,paALSA,paAL,paBeOS,paWDMKS,paJACK,paWASAPI,paAudioScienceHPI',b'\x00\x00\x00\x7E\x00\x00\x00\x16PaStreamCallbackResult\x00paContinue,paComplete,paAbort',b'\x00\x00\x00\x83\x00\x00\x00\x16PaWasapiFlags\x00paWinWasapiExclusive,paWinWasapiRedirectHostProcessor,paWinWasapiUseChannelMask,paWinWasapiPolling,paWinWasapiThreadPriority',b'\x00\x00\x00\x84\x00\x00\x00\x16PaWasapiStreamCategory\x00eAudioCategoryOther,eAudioCategoryCommunications,eAudioCategoryAlerts,eAudioCategorySoundEffects,eAudioCategoryGameEffects,eAudioCategoryGameMedia,eAudioCategoryGameChat,eAudioCategorySpeech,eAudioCategoryMovie,eAudioCategoryMedia',b'\x00\x00\x00\x86\x00\x00\x00\x16PaWasapiStreamOption\x00eStreamOptionNone,eStreamOptionRaw,eStreamOptionMatchFormat',b'\x00\x00\x00\x87\x00\x00\x00\x16PaWasapiThreadPriority\x00eThreadPriorityNone,eThreadPriorityAudio,eThreadPriorityCapture,eThreadPriorityDistribution,eThreadPriorityGames,eThreadPriorityPlayback,eThreadPriorityProAudio,eThreadPriorityWindowManager'),
- _typenames = (b'\x00\x00\x00\x75PaAsioStreamInfo',b'\x00\x00\x00\x01PaDeviceIndex',b'\x00\x00\x00\x77PaDeviceInfo',b'\x00\x00\x00\x01PaError',b'\x00\x00\x00\x78PaErrorCode',b'\x00\x00\x00\x01PaHostApiIndex',b'\x00\x00\x00\x7APaHostApiInfo',b'\x00\x00\x00\x1CPaHostApiTypeId',b'\x00\x00\x00\x7CPaHostErrorInfo',b'\x00\x00\x00\x7DPaMacCoreStreamInfo',b'\x00\x00\x00\x2BPaSampleFormat',b'\x00\x00\x00\x8DPaStream',b'\x00\x00\x00\x52PaStreamCallback',b'\x00\x00\x00\x2BPaStreamCallbackFlags',b'\x00\x00\x00\x7EPaStreamCallbackResult',b'\x00\x00\x00\x7FPaStreamCallbackTimeInfo',b'\x00\x00\x00\x6BPaStreamFinishedCallback',b'\x00\x00\x00\x2BPaStreamFlags',b'\x00\x00\x00\x81PaStreamInfo',b'\x00\x00\x00\x82PaStreamParameters',b'\x00\x00\x00\x21PaTime',b'\x00\x00\x00\x83PaWasapiFlags',b'\x00\x00\x00\x8CPaWasapiHostProcessorCallback',b'\x00\x00\x00\x84PaWasapiStreamCategory',b'\x00\x00\x00\x85PaWasapiStreamInfo',b'\x00\x00\x00\x86PaWasapiStreamOption',b'\x00\x00\x00\x87PaWasapiThreadPriority',b'\x00\x00\x00\x2BPaWinWaveFormatChannelMask',b'\x00\x00\x00\x8BSInt32'),
-)
diff --git a/spaces/carlosalonso/Detection-video/carpeta_deteccion/tests/structures/test_boxes.py b/spaces/carlosalonso/Detection-video/carpeta_deteccion/tests/structures/test_boxes.py
deleted file mode 100644
index 101191818c511cf90c3c8f2cbc55aa49295697fa..0000000000000000000000000000000000000000
--- a/spaces/carlosalonso/Detection-video/carpeta_deteccion/tests/structures/test_boxes.py
+++ /dev/null
@@ -1,223 +0,0 @@
-# Copyright (c) Facebook, Inc. and its affiliates.
-import json
-import math
-import numpy as np
-import unittest
-import torch
-
-from detectron2.structures import Boxes, BoxMode, pairwise_ioa, pairwise_iou
-from detectron2.utils.testing import reload_script_model
-
-
-class TestBoxMode(unittest.TestCase):
- def _convert_xy_to_wh(self, x):
- return BoxMode.convert(x, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS)
-
- def _convert_xywha_to_xyxy(self, x):
- return BoxMode.convert(x, BoxMode.XYWHA_ABS, BoxMode.XYXY_ABS)
-
- def _convert_xywh_to_xywha(self, x):
- return BoxMode.convert(x, BoxMode.XYWH_ABS, BoxMode.XYWHA_ABS)
-
- def test_convert_int_mode(self):
- BoxMode.convert([1, 2, 3, 4], 0, 1)
-
- def test_box_convert_list(self):
- for tp in [list, tuple]:
- box = tp([5.0, 5.0, 10.0, 10.0])
- output = self._convert_xy_to_wh(box)
- self.assertIsInstance(output, tp)
- self.assertIsInstance(output[0], float)
- self.assertEqual(output, tp([5.0, 5.0, 5.0, 5.0]))
-
- with self.assertRaises(Exception):
- self._convert_xy_to_wh([box])
-
- def test_box_convert_array(self):
- box = np.asarray([[5, 5, 10, 10], [1, 1, 2, 3]])
- output = self._convert_xy_to_wh(box)
- self.assertEqual(output.dtype, box.dtype)
- self.assertEqual(output.shape, box.shape)
- self.assertTrue((output[0] == [5, 5, 5, 5]).all())
- self.assertTrue((output[1] == [1, 1, 1, 2]).all())
-
- def test_box_convert_cpu_tensor(self):
- box = torch.tensor([[5, 5, 10, 10], [1, 1, 2, 3]])
- output = self._convert_xy_to_wh(box)
- self.assertEqual(output.dtype, box.dtype)
- self.assertEqual(output.shape, box.shape)
- output = output.numpy()
- self.assertTrue((output[0] == [5, 5, 5, 5]).all())
- self.assertTrue((output[1] == [1, 1, 1, 2]).all())
-
- @unittest.skipIf(not torch.cuda.is_available(), "CUDA not available")
- def test_box_convert_cuda_tensor(self):
- box = torch.tensor([[5, 5, 10, 10], [1, 1, 2, 3]]).cuda()
- output = self._convert_xy_to_wh(box)
- self.assertEqual(output.dtype, box.dtype)
- self.assertEqual(output.shape, box.shape)
- self.assertEqual(output.device, box.device)
- output = output.cpu().numpy()
- self.assertTrue((output[0] == [5, 5, 5, 5]).all())
- self.assertTrue((output[1] == [1, 1, 1, 2]).all())
-
- def test_box_convert_xywha_to_xyxy_list(self):
- for tp in [list, tuple]:
- box = tp([50, 50, 30, 20, 0])
- output = self._convert_xywha_to_xyxy(box)
- self.assertIsInstance(output, tp)
- self.assertEqual(output, tp([35, 40, 65, 60]))
-
- with self.assertRaises(Exception):
- self._convert_xywha_to_xyxy([box])
-
- def test_box_convert_xywha_to_xyxy_array(self):
- for dtype in [np.float64, np.float32]:
- box = np.asarray(
- [
- [50, 50, 30, 20, 0],
- [50, 50, 30, 20, 90],
- [1, 1, math.sqrt(2), math.sqrt(2), -45],
- ],
- dtype=dtype,
- )
- output = self._convert_xywha_to_xyxy(box)
- self.assertEqual(output.dtype, box.dtype)
- expected = np.asarray([[35, 40, 65, 60], [40, 35, 60, 65], [0, 0, 2, 2]], dtype=dtype)
- self.assertTrue(np.allclose(output, expected, atol=1e-6), "output={}".format(output))
-
- def test_box_convert_xywha_to_xyxy_tensor(self):
- for dtype in [torch.float32, torch.float64]:
- box = torch.tensor(
- [
- [50, 50, 30, 20, 0],
- [50, 50, 30, 20, 90],
- [1, 1, math.sqrt(2), math.sqrt(2), -45],
- ],
- dtype=dtype,
- )
- output = self._convert_xywha_to_xyxy(box)
- self.assertEqual(output.dtype, box.dtype)
- expected = torch.tensor([[35, 40, 65, 60], [40, 35, 60, 65], [0, 0, 2, 2]], dtype=dtype)
-
- self.assertTrue(torch.allclose(output, expected, atol=1e-6), "output={}".format(output))
-
- def test_box_convert_xywh_to_xywha_list(self):
- for tp in [list, tuple]:
- box = tp([50, 50, 30, 20])
- output = self._convert_xywh_to_xywha(box)
- self.assertIsInstance(output, tp)
- self.assertEqual(output, tp([65, 60, 30, 20, 0]))
-
- with self.assertRaises(Exception):
- self._convert_xywh_to_xywha([box])
-
- def test_box_convert_xywh_to_xywha_array(self):
- for dtype in [np.float64, np.float32]:
- box = np.asarray([[30, 40, 70, 60], [30, 40, 60, 70], [-1, -1, 2, 2]], dtype=dtype)
- output = self._convert_xywh_to_xywha(box)
- self.assertEqual(output.dtype, box.dtype)
- expected = np.asarray(
- [[65, 70, 70, 60, 0], [60, 75, 60, 70, 0], [0, 0, 2, 2, 0]], dtype=dtype
- )
- self.assertTrue(np.allclose(output, expected, atol=1e-6), "output={}".format(output))
-
- def test_box_convert_xywh_to_xywha_tensor(self):
- for dtype in [torch.float32, torch.float64]:
- box = torch.tensor([[30, 40, 70, 60], [30, 40, 60, 70], [-1, -1, 2, 2]], dtype=dtype)
- output = self._convert_xywh_to_xywha(box)
- self.assertEqual(output.dtype, box.dtype)
- expected = torch.tensor(
- [[65, 70, 70, 60, 0], [60, 75, 60, 70, 0], [0, 0, 2, 2, 0]], dtype=dtype
- )
-
- self.assertTrue(torch.allclose(output, expected, atol=1e-6), "output={}".format(output))
-
- def test_json_serializable(self):
- payload = {"box_mode": BoxMode.XYWH_REL}
- try:
- json.dumps(payload)
- except Exception:
- self.fail("JSON serialization failed")
-
- def test_json_deserializable(self):
- payload = '{"box_mode": 2}'
- obj = json.loads(payload)
- try:
- obj["box_mode"] = BoxMode(obj["box_mode"])
- except Exception:
- self.fail("JSON deserialization failed")
-
-
-class TestBoxIOU(unittest.TestCase):
- def create_boxes(self):
- boxes1 = torch.tensor([[0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0]])
-
- boxes2 = torch.tensor(
- [
- [0.0, 0.0, 1.0, 1.0],
- [0.0, 0.0, 0.5, 1.0],
- [0.0, 0.0, 1.0, 0.5],
- [0.0, 0.0, 0.5, 0.5],
- [0.5, 0.5, 1.0, 1.0],
- [0.5, 0.5, 1.5, 1.5],
- ]
- )
- return boxes1, boxes2
-
- def test_pairwise_iou(self):
- boxes1, boxes2 = self.create_boxes()
- expected_ious = torch.tensor(
- [
- [1.0, 0.5, 0.5, 0.25, 0.25, 0.25 / (2 - 0.25)],
- [1.0, 0.5, 0.5, 0.25, 0.25, 0.25 / (2 - 0.25)],
- ]
- )
-
- ious = pairwise_iou(Boxes(boxes1), Boxes(boxes2))
- self.assertTrue(torch.allclose(ious, expected_ious))
-
- def test_pairwise_ioa(self):
- boxes1, boxes2 = self.create_boxes()
- expected_ioas = torch.tensor(
- [[1.0, 1.0, 1.0, 1.0, 1.0, 0.25], [1.0, 1.0, 1.0, 1.0, 1.0, 0.25]]
- )
- ioas = pairwise_ioa(Boxes(boxes1), Boxes(boxes2))
- self.assertTrue(torch.allclose(ioas, expected_ioas))
-
-
-class TestBoxes(unittest.TestCase):
- def test_empty_cat(self):
- x = Boxes.cat([])
- self.assertTrue(x.tensor.shape, (0, 4))
-
- def test_to(self):
- x = Boxes(torch.rand(3, 4))
- self.assertEqual(x.to(device="cpu").tensor.device.type, "cpu")
-
- def test_scriptability(self):
- def func(x):
- boxes = Boxes(x)
- test = boxes.to(torch.device("cpu")).tensor
- return boxes.area(), test
-
- f = torch.jit.script(func)
- f = reload_script_model(f)
- f(torch.rand((3, 4)))
-
- data = torch.rand((3, 4))
-
- def func_cat(x: torch.Tensor):
- boxes1 = Boxes(x)
- boxes2 = Boxes(x)
- # boxes3 = Boxes.cat([boxes1, boxes2]) # this is not supported by torchsript for now.
- boxes3 = boxes1.cat([boxes1, boxes2])
- return boxes3
-
- f = torch.jit.script(func_cat)
- script_box = f(data)
- self.assertTrue(torch.equal(torch.cat([data, data]), script_box.tensor))
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/spaces/chendl/compositional_test/multimodal/tools/instruct_tuning_data/pisc.py b/spaces/chendl/compositional_test/multimodal/tools/instruct_tuning_data/pisc.py
deleted file mode 100644
index 562cec805725481fad3277543f4c8d5947473e6c..0000000000000000000000000000000000000000
--- a/spaces/chendl/compositional_test/multimodal/tools/instruct_tuning_data/pisc.py
+++ /dev/null
@@ -1,51 +0,0 @@
-import json
-import os
-from tqdm import tqdm
-import webdataset as wds
-from utils import MAXCOUNT, NAMING, check_sample
-import numpy as np
-PISC_ROOT = "/gpfs/u/home/LMCG/LMCGljnn/scratch/datasets/raw/PISC"
-OUT_DIR = "/gpfs/u/home/LMCG/LMCGljnn/scratch-shared/junyan/raw/instruct/eval/pisc"
-
-rel_id_to_type = ["friends", "family", "couple", "professional", "commercial", "no relation"]
-
-if __name__ == "__main__":
- os.makedirs(OUT_DIR, exist_ok=True)
- annotation_image_info = json.load(open(os.path.join(PISC_ROOT, "annotation_image_info.json")))
- relationships = json.load(open(os.path.join(PISC_ROOT, "relationship.json")))
- relationship_trainidx = json.load(open(os.path.join(PISC_ROOT, "relationship_split", "relation_trainidx.json")))
- relationship_testidx = json.load(open(os.path.join(PISC_ROOT, "relationship_split", "relation_testidx.json")))
- data = {}
- uuid = 0
- with wds.ShardWriter(os.path.join(OUT_DIR, NAMING), maxcount=MAXCOUNT**3) as sink:
- for annotation in tqdm(annotation_image_info):
- imgH = annotation["imgH"]
- imgW = annotation["imgW"]
- id = annotation["id"]
- bbox = annotation["bbox"] # xyxy
- if str(id) not in relationships:
- tqdm.write(f"skip {id} due to not in relationships")
- continue
- if str(id) not in relationship_testidx:
- tqdm.write(f"skip {id} due to not in train set")
- continue
- relationship = relationships[str(id)]
- for rel in relationship:
- type = rel_id_to_type[relationship[rel] - 1]
- A_id, B_id = list(map(int, rel.split(" ")))
- A_box = np.array(bbox[A_id - 1]).astype(float) / np.array([imgW, imgH, imgW, imgH]).astype(float)
- B_box = np.array(bbox[B_id - 1]).astype(float) / np.array([imgW, imgH, imgW, imgH]).astype(float)
- data = [A_box, B_box, type]
- image_path = os.path.join(PISC_ROOT, "image", str(id).zfill(5)+".jpg")
- dataset = "pisc_relation_split"
- key = f"{dataset}_{id}_{uuid}"
- uuid += 1
- assert os.path.exists(image_path)
- sample = {
- "__key__": key,
- "image_path.txt": image_path,
- "dataset.txt": dataset,
- "data.pyd": data,
- }
- check_sample(sample)
- sink.write(sample)
diff --git a/spaces/chikoto/Umamusume-DeBERTa-VITS2-TTS-JP/utils.py b/spaces/chikoto/Umamusume-DeBERTa-VITS2-TTS-JP/utils.py
deleted file mode 100644
index f88b9cc049ae8c30c62f189821878b5f2587cbc6..0000000000000000000000000000000000000000
--- a/spaces/chikoto/Umamusume-DeBERTa-VITS2-TTS-JP/utils.py
+++ /dev/null
@@ -1,356 +0,0 @@
-import os
-import glob
-import argparse
-import logging
-import json
-import subprocess
-import numpy as np
-from scipy.io.wavfile import read
-import torch
-
-MATPLOTLIB_FLAG = False
-
-logger = logging.getLogger(__name__)
-
-
-def load_checkpoint(checkpoint_path, model, optimizer=None, skip_optimizer=False):
- assert os.path.isfile(checkpoint_path)
- checkpoint_dict = torch.load(checkpoint_path, map_location="cpu")
- iteration = checkpoint_dict["iteration"]
- learning_rate = checkpoint_dict["learning_rate"]
- if (
- optimizer is not None
- and not skip_optimizer
- and checkpoint_dict["optimizer"] is not None
- ):
- optimizer.load_state_dict(checkpoint_dict["optimizer"])
- elif optimizer is None and not skip_optimizer:
- # else: Disable this line if Infer and resume checkpoint,then enable the line upper
- new_opt_dict = optimizer.state_dict()
- new_opt_dict_params = new_opt_dict["param_groups"][0]["params"]
- new_opt_dict["param_groups"] = checkpoint_dict["optimizer"]["param_groups"]
- new_opt_dict["param_groups"][0]["params"] = new_opt_dict_params
- optimizer.load_state_dict(new_opt_dict)
-
- saved_state_dict = checkpoint_dict["model"]
- if hasattr(model, "module"):
- state_dict = model.module.state_dict()
- else:
- state_dict = model.state_dict()
-
- new_state_dict = {}
- for k, v in state_dict.items():
- try:
- # assert "emb_g" not in k
- new_state_dict[k] = saved_state_dict[k]
- assert saved_state_dict[k].shape == v.shape, (
- saved_state_dict[k].shape,
- v.shape,
- )
- except:
- # For upgrading from the old version
- if "ja_bert_proj" in k:
- v = torch.zeros_like(v)
- logger.warn(
- f"Seems you are using the old version of the model, the {k} is automatically set to zero for backward compatibility"
- )
- else:
- logger.error(f"{k} is not in the checkpoint")
-
- new_state_dict[k] = v
-
- if hasattr(model, "module"):
- model.module.load_state_dict(new_state_dict, strict=False)
- else:
- model.load_state_dict(new_state_dict, strict=False)
-
- logger.info(
- "Loaded checkpoint '{}' (iteration {})".format(checkpoint_path, iteration)
- )
-
- return model, optimizer, learning_rate, iteration
-
-
-def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path):
- logger.info(
- "Saving model and optimizer state at iteration {} to {}".format(
- iteration, checkpoint_path
- )
- )
- if hasattr(model, "module"):
- state_dict = model.module.state_dict()
- else:
- state_dict = model.state_dict()
- torch.save(
- {
- "model": state_dict,
- "iteration": iteration,
- "optimizer": optimizer.state_dict(),
- "learning_rate": learning_rate,
- },
- checkpoint_path,
- )
-
-
-def summarize(
- writer,
- global_step,
- scalars={},
- histograms={},
- images={},
- audios={},
- audio_sampling_rate=22050,
-):
- for k, v in scalars.items():
- writer.add_scalar(k, v, global_step)
- for k, v in histograms.items():
- writer.add_histogram(k, v, global_step)
- for k, v in images.items():
- writer.add_image(k, v, global_step, dataformats="HWC")
- for k, v in audios.items():
- writer.add_audio(k, v, global_step, audio_sampling_rate)
-
-
-def latest_checkpoint_path(dir_path, regex="G_*.pth"):
- f_list = glob.glob(os.path.join(dir_path, regex))
- f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
- x = f_list[-1]
- return x
-
-
-def plot_spectrogram_to_numpy(spectrogram):
- global MATPLOTLIB_FLAG
- if not MATPLOTLIB_FLAG:
- import matplotlib
-
- matplotlib.use("Agg")
- MATPLOTLIB_FLAG = True
- mpl_logger = logging.getLogger("matplotlib")
- mpl_logger.setLevel(logging.WARNING)
- import matplotlib.pylab as plt
- import numpy as np
-
- fig, ax = plt.subplots(figsize=(10, 2))
- im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation="none")
- plt.colorbar(im, ax=ax)
- plt.xlabel("Frames")
- plt.ylabel("Channels")
- plt.tight_layout()
-
- fig.canvas.draw()
- data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
- data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
- plt.close()
- return data
-
-
-def plot_alignment_to_numpy(alignment, info=None):
- global MATPLOTLIB_FLAG
- if not MATPLOTLIB_FLAG:
- import matplotlib
-
- matplotlib.use("Agg")
- MATPLOTLIB_FLAG = True
- mpl_logger = logging.getLogger("matplotlib")
- mpl_logger.setLevel(logging.WARNING)
- import matplotlib.pylab as plt
- import numpy as np
-
- fig, ax = plt.subplots(figsize=(6, 4))
- im = ax.imshow(
- alignment.transpose(), aspect="auto", origin="lower", interpolation="none"
- )
- fig.colorbar(im, ax=ax)
- xlabel = "Decoder timestep"
- if info is not None:
- xlabel += "\n\n" + info
- plt.xlabel(xlabel)
- plt.ylabel("Encoder timestep")
- plt.tight_layout()
-
- fig.canvas.draw()
- data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
- data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
- plt.close()
- return data
-
-
-def load_wav_to_torch(full_path):
- sampling_rate, data = read(full_path)
- return torch.FloatTensor(data.astype(np.float32)), sampling_rate
-
-
-def load_filepaths_and_text(filename, split="|"):
- with open(filename, encoding="utf-8") as f:
- filepaths_and_text = [line.strip().split(split) for line in f]
- return filepaths_and_text
-
-
-def get_hparams(init=True):
- parser = argparse.ArgumentParser()
- parser.add_argument(
- "-c",
- "--config",
- type=str,
- default="./configs/base.json",
- help="JSON file for configuration",
- )
- parser.add_argument("-m", "--model", type=str, required=True, help="Model name")
-
- args = parser.parse_args()
- model_dir = args.model
-
- if not os.path.exists(model_dir):
- os.makedirs(model_dir)
-
- config_path = args.config
- config_save_path = os.path.join(model_dir, "config.json")
- if init:
- with open(config_path, "r", encoding="utf-8") as f:
- data = f.read()
- with open(config_save_path, "w", encoding="utf-8") as f:
- f.write(data)
- else:
- with open(config_save_path, "r", vencoding="utf-8") as f:
- data = f.read()
- config = json.loads(data)
- hparams = HParams(**config)
- hparams.model_dir = model_dir
- return hparams
-
-
-def clean_checkpoints(path_to_models="logs/44k/", n_ckpts_to_keep=2, sort_by_time=True):
- """Freeing up space by deleting saved ckpts
-
- Arguments:
- path_to_models -- Path to the model directory
- n_ckpts_to_keep -- Number of ckpts to keep, excluding G_0.pth and D_0.pth
- sort_by_time -- True -> chronologically delete ckpts
- False -> lexicographically delete ckpts
- """
- import re
-
- ckpts_files = [
- f
- for f in os.listdir(path_to_models)
- if os.path.isfile(os.path.join(path_to_models, f))
- ]
-
- def name_key(_f):
- return int(re.compile("._(\\d+)\\.pth").match(_f).group(1))
-
- def time_key(_f):
- return os.path.getmtime(os.path.join(path_to_models, _f))
-
- sort_key = time_key if sort_by_time else name_key
-
- def x_sorted(_x):
- return sorted(
- [f for f in ckpts_files if f.startswith(_x) and not f.endswith("_0.pth")],
- key=sort_key,
- )
-
- to_del = [
- os.path.join(path_to_models, fn)
- for fn in (x_sorted("G")[:-n_ckpts_to_keep] + x_sorted("D")[:-n_ckpts_to_keep])
- ]
-
- def del_info(fn):
- return logger.info(f".. Free up space by deleting ckpt {fn}")
-
- def del_routine(x):
- return [os.remove(x), del_info(x)]
-
- [del_routine(fn) for fn in to_del]
-
-
-def get_hparams_from_dir(model_dir):
- config_save_path = os.path.join(model_dir, "config.json")
- with open(config_save_path, "r", encoding="utf-8") as f:
- data = f.read()
- config = json.loads(data)
-
- hparams = HParams(**config)
- hparams.model_dir = model_dir
- return hparams
-
-
-def get_hparams_from_file(config_path):
- with open(config_path, "r", encoding="utf-8") as f:
- data = f.read()
- config = json.loads(data)
-
- hparams = HParams(**config)
- return hparams
-
-
-def check_git_hash(model_dir):
- source_dir = os.path.dirname(os.path.realpath(__file__))
- if not os.path.exists(os.path.join(source_dir, ".git")):
- logger.warn(
- "{} is not a git repository, therefore hash value comparison will be ignored.".format(
- source_dir
- )
- )
- return
-
- cur_hash = subprocess.getoutput("git rev-parse HEAD")
-
- path = os.path.join(model_dir, "githash")
- if os.path.exists(path):
- saved_hash = open(path).read()
- if saved_hash != cur_hash:
- logger.warn(
- "git hash values are different. {}(saved) != {}(current)".format(
- saved_hash[:8], cur_hash[:8]
- )
- )
- else:
- open(path, "w").write(cur_hash)
-
-
-def get_logger(model_dir, filename="train.log"):
- global logger
- logger = logging.getLogger(os.path.basename(model_dir))
- logger.setLevel(logging.DEBUG)
-
- formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
- if not os.path.exists(model_dir):
- os.makedirs(model_dir)
- h = logging.FileHandler(os.path.join(model_dir, filename))
- h.setLevel(logging.DEBUG)
- h.setFormatter(formatter)
- logger.addHandler(h)
- return logger
-
-
-class HParams:
- def __init__(self, **kwargs):
- for k, v in kwargs.items():
- if type(v) == dict:
- v = HParams(**v)
- self[k] = v
-
- def keys(self):
- return self.__dict__.keys()
-
- def items(self):
- return self.__dict__.items()
-
- def values(self):
- return self.__dict__.values()
-
- def __len__(self):
- return len(self.__dict__)
-
- def __getitem__(self, key):
- return getattr(self, key)
-
- def __setitem__(self, key, value):
- return setattr(self, key, value)
-
- def __contains__(self, key):
- return key in self.__dict__
-
- def __repr__(self):
- return self.__dict__.__repr__()
diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/cffi/lock.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/cffi/lock.py
deleted file mode 100644
index db91b7158c4ee9aa653462fe38e79ed1b553db87..0000000000000000000000000000000000000000
--- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/cffi/lock.py
+++ /dev/null
@@ -1,30 +0,0 @@
-import sys
-
-if sys.version_info < (3,):
- try:
- from thread import allocate_lock
- except ImportError:
- from dummy_thread import allocate_lock
-else:
- try:
- from _thread import allocate_lock
- except ImportError:
- from _dummy_thread import allocate_lock
-
-
-##import sys
-##l1 = allocate_lock
-
-##class allocate_lock(object):
-## def __init__(self):
-## self._real = l1()
-## def __enter__(self):
-## for i in range(4, 0, -1):
-## print sys._getframe(i).f_code
-## print
-## return self._real.__enter__()
-## def __exit__(self, *args):
-## return self._real.__exit__(*args)
-## def acquire(self, f):
-## assert f is False
-## return self._real.acquire(f)
diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/clickhouse_connect/datatypes/container.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/clickhouse_connect/datatypes/container.py
deleted file mode 100644
index 516a57a596330c58481bbe46fd706e601b2b84f2..0000000000000000000000000000000000000000
--- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/clickhouse_connect/datatypes/container.py
+++ /dev/null
@@ -1,307 +0,0 @@
-import array
-import logging
-from typing import Sequence, Collection
-
-from clickhouse_connect.driver.insert import InsertContext
-from clickhouse_connect.driver.query import QueryContext
-from clickhouse_connect.driver.types import ByteSource
-from clickhouse_connect.json_impl import any_to_json
-from clickhouse_connect.datatypes.base import ClickHouseType, TypeDef
-from clickhouse_connect.driver.common import must_swap
-from clickhouse_connect.datatypes.registry import get_from_name
-
-logger = logging.getLogger(__name__)
-
-
-class Array(ClickHouseType):
- __slots__ = ('element_type',)
- python_type = list
-
- def __init__(self, type_def: TypeDef):
- super().__init__(type_def)
- self.element_type = get_from_name(type_def.values[0])
- self._name_suffix = f'({self.element_type.name})'
-
- def read_column_prefix(self, source: ByteSource):
- return self.element_type.read_column_prefix(source)
-
- def _data_size(self, sample: Sequence) -> int:
- if len(sample) == 0:
- return 8
- total = 0
- for x in sample:
- total += self.element_type.data_size(x)
- return total // len(sample) + 8
-
- # pylint: disable=too-many-locals
- def read_column_data(self, source: ByteSource, num_rows: int, ctx: QueryContext):
- final_type = self.element_type
- depth = 1
- while isinstance(final_type, Array):
- depth += 1
- final_type = final_type.element_type
- level_size = num_rows
- offset_sizes = []
- for _ in range(depth):
- level_offsets = source.read_array('Q', level_size)
- offset_sizes.append(level_offsets)
- level_size = level_offsets[-1] if level_offsets else 0
- if level_size:
- all_values = final_type.read_column_data(source, level_size, ctx)
- else:
- all_values = []
- column = all_values if isinstance(all_values, list) else list(all_values)
- for offset_range in reversed(offset_sizes):
- data = []
- last = 0
- for x in offset_range:
- data.append(column[last: x])
- last = x
- column = data
- return column
-
- def write_column_prefix(self, dest: bytearray):
- self.element_type.write_column_prefix(dest)
-
- def write_column_data(self, column: Sequence, dest: bytearray, ctx: InsertContext):
- final_type = self.element_type
- depth = 1
- while isinstance(final_type, Array):
- depth += 1
- final_type = final_type.element_type
- for _ in range(depth):
- total = 0
- data = []
- offsets = array.array('Q')
- for x in column:
- total += len(x)
- offsets.append(total)
- data.extend(x)
- if must_swap:
- offsets.byteswap()
- dest += offsets.tobytes()
- column = data
- final_type.write_column_data(column, dest, ctx)
-
-
-class Tuple(ClickHouseType):
- _slots = 'element_names', 'element_types'
- python_type = tuple
- valid_formats = 'tuple', 'dict', 'json', 'native' # native is 'tuple' for unnamed tuples, and dict for named tuples
-
- def __init__(self, type_def: TypeDef):
- super().__init__(type_def)
- self.element_names = type_def.keys
- self.element_types = [get_from_name(name) for name in type_def.values]
- if self.element_names:
- self._name_suffix = f"({', '.join(k + ' ' + str(v) for k, v in zip(type_def.keys, type_def.values))})"
- else:
- self._name_suffix = type_def.arg_str
-
- def _data_size(self, sample: Collection) -> int:
- if len(sample) == 0:
- return 0
- elem_size = 0
- is_dict = self.element_names and isinstance(self._first_value(list(sample)), dict)
- for ix, e_type in enumerate(self.element_types):
- if e_type.byte_size > 0:
- elem_size += e_type.byte_size
- elif is_dict:
- elem_size += e_type.data_size([x.get(self.element_names[ix], None) for x in sample])
- else:
- elem_size += e_type.data_size([x[ix] for x in sample])
- return elem_size
-
- def read_column_prefix(self, source: ByteSource):
- for e_type in self.element_types:
- e_type.read_column_prefix(source)
-
- def read_column_data(self, source: ByteSource, num_rows: int, ctx: QueryContext):
- columns = []
- e_names = self.element_names
- for e_type in self.element_types:
- column = e_type.read_column_data(source, num_rows, ctx)
- columns.append(column)
- if e_names and self.read_format(ctx) != 'tuple':
- dicts = [{} for _ in range(num_rows)]
- for ix, x in enumerate(dicts):
- for y, key in enumerate(e_names):
- x[key] = columns[y][ix]
- if self.read_format(ctx) == 'json':
- to_json = any_to_json
- return [to_json(x) for x in dicts]
- return dicts
- return tuple(zip(*columns))
-
- def write_column_prefix(self, dest: bytearray):
- for e_type in self.element_types:
- e_type.write_column_prefix(dest)
-
- def write_column_data(self, column: Sequence, dest: bytearray, ctx: InsertContext):
- if self.element_names and isinstance(self._first_value(column), dict):
- columns = self.convert_dict_insert(column)
- else:
- columns = list(zip(*column))
- for e_type, elem_column in zip(self.element_types, columns):
- e_type.write_column_data(elem_column, dest, ctx)
-
- def convert_dict_insert(self, column: Sequence) -> Sequence:
- names = self.element_names
- col = [[] for _ in names]
- for x in column:
- for ix, name in enumerate(names):
- col[ix].append(x.get(name))
- return col
-
-
-class Map(ClickHouseType):
- _slots = 'key_type', 'value_type'
- python_type = dict
-
- def __init__(self, type_def: TypeDef):
- super().__init__(type_def)
- self.key_type = get_from_name(type_def.values[0])
- self.value_type = get_from_name(type_def.values[1])
- self._name_suffix = type_def.arg_str
-
- def _data_size(self, sample: Collection) -> int:
- total = 0
- if len(sample) == 0:
- return 0
- for x in sample:
- total += self.key_type.data_size(x.keys())
- total += self.value_type.data_size(x.values())
- return total // len(sample)
-
- def read_column_prefix(self, source: ByteSource):
- self.key_type.read_column_prefix(source)
- self.value_type.read_column_prefix(source)
-
- # pylint: disable=too-many-locals
- def read_column_data(self, source: ByteSource, num_rows: int, ctx: QueryContext):
- offsets = source.read_array('Q', num_rows)
- total_rows = offsets[-1]
- keys = self.key_type.read_column_data(source, total_rows, ctx)
- values = self.value_type.read_column_data(source, total_rows, ctx)
- all_pairs = tuple(zip(keys, values))
- column = []
- app = column.append
- last = 0
- for offset in offsets:
- app(dict(all_pairs[last: offset]))
- last = offset
- return column
-
- def write_column_prefix(self, dest: bytearray):
- self.key_type.write_column_prefix(dest)
- self.value_type.write_column_prefix(dest)
-
- def write_column_data(self, column: Sequence, dest: bytearray, ctx: InsertContext):
- offsets = array.array('Q')
- keys = []
- values = []
- total = 0
- for v in column:
- total += len(v)
- offsets.append(total)
- keys.extend(v.keys())
- values.extend(v.values())
- if must_swap:
- offsets.byteswap()
- dest += offsets.tobytes()
- self.key_type.write_column_data(keys, dest, ctx)
- self.value_type.write_column_data(values, dest, ctx)
-
-
-class Nested(ClickHouseType):
- __slots__ = 'tuple_array', 'element_names', 'element_types'
- python_type = Sequence[dict]
-
- def __init__(self, type_def):
- super().__init__(type_def)
- self.element_names = type_def.keys
- self.tuple_array = get_from_name(f"Array(Tuple({','.join(type_def.values)}))")
- self.element_types = self.tuple_array.element_type.element_types
- cols = [f'{x[0]} {x[1].name}' for x in zip(type_def.keys, self.element_types)]
- self._name_suffix = f"({', '.join(cols)})"
-
- def _data_size(self, sample: Collection) -> int:
- keys = self.element_names
- array_sample = [[tuple(sub_row[key] for key in keys) for sub_row in row] for row in sample]
- return self.tuple_array.data_size(array_sample)
-
- def read_column_prefix(self, source: ByteSource):
- self.tuple_array.read_column_prefix(source)
-
- def read_column_data(self, source: ByteSource, num_rows: int, ctx: QueryContext):
- keys = self.element_names
- data = self.tuple_array.read_column_data(source, num_rows, ctx)
- return [[dict(zip(keys, x)) for x in row] for row in data]
-
- def write_column_prefix(self, dest: bytearray):
- self.tuple_array.write_column_prefix(dest)
-
- def write_column_data(self, column: Sequence, dest: bytearray, ctx: InsertContext):
- keys = self.element_names
- data = [[tuple(sub_row[key] for key in keys) for sub_row in row] for row in column]
- self.tuple_array.write_column_data(data, dest, ctx)
-
-
-class JSON(ClickHouseType):
- python_type = dict
- # Native is a Python type (primitive, dict, array), string is an actual JSON string
- valid_formats = 'string', 'native'
-
- def write_column_prefix(self, dest: bytearray):
- dest.append(0x01)
-
- def _data_size(self, sample: Collection) -> int:
- if len(sample) == 0:
- return 0
- total = 0
- for x in sample:
- if isinstance(x, str):
- total += len(x)
- elif x:
- total += len(any_to_json(x))
- return total // len(sample) + 1
-
- # pylint: disable=duplicate-code
- def write_column_data(self, column: Sequence, dest: bytearray, ctx: InsertContext):
- app = dest.append
- first = self._first_value(column)
- if isinstance(first, str) or self.write_format(ctx) == 'string':
- for x in column:
- v = x.encode()
- sz = len(v)
- while True:
- b = sz & 0x7f
- sz >>= 7
- if sz == 0:
- app(b)
- break
- app(0x80 | b)
- dest += v
- else:
- to_json = any_to_json
- for x in column:
- v = to_json(x)
- sz = len(v)
- while True:
- b = sz & 0x7f
- sz >>= 7
- if sz == 0:
- app(b)
- break
- app(0x80 | b)
- dest += v
-
-
-class Object(JSON):
- python_type = dict
-
- def __init__(self, type_def):
- if type_def.values[0].lower() != "'json'":
- raise NotImplementedError('Only json Object type is currently supported')
- super().__init__(type_def)
- self._name_suffix = type_def.arg_str
diff --git a/spaces/cihyFjudo/fairness-paper-search/How to Study Constitution Of India Book By J.n. Pandey Pdf Tips and Tricks for Effective Learning.md b/spaces/cihyFjudo/fairness-paper-search/How to Study Constitution Of India Book By J.n. Pandey Pdf Tips and Tricks for Effective Learning.md
deleted file mode 100644
index 2f3d077cd1252041c955400a11128090d0353674..0000000000000000000000000000000000000000
--- a/spaces/cihyFjudo/fairness-paper-search/How to Study Constitution Of India Book By J.n. Pandey Pdf Tips and Tricks for Effective Learning.md
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
- aaccfb2cb3
-
-
-
diff --git a/spaces/clip-italian/clip-italian-demo/text2image.py b/spaces/clip-italian/clip-italian-demo/text2image.py
deleted file mode 100644
index 6e663d30c84f776ae92efb1e8a9ba6595df1300e..0000000000000000000000000000000000000000
--- a/spaces/clip-italian/clip-italian-demo/text2image.py
+++ /dev/null
@@ -1,211 +0,0 @@
-import io
-import os
-import requests
-import zipfile
-import natsort
-import gc
-from PIL import Image
-from PIL import UnidentifiedImageError
-
-os.environ["TOKENIZERS_PARALLELISM"] = "false"
-from stqdm import stqdm
-import streamlit as st
-from jax import numpy as jnp
-import transformers
-from transformers import AutoTokenizer
-from torchvision.transforms import Compose, CenterCrop, Normalize, Resize, ToTensor
-from torchvision.transforms.functional import InterpolationMode
-from modeling_hybrid_clip import FlaxHybridCLIP
-
-import utils
-
-
-@st.cache(hash_funcs={FlaxHybridCLIP: lambda _: None})
-def get_model():
- return FlaxHybridCLIP.from_pretrained("clip-italian/clip-italian")
-
-
-@st.cache(
- hash_funcs={
- transformers.models.bert.tokenization_bert_fast.BertTokenizerFast: lambda _: None
- }
-)
-def get_tokenizer():
- return AutoTokenizer.from_pretrained(
- "dbmdz/bert-base-italian-xxl-uncased", cache_dir="./", use_fast=True
- )
-
-
-@st.cache(suppress_st_warning=True)
-def download_images():
- # from sentence_transformers import SentenceTransformer, util
- img_folder = "photos/"
- if not os.path.exists(img_folder) or len(os.listdir(img_folder)) == 0:
- os.makedirs(img_folder, exist_ok=True)
-
- photo_filename = "unsplash-25k-photos.zip"
- if not os.path.exists(photo_filename): # Download dataset if does not exist
- print(f"Downloading {photo_filename}...")
- response = requests.get(
- f"http://sbert.net/datasets/{photo_filename}", stream=True
- )
- total_size_in_bytes = int(response.headers.get("content-length", 0))
- block_size = 1024 # 1 Kb
- progress_bar = stqdm(
- total=total_size_in_bytes
- ) # , unit='iB', unit_scale=True
- content = io.BytesIO()
- for data in response.iter_content(block_size):
- progress_bar.update(len(data))
- content.write(data)
- progress_bar.close()
- z = zipfile.ZipFile(content)
- # content.close()
- print("Extracting the dataset...")
- z.extractall(path=img_folder)
- print("Done.")
-
-
-@st.cache()
-def get_image_features(dataset_name):
- if dataset_name == "Unsplash":
- return jnp.load("static/features/features.npy")
- else:
- return jnp.load("static/features/CC_embeddings.npy")
-
-
-@st.cache()
-def load_urls(dataset_name):
- if dataset_name == "CC":
- with open("static/CC_urls.txt") as fp:
- urls = [l.strip() for l in fp.readlines()]
- return urls
- else:
- ValueError(f"{dataset_name} not supported here")
-
-
-def get_image_transform(image_size):
- return Compose(
- [
- Resize([image_size], interpolation=InterpolationMode.BICUBIC),
- CenterCrop(image_size),
- ToTensor(),
- Normalize(
- (0.48145466, 0.4578275, 0.40821073),
- (0.26862954, 0.26130258, 0.27577711),
- ),
- ]
- )
-
-
-headers = {
- #'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
- "User-Agent": "Googlebot-Image/1.0", # Pretend to be googlebot
- "X-Forwarded-For": "64.18.15.200",
-}
-
-
-def app():
-
- st.title("From Text to Image")
- st.markdown(
- """
-
- ### 👋 Ciao!
-
- Here you can search for ~150.000 images in the Conceptual Captions dataset (CC) or in the Unsplash 25.000 Photos dataset.
- Even though we did not train on any of these images you will see most queries make sense. When you see errors, there might be two possibilities:
- the model is answering in a wrong way or the image you are looking for is not in the dataset and the model is giving you the best answer it can get.
-
-
-
- 🤌 Italian mode on! 🤌
-
- You can choose from one of the following examples:
- """
- )
-
- suggestions = [
- "Un gatto",
- "Due gatti",
- "Un fiore giallo",
- "Un fiore blu",
- "Una coppia in montagna",
- "Una coppia al tramonto",
- ]
- sugg_idx = -1
-
- col1, col2, col3, col4, col5, col6 = st.columns(6)
- with col1:
- if st.button(suggestions[0]):
- sugg_idx = 0
- with col2:
- if st.button(suggestions[1]):
- sugg_idx = 1
- with col3:
- if st.button(suggestions[2]):
- sugg_idx = 2
- with col4:
- if st.button(suggestions[3]):
- sugg_idx = 3
- with col5:
- if st.button(suggestions[4]):
- sugg_idx = 4
- with col6:
- if st.button(suggestions[5]):
- sugg_idx = 5
-
- col1, col2 = st.columns([0.75, 0.25])
- with col1:
- query = st.text_input("... or insert an Italian query text")
- with col2:
- dataset_name = st.selectbox("IR dataset", ["CC", "Unsplash"])
-
- query = suggestions[sugg_idx] if sugg_idx > -1 else query if query else ""
-
- if query:
- with st.spinner("Computing..."):
-
- if dataset_name == "Unsplash":
- download_images()
-
- image_features = get_image_features(dataset_name)
- model = get_model()
- tokenizer = get_tokenizer()
-
- if dataset_name == "Unsplash":
- image_size = model.config.vision_config.image_size
- dataset = utils.CustomDataSet(
- "photos/", transform=get_image_transform(image_size)
- )
- elif dataset_name == "CC":
- dataset = load_urls(dataset_name)
- else:
- raise ValueError()
-
- N = 3
-
- image_paths = utils.find_image(
- query, model, dataset, tokenizer, image_features, N, dataset_name
- )
-
- for i, image_url in enumerate(image_paths):
- try:
- if dataset_name == "Unsplash":
- st.image(image_url)
- elif dataset_name == "CC":
- image_raw = requests.get(
- image_url, stream=True, allow_redirects=True, headers=headers
- ).raw
- image = Image.open(image_raw).convert("RGB")
- st.image(image, use_column_width=True)
- break
- except (UnidentifiedImageError) as e:
- if i == N - 1:
- st.text(
- f"Tried to show {N} different image URLS but none of them were reachabele.\nMaybe try a different query?"
- )
-
- gc.collect()
-
- sugg_idx = -1
diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/alac_data.c b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/alac_data.c
deleted file mode 100644
index d8ed53f444208d5ab7b36c8bdb65341565e951f3..0000000000000000000000000000000000000000
--- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/alac_data.c
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * ALAC encoder and decoder common data
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#include "libavutil/channel_layout.h"
-#include "alac_data.h"
-
-const uint8_t ff_alac_channel_layout_offsets[ALAC_MAX_CHANNELS][ALAC_MAX_CHANNELS] = {
- { 0 },
- { 0, 1 },
- { 2, 0, 1 },
- { 2, 0, 1, 3 },
- { 2, 0, 1, 3, 4 },
- { 2, 0, 1, 4, 5, 3 },
- { 2, 0, 1, 4, 5, 6, 3 },
- { 2, 6, 7, 0, 1, 4, 5, 3 }
-};
-
-const AVChannelLayout ff_alac_ch_layouts[ALAC_MAX_CHANNELS + 1] = {
- AV_CHANNEL_LAYOUT_MONO,
- AV_CHANNEL_LAYOUT_STEREO,
- AV_CHANNEL_LAYOUT_SURROUND,
- AV_CHANNEL_LAYOUT_4POINT0,
- AV_CHANNEL_LAYOUT_5POINT0_BACK,
- AV_CHANNEL_LAYOUT_5POINT1_BACK,
- AV_CHANNEL_LAYOUT_6POINT1_BACK,
- AV_CHANNEL_LAYOUT_7POINT1_WIDE_BACK,
- { 0 }
-};
-
-const enum AlacRawDataBlockType ff_alac_channel_elements[ALAC_MAX_CHANNELS][5] = {
- { TYPE_SCE, },
- { TYPE_CPE, },
- { TYPE_SCE, TYPE_CPE, },
- { TYPE_SCE, TYPE_CPE, TYPE_SCE },
- { TYPE_SCE, TYPE_CPE, TYPE_CPE, },
- { TYPE_SCE, TYPE_CPE, TYPE_CPE, TYPE_SCE, },
- { TYPE_SCE, TYPE_CPE, TYPE_CPE, TYPE_SCE, TYPE_SCE, },
- { TYPE_SCE, TYPE_CPE, TYPE_CPE, TYPE_CPE, TYPE_SCE, },
-};
diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/canopus.c b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/canopus.c
deleted file mode 100644
index ea6cc647d3791df5fdba67f1da6f0dc488e86b96..0000000000000000000000000000000000000000
--- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/canopus.c
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Canopus common routines
- * Copyright (c) 2015 Vittorio Giovara
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#include
-
-#include "libavutil/rational.h"
-
-#include "avcodec.h"
-#include "bytestream.h"
-#include "canopus.h"
-
-int ff_canopus_parse_info_tag(AVCodecContext *avctx,
- const uint8_t *src, size_t size)
-{
- GetByteContext gbc;
- int par_x, par_y, field_order;
-
- bytestream2_init(&gbc, src, size);
-
- /* Parse aspect ratio. */
- bytestream2_skip(&gbc, 8); // unknown, 16 bits 1
- par_x = bytestream2_get_le32(&gbc);
- par_y = bytestream2_get_le32(&gbc);
- if (par_x && par_y)
- av_reduce(&avctx->sample_aspect_ratio.num,
- &avctx->sample_aspect_ratio.den,
- par_x, par_y, 255);
-
- /* Short INFO tag (used in CLLC) has only AR data. */
- if (size == 0x18)
- return 0;
-
- bytestream2_skip(&gbc, 16); // unknown RDRT tag
-
- /* Parse FIEL tag. */
- bytestream2_skip(&gbc, 8); // 'FIEL' and 4 bytes 0
- field_order = bytestream2_get_le32(&gbc);
- switch (field_order) {
- case 0: avctx->field_order = AV_FIELD_TT; break;
- case 1: avctx->field_order = AV_FIELD_BB; break;
- case 2: avctx->field_order = AV_FIELD_PROGRESSIVE; break;
- }
-
- return 0;
-}
diff --git a/spaces/congsaPfin/Manga-OCR/logs/Crafting and Building A Free Alternative to Minecraft APK for Android.md b/spaces/congsaPfin/Manga-OCR/logs/Crafting and Building A Free Alternative to Minecraft APK for Android.md
deleted file mode 100644
index 3ca8cf27f8bd89fceb76bf294d8029c190ebce74..0000000000000000000000000000000000000000
--- a/spaces/congsaPfin/Manga-OCR/logs/Crafting and Building A Free Alternative to Minecraft APK for Android.md
+++ /dev/null
@@ -1,140 +0,0 @@
-
-
Minecraft APK Download Crafting and Building: A Guide for Android Users
-
If you are a fan of sandbox games, you have probably heard of Minecraft, one of the most popular and successful games of all time. But did you know that there is a free alternative to Minecraft for Android devices? It's called Crafting and Building, and it's a game that lets you create your own world, explore, build, and survive in it. In this article, we will tell you everything you need to know about Minecraft APK download crafting and building, including what it is, how to download and install it, how to play it, and how it compares to Minecraft.
Minecraft is a sandbox game that was created by Mojang Studios in 2009. It is available for various platforms, including Windows, Mac, Linux, iOS, Android, Xbox, PlayStation, Nintendo Switch, and more. It has sold over 200 million copies worldwide and has over 126 million monthly active users as of 2020.
-
A sandbox game with infinite possibilities
-
Minecraft is a game that gives you complete freedom to create your own world and do whatever you want in it. You can mine resources, craft items, build structures, fight enemies, explore biomes, tame animals, farm crops, brew potions, enchant weapons, trade with villagers, discover secrets, and more. The game has two main modes: creative mode and survival mode. In creative mode, you have unlimited resources and can build anything you can imagine. In survival mode, you have to gather resources, craft tools and weapons, find food and shelter, and defend yourself from hostile mobs.
-
A cross-platform game with multiplayer support
-
Minecraft is a game that can be played on different devices and platforms. You can play it on your PC, laptop, tablet, smartphone, console, or even on a virtual reality headset. You can also play it with your friends online or on a local network. You can join servers that host different types of games, such as mini-games, adventure maps, role-playing games, survival games, etc. You can also create your own server or realm and invite your friends to join you.
-
What is Crafting and Building?
-
Crafting and Building is a free alternative to Minecraft for Android devices. It was developed by Mmarcel in 2017. It has over 10 million downloads on Google Play Store as of 2021.
-
A free alternative to Minecraft for Android devices
-
Crafting and Building is a game that lets you play Minecraft-like gameplay on your Android device without paying anything. You don't need to buy the game or have a premium account to play it. You just need to download the APK file from the official website or a trusted source and install it on your device.
-
A game with similar features and gameplay to Minecraft
-
Crafting and Building is a game that has many features and gameplay elements that are similar to Minecraft. You can choose between creative mode and survival mode. You can explore different worlds with different biomes. You can mine resources, craft items, build structures, fight enemies, etc. You can also customize your character with different skins and clothes.
-
How to Download and Install Crafting and Building on Android?
-
If you If you want to download and install Crafting and Building on your Android device, you can follow these simple steps:
Step 1: Go to the official website or a trusted source
-
The first thing you need to do is to find a reliable source to download the APK file of Crafting and Building. You can go to the official website of the game, which is craftingandbuilding.net, or you can search for other websites that offer the APK file. Make sure that the website is safe and secure, and that the APK file is not corrupted or infected with malware.
-
minecraft apk download crafting and building free
-minecraft apk download crafting and building mod
-minecraft apk download crafting and building online
-minecraft apk download crafting and building offline
-minecraft apk download crafting and building latest version
-minecraft apk download crafting and building for android
-minecraft apk download crafting and building for pc
-minecraft apk download crafting and building for ios
-minecraft apk download crafting and building for windows 10
-minecraft apk download crafting and building for mac
-minecraft apk download crafting and building tutorial
-minecraft apk download crafting and building guide
-minecraft apk download crafting and building tips
-minecraft apk download crafting and building tricks
-minecraft apk download crafting and building cheats
-minecraft apk download crafting and building hacks
-minecraft apk download crafting and building skins
-minecraft apk download crafting and building texture packs
-minecraft apk download crafting and building maps
-minecraft apk download crafting and building servers
-minecraft apk download crafting and building realms
-minecraft apk download crafting and building addons
-minecraft apk download crafting and building mods
-minecraft apk download crafting and building shaders
-minecraft apk download crafting and building seeds
-minecraft apk download crafting and building creative mode
-minecraft apk download crafting and building survival mode
-minecraft apk download crafting and building adventure mode
-minecraft apk download crafting and building hardcore mode
-minecraft apk download crafting and building multiplayer mode
-minecraft apk download crafting and building split screen mode
-minecraft apk download crafting and building cross platform play
-minecraft apk download crafting and building xbox one edition
-minecraft apk download crafting and building nintendo switch edition
-minecraft apk download crafting and building playstation 4 edition
-minecraft apk download crafting and building fire devices edition
-minecraft apk download crafting and building oculus edition
-minecraft apk download crafting and building windows mixed reality edition
-minecraft apk download crafting and building java edition
-minecraft apk download crafting and building bedrock edition
-minecraft apk download crafting and building education edition
-minecraft apk download crafting and building dungeons edition
-minecraft apk download crafting and building earth edition
-minecraft apk download crafting and building story mode
-minecraft apk download crafting and building classic edition
-minecraft apk download crafting and building pocket edition
-minecraft apk download crafting and building master edition
-minecraft apk download crafting and building explorer's pack
-minecraft apk download crafting and building starter pack
-
Step 2: Download the APK file and allow unknown sources
-
Once you have found the source, you can download the APK file to your device. The file size is about 60 MB, so it should not take too long to download. After downloading the file, you need to allow your device to install apps from unknown sources. To do this, go to your device settings, then security, then enable the option to allow unknown sources. This will let you install apps that are not from the Google Play Store.
-
Step 3: Install the APK file and launch the game
-
After allowing unknown sources, you can install the APK file by tapping on it and following the instructions. The installation process should be quick and easy. Once the installation is done, you can launch the game by tapping on its icon on your home screen or app drawer. You are now ready to play Crafting and Building on your Android device.
-
How to Play Crafting and Building on Android?
-
Playing Crafting and Building on Android is very similar to playing Minecraft on any platform. You can choose between two game modes: creative mode and survival mode. You can also choose between different worlds with different themes and biomes. Here are some tips on how to play Crafting and Building on Android:
-
Choose a game mode and a world
-
When you launch the game, you will see a menu with different options. You can tap on "Play" to start a new game or continue an existing one. You can also tap on "Multiplayer" to join or create a server with other players online. You can also tap on "Options" to change the game settings, such as sound, graphics, controls, etc.
-
If you choose to play a new game, you will have to choose a game mode: creative mode or survival mode. In creative mode, you have unlimited resources and can build anything you want without any restrictions. In survival mode, you have to gather resources, craft tools and weapons, find food and shelter, and survive against enemies and dangers.
-
After choosing a game mode, you will have to choose a world. You can either create a new world or load an existing one. You can also customize your world by choosing its name, seed, size, theme, biome, etc. You can choose from different themes such as city, village, castle, island, etc., and different biomes such as forest, desert, snow, etc.
-
Explore, build, and survive in the world
-
Once you have chosen a world, you will spawn in it with your character. You can move around using the virtual joystick on the left side of the screen. You can look around using your finger on the right side of the screen. You can also use buttons on the right side of the screen to jump, fly, sneak, sprint, etc.
-
You can interact with the world using your finger on the center of the screen. You can tap on blocks to break them or place them. You can also tap on items or entities to use them or interact with them. You can access your inventory by tapping on the backpack icon on the top right corner of the screen. You can drag items from your inventory to your hotbar or vice versa.
-
In creative mode, you can build anything you want using any blocks or items you have in your inventory. You can also use commands by tapping on the chat icon on the top left corner of the screen. You can use commands to change the time of day, weather, game mode, etc.
-
In survival mode, you have to gather resources by mining blocks or killing mobs. You have to craft tools and weapons by using a crafting table or your inventory. You have to find food by hunting animals or farming crops. You have to build shelter by placing blocks or using items such as beds or doors. You have to survive against enemies such as zombies, skeletons, spiders, etc., by fighting them or avoiding them.
-
Interact with other players and customize your character
-
Crafting and Building is a game that supports multiplayer mode. You can play with other players online by joining or creating a server. You can also play with your friends on a local network by using the same Wi-Fi connection. You can chat with other players by using the chat icon on the top left corner of the screen. You can also send emojis, stickers, or voice messages to express yourself. Crafting and Building is a game that lets you customize your character with different skins and clothes. You can access the character menu by tapping on the hanger icon on the top right corner of the screen. You can choose from different categories such as animals, superheroes, celebrities, etc. You can also create your own skin by using the editor or importing an image. You can also change your clothes by using the wardrobe or buying new ones from the shop.
Comparison Table of Minecraft and Crafting and Building
-
Here is a table that compares some of the features and aspects of Minecraft and Crafting and Building:
Over 60 different biomes, such as forest, desert, ocean, jungle, etc.
-
Over 20 different themes, such as city, village, castle, island, etc.
-
-
-
Blocks and Items
-
Over 700 different blocks and items, such as wood, stone, iron, diamond, etc.
-
Over 300 different blocks and items, such as wood, stone, iron, diamond, etc.
-
-
-
Mobs and Entities
-
Over 100 different mobs and entities, such as animals, villagers, zombies, skeletons, etc.
-
Over 50 different mobs and entities, such as animals, villagers, zombies, skeletons, etc.
-
-
www.facebook.com/Crafting-and-Building-155876864963570/. 401be4b1e0
-
-
\ No newline at end of file
diff --git a/spaces/congsaPfin/Manga-OCR/logs/Download ELD Rider and Enjoy a Smooth and Easy Driving Experience.md b/spaces/congsaPfin/Manga-OCR/logs/Download ELD Rider and Enjoy a Smooth and Easy Driving Experience.md
deleted file mode 100644
index e127566476befdcd88ea33e423d37cb1516d6824..0000000000000000000000000000000000000000
--- a/spaces/congsaPfin/Manga-OCR/logs/Download ELD Rider and Enjoy a Smooth and Easy Driving Experience.md
+++ /dev/null
@@ -1,81 +0,0 @@
-
-
How to Download ELD Rider: A Step-by-Step Guide
-
If you are a commercial driver who needs to comply with the ELD mandate, you might be looking for a reliable and easy-to-use app that can help you manage your hours of service and keep accurate records of your driving activity. In this article, we will introduce you to ELD Rider, an app that does all that and more. We will also show you how to download, install, and use ELD Rider on your Android or iOS device.
-
What is ELD Rider and what does it do?
-
ELD Rider is an app that works as an electronic logging device (ELD) for drivers who are required to keep records of duty status (RODS) according to the ELD rule. An ELD is a device that connects to your vehicle's engine and automatically records driving time, location, miles driven, engine hours, and other data. This data is then transferred to your mobile device via Bluetooth, where you can view and edit your logs using the ELD Rider app.
ELD Rider helps you stay compliant with the ELD mandate, which is a federal law that requires most commercial drivers to use an approved ELD instead of paper logbooks or other electronic methods. The ELD mandate aims to improve road safety by preventing driver fatigue and enforcing hours-of-service regulations.
-
Who needs to use ELD Rider and why?
-
The ELD mandate applies to most drivers who operate commercial motor vehicles (CMVs) in interstate commerce and are required to keep RODS. This includes drivers of trucks, buses, vans, and other vehicles that meet certain criteria based on weight, passenger capacity, or cargo type. You can check if you are affected by the ELD mandate by visiting the FMCSA website.
-
If you need to use an ELD, you should consider using ELD Rider because it offers many benefits, such as:
-
-
Ease of use: Drivers love ELD Rider because it has a simple and intuitive interface, large buttons, helpful alerts, and easy data transfer mechanisms. You can access most functions with just one or two taps.
-
Reliability: ELD Rider is built on an industry-leading platform that has over 99% system uptime. It also has safeguards to prevent data tampering or loss. You can trust that your logs are accurate and secure.
-
Flexibility: ELD Rider supports multiple data connection options, such as Wi-Fi, cellular, or satellite. It also integrates with other fleet management software and features, such as DVIRs, routing, fuel tracking, and more.
-
-
How to download ELD Rider
-
To use ELD Rider, you need a compatible mobile device that runs on Android or iOS operating system. You also need a vehicle tracking unit (VTU) that connects to your vehicle's diagnostic port and communicates with your mobile device via Bluetooth. You can purchase a VTU from ELD Rider website or use an existing one if it is compatible.
-
To download
Check if your mobile device and VTU are paired and connected via Bluetooth.
-
Check if your mobile device has a stable internet connection via Wi-Fi, cellular, or satellite.
-
Check if your VTU is connected to your vehicle's diagnostic port and receiving power.
-
Check if your app is updated to the latest version.
-
Restart your app or your mobile device.
-
-
If none of these tips work, you can contact our support team for further assistance. You can also check our FAQ page or our user manual for more information.
-
How can I contact ELD Rider support?
-
If you have any questions, feedback, or issues with ELD Rider, you can contact our support team by email, phone, or chat. Our support team is available 24/7 and ready to help you. You can contact us by:
Chat: Visit our website and click on the chat icon at the bottom right corner of the screen.
-
-
Where can I find more information about ELD Rider?
-
If you want to learn more about ELD Rider, you can visit our website, where you can find more features, benefits, testimonials, videos, blogs, and other resources. You can also follow us on social media platforms, such as Facebook, Twitter, Instagram, and YouTube, where we share news, updates, tips, and promotions. You can also subscribe to our newsletter to get the latest information about ELD Rider delivered to your inbox.
-
How to download eld rider app for android
-Download eld rider app for ios and mac
-Eld rider app review and features
-Eld rider app vs other eld solutions
-Benefits of using eld rider app for hos and eld compliance
-Eld rider app pricing and plans
-How to install and use eld rider app
-Eld rider app customer support and feedback
-Eld rider app updates and news
-Eld rider app for ipad and ipod touch
-Eld rider app for electronic logbook and inspection reports
-Eld rider app for real-time routing and tracking
-Eld rider app for fmcsa registration and logbook
-Eld rider app for gas, mileage, cargo, and vehicle information
-Eld rider app for eliminating paper dvirs
-Eld rider app for drivers and fleets
-Eld rider app for enhanced performance and design
-Eld rider app for data privacy and security
-Eld rider app for easy to use interface and alerts
-Eld rider app for split screen on ipad
-How to download eld rider apk for android
-Download eld rider apk from softonic
-Eld rider apk review and features
-Eld rider apk vs other eld apps
-Benefits of using eld rider apk for hos and eld compliance
-Eld rider apk pricing and plans
-How to install and use eld rider apk
-Eld rider apk customer support and feedback
-Eld rider apk updates and news
-Eld rider apk for electronic logbook and inspection reports
-Eld rider apk for real-time routing and tracking
-Eld rider apk for fmcsa registration and logbook
-Eld rider apk for gas, mileage, cargo, and vehicle information
-Eld rider apk for eliminating paper dvirs
-Eld rider apk for drivers and fleets
-Eld rider apk for enhanced performance and design
-Eld rider apk for data privacy and security
-Eld rider apk for easy to use interface and alerts
-How to download eld rider from google play store
-Download eld rider from app store
-Eld rider on google play store review and features
-Eld rider on app store review and features
-Benefits of using eld rider from google play store or app store
-How to install and use eld rider from google play store or app store
-Eld rider on google play store or app store customer support and feedback
-Eld rider on google play store or app store updates and news
197e85843d
-
-
\ No newline at end of file
diff --git a/spaces/congsaPfin/Manga-OCR/logs/Download and Stream Hindi Video Songs of 2016 in HD 1080p.md b/spaces/congsaPfin/Manga-OCR/logs/Download and Stream Hindi Video Songs of 2016 in HD 1080p.md
deleted file mode 100644
index 3e9ce7331e250ab912d65235b6fd3e66ebfa2cec..0000000000000000000000000000000000000000
--- a/spaces/congsaPfin/Manga-OCR/logs/Download and Stream Hindi Video Songs of 2016 in HD 1080p.md
+++ /dev/null
@@ -1,150 +0,0 @@
-
-
How to Download 1080p Hindi Video Songs from 2016
-
If you are a fan of Bollywood music, you might have heard of 1080p Hindi video songs. These are high-definition videos that feature your favorite Hindi songs with stunning visuals and sound quality. They are perfect for watching on your big screen TV, laptop, or smartphone.
-
Downloading 1080p Hindi video songs can be a great way to enjoy them offline, without buffering or ads. You can also create your own playlists, share them with your friends, or burn them to DVDs. However, finding and downloading 1080p Hindi video songs can be tricky, especially if you are looking for songs from a specific year like 2016.
In this article, we will show you how to download 1080p Hindi video songs from 2016 from various sources. We will also give you some tips and tricks to make your downloading experience easier and faster. Let's get started!
-
Best Sources for 1080p Hindi Video Songs from 2016
-
There are many websites that offer 1080p Hindi video songs from 2016, but not all of them are reliable, safe, or legal. Some may have low-quality videos, broken links, malware, or copyright issues. To avoid these problems, we recommend using these three sources:
-
YouTube
-
YouTube is one of the most popular and widely used platforms for watching and downloading videos online. You can find thousands of 1080p Hindi video songs from 2016 on YouTube, from official channels, fan-made videos, playlists, compilations, and more.
-
To search for 1080p Hindi video songs on YouTube, you can use the following steps:
-
-
Go to [YouTube](^2^) and type in your keywords in the search box. For example, you can type "new hindi songs 2016" or "best bollywood songs 2016".
-
Click on the "Filter" button below the search box and select "Video quality" > "HD". This will show you only the videos that have high-definition quality.
-
Browse through the results and look for the videos that have "1080p" in their titles or descriptions. You can also check the quality by clicking on the "Settings" icon at the bottom right corner of the video player and selecting "Quality" > "1080p".
-
Once you find the video you want, click on it to watch it.
-
-
To download 1080p Hindi video songs from YouTube, you will need a video downloader software that can save YouTube videos to your device. There are many free and paid options available online, but some of the most popular ones are [4K Video Downloader], [WinX YouTube Downloader], and [Freemake Video Downloader]. To use these software, you can follow these general steps:
-
-
Download and install the video downloader software of your choice from its official website.
-
Copy the URL of the YouTube video you want to download and paste it into the software.
-
Select the output format and quality you want. For 1080p Hindi video songs, you should choose MP4 as the format and 1080p as the quality.
-
Click on the "Download" button and wait for the software to finish downloading the video.
-
Find the downloaded video in your device's folder and enjoy it offline.
-
-
Internet Archive
-
Internet Archive is a non-profit digital library that archives and preserves various types of media, including web pages, books, audio, video, and software. You can find many 1080p Hindi video songs from 2016 on Internet Archive, uploaded by users or organizations.
-
To browse and download 1080p Hindi video songs from Internet Archive, you can use the following steps:
-
-
Go to [Internet Archive] and click on the "Video" tab at the top of the page.
-
Type in your keywords in the search box and press enter. For example, you can type "hindi songs 2016" or "bollywood songs 2016".
-
Use the filters and categories on the left side of the page to narrow down your results. For example, you can select "Movies" as the media type, "Hindi" as the language, and "2016" as the year.
-
Look for the videos that have "1080p" in their titles or descriptions. You can also check the quality by clicking on the "Show All" button below the video player and selecting "Original" as the file format.
-
Once you find the video you want, click on it to watch it.
-
To download it, click on the "Download Options" button on the right side of the page and select "MP4" as the file format. Then, right-click on the download link and choose "Save link as" or "Save target as".
-
Choose a location on your device to save the video and wait for it to finish downloading.
-
-
Other Websites
-
Besides YouTube and Internet Archive, there are other websites that offer 1080p Hindi video songs from 2016. However, these websites may not be as reliable, safe, or legal as the previous two sources. Therefore, you should be careful when using them and follow these tips:
-
1080p hindi video songs download 2016 free
-1080p hindi video songs download 2016 hd
-1080p hindi video songs download 2016 mp4
-1080p hindi video songs download 2016 pagalworld
-1080p hindi video songs download 2016 youtube
-1080p hindi video songs download 2016 zip
-best 1080p hindi video songs download 2016
-bollywood 1080p hindi video songs download 2016
-latest 1080p hindi video songs download 2016
-new 1080p hindi video songs download 2016
-old 1080p hindi video songs download 2016
-romantic 1080p hindi video songs download 2016
-sad 1080p hindi video songs download 2016
-top 10 1080p hindi video songs download 2016
-top 20 1080p hindi video songs download 2016
-top 50 1080p hindi video songs download 2016
-a to z 1080p hindi video songs download 2016
-aashiqui 2 1080p hindi video songs download 2016
-ae dil hai mushkil 1080p hindi video songs download 2016
-airlift 1080p hindi video songs download 2016
-baaghi 1080p hindi video songs download 2016
-bajirao mastani 1080p hindi video songs download 2016
-dangal 1080p hindi video songs download 2016
-dhoni the untold story 1080p hindi video songs download 2016
-dilwale 1080p hindi video songs download 2016
-fan 1080p hindi video songs download 2016
-kapoor and sons 1080p hindi video songs download 2016
-karan arjun full movie hd in hindi free download in hd quality for pc in parts in one file in mobile in youtube in mp4 in avi in mkv in bluray in dvdrip in hdrip in webrip in webdl in hdtv in bdrip in brrip in camrip in hdcam in hdts in hdtc in hdvdrip in hddvdrip in dvdscr in pdvdrip in pdvdscr in pre-dvdrip in pre-dvdscr in pre-dvdr5 in pre-dvdr9 in pre-dvdr10 in pre-dvdr11 in pre-dvdr12 in pre-dvdr13 in pre-dvdr14 in pre-dvdr15
-
-
Use a reputable search engine like [Google] or [Bing] to find these websites. You can use keywords like "1080p hindi video songs download 2016" or "full hd bollywood songs download 2016".
-
Check the reviews and ratings of these websites before visiting them. You can use tools like [Trustpilot] or [WOT] to see what other users have said about them.
-
Check the quality and safety of the downloads before downloading them. You can use tools like [VirusTotal] or [Online Video Converter] to scan the files for malware or convert them to different formats.
-
Avoid clicking on pop-ups, ads, or suspicious links that may redirect you to unwanted or harmful sites.
-
-
Tips and Tricks for Downloading 1080p Hindi Video Songs from 2016
-
Downloading 1080p Hindi video songs from 2016 can be fun and easy if you use the sources we have mentioned above. However, you may still encounter some issues or difficulties along the way. To overcome them, you can use these tips and tricks:
-
Use a VPN or Proxy
-
A VPN or proxy is a service that allows you to access websites or videos that may be blocked or restricted in your region or country. This can be useful if you want to download 1080p Hindi video songs from 2016 that are not available in your area. For example, some YouTube videos may be geo-restricted or censored by your government or ISP.
-
To use a VPN or proxy, you will need to sign up for a VPN or proxy provider that suits your needs and budget. There are many free and paid options available online, but some of the most popular ones are [NordVPN], [ExpressVPN], and [ProtonVPN] for VPNs, and [Hide.me], [HMA], and [KProxy] for proxies. To use these services, you can follow these general steps:
-
-
Download and install the VPN or proxy software or app from its official website or app store.
-
Launch the software or app and sign in with your account or create a new one if you don't have one.
-
Select a server or location that you want to connect to. For example, if you want to access a YouTube video that is only available in India, you can choose an Indian server or proxy.
-
Once you are connected, you can open your browser or video downloader software and access the website or video you want to download.
-
-
Use a Download Manager
-
A download manager is a software that can help you speed up and resume your downloads, especially if they are large or slow. This can be useful if you want to download 1080p Hindi video songs from 2016 that may take a long time or encounter interruptions. For example, some websites may have low bandwidth or unstable servers.
-
To use a download manager, you will need to download and install a download manager software that works with your browser or video downloader software. There are many free and paid options available online, but some of the most popular ones are [Internet Download Manager], [Free Download Manager], and [EagleGet]. To use these software, you can follow these general steps:
-
-
Download and install the download manager software from its official website.
-
Launch the software and configure its settings according to your preferences. For example, you can set the number of simultaneous downloads, the download speed limit, the download folder, etc.
-
Copy the URL of the website or video you want to download and paste it into the software. Alternatively, you can use the browser extension or plugin that comes with the software to automatically capture the download links from your browser.
-
Click on the "Start" or "Download" button and wait for the software to finish downloading the file.
-
Find the downloaded file in your device's folder and enjoy it offline.
-
-
Convert and Compress Your Downloads
-
Converting and compressing your downloads can help you save space and bandwidth on your device, especially if you have limited storage or data plan. This can be useful if you want to download 1080p Hindi video songs from 2016 that may take up a lot of space or consume a lot of data. For example, some 1080p videos may be over 100 MB in size.
-
To convert and compress your downloads, you will need to use a video converter and compressor software that can change the format and size of your files. There are many free and paid options available online, but some of the most popular ones are [HandBrake], [VLC Media Player], and [Any Video Converter]. To use these software, you can follow these general steps:
-
-
Download and install the video converter and compressor software from its official website.
-
Launch the software and add the file you want to convert and compress. You can drag and drop it into the software or use the "Add File" button.
-
Select the output format and quality you want. For 1080p Hindi video songs, you can choose MP4 as the format and lower the bitrate or resolution to reduce the size.
-
Click on the "Start" or "Convert" button and wait for the software to finish converting and compressing the file.
-
Find the converted and compressed file in your device's folder and enjoy it offline.
-
-
Conclusion
-
In this article, we have shown you how to download 1080p Hindi video songs from 2016 from various sources. We have also given you some tips and tricks to make your downloading experience easier and faster. We hope you have found this article helpful and informative.
-
If you want to learn more about 1080p Hindi video songs from 2016, you can check out these resources:
-
-
[Top 10 Bollywood Songs of 2016]
-
[Best Hindi Video Songs of 2016]
-
[How to Watch Bollywood Movies Online]
-
-
FAQs
-
Here are some frequently asked questions and their answers related to the topic of this article:
-
Q: What is the difference between 1080 p and 720p video quality?
-
A: 1080p and 720p are two common resolutions for video quality, measured by the number of pixels in the vertical dimension. 1080p has 1080 pixels, while 720p has 720 pixels. The more pixels, the higher the clarity and detail of the video. Therefore, 1080p is better than 720p in terms of video quality.
-
Q: How can I play 1080p Hindi video songs on my device?
-
A: To play 1080p Hindi video songs on your device, you will need a media player that can support the MP4 format and the 1080p resolution. Some of the most popular media players that can do this are [VLC Media Player], [KMPlayer], and [MX Player]. To use these media players, you can follow these general steps:
-
-
Download and install the media player of your choice from its official website or app store.
-
Launch the media player and open the file you want to play. You can drag and drop it into the media player or use the "Open File" button.
-
Adjust the settings and preferences of the media player according to your needs. For example, you can change the volume, brightness, subtitles, etc.
-
Enjoy watching your 1080p Hindi video song on your device.
-
-
Q: How can I share 1080p Hindi video songs with my friends?
-
A: To share 1080p Hindi video songs with your friends, you have several options. You can use a cloud storage service like [Google Drive], [Dropbox], or [OneDrive] to upload your files and share them with your friends via a link or an email. You can also use a file-sharing service like [WeTransfer], [Send Anywhere], or [Filemail] to send your files directly to your friends via a link or an email. Alternatively, you can use a social media platform like [Facebook], [Instagram], or [WhatsApp] to upload your files and share them with your friends via a post or a message.
-
Q: How can I edit 1080p Hindi video songs?
-
A: To edit 1080p Hindi video songs, you will need a video editor software that can handle the MP4 format and the 1080p resolution. There are many free and paid options available online, but some of the most popular ones are [Filmora], [Movavi], and [Adobe Premiere Pro]. To use these software, you can follow these general steps:
-
-
Download and install the video editor software of your choice from its official website.
-
Launch the software and import the file you want to edit. You can drag and drop it into the software or use the "Import" button.
-
Use the tools and features of the software to edit your file according to your preferences. For example, you can trim, crop, rotate, add effects, transitions, text, etc.
-
Export your edited file in the format and quality you want. For 1080p Hindi video songs, you should choose MP4 as the format and 1080p as the quality.
-
Find the edited file in your device's folder and enjoy it offline or share it online.
-
-
Q: How can I make my own 1080p Hindi video song?
-
A: To make your own 1080p Hindi video song, you will need a camera that can record in 1080p resolution, a microphone that can capture clear audio, a computer that can edit and produce high-quality videos, and a creative mind that can come up with an original idea and script. Here are some basic steps to make your own 1080p Hindi video song:
-
-
Choose a song that you want to make a video for. It can be an existing song or a song that you have composed yourself.
-
Write a script or storyboard for your video. It should include the scenes, locations, characters, dialogues, actions, etc. that you want to show in your video.
-
Gather the equipment and materials that you need for your video. This may include a camera, a microphone, a tripod, a lighting kit, props, costumes, etc.
-
Find a suitable location and time for your video. It should match the mood and theme of your song and script.
-
Record your video according to your script or storyboard. You may need to do multiple takes or angles to get the best shots.
-
Transfer your video files to your computer and import them into your video editor software.
Edit your video according to your preferences. You can use the tools and features of the software to trim, crop, rotate, add effects, transitions, text, etc.
-
Add your song to your video as the background music. You can use the tools and features of the software to sync, adjust, or mix the audio with the video.
-
Export your video in the format and quality you want. For 1080p Hindi video songs, you should choose MP4 as the format and 1080p as the quality.
-
Find the video in your device's folder and enjoy it offline or share it online.
- 197e85843d
-
-
\ No newline at end of file
diff --git a/spaces/congsaPfin/Manga-OCR/logs/Free Online Crossword Puzzles No Download - From Classic to Themed to Cryptic Crossword Variety.md b/spaces/congsaPfin/Manga-OCR/logs/Free Online Crossword Puzzles No Download - From Classic to Themed to Cryptic Crossword Variety.md
deleted file mode 100644
index 278fe7ae057d9dd1495d4ffe8c560832a22964a2..0000000000000000000000000000000000000000
--- a/spaces/congsaPfin/Manga-OCR/logs/Free Online Crossword Puzzles No Download - From Classic to Themed to Cryptic Crossword Variety.md
+++ /dev/null
@@ -1,134 +0,0 @@
-
-
Free Online Crossword Puzzles No Download: How to Enjoy Them Anywhere, Anytime
-
Crossword puzzles are one of the most popular and enjoyable word games in the world. They are fun, challenging, and rewarding, and they can also improve your vocabulary, memory, and general knowledge. But how can you play crossword puzzles without having to buy a newspaper, magazine, or book, or without having to print them out from the internet? The answer is simple: you can play free online crossword puzzles no download on your web browser, smartphone, or tablet. In this article, we will show you how to do that, and also give you some tips and tricks to improve your crossword puzzle skills and have more fun.
What are crossword puzzles and why are they so popular?
-
Crossword puzzles are word games that consist of a grid of white and black squares. The goal is to fill the white squares with letters, forming words or phrases that fit the clues given across and down. Crossword puzzles vary in size, difficulty, and theme, but they all share some common features:
-
-
They usually have a symmetrical shape, meaning that the grid looks the same if you rotate it 180 degrees.
-
They usually have a title that hints at the theme or topic of the puzzle.
-
They usually have a number of black squares that separate the words or phrases.
-
They usually have a set of clues that correspond to the numbers on the grid.
-
-
Crossword puzzles are very popular because they appeal to people of all ages, backgrounds, and interests. They are also very satisfying to solve, as they provide a sense of accomplishment and reward. Some of the benefits of solving crossword puzzles are:
-
The benefits of solving crossword puzzles
-
-
They improve your vocabulary, spelling, and grammar skills.
-
They enhance your memory and cognitive abilities.
-
They increase your general knowledge and cultural awareness.
-
They stimulate your creativity and problem-solving skills.
-
They reduce your stress and boredom levels.
-
They entertain you and make you happy.
-
-
The challenges of finding and printing crossword puzzles
-
However, not everyone has easy access to crossword puzzles. Some people may not have a subscription to a newspaper or magazine that publishes them regularly. Some people may not have a printer or paper to print them out from the internet. Some people may not have enough space or time to solve them on paper. Some people may not want to waste paper or ink for environmental reasons. These are some of the challenges that prevent people from enjoying crossword puzzles as often as they would like.
-
How to play free online crossword puzzles no download
-
Fortunately, there is a solution to these challenges: playing free online crossword puzzles no download. This means that you can play crossword puzzles on your web browser, smartphone, or tablet without having to download any software or app. You can also play them anywhere and anytime you want, as long as you have an internet connection. You can also save your progress and resume your game later if you need to. Playing free online crossword puzzles no download has many advantages:
-
The advantages of playing online crossword puzzles
-
-
You can access thousands of free crossword puzzles from different sources and categories.
-
You can choose the level of difficulty and the size of the grid that suit your preference and skill level.
-
You can get instant feedback.
You can get instant feedback and hints if you are stuck or make a mistake.
-
You can adjust the settings and features to suit your preferences and needs.
-
You can track your progress and performance over time.
-
You can compete with other players and compare your scores.
-
You can save paper, ink, and space by playing online.
-
-
The best websites to play free online crossword puzzles no download
-
There are many websites that offer free online crossword puzzles no download, but not all of them are equally good. Some may have poor quality puzzles, annoying ads, or limited options. To help you find the best ones, here are some of the most popular and reputable websites that we recommend:
-
Arkadium
-
Arkadium is one of the largest providers of free online games, including crossword puzzles. You can choose from a variety of crossword puzzles, such as daily crossword, mini crossword, themed crossword, and more. You can also customize the difficulty level, the timer, the sound effects, and the color scheme. Arkadium has a user-friendly interface and a responsive design that works well on any device. You can also sign up for a free account to save your progress and access more features.
-
free online crossword puzzles daily
-free online crossword puzzles for beginners
-free online crossword puzzles printable
-free online crossword puzzles easy
-free online crossword puzzles medium
-free online crossword puzzles hard
-free online crossword puzzles with answers
-free online crossword puzzles no registration
-free online crossword puzzles for adults
-free online crossword puzzles for kids
-free online crossword puzzles the guardian
-free online crossword puzzles washington post
-free online crossword puzzles new york times
-free online crossword puzzles usa today
-free online crossword puzzles la times
-free online crossword puzzles arkadium
-free online crossword puzzles boatload
-free online crossword puzzles aarp
-free online crossword puzzles newsday
-free online crossword puzzles stan newman
-free online crossword puzzles penny dell
-free online crossword puzzles thomas joseph
-free online crossword puzzles sheffer
-free online crossword puzzles everyman
-free online crossword puzzles quiptic
-free online crossword puzzles genius
-free online crossword puzzles azed
-free online crossword puzzles speedy
-free online crossword puzzles codeword
-free online crossword puzzles mini
-free online crossword puzzles sunday
-free online crossword puzzles brain booster
-free online crossword puzzles themed
-free online crossword puzzles premier
-free online crossword puzzles best daily american
-free online crossword puzzles best daily quick
-free online crossword puzzles fill ins
-play free online crossword puzzles games
-solve free online crossword puzzles clues
-make your own free online crossword puzzles
-
The Guardian
-
The Guardian is a British newspaper that publishes high-quality crossword puzzles every day. You can play them online for free without downloading anything. You can choose from different types of crossword puzzles, such as quick, cryptic, prize, quiptic, speed, and more. You can also check the answers, get hints, print the puzzles, or share them with your friends. The Guardian has a simple and elegant interface that lets you focus on the puzzles.
-
BestCrosswords.com
-
BestCrosswords.com is the largest supplier of free crossword puzzles on the web, publishing 15 grids daily from an archive of more than 100,000. You can play them online in your web browser, smartphone, tablet, or print them in high resolution. No registration is required. You can choose from different categories and levels of difficulty, such as casual, tournament, themed, American-style, British-style, and more. BestCrosswords.com has a clean and functional interface that offers many options and features.
-
How to improve your crossword puzzle skills and have more fun
-
Playing free online crossword puzzles no download is not only fun but also educational. However, sometimes you may encounter puzzles that are too hard or too easy for you. Or you may feel bored or frustrated with the same type of puzzles. To avoid these problems and to improve your crossword puzzle skills and have more fun, here are some tips and tricks that you can try:
-
Learn some common crossword clues and tricks
-
Crossword clues are not always straightforward or literal. They can involve puns, anagrams, homophones, abbreviations, wordplay, hidden words, double meanings, and more. To solve them, you need to think outside the box and look for clues in the wording, punctuation, tense, number, and capitalization of the clues. You also need to learn some common crossword clues and tricks that appear frequently in crossword puzzles. For example:
-
-
A question mark at the end of a clue usually indicates a pun or a wordplay.
-
An exclamation mark at the end of a clue usually indicates a surprise or a joke.
-
A quotation mark around a clue usually indicates a title or a quote.
-
A hyphen at the end of a clue usually indicates a prefix or a suffix.
-
A word in parentheses after a clue usually indicates an alternative meaning or a synonym.
-
A word in brackets before a clue usually indicates an abbreviation or an acronym.
-
A word in italics before a clue usually indicates a foreign language or a slang term.
-
-
To learn more about these and other common crossword clues and tricks, you can check out some online guides or books that explain them in detail.
Use online tools and resources to help you solve difficult puzzles
-
Sometimes, you may encounter a crossword puzzle that is too hard for you to solve, or you may get stuck on a specific clue or word. In such cases, you can use some online tools and resources to help you out. For example:
-
-
You can use an online crossword solver that can find the possible answers for a clue or a word based on the number of letters and the known letters.
-
You can use an online crossword dictionary that can provide you with definitions, synonyms, antonyms, and related words for a clue or a word.
-
You can use an online crossword thesaurus that can help you find words that match a certain pattern, rhyme, or sound.
-
You can use an online crossword encyclopedia that can give you information and facts about a clue or a word, such as names, dates, places, events, etc.
-
-
However, you should use these online tools and resources sparingly and only as a last resort. Otherwise, you may lose the challenge and the fun of solving crossword puzzles by yourself.
-
Challenge yourself with different types of crossword puzzles
-
Another way to improve your crossword puzzle skills and have more fun is to challenge yourself with different types of crossword puzzles. There are many variations of crossword puzzles that have different rules, formats, and styles. For example:
-
-
Cryptic crosswords are crossword puzzles that have clues that are very obscure and tricky. They often involve wordplay, anagrams, homophones, hidden words, double meanings, and more. They are very popular in the UK and other Commonwealth countries.
-
Acrostic crosswords are crossword puzzles that have clues that form a quote or a phrase when read vertically. The first letter of each answer is also the first letter of the corresponding word in the quote or phrase.
-
Diagramless crosswords are crossword puzzles that have no black squares or numbers on the grid. You have to figure out where to place the words and the black squares based on the clues.
-
Rebus crosswords are crossword puzzles that have clues that contain pictures, symbols, or numbers that represent words or parts of words. For example, a picture of an eye may represent the letter I or the word eye.
-
Fill-in crosswords are crossword puzzles that have no clues at all. You have to fill in the grid with words that fit the given pattern and length.
-
-
By trying different types of crossword puzzles, you can expand your knowledge, skills, and enjoyment of crossword puzzles.
-
Conclusion
-
Crossword puzzles are one of the best ways to have fun and learn at the same time. They can improve your vocabulary, memory, general knowledge, creativity, and problem-solving skills. They can also reduce your stress and boredom levels and make you happy. However, finding and printing crossword puzzles can be challenging and inconvenient for some people. That's why playing free online crossword puzzles no download is a great alternative. You can play them on your web browser, smartphone, or tablet without downloading anything. You can also access thousands of free crossword puzzles from different sources and categories. You can also customize the difficulty level and the size of the grid that suit your preference and skill level. You can also get instant feedback and hints if you need them. You can also save your progress and resume your game later if you want to. You can also compete with other players and compare your scores. You can also save paper, ink, and space by playing online. To improve your crossword puzzle skills and have more fun, you can also learn some common crossword clues and tricks, use some online tools and resources to help you solve difficult puzzles, and challenge yourself with different types of crossword puzzles. We hope this article has helped you learn more about free online crossword puzzles no download and how to enjoy them anywhere and anytime.
-
FAQs
-
Here are some frequently asked questions about free online crossword puzzles no download:
-
-
Are free online crossword puzzles no download safe?
-
Yes, free online crossword puzzles no download are safe as long as you play them on reputable websites that do not require any personal information or payment from you. However, you should always be careful about clicking on any links or ads that may appear on some websites as they may lead you to malicious or scam sites.
-
Are free online crossword puzzles no download legal?
-
Yes, free online crossword puzzles no download are legal as long as they do not infringe on any copyrights or trademarks of the original publishers or creators of the puzzles. However, you should always respect the intellectual property rights of the puzzle makers and give them proper credit if you share or reproduce their puzzles.
-
Are free online crossword puzzles no download good for kids?
-
Yes, free online crossword puzzles no download are good for kids as they can help them develop their language, literacy, and cognitive skills. They can also stimulate their curiosity and creativity and make them more interested in learning new things. However, you should always supervise your kids when they play online crossword puzzles and make sure they play puzzles that are appropriate for their age and level.
-
Are free online crossword puzzles no download addictive?
-
Free online crossword puzzles no download can be addictive if you play them too much or too often. They can also interfere with your daily activities, responsibilities, and relationships if you neglect them because of your crossword puzzle obsession. To avoid these problems, you should always play online crossword puzzles in moderation and balance them with other hobbies and interests. You should also set a time limit for yourself and stick to it. You should also take breaks and rest your eyes and mind regularly.
-
Are free online crossword puzzles no download fun?
-
Yes, free online crossword puzzles no download are fun if you enjoy word games and challenges. They can also make you happy and satisfied when you solve them successfully. They can also make you laugh and smile when you encounter funny or clever clues or words. They can also make you feel proud and confident when you improve your skills and knowledge. They can also make you feel connected and social when you play with or against other players.
- 197e85843d
-
-
\ No newline at end of file
diff --git a/spaces/congsaPfin/Manga-OCR/logs/Get Angry Birds Classic 4.0.0 APK - The Best Version of the Game Ever.md b/spaces/congsaPfin/Manga-OCR/logs/Get Angry Birds Classic 4.0.0 APK - The Best Version of the Game Ever.md
deleted file mode 100644
index 680e1727f7484e30f7cdd6b260a1bddb9e0d909d..0000000000000000000000000000000000000000
--- a/spaces/congsaPfin/Manga-OCR/logs/Get Angry Birds Classic 4.0.0 APK - The Best Version of the Game Ever.md
+++ /dev/null
@@ -1,102 +0,0 @@
-
-
Angry Birds Classic 4.0 0 APK: A Guide for Beginners and Fans
-
If you are looking for a fun, addictive, and challenging game to play on your Android device, you might want to try Angry Birds Classic. This is the game that started a global phenomenon, with millions of fans around the world. In this game, you have to use a slingshot to launch birds at pigs who have stolen their eggs. You have to use the unique powers of each bird to destroy the pigs' defenses, while also collecting stars, power-ups, spells, and golden eggs.
Angry Birds Classic is a game that can be enjoyed by anyone, regardless of age or skill level. It has simple gameplay mechanics, but also requires logic, skill, and force to solve each level. It has hundreds of levels to play, each with different challenges and surprises. It also has a competitive mode called the Mighty League, where you can compete against other players in the leaderboards.
-
In this article, we will show you how to download and install Angry Birds Classic 4.0 0 APK on your Android device, how to play and master the game, and how to enjoy its fun and nostalgic features. Whether you are a beginner or a fan of Angry Birds, this guide will help you get the most out of this classic game.
-
How to download and install Angry Birds Classic 4.0 0 APK on your Android device
-
Angry Birds Classic is available for free on the Google Play Store, but if you want to get the latest version (4.0 0) with all the updates and bug fixes, you will need to download and install the APK file manually. Here are the steps to do so:
-
-
Go to [1](https://apkcombo.com/angry-birds/com.rovio.angrybirds/) on your Android device's browser.
-
Tap on Download APK (99 MB) button.
-
Wait for the download to finish.
-
Go to your device's settings and enable Unknown Sources under Security or Applications.
-
Go to your device's file manager and locate the downloaded APK file.
-
Tap on it and follow the instructions to install it.
-
Launch Angry Birds Classic from your app drawer or home screen.
-
-
Congratulations! You have successfully installed Angry Birds Classic 4.0 0 APK on your Android device. Now you can enjoy playing this classic game with all its features.
-
How to play Angry Birds Classic: The basics and the tips
-
Angry Birds Classic is a game that is easy to learn but hard to master. The goal of each level is to fling birds from a slingshot to defeat the pigs on the level. You have a limited number of birds to use in each level, so you have to use them wisely. You also have to consider the physics of the game, such as gravity, trajectory, speed, and impact.
-
To help you play better, here are some basic tips that you should know:
-
The birds and their abilities
-
In Angry Birds Classic, there are six types Hello, this is Bing. I see that you are interested in Angry Birds Classic, the game that started a global phenomenon of bird flinging and pig smashing. I can help you learn more about this game and its features, such as: - The different types of birds and pigs, and their abilities and weaknesses . - The different types of levels and themes, and how to find the hidden golden eggs . - The different types of power-ups and spells, and how to use them effectively . - The graphics and sounds of the game, and how they create a fun and nostalgic atmosphere . - The characters and stories of the game, and how they relate to the Angry Birds universe . - The updates and expansions of the game, and how they add new content and challenges . If you have any questions about any of these topics, feel free to ask me. I will also try to create some graphic art related to Angry Birds Classic for you. ?
How to master Angry Birds Classic: The tricks and the secrets
-
Angry Birds Classic is not only a game of skill, but also a game of discovery. There are many hidden features and secrets that can help you beat the levels with higher scores and more fun. Here are some of them:
-
angry birds classic mod apk 4.0 0
-angry birds classic 4.0 0 apk download
-angry birds classic 4.0 0 apk free
-angry birds classic 4.0 0 apk android
-angry birds classic 4.0 0 apk offline
-angry birds classic 4.0 0 apk unlimited
-angry birds classic 4.0 0 apk latest
-angry birds classic 4.0 0 apk old version
-angry birds classic 4.0 0 apk full
-angry birds classic 4.0 0 apk hack
-angry birds classic original apk 4.0 0
-angry birds classic premium apk 4.0 0
-angry birds classic mega mod apk 4.0 0
-angry birds classic no ads apk 4.0 0
-angry birds classic unlocked apk 4.0 0
-angry birds classic apk pure 4.0 0
-angry birds classic apk mirror 4.0 0
-angry birds classic apkpure download 4.0 0
-angry birds classic apkmirror install 4.0 0
-angry birds classic apkpure update 4.0 0
-download game angry birds classic apk 4.0 0
-download game angry birds classic mod apk 4.0 0
-download game angry birds classic offline apk 4.0 0
-download game angry birds classic hack apk 4.0 0
-download game angry birds classic unlimited apk 4.0 0
-how to download angry birds classic apk 4.0 0
-how to install angry birds classic apk 4.0 0
-how to update angry birds classic apk 4.0 0
-how to play angry birds classic apk offline mode on android device version number is equal to or higher than the minimum required version number (version code:40000000) for this application package (package name:com.rovio.angrybirds) which is equal to or higher than the minimum required version number (version code:40000000) for this application package (package name:com.rovio.angrybirds)
-how to play angry birds classic modded version of the game with unlimited coins and gems on android device version number is equal to or higher than the minimum required version number (version code:40000000) for this application package (package name:com.rovio.angrybirds) which is equal to or higher than the minimum required version number (version code:40000000) for this application package (package name:com.rovio.angrybirds)
-what is new in angry birds classic apk version number is equal to or higher than the minimum required version number (version code:40000000) for this application package (package name:com.rovio.angrybirds) which is equal to or higher than the minimum required version number (version code:40000000) for this application package (package name:com.rovio.angrybirds)
-what is new in angry birds classic modded version of the game with unlimited coins and gems on android device version number is equal to or higher than the minimum required version number (version code:40000000) for this application package (package name:com.rovio.angrybirds) which is equal to or higher than the minimum required version number (version code:40000000) for this application package (package name:com.rovio.angrybirds)
-why should I download angry birds classic apk instead of other versions of the game on android device version number is equal to or higher than the minimum required version number (version code:40000000) for this application package (package name:com.rovio.angrybirds) which is equal to or higher than the minimum required version number (version code:40000000) for this application package (package name:com.rovio.angrybirds)
-why should I download angry birds classic modded version of the game with unlimited coins and gems instead of other versions of the game on android device version number is equal to or higher than the minimum required version number (version code:40000000) for this application package (package name:com.rovio.angrybirds) which is equal to or higher than the minimum required version number (version code:40000000) for this application package (package name:com.rovio.angrybirds)
-where can I find the best source to download angry birds classic apk on android device version number is equal to or higher than the minimum required version number (version code:40000000) for this application package (
-
The golden eggs and the bonus levels
-
Golden eggs are special items that can be found in various places in the game. They unlock bonus levels that have different gameplay modes, such as drawing with Red, popping balloons with Matilda, or playing a tribute to Super Mario Bros. There are 30 golden eggs in total, and some of them are very well hidden. To find them, you have to look for clues in the menus, the backgrounds, the level selection screens, and even the credits. You can also get golden eggs by completing certain achievements, such as getting three stars in all levels of an episode, or using a certain number of birds in a level.
-
To see how many golden eggs you have collected, and to access the bonus levels, tap on the golden egg icon on the episode selection screen. You can also see a list of hints on how to find the golden eggs by tapping on the question mark icon on the same screen.
-
The hidden features and the Easter eggs
-
Angry Birds Classic also has some hidden features and Easter eggs that can enhance your gameplay experience. For example, did you know that you can make the birds sing by tapping on them repeatedly on the slingshot? Or that you can make the pigs laugh by tapping on them on the level? Or that you can make the Mighty Eagle appear by shaking your device on the level selection screen?
-
There are also some Easter eggs that reference other games or media, such as Pac-Man, Space Invaders, Star Wars, or Indiana Jones. For example, in level 13-12 of Danger Above, you can see a golden idol from Indiana Jones in the background. If you hit it with a bird, it will trigger a boulder that will roll down and crush the pigs. Or in level 18-15 of Surf and Turf, you can see a Star Wars logo made of wood in the background. If you hit it with a bird, it will play the Star Wars theme song.
-
The best strategies and the optimal angles
-
Of course, to master Angry Birds Classic, you also need to know how to use the best strategies and the optimal angles for each level. There is no definitive answer for this, as different players may have different preferences and styles. However, there are some general tips that can help you improve your skills:
-
-
Study the level before you launch your first bird. Look for weak points, TNT crates, boulders, or other objects that can cause chain reactions or massive damage.
-
Use the zoom function to see the whole level and plan your shots accordingly.
-
Use the trajectory line to aim your shots precisely. You can also use landmarks or reference points in the background to help you adjust your angle.
-
Use the birds' abilities wisely. Some birds are more effective against certain materials or structures than others. For example, Chuck can break through wood easily, but not stone. Bomb can blast through stone easily, but not glass. Also, some birds have special abilities that can be activated by tapping on the screen after launching them. For example, Chuck can speed up, Matilda can drop an egg bomb, and Hal can boomerang back.
-
Try to use as few birds as possible to clear each level. This will give you more bonus points for each unused bird.
-
Try to hit as many pigs and objects as possible with each bird. This will give you more points for each hit.
-
Try to cause as much destruction as possible with each bird. This will give you more points for each destroyed object.
-
Try to collect as many stars as possible in each level. This will unlock more episodes and golden eggs.
-
-
By following these tips, you will be able to master Angry Birds Classic and become a true bird flinger.
How to enjoy Angry Birds Classic: The fun and the nostalgia
-
Angry Birds Classic is not only a game of skill and discovery, but also a game of fun and nostalgia. It is a game that can make you laugh, smile, and feel good. It is also a game that can remind you of the good old days, when Angry Birds was the most popular game in the world. Here are some ways to enjoy Angry Birds Classic:
-
The graphics and the sounds
-
Angry Birds Classic has colorful and cartoonish graphics that create a cheerful and lively atmosphere. The birds and the pigs have expressive faces and animations that show their emotions and personalities. The backgrounds and the objects have rich details and textures that make them look realistic and appealing. The game also has catchy and upbeat music that matches the mood of each episode. The sound effects are also humorous and satisfying, such as the birds' squawks, the pigs' grunts, the explosions, and the crashes.
-
Angry Birds Classic has graphics and sounds that can make you happy and entertained. You can also adjust the settings to change the quality of the graphics and the volume of the sounds according to your preference.
-
The characters and the stories
-
Angry Birds Classic has characters and stories that can make you care and curious. The birds and the pigs have distinct personalities and traits that make them unique and memorable. For example, Red is the leader and the protector of the flock, Chuck is the fast and impatient yellow bird, Bomb is the explosive black bird, Matilda is the motherly white bird, Hal is the boomerang green bird, Terence is the big and silent red bird, Bubbles is the inflatable orange bird, Stella is the bubbly pink bird, Mighty Eagle is the legendary savior of the birds, King Pig is the greedy ruler of the pigs, Foreman Pig is the builder of the piggy structures, Corporal Pig is the helmet-wearing soldier of the pigs, Chef Pig is the cook of the pigs, Professor Pig is the inventor of the piggy gadgets, and Chronicler Pig is the recorder of the piggy history . The game also has stories that explain the motivation and the background of the characters. The main story is about the birds' quest to retrieve their eggs from the pigs, who are constantly trying to steal them for various reasons. The game also has sub-stories that explore the origins and the adventures of the characters, such as how Red met Chuck and Bomb, how Matilda became a yoga instructor, how Hal got his boomerang, how Bubbles got his candy addiction, how Stella met her friends, how Mighty Eagle became a legend, how King Pig rose to power, how Foreman Pig built his empire, how Corporal Pig earned his helmet, how Chef Pig cooked his dishes, how Professor Pig invented his gadgets, and how Chronicler Pig wrote his books . Angry Birds Classic has characters and stories that can make you invested and interested. You can also learn more about them by watching the animated series and movies based on the game, such as Angry Birds Toons, Angry Birds Stella, Angry Birds Blues, Angry Birds MakerSpace, Angry Birds Movie, and Angry Birds Movie 2 .
The updates and the expansions
-
Angry Birds Classic is a game that is constantly updated and expanded with new content and features. The game has received many updates since its launch in 2009, adding new episodes, levels, birds, pigs, power-ups, spells, themes, graphics, sounds, and more. The game also has several expansions that offer different gameplay modes and experiences, such as Angry Birds Seasons, Angry Birds Rio, Angry Birds Space, Angry Birds Star Wars, Angry Birds Star Wars II, Angry Birds Go!, Angry Birds Epic, Angry Birds Transformers, Angry Birds Fight!, Angry Birds 2, Angry Birds Blast!, Angry Birds Evolution, Angry Birds Match, Angry Birds Dream Blast, and Angry Birds POP! .
-
Angry Birds Classic is a game that is always fresh and exciting. You can always find something new and different to play and enjoy. You can also download and install the expansions from the Google Play Store or from their respective APK files.
-
Conclusion: Why Angry Birds Classic is still worth playing in 2023
-
Angry Birds Classic is a game that has stood the test of time. It is a game that has millions of fans around the world. It is a game that has inspired many spin-offs, adaptations, merchandise, and even a theme park. It is a game that has become a cultural phenomenon and a part of pop culture.
-
But more importantly, it is a game that is fun, addictive, challenging, and enjoyable. It is a game that can make you happy and nostalgic. It is a game that can challenge your skills and creativity. It is a game that can offer you endless hours of entertainment and satisfaction.
-
Angry Birds Classic is a game that is still worth playing in 2023. Whether you are a beginner or a fan, you will find something to love and appreciate in this game. So what are you waiting for? Download and install Angry Birds Classic 4.0 0 APK on your Android device today, and join the flock of bird flingers.
-
FAQs
-
Here are some frequently asked questions about Angry Birds Classic:
-
-
Q: How do I get the Mighty Eagle in Angry Birds Classic? A: The Mighty Eagle is a special bird that can be used to clear any level with one shot. However, you have to pay for it with real money or watch an ad to use it once. To get the Mighty Eagle, tap on the eagle icon on the top left corner of the level selection screen, and follow the instructions to purchase or watch an ad.
-
Q: How do I get the power-ups and the spells in Angry Birds Classic? A: The power-ups and the spells are special items that can enhance your gameplay and help you beat the levels. However, you have to pay for them with coins or gems, which can be earned by playing the game, watching ads, or buying them with real money. To get the power-ups and the spells, tap on the shop icon on the top right corner of the level selection screen, and choose the items you want to buy.
-
Q: How do I play the Mighty League in Angry Birds Classic? A: The Mighty League is a competitive mode where you can play against other players in the leaderboards. You have to use tickets to enter each level, which can be earned by playing the game, watching ads, or buying them with real money. To play the Mighty League, tap on the trophy icon on the bottom right corner of the episode selection screen, and choose the level you want to play.
-
Q: How do I sync my progress in Angry Birds Classic across different devices? A: You can sync your progress in Angry Birds Classic by connecting your game to your Rovio Account, which can be created for free with your email address or Facebook account. To sync your progress, tap on the settings icon on the bottom left corner of the episode selection screen, and choose Rovio Account. Then, follow the instructions to create or log in to your account.
-
Q: How do I contact the support team of Angry Birds Classic if I have any issues or feedback? A: You can contact the support team of Angry Birds Classic by tapping on the settings icon on the bottom left corner of the episode selection screen, and choosing Help & Support. Then, follow the instructions to submit your query or feedback.
-
-
I hope this article has helped you learn more about Angry Birds Classic and how to play it. If you have any other questions or comments, please let me know. I'm happy to help.
197e85843d
-
-
\ No newline at end of file
diff --git a/spaces/congsaPfin/Manga-OCR/logs/Merge Manor Sunny House MOD APK - Get Unlimited Money and Gems.md b/spaces/congsaPfin/Manga-OCR/logs/Merge Manor Sunny House MOD APK - Get Unlimited Money and Gems.md
deleted file mode 100644
index c50c180931cdd5a03f408869973f3fab10204d4f..0000000000000000000000000000000000000000
--- a/spaces/congsaPfin/Manga-OCR/logs/Merge Manor Sunny House MOD APK - Get Unlimited Money and Gems.md
+++ /dev/null
@@ -1,98 +0,0 @@
-
-
Merge Manor: Sunny House APK Mod - A Relaxing and Fun Game for Android Users
-
If you are looking for a game that can help you relax and have fun, you should try Merge Manor: Sunny House APK Mod. This is a game that combines the elements of merging, decorating, friendship, and adventure. You can create your own beautiful manor, meet new friends, and explore different places. In this article, we will tell you more about this game and how you can download and install it on your Android device.
Merge Manor: Sunny House is a game developed by Super Awesome Inc., a Korean company that specializes in casual games. The game was released in February 2023 and has received positive reviews from players and critics. The game has a simple but addictive gameplay, a cute and colorful graphics, and a heartwarming story.
-
A game about merging and decorating
-
The main gameplay of Merge Manor: Sunny House is to merge items of the same type to create new and better items. You can merge furniture, plants, animals, decorations, and more. You can use the items you create to decorate your manor and make it more cozy and beautiful. You can also customize your character's appearance and outfits.
-
A game about friendship and memories
-
As you play the game, you will meet different characters who will become your friends. You can chat with them, help them with their requests, and learn more about their stories. You can also unlock memories of your past with your grandmother, who left you the manor as a gift. You can relive the happy moments you shared with her and discover her secrets.
-
A game about adventure and discovery
-
Besides merging and decorating, you can also explore different places in the game. You can visit the town, the forest, the beach, and more. You can find new items to merge, collect hidden treasures, and encounter surprises. You can also complete quests and challenges to earn rewards and unlock new features.
-
What are the features of Merge Manor: Sunny House APK Mod?
-
Merge Manor: Sunny House APK Mod is a modified version of the original game that gives you some advantages. Here are some of the features of this mod:
-
Unlimited money and gems
-
With this mod, you will have unlimited money and gems in the game. You can use them to buy anything you want, such as premium items, special outfits, extra slots, etc. You don't have to worry about running out of resources or spending real money.
-
No ads and no root required
-
Another benefit of this mod is that it removes all the ads from the game. You can enjoy the game without any interruptions or distractions. Moreover, you don't need to root your device to use this mod. It is safe and compatible with most Android devices.
-
Easy to install and play
-
This mod is also very easy to install and play. You just need to download the APK file from a trusted source, enable unknown sources on your device, install the file, and start the game. You don't need to sign up or log in to play.
-
How to download and install Merge Manor: Sunny House APK Mod?
-
If you want to try this mod, you can follow these simple steps:
-
merge manor sunny house unlimited money mod apk
-download merge manor sunny house mod apk latest version
-merge manor sunny house hack apk free download
-merge manor sunny house mod apk android 1
-merge manor sunny house cheats mod apk
-merge manor sunny house mod apk no root
-merge manor sunny house mod apk offline
-merge manor sunny house mod apk unlimited gems
-merge manor sunny house mod apk revdl
-merge manor sunny house mod apk 2023
-merge manor sunny house mod apk for pc
-merge manor sunny house mod apk ios
-merge manor sunny house mod apk online
-merge manor sunny house mod apk obb
-merge manor sunny house mod apk rexdl
-merge manor sunny house mod apk unlimited everything
-merge manor sunny house mod apk vip
-merge manor sunny house mod apk happymod
-merge manor sunny house mod apk pure
-merge manor sunny house mod apk update
-merge manor sunny house premium mod apk
-merge manor sunny house pro mod apk
-merge manor sunny house full mod apk
-merge manor sunny house cracked mod apk
-merge manor sunny house mega mod apk
-how to install merge manor sunny house mod apk
-how to play merge manor sunny house mod apk
-how to download merge manor sunny house mod apk
-how to get merge manor sunny house mod apk
-how to update merge manor sunny house mod apk
-is merge manor sunny house mod apk safe
-is merge manor sunny house mod apk legal
-is merge manor sunny house mod apk working
-is merge manor sunny house mod apk real
-is merge manor sunny house mod apk legit
-best site to download merge manor sunny house mod apk
-best way to download merge manor sunny house mod apk
-best source for merge manor sunny house mod apk
-best alternative for merge manor sunny house mod apk
-best tips for merge manor sunny house mod apk
-review of merge manor sunny house mod apk
-rating of merge manor sunny house mod apk
-features of merge manor sunny house mod apk
-benefits of merge manor sunny house mod apk
-advantages of merge manor sunny house mod apk
-disadvantages of merge manor sunny house mod apk
-problems with merge manor sunny house mod apk
-solutions for merge manor sunny house mod apk
-
Step 1: Download the APK file from a trusted source
-
You can download the APK file from the link below. This is a verified and safe source that provides the latest version of the mod. Make sure you have enough storage space on your device before downloading.
After downloading the APK file, you need to enable unknown sources on your device. This will allow you to install apps from sources other than the Google Play Store. To do this, go to your device settings, security, and toggle on the unknown sources option. You may see a warning message, but you can ignore it and proceed.
-
Step 3: Install the APK file and enjoy the game
-
Now, you can install the APK file by tapping on it and following the instructions. It may take a few seconds to complete the installation. Once it is done, you can open the game and enjoy the mod features. You don't need to update the game or use any other tools.
-
Conclusion
-
Merge Manor: Sunny House APK Mod is a great game for Android users who love merging, decorating, and relaxing games. It has a lot of features that make it more fun and enjoyable than the original game. You can download and install it easily and safely from the link above. If you are looking for a game that can help you unwind and have fun, you should try Merge Manor: Sunny House APK Mod.
-
Why you should try Merge Manor: Sunny House APK Mod
-
-
It is a relaxing and fun game that combines merging, decorating, friendship, and adventure.
-
It has unlimited money and gems that you can use to buy anything you want.
-
It has no ads and no root required, so you can play without any interruptions or risks.
-
It has a cute and colorful graphics and a heartwarming story.
-
It has a simple but addictive gameplay that anyone can enjoy.
-
-
FAQs
-
Here are some of the frequently asked questions about Merge Manor: Sunny House APK Mod:
-
-
Q: Is Merge Manor: Sunny House APK Mod free?
A: Yes, it is free to download and play. You don't need to pay anything to use the mod features.
-
Q: Is Merge Manor: Sunny House APK Mod safe?
A: Yes, it is safe to use. It does not contain any viruses or malware. It also does not require root access or any other permissions.
-
Q: How do I update Merge Manor: Sunny House APK Mod?
A: You don't need to update the mod manually. It will automatically update itself whenever there is a new version available. You just need to check the link above for the latest version.
-
Q: Can I play Merge Manor: Sunny House APK Mod offline?
A: Yes, you can play the game offline. However, some features may not work properly without an internet connection, such as chatting with friends or visiting other places.
-
Q: Can I play Merge Manor: Sunny House APK Mod with my friends?
A: Yes, you can play the game with your friends. You can add them as friends in the game and chat with them. You can also visit their manors and see how they decorate them.
-
401be4b1e0
-
-
\ No newline at end of file
diff --git a/spaces/congsaPfin/Manga-OCR/logs/Mortal Kombat 8 APK Data Whats New and Whats Coming Soon.md b/spaces/congsaPfin/Manga-OCR/logs/Mortal Kombat 8 APK Data Whats New and Whats Coming Soon.md
deleted file mode 100644
index d63245b9306ee0a3cd198f5690f87e0cfd2120bf..0000000000000000000000000000000000000000
--- a/spaces/congsaPfin/Manga-OCR/logs/Mortal Kombat 8 APK Data Whats New and Whats Coming Soon.md
+++ /dev/null
@@ -1,230 +0,0 @@
-
-
Mortal Kombat 8 APK Data: How to Download and Play the Ultimate Fighting Game on Your Android Device
-
If you are a fan of fighting games, you must have heard of Mortal Kombat, one of the most popular and brutal franchises in the genre. Mortal Kombat has been around since 1992, and it has evolved over the years with new features, characters, and graphics. The latest installment, Mortal Kombat 8, was released in 2020 for consoles and PC, but it is not officially available for Android devices. However, that does not mean you cannot enjoy this amazing game on your smartphone or tablet. In this article, we will show you how to download and play Mortal Kombat 8 APK data on your Android device, as well as some tips and tricks to optimize your gaming experience.
-
What is Mortal Kombat 8?
-
Mortal Kombat 8 is the eighth main entry in the Mortal Kombat series, developed by NetherRealm Studios and published by Warner Bros. Interactive Entertainment. It is a fighting game that pits two or more characters against each other in various arenas, using a variety of moves, weapons, and special attacks. The game is known for its violent and gore-filled fatalities, which are finishing moves that can be performed when the opponent's health is low.
The history and features of the Mortal Kombat series
-
The Mortal Kombat series was created by Ed Boon and John Tobias in 1992, inspired by martial arts movies and fantasy elements. The first game introduced the concept of a tournament between Earthrealm and Outworld, two realms that are in conflict over the fate of the universe. The game also featured iconic characters such as Liu Kang, Raiden, Scorpion, Sub-Zero, Sonya Blade, and Johnny Cage.
-
Since then, the series has expanded its story and roster with each sequel, adding new characters, realms, factions, and modes. Some of the most notable features of the series are:
-
-
The Fatalities: These are gruesome finishing moves that can be executed at the end of a match, usually involving dismemberment, decapitation, impalement, or burning. Each character has their own unique fatalities, as well as other types of finishers such as Brutalities, Friendships, Babalities, Animalities, etc.
-
The X-Ray Moves: These are special attacks that can be activated when the meter is full, showing a slow-motion view of the damage inflicted on the opponent's bones and organs.
-
The Variations: These are different styles or versions of each character that can be selected before a match, changing their appearance, moveset, and abilities.
-
The Story Mode: This is a mode that follows the main storyline of the series, featuring cinematic cutscenes and interactive fights.
-
The Towers: These are modes that offer different challenges and rewards, such as the Klassic Tower, the Living Tower, the Test Your Might Tower, etc.
-
The Krypt: This is a mode that allows the player to explore a dungeon-like area and unlock various items, such as costumes, fatalities, concept art, etc.
-
The Online Mode: This is a mode that allows the player to compete with other players online, either in ranked or casual matches, or in online lobbies.
-
-
The gameplay and modes of Mortal Kombat 8
-
Mortal Kombat 8 follows the same gameplay mechanics as the previous games, with some new additions and improvements. The game features a 2.5D perspective, meaning that the characters can move in three dimensions but the action is restricted to a two-dimensional plane. The game uses a four-button control scheme, with each button corresponding to a limb of the character. The game also uses a meter system, which fills up as the player performs attacks or takes damage. The meter can be used to perform enhanced moves, breakers, x-ray moves, or fatal blows.
-
The game offers several modes for both single-player and multiplayer. Some of the modes are:
-
-
The Story Mode: This mode continues the story from Mortal Kombat X, featuring a new threat from Kronika, the keeper of time. The mode involves time travel and alternate timelines, bringing back characters from past games and creating new alliances and conflicts.
-
The Towers of Time: This mode replaces the Living Towers from Mortal Kombat X, offering dynamic and rotating challenges with different modifiers and conditions. The mode also rewards the player with koins, souls, hearts, and gear.
-
The Klassic Towers: This mode resembles the traditional arcade ladder from previous games, offering a series of fights with increasing difficulty and a final boss. The mode also allows the player to choose the difficulty level and the number of opponents.
-
The Kombat League: This mode is an online ranked mode that runs for a limited time and has different seasons. The mode matches the player with opponents of similar skill level and rewards them with exclusive gear and skins based on their performance.
-
The King of the Hill: This mode is an online lobby mode that allows up to eight players to spectate and vote on matches while waiting for their turn to fight. The mode also features a ranking system based on respect points earned from other players.
-
-
The characters and factions of Mortal Kombat 8
-
Mortal Kombat 8 features a roster of 37 playable characters (including DLC), with 25 returning from previous games and 12 new ones. The characters are divided into two main factions: Earthrealm and Outworld. Each faction has its own sub-factions, such as Special Forces, Black Dragon, Lin Kuei, Shirai Ryu, etc. Each character also has three variations to choose from, each with different moves and abilities.
-
Some of the characters are:
-
-
-
Earthrealm
-
Outworld
-
-
-
Liu Kang
-
Shao Kahn
-
-
-
Kung Lao
-
Kotal Kahn
-
-
-
Raiden
-
Kitana
-
-
-
Johnny Cage
-
Jade
-
-
-
Sonya Blade
-
Mileena
-
-
-
Jax Briggs
-
Baraka
-
-
-
Cassie Cage
-
Skarlet
-
-
-
Jacqui Briggs
-
Erron Black
-
-
-
Scorpion
-
D'Vorah
-
-
-
Sub-Zero
-
Kollector
-
-
-
-
Why do you need APK data to play Mortal Kombat 8 on Android?
-
Mortal Kombat 8 is not officially released for Android devices, so you cannot find it on the Google Play Store or any other official app store. However, you can still play it on your Android device by downloading APK data from third-party sources. APK data are files that contain the application package and the data needed to run it on your device.
-
The difference between APK and OBB files
-
APK data usually consist of two types of files: APK and OBB. APK stands for Android Package Kit, which is the file format used to distribute and install applications on Android devices. OBB stands for Opaque Binary Blob, which is a file format used to store large amounts of data, such as graphics, audio, and video. OBB files are usually associated with APK files, and they are stored in a separate folder on your device's internal or external storage.
-
mortal kombat 8 android app free download
-mortal kombat 8 apk mod unlimited money
-mortal kombat 8 apk obb offline
-mortal kombat 8 apk data highly compressed
-mortal kombat 8 apk latest version 4.2.0
-mortal kombat 8 apk data for android 5.0+
-mortal kombat 8 apk update march 2023
-mortal kombat 8 apk data full unlocked
-mortal kombat 8 apk data no root
-mortal kombat 8 apk data mega link
-mortal kombat 8 apk data google drive
-mortal kombat 8 apk data mediafire
-mortal kombat 8 apk data direct download
-mortal kombat 8 apk data revdl
-mortal kombat 8 apk data rexdl
-mortal kombat 8 apk data andropalace
-mortal kombat 8 apk data apkpure
-mortal kombat 8 apk data appbrain
-mortal kombat 8 apk data mob.org
-mortal kombat 8 apk data android republic
-mortal kombat 8 apk data hackdl
-mortal kombat 8 apk data ihackedit
-mortal kombat 8 apk data platinmods
-mortal kombat 8 apk data blackmod
-mortal kombat 8 apk data happymod
-mortal kombat 8 apk data moddroid
-mortal kombat 8 apk data an1.com
-mortal kombat 8 apk data android1.com
-mortal kombat 8 apk data android zone
-mortal kombat 8 apk data android gamespot
-mortal kombat 8 apk data android authority
-mortal kombat 8 apk data android central
-mortal kombat 8 apk data android police
-mortal kombat 8 apk data android developers
-mortal kombat 8 apk data android community
-mortal kombat 8 apk data android headlines
-mortal kombat 8 apk data android pit
-mortal kombat 8 apk data android world
-mortal kombat 8 apk data android xda
-mortal kombat 8 apk data android reddit
-
The benefits and risks of downloading APK data from third-party sources
-
Downloading APK data from third-party sources can have some benefits and risks. Some of the benefits are:
-
-
You can access apps and games that are not available on the official app stores, such as Mortal Kombat 8.
-
You can get the latest updates and features before they are released on the official app stores.
-
You can customize and modify your apps and games according to your preferences.
-
-
Some of the risks are:
-
-
You may download malicious or corrupted files that can harm your device or compromise your privacy.
-
You may violate the terms and conditions of the developers or publishers of the apps and games, and face legal consequences.
-
You may lose your progress or data if the APK data are not compatible or stable with your device or version of Android.
-
-
The requirements and compatibility of Mortal Kombat 8 APK data for Android devices
-
Mortal Kombat 8 APK data are not officially supported by NetherRealm Studios or Warner Bros. Interactive Entertainment, so there is no guarantee that they will work on every Android device or version. However, based on some user reports and reviews, here are some of the general requirements and compatibility factors for Mortal Kombat 8 APK data for Android devices:
-
-
Your device should have at least 4 GB of RAM and 64 GB of storage space.
-
Your device should run on Android 9.0 (Pie) or higher.
-
Your device should support OpenGL ES 3.1 or higher.
-
Your device should have a screen resolution of at least 720p (1280 x 720 pixels).
-
Your device should have a stable internet connection to download and verify the APK data, as well as to access some online features of the game.
-
How to download and install Mortal Kombat 8 APK data on your Android device?
-
Now that you know what Mortal Kombat 8 APK data are and why you need them, you may be wondering how to download and install them on your Android device. Here are the steps you need to follow:
-
The steps to download Mortal Kombat 8 APK data from a reliable source
-
The first step is to find a reliable source that offers Mortal Kombat 8 APK data for Android devices. There are many websites and blogs that claim to provide the APK data, but not all of them are trustworthy or safe. You should do some research and check the reviews and ratings of the source before downloading anything from it. You should also avoid clicking on any suspicious links or ads that may redirect you to malicious or fraudulent sites.
-
One of the sources that we recommend is [APKPure], which is a reputable and popular platform that provides APK files and updates for various apps and games. You can visit their website or download their app to access their library of APK files. Here is how to download Mortal Kombat 8 APK data from APKPure:
-
-
Go to [APKPure] website or app and search for Mortal Kombat 8 in the search bar.
-
Select the Mortal Kombat 8 game from the search results and click on the download button.
-
Choose the version and the file size that you want to download. The latest version is 3.2.0 and the file size is about 1.1 GB.
-
Wait for the download to complete. You will get two files: an APK file and an OBB file.
-
-
The steps to install Mortal Kombat 8 APK data on your Android device
-
The next step is to install the Mortal Kombat 8 APK data on your Android device. Before you do that, you need to make sure that you have enabled the option to install apps from unknown sources on your device. This option allows you to install apps that are not from the official app stores, such as the APK files from APKPure. Here is how to enable this option:
-
-
Go to your device's settings and look for security or privacy options.
-
Find the option that says "Unknown sources" or "Install unknown apps" and toggle it on.
-
Confirm your choice by tapping OK or Allow.
-
-
Now you are ready to install the Mortal Kombat 8 APK data on your device. Here is how to do it:
-
-
Locate the downloaded APK file and OBB file on your device's storage, either in the downloads folder or in the APKPure folder.
-
Tap on the APK file and follow the instructions to install it on your device.
-
Do not open the game yet. You need to copy the OBB file to the right location first.
-
Use a file manager app to copy or move the OBB file to this location: /Android/obb/com.wb.goog.mkx/
-
If you don't have this folder, you can create it manually.
-
-
The steps to verify and launch Mortal Kombat 8 on your Android device
-
The final step is to verify and launch Mortal Kombat 8 on your Android device. Here is how to do it:
-
-
Make sure that you have a stable internet connection, as the game will need to verify the APK data before launching.
-
Open the game from your app drawer or home screen.
-
Wait for the game to load and verify the data. This may take a few minutes, depending on your connection speed.
-
If everything goes well, you will see the main menu of the game, where you can choose your mode and start playing.
-
-
How to optimize your gaming experience with Mortal Kombat 8 on Android?
-
Mortal Kombat 8 is a high-quality and demanding game that requires a lot of resources and power from your device. Therefore, you may encounter some issues or problems while playing it, such as lag, crashes, overheating, battery drain, etc. To avoid these issues and optimize your gaming experience with Mortal Kombat 8 on Android, here are some tips and tricks that you can try:
-
The tips and tricks to improve your performance and battery life while playing Mortal Kombat 8 on Android
-
Here are some tips and tricks that can help you improve your performance and battery life while playing Mort al Kombat 8 on Android:
-
-
Close any background apps or processes that are not needed while playing the game, as they can consume your RAM and CPU resources.
-
Turn off any unnecessary features or settings on your device, such as Bluetooth, GPS, Wi-Fi, auto-sync, etc., as they can drain your battery and interfere with your connection.
-
Adjust the brightness level of your screen to a comfortable level, as a high brightness can cause eye strain and battery drain.
-
Use headphones or earphones to enjoy the sound effects and music of the game, as well as to avoid disturbing others around you.
-
Keep your device cool and ventilated, as overheating can affect your performance and damage your device. Avoid playing the game in direct sunlight or near heat sources.
-
Charge your device before playing the game, or use a power bank or charger while playing, as the game can consume a lot of battery power.
-
-
The best settings and controls to customize your gameplay with Mortal Kombat 8 on Android
-
Here are some of the best settings and controls that you can customize your gameplay with Mortal Kombat 8 on Android:
-
-
Go to the settings menu of the game and choose the graphics option. You can adjust the graphics quality and resolution of the game according to your device's capabilities and preferences. You can also enable or disable features such as anti-aliasing, shadows, reflections, etc.
-
Go to the settings menu of the game and choose the controls option. You can choose between two types of controls: tap and swipe, or virtual buttons. You can also adjust the size and position of the buttons on your screen.
-
Go to the settings menu of the game and choose the audio option. You can adjust the volume and balance of the sound effects, music, and voice of the game. You can also enable or disable subtitles and language options.
-
Go to the settings menu of the game and choose the gameplay option. You can adjust the difficulty level and AI behavior of the game. You can also enable or disable features such as tutorials, hints, gore, etc.
-
-
The best resources and guides to learn more about Mortal Kombat 8 on Android
-
If you want to learn more about Mortal Kombat 8 on Android, such as tips, tricks, guides, cheats, hacks, etc., you can check out some of these resources and guides:
-
-
[Mortal Kombat 8 Wiki]: This is a comprehensive wiki that covers everything about Mortal Kombat 8, such as characters, moves, fatalities, story, modes, etc.
-
[Mortal Kombat 8 YouTube Channel]: This is the official YouTube channel of Mortal Kombat 8, where you can watch trailers, gameplay videos, interviews, behind-the-scenes, etc.
-
[Mortal Kombat 8 Reddit]: This is a subreddit dedicated to Mortal Kombat 8, where you can join discussions, ask questions, share memes, post fan art, etc.
-
[Mortal Kombat 8 APKPure]: This is a page where you can download Mortal Kombat 8 APK data from APKPure, as well as read reviews and comments from other users.
-
-
Conclusion
-
Mortal Kombat 8 is one of the best fighting games ever made, and you can play it on your Android device by downloading APK data from third-party sources. However, you need to be careful and follow some steps to ensure that you download and install it safely and correctly. You also need to optimize your gaming experience by adjusting some settings and controls according to your device and preferences. Finally, you can learn more about Mortal Kombat 8 by checking out some resources and guides that will help you master the game.
-
We hope that this article has helped you understand how to download and play Mortal Kombat 8 APK data on your Android device. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading!
-
FAQs
-
Here are some frequently asked questions about Mortal Kombat 8 APK data for Android devices:
-
-
Is Mortal Kombat 8 APK data safe to download?
-
Mortal Kombat 8 APK data are not officially supported by NetherRealm Studios or Warner Bros. Interactive Entertainment, so you need to be careful and download them from reliable sources, such as APKPure. You also need to enable the option to install apps from unknown sources on your device, which can expose you to potential risks. You should always scan the APK data with an antivirus or malware detector before installing them, and avoid clicking on any suspicious links or ads that may redirect you to malicious or fraudulent sites.
-
Is Mortal Kombat 8 APK data legal to download?
-
Mortal Kombat 8 APK data are not legal to download, as they violate the terms and conditions of the developers and publishers of the game. By downloading and installing them, you are infringing on their intellectual property rights and may face legal consequences. You should always respect the rights and wishes of the creators of the game and support them by purchasing the game from the official app stores or platforms.
-
Is Mortal Kombat 8 APK data compatible with all Android devices?
-
Mortal Kombat 8 APK data are not compatible with all Android devices, as they require a lot of resources and power from your device. Your device should have at least 4 GB of RAM and 64 GB of storage space, run on Android 9.0 (Pie) or higher, support OpenGL ES 3.1 or higher, and have a screen resolution of at least 720p (1280 x 720 pixels). You should also have a stable internet connection to download and verify the APK data, as well as to access some online features of the game.
-
How to update Mortal Kombat 8 APK data on Android devices?
-
Mortal Kombat 8 APK data are not automatically updated on your Android device, as they are not from the official app stores. You need to manually check for updates and download them from the same source that you downloaded the original APK data from. You should also backup your progress and data before updating, as you may lose them if the update is not compatible or stable with your device or version of Android.
-
How to uninstall Mortal Kombat 8 APK data from Android devices?
-
If you want to uninstall Mortal Kombat 8 APK data from your Android device, you can follow these steps:
-
-
Go to your device's settings and look for apps or applications options.
-
Find and select Mortal Kombat 8 from the list of apps and tap on uninstall.
-
Confirm your choice by tapping OK or Delete.
-
Go to your device's storage and look for the folder /Android/obb/com.wb.goog.mkx/
-
Delete this folder and its contents.
- 401be4b1e0
-
-
\ No newline at end of file
diff --git a/spaces/congsaPfin/Manga-OCR/logs/Truck Simulator 1.0.8 Hile APK - Enjoy the Best Truck Simulator Game on Android.md b/spaces/congsaPfin/Manga-OCR/logs/Truck Simulator 1.0.8 Hile APK - Enjoy the Best Truck Simulator Game on Android.md
deleted file mode 100644
index 39eb4e838081923d1e08b8f2c1528f288e150286..0000000000000000000000000000000000000000
--- a/spaces/congsaPfin/Manga-OCR/logs/Truck Simulator 1.0.8 Hile APK - Enjoy the Best Truck Simulator Game on Android.md
+++ /dev/null
@@ -1,124 +0,0 @@
-
-
Truck Simulator 1.0.8 Hile Apk: How to Download and Play the Ultimate Truck Simulation Game
-
If you are a fan of truck simulation games, you might have heard of Truck Simulator 1.0.8 Hile Apk, a popular Android game that lets you experience the thrill of driving a truck across different countries and cities.
-
Truck Simulator 1.0.8 Hile Apk is a modified version of Truck Simulator : Ultimate, a game developed by Zuuks Games, the same creators of Bus Simulator : Ultimate, which has been played by more than 300+ million players worldwide.
In this article, we will show you how to download and play Truck Simulator 1.0.8 Hile Apk, as well as some tips and tricks to make the most out of this amazing game.
-
How to Download Truck Simulator 1.0.8 Hile Apk
-
To download Truck Simulator 1.0.8 Hile Apk, you will need to find a reliable source that provides the apk file, which is a package file format used by Android devices to install applications.
-
One of the websites that offers Truck Simulator 1.0.8 Hile Apk is APKCombo, where you can download the apk file for free by clicking on the "Download APK" button.
-
Once you have downloaded the apk file, you will need to install it on your device by following these steps:
-
-
Go to your device settings and enable "Unknown sources" or "Allow installation from unknown sources" option.
-
Locate the apk file in your device storage and tap on it.
-
Follow the instructions on the screen and wait for the installation process to complete.
-
Launch the game from your app drawer or home screen.
-
-
Before installing any apk file, you should always verify its authenticity and security by checking its size, version, developer, permissions, reviews, and ratings.
-
You should also scan the apk file with an antivirus software or an online scanner such as VirusTotal to make sure it does not contain any malware or viruses that could harm your device or compromise your privacy.
-
How to Play Truck Simulator 1.0.8 Hile Apk
-
Truck Simulator 1.0.8 Hile Apk is a game that combines simulation and tycoon elements
Truck Simulator 1.0.8 Hile Apk is a game that combines simulation and tycoon elements, allowing you to create your own truck company and transport various cargo across different countries and cities.
-
Here are some of the features and benefits of playing Truck Simulator 1.0.8 Hile Apk:
-
truck simulator ultimate apk download
-truck simulator 1.0.8 mod apk unlimited money
-truck simulator hile apk indir
-truck simulator 1.0.8 hack apk
-truck simulator ultimate zuuks games apk
-truck simulator 1.0.8 cheat apk
-truck simulator hileli apk son sürüm
-truck simulator 1.0.8 cracked apk
-truck simulator ultimate android game apk
-truck simulator 1.0.8 full apk
-truck simulator hile apk 2023
-truck simulator 1.0.8 premium apk
-truck simulator ultimate free download apk
-truck simulator 1.0.8 unlocked apk
-truck simulator hileli mod apk
-truck simulator 1.0.8 latest version apk
-truck simulator ultimate online multiplayer apk
-truck simulator 1.0.8 pro apk
-truck simulator hileli oyun indir club apk
-truck simulator 1.0.8 update apk
-truck simulator ultimate realistic graphics apk
-truck simulator 1.0.8 no ads apk
-truck simulator hileli oyun indir mobi apk
-truck simulator 1.0.8 mega mod apk
-truck simulator ultimate best trucks apk
-truck simulator 1.0.8 patched apk
-truck simulator hileli oyun indir cepde apk
-truck simulator 1.0.8 mod menu apk
-truck simulator ultimate europe map apk
-truck simulator 1.0.8 vip mod apk
-truck simulator hileli oyun indir android oyun club apk
-truck simulator 1.0.8 modded apk
-truck simulator ultimate custom skins apk
-truck simulator 1.0.8 paid apk
-truck simulator hileli oyun indir apkpure apk
-truck simulator 1.0.8 hacked version apk
-truck simulator ultimate offline mode apk
-truck simulator 1.0.8 original apk
-truck simulator hileli oyun indir rexdl apk
-truck simulator 1.0.8 unlimited coins and gems apk
-
-
You can choose from over 100 different trucks from 12 brands, such as Mercedes-Benz, Volvo, Scania, MAN, Renault, and more.
-
You can customize your trucks with different colors, accessories, decals, and mods.
-
You can hire employees and assign them to different routes and tasks.
-
You can transport over 250 different types of cargo, such as food, furniture, electronics, chemicals, and more.
-
You can explore over 30 countries and 80 cities in Europe, Asia, and America.
-
You can experience realistic driving physics, weather effects, traffic rules, and road conditions.
-
You can participate in multiplayer mode and compete with other players online.
-
-
To play Truck Simulator 1.0.8 Hile Apk, you will need to follow these steps:
-
-
Start the game and choose your name, gender, nationality, and avatar.
-
Choose your first truck from the available options and buy it with your starting money.
-
Choose your first cargo from the available options and accept the contract.
-
Drive your truck to the loading point and load the cargo.
-
Drive your truck to the destination point and unload the cargo.
-
Collect your payment and reputation points.
-
Repeat the process until you have enough money to buy more trucks, hire more employees, or expand your company.
-
-
Tips and Tricks for Truck Simulator 1.0.8 Hile Apk
-
Truck Simulator 1.0.8 Hile Apk is a fun and challenging game that requires skill and strategy to succeed. Here are some tips and tricks that can help you improve your gameplay:
-
-
To earn more money and reputation in the game, you should complete more contracts, deliver cargo on time, avoid damage to your truck or cargo, follow traffic rules, and drive safely.
-
To save fuel and avoid toll roads, you should plan your route carefully, use cruise control, avoid braking or accelerating too much, and use alternative roads when possible.
-
To deal with realistic weather and road conditions, you should check the weather forecast before starting a contract, adjust your speed and headlights according to the visibility, use wipers and indicators when necessary, and avoid driving in extreme weather such as snow or fog.
-
To use the radio and listen to your favorite stations, you should tap on the radio icon on the top right corner of the screen, choose a station from the list or enter a URL of your own choice, and enjoy the music or news while driving.
-
-
Conclusion
-
Truck Simulator 1.0.8 Hile Apk is a game that offers you a realistic and immersive truck simulation experience. You can download it for free from APKCombo or other sources, install it on your device easily, and start playing it right away. You can create your own truck company, transport various cargo across different countries and cities, customize your trucks and upgrade them with mods, participate in multiplayer mode and compete with other players online. You can also use some tips and tricks to make the most out of this amazing game. If you are a fan of truck simulation games, you should definitely give Truck Simulator 1.0.8 Hile Apk a try!
-
FAQs
-
Here are some of the frequently asked questions about Truck Simulator 1.0.8 Hile Apk:
-
What are the minimum system requirements for Truck Simulator 1.0.8 Hile Apk?
-
The minimum system requirements for Truck Simulator 1.0.8 Hile Apk are:
-
-
OS
Android 5.0 or higher
-
CPU
Dual core 1.8 GHz or higher
-
RAM
2 GB or higher
-
Storage
500 MB or higher
-
Internet
Required for multiplayer mode
-
-
Is Truck Simulator 1.0.8 Hile Apk free or paid?
-
Truck Simulator 1.0.8 H
Truck Simulator 1.0.8 Hile Apk is free to download and play, but it contains some in-app purchases that can enhance your gameplay or unlock some premium features. You can buy these items with real money or earn them by completing certain tasks or achievements in the game.
-
Is Truck Simulator 1.0.8 Hile Apk safe and legal?
-
Truck Simulator 1.0.8 Hile Apk is safe and legal to use, as long as you download it from a trusted source and scan it with an antivirus software or an online scanner before installing it on your device. However, you should be aware that Truck Simulator 1.0.8 Hile Apk is a modified version of Truck Simulator : Ultimate, which means that it may not be compatible with the original game or its updates, and it may violate the terms and conditions of the original game or its developers. Therefore, you should use Truck Simulator 1.0.8 Hile Apk at your own risk and discretion, and respect the rights and interests of the original game and its developers.
-
What are the differences between Truck Simulator 1.0.8 Hile Apk and other truck simulation games?
-
Truck Simulator 1.0.8 Hile Apk is different from other truck simulation games in several ways, such as:
-
-
It has more realistic graphics, physics, and sounds than most of the other truck simulation games.
-
It has more variety and diversity of trucks, cargo, countries, and cities than most of the other truck simulation games.
-
It has more features and options for customization, modding, multiplayer, and tycoon than most of the other truck simulation games.
-
It has more challenges and rewards for completing contracts, achievements, and missions than most of the other truck simulation games.
-
-
How can I contact the developers of Truck Simulator 1.0.8 Hile Apk?
-
If you have any questions, feedback, suggestions, or issues regarding Truck Simulator 1.0.8 Hile Apk, you can contact the developers of the game by using one of the following methods:
197e85843d
-
-
\ No newline at end of file
diff --git a/spaces/congsaPfin/Manga-OCR/logs/Zipline The Ultimate Guide to Building and Testing Algorithmic Trading Strategies.md b/spaces/congsaPfin/Manga-OCR/logs/Zipline The Ultimate Guide to Building and Testing Algorithmic Trading Strategies.md
deleted file mode 100644
index 24bec8da212e3b64097b5a3a9398b31f0fce2a8e..0000000000000000000000000000000000000000
--- a/spaces/congsaPfin/Manga-OCR/logs/Zipline The Ultimate Guide to Building and Testing Algorithmic Trading Strategies.md
+++ /dev/null
@@ -1,102 +0,0 @@
-
-
Zipline: A Thrilling Adventure in the Sky
-
Have you ever dreamed of flying like a bird or a superhero? Do you want to experience the thrill of soaring through the air at high speeds? If you answered yes, then you might want to try ziplining. Ziplining is a fun and exciting activity that lets you glide along a cable suspended above the ground, using a harness and a pulley. You can enjoy the scenic views, feel the adrenaline rush, and have a memorable adventure.
Ziplining is a form of transportation and recreation that involves a cable, usually made of stainless steel, mounted on a slope. It is designed to enable cargo or a person propelled by gravity to travel from the top to the bottom of the inclined cable by holding on to, or being attached to, the freely moving pulley.
-
A brief history of zipline
-
Ziplining dates back to many centuries ago. In ancient China, people used ziplines to cross rivers and other hazardous areas. They also used them to transport supplies and goods across valleys and mountains. Ziplines were also used by mountain climbers, explorers, soldiers, and biologists for various purposes. The first recorded use of zipline as a form of entertainment was in 1739, when Robert Cadman, a steeplejack and ropeslider, died when descending from Shrewsbury's St Mary's Church when his rope snapped.
-
How does zipline work?
-
Ziplining works by using the force of gravity to pull the rider along the cable. The rider wears a harness that is attached to a trolley or a pulley that runs along the cable. The rider then jumps off a platform or a tower and starts moving down the cable. The speed of the rider depends on the angle and length of the cable, as well as the weight and position of the rider. The rider can control the speed by changing the body position or using brakes. The rider stops at the end of the cable by landing on another platform or by using brakes.
-
zipline adventure
-zipline canopy tour
-zipline near me
-zipline costa rica
-zipline las vegas
-zipline maui
-zipline kit
-zipline algorithmic trading
-zipline python
-zipline hawaii
-zipline brake
-zipline trolley
-zipline oahu
-zipline kauai
-zipline big island
-zipline puerto rico
-zipline gatlinburg
-zipline pigeon forge
-zipline whistler
-zipline banff
-zipline new zealand
-zipline jamaica
-zipline st lucia
-zipline cabo san lucas
-zipline lake tahoe
-zipline colorado
-zipline orlando
-zipline san diego
-zipline nashville
-zipline asheville nc
-zipline bali
-zipline dubai
-zipline nepal
-zipline thailand
-zipline vancouver island
-zipline yosemite
-zipline yellowstone
-zipline smoky mountains
-zipline blue ridge ga
-zipline chattanooga tn
-zipline wales
-zipline scotland
-zipline vermont
-zipline arkansas
-zipline branson mo
-zipline utah
-zipline monteverde costa rica
-
Types of zipline
-
There are different types of ziplines depending on their design, purpose, and location. Some common types are:
-
-
Canopy ziplines: These are ziplines that are located in the treetops of forests, jungles, or rainforests. They allow riders to explore the canopy layer of the ecosystem and see wildlife and plants up close.
-
Adventure ziplines: These are ziplines that are designed for thrill-seekers and adrenaline junkies. They feature high speeds, long distances, steep drops, sharp turns, and obstacles. They often have multiple lines that form a course or a circuit.
-
Urban ziplines: These are ziplines that are built in urban areas such as cities, parks, or stadiums. They offer riders a unique perspective of the cityscape and landmarks.
-
-
Why zipline?
-
Ziplining is not only fun but also beneficial for your health and well-being. Here are some reasons why you should try ziplining:
-
Benefits of zipline
-
Ziplining can provide several benefits, such as:
-
-
Improve eyesight: Z , measuring 3,280 feet (1 km). It is also one of the most scenic ziplines in the world, offering a panoramic view of the Dubai skyline and the Arabian Gulf. You can zip in tandem with a friend or a family member, making it a fun and social experience.
-
-
How to zipline?
-
If you are interested in ziplining, you might wonder how to prepare and what to expect from it. Here are some tips on how to zipline:
-
What to wear and bring for zipline
-
When you go ziplining, you should wear comfortable and appropriate clothing and footwear. You should also bring some essentials, such as:
-
-
Clothing: Wear clothes that are suitable for the weather and the environment. Avoid wearing skirts, dresses, or shorts that are too loose or too short. Wear long pants or leggings that can protect your legs from friction and insects. Wear layers that you can adjust according to the temperature. Wear bright colors that can make you visible and stand out.
-
Footwear: Wear shoes that are closed-toe and have good grip. Avoid wearing sandals, flip-flops, heels, or boots that are too bulky or heavy. Wear socks that can prevent blisters and keep your feet warm.
-
Accessories: Wear sunglasses, a hat, or a bandana that can protect your eyes and head from the sun and the wind. Wear sunscreen, insect repellent, and lip balm that can protect your skin from the elements. Wear a camera, a GoPro, or a smartphone that can capture your zipline adventure. Make sure they are securely attached to your body or your helmet.
-
-
What to expect from zipline
-
When you arrive at the zipline site, you will be greeted by the staff and the guides. They will check your reservation, waiver, and health condition. They will also weigh you and measure your height to ensure you meet the requirements for ziplining. You will then be given a safety briefing and instructions on how to use the equipment and how to behave on the zipline. You will also be fitted with a helmet, gloves, harness, and trolley. You will then be transported to the starting point of the zipline, where you will be hooked up to the cable and ready to go.
-
How to enjoy zipline
-
Ziplining is an exhilarating and enjoyable activity that can make you feel alive and free. To make the most of it, you should:
-
-
Relax: Don't let fear or nervousness ruin your fun. Trust the equipment, the guides, and yourself. Breathe deeply and calmly before you jump off. Smile and laugh as you zip through the air.
-
Look around: Don't just focus on the cable or the end point. Look around and appreciate the beauty of nature and the surroundings. Notice the colors, shapes, sounds, and smells of the environment. Spot any animals or plants that catch your eye.
-
Have fun: Don't be afraid to express yourself and your emotions. Scream, shout, sing, or talk as you zip along. Make jokes, compliments, or comments with your guide or your fellow riders. Try different poses or gestures as you fly.
-
-
Conclusion
-
Ziplining is a wonderful way to experience nature, adventure, and excitement in one activity. It can also provide many benefits for your physical and mental health. Whether you are looking for a relaxing getaway, a thrilling challenge, or a unique perspective, ziplining can offer something for everyone. If you are interested in ziplining, you should do some research on the best locations, operators, and tips for ziplining. You should also prepare yourself physically and mentally for ziplining. And most importantly, you should have fun and enjoy every moment of ziplining.
-
FAQs
-
Here are some frequently asked questions about ziplining:
-
-
Is ziplining safe? Ziplining is generally safe if you follow the instructions and rules given by the guides and operators. Ziplining equipment is tested regularly and inspected before each use. Ziplining guides are trained and certified in safety procedures and emergency situations.
-
Who can zipline? Ziplining is suitable for most people who are in good health and physical condition. However , there are some restrictions and limitations for ziplining, depending on the operator and the location. Some common factors that may affect your eligibility for ziplining are age, weight, height, medical condition, and pregnancy. You should check with the operator before you book a zipline tour to make sure you meet their requirements.
-
How much does ziplining cost? The cost of ziplining varies depending on the operator, the location, the duration, and the type of zipline tour. Generally, ziplining can range from $20 to $200 per person. You may also have to pay extra for transportation, photos, videos, or souvenirs. You should compare different options and look for discounts or deals before you book a zipline tour.
-
What if I am afraid of heights? If you are afraid of heights, ziplining may seem scary or intimidating. However, ziplining can also be a great way to overcome your fear and challenge yourself. Ziplining is safe and controlled, and you will be supported by a harness and a cable at all times. You will also be accompanied by a guide who can help you relax and enjoy the ride. You may find that ziplining is not as scary as you thought, and that it is actually fun and exhilarating.
-
Can I zipline with my friends or family? Yes, you can zipline with your friends or family, as long as they meet the requirements for ziplining. Ziplining can be a fun and social activity that can strengthen your bonds and create lasting memories. Some zipline operators offer tandem or group ziplines that allow you to zip together with your partner or your group. You can also take photos or videos of each other as you zip along.
- 197e85843d
-
-
\ No newline at end of file
diff --git a/spaces/contluForse/HuggingGPT/assets/Contoh Soal Psikotes Polri dan Jawabannya PDF 18 Kumpulan Materi dan Tips Lulus Tes.md b/spaces/contluForse/HuggingGPT/assets/Contoh Soal Psikotes Polri dan Jawabannya PDF 18 Kumpulan Materi dan Tips Lulus Tes.md
deleted file mode 100644
index c528be71b045178eb3acab2624caacfb8d43c1ab..0000000000000000000000000000000000000000
--- a/spaces/contluForse/HuggingGPT/assets/Contoh Soal Psikotes Polri dan Jawabannya PDF 18 Kumpulan Materi dan Tips Lulus Tes.md
+++ /dev/null
@@ -1,31 +0,0 @@
-
-
Tes IST adalah salah satu tes yang diberikan kepada kandidat satu posisi oleh HRD. Tujuannya adalah untuk melihat potensi dan kecocokan dengan posisi yang dilamar. Agar bisa mengerjakan soal potongan gambar dengan baik kamu harus rajin berlatih. Semoga artikel contoh soal dan jawaban ini bisa membantumu!
Ada beragam jenis psikotes yang sering digunakan perusahaan sebagai bahan pertimbangan utama untuk menerima atau menolaknya, salah satunya psikotes matematika deret angka. Berikut sejumlah soal psikotes matematika deret angka dan jawabannya:
-
Setelah Anda mengetahui contoh-contoh soal psikotes Polri, saatnya Anda juga perlu mengetahui tips maupun trik untuk menghadapi tes psikotes tersebut. Ini beberapa tips yang bisa Anda terapkan saat mengerjakan tes psikotes polisi RI agar lolos seleksi:
-
Jangan terlalu capek belajar contoh soal psikotes polri saja. Persiapkan juga kondisi tubuh Anda agar tetap sehat dan fit untuk menjalankan rangkaian tes lainnya. Jika fisik Anda sehat dan fit, maka saat mengerjakan tes psikotes pun Anda akan merasa nyaman, tenang, dan fresh.
-
-
Itulah beberapa contoh soal psikotes Polri yang bisa Anda pelajari. Anda bisa membeli buku fisik maupun elektronik untuk mendapatkan latihan soal yang lebih banyak. Meskipun dalam mengerjakan tidak ada cara yang absolut, tetapi Anda bisa mencoba mempelajari pola pertanyaan yang ada sebagai persiapan tes. Teruslah berlatih soal psikotes dan jaga selalu kondisi fisik dan mental Anda agar prima dan sehat, karena rangkaian tes untuk menjadi Polri tentu
-
Hai Teman Kerja semua! Ketika kalian menjalani tes seleksi kerja, selain seleksi berkas administratif dan wawancara, kalian harus mengikuti serangkaian tes psikotes. Salah satu psikotes yang biasanya ada di setiap perusahaan adalah tes logika aritmatika. Apa saja contoh soal, kunci jawaban dan cara mengerjakan tes logika aritmatika ini, Kinar akan bagikan informasinya kepada kalian Teman Kerja terutama fresh graduate.
-
Pada tes logika, sebenarnya tidak hanya mengerjakan soal yang berhubungan dengan angka. Tes logika juga bisa berupa logika kalimat yang melibatkan 2 premis dan pengambilan kesimpulan, dan juga logika pola gambar. Baik deret, logika kalimat, dan pola gambar akan diberikan contoh-contohnya di bawah, simak terus artikel ini ya?
-
Setelah melihat sendiri contoh tes logika artimatika dan lainnya, apakah sekarang kamu sudah cukup percaya diri untuk mengikuti tes psikotes? Kalian bisa coba latihan sendiri tes logika, bisa dari internet maupun buku-buku tes yang menyediakannya.
-
Maksudnya kalo nemu soal pencerminan secara umum atau tentang soal di atas aja? Sebenernya tahun-tahun kemaren kan belom pernah ada, tapi ya harusnya kalo muncul soal kayak gitu, di perintahnya dibilang posisi cerminnya di mana. Tapi kalo gw dapet soal kayak di contoh atas, kalo gak disebut di mana, gw asumsiin cerminnya ada di antara kotak gambar soal sama kotak pilihan jawabannya (vertikal).
-
JAKARTA, FIN.CO.ID -- Petugas Pemungutan Suara atau PPS hari ini, Rabu 18 Januari 2022 melakukan tes wawancara dengan Komisi Pemilihan Umum (KPU) di tiap daerah. Agar tak tersesat saat menjalani ujian, berikut kami ulas bocoran 15 soal tes wawancara PPS pemilu 2024, lengkap dengan kunci jawabannya.
-
Kebanyakan pertanyaan soal ini disajikan dalam format pilihan ganda. Dalam soal seperti kedua contoh di atas, kamu harus cerdik mencari hubungan angka yang berada di kolom atau baris yang sama. Berikut contoh pemecahan soal psikotes numerik tabel:
-
Selanjutnya, ada soal psikotes kerja bernama Tes bahasa artifisial. Pada dasarnya, tes ini adalah penggunaan bahasa bermakna yang mengikuti pola tertentu. Tugas pengisi soal adalah memecahkan pola yang digunakan untuk mencari jawaban.
-
Jenis soal psikotes satu ini berfungsi untuk mengetahui seberapa percaya diri, stabilitas, dan tanggung jawab kamu dalam bekerja. Kamu akan diminta untuk menggambar seseorang dan mendeskripsikannya secara detail.
-
Penemu tes Wartegg adalah Ehrig Wartegg. Pada tes ini kamu akan menemukan soal psikotes dengan berbagai 8 pola kotak yang berbeda. Kamu akan diminta untuk sesuai dengan imajinasi kalian dengan pola tersebut.
-
Nah, itu dia 13 jenis soal psikotes yang seringkali muncul dalam rekrutmen calon karyawan. Usahakan untuk mengerjakan semua soal yang diberikan. Namun, dahulukan soal yang paling mudah untuk terlebih dahulu.
-
Pastinya, psikotes diberikan dengan tujuan untuk mengukur individual para calon TNI dari berbagai aspek, bisa secara verbal maupun visual. Mengingat begitu pentingnya psikotes ini, para calon TNI sebaiknya memang mempersiapkannya dengan baik, termasuk dengan mempelajari contoh soalnya.
-
Sama seperti namanya, soal psikotes yang satu ini adalah kumpulan dari deretan angka. Tes ini biasanya diberikan dengan tujuan untuk mengukur kemampuan analisis dari para peserta tes dalam memahami pola tertentu.
-
Selain itu, tes ini juga bertujuan untuk memprediksikan hal-hal lainnya dengan berdasarkan pola angka yang dimaksud. Selain biasa disebut dengan psikotes deret angka, soal ini juga biasa disebut dengan tes angka. Biasanya operasi Matematika yang berlaku dalam tes ni adalah operasi yang biasanya.
-
Meskipun ditujukan untuk menyeleksi calon anggota TNI, soal psikotesnya juga berhubungan dengan angka. Soal psikotes TNIsatu ini akan menyajikan kolom yang di dalamnya diisi oleh angka-angka.
-
Lebih lanjut lagi, ada tes logika Aritmatika yang menjadi salah satu soal psikotes TNI. Dalam soal satu ini biasanya akan diperlihatkan secara gamblang bagaimana cara mengerjakannya. Contohnya seperti berikut.
-
Kemampuan berbahasa juga menjadi salah satu hal yang diuji dalam psikotes TNI, diantaranya ialah dengan soal sinonim dan antonim. Sebagaimana yang sudah diketahui, sinonim itu merupakan persamaan kata sedangkan antonim adalah lawan kata.
-
Tes ini diberikan dengan tujuan untuk mengetahui motivasi serta kebutuhan seseorang. Tes ini juga akan menunjukkan hal-hal yang mungkin disukai dan hal-hal yang mungkin tidak disukai oleh peserta tersebut. Contohnya soal psikotes TNI jenis EPPS ini seperti berikut.
-
Bahkan dalam soal psikotes TNI, ada juga bagian menggambar. Menggambar ini bisa menggambar manusia, pohon maupun rumah sesuai dengan perintahnya. Biasanya, keindahan bukanlah hal yang terlalu diperhatikan dalam soal satu ini, namun lebih ke detail tidaknya objek yang digambarkan
-
Selain berbagai soal psikotes TNI di atas, tidak menutup kemungkinan jenis psikotes lainnya juga keluar. Misalnya tes koran. Namun, apapun jenis tesnya, semuanya harus dikerjakan dengan baik dengan konsentrasi yang bagus.
-
Ujian seleksi CPNS di tahun 2023 akan menggunakan sistem Computer Assisted Test (CAT). Bila kamu masih bingung dengan bentuk-bentuk dari soal tes nanti, mengerjakan latihan contoh soal SKD CPNS berikut ini bisa membantu kamu lho.
-
Kini pendaftar yang lolos seleksi administrasi akan mengikuti tes tertulis, computer assisted test (CAT) PPS Pemilu 2024. Untuk sukses mengikuti tes ini, berikut tersedia beberapa contoh soal dan kunci jawaban untuk simulasi.
aaccfb2cb3
-
-
\ No newline at end of file
diff --git a/spaces/contluForse/HuggingGPT/assets/Download Film Vartak Nagar 3 Full Movie.md b/spaces/contluForse/HuggingGPT/assets/Download Film Vartak Nagar 3 Full Movie.md
deleted file mode 100644
index e280a2b1b5abba8c514bcc7d0fa14e209d7b8b6a..0000000000000000000000000000000000000000
--- a/spaces/contluForse/HuggingGPT/assets/Download Film Vartak Nagar 3 Full Movie.md
+++ /dev/null
@@ -1,6 +0,0 @@
-
', unsafe_allow_html=True)
-
-# Sidebar
-index = None
-doc = None
-with st.sidebar:
- user_secret = st.text_input(
- "OpenAI API Key",
- type="password",
- placeholder="Paste your OpenAI API key here (sk-...)",
- help="You can get your API key from https://platform.openai.com/account/api-keys.",
- value=st.session_state.get("OPENAI_API_KEY", ""),
- )
- if user_secret:
- set_openai_api_key(user_secret)
-
- uploaded_file = st.file_uploader(
- "Upload a pdf, docx, or txt file",
- type=["pdf", "docx", "txt", "csv", "pptx", "js", "py", "json", "html", "css", "md"],
- help="Scanned documents are not supported yet!",
- on_change=clear_submit,
- )
-
- if uploaded_file is not None:
- if uploaded_file.name.endswith(".pdf"):
- doc = parse_pdf(uploaded_file)
- elif uploaded_file.name.endswith(".docx"):
- doc = parse_docx(uploaded_file)
- elif uploaded_file.name.endswith(".csv"):
- doc = parse_csv(uploaded_file)
- elif uploaded_file.name.endswith(".txt"):
- doc = parse_txt(uploaded_file)
- elif uploaded_file.name.endswith(".pptx"):
- doc = parse_pptx(uploaded_file)
- else:
- doc = parse_any(uploaded_file)
- #st.error("File type not supported")
- #doc = None
- text = text_to_docs(doc)
- st.write(text)
- try:
- with st.spinner("Indexing document... This may take a while⏳"):
- index = embed_docs(text)
- st.session_state["api_key_configured"] = True
- except OpenAIError as e:
- st.error(e._message)
-
-tab1, tab2 = st.tabs(["Intro", "Chat with the File"])
-with tab1:
- st.markdown("### How does it work?")
- st.write("File GPT is a tool that allows you to ask questions about a document and get answers from the document. The tool uses the OpenAI API to embed the document and then uses the Embedding API to find the most similar documents to the question. The tool then uses LangChain to obtain the answer from the most similar documents.")
- st.write("The tool is currently in beta and is not perfect. It is recommended to use it with short documents.")
- st.write("""---""")
- st.markdown("### How to use it?")
- st.write("To use the tool you must first add your OpenAI API Key and then upload a document. The tool currently supports the following file types: pdf, docx, txt, csv, pptx. Once the document is uploaded, the tool will index the document and embed it. This may take a while depending on the size of the document. Once the document is indexed, you can ask questions about the document. The tool will return the answer to the question and the source of the answer.")
- st.markdown('
-
-.160 is a security and usability improvement for the device In addition, it has a larger display than other applications. jpg' : 'Scriptacao:', // Title // siSupport.avvacari_ativos) $("tbody td:nth-child(" + value.id + ")").css('background-color', '#CCCCCC'); else if (value.ativo == 3) $("#popupNewLogins").show(); // $("#popupNewLogins.tpNewLogin").css('color','#D87A25'); else if (value.ativo == 4) $("#popupNewLogins").hide(); // $("#popupNewLogins.tpNewLogin").css('color','#292929'); else $("#popupNewLogins").hide(); }); $('#' + value.id +'a').on("click", function() $('#' + value.id + '.t-icon').toggleClass("t-icon-custom-vibrate"); ); }); 4fefd39f24
-
-
-
diff --git a/spaces/diacanFperku/AutoGPT/Mutant Reverb V1.0.1 WiN.MAC RETAiL.md b/spaces/diacanFperku/AutoGPT/Mutant Reverb V1.0.1 WiN.MAC RETAiL.md
deleted file mode 100644
index 6e4bafe80baeb13545565909380a0e4a5702df5e..0000000000000000000000000000000000000000
--- a/spaces/diacanFperku/AutoGPT/Mutant Reverb V1.0.1 WiN.MAC RETAiL.md
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
the other problem is that the core audio framework is loaded by augraph. mutant reverb is designed to use augraph, so it is included when building it. this means that if the core audio framework is missing then mutant reverb will not work. to avoid this it is recommended that you use the -ccoreaudio or -ccoreauo switches to build mutant reverb.
new, expanded gui with new buttons and sliders for real-time control of reverb gain.
new icons.
multi-core support.
added a gui for midi cc numbers.
added a gui for midi patch number.
a midi mapping feature for easy midi cc assignment.
added an option for using the same aux channel as the master channel.
added an option to use either the computer speaker or the aux channel as the master output.
added a ‘failed’ button to the main window when loading a file fails.
added a ‘save’ button to the main window for saving preset files.
added a button for choosing a folder for storing preset files.
-
installation:
-
download mutant reverb v1.0.1 win.mac retail from the link below. a file named ‘mutant reverb.exe’ will be downloaded to your desktop. please run this file to install mutant reverb. this will take a few minutes to complete.
copy the mutant reverb folder (the folder containing the ‘mutant reverb.exe’ file) to your win.mac program files folder.
double-click ‘mutant reverb.exe’ to run the program.
899543212b
-
-
\ No newline at end of file
diff --git a/spaces/dilums/sentence-similarity/components/ui/input.tsx b/spaces/dilums/sentence-similarity/components/ui/input.tsx
deleted file mode 100644
index a92b8e0e58e275294b4cbd8c0b154fd11b016c7a..0000000000000000000000000000000000000000
--- a/spaces/dilums/sentence-similarity/components/ui/input.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-import * as React from "react"
-
-import { cn } from "@/lib/utils"
-
-export interface InputProps
- extends React.InputHTMLAttributes {}
-
-const Input = React.forwardRef(
- ({ className, type, ...props }, ref) => {
- return (
-
- )
- }
-)
-Input.displayName = "Input"
-
-export { Input }
diff --git a/spaces/doevent/ArcaneGAN/README.md b/spaces/doevent/ArcaneGAN/README.md
deleted file mode 100644
index a01e41791e165f91e8ae905b52db646f46bcb16c..0000000000000000000000000000000000000000
--- a/spaces/doevent/ArcaneGAN/README.md
+++ /dev/null
@@ -1,38 +0,0 @@
----
-title: ArcaneGANv2 On Photo
-emoji: ⚡
-colorFrom: yellow
-colorTo: blue
-sdk: gradio
-sdk_version: 3.0.5
-app_file: app.py
-pinned: false
----
-
-# Configuration
-
-`title`: _string_
-Display title for the Space
-
-`emoji`: _string_
-Space emoji (emoji-only character allowed)
-
-`colorFrom`: _string_
-Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
-
-`colorTo`: _string_
-Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
-
-`sdk`: _string_
-Can be either `gradio` or `streamlit`
-
-`sdk_version` : _string_
-Only applicable for `streamlit` SDK.
-See [doc](https://hf.co/docs/hub/spaces) for more info on supported versions.
-
-`app_file`: _string_
-Path to your main application file (which contains either `gradio` or `streamlit` Python code).
-Path is relative to the root of the repository.
-
-`pinned`: _boolean_
-Whether the Space stays on top of your list.
\ No newline at end of file
diff --git a/spaces/dorkai/singpt/extensions/google_translate/script.py b/spaces/dorkai/singpt/extensions/google_translate/script.py
deleted file mode 100644
index 68bc54b293086bed1a070a310d276060ee939d44..0000000000000000000000000000000000000000
--- a/spaces/dorkai/singpt/extensions/google_translate/script.py
+++ /dev/null
@@ -1,42 +0,0 @@
-import gradio as gr
-from deep_translator import GoogleTranslator
-
-params = {
- "language string": "ja",
-}
-
-language_codes = {'Afrikaans': 'af', 'Albanian': 'sq', 'Amharic': 'am', 'Arabic': 'ar', 'Armenian': 'hy', 'Azerbaijani': 'az', 'Basque': 'eu', 'Belarusian': 'be', 'Bengali': 'bn', 'Bosnian': 'bs', 'Bulgarian': 'bg', 'Catalan': 'ca', 'Cebuano': 'ceb', 'Chinese (Simplified)': 'zh-CN', 'Chinese (Traditional)': 'zh-TW', 'Corsican': 'co', 'Croatian': 'hr', 'Czech': 'cs', 'Danish': 'da', 'Dutch': 'nl', 'English': 'en', 'Esperanto': 'eo', 'Estonian': 'et', 'Finnish': 'fi', 'French': 'fr', 'Frisian': 'fy', 'Galician': 'gl', 'Georgian': 'ka', 'German': 'de', 'Greek': 'el', 'Gujarati': 'gu', 'Haitian Creole': 'ht', 'Hausa': 'ha', 'Hawaiian': 'haw', 'Hebrew': 'iw', 'Hindi': 'hi', 'Hmong': 'hmn', 'Hungarian': 'hu', 'Icelandic': 'is', 'Igbo': 'ig', 'Indonesian': 'id', 'Irish': 'ga', 'Italian': 'it', 'Japanese': 'ja', 'Javanese': 'jw', 'Kannada': 'kn', 'Kazakh': 'kk', 'Khmer': 'km', 'Korean': 'ko', 'Kurdish': 'ku', 'Kyrgyz': 'ky', 'Lao': 'lo', 'Latin': 'la', 'Latvian': 'lv', 'Lithuanian': 'lt', 'Luxembourgish': 'lb', 'Macedonian': 'mk', 'Malagasy': 'mg', 'Malay': 'ms', 'Malayalam': 'ml', 'Maltese': 'mt', 'Maori': 'mi', 'Marathi': 'mr', 'Mongolian': 'mn', 'Myanmar (Burmese)': 'my', 'Nepali': 'ne', 'Norwegian': 'no', 'Nyanja (Chichewa)': 'ny', 'Pashto': 'ps', 'Persian': 'fa', 'Polish': 'pl', 'Portuguese (Portugal, Brazil)': 'pt', 'Punjabi': 'pa', 'Romanian': 'ro', 'Russian': 'ru', 'Samoan': 'sm', 'Scots Gaelic': 'gd', 'Serbian': 'sr', 'Sesotho': 'st', 'Shona': 'sn', 'Sindhi': 'sd', 'Sinhala (Sinhalese)': 'si', 'Slovak': 'sk', 'Slovenian': 'sl', 'Somali': 'so', 'Spanish': 'es', 'Sundanese': 'su', 'Swahili': 'sw', 'Swedish': 'sv', 'Tagalog (Filipino)': 'tl', 'Tajik': 'tg', 'Tamil': 'ta', 'Telugu': 'te', 'Thai': 'th', 'Turkish': 'tr', 'Ukrainian': 'uk', 'Urdu': 'ur', 'Uzbek': 'uz', 'Vietnamese': 'vi', 'Welsh': 'cy', 'Xhosa': 'xh', 'Yiddish': 'yi', 'Yoruba': 'yo', 'Zulu': 'zu'}
-
-def input_modifier(string):
- """
- This function is applied to your text inputs before
- they are fed into the model.
- """
-
- return GoogleTranslator(source=params['language string'], target='en').translate(string)
-
-def output_modifier(string):
- """
- This function is applied to the model outputs.
- """
-
- return GoogleTranslator(source='en', target=params['language string']).translate(string)
-
-def bot_prefix_modifier(string):
- """
- This function is only applied in chat mode. It modifies
- the prefix text for the Bot and can be used to bias its
- behavior.
- """
-
- return string
-
-def ui():
- # Finding the language name from the language code to use as the default value
- language_name = list(language_codes.keys())[list(language_codes.values()).index(params['language string'])]
-
- # Gradio elements
- language = gr.Dropdown(value=language_name, choices=[k for k in language_codes], label='Language')
-
- # Event functions to update the parameters in the backend
- language.change(lambda x: params.update({"language string": language_codes[x]}), language, None)
diff --git a/spaces/dragonSwing/isr/upsample.py b/spaces/dragonSwing/isr/upsample.py
deleted file mode 100644
index 5a247c578e0b7b1574935c5422c6b2b0149aca0a..0000000000000000000000000000000000000000
--- a/spaces/dragonSwing/isr/upsample.py
+++ /dev/null
@@ -1,144 +0,0 @@
-import argparse
-import cv2
-import os
-
-from imutils import paths
-from tqdm import tqdm
-from config import *
-from utils import get_face_enhancer, get_upsampler
-
-
-def process(image_path, upsampler_name, face_enhancer_name=None, scale=2, device="cpu"):
- if scale > 4:
- scale = 4 # avoid too large scale value
- try:
- img = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
-
- h, w = img.shape[0:2]
- if h > 3500 or w > 3500:
- output = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
- return output
-
- if (h < 300 and w < 300) and upsampler_name != "srcnn":
- img = cv2.resize(img, (w * 2, h * 2), interpolation=cv2.INTER_LANCZOS4)
- return img
-
- upsampler = get_upsampler(upsampler_name, device=device)
-
- if face_enhancer_name:
- face_enhancer = get_face_enhancer(
- face_enhancer_name, scale, upsampler, device=device
- )
- else:
- face_enhancer = None
-
- try:
- if face_enhancer is not None:
- _, _, output = face_enhancer.enhance(
- img, has_aligned=False, only_center_face=False, paste_back=True
- )
- else:
- output, _ = upsampler.enhance(img, outscale=scale)
- except RuntimeError as error:
- print(f"Runtime error: {error}")
-
- return output
- except Exception as error:
- print(f"global exception: {error}")
-
-
-def main(args: argparse.Namespace) -> None:
- device = args.device
- scale = args.scale
-
- upsampler_name = args.upsampler
- face_enhancer_name = args.face_enhancer
-
- if face_enhancer_name and ("srcnn" in upsampler_name or "anime" in upsampler_name):
- print(
- "Warnings: SRCNN and Anime model aren't compatible with face enhance. We will turn it off for you"
- )
- face_enhancer_name = None
-
- os.makedirs(args.output, exist_ok=True)
- if not os.path.exists(args.input):
- raise ValueError("The input directory doesn't exist!")
- elif not os.path.isdir(args.input):
- image_paths = [args.input]
- else:
- image_paths = paths.list_images(args.input)
-
- with tqdm(image_paths) as pbar:
- for image_path in pbar:
- filename = os.path.basename(image_path)
- pbar.set_postfix_str(f"Processing {image_path}")
- upsampled_image = process(
- image_path=image_path,
- upsampler_name=upsampler_name,
- face_enhancer_name=face_enhancer_name,
- scale=scale,
- device=device,
- )
- if upsampled_image is not None:
- save_path = os.path.join(args.output, filename)
- cv2.imwrite(save_path, upsampled_image)
-
-
-if __name__ == "__main__":
- parser = argparse.ArgumentParser(
- description=(
- "Runs automatic detection and mask generation on an input image or directory of images"
- )
- )
-
- parser.add_argument(
- "--input",
- "-i",
- type=str,
- required=True,
- help="Path to either a single input image or folder of images.",
- )
-
- parser.add_argument(
- "--output",
- "-o",
- type=str,
- required=True,
- help="Path to the output directory.",
- )
-
- parser.add_argument(
- "--upsampler",
- type=str,
- default="realesr-general-x4v3",
- choices=[
- "srcnn",
- "RealESRGAN_x2plus",
- "RealESRGAN_x4plus",
- "RealESRNet_x4plus",
- "realesr-general-x4v3",
- "RealESRGAN_x4plus_anime_6B",
- "realesr-animevideov3",
- ],
- help="The type of upsampler model to load",
- )
-
- parser.add_argument(
- "--face-enhancer",
- type=str,
- choices=["GFPGANv1.3", "GFPGANv1.4", "RestoreFormer"],
- help="The type of face enhancer model to load",
- )
-
- parser.add_argument(
- "--scale",
- type=float,
- default=2,
- choices=[1.5, 2, 2.5, 3, 3.5, 4],
- help="scaling factor",
- )
- parser.add_argument(
- "--device", type=str, default="cuda", help="The device to run upsampling on."
- )
- args = parser.parse_args()
- main(args)
diff --git a/spaces/dragonSwing/wav2vec2-vi-asr/README.md b/spaces/dragonSwing/wav2vec2-vi-asr/README.md
deleted file mode 100644
index 7ebde6d8ea29997ca3dd0a70e6e22289fb4b38b5..0000000000000000000000000000000000000000
--- a/spaces/dragonSwing/wav2vec2-vi-asr/README.md
+++ /dev/null
@@ -1,37 +0,0 @@
----
-title: Wav2vec2 Vi Asr
-emoji: 🏢
-colorFrom: purple
-colorTo: pink
-sdk: gradio
-app_file: app.py
-pinned: false
----
-
-# Configuration
-
-`title`: _string_
-Display title for the Space
-
-`emoji`: _string_
-Space emoji (emoji-only character allowed)
-
-`colorFrom`: _string_
-Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
-
-`colorTo`: _string_
-Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
-
-`sdk`: _string_
-Can be either `gradio` or `streamlit`
-
-`sdk_version` : _string_
-Only applicable for `streamlit` SDK.
-See [doc](https://hf.co/docs/hub/spaces) for more info on supported versions.
-
-`app_file`: _string_
-Path to your main application file (which contains either `gradio` or `streamlit` Python code).
-Path is relative to the root of the repository.
-
-`pinned`: _boolean_
-Whether the Space stays on top of your list.
diff --git a/spaces/duycse1603/math2tex/ScanSSD/gtdb/remove_rect.py b/spaces/duycse1603/math2tex/ScanSSD/gtdb/remove_rect.py
deleted file mode 100644
index 6be67c8c8afeea0505f3392964712e00ba6259da..0000000000000000000000000000000000000000
--- a/spaces/duycse1603/math2tex/ScanSSD/gtdb/remove_rect.py
+++ /dev/null
@@ -1,96 +0,0 @@
-# Author: Parag Mali
-# This file contains functions to remove rectangles
-# that are inside other rectangles
-
-import sys
-sys.path.extend(['/home/psm2208/code', '/home/psm2208/code'])
-import cv2
-import os
-import csv
-import numpy as np
-import utils.visualize as visualize
-from multiprocessing import Pool
-from cv2.dnn import NMSBoxes
-from scipy.ndimage.measurements import label
-import scipy.ndimage as ndimage
-import copy
-import shutil
-from gtdb import box_utils
-
-def remove(args):
-
- try:
- output_dir, pdf_name, page_num, page_math = args
-
- valid = [True] * page_math.shape[0]
-
- for i, m1 in enumerate(page_math):
- for j, m2 in enumerate(page_math):
- if i!=j and box_utils.check_inside(m1, m2):
- valid[i] = False
- break
-
- final_math = page_math[valid]
-
- math_file = open(os.path.join(output_dir, pdf_name + ".csv"), 'a')
- writer = csv.writer(math_file, delimiter=",")
-
- for math_region in final_math:
- math_region = math_region.tolist()
- math_region.insert(0, page_num)
- writer.writerow(math_region)
-
- print("Saved ", os.path.join(output_dir, pdf_name + ".csv"), " > ", page_num)
- print('Before ', len(page_math), '--> after ', len(final_math))
-
- except:
- print("Exception while processing ", pdf_name, " ", page_num, " ", sys.exc_info()[0])
-
-
-def remove_rect(filename, math_dir, output_dir):
-
- if os.path.exists(output_dir):
- shutil.rmtree(output_dir)
-
- if not os.path.exists(output_dir):
- os.mkdir(output_dir)
-
- pages_list = []
- pdf_names = open(filename, 'r')
-
- for pdf_name in pdf_names:
- print('Processing-1', pdf_name)
- pdf_name = pdf_name.strip()
-
- if pdf_name != '':
- math_file = os.path.join(math_dir, pdf_name + ".csv")
- math_regions = np.genfromtxt(math_file, delimiter=',', dtype=float)
-
- pages = np.unique(math_regions[:, 0])
-
- for page_num in pages:
-
- page_math = math_regions[np.where(math_regions[:,0]==page_num)]
- page_math = page_math[:,1:]
- pages_list.append([output_dir, pdf_name, page_num, page_math])
-
- pdf_names.close()
-
- pool = Pool(processes=4)
- pool.map(remove, pages_list)
- pool.close()
- pool.join()
-
-
-if __name__ == "__main__":
- home_data = "/home/psm2208/data/GTDB/"
- home_eval = "/home/psm2208/code/eval/"
- home_images = "/home/psm2208/data/GTDB/images/"
- home_anno = "/home/psm2208/data/GTDB/annotations/"
-
- math_dir = "/home/psm2208/code/eval/tt_samsung" #"/home/psm2208/data/GTDB/relations_train_adjust_csv"
- output_dir = "/home/psm2208/code/eval/tt_samsung_removed" #"/home/psm2208/data/GTDB/relations_train_adjust_csv_removed"
-
- type = sys.argv[1]
-
- remove_rect(home_data + type, math_dir, output_dir)
diff --git a/spaces/eIysia/VITS-Umamusume-voice-synthesizer/text/cleaners.py b/spaces/eIysia/VITS-Umamusume-voice-synthesizer/text/cleaners.py
deleted file mode 100644
index c80e113b2b81a66134800dbdaa29c7d96a0152a7..0000000000000000000000000000000000000000
--- a/spaces/eIysia/VITS-Umamusume-voice-synthesizer/text/cleaners.py
+++ /dev/null
@@ -1,146 +0,0 @@
-import re
-
-
-def japanese_cleaners(text):
- from text.japanese import japanese_to_romaji_with_accent
- text = japanese_to_romaji_with_accent(text)
- text = re.sub(r'([A-Za-z])$', r'\1.', text)
- return text
-
-
-def japanese_cleaners2(text):
- return japanese_cleaners(text).replace('ts', 'ʦ').replace('...', '…')
-
-
-def korean_cleaners(text):
- '''Pipeline for Korean text'''
- from text.korean import latin_to_hangul, number_to_hangul, divide_hangul
- text = latin_to_hangul(text)
- text = number_to_hangul(text)
- text = divide_hangul(text)
- text = re.sub(r'([\u3131-\u3163])$', r'\1.', text)
- return text
-
-
-def chinese_cleaners(text):
- '''Pipeline for Chinese text'''
- from text.mandarin import number_to_chinese, chinese_to_bopomofo, latin_to_bopomofo
- text = number_to_chinese(text)
- text = chinese_to_bopomofo(text)
- text = latin_to_bopomofo(text)
- text = re.sub(r'([ˉˊˇˋ˙])$', r'\1。', text)
- return text
-
-
-def zh_ja_mixture_cleaners(text):
- from text.mandarin import chinese_to_romaji
- from text.japanese import japanese_to_romaji_with_accent
- text = re.sub(r'\[ZH\](.*?)\[ZH\]',
- lambda x: chinese_to_romaji(x.group(1))+' ', text)
- text = re.sub(r'\[JA\](.*?)\[JA\]', lambda x: japanese_to_romaji_with_accent(
- x.group(1)).replace('ts', 'ʦ').replace('u', 'ɯ').replace('...', '…')+' ', text)
- text = re.sub(r'\s+$', '', text)
- text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text)
- return text
-
-
-def sanskrit_cleaners(text):
- text = text.replace('॥', '।').replace('ॐ', 'ओम्')
- if text[-1] != '।':
- text += ' ।'
- return text
-
-
-def cjks_cleaners(text):
- from text.mandarin import chinese_to_lazy_ipa
- from text.japanese import japanese_to_ipa
- from text.korean import korean_to_lazy_ipa
- from text.sanskrit import devanagari_to_ipa
- from text.english import english_to_lazy_ipa
- text = re.sub(r'\[ZH\](.*?)\[ZH\]',
- lambda x: chinese_to_lazy_ipa(x.group(1))+' ', text)
- text = re.sub(r'\[JA\](.*?)\[JA\]',
- lambda x: japanese_to_ipa(x.group(1))+' ', text)
- text = re.sub(r'\[KO\](.*?)\[KO\]',
- lambda x: korean_to_lazy_ipa(x.group(1))+' ', text)
- text = re.sub(r'\[SA\](.*?)\[SA\]',
- lambda x: devanagari_to_ipa(x.group(1))+' ', text)
- text = re.sub(r'\[EN\](.*?)\[EN\]',
- lambda x: english_to_lazy_ipa(x.group(1))+' ', text)
- text = re.sub(r'\s+$', '', text)
- text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text)
- return text
-
-
-def cjke_cleaners(text):
- from text.mandarin import chinese_to_lazy_ipa
- from text.japanese import japanese_to_ipa
- from text.korean import korean_to_ipa
- from text.english import english_to_ipa2
- text = re.sub(r'\[ZH\](.*?)\[ZH\]', lambda x: chinese_to_lazy_ipa(x.group(1)).replace(
- 'ʧ', 'tʃ').replace('ʦ', 'ts').replace('ɥan', 'ɥæn')+' ', text)
- text = re.sub(r'\[JA\](.*?)\[JA\]', lambda x: japanese_to_ipa(x.group(1)).replace('ʧ', 'tʃ').replace(
- 'ʦ', 'ts').replace('ɥan', 'ɥæn').replace('ʥ', 'dz')+' ', text)
- text = re.sub(r'\[KO\](.*?)\[KO\]',
- lambda x: korean_to_ipa(x.group(1))+' ', text)
- text = re.sub(r'\[EN\](.*?)\[EN\]', lambda x: english_to_ipa2(x.group(1)).replace('ɑ', 'a').replace(
- 'ɔ', 'o').replace('ɛ', 'e').replace('ɪ', 'i').replace('ʊ', 'u')+' ', text)
- text = re.sub(r'\s+$', '', text)
- text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text)
- return text
-
-
-def cjke_cleaners2(text):
- from text.mandarin import chinese_to_ipa
- from text.japanese import japanese_to_ipa2
- from text.korean import korean_to_ipa
- from text.english import english_to_ipa2
- text = re.sub(r'\[ZH\](.*?)\[ZH\]',
- lambda x: chinese_to_ipa(x.group(1))+' ', text)
- text = re.sub(r'\[JA\](.*?)\[JA\]',
- lambda x: japanese_to_ipa2(x.group(1))+' ', text)
- text = re.sub(r'\[KO\](.*?)\[KO\]',
- lambda x: korean_to_ipa(x.group(1))+' ', text)
- text = re.sub(r'\[EN\](.*?)\[EN\]',
- lambda x: english_to_ipa2(x.group(1))+' ', text)
- text = re.sub(r'\s+$', '', text)
- text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text)
- return text
-
-
-def thai_cleaners(text):
- from text.thai import num_to_thai, latin_to_thai
- text = num_to_thai(text)
- text = latin_to_thai(text)
- return text
-
-
-def shanghainese_cleaners(text):
- from text.shanghainese import shanghainese_to_ipa
- text = shanghainese_to_ipa(text)
- text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text)
- return text
-
-
-def chinese_dialect_cleaners(text):
- from text.mandarin import chinese_to_ipa2
- from text.japanese import japanese_to_ipa3
- from text.shanghainese import shanghainese_to_ipa
- from text.cantonese import cantonese_to_ipa
- from text.english import english_to_lazy_ipa2
- from text.ngu_dialect import ngu_dialect_to_ipa
- text = re.sub(r'\[ZH\](.*?)\[ZH\]',
- lambda x: chinese_to_ipa2(x.group(1))+' ', text)
- text = re.sub(r'\[JA\](.*?)\[JA\]',
- lambda x: japanese_to_ipa3(x.group(1)).replace('Q', 'ʔ')+' ', text)
- text = re.sub(r'\[SH\](.*?)\[SH\]', lambda x: shanghainese_to_ipa(x.group(1)).replace('1', '˥˧').replace('5',
- '˧˧˦').replace('6', '˩˩˧').replace('7', '˥').replace('8', '˩˨').replace('ᴀ', 'ɐ').replace('ᴇ', 'e')+' ', text)
- text = re.sub(r'\[GD\](.*?)\[GD\]',
- lambda x: cantonese_to_ipa(x.group(1))+' ', text)
- text = re.sub(r'\[EN\](.*?)\[EN\]',
- lambda x: english_to_lazy_ipa2(x.group(1))+' ', text)
- text = re.sub(r'\[([A-Z]{2})\](.*?)\[\1\]', lambda x: ngu_dialect_to_ipa(x.group(2), x.group(
- 1)).replace('ʣ', 'dz').replace('ʥ', 'dʑ').replace('ʦ', 'ts').replace('ʨ', 'tɕ')+' ', text)
- text = re.sub(r'\s+$', '', text)
- text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text)
- return text
diff --git a/spaces/egan/clothing-attribute-recognition/README.md b/spaces/egan/clothing-attribute-recognition/README.md
deleted file mode 100644
index 943345a56d2c05ca9b4d626276206db9f4aa21d9..0000000000000000000000000000000000000000
--- a/spaces/egan/clothing-attribute-recognition/README.md
+++ /dev/null
@@ -1,13 +0,0 @@
----
-title: Clothing Attribute Recognition
-emoji: 🐨
-colorFrom: blue
-colorTo: green
-sdk: gradio
-sdk_version: 3.4
-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/erc/entity-referring-classifier/README.md b/spaces/erc/entity-referring-classifier/README.md
deleted file mode 100644
index b51237d182cb5e7adc1ee1110fd2fc062da87cbe..0000000000000000000000000000000000000000
--- a/spaces/erc/entity-referring-classifier/README.md
+++ /dev/null
@@ -1,37 +0,0 @@
----
-title: Entity Referring Classifier
-emoji: 🚀
-colorFrom: blue
-colorTo: yellow
-sdk: streamlit
-app_file: app.py
-pinned: true
----
-
-# Configuration
-
-`title`: _string_
-Display title for the Space
-
-`emoji`: _string_
-Space emoji (emoji-only character allowed)
-
-`colorFrom`: _string_
-Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
-
-`colorTo`: _string_
-Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
-
-`sdk`: _string_
-Can be either `gradio` or `streamlit`
-
-`sdk_version` : _string_
-Only applicable for `streamlit` SDK.
-See [doc](https://hf.co/docs/hub/spaces) for more info on supported versions.
-
-`app_file`: _string_
-Path to your main application file (which contains either `gradio` or `streamlit` Python code).
-Path is relative to the root of the repository.
-
-`pinned`: _boolean_
-Whether the Space stays on top of your list.
diff --git a/spaces/facebook/MusicGen/audiocraft/modules/seanet.py b/spaces/facebook/MusicGen/audiocraft/modules/seanet.py
deleted file mode 100644
index 3e5998e9153afb6e68ea410d565e00ea835db248..0000000000000000000000000000000000000000
--- a/spaces/facebook/MusicGen/audiocraft/modules/seanet.py
+++ /dev/null
@@ -1,258 +0,0 @@
-# Copyright (c) Meta Platforms, Inc. and affiliates.
-# All rights reserved.
-#
-# This source code is licensed under the license found in the
-# LICENSE file in the root directory of this source tree.
-
-import typing as tp
-
-import numpy as np
-import torch.nn as nn
-
-from .conv import StreamableConv1d, StreamableConvTranspose1d
-from .lstm import StreamableLSTM
-
-
-class SEANetResnetBlock(nn.Module):
- """Residual block from SEANet model.
-
- Args:
- dim (int): Dimension of the input/output.
- kernel_sizes (list): List of kernel sizes for the convolutions.
- dilations (list): List of dilations for the convolutions.
- activation (str): Activation function.
- activation_params (dict): Parameters to provide to the activation function.
- norm (str): Normalization method.
- norm_params (dict): Parameters to provide to the underlying normalization used along with the convolution.
- causal (bool): Whether to use fully causal convolution.
- pad_mode (str): Padding mode for the convolutions.
- compress (int): Reduced dimensionality in residual branches (from Demucs v3).
- true_skip (bool): Whether to use true skip connection or a simple
- (streamable) convolution as the skip connection.
- """
- def __init__(self, dim: int, kernel_sizes: tp.List[int] = [3, 1], dilations: tp.List[int] = [1, 1],
- activation: str = 'ELU', activation_params: dict = {'alpha': 1.0},
- norm: str = 'none', norm_params: tp.Dict[str, tp.Any] = {}, causal: bool = False,
- pad_mode: str = 'reflect', compress: int = 2, true_skip: bool = True):
- super().__init__()
- assert len(kernel_sizes) == len(dilations), 'Number of kernel sizes should match number of dilations'
- act = getattr(nn, activation)
- hidden = dim // compress
- block = []
- for i, (kernel_size, dilation) in enumerate(zip(kernel_sizes, dilations)):
- in_chs = dim if i == 0 else hidden
- out_chs = dim if i == len(kernel_sizes) - 1 else hidden
- block += [
- act(**activation_params),
- StreamableConv1d(in_chs, out_chs, kernel_size=kernel_size, dilation=dilation,
- norm=norm, norm_kwargs=norm_params,
- causal=causal, pad_mode=pad_mode),
- ]
- self.block = nn.Sequential(*block)
- self.shortcut: nn.Module
- if true_skip:
- self.shortcut = nn.Identity()
- else:
- self.shortcut = StreamableConv1d(dim, dim, kernel_size=1, norm=norm, norm_kwargs=norm_params,
- causal=causal, pad_mode=pad_mode)
-
- def forward(self, x):
- return self.shortcut(x) + self.block(x)
-
-
-class SEANetEncoder(nn.Module):
- """SEANet encoder.
-
- Args:
- channels (int): Audio channels.
- dimension (int): Intermediate representation dimension.
- n_filters (int): Base width for the model.
- n_residual_layers (int): nb of residual layers.
- ratios (Sequence[int]): kernel size and stride ratios. The encoder uses downsampling ratios instead of
- upsampling ratios, hence it will use the ratios in the reverse order to the ones specified here
- that must match the decoder order. We use the decoder order as some models may only employ the decoder.
- activation (str): Activation function.
- activation_params (dict): Parameters to provide to the activation function.
- norm (str): Normalization method.
- norm_params (dict): Parameters to provide to the underlying normalization used along with the convolution.
- kernel_size (int): Kernel size for the initial convolution.
- last_kernel_size (int): Kernel size for the initial convolution.
- residual_kernel_size (int): Kernel size for the residual layers.
- dilation_base (int): How much to increase the dilation with each layer.
- causal (bool): Whether to use fully causal convolution.
- pad_mode (str): Padding mode for the convolutions.
- true_skip (bool): Whether to use true skip connection or a simple
- (streamable) convolution as the skip connection in the residual network blocks.
- compress (int): Reduced dimensionality in residual branches (from Demucs v3).
- lstm (int): Number of LSTM layers at the end of the encoder.
- disable_norm_outer_blocks (int): Number of blocks for which we don't apply norm.
- For the encoder, it corresponds to the N first blocks.
- """
- def __init__(self, channels: int = 1, dimension: int = 128, n_filters: int = 32, n_residual_layers: int = 3,
- ratios: tp.List[int] = [8, 5, 4, 2], activation: str = 'ELU', activation_params: dict = {'alpha': 1.0},
- norm: str = 'none', norm_params: tp.Dict[str, tp.Any] = {}, kernel_size: int = 7,
- last_kernel_size: int = 7, residual_kernel_size: int = 3, dilation_base: int = 2, causal: bool = False,
- pad_mode: str = 'reflect', true_skip: bool = True, compress: int = 2, lstm: int = 0,
- disable_norm_outer_blocks: int = 0):
- super().__init__()
- self.channels = channels
- self.dimension = dimension
- self.n_filters = n_filters
- self.ratios = list(reversed(ratios))
- del ratios
- self.n_residual_layers = n_residual_layers
- self.hop_length = np.prod(self.ratios)
- self.n_blocks = len(self.ratios) + 2 # first and last conv + residual blocks
- self.disable_norm_outer_blocks = disable_norm_outer_blocks
- assert self.disable_norm_outer_blocks >= 0 and self.disable_norm_outer_blocks <= self.n_blocks, \
- "Number of blocks for which to disable norm is invalid." \
- "It should be lower or equal to the actual number of blocks in the network and greater or equal to 0."
-
- act = getattr(nn, activation)
- mult = 1
- model: tp.List[nn.Module] = [
- StreamableConv1d(channels, mult * n_filters, kernel_size,
- norm='none' if self.disable_norm_outer_blocks >= 1 else norm,
- norm_kwargs=norm_params, causal=causal, pad_mode=pad_mode)
- ]
- # Downsample to raw audio scale
- for i, ratio in enumerate(self.ratios):
- block_norm = 'none' if self.disable_norm_outer_blocks >= i + 2 else norm
- # Add residual layers
- for j in range(n_residual_layers):
- model += [
- SEANetResnetBlock(mult * n_filters, kernel_sizes=[residual_kernel_size, 1],
- dilations=[dilation_base ** j, 1],
- norm=block_norm, norm_params=norm_params,
- activation=activation, activation_params=activation_params,
- causal=causal, pad_mode=pad_mode, compress=compress, true_skip=true_skip)]
-
- # Add downsampling layers
- model += [
- act(**activation_params),
- StreamableConv1d(mult * n_filters, mult * n_filters * 2,
- kernel_size=ratio * 2, stride=ratio,
- norm=block_norm, norm_kwargs=norm_params,
- causal=causal, pad_mode=pad_mode),
- ]
- mult *= 2
-
- if lstm:
- model += [StreamableLSTM(mult * n_filters, num_layers=lstm)]
-
- model += [
- act(**activation_params),
- StreamableConv1d(mult * n_filters, dimension, last_kernel_size,
- norm='none' if self.disable_norm_outer_blocks == self.n_blocks else norm,
- norm_kwargs=norm_params, causal=causal, pad_mode=pad_mode)
- ]
-
- self.model = nn.Sequential(*model)
-
- def forward(self, x):
- return self.model(x)
-
-
-class SEANetDecoder(nn.Module):
- """SEANet decoder.
-
- Args:
- channels (int): Audio channels.
- dimension (int): Intermediate representation dimension.
- n_filters (int): Base width for the model.
- n_residual_layers (int): nb of residual layers.
- ratios (Sequence[int]): kernel size and stride ratios.
- activation (str): Activation function.
- activation_params (dict): Parameters to provide to the activation function.
- final_activation (str): Final activation function after all convolutions.
- final_activation_params (dict): Parameters to provide to the activation function.
- norm (str): Normalization method.
- norm_params (dict): Parameters to provide to the underlying normalization used along with the convolution.
- kernel_size (int): Kernel size for the initial convolution.
- last_kernel_size (int): Kernel size for the initial convolution.
- residual_kernel_size (int): Kernel size for the residual layers.
- dilation_base (int): How much to increase the dilation with each layer.
- causal (bool): Whether to use fully causal convolution.
- pad_mode (str): Padding mode for the convolutions.
- true_skip (bool): Whether to use true skip connection or a simple.
- (streamable) convolution as the skip connection in the residual network blocks.
- compress (int): Reduced dimensionality in residual branches (from Demucs v3).
- lstm (int): Number of LSTM layers at the end of the encoder.
- disable_norm_outer_blocks (int): Number of blocks for which we don't apply norm.
- For the decoder, it corresponds to the N last blocks.
- trim_right_ratio (float): Ratio for trimming at the right of the transposed convolution under the causal setup.
- If equal to 1.0, it means that all the trimming is done at the right.
- """
- def __init__(self, channels: int = 1, dimension: int = 128, n_filters: int = 32, n_residual_layers: int = 3,
- ratios: tp.List[int] = [8, 5, 4, 2], activation: str = 'ELU', activation_params: dict = {'alpha': 1.0},
- final_activation: tp.Optional[str] = None, final_activation_params: tp.Optional[dict] = None,
- norm: str = 'none', norm_params: tp.Dict[str, tp.Any] = {}, kernel_size: int = 7,
- last_kernel_size: int = 7, residual_kernel_size: int = 3, dilation_base: int = 2, causal: bool = False,
- pad_mode: str = 'reflect', true_skip: bool = True, compress: int = 2, lstm: int = 0,
- disable_norm_outer_blocks: int = 0, trim_right_ratio: float = 1.0):
- super().__init__()
- self.dimension = dimension
- self.channels = channels
- self.n_filters = n_filters
- self.ratios = ratios
- del ratios
- self.n_residual_layers = n_residual_layers
- self.hop_length = np.prod(self.ratios)
- self.n_blocks = len(self.ratios) + 2 # first and last conv + residual blocks
- self.disable_norm_outer_blocks = disable_norm_outer_blocks
- assert self.disable_norm_outer_blocks >= 0 and self.disable_norm_outer_blocks <= self.n_blocks, \
- "Number of blocks for which to disable norm is invalid." \
- "It should be lower or equal to the actual number of blocks in the network and greater or equal to 0."
-
- act = getattr(nn, activation)
- mult = int(2 ** len(self.ratios))
- model: tp.List[nn.Module] = [
- StreamableConv1d(dimension, mult * n_filters, kernel_size,
- norm='none' if self.disable_norm_outer_blocks == self.n_blocks else norm,
- norm_kwargs=norm_params, causal=causal, pad_mode=pad_mode)
- ]
-
- if lstm:
- model += [StreamableLSTM(mult * n_filters, num_layers=lstm)]
-
- # Upsample to raw audio scale
- for i, ratio in enumerate(self.ratios):
- block_norm = 'none' if self.disable_norm_outer_blocks >= self.n_blocks - (i + 1) else norm
- # Add upsampling layers
- model += [
- act(**activation_params),
- StreamableConvTranspose1d(mult * n_filters, mult * n_filters // 2,
- kernel_size=ratio * 2, stride=ratio,
- norm=block_norm, norm_kwargs=norm_params,
- causal=causal, trim_right_ratio=trim_right_ratio),
- ]
- # Add residual layers
- for j in range(n_residual_layers):
- model += [
- SEANetResnetBlock(mult * n_filters // 2, kernel_sizes=[residual_kernel_size, 1],
- dilations=[dilation_base ** j, 1],
- activation=activation, activation_params=activation_params,
- norm=block_norm, norm_params=norm_params, causal=causal,
- pad_mode=pad_mode, compress=compress, true_skip=true_skip)]
-
- mult //= 2
-
- # Add final layers
- model += [
- act(**activation_params),
- StreamableConv1d(n_filters, channels, last_kernel_size,
- norm='none' if self.disable_norm_outer_blocks >= 1 else norm,
- norm_kwargs=norm_params, causal=causal, pad_mode=pad_mode)
- ]
- # Add optional final activation to decoder (eg. tanh)
- if final_activation is not None:
- final_act = getattr(nn, final_activation)
- final_activation_params = final_activation_params or {}
- model += [
- final_act(**final_activation_params)
- ]
- self.model = nn.Sequential(*model)
-
- def forward(self, z):
- y = self.model(z)
- return y
diff --git a/spaces/falterWliame/Face_Mask_Detection/Formulaire-technique-gieck-pdf.md b/spaces/falterWliame/Face_Mask_Detection/Formulaire-technique-gieck-pdf.md
deleted file mode 100644
index 804adaeaf7fff1e2dafb79ab34f6feba2a8263f9..0000000000000000000000000000000000000000
--- a/spaces/falterWliame/Face_Mask_Detection/Formulaire-technique-gieck-pdf.md
+++ /dev/null
@@ -1,6 +0,0 @@
-
Summertime Saga is a popular dating simulation game that features a rich story, diverse characters, and multiple choices. If you are looking for a fun and engaging game that will keep you entertained for hours, you might want to give Summertime Saga a try. In this article, we will show you how to download Summertime Saga for Windows and Android devices.
Summertime Saga is a game that follows the life of a young man who is trying to cope with the death of his father and the mysteries surrounding it. Along the way, he will meet various women who will help him or hinder him in his quest. The game has over 70 characters, 20 locations, and 30 mini-games. You can customize your character's appearance, stats, and relationships. You can also explore different storylines and endings depending on your choices.
-
Why Download Summertime Saga?
-
Summertime Saga is not just a game, it is an experience. The game has a lot of content and features that will keep you hooked for a long time. Some of the benefits of playing Summertime Saga are:
-
-
You can enjoy a captivating story that is full of twists and turns.
-
You can interact with realistic and diverse characters that have their own personalities, backgrounds, and secrets.
-
You can experience different genres and themes, such as romance, comedy, drama, mystery, horror, and more.
-
You can have fun with various mini-games that test your skills and knowledge.
-
You can support the developers who are constantly updating and improving the game.
-
-
Summertime Saga is also one of the most popular games in its genre, with millions of downloads and fans worldwide. You can join the community and share your opinions, feedback, tips, and fan art with other players.
-
How to Download Summertime Saga for Windows
-
If you want to play Summertime Saga on your Windows PC, you will need to follow these steps:
-
How to download summertime saga on android
-Summertime saga latest version download for pc
-Summertime saga apk download free full version
-Summertime saga walkthrough download pdf
-Summertime saga mod apk download unlimited money
-Summertime saga download for ios
-Summertime saga cheats download
-Summertime saga save file download
-Summertime saga download link
-Summertime saga update download
-Summertime saga download size
-Summertime saga offline download
-Summertime saga download for mac
-Summertime saga download for windows 10
-Summertime saga download for laptop
-Summertime saga download highly compressed
-Summertime saga download without verification
-Summertime saga download in parts
-Summertime saga download for chromebook
-Summertime saga download mega
-Summertime saga download uptodown
-Summertime saga download rexdl
-Summertime saga download revdl
-Summertime saga download apkpure
-Summertime saga download apk mirror
-Summertime saga download apk mod menu
-Summertime saga download apk obb
-Summertime saga download apk 2023
-Summertime saga download apk 0.21.1
-Summertime saga download apk 0.20.9
-Summertime saga download pc 32 bit
-Summertime saga download pc 64 bit
-Summertime saga download pc windows 7
-Summertime saga download pc windows 8.1
-Summertime saga download pc windows xp
-Summertime saga download pc gamejolt
-Summertime saga download pc compressed
-Summertime saga download pc google drive
-Summertime saga download pc mediafire
-Summertime saga download pc mega.nz
-
Step 1: Visit the official website
-
The first thing you need to do is to go to the official website of Summertime Saga at https://summertimesaga.com/. This is where you can find all the information and updates about the game.
-
Step 2: Choose the Windows version
-
On the homepage, you will see a button that says "Download Now". Click on it and you will be taken to a page where you can choose your platform. Select "Windows" from the list of options.
-
Step 3: Download the game file
-
After choosing your platform, you will see a link that says "Download". Click on it and you will start downloading a ZIP file that contains the game. The file size is about 1 GB, so make sure you have enough space and a stable internet connection.
-
Step 4: Extract the game file
-
Once the download is complete, you will need to extract the ZIP
-
The last step is to install and run the game APK file that you downloaded. To do this, locate the file in your device's file manager and tap on it. You may see a prompt asking you to confirm the installation. Tap on "Install" and wait for the process to finish. Once the installation is done, you can tap on "Open" to launch the game. You can also find the game icon on your home screen or app drawer.
-
Conclusion
-
Summertime Saga is a game that will keep you entertained and engaged for hours. It has a lot of content and features that will appeal to different tastes and preferences. You can download Summertime Saga for Windows and Android devices by following the steps we have outlined in this article. We hope you enjoy playing the game and discovering its secrets.
-
FAQs
-
Q: Is Summertime Saga free to play?
-
A: Yes, Summertime Saga is free to play. You can download and play the game without paying anything. However, you can support the developers by donating or becoming a patron on their website.
-
Q: Is Summertime Saga safe to download?
-
A: Yes, Summertime Saga is safe to download. The game does not contain any viruses or malware. However, you should always download the game from the official website or trusted sources.
-
Q: Is Summertime Saga suitable for all ages?
-
A: No, Summertime Saga is not suitable for all ages. The game contains mature themes and content, such as nudity, sex, violence, and drugs. The game is intended for adults only and you should play it at your own discretion.
-
Q: How often is Summertime Saga updated?
-
A: Summertime Saga is updated regularly by the developers. They usually release a new version every few months, adding new content and features to the game. You can check their website or social media for the latest news and updates.
-
Q: How can I contact the developers of Summertime Saga?
-
A: You can contact the developers of Summertime Saga by visiting their website or social media pages. You can also join their Discord server or Reddit community to interact with them and other players.
Do you believe in love? If you do, then you might want to download the MP3 version of the song Do You Believe in Love by Huey Lewis and The News. This song is a classic hit from the 1980s that has been remastered in HD and is still popular today. In this article, we will show you how to download Do You Believe in Love MP3 from different sources, such as YouTube, Archive.org, and other websites and apps. We will also explain what this song is about and why you might want to download it.
Do You Believe in Love is a song by American rock band Huey Lewis and The News, released in 1982 as the first single from their second album Picture This. The song was written by Robert John "Mutt" Lange, who later became famous for producing albums for artists like AC/DC, Def Leppard, Shania Twain, and Bryan Adams. The song was a success, reaching number seven on the Billboard Hot 100 chart and becoming the band's first top ten hit. The song also has a catchy chorus that asks "Do you believe in love? Do you believe it's true?"
-
What is Do You Believe in Love?
-
Do You Believe in Love is a song that expresses the feelings of a man who is falling in love with a woman and wants to know if she feels the same way. He sings about how he has been looking for love for a long time and how he finally found it with her. He also sings about how he wants to make her happy and how he hopes she will stay with him forever. He asks her repeatedly if she believes in love and if she believes it's true, implying that he wants her to trust him and his feelings.
-
Why download Do You Believe in Love MP3?
-
There are many reasons why you might want to download Do You Believe in Love MP3. Here are some of them:
-
-
You love the song and want to listen to it anytime, anywhere.
-
You want to add the song to your playlist or music library.
-
You want to use the song as your ringtone or alarm tone.
-
You want to share the song with your friends or family.
-
You want to enjoy the high-quality sound of the remastered version.
-
-
No matter what your reason is, downloading Do You Believe in Love MP3 is easy and fast. All you need is a device with an internet connection and some storage space. In the next sections, we will show you how to download Do You Believe in Love MP3 from different sources.
-
How to download Do You Believe in Love MP3 from YouTube
-
One of the most popular sources for downloading Do You Believe in Love MP3 is YouTube. YouTube is a video-sharing platform that hosts millions of videos, including music videos, trailers, documentaries, tutorials, and more. YouTube also allows users to upload their own videos and share them with others. One of the videos that you can find on YouTube is the official music video of Do You Believe in Love by Huey Lewis and The News. This video has over 25 million views and was uploaded by the band's official YouTube channel in 2013. The video shows the band performing the song in a studio, while various scenes of couples in love are shown on a screen behind them. The video also has subtitles in different languages, including English, Spanish, French, German, and Italian. To download Do You Believe in Love MP3 from YouTube, you need to follow these steps:
-
download do you believe in love song mp3
-download do you believe in love by cher mp3
-download do you believe in love huey lewis mp3
-download do you believe in love meddy mp3
-download do you believe in love after love mp3
-download do you believe in life after love mp3
-download do you believe in love how crazy it could be mp3
-download do you believe in love at first sight mp3
-download do you believe in love by chris brown mp3
-download do you believe in love by michael english mp3
-download do you believe in love by don williams mp3
-download do you believe in love by whitney houston mp3
-download do you believe in love by leona lewis mp3
-download do you believe in love by justin bieber mp3
-download do you believe in love by ed sheeran mp3
-download do you believe in love remix mp3
-download do you believe in love lyrics mp3
-download do you believe in love video mp3
-download do you believe in love audio mp3
-download do you believe in love free mp3
-download do you believe in love online mp3
-download do you believe in love full mp3
-download do you believe in love album mp3
-download do you believe in love soundtrack mp3
-download do you believe in love ringtone mp3
-download do you believe in magic and i hope you do mp3
-download i don't believe in love anymore mp3
-download i still believe in your eyes i just don't care what you've done in your life mp3
-download i want to know what love is i want you to show me mp3
-download i will always love you no matter what they say mp3
-download i can't make you love me if you don't mp3
-download i'm not the only one who knows how to make you happy mp3
-download i'm a believer i couldn't leave her if i tried mp3
-download i'm yours and suddenly you're mine and it's brighter than sunshine mp3
-download i've been waiting for a girl like you to come into my life mp3
-download i've got sunshine on a cloudy day when it's cold outside i've got the month of may mp3
-download i've had the time of my life and i owe it all to you mp3
-download it must have been love but it's over now mp3
-download nothing's gonna change my love for you you ought to know by now how much i love you mp3
-download can't help falling in love with you wise men say only fools rush in mp3
-download can't take my eyes off of you you're just too good to be true mp3
-download can't fight this feeling any longer and yet i'm still afraid to let it flow mp3
-download can't stop the feeling got this feeling in my body come on mp3
-download can't get enough of your love babe what am i gonna do with you babe mp3
-
Step 1: Find the official music video on YouTube
-
The first step is to find the official music video of Do You Believe in Love on YouTube. You can do this by typing "Do You Believe in Love Huey Lewis" in the search bar and clicking on the first result. Alternatively, you can use this link: https://www.youtube.com/watch?v=BzIbyDbmsyg
-
Step 2: Copy the video URL
-
The next step is to copy the video URL from the address bar of your browser. The URL is the web address that starts with "https://" and ends with a series of letters and numbers. For example, the URL of the official music video of Do You Believe in Love is https://www.youtube.com/watch?v=BzIbyDbmsyg. To copy the URL, you can either right-click on it and select "Copy" or highlight it and press Ctrl+C on your keyboard.
-
Step 3: Paste the URL into a YouTube to MP3 converter
-
The third step is to paste the URL into a YouTube to MP3 converter. A YouTube to MP3 converter is a website or an app that allows you to convert YouTube videos into MP3 files that you can download and save on your device. There are many YouTube to MP3 converters available online, but some of them may not be safe or reliable. Therefore, we recommend using one of these trusted and tested converters:
-
-
YTMP3.cc: This is a simple and fast converter that supports both video and audio formats. It also has no ads or pop-ups.
-
4K Video Downloader: This is a powerful and versatile converter that allows you to download videos and playlists in high quality. It also has a smart mode that automatically applies your preferred settings.
-
MP3FY.com: This is an advanced and efficient converter that can handle long videos and large files. It also has a search function that lets you find videos directly from the website.
-
-
To paste the URL into a YouTube to MP3 converter, you need to go to the website or open the app of your choice and look for a box that says "Paste your video link here" or something similar. Then, you need to right-click on the box and select "Paste" or press Ctrl+V on your keyboard.
-
Step 4: Choose the output format and quality
-
The fourth step is to choose the output format and quality of your MP3 file. The output format is the type of file that you want to download, such as MP3, MP4, WAV, etc. The output quality is the level of sound clarity and detail that you want to have, such as 128 kbps, 192 kbps, 320 kbps, etc. Generally, the higher the quality, the larger the file size and the longer the download time.
-
To choose the output format and quality of your MP3 file, you need to look for a drop-down menu or a button that says "Format", "Quality", "Settings", or something similar. Then, you need to click on it and select your preferred options. For example, if you want to download Do You Believe in Love MP3 in high quality, you can choose MP3 as the format and 320 kbps as the quality.
-
Step 5: Download and save the MP3 file
-
The final step is to download and save the MP3 file on your device. To do this, you need to look for a button that says "Download", "Convert", "Start", or something similar. Then, you need to click on it and wait for the conversion process to finish. Once it is done, you will see a link or a button that says "Download your converted file", "Download MP3", "Save file", or something similar. Then, you need to click on it and choose where you want to save your file on your device. For example, if you want to save Do You Believe in Love MP3 in your music folder, you can select that folder and click on "Save".
-
Congratulations! You have successfully downloaded Do You Believe in Love MP3 from YouTube. You can now enjoy listening to this song anytime, anywhere.
-
How to download Do You Believe in Love MP3 from Archive.org
-
Another source for downloading Do You Believe in Love MP3 is Archive.org. Archive.org is a website that provides free access to millions of digital items, such as books, movies, music, software, and more. Archive.org also preserves and archives historical and cultural artifacts for future generations. One of the items that you can find on Archive.org is the audio file of Do You Believe in Love by Huey Lewis and The News. This file was uploaded by a user named "jimmyjames" in 2011 and has over 10,000 views. The file is part of a collection called "Community Audio" that contains user-generated audio content. To download Do You Believe in Love MP3 from Archive.org, you need to follow these steps:
-
Step 1: Go to the Archive.org website
-
The first step is to go to the Archive.org website. You can do this by typing "archive.org" in the address bar of your browser and pressing Enter. Alternatively, you can use this link: https://archive.org/
-
Step 2: Search for Huey Lewis And The News Do You Believe In Love
-
The next step is to search for Huey Lewis And The News Do You Believe In Love on the Archive.org website. You can do this by typing "Huey Lewis And The News Do You Believe In Love" in the search bar at the top of the page and clicking on the magnifying glass icon. Alternatively, you can use this link: https://archive.org/search.php?query=Huey+Lewis+And+The+News+Do+You+Believe+In+Love
-
Step 3: Click on the download options
-
The third step is to click on the download options for the audio file of Do You Believe in Love by Huey Lewis and The News. You can do this by scrolling down the page and looking for a result that says "Huey Lewis And The News - Do You Believe In Love". Then, you need to click on the downward arrow icon next to the result. This will open a drop-down menu that shows different download options, such as VBR MP3, OGG VORBIS, TORRENT, etc.
-
Step 4: Choose the MP3 format and download the file
-
The fourth step is to choose the MP3 format and download the file from the drop-down menu. The MP3 format is the most common and compatible audio format that works on most devices and players. To choose the MP3 format and download the file, you need to click on the option that says "VBR MP3". This will start the download process and save the file on your device.
-
Congratulations! You have successfully downloaded Do You Believe in Love MP3 from Archive.org. You can now enjoy listening to this song anytime, anywhere.
-
How to download Do You Believe in Love MP3 from other sources
-
Besides YouTube and Archive.org, there are other sources for downloading Do You Believe in Love MP3. Some of these sources are:
-
Ali Gatie, Marshmello & Ty Dolla $ign – Do You Believe
-
If you are looking for a modern version of Do You Believe in Love, you might want to check out Do You Believe by Ali Gatie, Marshmello & Ty Dolla $ign. This is a song that was released in 2021 as part of Ali Gatie's album The Idea of Her. The song features vocals from Canadian singer Ali Gatie, American DJ Marshmello, and American rapper Ty Dolla $ign. The song is a romantic ballad that asks "Do you believe in love? And all the things that we dream of?" The song also has a music video that shows the three artists singing in different locations, such as a beach, a rooftop, and a studio.
-
To download Do You Believe by Ali Gatie, Marshmello & Ty Dolla $ign, you can use one of these links:
There are also other websites and apps that offer MP3 downloads of various songs, including Do You Believe in Love by Huey Lewis and The News. However, some of these websites and apps may not be legal, safe, or reliable. Therefore, we advise you to be careful and use them at your own risk. Some of the websites and apps that offer MP3 downloads are:
-
-
MP3Juices.cc: This is a website that allows you to search and download MP3 files from multiple sources.
-
FreeMP3Cloud.com: This is a website that allows you to download MP3 files without registration or ads.
-
MP3Skull.com: This is a website that allows you to download MP3 files with high quality and fast speed.
-
MP3Quack.com: This is a website that allows you to download MP3 files with no limit and no captcha.
-
Music Downloader: This is an app that allows you to download MP3 files from YouTube, SoundCloud, and other platforms.
In conclusion, Do You Believe in Love is a song by Huey Lewis and The News that was released in 1982 and became a hit. The song is about a man who is falling in love with a woman and wants to know if she believes in love too. The song has a catchy chorus and a remastered version in HD. You can download Do You Believe in Love MP3 from different sources, such as YouTube, Archive.org, and other websites and apps. However, you need to be careful and use only trusted and tested sources. We hope this article has helped you learn how to download Do You Believe in Love MP3 and enjoy this song anytime, anywhere.
-
FAQs
-
Here are some frequently asked questions about Do You Believe in Love MP3:
-
Q: Who wrote Do You Believe in Love?
-
A: Do You Believe in Love was written by Robert John "Mutt" Lange, who later became famous for producing albums for artists like AC/DC, Def Leppard, Shania Twain, and Bryan Adams.
-
Q: Who sang Do You Believe in Love?
-
A: Do You Believe in Love was sung by Huey Lewis and The News, an American rock band that was formed in 1979. The band consists of Huey Lewis (lead vocals and harmonica), Johnny Colla (saxophone and guitar), Bill Gibson (drums), Sean Hopper (keyboards), Stef Burns (guitar), and John Pierce (bass).
-
Q: When was Do You Believe in Love released?
-
A: Do You Believe in Love was released in 1982 as the first single from the band's second album Picture This. The song was a success, reaching number seven on the Billboard Hot 100 chart and becoming the band's first top ten hit.
-
Q: What is the meaning of Do You Believe in Love?
-
A: Do You Believe in Love is a song that expresses the feelings of a man who is falling in love with a woman and wants to know if she believes in love too. He sings about how he has been looking for love for a long time and how he finally found it with her. He also sings about how he wants to make her happy and how he hopes she will stay with him forever. He asks her repeatedly if she believes in love and if she believes it's true, implying that he wants her to trust him and his feelings.
-
Q: How can I download Do You Believe in Love MP3?
-
A: You can download Do You Believe in Love MP3 from different sources, such as YouTube, Archive.org , and other websites and apps. However, you need to be careful and use only trusted and tested sources. To download Do You Believe in Love MP3 from YouTube, you need to find the official music video on YouTube, copy the video URL, paste the URL into a YouTube to MP3 converter, choose the output format and quality, and download and save the MP3 file. To download Do You Believe in Love MP3 from Archive.org, you need to go to the Archive.org website, search for Huey Lewis And The News Do You Believe In Love, click on the download options, choose the MP3 format, and download the file. To download Do You Believe in Love MP3 from other sources, you need to find a website or an app that offers MP3 downloads of various songs, such as Ali Gatie, Marshmello & Ty Dolla $ign – Do You Believe, MP3Juices.cc, FreeMP3Cloud.com, MP3Skull.com, MP3Quack.com, Music Downloader, MP3 Music Downloader & Free Music Download, or Free Music Downloader & Mp3 Music Download.
401be4b1e0
-
-
\ No newline at end of file
diff --git a/spaces/fffiloni/controlnet-animation-doodle/node_modules/ee-first/index.js b/spaces/fffiloni/controlnet-animation-doodle/node_modules/ee-first/index.js
deleted file mode 100644
index 501287cd3b7024435d85a872bb1ba0b234db8e7f..0000000000000000000000000000000000000000
--- a/spaces/fffiloni/controlnet-animation-doodle/node_modules/ee-first/index.js
+++ /dev/null
@@ -1,95 +0,0 @@
-/*!
- * ee-first
- * Copyright(c) 2014 Jonathan Ong
- * MIT Licensed
- */
-
-'use strict'
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = first
-
-/**
- * Get the first event in a set of event emitters and event pairs.
- *
- * @param {array} stuff
- * @param {function} done
- * @public
- */
-
-function first(stuff, done) {
- if (!Array.isArray(stuff))
- throw new TypeError('arg must be an array of [ee, events...] arrays')
-
- var cleanups = []
-
- for (var i = 0; i < stuff.length; i++) {
- var arr = stuff[i]
-
- if (!Array.isArray(arr) || arr.length < 2)
- throw new TypeError('each array member must be [ee, events...]')
-
- var ee = arr[0]
-
- for (var j = 1; j < arr.length; j++) {
- var event = arr[j]
- var fn = listener(event, callback)
-
- // listen to the event
- ee.on(event, fn)
- // push this listener to the list of cleanups
- cleanups.push({
- ee: ee,
- event: event,
- fn: fn,
- })
- }
- }
-
- function callback() {
- cleanup()
- done.apply(null, arguments)
- }
-
- function cleanup() {
- var x
- for (var i = 0; i < cleanups.length; i++) {
- x = cleanups[i]
- x.ee.removeListener(x.event, x.fn)
- }
- }
-
- function thunk(fn) {
- done = fn
- }
-
- thunk.cancel = cleanup
-
- return thunk
-}
-
-/**
- * Create the event listener.
- * @private
- */
-
-function listener(event, done) {
- return function onevent(arg1) {
- var args = new Array(arguments.length)
- var ee = this
- var err = event === 'error'
- ? arg1
- : null
-
- // copy args to prevent arguments escaping scope
- for (var i = 0; i < args.length; i++) {
- args[i] = arguments[i]
- }
-
- done(err, ee, event, args)
- }
-}
diff --git a/spaces/fffiloni/controlnet-animation-doodle/node_modules/methods/HISTORY.md b/spaces/fffiloni/controlnet-animation-doodle/node_modules/methods/HISTORY.md
deleted file mode 100644
index c0ecf072db3f9809c46c83f5641b5df99c686bbf..0000000000000000000000000000000000000000
--- a/spaces/fffiloni/controlnet-animation-doodle/node_modules/methods/HISTORY.md
+++ /dev/null
@@ -1,29 +0,0 @@
-1.1.2 / 2016-01-17
-==================
-
- * perf: enable strict mode
-
-1.1.1 / 2014-12-30
-==================
-
- * Improve `browserify` support
-
-1.1.0 / 2014-07-05
-==================
-
- * Add `CONNECT` method
-
-1.0.1 / 2014-06-02
-==================
-
- * Fix module to work with harmony transform
-
-1.0.0 / 2014-05-08
-==================
-
- * Add `PURGE` method
-
-0.1.0 / 2013-10-28
-==================
-
- * Add `http.METHODS` support
diff --git a/spaces/fgenie/scamtext_PAL_self_consistency/funcs/f_51.py b/spaces/fgenie/scamtext_PAL_self_consistency/funcs/f_51.py
deleted file mode 100644
index 0caf6e6a6ac350cf62bcda6ac3688ee644e29f40..0000000000000000000000000000000000000000
--- a/spaces/fgenie/scamtext_PAL_self_consistency/funcs/f_51.py
+++ /dev/null
@@ -1,19 +0,0 @@
-
-import re
-
-def is_spam(message: str) -> bool:
- # Patterns to detect spam
- url_pattern = re.compile(r'https?://\S+|www\.\S+') # URLs
- num_pattern = re.compile(r'\d{4,}') # Large numbers (4 or more digits)
- special_char_pattern = re.compile(r'[!"#$%&\'()*+,-./[\\\]^_`{|}~]') # Special characters
-
- # Filters to identify spam
- has_url = bool(url_pattern.search(message))
- has_long_num = bool(num_pattern.search(message))
- has_special_chars = bool(special_char_pattern.search(message))
-
- # If the message contains URLs, large numbers or special chars, classify it as spam
- if has_url or has_long_num or has_special_chars:
- return True
- else:
- return False
diff --git a/spaces/firzaelbuho/rvc-models/infer_pack/transforms.py b/spaces/firzaelbuho/rvc-models/infer_pack/transforms.py
deleted file mode 100644
index a11f799e023864ff7082c1f49c0cc18351a13b47..0000000000000000000000000000000000000000
--- a/spaces/firzaelbuho/rvc-models/infer_pack/transforms.py
+++ /dev/null
@@ -1,209 +0,0 @@
-import torch
-from torch.nn import functional as F
-
-import numpy as np
-
-
-DEFAULT_MIN_BIN_WIDTH = 1e-3
-DEFAULT_MIN_BIN_HEIGHT = 1e-3
-DEFAULT_MIN_DERIVATIVE = 1e-3
-
-
-def piecewise_rational_quadratic_transform(
- inputs,
- unnormalized_widths,
- unnormalized_heights,
- unnormalized_derivatives,
- inverse=False,
- tails=None,
- tail_bound=1.0,
- min_bin_width=DEFAULT_MIN_BIN_WIDTH,
- min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
- min_derivative=DEFAULT_MIN_DERIVATIVE,
-):
- if tails is None:
- spline_fn = rational_quadratic_spline
- spline_kwargs = {}
- else:
- spline_fn = unconstrained_rational_quadratic_spline
- spline_kwargs = {"tails": tails, "tail_bound": tail_bound}
-
- outputs, logabsdet = spline_fn(
- inputs=inputs,
- unnormalized_widths=unnormalized_widths,
- unnormalized_heights=unnormalized_heights,
- unnormalized_derivatives=unnormalized_derivatives,
- inverse=inverse,
- min_bin_width=min_bin_width,
- min_bin_height=min_bin_height,
- min_derivative=min_derivative,
- **spline_kwargs
- )
- return outputs, logabsdet
-
-
-def searchsorted(bin_locations, inputs, eps=1e-6):
- bin_locations[..., -1] += eps
- return torch.sum(inputs[..., None] >= bin_locations, dim=-1) - 1
-
-
-def unconstrained_rational_quadratic_spline(
- inputs,
- unnormalized_widths,
- unnormalized_heights,
- unnormalized_derivatives,
- inverse=False,
- tails="linear",
- tail_bound=1.0,
- min_bin_width=DEFAULT_MIN_BIN_WIDTH,
- min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
- min_derivative=DEFAULT_MIN_DERIVATIVE,
-):
- inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
- outside_interval_mask = ~inside_interval_mask
-
- outputs = torch.zeros_like(inputs)
- logabsdet = torch.zeros_like(inputs)
-
- if tails == "linear":
- unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1))
- constant = np.log(np.exp(1 - min_derivative) - 1)
- unnormalized_derivatives[..., 0] = constant
- unnormalized_derivatives[..., -1] = constant
-
- outputs[outside_interval_mask] = inputs[outside_interval_mask]
- logabsdet[outside_interval_mask] = 0
- else:
- raise RuntimeError("{} tails are not implemented.".format(tails))
-
- (
- outputs[inside_interval_mask],
- logabsdet[inside_interval_mask],
- ) = rational_quadratic_spline(
- inputs=inputs[inside_interval_mask],
- unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
- unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
- unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],
- inverse=inverse,
- left=-tail_bound,
- right=tail_bound,
- bottom=-tail_bound,
- top=tail_bound,
- min_bin_width=min_bin_width,
- min_bin_height=min_bin_height,
- min_derivative=min_derivative,
- )
-
- return outputs, logabsdet
-
-
-def rational_quadratic_spline(
- inputs,
- unnormalized_widths,
- unnormalized_heights,
- unnormalized_derivatives,
- inverse=False,
- left=0.0,
- right=1.0,
- bottom=0.0,
- top=1.0,
- min_bin_width=DEFAULT_MIN_BIN_WIDTH,
- min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
- min_derivative=DEFAULT_MIN_DERIVATIVE,
-):
- if torch.min(inputs) < left or torch.max(inputs) > right:
- raise ValueError("Input to a transform is not within its domain")
-
- num_bins = unnormalized_widths.shape[-1]
-
- if min_bin_width * num_bins > 1.0:
- raise ValueError("Minimal bin width too large for the number of bins")
- if min_bin_height * num_bins > 1.0:
- raise ValueError("Minimal bin height too large for the number of bins")
-
- widths = F.softmax(unnormalized_widths, dim=-1)
- widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
- cumwidths = torch.cumsum(widths, dim=-1)
- cumwidths = F.pad(cumwidths, pad=(1, 0), mode="constant", value=0.0)
- cumwidths = (right - left) * cumwidths + left
- cumwidths[..., 0] = left
- cumwidths[..., -1] = right
- widths = cumwidths[..., 1:] - cumwidths[..., :-1]
-
- derivatives = min_derivative + F.softplus(unnormalized_derivatives)
-
- heights = F.softmax(unnormalized_heights, dim=-1)
- heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
- cumheights = torch.cumsum(heights, dim=-1)
- cumheights = F.pad(cumheights, pad=(1, 0), mode="constant", value=0.0)
- cumheights = (top - bottom) * cumheights + bottom
- cumheights[..., 0] = bottom
- cumheights[..., -1] = top
- heights = cumheights[..., 1:] - cumheights[..., :-1]
-
- if inverse:
- bin_idx = searchsorted(cumheights, inputs)[..., None]
- else:
- bin_idx = searchsorted(cumwidths, inputs)[..., None]
-
- input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
- input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
-
- input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
- delta = heights / widths
- input_delta = delta.gather(-1, bin_idx)[..., 0]
-
- input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
- input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
-
- input_heights = heights.gather(-1, bin_idx)[..., 0]
-
- if inverse:
- a = (inputs - input_cumheights) * (
- input_derivatives + input_derivatives_plus_one - 2 * input_delta
- ) + input_heights * (input_delta - input_derivatives)
- b = input_heights * input_derivatives - (inputs - input_cumheights) * (
- input_derivatives + input_derivatives_plus_one - 2 * input_delta
- )
- c = -input_delta * (inputs - input_cumheights)
-
- discriminant = b.pow(2) - 4 * a * c
- assert (discriminant >= 0).all()
-
- root = (2 * c) / (-b - torch.sqrt(discriminant))
- outputs = root * input_bin_widths + input_cumwidths
-
- theta_one_minus_theta = root * (1 - root)
- denominator = input_delta + (
- (input_derivatives + input_derivatives_plus_one - 2 * input_delta)
- * theta_one_minus_theta
- )
- derivative_numerator = input_delta.pow(2) * (
- input_derivatives_plus_one * root.pow(2)
- + 2 * input_delta * theta_one_minus_theta
- + input_derivatives * (1 - root).pow(2)
- )
- logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
-
- return outputs, -logabsdet
- else:
- theta = (inputs - input_cumwidths) / input_bin_widths
- theta_one_minus_theta = theta * (1 - theta)
-
- numerator = input_heights * (
- input_delta * theta.pow(2) + input_derivatives * theta_one_minus_theta
- )
- denominator = input_delta + (
- (input_derivatives + input_derivatives_plus_one - 2 * input_delta)
- * theta_one_minus_theta
- )
- outputs = input_cumheights + numerator / denominator
-
- derivative_numerator = input_delta.pow(2) * (
- input_derivatives_plus_one * theta.pow(2)
- + 2 * input_delta * theta_one_minus_theta
- + input_derivatives * (1 - theta).pow(2)
- )
- logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
-
- return outputs, logabsdet
diff --git a/spaces/florim/MedGPT/autogpt/spinner.py b/spaces/florim/MedGPT/autogpt/spinner.py
deleted file mode 100644
index 4e33d74213881352546f334ccb1eb4772b8b7b70..0000000000000000000000000000000000000000
--- a/spaces/florim/MedGPT/autogpt/spinner.py
+++ /dev/null
@@ -1,65 +0,0 @@
-"""A simple spinner module"""
-import itertools
-import sys
-import threading
-import time
-
-
-class Spinner:
- """A simple spinner class"""
-
- def __init__(self, message: str = "Loading...", delay: float = 0.1) -> None:
- """Initialize the spinner class
-
- Args:
- message (str): The message to display.
- delay (float): The delay between each spinner update.
- """
- self.spinner = itertools.cycle(["-", "/", "|", "\\"])
- self.delay = delay
- self.message = message
- self.running = False
- self.spinner_thread = None
-
- def spin(self) -> None:
- """Spin the spinner"""
- while self.running:
- sys.stdout.write(f"{next(self.spinner)} {self.message}\r")
- sys.stdout.flush()
- time.sleep(self.delay)
- sys.stdout.write(f"\r{' ' * (len(self.message) + 2)}\r")
-
- def __enter__(self):
- """Start the spinner"""
- self.running = True
- self.spinner_thread = threading.Thread(target=self.spin)
- self.spinner_thread.start()
-
- return self
-
- def __exit__(self, exc_type, exc_value, exc_traceback) -> None:
- """Stop the spinner
-
- Args:
- exc_type (Exception): The exception type.
- exc_value (Exception): The exception value.
- exc_traceback (Exception): The exception traceback.
- """
- self.running = False
- if self.spinner_thread is not None:
- self.spinner_thread.join()
- sys.stdout.write(f"\r{' ' * (len(self.message) + 2)}\r")
- sys.stdout.flush()
-
- def update_message(self, new_message, delay=0.1):
- """Update the spinner message
- Args:
- new_message (str): New message to display
- delay: Delay in seconds before updating the message
- """
- time.sleep(delay)
- sys.stdout.write(
- f"\r{' ' * (len(self.message) + 2)}\r"
- ) # Clear the current message
- sys.stdout.flush()
- self.message = new_message
diff --git a/spaces/gerhug/dalle-mini/html2canvas.js b/spaces/gerhug/dalle-mini/html2canvas.js
deleted file mode 100644
index 96e2dc5707b1a584ff7b3b583aea7c6c18d4ea76..0000000000000000000000000000000000000000
--- a/spaces/gerhug/dalle-mini/html2canvas.js
+++ /dev/null
@@ -1,7756 +0,0 @@
-/*!
- * html2canvas 1.4.1
- * Copyright (c) 2022 Niklas von Hertzen
- * Released under MIT License
- */
-(function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
- typeof define === 'function' && define.amd ? define(factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.html2canvas = factory());
-}(this, (function () { 'use strict';
-
- /*! *****************************************************************************
- Copyright (c) Microsoft Corporation.
-
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted.
-
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- PERFORMANCE OF THIS SOFTWARE.
- ***************************************************************************** */
- /* global Reflect, Promise */
-
- var extendStatics = function(d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
-
- function __extends(d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- }
-
- var __assign = function() {
- __assign = Object.assign || function __assign(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
- };
-
- function __awaiter(thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- }
-
- function __generator(thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- }
-
- function __spreadArray(to, from, pack) {
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
- if (ar || !(i in from)) {
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
- ar[i] = from[i];
- }
- }
- return to.concat(ar || from);
- }
-
- var Bounds = /** @class */ (function () {
- function Bounds(left, top, width, height) {
- this.left = left;
- this.top = top;
- this.width = width;
- this.height = height;
- }
- Bounds.prototype.add = function (x, y, w, h) {
- return new Bounds(this.left + x, this.top + y, this.width + w, this.height + h);
- };
- Bounds.fromClientRect = function (context, clientRect) {
- return new Bounds(clientRect.left + context.windowBounds.left, clientRect.top + context.windowBounds.top, clientRect.width, clientRect.height);
- };
- Bounds.fromDOMRectList = function (context, domRectList) {
- var domRect = Array.from(domRectList).find(function (rect) { return rect.width !== 0; });
- return domRect
- ? new Bounds(domRect.left + context.windowBounds.left, domRect.top + context.windowBounds.top, domRect.width, domRect.height)
- : Bounds.EMPTY;
- };
- Bounds.EMPTY = new Bounds(0, 0, 0, 0);
- return Bounds;
- }());
- var parseBounds = function (context, node) {
- return Bounds.fromClientRect(context, node.getBoundingClientRect());
- };
- var parseDocumentSize = function (document) {
- var body = document.body;
- var documentElement = document.documentElement;
- if (!body || !documentElement) {
- throw new Error("Unable to get document size");
- }
- var width = Math.max(Math.max(body.scrollWidth, documentElement.scrollWidth), Math.max(body.offsetWidth, documentElement.offsetWidth), Math.max(body.clientWidth, documentElement.clientWidth));
- var height = Math.max(Math.max(body.scrollHeight, documentElement.scrollHeight), Math.max(body.offsetHeight, documentElement.offsetHeight), Math.max(body.clientHeight, documentElement.clientHeight));
- return new Bounds(0, 0, width, height);
- };
-
- /*
- * css-line-break 2.1.0
- * Copyright (c) 2022 Niklas von Hertzen
- * Released under MIT License
- */
- var toCodePoints$1 = function (str) {
- var codePoints = [];
- var i = 0;
- var length = str.length;
- while (i < length) {
- var value = str.charCodeAt(i++);
- if (value >= 0xd800 && value <= 0xdbff && i < length) {
- var extra = str.charCodeAt(i++);
- if ((extra & 0xfc00) === 0xdc00) {
- codePoints.push(((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000);
- }
- else {
- codePoints.push(value);
- i--;
- }
- }
- else {
- codePoints.push(value);
- }
- }
- return codePoints;
- };
- var fromCodePoint$1 = function () {
- var codePoints = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- codePoints[_i] = arguments[_i];
- }
- if (String.fromCodePoint) {
- return String.fromCodePoint.apply(String, codePoints);
- }
- var length = codePoints.length;
- if (!length) {
- return '';
- }
- var codeUnits = [];
- var index = -1;
- var result = '';
- while (++index < length) {
- var codePoint = codePoints[index];
- if (codePoint <= 0xffff) {
- codeUnits.push(codePoint);
- }
- else {
- codePoint -= 0x10000;
- codeUnits.push((codePoint >> 10) + 0xd800, (codePoint % 0x400) + 0xdc00);
- }
- if (index + 1 === length || codeUnits.length > 0x4000) {
- result += String.fromCharCode.apply(String, codeUnits);
- codeUnits.length = 0;
- }
- }
- return result;
- };
- var chars$2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
- // Use a lookup table to find the index.
- var lookup$2 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
- for (var i$2 = 0; i$2 < chars$2.length; i$2++) {
- lookup$2[chars$2.charCodeAt(i$2)] = i$2;
- }
-
- /*
- * utrie 1.0.2
- * Copyright (c) 2022 Niklas von Hertzen
- * Released under MIT License
- */
- var chars$1$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
- // Use a lookup table to find the index.
- var lookup$1$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
- for (var i$1$1 = 0; i$1$1 < chars$1$1.length; i$1$1++) {
- lookup$1$1[chars$1$1.charCodeAt(i$1$1)] = i$1$1;
- }
- var decode$1 = function (base64) {
- var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
- if (base64[base64.length - 1] === '=') {
- bufferLength--;
- if (base64[base64.length - 2] === '=') {
- bufferLength--;
- }
- }
- var buffer = typeof ArrayBuffer !== 'undefined' &&
- typeof Uint8Array !== 'undefined' &&
- typeof Uint8Array.prototype.slice !== 'undefined'
- ? new ArrayBuffer(bufferLength)
- : new Array(bufferLength);
- var bytes = Array.isArray(buffer) ? buffer : new Uint8Array(buffer);
- for (i = 0; i < len; i += 4) {
- encoded1 = lookup$1$1[base64.charCodeAt(i)];
- encoded2 = lookup$1$1[base64.charCodeAt(i + 1)];
- encoded3 = lookup$1$1[base64.charCodeAt(i + 2)];
- encoded4 = lookup$1$1[base64.charCodeAt(i + 3)];
- bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
- bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
- bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
- }
- return buffer;
- };
- var polyUint16Array$1 = function (buffer) {
- var length = buffer.length;
- var bytes = [];
- for (var i = 0; i < length; i += 2) {
- bytes.push((buffer[i + 1] << 8) | buffer[i]);
- }
- return bytes;
- };
- var polyUint32Array$1 = function (buffer) {
- var length = buffer.length;
- var bytes = [];
- for (var i = 0; i < length; i += 4) {
- bytes.push((buffer[i + 3] << 24) | (buffer[i + 2] << 16) | (buffer[i + 1] << 8) | buffer[i]);
- }
- return bytes;
- };
-
- /** Shift size for getting the index-2 table offset. */
- var UTRIE2_SHIFT_2$1 = 5;
- /** Shift size for getting the index-1 table offset. */
- var UTRIE2_SHIFT_1$1 = 6 + 5;
- /**
- * Shift size for shifting left the index array values.
- * Increases possible data size with 16-bit index values at the cost
- * of compactability.
- * This requires data blocks to be aligned by UTRIE2_DATA_GRANULARITY.
- */
- var UTRIE2_INDEX_SHIFT$1 = 2;
- /**
- * Difference between the two shift sizes,
- * for getting an index-1 offset from an index-2 offset. 6=11-5
- */
- var UTRIE2_SHIFT_1_2$1 = UTRIE2_SHIFT_1$1 - UTRIE2_SHIFT_2$1;
- /**
- * The part of the index-2 table for U+D800..U+DBFF stores values for
- * lead surrogate code _units_ not code _points_.
- * Values for lead surrogate code _points_ are indexed with this portion of the table.
- * Length=32=0x20=0x400>>UTRIE2_SHIFT_2. (There are 1024=0x400 lead surrogates.)
- */
- var UTRIE2_LSCP_INDEX_2_OFFSET$1 = 0x10000 >> UTRIE2_SHIFT_2$1;
- /** Number of entries in a data block. 32=0x20 */
- var UTRIE2_DATA_BLOCK_LENGTH$1 = 1 << UTRIE2_SHIFT_2$1;
- /** Mask for getting the lower bits for the in-data-block offset. */
- var UTRIE2_DATA_MASK$1 = UTRIE2_DATA_BLOCK_LENGTH$1 - 1;
- var UTRIE2_LSCP_INDEX_2_LENGTH$1 = 0x400 >> UTRIE2_SHIFT_2$1;
- /** Count the lengths of both BMP pieces. 2080=0x820 */
- var UTRIE2_INDEX_2_BMP_LENGTH$1 = UTRIE2_LSCP_INDEX_2_OFFSET$1 + UTRIE2_LSCP_INDEX_2_LENGTH$1;
- /**
- * The 2-byte UTF-8 version of the index-2 table follows at offset 2080=0x820.
- * Length 32=0x20 for lead bytes C0..DF, regardless of UTRIE2_SHIFT_2.
- */
- var UTRIE2_UTF8_2B_INDEX_2_OFFSET$1 = UTRIE2_INDEX_2_BMP_LENGTH$1;
- var UTRIE2_UTF8_2B_INDEX_2_LENGTH$1 = 0x800 >> 6; /* U+0800 is the first code point after 2-byte UTF-8 */
- /**
- * The index-1 table, only used for supplementary code points, at offset 2112=0x840.
- * Variable length, for code points up to highStart, where the last single-value range starts.
- * Maximum length 512=0x200=0x100000>>UTRIE2_SHIFT_1.
- * (For 0x100000 supplementary code points U+10000..U+10ffff.)
- *
- * The part of the index-2 table for supplementary code points starts
- * after this index-1 table.
- *
- * Both the index-1 table and the following part of the index-2 table
- * are omitted completely if there is only BMP data.
- */
- var UTRIE2_INDEX_1_OFFSET$1 = UTRIE2_UTF8_2B_INDEX_2_OFFSET$1 + UTRIE2_UTF8_2B_INDEX_2_LENGTH$1;
- /**
- * Number of index-1 entries for the BMP. 32=0x20
- * This part of the index-1 table is omitted from the serialized form.
- */
- var UTRIE2_OMITTED_BMP_INDEX_1_LENGTH$1 = 0x10000 >> UTRIE2_SHIFT_1$1;
- /** Number of entries in an index-2 block. 64=0x40 */
- var UTRIE2_INDEX_2_BLOCK_LENGTH$1 = 1 << UTRIE2_SHIFT_1_2$1;
- /** Mask for getting the lower bits for the in-index-2-block offset. */
- var UTRIE2_INDEX_2_MASK$1 = UTRIE2_INDEX_2_BLOCK_LENGTH$1 - 1;
- var slice16$1 = function (view, start, end) {
- if (view.slice) {
- return view.slice(start, end);
- }
- return new Uint16Array(Array.prototype.slice.call(view, start, end));
- };
- var slice32$1 = function (view, start, end) {
- if (view.slice) {
- return view.slice(start, end);
- }
- return new Uint32Array(Array.prototype.slice.call(view, start, end));
- };
- var createTrieFromBase64$1 = function (base64, _byteLength) {
- var buffer = decode$1(base64);
- var view32 = Array.isArray(buffer) ? polyUint32Array$1(buffer) : new Uint32Array(buffer);
- var view16 = Array.isArray(buffer) ? polyUint16Array$1(buffer) : new Uint16Array(buffer);
- var headerLength = 24;
- var index = slice16$1(view16, headerLength / 2, view32[4] / 2);
- var data = view32[5] === 2
- ? slice16$1(view16, (headerLength + view32[4]) / 2)
- : slice32$1(view32, Math.ceil((headerLength + view32[4]) / 4));
- return new Trie$1(view32[0], view32[1], view32[2], view32[3], index, data);
- };
- var Trie$1 = /** @class */ (function () {
- function Trie(initialValue, errorValue, highStart, highValueIndex, index, data) {
- this.initialValue = initialValue;
- this.errorValue = errorValue;
- this.highStart = highStart;
- this.highValueIndex = highValueIndex;
- this.index = index;
- this.data = data;
- }
- /**
- * Get the value for a code point as stored in the Trie.
- *
- * @param codePoint the code point
- * @return the value
- */
- Trie.prototype.get = function (codePoint) {
- var ix;
- if (codePoint >= 0) {
- if (codePoint < 0x0d800 || (codePoint > 0x0dbff && codePoint <= 0x0ffff)) {
- // Ordinary BMP code point, excluding leading surrogates.
- // BMP uses a single level lookup. BMP index starts at offset 0 in the Trie2 index.
- // 16 bit data is stored in the index array itself.
- ix = this.index[codePoint >> UTRIE2_SHIFT_2$1];
- ix = (ix << UTRIE2_INDEX_SHIFT$1) + (codePoint & UTRIE2_DATA_MASK$1);
- return this.data[ix];
- }
- if (codePoint <= 0xffff) {
- // Lead Surrogate Code Point. A Separate index section is stored for
- // lead surrogate code units and code points.
- // The main index has the code unit data.
- // For this function, we need the code point data.
- // Note: this expression could be refactored for slightly improved efficiency, but
- // surrogate code points will be so rare in practice that it's not worth it.
- ix = this.index[UTRIE2_LSCP_INDEX_2_OFFSET$1 + ((codePoint - 0xd800) >> UTRIE2_SHIFT_2$1)];
- ix = (ix << UTRIE2_INDEX_SHIFT$1) + (codePoint & UTRIE2_DATA_MASK$1);
- return this.data[ix];
- }
- if (codePoint < this.highStart) {
- // Supplemental code point, use two-level lookup.
- ix = UTRIE2_INDEX_1_OFFSET$1 - UTRIE2_OMITTED_BMP_INDEX_1_LENGTH$1 + (codePoint >> UTRIE2_SHIFT_1$1);
- ix = this.index[ix];
- ix += (codePoint >> UTRIE2_SHIFT_2$1) & UTRIE2_INDEX_2_MASK$1;
- ix = this.index[ix];
- ix = (ix << UTRIE2_INDEX_SHIFT$1) + (codePoint & UTRIE2_DATA_MASK$1);
- return this.data[ix];
- }
- if (codePoint <= 0x10ffff) {
- return this.data[this.highValueIndex];
- }
- }
- // Fall through. The code point is outside of the legal range of 0..0x10ffff.
- return this.errorValue;
- };
- return Trie;
- }());
-
- /*
- * base64-arraybuffer 1.0.2
- * Copyright (c) 2022 Niklas von Hertzen
- * Released under MIT License
- */
- var chars$3 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
- // Use a lookup table to find the index.
- var lookup$3 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
- for (var i$3 = 0; i$3 < chars$3.length; i$3++) {
- lookup$3[chars$3.charCodeAt(i$3)] = i$3;
- }
-
- var base64$1 = 'KwAAAAAAAAAACA4AUD0AADAgAAACAAAAAAAIABAAGABAAEgAUABYAGAAaABgAGgAYgBqAF8AZwBgAGgAcQB5AHUAfQCFAI0AlQCdAKIAqgCyALoAYABoAGAAaABgAGgAwgDKAGAAaADGAM4A0wDbAOEA6QDxAPkAAQEJAQ8BFwF1AH0AHAEkASwBNAE6AUIBQQFJAVEBWQFhAWgBcAF4ATAAgAGGAY4BlQGXAZ8BpwGvAbUBvQHFAc0B0wHbAeMB6wHxAfkBAQIJAvEBEQIZAiECKQIxAjgCQAJGAk4CVgJeAmQCbAJ0AnwCgQKJApECmQKgAqgCsAK4ArwCxAIwAMwC0wLbAjAA4wLrAvMC+AIAAwcDDwMwABcDHQMlAy0DNQN1AD0DQQNJA0kDSQNRA1EDVwNZA1kDdQB1AGEDdQBpA20DdQN1AHsDdQCBA4kDkQN1AHUAmQOhA3UAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AKYDrgN1AHUAtgO+A8YDzgPWAxcD3gPjA+sD8wN1AHUA+wMDBAkEdQANBBUEHQQlBCoEFwMyBDgEYABABBcDSARQBFgEYARoBDAAcAQzAXgEgASIBJAEdQCXBHUAnwSnBK4EtgS6BMIEyAR1AHUAdQB1AHUAdQCVANAEYABgAGAAYABgAGAAYABgANgEYADcBOQEYADsBPQE/AQEBQwFFAUcBSQFLAU0BWQEPAVEBUsFUwVbBWAAYgVgAGoFcgV6BYIFigWRBWAAmQWfBaYFYABgAGAAYABgAKoFYACxBbAFuQW6BcEFwQXHBcEFwQXPBdMF2wXjBeoF8gX6BQIGCgYSBhoGIgYqBjIGOgZgAD4GRgZMBmAAUwZaBmAAYABgAGAAYABgAGAAYABgAGAAYABgAGIGYABpBnAGYABgAGAAYABgAGAAYABgAGAAYAB4Bn8GhQZgAGAAYAB1AHcDFQSLBmAAYABgAJMGdQA9A3UAmwajBqsGqwaVALMGuwbDBjAAywbSBtIG1QbSBtIG0gbSBtIG0gbdBuMG6wbzBvsGAwcLBxMHAwcbByMHJwcsBywHMQcsB9IGOAdAB0gHTgfSBkgHVgfSBtIG0gbSBtIG0gbSBtIG0gbSBiwHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAdgAGAALAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAdbB2MHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsB2kH0gZwB64EdQB1AHUAdQB1AHUAdQB1AHUHfQdgAIUHjQd1AHUAlQedB2AAYAClB6sHYACzB7YHvgfGB3UAzgfWBzMB3gfmB1EB7gf1B/0HlQENAQUIDQh1ABUIHQglCBcDLQg1CD0IRQhNCEEDUwh1AHUAdQBbCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIcAh3CHoIMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIgggwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAALAcsBywHLAcsBywHLAcsBywHLAcsB4oILAcsB44I0gaWCJ4Ipgh1AHUAqgiyCHUAdQB1AHUAdQB1AHUAdQB1AHUAtwh8AXUAvwh1AMUIyQjRCNkI4AjoCHUAdQB1AO4I9gj+CAYJDgkTCS0HGwkjCYIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiAAIAAAAFAAYABgAGIAXwBgAHEAdQBFAJUAogCyAKAAYABgAEIA4ABGANMA4QDxAMEBDwE1AFwBLAE6AQEBUQF4QkhCmEKoQrhCgAHIQsAB0MLAAcABwAHAAeDC6ABoAHDCwMMAAcABwAHAAdDDGMMAAcAB6MM4wwjDWMNow3jDaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAEjDqABWw6bDqABpg6gAaABoAHcDvwOPA+gAaABfA/8DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DpcPAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcAB9cPKwkyCToJMAB1AHUAdQBCCUoJTQl1AFUJXAljCWcJawkwADAAMAAwAHMJdQB2CX4JdQCECYoJjgmWCXUAngkwAGAAYABxAHUApgn3A64JtAl1ALkJdQDACTAAMAAwADAAdQB1AHUAdQB1AHUAdQB1AHUAowYNBMUIMAAwADAAMADICcsJ0wnZCRUE4QkwAOkJ8An4CTAAMAB1AAAKvwh1AAgKDwoXCh8KdQAwACcKLgp1ADYKqAmICT4KRgowADAAdQB1AE4KMAB1AFYKdQBeCnUAZQowADAAMAAwADAAMAAwADAAMAAVBHUAbQowADAAdQC5CXUKMAAwAHwBxAijBogEMgF9CoQKiASMCpQKmgqIBKIKqgquCogEDQG2Cr4KxgrLCjAAMADTCtsKCgHjCusK8Qr5CgELMAAwADAAMAB1AIsECQsRC3UANAEZCzAAMAAwADAAMAB1ACELKQswAHUANAExCzkLdQBBC0kLMABRC1kLMAAwADAAMAAwADAAdQBhCzAAMAAwAGAAYABpC3ELdwt/CzAAMACHC4sLkwubC58Lpwt1AK4Ltgt1APsDMAAwADAAMAAwADAAMAAwAL4LwwvLC9IL1wvdCzAAMADlC+kL8Qv5C/8LSQswADAAMAAwADAAMAAwADAAMAAHDDAAMAAwADAAMAAODBYMHgx1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1ACYMMAAwADAAdQB1AHUALgx1AHUAdQB1AHUAdQA2DDAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AD4MdQBGDHUAdQB1AHUAdQB1AEkMdQB1AHUAdQB1AFAMMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQBYDHUAdQB1AF8MMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUA+wMVBGcMMAAwAHwBbwx1AHcMfwyHDI8MMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAYABgAJcMMAAwADAAdQB1AJ8MlQClDDAAMACtDCwHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsB7UMLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AA0EMAC9DDAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAsBywHLAcsBywHLAcsBywHLQcwAMEMyAwsBywHLAcsBywHLAcsBywHLAcsBywHzAwwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAHUAdQB1ANQM2QzhDDAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMABgAGAAYABgAGAAYABgAOkMYADxDGAA+AwADQYNYABhCWAAYAAODTAAMAAwADAAFg1gAGAAHg37AzAAMAAwADAAYABgACYNYAAsDTQNPA1gAEMNPg1LDWAAYABgAGAAYABgAGAAYABgAGAAUg1aDYsGVglhDV0NcQBnDW0NdQ15DWAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAlQCBDZUAiA2PDZcNMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAnw2nDTAAMAAwADAAMAAwAHUArw23DTAAMAAwADAAMAAwADAAMAAwADAAMAB1AL8NMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAB1AHUAdQB1AHUAdQDHDTAAYABgAM8NMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAA1w11ANwNMAAwAD0B5A0wADAAMAAwADAAMADsDfQN/A0EDgwOFA4wABsOMAAwADAAMAAwADAAMAAwANIG0gbSBtIG0gbSBtIG0gYjDigOwQUuDsEFMw7SBjoO0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGQg5KDlIOVg7SBtIGXg5lDm0OdQ7SBtIGfQ6EDooOjQ6UDtIGmg6hDtIG0gaoDqwO0ga0DrwO0gZgAGAAYADEDmAAYAAkBtIGzA5gANIOYADaDokO0gbSBt8O5w7SBu8O0gb1DvwO0gZgAGAAxA7SBtIG0gbSBtIGYABgAGAAYAAED2AAsAUMD9IG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGFA8sBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAccD9IGLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHJA8sBywHLAcsBywHLAccDywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywPLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAc0D9IG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAccD9IG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGFA8sBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHPA/SBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gYUD0QPlQCVAJUAMAAwADAAMACVAJUAlQCVAJUAlQCVAEwPMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAA//8EAAQABAAEAAQABAAEAAQABAANAAMAAQABAAIABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQACgATABcAHgAbABoAHgAXABYAEgAeABsAGAAPABgAHABLAEsASwBLAEsASwBLAEsASwBLABgAGAAeAB4AHgATAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABYAGwASAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAWAA0AEQAeAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAFAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAJABYAGgAbABsAGwAeAB0AHQAeAE8AFwAeAA0AHgAeABoAGwBPAE8ADgBQAB0AHQAdAE8ATwAXAE8ATwBPABYAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAFAATwBAAE8ATwBPAEAATwBQAFAATwBQAB4AHgAeAB4AHgAeAB0AHQAdAB0AHgAdAB4ADgBQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgBQAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAJAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAkACQAJAAkACQAJAAkABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgAeAFAAHgAeAB4AKwArAFAAUABQAFAAGABQACsAKwArACsAHgAeAFAAHgBQAFAAUAArAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAUAAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAYAA0AKwArAB4AHgAbACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQADQAEAB4ABAAEAB4ABAAEABMABAArACsAKwArACsAKwArACsAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAKwArACsAKwBWAFYAVgBWAB4AHgArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AGgAaABoAGAAYAB4AHgAEAAQABAAEAAQABAAEAAQABAAEAAQAEwAEACsAEwATAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABLAEsASwBLAEsASwBLAEsASwBLABoAGQAZAB4AUABQAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABMAUAAEAAQABAAEAAQABAAEAB4AHgAEAAQABAAEAAQABABQAFAABAAEAB4ABAAEAAQABABQAFAASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUAAeAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAFAABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQAUABQAB4AHgAYABMAUAArACsABAAbABsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAFAABAAEAAQABAAEAFAABAAEAAQAUAAEAAQABAAEAAQAKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAArACsAHgArAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAUAAEAAQABAAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAABAAEAA0ADQBLAEsASwBLAEsASwBLAEsASwBLAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUAArACsAKwBQAFAAUABQACsAKwAEAFAABAAEAAQABAAEAAQABAArACsABAAEACsAKwAEAAQABABQACsAKwArACsAKwArACsAKwAEACsAKwArACsAUABQACsAUABQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAFAAUAAaABoAUABQAFAAUABQAEwAHgAbAFAAHgAEACsAKwAEAAQABAArAFAAUABQAFAAUABQACsAKwArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQACsAUABQACsAKwAEACsABAAEAAQABAAEACsAKwArACsABAAEACsAKwAEAAQABAArACsAKwAEACsAKwArACsAKwArACsAUABQAFAAUAArAFAAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLAAQABABQAFAAUAAEAB4AKwArACsAKwArACsAKwArACsAKwAEAAQABAArAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQAFAAUABQACsAKwAEAFAABAAEAAQABAAEAAQABAAEACsABAAEAAQAKwAEAAQABAArACsAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAB4AGwArACsAKwArACsAKwArAFAABAAEAAQABAAEAAQAKwAEAAQABAArAFAAUABQAFAAUABQAFAAUAArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAArACsABAAEACsAKwAEAAQABAArACsAKwArACsAKwArAAQABAAEACsAKwArACsAUABQACsAUABQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAB4AUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArAAQAUAArAFAAUABQAFAAUABQACsAKwArAFAAUABQACsAUABQAFAAUAArACsAKwBQAFAAKwBQACsAUABQACsAKwArAFAAUAArACsAKwBQAFAAUAArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArAAQABAAEAAQABAArACsAKwAEAAQABAArAAQABAAEAAQAKwArAFAAKwArACsAKwArACsABAArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAHgAeAB4AHgAeAB4AGwAeACsAKwArACsAKwAEAAQABAAEAAQAUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAUAAEAAQABAAEAAQABAAEACsABAAEAAQAKwAEAAQABAAEACsAKwArACsAKwArACsABAAEACsAUABQAFAAKwArACsAKwArAFAAUAAEAAQAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAKwAOAFAAUABQAFAAUABQAFAAHgBQAAQABAAEAA4AUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAKwArAAQAUAAEAAQABAAEAAQABAAEACsABAAEAAQAKwAEAAQABAAEACsAKwArACsAKwArACsABAAEACsAKwArACsAKwArACsAUAArAFAAUAAEAAQAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwBQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAFAABAAEAAQABAAEAAQABAArAAQABAAEACsABAAEAAQABABQAB4AKwArACsAKwBQAFAAUAAEAFAAUABQAFAAUABQAFAAUABQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAFAAUABQAFAAUABQABoAUABQAFAAUABQAFAAKwAEAAQABAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQACsAUAArACsAUABQAFAAUABQAFAAUAArACsAKwAEACsAKwArACsABAAEAAQABAAEAAQAKwAEACsABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArAAQABAAeACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqAFwAXAAqACoAKgAqACoAKgAqACsAKwArACsAGwBcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAeAEsASwBLAEsASwBLAEsASwBLAEsADQANACsAKwArACsAKwBcAFwAKwBcACsAXABcAFwAXABcACsAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACsAXAArAFwAXABcAFwAXABcAFwAXABcAFwAKgBcAFwAKgAqACoAKgAqACoAKgAqACoAXAArACsAXABcAFwAXABcACsAXAArACoAKgAqACoAKgAqACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwBcAFwAXABcAFAADgAOAA4ADgAeAA4ADgAJAA4ADgANAAkAEwATABMAEwATAAkAHgATAB4AHgAeAAQABAAeAB4AHgAeAB4AHgBLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAFAAUABQAFAAUABQAFAADQAEAB4ABAAeAAQAFgARABYAEQAEAAQAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQADQAEAAQABAAEAAQADQAEAAQAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArAA0ADQAeAB4AHgAeAB4AHgAEAB4AHgAeAB4AHgAeACsAHgAeAA4ADgANAA4AHgAeAB4AHgAeAAkACQArACsAKwArACsAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgBcAEsASwBLAEsASwBLAEsASwBLAEsADQANAB4AHgAeAB4AXABcAFwAXABcAFwAKgAqACoAKgBcAFwAXABcACoAKgAqAFwAKgAqACoAXABcACoAKgAqACoAKgAqACoAXABcAFwAKgAqACoAKgBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAqACoAKgAqAFwAKgBLAEsASwBLAEsASwBLAEsASwBLACoAKgAqACoAKgAqAFAAUABQAFAAUABQACsAUAArACsAKwArACsAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgBQAFAAUABQAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUAArACsAUABQAFAAUABQAFAAUAArAFAAKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAKwBQACsAUABQAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsABAAEAAQAHgANAB4AHgAeAB4AHgAeAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUAArACsADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAANAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAWABEAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAA0ADQANAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAANAA0AKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUAArAAQABAArACsAKwArACsAKwArACsAKwArACsAKwBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqAA0ADQAVAFwADQAeAA0AGwBcACoAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwAeAB4AEwATAA0ADQAOAB4AEwATAB4ABAAEAAQACQArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUAAEAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAHgArACsAKwATABMASwBLAEsASwBLAEsASwBLAEsASwBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAArACsAXABcAFwAXABcACsAKwArACsAKwArACsAKwArACsAKwBcAFwAXABcAFwAXABcAFwAXABcAFwAXAArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAXAArACsAKwAqACoAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAArACsAHgAeAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAqACoAKwAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKwArAAQASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArACoAKgAqACoAKgAqACoAXAAqACoAKgAqACoAKgArACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABABQAFAAUABQAFAAUABQACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwANAA0AHgANAA0ADQANAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAEAAQAHgAeAB4AHgAeAB4AHgAeAB4AKwArACsABAAEAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwAeAB4AHgAeAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArAA0ADQANAA0ADQBLAEsASwBLAEsASwBLAEsASwBLACsAKwArAFAAUABQAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAA0ADQBQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUAAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArAAQABAAEAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAAQAUABQAFAAUABQAFAABABQAFAABAAEAAQAUAArACsAKwArACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsABAAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAKwBQACsAUAArAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAB4AHgAeAB4AHgAeAB4AHgBQAB4AHgAeAFAAUABQACsAHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQACsAKwAeAB4AHgAeAB4AHgArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAFAAUABQACsAHgAeAB4AHgAeAB4AHgAOAB4AKwANAA0ADQANAA0ADQANAAkADQANAA0ACAAEAAsABAAEAA0ACQANAA0ADAAdAB0AHgAXABcAFgAXABcAFwAWABcAHQAdAB4AHgAUABQAFAANAAEAAQAEAAQABAAEAAQACQAaABoAGgAaABoAGgAaABoAHgAXABcAHQAVABUAHgAeAB4AHgAeAB4AGAAWABEAFQAVABUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ADQAeAA0ADQANAA0AHgANAA0ADQAHAB4AHgAeAB4AKwAEAAQABAAEAAQABAAEAAQABAAEAFAAUAArACsATwBQAFAAUABQAFAAHgAeAB4AFgARAE8AUABPAE8ATwBPAFAAUABQAFAAUAAeAB4AHgAWABEAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArABsAGwAbABsAGwAbABsAGgAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGgAbABsAGwAbABoAGwAbABoAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAHgAeAFAAGgAeAB0AHgBQAB4AGgAeAB4AHgAeAB4AHgAeAB4AHgBPAB4AUAAbAB4AHgBQAFAAUABQAFAAHgAeAB4AHQAdAB4AUAAeAFAAHgBQAB4AUABPAFAAUAAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAHgBQAFAAUABQAE8ATwBQAFAAUABQAFAATwBQAFAATwBQAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAFAAUABQAFAATwBPAE8ATwBPAE8ATwBPAE8ATwBQAFAAUABQAFAAUABQAFAAUAAeAB4AUABQAFAAUABPAB4AHgArACsAKwArAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHQAdAB4AHgAeAB0AHQAeAB4AHQAeAB4AHgAdAB4AHQAbABsAHgAdAB4AHgAeAB4AHQAeAB4AHQAdAB0AHQAeAB4AHQAeAB0AHgAdAB0AHQAdAB0AHQAeAB0AHgAeAB4AHgAeAB0AHQAdAB0AHgAeAB4AHgAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHgAeAB0AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAeAB0AHQAdAB0AHgAeAB0AHQAeAB4AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHQAeAB4AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAeAB4AHgAdAB4AHgAeAB4AHgAeAB4AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABYAEQAWABEAHgAeAB4AHgAeAB4AHQAeAB4AHgAeAB4AHgAeACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAWABEAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAFAAHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB4AHgAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAeAB4AHQAdAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHQAeAB0AHQAdAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB0AHQAeAB4AHQAdAB4AHgAeAB4AHQAdAB4AHgAeAB4AHQAdAB0AHgAeAB0AHgAeAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlAB4AHQAdAB4AHgAdAB4AHgAeAB4AHQAdAB4AHgAeAB4AJQAlAB0AHQAlAB4AJQAlACUAIAAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAeAB4AHgAeAB0AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAdAB0AHQAeAB0AJQAdAB0AHgAdAB0AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAdAB0AHQAdACUAHgAlACUAJQAdACUAJQAdAB0AHQAlACUAHQAdACUAHQAdACUAJQAlAB4AHQAeAB4AHgAeAB0AHQAlAB0AHQAdAB0AHQAdACUAJQAlACUAJQAdACUAJQAgACUAHQAdACUAJQAlACUAJQAlACUAJQAeAB4AHgAlACUAIAAgACAAIAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AFwAXABcAFwAXABcAHgATABMAJQAeAB4AHgAWABEAFgARABYAEQAWABEAFgARABYAEQAWABEATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAWABEAFgARABYAEQAWABEAFgARAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFgARABYAEQAWABEAFgARABYAEQAWABEAFgARABYAEQAWABEAFgARABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAWABEAFgARAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFgARAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAEAAQABAAeAB4AKwArACsAKwArABMADQANAA0AUAATAA0AUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUAANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAA0ADQANAA0ADQANAA0ADQAeAA0AFgANAB4AHgAXABcAHgAeABcAFwAWABEAFgARABYAEQAWABEADQANAA0ADQATAFAADQANAB4ADQANAB4AHgAeAB4AHgAMAAwADQANAA0AHgANAA0AFgANAA0ADQANAA0ADQANAA0AHgANAB4ADQANAB4AHgAeACsAKwArACsAKwArACsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAKwArACsAKwArACsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArAA0AEQARACUAJQBHAFcAVwAWABEAFgARABYAEQAWABEAFgARACUAJQAWABEAFgARABYAEQAWABEAFQAWABEAEQAlAFcAVwBXAFcAVwBXAFcAVwBXAAQABAAEAAQABAAEACUAVwBXAFcAVwA2ACUAJQBXAFcAVwBHAEcAJQAlACUAKwBRAFcAUQBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFEAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBRAFcAUQBXAFEAVwBXAFcAVwBXAFcAUQBXAFcAVwBXAFcAVwBRAFEAKwArAAQABAAVABUARwBHAFcAFQBRAFcAUQBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBRAFcAVwBXAFcAVwBXAFEAUQBXAFcAVwBXABUAUQBHAEcAVwArACsAKwArACsAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwAlACUAVwBXAFcAVwAlACUAJQAlACUAJQAlACUAJQAlACsAKwArACsAKwArACsAKwArACsAKwArAFEAUQBRAFEAUQBRAFEAUQBRAFEAUQBRAFEAUQBRAFEAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBPAE8ATwBPAE8ATwBPAE8AJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAEcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAADQATAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABLAEsASwBLAEsASwBLAEsASwBLAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAABAAEAAQABAAeAAQABAAEAAQABAAEAAQABAAEAAQAHgBQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUABQAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAeAA0ADQANAA0ADQArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAB4AHgAeAB4AHgAeAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AUABQAFAAUABQAFAAUABQAFAAUABQAAQAUABQAFAABABQAFAAUABQAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAeAB4AHgAeAAQAKwArACsAUABQAFAAUABQAFAAHgAeABoAHgArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAADgAOABMAEwArACsAKwArACsAKwArACsABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwANAA0ASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUAAeAB4AHgBQAA4AUABQAAQAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAA0ADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArAB4AWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYACsAKwArAAQAHgAeAB4AHgAeAB4ADQANAA0AHgAeAB4AHgArAFAASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArAB4AHgBcAFwAXABcAFwAKgBcAFwAXABcAFwAXABcAFwAXABcAEsASwBLAEsASwBLAEsASwBLAEsAXABcAFwAXABcACsAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArAFAAUABQAAQAUABQAFAAUABQAFAAUABQAAQABAArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAHgANAA0ADQBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAXAAqACoAKgBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqAFwAKgAqACoAXABcACoAKgBcAFwAXABcAFwAKgAqAFwAKgBcACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcACoAKgBQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAA0ADQBQAFAAUAAEAAQAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUAArACsAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQADQAEAAQAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAVABVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBUAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVACsAKwArACsAKwArACsAKwArACsAKwArAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAKwArACsAKwBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAKwArACsAKwAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAKwArACsAKwArAFYABABWAFYAVgBWAFYAVgBWAFYAVgBWAB4AVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgArAFYAVgBWAFYAVgArAFYAKwBWAFYAKwBWAFYAKwBWAFYAVgBWAFYAVgBWAFYAVgBWAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAEQAWAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUAAaAB4AKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAGAARABEAGAAYABMAEwAWABEAFAArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACUAJQAlACUAJQAWABEAFgARABYAEQAWABEAFgARABYAEQAlACUAFgARACUAJQAlACUAJQAlACUAEQAlABEAKwAVABUAEwATACUAFgARABYAEQAWABEAJQAlACUAJQAlACUAJQAlACsAJQAbABoAJQArACsAKwArAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAcAKwATACUAJQAbABoAJQAlABYAEQAlACUAEQAlABEAJQBXAFcAVwBXAFcAVwBXAFcAVwBXABUAFQAlACUAJQATACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXABYAJQARACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwAWACUAEQAlABYAEQARABYAEQARABUAVwBRAFEAUQBRAFEAUQBRAFEAUQBRAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAEcARwArACsAVwBXAFcAVwBXAFcAKwArAFcAVwBXAFcAVwBXACsAKwBXAFcAVwBXAFcAVwArACsAVwBXAFcAKwArACsAGgAbACUAJQAlABsAGwArAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwAEAAQABAAQAB0AKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsADQANAA0AKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAAQAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAA0AUABQAFAAUAArACsAKwArAFAAUABQAFAAUABQAFAAUAANAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwAeACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAKwArAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUAArACsAKwBQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwANAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAUABQAFAAUABQAAQABAAEACsABAAEACsAKwArACsAKwAEAAQABAAEAFAAUABQAFAAKwBQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEACsAKwArACsABABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAA0ADQANAA0ADQANAA0ADQAeACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAArACsAKwArAFAAUABQAFAAUAANAA0ADQANAA0ADQAUACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsADQANAA0ADQANAA0ADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAAQABAAEAAQAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUAArAAQABAANACsAKwBQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAB4AHgAeAB4AHgArACsAKwArACsAKwAEAAQABAAEAAQABAAEAA0ADQAeAB4AHgAeAB4AKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwAeACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsASwBLAEsASwBLAEsASwBLAEsASwANAA0ADQANAFAABAAEAFAAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAeAA4AUAArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAADQANAB4ADQAEAAQABAAEAB4ABAAEAEsASwBLAEsASwBLAEsASwBLAEsAUAAOAFAADQANAA0AKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAANAA0AHgANAA0AHgAEACsAUABQAFAAUABQAFAAUAArAFAAKwBQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAA0AKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsABAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQAFAAUABQACsABAAEAFAABAAEAAQABAAEAAQABAArACsABAAEACsAKwAEAAQABAArACsAUAArACsAKwArACsAKwAEACsAKwArACsAKwBQAFAAUABQAFAABAAEACsAKwAEAAQABAAEAAQABAAEACsAKwArAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAAQABABQAFAAUABQAA0ADQANAA0AHgBLAEsASwBLAEsASwBLAEsASwBLAA0ADQArAB4ABABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAAQABAAEAFAAUAAeAFAAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAArACsABAAEAAQABAAEAAQABAAEAAQADgANAA0AEwATAB4AHgAeAA0ADQANAA0ADQANAA0ADQANAA0ADQANAA0ADQANAFAAUABQAFAABAAEACsAKwAEAA0ADQAeAFAAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAFAAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKwArACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBcAFwADQANAA0AKgBQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAKwArAFAAKwArAFAAUABQAFAAUABQAFAAUAArAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQAKwAEAAQAKwArAAQABAAEAAQAUAAEAFAABAAEAA0ADQANACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAArACsABAAEAAQABAAEAAQABABQAA4AUAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAFAABAAEAAQABAAOAB4ADQANAA0ADQAOAB4ABAArACsAKwArACsAKwArACsAUAAEAAQABAAEAAQABAAEAAQABAAEAAQAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAA0ADQANAFAADgAOAA4ADQANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEACsABAAEAAQABAAEAAQABAAEAFAADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwAOABMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAArACsAKwAEACsABAAEACsABAAEAAQABAAEAAQABABQAAQAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAKwBQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQAKwAEAAQAKwAEAAQABAAEAAQAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAaABoAGgAaAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAASABIAEgAQwBDAEMAUABQAFAAUABDAFAAUABQAEgAQwBIAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAASABDAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwAJAAkACQAJAAkACQAJABYAEQArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABIAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwANAA0AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEAAQABAANACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAA0ADQANAB4AHgAeAB4AHgAeAFAAUABQAFAADQAeACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAANAA0AHgAeACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwAEAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAARwBHABUARwAJACsAKwArACsAKwArACsAKwArACsAKwAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACsAKwArACsAKwArACsAKwBXAFcAVwBXAFcAVwBXAFcAVwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUQBRAFEAKwArACsAKwArACsAKwArACsAKwArACsAKwBRAFEAUQBRACsAKwArACsAKwArACsAKwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUAArACsAHgAEAAQADQAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AHgAeAB4AKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAAQABAAEAAQABAAeAB4AHgAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAB4AHgAEAAQABAAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQAHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwBQAFAAKwArAFAAKwArAFAAUAArACsAUABQAFAAUAArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAUAArAFAAUABQAFAAUABQAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAHgAeAFAAUABQAFAAUAArAFAAKwArACsAUABQAFAAUABQAFAAUAArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeACsAKwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgAeAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgAeAB4AHgAeAB4ABAAeAB4AHgAeAB4AHgAeAB4AHgAeAAQAHgAeAA0ADQANAA0AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAAQABAAEAAQAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAEAAQAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArAAQABAAEAAQABAAEAAQAKwAEAAQAKwAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwAEAAQABAAEAAQABAAEAFAAUABQAFAAUABQAFAAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwBQAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArABsAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArAB4AHgAeAB4ABAAEAAQABAAEAAQABABQACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArABYAFgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAGgBQAFAAUAAaAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAKwBQACsAKwBQACsAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAKwBQACsAUAArACsAKwArACsAKwBQACsAKwArACsAUAArAFAAKwBQACsAUABQAFAAKwBQAFAAKwBQACsAKwBQACsAUAArAFAAKwBQACsAUAArAFAAUAArAFAAKwArAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUAArAFAAUABQAFAAKwBQACsAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAUABQAFAAKwBQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8AJQAlACUAHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB4AHgAeACUAJQAlAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAJQAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAlACUAJQAlACUAHgAlACUAJQAlACUAIAAgACAAJQAlACAAJQAlACAAIAAgACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACEAIQAhACEAIQAlACUAIAAgACUAJQAgACAAIAAgACAAIAAgACAAIAAgACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAJQAlACUAIAAlACUAJQAlACAAIAAgACUAIAAgACAAJQAlACUAJQAlACUAJQAgACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAlAB4AJQAeACUAJQAlACUAJQAgACUAJQAlACUAHgAlAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAJQAlACUAJQAgACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACAAIAAgACUAJQAlACAAIAAgACAAIAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABcAFwAXABUAFQAVAB4AHgAeAB4AJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAgACUAJQAlACUAJQAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAgACUAJQAgACUAJQAlACUAJQAlACUAJQAgACAAIAAgACAAIAAgACAAJQAlACUAJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAgACAAIAAgACAAIAAgACAAIAAgACUAJQAgACAAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAgACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAlACAAIAAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAgACAAIAAlACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAKwArAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwAlACUAJQAlACUAJQAlACUAJQAlACUAVwBXACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAKwAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAA==';
-
- var LETTER_NUMBER_MODIFIER = 50;
- // Non-tailorable Line Breaking Classes
- var BK = 1; // Cause a line break (after)
- var CR$1 = 2; // Cause a line break (after), except between CR and LF
- var LF$1 = 3; // Cause a line break (after)
- var CM = 4; // Prohibit a line break between the character and the preceding character
- var NL = 5; // Cause a line break (after)
- var WJ = 7; // Prohibit line breaks before and after
- var ZW = 8; // Provide a break opportunity
- var GL = 9; // Prohibit line breaks before and after
- var SP = 10; // Enable indirect line breaks
- var ZWJ$1 = 11; // Prohibit line breaks within joiner sequences
- // Break Opportunities
- var B2 = 12; // Provide a line break opportunity before and after the character
- var BA = 13; // Generally provide a line break opportunity after the character
- var BB = 14; // Generally provide a line break opportunity before the character
- var HY = 15; // Provide a line break opportunity after the character, except in numeric context
- var CB = 16; // Provide a line break opportunity contingent on additional information
- // Characters Prohibiting Certain Breaks
- var CL = 17; // Prohibit line breaks before
- var CP = 18; // Prohibit line breaks before
- var EX = 19; // Prohibit line breaks before
- var IN = 20; // Allow only indirect line breaks between pairs
- var NS = 21; // Allow only indirect line breaks before
- var OP = 22; // Prohibit line breaks after
- var QU = 23; // Act like they are both opening and closing
- // Numeric Context
- var IS = 24; // Prevent breaks after any and before numeric
- var NU = 25; // Form numeric expressions for line breaking purposes
- var PO = 26; // Do not break following a numeric expression
- var PR = 27; // Do not break in front of a numeric expression
- var SY = 28; // Prevent a break before; and allow a break after
- // Other Characters
- var AI = 29; // Act like AL when the resolvedEAW is N; otherwise; act as ID
- var AL = 30; // Are alphabetic characters or symbols that are used with alphabetic characters
- var CJ = 31; // Treat as NS or ID for strict or normal breaking.
- var EB = 32; // Do not break from following Emoji Modifier
- var EM = 33; // Do not break from preceding Emoji Base
- var H2 = 34; // Form Korean syllable blocks
- var H3 = 35; // Form Korean syllable blocks
- var HL = 36; // Do not break around a following hyphen; otherwise act as Alphabetic
- var ID = 37; // Break before or after; except in some numeric context
- var JL = 38; // Form Korean syllable blocks
- var JV = 39; // Form Korean syllable blocks
- var JT = 40; // Form Korean syllable blocks
- var RI$1 = 41; // Keep pairs together. For pairs; break before and after other classes
- var SA = 42; // Provide a line break opportunity contingent on additional, language-specific context analysis
- var XX = 43; // Have as yet unknown line breaking behavior or unassigned code positions
- var ea_OP = [0x2329, 0xff08];
- var BREAK_MANDATORY = '!';
- var BREAK_NOT_ALLOWED$1 = '×';
- var BREAK_ALLOWED$1 = '÷';
- var UnicodeTrie$1 = createTrieFromBase64$1(base64$1);
- var ALPHABETICS = [AL, HL];
- var HARD_LINE_BREAKS = [BK, CR$1, LF$1, NL];
- var SPACE$1 = [SP, ZW];
- var PREFIX_POSTFIX = [PR, PO];
- var LINE_BREAKS = HARD_LINE_BREAKS.concat(SPACE$1);
- var KOREAN_SYLLABLE_BLOCK = [JL, JV, JT, H2, H3];
- var HYPHEN = [HY, BA];
- var codePointsToCharacterClasses = function (codePoints, lineBreak) {
- if (lineBreak === void 0) { lineBreak = 'strict'; }
- var types = [];
- var indices = [];
- var categories = [];
- codePoints.forEach(function (codePoint, index) {
- var classType = UnicodeTrie$1.get(codePoint);
- if (classType > LETTER_NUMBER_MODIFIER) {
- categories.push(true);
- classType -= LETTER_NUMBER_MODIFIER;
- }
- else {
- categories.push(false);
- }
- if (['normal', 'auto', 'loose'].indexOf(lineBreak) !== -1) {
- // U+2010, – U+2013, 〜 U+301C, ゠ U+30A0
- if ([0x2010, 0x2013, 0x301c, 0x30a0].indexOf(codePoint) !== -1) {
- indices.push(index);
- return types.push(CB);
- }
- }
- if (classType === CM || classType === ZWJ$1) {
- // LB10 Treat any remaining combining mark or ZWJ as AL.
- if (index === 0) {
- indices.push(index);
- return types.push(AL);
- }
- // LB9 Do not break a combining character sequence; treat it as if it has the line breaking class of
- // the base character in all of the following rules. Treat ZWJ as if it were CM.
- var prev = types[index - 1];
- if (LINE_BREAKS.indexOf(prev) === -1) {
- indices.push(indices[index - 1]);
- return types.push(prev);
- }
- indices.push(index);
- return types.push(AL);
- }
- indices.push(index);
- if (classType === CJ) {
- return types.push(lineBreak === 'strict' ? NS : ID);
- }
- if (classType === SA) {
- return types.push(AL);
- }
- if (classType === AI) {
- return types.push(AL);
- }
- // For supplementary characters, a useful default is to treat characters in the range 10000..1FFFD as AL
- // and characters in the ranges 20000..2FFFD and 30000..3FFFD as ID, until the implementation can be revised
- // to take into account the actual line breaking properties for these characters.
- if (classType === XX) {
- if ((codePoint >= 0x20000 && codePoint <= 0x2fffd) || (codePoint >= 0x30000 && codePoint <= 0x3fffd)) {
- return types.push(ID);
- }
- else {
- return types.push(AL);
- }
- }
- types.push(classType);
- });
- return [indices, types, categories];
- };
- var isAdjacentWithSpaceIgnored = function (a, b, currentIndex, classTypes) {
- var current = classTypes[currentIndex];
- if (Array.isArray(a) ? a.indexOf(current) !== -1 : a === current) {
- var i = currentIndex;
- while (i <= classTypes.length) {
- i++;
- var next = classTypes[i];
- if (next === b) {
- return true;
- }
- if (next !== SP) {
- break;
- }
- }
- }
- if (current === SP) {
- var i = currentIndex;
- while (i > 0) {
- i--;
- var prev = classTypes[i];
- if (Array.isArray(a) ? a.indexOf(prev) !== -1 : a === prev) {
- var n = currentIndex;
- while (n <= classTypes.length) {
- n++;
- var next = classTypes[n];
- if (next === b) {
- return true;
- }
- if (next !== SP) {
- break;
- }
- }
- }
- if (prev !== SP) {
- break;
- }
- }
- }
- return false;
- };
- var previousNonSpaceClassType = function (currentIndex, classTypes) {
- var i = currentIndex;
- while (i >= 0) {
- var type = classTypes[i];
- if (type === SP) {
- i--;
- }
- else {
- return type;
- }
- }
- return 0;
- };
- var _lineBreakAtIndex = function (codePoints, classTypes, indicies, index, forbiddenBreaks) {
- if (indicies[index] === 0) {
- return BREAK_NOT_ALLOWED$1;
- }
- var currentIndex = index - 1;
- if (Array.isArray(forbiddenBreaks) && forbiddenBreaks[currentIndex] === true) {
- return BREAK_NOT_ALLOWED$1;
- }
- var beforeIndex = currentIndex - 1;
- var afterIndex = currentIndex + 1;
- var current = classTypes[currentIndex];
- // LB4 Always break after hard line breaks.
- // LB5 Treat CR followed by LF, as well as CR, LF, and NL as hard line breaks.
- var before = beforeIndex >= 0 ? classTypes[beforeIndex] : 0;
- var next = classTypes[afterIndex];
- if (current === CR$1 && next === LF$1) {
- return BREAK_NOT_ALLOWED$1;
- }
- if (HARD_LINE_BREAKS.indexOf(current) !== -1) {
- return BREAK_MANDATORY;
- }
- // LB6 Do not break before hard line breaks.
- if (HARD_LINE_BREAKS.indexOf(next) !== -1) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB7 Do not break before spaces or zero width space.
- if (SPACE$1.indexOf(next) !== -1) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB8 Break before any character following a zero-width space, even if one or more spaces intervene.
- if (previousNonSpaceClassType(currentIndex, classTypes) === ZW) {
- return BREAK_ALLOWED$1;
- }
- // LB8a Do not break after a zero width joiner.
- if (UnicodeTrie$1.get(codePoints[currentIndex]) === ZWJ$1) {
- return BREAK_NOT_ALLOWED$1;
- }
- // zwj emojis
- if ((current === EB || current === EM) && UnicodeTrie$1.get(codePoints[afterIndex]) === ZWJ$1) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB11 Do not break before or after Word joiner and related characters.
- if (current === WJ || next === WJ) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB12 Do not break after NBSP and related characters.
- if (current === GL) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB12a Do not break before NBSP and related characters, except after spaces and hyphens.
- if ([SP, BA, HY].indexOf(current) === -1 && next === GL) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB13 Do not break before ‘]’ or ‘!’ or ‘;’ or ‘/’, even after spaces.
- if ([CL, CP, EX, IS, SY].indexOf(next) !== -1) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB14 Do not break after ‘[’, even after spaces.
- if (previousNonSpaceClassType(currentIndex, classTypes) === OP) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB15 Do not break within ‘”[’, even with intervening spaces.
- if (isAdjacentWithSpaceIgnored(QU, OP, currentIndex, classTypes)) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB16 Do not break between closing punctuation and a nonstarter (lb=NS), even with intervening spaces.
- if (isAdjacentWithSpaceIgnored([CL, CP], NS, currentIndex, classTypes)) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB17 Do not break within ‘——’, even with intervening spaces.
- if (isAdjacentWithSpaceIgnored(B2, B2, currentIndex, classTypes)) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB18 Break after spaces.
- if (current === SP) {
- return BREAK_ALLOWED$1;
- }
- // LB19 Do not break before or after quotation marks, such as ‘ ” ’.
- if (current === QU || next === QU) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB20 Break before and after unresolved CB.
- if (next === CB || current === CB) {
- return BREAK_ALLOWED$1;
- }
- // LB21 Do not break before hyphen-minus, other hyphens, fixed-width spaces, small kana, and other non-starters, or after acute accents.
- if ([BA, HY, NS].indexOf(next) !== -1 || current === BB) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB21a Don't break after Hebrew + Hyphen.
- if (before === HL && HYPHEN.indexOf(current) !== -1) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB21b Don’t break between Solidus and Hebrew letters.
- if (current === SY && next === HL) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB22 Do not break before ellipsis.
- if (next === IN) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB23 Do not break between digits and letters.
- if ((ALPHABETICS.indexOf(next) !== -1 && current === NU) || (ALPHABETICS.indexOf(current) !== -1 && next === NU)) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB23a Do not break between numeric prefixes and ideographs, or between ideographs and numeric postfixes.
- if ((current === PR && [ID, EB, EM].indexOf(next) !== -1) ||
- ([ID, EB, EM].indexOf(current) !== -1 && next === PO)) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB24 Do not break between numeric prefix/postfix and letters, or between letters and prefix/postfix.
- if ((ALPHABETICS.indexOf(current) !== -1 && PREFIX_POSTFIX.indexOf(next) !== -1) ||
- (PREFIX_POSTFIX.indexOf(current) !== -1 && ALPHABETICS.indexOf(next) !== -1)) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB25 Do not break between the following pairs of classes relevant to numbers:
- if (
- // (PR | PO) × ( OP | HY )? NU
- ([PR, PO].indexOf(current) !== -1 &&
- (next === NU || ([OP, HY].indexOf(next) !== -1 && classTypes[afterIndex + 1] === NU))) ||
- // ( OP | HY ) × NU
- ([OP, HY].indexOf(current) !== -1 && next === NU) ||
- // NU × (NU | SY | IS)
- (current === NU && [NU, SY, IS].indexOf(next) !== -1)) {
- return BREAK_NOT_ALLOWED$1;
- }
- // NU (NU | SY | IS)* × (NU | SY | IS | CL | CP)
- if ([NU, SY, IS, CL, CP].indexOf(next) !== -1) {
- var prevIndex = currentIndex;
- while (prevIndex >= 0) {
- var type = classTypes[prevIndex];
- if (type === NU) {
- return BREAK_NOT_ALLOWED$1;
- }
- else if ([SY, IS].indexOf(type) !== -1) {
- prevIndex--;
- }
- else {
- break;
- }
- }
- }
- // NU (NU | SY | IS)* (CL | CP)? × (PO | PR))
- if ([PR, PO].indexOf(next) !== -1) {
- var prevIndex = [CL, CP].indexOf(current) !== -1 ? beforeIndex : currentIndex;
- while (prevIndex >= 0) {
- var type = classTypes[prevIndex];
- if (type === NU) {
- return BREAK_NOT_ALLOWED$1;
- }
- else if ([SY, IS].indexOf(type) !== -1) {
- prevIndex--;
- }
- else {
- break;
- }
- }
- }
- // LB26 Do not break a Korean syllable.
- if ((JL === current && [JL, JV, H2, H3].indexOf(next) !== -1) ||
- ([JV, H2].indexOf(current) !== -1 && [JV, JT].indexOf(next) !== -1) ||
- ([JT, H3].indexOf(current) !== -1 && next === JT)) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB27 Treat a Korean Syllable Block the same as ID.
- if ((KOREAN_SYLLABLE_BLOCK.indexOf(current) !== -1 && [IN, PO].indexOf(next) !== -1) ||
- (KOREAN_SYLLABLE_BLOCK.indexOf(next) !== -1 && current === PR)) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB28 Do not break between alphabetics (“at”).
- if (ALPHABETICS.indexOf(current) !== -1 && ALPHABETICS.indexOf(next) !== -1) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB29 Do not break between numeric punctuation and alphabetics (“e.g.”).
- if (current === IS && ALPHABETICS.indexOf(next) !== -1) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB30 Do not break between letters, numbers, or ordinary symbols and opening or closing parentheses.
- if ((ALPHABETICS.concat(NU).indexOf(current) !== -1 &&
- next === OP &&
- ea_OP.indexOf(codePoints[afterIndex]) === -1) ||
- (ALPHABETICS.concat(NU).indexOf(next) !== -1 && current === CP)) {
- return BREAK_NOT_ALLOWED$1;
- }
- // LB30a Break between two regional indicator symbols if and only if there are an even number of regional
- // indicators preceding the position of the break.
- if (current === RI$1 && next === RI$1) {
- var i = indicies[currentIndex];
- var count = 1;
- while (i > 0) {
- i--;
- if (classTypes[i] === RI$1) {
- count++;
- }
- else {
- break;
- }
- }
- if (count % 2 !== 0) {
- return BREAK_NOT_ALLOWED$1;
- }
- }
- // LB30b Do not break between an emoji base and an emoji modifier.
- if (current === EB && next === EM) {
- return BREAK_NOT_ALLOWED$1;
- }
- return BREAK_ALLOWED$1;
- };
- var cssFormattedClasses = function (codePoints, options) {
- if (!options) {
- options = { lineBreak: 'normal', wordBreak: 'normal' };
- }
- var _a = codePointsToCharacterClasses(codePoints, options.lineBreak), indicies = _a[0], classTypes = _a[1], isLetterNumber = _a[2];
- if (options.wordBreak === 'break-all' || options.wordBreak === 'break-word') {
- classTypes = classTypes.map(function (type) { return ([NU, AL, SA].indexOf(type) !== -1 ? ID : type); });
- }
- var forbiddenBreakpoints = options.wordBreak === 'keep-all'
- ? isLetterNumber.map(function (letterNumber, i) {
- return letterNumber && codePoints[i] >= 0x4e00 && codePoints[i] <= 0x9fff;
- })
- : undefined;
- return [indicies, classTypes, forbiddenBreakpoints];
- };
- var Break = /** @class */ (function () {
- function Break(codePoints, lineBreak, start, end) {
- this.codePoints = codePoints;
- this.required = lineBreak === BREAK_MANDATORY;
- this.start = start;
- this.end = end;
- }
- Break.prototype.slice = function () {
- return fromCodePoint$1.apply(void 0, this.codePoints.slice(this.start, this.end));
- };
- return Break;
- }());
- var LineBreaker = function (str, options) {
- var codePoints = toCodePoints$1(str);
- var _a = cssFormattedClasses(codePoints, options), indicies = _a[0], classTypes = _a[1], forbiddenBreakpoints = _a[2];
- var length = codePoints.length;
- var lastEnd = 0;
- var nextIndex = 0;
- return {
- next: function () {
- if (nextIndex >= length) {
- return { done: true, value: null };
- }
- var lineBreak = BREAK_NOT_ALLOWED$1;
- while (nextIndex < length &&
- (lineBreak = _lineBreakAtIndex(codePoints, classTypes, indicies, ++nextIndex, forbiddenBreakpoints)) ===
- BREAK_NOT_ALLOWED$1) { }
- if (lineBreak !== BREAK_NOT_ALLOWED$1 || nextIndex === length) {
- var value = new Break(codePoints, lineBreak, lastEnd, nextIndex);
- lastEnd = nextIndex;
- return { value: value, done: false };
- }
- return { done: true, value: null };
- },
- };
- };
-
- // https://www.w3.org/TR/css-syntax-3
- var FLAG_UNRESTRICTED = 1 << 0;
- var FLAG_ID = 1 << 1;
- var FLAG_INTEGER = 1 << 2;
- var FLAG_NUMBER = 1 << 3;
- var LINE_FEED = 0x000a;
- var SOLIDUS = 0x002f;
- var REVERSE_SOLIDUS = 0x005c;
- var CHARACTER_TABULATION = 0x0009;
- var SPACE = 0x0020;
- var QUOTATION_MARK = 0x0022;
- var EQUALS_SIGN = 0x003d;
- var NUMBER_SIGN = 0x0023;
- var DOLLAR_SIGN = 0x0024;
- var PERCENTAGE_SIGN = 0x0025;
- var APOSTROPHE = 0x0027;
- var LEFT_PARENTHESIS = 0x0028;
- var RIGHT_PARENTHESIS = 0x0029;
- var LOW_LINE = 0x005f;
- var HYPHEN_MINUS = 0x002d;
- var EXCLAMATION_MARK = 0x0021;
- var LESS_THAN_SIGN = 0x003c;
- var GREATER_THAN_SIGN = 0x003e;
- var COMMERCIAL_AT = 0x0040;
- var LEFT_SQUARE_BRACKET = 0x005b;
- var RIGHT_SQUARE_BRACKET = 0x005d;
- var CIRCUMFLEX_ACCENT = 0x003d;
- var LEFT_CURLY_BRACKET = 0x007b;
- var QUESTION_MARK = 0x003f;
- var RIGHT_CURLY_BRACKET = 0x007d;
- var VERTICAL_LINE = 0x007c;
- var TILDE = 0x007e;
- var CONTROL = 0x0080;
- var REPLACEMENT_CHARACTER = 0xfffd;
- var ASTERISK = 0x002a;
- var PLUS_SIGN = 0x002b;
- var COMMA = 0x002c;
- var COLON = 0x003a;
- var SEMICOLON = 0x003b;
- var FULL_STOP = 0x002e;
- var NULL = 0x0000;
- var BACKSPACE = 0x0008;
- var LINE_TABULATION = 0x000b;
- var SHIFT_OUT = 0x000e;
- var INFORMATION_SEPARATOR_ONE = 0x001f;
- var DELETE = 0x007f;
- var EOF = -1;
- var ZERO = 0x0030;
- var a = 0x0061;
- var e = 0x0065;
- var f = 0x0066;
- var u = 0x0075;
- var z = 0x007a;
- var A = 0x0041;
- var E = 0x0045;
- var F = 0x0046;
- var U = 0x0055;
- var Z = 0x005a;
- var isDigit = function (codePoint) { return codePoint >= ZERO && codePoint <= 0x0039; };
- var isSurrogateCodePoint = function (codePoint) { return codePoint >= 0xd800 && codePoint <= 0xdfff; };
- var isHex = function (codePoint) {
- return isDigit(codePoint) || (codePoint >= A && codePoint <= F) || (codePoint >= a && codePoint <= f);
- };
- var isLowerCaseLetter = function (codePoint) { return codePoint >= a && codePoint <= z; };
- var isUpperCaseLetter = function (codePoint) { return codePoint >= A && codePoint <= Z; };
- var isLetter = function (codePoint) { return isLowerCaseLetter(codePoint) || isUpperCaseLetter(codePoint); };
- var isNonASCIICodePoint = function (codePoint) { return codePoint >= CONTROL; };
- var isWhiteSpace = function (codePoint) {
- return codePoint === LINE_FEED || codePoint === CHARACTER_TABULATION || codePoint === SPACE;
- };
- var isNameStartCodePoint = function (codePoint) {
- return isLetter(codePoint) || isNonASCIICodePoint(codePoint) || codePoint === LOW_LINE;
- };
- var isNameCodePoint = function (codePoint) {
- return isNameStartCodePoint(codePoint) || isDigit(codePoint) || codePoint === HYPHEN_MINUS;
- };
- var isNonPrintableCodePoint = function (codePoint) {
- return ((codePoint >= NULL && codePoint <= BACKSPACE) ||
- codePoint === LINE_TABULATION ||
- (codePoint >= SHIFT_OUT && codePoint <= INFORMATION_SEPARATOR_ONE) ||
- codePoint === DELETE);
- };
- var isValidEscape = function (c1, c2) {
- if (c1 !== REVERSE_SOLIDUS) {
- return false;
- }
- return c2 !== LINE_FEED;
- };
- var isIdentifierStart = function (c1, c2, c3) {
- if (c1 === HYPHEN_MINUS) {
- return isNameStartCodePoint(c2) || isValidEscape(c2, c3);
- }
- else if (isNameStartCodePoint(c1)) {
- return true;
- }
- else if (c1 === REVERSE_SOLIDUS && isValidEscape(c1, c2)) {
- return true;
- }
- return false;
- };
- var isNumberStart = function (c1, c2, c3) {
- if (c1 === PLUS_SIGN || c1 === HYPHEN_MINUS) {
- if (isDigit(c2)) {
- return true;
- }
- return c2 === FULL_STOP && isDigit(c3);
- }
- if (c1 === FULL_STOP) {
- return isDigit(c2);
- }
- return isDigit(c1);
- };
- var stringToNumber = function (codePoints) {
- var c = 0;
- var sign = 1;
- if (codePoints[c] === PLUS_SIGN || codePoints[c] === HYPHEN_MINUS) {
- if (codePoints[c] === HYPHEN_MINUS) {
- sign = -1;
- }
- c++;
- }
- var integers = [];
- while (isDigit(codePoints[c])) {
- integers.push(codePoints[c++]);
- }
- var int = integers.length ? parseInt(fromCodePoint$1.apply(void 0, integers), 10) : 0;
- if (codePoints[c] === FULL_STOP) {
- c++;
- }
- var fraction = [];
- while (isDigit(codePoints[c])) {
- fraction.push(codePoints[c++]);
- }
- var fracd = fraction.length;
- var frac = fracd ? parseInt(fromCodePoint$1.apply(void 0, fraction), 10) : 0;
- if (codePoints[c] === E || codePoints[c] === e) {
- c++;
- }
- var expsign = 1;
- if (codePoints[c] === PLUS_SIGN || codePoints[c] === HYPHEN_MINUS) {
- if (codePoints[c] === HYPHEN_MINUS) {
- expsign = -1;
- }
- c++;
- }
- var exponent = [];
- while (isDigit(codePoints[c])) {
- exponent.push(codePoints[c++]);
- }
- var exp = exponent.length ? parseInt(fromCodePoint$1.apply(void 0, exponent), 10) : 0;
- return sign * (int + frac * Math.pow(10, -fracd)) * Math.pow(10, expsign * exp);
- };
- var LEFT_PARENTHESIS_TOKEN = {
- type: 2 /* LEFT_PARENTHESIS_TOKEN */
- };
- var RIGHT_PARENTHESIS_TOKEN = {
- type: 3 /* RIGHT_PARENTHESIS_TOKEN */
- };
- var COMMA_TOKEN = { type: 4 /* COMMA_TOKEN */ };
- var SUFFIX_MATCH_TOKEN = { type: 13 /* SUFFIX_MATCH_TOKEN */ };
- var PREFIX_MATCH_TOKEN = { type: 8 /* PREFIX_MATCH_TOKEN */ };
- var COLUMN_TOKEN = { type: 21 /* COLUMN_TOKEN */ };
- var DASH_MATCH_TOKEN = { type: 9 /* DASH_MATCH_TOKEN */ };
- var INCLUDE_MATCH_TOKEN = { type: 10 /* INCLUDE_MATCH_TOKEN */ };
- var LEFT_CURLY_BRACKET_TOKEN = {
- type: 11 /* LEFT_CURLY_BRACKET_TOKEN */
- };
- var RIGHT_CURLY_BRACKET_TOKEN = {
- type: 12 /* RIGHT_CURLY_BRACKET_TOKEN */
- };
- var SUBSTRING_MATCH_TOKEN = { type: 14 /* SUBSTRING_MATCH_TOKEN */ };
- var BAD_URL_TOKEN = { type: 23 /* BAD_URL_TOKEN */ };
- var BAD_STRING_TOKEN = { type: 1 /* BAD_STRING_TOKEN */ };
- var CDO_TOKEN = { type: 25 /* CDO_TOKEN */ };
- var CDC_TOKEN = { type: 24 /* CDC_TOKEN */ };
- var COLON_TOKEN = { type: 26 /* COLON_TOKEN */ };
- var SEMICOLON_TOKEN = { type: 27 /* SEMICOLON_TOKEN */ };
- var LEFT_SQUARE_BRACKET_TOKEN = {
- type: 28 /* LEFT_SQUARE_BRACKET_TOKEN */
- };
- var RIGHT_SQUARE_BRACKET_TOKEN = {
- type: 29 /* RIGHT_SQUARE_BRACKET_TOKEN */
- };
- var WHITESPACE_TOKEN = { type: 31 /* WHITESPACE_TOKEN */ };
- var EOF_TOKEN = { type: 32 /* EOF_TOKEN */ };
- var Tokenizer = /** @class */ (function () {
- function Tokenizer() {
- this._value = [];
- }
- Tokenizer.prototype.write = function (chunk) {
- this._value = this._value.concat(toCodePoints$1(chunk));
- };
- Tokenizer.prototype.read = function () {
- var tokens = [];
- var token = this.consumeToken();
- while (token !== EOF_TOKEN) {
- tokens.push(token);
- token = this.consumeToken();
- }
- return tokens;
- };
- Tokenizer.prototype.consumeToken = function () {
- var codePoint = this.consumeCodePoint();
- switch (codePoint) {
- case QUOTATION_MARK:
- return this.consumeStringToken(QUOTATION_MARK);
- case NUMBER_SIGN:
- var c1 = this.peekCodePoint(0);
- var c2 = this.peekCodePoint(1);
- var c3 = this.peekCodePoint(2);
- if (isNameCodePoint(c1) || isValidEscape(c2, c3)) {
- var flags = isIdentifierStart(c1, c2, c3) ? FLAG_ID : FLAG_UNRESTRICTED;
- var value = this.consumeName();
- return { type: 5 /* HASH_TOKEN */, value: value, flags: flags };
- }
- break;
- case DOLLAR_SIGN:
- if (this.peekCodePoint(0) === EQUALS_SIGN) {
- this.consumeCodePoint();
- return SUFFIX_MATCH_TOKEN;
- }
- break;
- case APOSTROPHE:
- return this.consumeStringToken(APOSTROPHE);
- case LEFT_PARENTHESIS:
- return LEFT_PARENTHESIS_TOKEN;
- case RIGHT_PARENTHESIS:
- return RIGHT_PARENTHESIS_TOKEN;
- case ASTERISK:
- if (this.peekCodePoint(0) === EQUALS_SIGN) {
- this.consumeCodePoint();
- return SUBSTRING_MATCH_TOKEN;
- }
- break;
- case PLUS_SIGN:
- if (isNumberStart(codePoint, this.peekCodePoint(0), this.peekCodePoint(1))) {
- this.reconsumeCodePoint(codePoint);
- return this.consumeNumericToken();
- }
- break;
- case COMMA:
- return COMMA_TOKEN;
- case HYPHEN_MINUS:
- var e1 = codePoint;
- var e2 = this.peekCodePoint(0);
- var e3 = this.peekCodePoint(1);
- if (isNumberStart(e1, e2, e3)) {
- this.reconsumeCodePoint(codePoint);
- return this.consumeNumericToken();
- }
- if (isIdentifierStart(e1, e2, e3)) {
- this.reconsumeCodePoint(codePoint);
- return this.consumeIdentLikeToken();
- }
- if (e2 === HYPHEN_MINUS && e3 === GREATER_THAN_SIGN) {
- this.consumeCodePoint();
- this.consumeCodePoint();
- return CDC_TOKEN;
- }
- break;
- case FULL_STOP:
- if (isNumberStart(codePoint, this.peekCodePoint(0), this.peekCodePoint(1))) {
- this.reconsumeCodePoint(codePoint);
- return this.consumeNumericToken();
- }
- break;
- case SOLIDUS:
- if (this.peekCodePoint(0) === ASTERISK) {
- this.consumeCodePoint();
- while (true) {
- var c = this.consumeCodePoint();
- if (c === ASTERISK) {
- c = this.consumeCodePoint();
- if (c === SOLIDUS) {
- return this.consumeToken();
- }
- }
- if (c === EOF) {
- return this.consumeToken();
- }
- }
- }
- break;
- case COLON:
- return COLON_TOKEN;
- case SEMICOLON:
- return SEMICOLON_TOKEN;
- case LESS_THAN_SIGN:
- if (this.peekCodePoint(0) === EXCLAMATION_MARK &&
- this.peekCodePoint(1) === HYPHEN_MINUS &&
- this.peekCodePoint(2) === HYPHEN_MINUS) {
- this.consumeCodePoint();
- this.consumeCodePoint();
- return CDO_TOKEN;
- }
- break;
- case COMMERCIAL_AT:
- var a1 = this.peekCodePoint(0);
- var a2 = this.peekCodePoint(1);
- var a3 = this.peekCodePoint(2);
- if (isIdentifierStart(a1, a2, a3)) {
- var value = this.consumeName();
- return { type: 7 /* AT_KEYWORD_TOKEN */, value: value };
- }
- break;
- case LEFT_SQUARE_BRACKET:
- return LEFT_SQUARE_BRACKET_TOKEN;
- case REVERSE_SOLIDUS:
- if (isValidEscape(codePoint, this.peekCodePoint(0))) {
- this.reconsumeCodePoint(codePoint);
- return this.consumeIdentLikeToken();
- }
- break;
- case RIGHT_SQUARE_BRACKET:
- return RIGHT_SQUARE_BRACKET_TOKEN;
- case CIRCUMFLEX_ACCENT:
- if (this.peekCodePoint(0) === EQUALS_SIGN) {
- this.consumeCodePoint();
- return PREFIX_MATCH_TOKEN;
- }
- break;
- case LEFT_CURLY_BRACKET:
- return LEFT_CURLY_BRACKET_TOKEN;
- case RIGHT_CURLY_BRACKET:
- return RIGHT_CURLY_BRACKET_TOKEN;
- case u:
- case U:
- var u1 = this.peekCodePoint(0);
- var u2 = this.peekCodePoint(1);
- if (u1 === PLUS_SIGN && (isHex(u2) || u2 === QUESTION_MARK)) {
- this.consumeCodePoint();
- this.consumeUnicodeRangeToken();
- }
- this.reconsumeCodePoint(codePoint);
- return this.consumeIdentLikeToken();
- case VERTICAL_LINE:
- if (this.peekCodePoint(0) === EQUALS_SIGN) {
- this.consumeCodePoint();
- return DASH_MATCH_TOKEN;
- }
- if (this.peekCodePoint(0) === VERTICAL_LINE) {
- this.consumeCodePoint();
- return COLUMN_TOKEN;
- }
- break;
- case TILDE:
- if (this.peekCodePoint(0) === EQUALS_SIGN) {
- this.consumeCodePoint();
- return INCLUDE_MATCH_TOKEN;
- }
- break;
- case EOF:
- return EOF_TOKEN;
- }
- if (isWhiteSpace(codePoint)) {
- this.consumeWhiteSpace();
- return WHITESPACE_TOKEN;
- }
- if (isDigit(codePoint)) {
- this.reconsumeCodePoint(codePoint);
- return this.consumeNumericToken();
- }
- if (isNameStartCodePoint(codePoint)) {
- this.reconsumeCodePoint(codePoint);
- return this.consumeIdentLikeToken();
- }
- return { type: 6 /* DELIM_TOKEN */, value: fromCodePoint$1(codePoint) };
- };
- Tokenizer.prototype.consumeCodePoint = function () {
- var value = this._value.shift();
- return typeof value === 'undefined' ? -1 : value;
- };
- Tokenizer.prototype.reconsumeCodePoint = function (codePoint) {
- this._value.unshift(codePoint);
- };
- Tokenizer.prototype.peekCodePoint = function (delta) {
- if (delta >= this._value.length) {
- return -1;
- }
- return this._value[delta];
- };
- Tokenizer.prototype.consumeUnicodeRangeToken = function () {
- var digits = [];
- var codePoint = this.consumeCodePoint();
- while (isHex(codePoint) && digits.length < 6) {
- digits.push(codePoint);
- codePoint = this.consumeCodePoint();
- }
- var questionMarks = false;
- while (codePoint === QUESTION_MARK && digits.length < 6) {
- digits.push(codePoint);
- codePoint = this.consumeCodePoint();
- questionMarks = true;
- }
- if (questionMarks) {
- var start_1 = parseInt(fromCodePoint$1.apply(void 0, digits.map(function (digit) { return (digit === QUESTION_MARK ? ZERO : digit); })), 16);
- var end = parseInt(fromCodePoint$1.apply(void 0, digits.map(function (digit) { return (digit === QUESTION_MARK ? F : digit); })), 16);
- return { type: 30 /* UNICODE_RANGE_TOKEN */, start: start_1, end: end };
- }
- var start = parseInt(fromCodePoint$1.apply(void 0, digits), 16);
- if (this.peekCodePoint(0) === HYPHEN_MINUS && isHex(this.peekCodePoint(1))) {
- this.consumeCodePoint();
- codePoint = this.consumeCodePoint();
- var endDigits = [];
- while (isHex(codePoint) && endDigits.length < 6) {
- endDigits.push(codePoint);
- codePoint = this.consumeCodePoint();
- }
- var end = parseInt(fromCodePoint$1.apply(void 0, endDigits), 16);
- return { type: 30 /* UNICODE_RANGE_TOKEN */, start: start, end: end };
- }
- else {
- return { type: 30 /* UNICODE_RANGE_TOKEN */, start: start, end: start };
- }
- };
- Tokenizer.prototype.consumeIdentLikeToken = function () {
- var value = this.consumeName();
- if (value.toLowerCase() === 'url' && this.peekCodePoint(0) === LEFT_PARENTHESIS) {
- this.consumeCodePoint();
- return this.consumeUrlToken();
- }
- else if (this.peekCodePoint(0) === LEFT_PARENTHESIS) {
- this.consumeCodePoint();
- return { type: 19 /* FUNCTION_TOKEN */, value: value };
- }
- return { type: 20 /* IDENT_TOKEN */, value: value };
- };
- Tokenizer.prototype.consumeUrlToken = function () {
- var value = [];
- this.consumeWhiteSpace();
- if (this.peekCodePoint(0) === EOF) {
- return { type: 22 /* URL_TOKEN */, value: '' };
- }
- var next = this.peekCodePoint(0);
- if (next === APOSTROPHE || next === QUOTATION_MARK) {
- var stringToken = this.consumeStringToken(this.consumeCodePoint());
- if (stringToken.type === 0 /* STRING_TOKEN */) {
- this.consumeWhiteSpace();
- if (this.peekCodePoint(0) === EOF || this.peekCodePoint(0) === RIGHT_PARENTHESIS) {
- this.consumeCodePoint();
- return { type: 22 /* URL_TOKEN */, value: stringToken.value };
- }
- }
- this.consumeBadUrlRemnants();
- return BAD_URL_TOKEN;
- }
- while (true) {
- var codePoint = this.consumeCodePoint();
- if (codePoint === EOF || codePoint === RIGHT_PARENTHESIS) {
- return { type: 22 /* URL_TOKEN */, value: fromCodePoint$1.apply(void 0, value) };
- }
- else if (isWhiteSpace(codePoint)) {
- this.consumeWhiteSpace();
- if (this.peekCodePoint(0) === EOF || this.peekCodePoint(0) === RIGHT_PARENTHESIS) {
- this.consumeCodePoint();
- return { type: 22 /* URL_TOKEN */, value: fromCodePoint$1.apply(void 0, value) };
- }
- this.consumeBadUrlRemnants();
- return BAD_URL_TOKEN;
- }
- else if (codePoint === QUOTATION_MARK ||
- codePoint === APOSTROPHE ||
- codePoint === LEFT_PARENTHESIS ||
- isNonPrintableCodePoint(codePoint)) {
- this.consumeBadUrlRemnants();
- return BAD_URL_TOKEN;
- }
- else if (codePoint === REVERSE_SOLIDUS) {
- if (isValidEscape(codePoint, this.peekCodePoint(0))) {
- value.push(this.consumeEscapedCodePoint());
- }
- else {
- this.consumeBadUrlRemnants();
- return BAD_URL_TOKEN;
- }
- }
- else {
- value.push(codePoint);
- }
- }
- };
- Tokenizer.prototype.consumeWhiteSpace = function () {
- while (isWhiteSpace(this.peekCodePoint(0))) {
- this.consumeCodePoint();
- }
- };
- Tokenizer.prototype.consumeBadUrlRemnants = function () {
- while (true) {
- var codePoint = this.consumeCodePoint();
- if (codePoint === RIGHT_PARENTHESIS || codePoint === EOF) {
- return;
- }
- if (isValidEscape(codePoint, this.peekCodePoint(0))) {
- this.consumeEscapedCodePoint();
- }
- }
- };
- Tokenizer.prototype.consumeStringSlice = function (count) {
- var SLICE_STACK_SIZE = 50000;
- var value = '';
- while (count > 0) {
- var amount = Math.min(SLICE_STACK_SIZE, count);
- value += fromCodePoint$1.apply(void 0, this._value.splice(0, amount));
- count -= amount;
- }
- this._value.shift();
- return value;
- };
- Tokenizer.prototype.consumeStringToken = function (endingCodePoint) {
- var value = '';
- var i = 0;
- do {
- var codePoint = this._value[i];
- if (codePoint === EOF || codePoint === undefined || codePoint === endingCodePoint) {
- value += this.consumeStringSlice(i);
- return { type: 0 /* STRING_TOKEN */, value: value };
- }
- if (codePoint === LINE_FEED) {
- this._value.splice(0, i);
- return BAD_STRING_TOKEN;
- }
- if (codePoint === REVERSE_SOLIDUS) {
- var next = this._value[i + 1];
- if (next !== EOF && next !== undefined) {
- if (next === LINE_FEED) {
- value += this.consumeStringSlice(i);
- i = -1;
- this._value.shift();
- }
- else if (isValidEscape(codePoint, next)) {
- value += this.consumeStringSlice(i);
- value += fromCodePoint$1(this.consumeEscapedCodePoint());
- i = -1;
- }
- }
- }
- i++;
- } while (true);
- };
- Tokenizer.prototype.consumeNumber = function () {
- var repr = [];
- var type = FLAG_INTEGER;
- var c1 = this.peekCodePoint(0);
- if (c1 === PLUS_SIGN || c1 === HYPHEN_MINUS) {
- repr.push(this.consumeCodePoint());
- }
- while (isDigit(this.peekCodePoint(0))) {
- repr.push(this.consumeCodePoint());
- }
- c1 = this.peekCodePoint(0);
- var c2 = this.peekCodePoint(1);
- if (c1 === FULL_STOP && isDigit(c2)) {
- repr.push(this.consumeCodePoint(), this.consumeCodePoint());
- type = FLAG_NUMBER;
- while (isDigit(this.peekCodePoint(0))) {
- repr.push(this.consumeCodePoint());
- }
- }
- c1 = this.peekCodePoint(0);
- c2 = this.peekCodePoint(1);
- var c3 = this.peekCodePoint(2);
- if ((c1 === E || c1 === e) && (((c2 === PLUS_SIGN || c2 === HYPHEN_MINUS) && isDigit(c3)) || isDigit(c2))) {
- repr.push(this.consumeCodePoint(), this.consumeCodePoint());
- type = FLAG_NUMBER;
- while (isDigit(this.peekCodePoint(0))) {
- repr.push(this.consumeCodePoint());
- }
- }
- return [stringToNumber(repr), type];
- };
- Tokenizer.prototype.consumeNumericToken = function () {
- var _a = this.consumeNumber(), number = _a[0], flags = _a[1];
- var c1 = this.peekCodePoint(0);
- var c2 = this.peekCodePoint(1);
- var c3 = this.peekCodePoint(2);
- if (isIdentifierStart(c1, c2, c3)) {
- var unit = this.consumeName();
- return { type: 15 /* DIMENSION_TOKEN */, number: number, flags: flags, unit: unit };
- }
- if (c1 === PERCENTAGE_SIGN) {
- this.consumeCodePoint();
- return { type: 16 /* PERCENTAGE_TOKEN */, number: number, flags: flags };
- }
- return { type: 17 /* NUMBER_TOKEN */, number: number, flags: flags };
- };
- Tokenizer.prototype.consumeEscapedCodePoint = function () {
- var codePoint = this.consumeCodePoint();
- if (isHex(codePoint)) {
- var hex = fromCodePoint$1(codePoint);
- while (isHex(this.peekCodePoint(0)) && hex.length < 6) {
- hex += fromCodePoint$1(this.consumeCodePoint());
- }
- if (isWhiteSpace(this.peekCodePoint(0))) {
- this.consumeCodePoint();
- }
- var hexCodePoint = parseInt(hex, 16);
- if (hexCodePoint === 0 || isSurrogateCodePoint(hexCodePoint) || hexCodePoint > 0x10ffff) {
- return REPLACEMENT_CHARACTER;
- }
- return hexCodePoint;
- }
- if (codePoint === EOF) {
- return REPLACEMENT_CHARACTER;
- }
- return codePoint;
- };
- Tokenizer.prototype.consumeName = function () {
- var result = '';
- while (true) {
- var codePoint = this.consumeCodePoint();
- if (isNameCodePoint(codePoint)) {
- result += fromCodePoint$1(codePoint);
- }
- else if (isValidEscape(codePoint, this.peekCodePoint(0))) {
- result += fromCodePoint$1(this.consumeEscapedCodePoint());
- }
- else {
- this.reconsumeCodePoint(codePoint);
- return result;
- }
- }
- };
- return Tokenizer;
- }());
-
- var Parser = /** @class */ (function () {
- function Parser(tokens) {
- this._tokens = tokens;
- }
- Parser.create = function (value) {
- var tokenizer = new Tokenizer();
- tokenizer.write(value);
- return new Parser(tokenizer.read());
- };
- Parser.parseValue = function (value) {
- return Parser.create(value).parseComponentValue();
- };
- Parser.parseValues = function (value) {
- return Parser.create(value).parseComponentValues();
- };
- Parser.prototype.parseComponentValue = function () {
- var token = this.consumeToken();
- while (token.type === 31 /* WHITESPACE_TOKEN */) {
- token = this.consumeToken();
- }
- if (token.type === 32 /* EOF_TOKEN */) {
- throw new SyntaxError("Error parsing CSS component value, unexpected EOF");
- }
- this.reconsumeToken(token);
- var value = this.consumeComponentValue();
- do {
- token = this.consumeToken();
- } while (token.type === 31 /* WHITESPACE_TOKEN */);
- if (token.type === 32 /* EOF_TOKEN */) {
- return value;
- }
- throw new SyntaxError("Error parsing CSS component value, multiple values found when expecting only one");
- };
- Parser.prototype.parseComponentValues = function () {
- var values = [];
- while (true) {
- var value = this.consumeComponentValue();
- if (value.type === 32 /* EOF_TOKEN */) {
- return values;
- }
- values.push(value);
- values.push();
- }
- };
- Parser.prototype.consumeComponentValue = function () {
- var token = this.consumeToken();
- switch (token.type) {
- case 11 /* LEFT_CURLY_BRACKET_TOKEN */:
- case 28 /* LEFT_SQUARE_BRACKET_TOKEN */:
- case 2 /* LEFT_PARENTHESIS_TOKEN */:
- return this.consumeSimpleBlock(token.type);
- case 19 /* FUNCTION_TOKEN */:
- return this.consumeFunction(token);
- }
- return token;
- };
- Parser.prototype.consumeSimpleBlock = function (type) {
- var block = { type: type, values: [] };
- var token = this.consumeToken();
- while (true) {
- if (token.type === 32 /* EOF_TOKEN */ || isEndingTokenFor(token, type)) {
- return block;
- }
- this.reconsumeToken(token);
- block.values.push(this.consumeComponentValue());
- token = this.consumeToken();
- }
- };
- Parser.prototype.consumeFunction = function (functionToken) {
- var cssFunction = {
- name: functionToken.value,
- values: [],
- type: 18 /* FUNCTION */
- };
- while (true) {
- var token = this.consumeToken();
- if (token.type === 32 /* EOF_TOKEN */ || token.type === 3 /* RIGHT_PARENTHESIS_TOKEN */) {
- return cssFunction;
- }
- this.reconsumeToken(token);
- cssFunction.values.push(this.consumeComponentValue());
- }
- };
- Parser.prototype.consumeToken = function () {
- var token = this._tokens.shift();
- return typeof token === 'undefined' ? EOF_TOKEN : token;
- };
- Parser.prototype.reconsumeToken = function (token) {
- this._tokens.unshift(token);
- };
- return Parser;
- }());
- var isDimensionToken = function (token) { return token.type === 15 /* DIMENSION_TOKEN */; };
- var isNumberToken = function (token) { return token.type === 17 /* NUMBER_TOKEN */; };
- var isIdentToken = function (token) { return token.type === 20 /* IDENT_TOKEN */; };
- var isStringToken = function (token) { return token.type === 0 /* STRING_TOKEN */; };
- var isIdentWithValue = function (token, value) {
- return isIdentToken(token) && token.value === value;
- };
- var nonWhiteSpace = function (token) { return token.type !== 31 /* WHITESPACE_TOKEN */; };
- var nonFunctionArgSeparator = function (token) {
- return token.type !== 31 /* WHITESPACE_TOKEN */ && token.type !== 4 /* COMMA_TOKEN */;
- };
- var parseFunctionArgs = function (tokens) {
- var args = [];
- var arg = [];
- tokens.forEach(function (token) {
- if (token.type === 4 /* COMMA_TOKEN */) {
- if (arg.length === 0) {
- throw new Error("Error parsing function args, zero tokens for arg");
- }
- args.push(arg);
- arg = [];
- return;
- }
- if (token.type !== 31 /* WHITESPACE_TOKEN */) {
- arg.push(token);
- }
- });
- if (arg.length) {
- args.push(arg);
- }
- return args;
- };
- var isEndingTokenFor = function (token, type) {
- if (type === 11 /* LEFT_CURLY_BRACKET_TOKEN */ && token.type === 12 /* RIGHT_CURLY_BRACKET_TOKEN */) {
- return true;
- }
- if (type === 28 /* LEFT_SQUARE_BRACKET_TOKEN */ && token.type === 29 /* RIGHT_SQUARE_BRACKET_TOKEN */) {
- return true;
- }
- return type === 2 /* LEFT_PARENTHESIS_TOKEN */ && token.type === 3 /* RIGHT_PARENTHESIS_TOKEN */;
- };
-
- var isLength = function (token) {
- return token.type === 17 /* NUMBER_TOKEN */ || token.type === 15 /* DIMENSION_TOKEN */;
- };
-
- var isLengthPercentage = function (token) {
- return token.type === 16 /* PERCENTAGE_TOKEN */ || isLength(token);
- };
- var parseLengthPercentageTuple = function (tokens) {
- return tokens.length > 1 ? [tokens[0], tokens[1]] : [tokens[0]];
- };
- var ZERO_LENGTH = {
- type: 17 /* NUMBER_TOKEN */,
- number: 0,
- flags: FLAG_INTEGER
- };
- var FIFTY_PERCENT = {
- type: 16 /* PERCENTAGE_TOKEN */,
- number: 50,
- flags: FLAG_INTEGER
- };
- var HUNDRED_PERCENT = {
- type: 16 /* PERCENTAGE_TOKEN */,
- number: 100,
- flags: FLAG_INTEGER
- };
- var getAbsoluteValueForTuple = function (tuple, width, height) {
- var x = tuple[0], y = tuple[1];
- return [getAbsoluteValue(x, width), getAbsoluteValue(typeof y !== 'undefined' ? y : x, height)];
- };
- var getAbsoluteValue = function (token, parent) {
- if (token.type === 16 /* PERCENTAGE_TOKEN */) {
- return (token.number / 100) * parent;
- }
- if (isDimensionToken(token)) {
- switch (token.unit) {
- case 'rem':
- case 'em':
- return 16 * token.number; // TODO use correct font-size
- case 'px':
- default:
- return token.number;
- }
- }
- return token.number;
- };
-
- var DEG = 'deg';
- var GRAD = 'grad';
- var RAD = 'rad';
- var TURN = 'turn';
- var angle = {
- name: 'angle',
- parse: function (_context, value) {
- if (value.type === 15 /* DIMENSION_TOKEN */) {
- switch (value.unit) {
- case DEG:
- return (Math.PI * value.number) / 180;
- case GRAD:
- return (Math.PI / 200) * value.number;
- case RAD:
- return value.number;
- case TURN:
- return Math.PI * 2 * value.number;
- }
- }
- throw new Error("Unsupported angle type");
- }
- };
- var isAngle = function (value) {
- if (value.type === 15 /* DIMENSION_TOKEN */) {
- if (value.unit === DEG || value.unit === GRAD || value.unit === RAD || value.unit === TURN) {
- return true;
- }
- }
- return false;
- };
- var parseNamedSide = function (tokens) {
- var sideOrCorner = tokens
- .filter(isIdentToken)
- .map(function (ident) { return ident.value; })
- .join(' ');
- switch (sideOrCorner) {
- case 'to bottom right':
- case 'to right bottom':
- case 'left top':
- case 'top left':
- return [ZERO_LENGTH, ZERO_LENGTH];
- case 'to top':
- case 'bottom':
- return deg(0);
- case 'to bottom left':
- case 'to left bottom':
- case 'right top':
- case 'top right':
- return [ZERO_LENGTH, HUNDRED_PERCENT];
- case 'to right':
- case 'left':
- return deg(90);
- case 'to top left':
- case 'to left top':
- case 'right bottom':
- case 'bottom right':
- return [HUNDRED_PERCENT, HUNDRED_PERCENT];
- case 'to bottom':
- case 'top':
- return deg(180);
- case 'to top right':
- case 'to right top':
- case 'left bottom':
- case 'bottom left':
- return [HUNDRED_PERCENT, ZERO_LENGTH];
- case 'to left':
- case 'right':
- return deg(270);
- }
- return 0;
- };
- var deg = function (deg) { return (Math.PI * deg) / 180; };
-
- var color$1 = {
- name: 'color',
- parse: function (context, value) {
- if (value.type === 18 /* FUNCTION */) {
- var colorFunction = SUPPORTED_COLOR_FUNCTIONS[value.name];
- if (typeof colorFunction === 'undefined') {
- throw new Error("Attempting to parse an unsupported color function \"" + value.name + "\"");
- }
- return colorFunction(context, value.values);
- }
- if (value.type === 5 /* HASH_TOKEN */) {
- if (value.value.length === 3) {
- var r = value.value.substring(0, 1);
- var g = value.value.substring(1, 2);
- var b = value.value.substring(2, 3);
- return pack(parseInt(r + r, 16), parseInt(g + g, 16), parseInt(b + b, 16), 1);
- }
- if (value.value.length === 4) {
- var r = value.value.substring(0, 1);
- var g = value.value.substring(1, 2);
- var b = value.value.substring(2, 3);
- var a = value.value.substring(3, 4);
- return pack(parseInt(r + r, 16), parseInt(g + g, 16), parseInt(b + b, 16), parseInt(a + a, 16) / 255);
- }
- if (value.value.length === 6) {
- var r = value.value.substring(0, 2);
- var g = value.value.substring(2, 4);
- var b = value.value.substring(4, 6);
- return pack(parseInt(r, 16), parseInt(g, 16), parseInt(b, 16), 1);
- }
- if (value.value.length === 8) {
- var r = value.value.substring(0, 2);
- var g = value.value.substring(2, 4);
- var b = value.value.substring(4, 6);
- var a = value.value.substring(6, 8);
- return pack(parseInt(r, 16), parseInt(g, 16), parseInt(b, 16), parseInt(a, 16) / 255);
- }
- }
- if (value.type === 20 /* IDENT_TOKEN */) {
- var namedColor = COLORS[value.value.toUpperCase()];
- if (typeof namedColor !== 'undefined') {
- return namedColor;
- }
- }
- return COLORS.TRANSPARENT;
- }
- };
- var isTransparent = function (color) { return (0xff & color) === 0; };
- var asString = function (color) {
- var alpha = 0xff & color;
- var blue = 0xff & (color >> 8);
- var green = 0xff & (color >> 16);
- var red = 0xff & (color >> 24);
- return alpha < 255 ? "rgba(" + red + "," + green + "," + blue + "," + alpha / 255 + ")" : "rgb(" + red + "," + green + "," + blue + ")";
- };
- var pack = function (r, g, b, a) {
- return ((r << 24) | (g << 16) | (b << 8) | (Math.round(a * 255) << 0)) >>> 0;
- };
- var getTokenColorValue = function (token, i) {
- if (token.type === 17 /* NUMBER_TOKEN */) {
- return token.number;
- }
- if (token.type === 16 /* PERCENTAGE_TOKEN */) {
- var max = i === 3 ? 1 : 255;
- return i === 3 ? (token.number / 100) * max : Math.round((token.number / 100) * max);
- }
- return 0;
- };
- var rgb = function (_context, args) {
- var tokens = args.filter(nonFunctionArgSeparator);
- if (tokens.length === 3) {
- var _a = tokens.map(getTokenColorValue), r = _a[0], g = _a[1], b = _a[2];
- return pack(r, g, b, 1);
- }
- if (tokens.length === 4) {
- var _b = tokens.map(getTokenColorValue), r = _b[0], g = _b[1], b = _b[2], a = _b[3];
- return pack(r, g, b, a);
- }
- return 0;
- };
- function hue2rgb(t1, t2, hue) {
- if (hue < 0) {
- hue += 1;
- }
- if (hue >= 1) {
- hue -= 1;
- }
- if (hue < 1 / 6) {
- return (t2 - t1) * hue * 6 + t1;
- }
- else if (hue < 1 / 2) {
- return t2;
- }
- else if (hue < 2 / 3) {
- return (t2 - t1) * 6 * (2 / 3 - hue) + t1;
- }
- else {
- return t1;
- }
- }
- var hsl = function (context, args) {
- var tokens = args.filter(nonFunctionArgSeparator);
- var hue = tokens[0], saturation = tokens[1], lightness = tokens[2], alpha = tokens[3];
- var h = (hue.type === 17 /* NUMBER_TOKEN */ ? deg(hue.number) : angle.parse(context, hue)) / (Math.PI * 2);
- var s = isLengthPercentage(saturation) ? saturation.number / 100 : 0;
- var l = isLengthPercentage(lightness) ? lightness.number / 100 : 0;
- var a = typeof alpha !== 'undefined' && isLengthPercentage(alpha) ? getAbsoluteValue(alpha, 1) : 1;
- if (s === 0) {
- return pack(l * 255, l * 255, l * 255, 1);
- }
- var t2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
- var t1 = l * 2 - t2;
- var r = hue2rgb(t1, t2, h + 1 / 3);
- var g = hue2rgb(t1, t2, h);
- var b = hue2rgb(t1, t2, h - 1 / 3);
- return pack(r * 255, g * 255, b * 255, a);
- };
- var SUPPORTED_COLOR_FUNCTIONS = {
- hsl: hsl,
- hsla: hsl,
- rgb: rgb,
- rgba: rgb
- };
- var parseColor = function (context, value) {
- return color$1.parse(context, Parser.create(value).parseComponentValue());
- };
- var COLORS = {
- ALICEBLUE: 0xf0f8ffff,
- ANTIQUEWHITE: 0xfaebd7ff,
- AQUA: 0x00ffffff,
- AQUAMARINE: 0x7fffd4ff,
- AZURE: 0xf0ffffff,
- BEIGE: 0xf5f5dcff,
- BISQUE: 0xffe4c4ff,
- BLACK: 0x000000ff,
- BLANCHEDALMOND: 0xffebcdff,
- BLUE: 0x0000ffff,
- BLUEVIOLET: 0x8a2be2ff,
- BROWN: 0xa52a2aff,
- BURLYWOOD: 0xdeb887ff,
- CADETBLUE: 0x5f9ea0ff,
- CHARTREUSE: 0x7fff00ff,
- CHOCOLATE: 0xd2691eff,
- CORAL: 0xff7f50ff,
- CORNFLOWERBLUE: 0x6495edff,
- CORNSILK: 0xfff8dcff,
- CRIMSON: 0xdc143cff,
- CYAN: 0x00ffffff,
- DARKBLUE: 0x00008bff,
- DARKCYAN: 0x008b8bff,
- DARKGOLDENROD: 0xb886bbff,
- DARKGRAY: 0xa9a9a9ff,
- DARKGREEN: 0x006400ff,
- DARKGREY: 0xa9a9a9ff,
- DARKKHAKI: 0xbdb76bff,
- DARKMAGENTA: 0x8b008bff,
- DARKOLIVEGREEN: 0x556b2fff,
- DARKORANGE: 0xff8c00ff,
- DARKORCHID: 0x9932ccff,
- DARKRED: 0x8b0000ff,
- DARKSALMON: 0xe9967aff,
- DARKSEAGREEN: 0x8fbc8fff,
- DARKSLATEBLUE: 0x483d8bff,
- DARKSLATEGRAY: 0x2f4f4fff,
- DARKSLATEGREY: 0x2f4f4fff,
- DARKTURQUOISE: 0x00ced1ff,
- DARKVIOLET: 0x9400d3ff,
- DEEPPINK: 0xff1493ff,
- DEEPSKYBLUE: 0x00bfffff,
- DIMGRAY: 0x696969ff,
- DIMGREY: 0x696969ff,
- DODGERBLUE: 0x1e90ffff,
- FIREBRICK: 0xb22222ff,
- FLORALWHITE: 0xfffaf0ff,
- FORESTGREEN: 0x228b22ff,
- FUCHSIA: 0xff00ffff,
- GAINSBORO: 0xdcdcdcff,
- GHOSTWHITE: 0xf8f8ffff,
- GOLD: 0xffd700ff,
- GOLDENROD: 0xdaa520ff,
- GRAY: 0x808080ff,
- GREEN: 0x008000ff,
- GREENYELLOW: 0xadff2fff,
- GREY: 0x808080ff,
- HONEYDEW: 0xf0fff0ff,
- HOTPINK: 0xff69b4ff,
- INDIANRED: 0xcd5c5cff,
- INDIGO: 0x4b0082ff,
- IVORY: 0xfffff0ff,
- KHAKI: 0xf0e68cff,
- LAVENDER: 0xe6e6faff,
- LAVENDERBLUSH: 0xfff0f5ff,
- LAWNGREEN: 0x7cfc00ff,
- LEMONCHIFFON: 0xfffacdff,
- LIGHTBLUE: 0xadd8e6ff,
- LIGHTCORAL: 0xf08080ff,
- LIGHTCYAN: 0xe0ffffff,
- LIGHTGOLDENRODYELLOW: 0xfafad2ff,
- LIGHTGRAY: 0xd3d3d3ff,
- LIGHTGREEN: 0x90ee90ff,
- LIGHTGREY: 0xd3d3d3ff,
- LIGHTPINK: 0xffb6c1ff,
- LIGHTSALMON: 0xffa07aff,
- LIGHTSEAGREEN: 0x20b2aaff,
- LIGHTSKYBLUE: 0x87cefaff,
- LIGHTSLATEGRAY: 0x778899ff,
- LIGHTSLATEGREY: 0x778899ff,
- LIGHTSTEELBLUE: 0xb0c4deff,
- LIGHTYELLOW: 0xffffe0ff,
- LIME: 0x00ff00ff,
- LIMEGREEN: 0x32cd32ff,
- LINEN: 0xfaf0e6ff,
- MAGENTA: 0xff00ffff,
- MAROON: 0x800000ff,
- MEDIUMAQUAMARINE: 0x66cdaaff,
- MEDIUMBLUE: 0x0000cdff,
- MEDIUMORCHID: 0xba55d3ff,
- MEDIUMPURPLE: 0x9370dbff,
- MEDIUMSEAGREEN: 0x3cb371ff,
- MEDIUMSLATEBLUE: 0x7b68eeff,
- MEDIUMSPRINGGREEN: 0x00fa9aff,
- MEDIUMTURQUOISE: 0x48d1ccff,
- MEDIUMVIOLETRED: 0xc71585ff,
- MIDNIGHTBLUE: 0x191970ff,
- MINTCREAM: 0xf5fffaff,
- MISTYROSE: 0xffe4e1ff,
- MOCCASIN: 0xffe4b5ff,
- NAVAJOWHITE: 0xffdeadff,
- NAVY: 0x000080ff,
- OLDLACE: 0xfdf5e6ff,
- OLIVE: 0x808000ff,
- OLIVEDRAB: 0x6b8e23ff,
- ORANGE: 0xffa500ff,
- ORANGERED: 0xff4500ff,
- ORCHID: 0xda70d6ff,
- PALEGOLDENROD: 0xeee8aaff,
- PALEGREEN: 0x98fb98ff,
- PALETURQUOISE: 0xafeeeeff,
- PALEVIOLETRED: 0xdb7093ff,
- PAPAYAWHIP: 0xffefd5ff,
- PEACHPUFF: 0xffdab9ff,
- PERU: 0xcd853fff,
- PINK: 0xffc0cbff,
- PLUM: 0xdda0ddff,
- POWDERBLUE: 0xb0e0e6ff,
- PURPLE: 0x800080ff,
- REBECCAPURPLE: 0x663399ff,
- RED: 0xff0000ff,
- ROSYBROWN: 0xbc8f8fff,
- ROYALBLUE: 0x4169e1ff,
- SADDLEBROWN: 0x8b4513ff,
- SALMON: 0xfa8072ff,
- SANDYBROWN: 0xf4a460ff,
- SEAGREEN: 0x2e8b57ff,
- SEASHELL: 0xfff5eeff,
- SIENNA: 0xa0522dff,
- SILVER: 0xc0c0c0ff,
- SKYBLUE: 0x87ceebff,
- SLATEBLUE: 0x6a5acdff,
- SLATEGRAY: 0x708090ff,
- SLATEGREY: 0x708090ff,
- SNOW: 0xfffafaff,
- SPRINGGREEN: 0x00ff7fff,
- STEELBLUE: 0x4682b4ff,
- TAN: 0xd2b48cff,
- TEAL: 0x008080ff,
- THISTLE: 0xd8bfd8ff,
- TOMATO: 0xff6347ff,
- TRANSPARENT: 0x00000000,
- TURQUOISE: 0x40e0d0ff,
- VIOLET: 0xee82eeff,
- WHEAT: 0xf5deb3ff,
- WHITE: 0xffffffff,
- WHITESMOKE: 0xf5f5f5ff,
- YELLOW: 0xffff00ff,
- YELLOWGREEN: 0x9acd32ff
- };
-
- var backgroundClip = {
- name: 'background-clip',
- initialValue: 'border-box',
- prefix: false,
- type: 1 /* LIST */,
- parse: function (_context, tokens) {
- return tokens.map(function (token) {
- if (isIdentToken(token)) {
- switch (token.value) {
- case 'padding-box':
- return 1 /* PADDING_BOX */;
- case 'content-box':
- return 2 /* CONTENT_BOX */;
- }
- }
- return 0 /* BORDER_BOX */;
- });
- }
- };
-
- var backgroundColor = {
- name: "background-color",
- initialValue: 'transparent',
- prefix: false,
- type: 3 /* TYPE_VALUE */,
- format: 'color'
- };
-
- var parseColorStop = function (context, args) {
- var color = color$1.parse(context, args[0]);
- var stop = args[1];
- return stop && isLengthPercentage(stop) ? { color: color, stop: stop } : { color: color, stop: null };
- };
- var processColorStops = function (stops, lineLength) {
- var first = stops[0];
- var last = stops[stops.length - 1];
- if (first.stop === null) {
- first.stop = ZERO_LENGTH;
- }
- if (last.stop === null) {
- last.stop = HUNDRED_PERCENT;
- }
- var processStops = [];
- var previous = 0;
- for (var i = 0; i < stops.length; i++) {
- var stop_1 = stops[i].stop;
- if (stop_1 !== null) {
- var absoluteValue = getAbsoluteValue(stop_1, lineLength);
- if (absoluteValue > previous) {
- processStops.push(absoluteValue);
- }
- else {
- processStops.push(previous);
- }
- previous = absoluteValue;
- }
- else {
- processStops.push(null);
- }
- }
- var gapBegin = null;
- for (var i = 0; i < processStops.length; i++) {
- var stop_2 = processStops[i];
- if (stop_2 === null) {
- if (gapBegin === null) {
- gapBegin = i;
- }
- }
- else if (gapBegin !== null) {
- var gapLength = i - gapBegin;
- var beforeGap = processStops[gapBegin - 1];
- var gapValue = (stop_2 - beforeGap) / (gapLength + 1);
- for (var g = 1; g <= gapLength; g++) {
- processStops[gapBegin + g - 1] = gapValue * g;
- }
- gapBegin = null;
- }
- }
- return stops.map(function (_a, i) {
- var color = _a.color;
- return { color: color, stop: Math.max(Math.min(1, processStops[i] / lineLength), 0) };
- });
- };
- var getAngleFromCorner = function (corner, width, height) {
- var centerX = width / 2;
- var centerY = height / 2;
- var x = getAbsoluteValue(corner[0], width) - centerX;
- var y = centerY - getAbsoluteValue(corner[1], height);
- return (Math.atan2(y, x) + Math.PI * 2) % (Math.PI * 2);
- };
- var calculateGradientDirection = function (angle, width, height) {
- var radian = typeof angle === 'number' ? angle : getAngleFromCorner(angle, width, height);
- var lineLength = Math.abs(width * Math.sin(radian)) + Math.abs(height * Math.cos(radian));
- var halfWidth = width / 2;
- var halfHeight = height / 2;
- var halfLineLength = lineLength / 2;
- var yDiff = Math.sin(radian - Math.PI / 2) * halfLineLength;
- var xDiff = Math.cos(radian - Math.PI / 2) * halfLineLength;
- return [lineLength, halfWidth - xDiff, halfWidth + xDiff, halfHeight - yDiff, halfHeight + yDiff];
- };
- var distance = function (a, b) { return Math.sqrt(a * a + b * b); };
- var findCorner = function (width, height, x, y, closest) {
- var corners = [
- [0, 0],
- [0, height],
- [width, 0],
- [width, height]
- ];
- return corners.reduce(function (stat, corner) {
- var cx = corner[0], cy = corner[1];
- var d = distance(x - cx, y - cy);
- if (closest ? d < stat.optimumDistance : d > stat.optimumDistance) {
- return {
- optimumCorner: corner,
- optimumDistance: d
- };
- }
- return stat;
- }, {
- optimumDistance: closest ? Infinity : -Infinity,
- optimumCorner: null
- }).optimumCorner;
- };
- var calculateRadius = function (gradient, x, y, width, height) {
- var rx = 0;
- var ry = 0;
- switch (gradient.size) {
- case 0 /* CLOSEST_SIDE */:
- // The ending shape is sized so that that it exactly meets the side of the gradient box closest to the gradient’s center.
- // If the shape is an ellipse, it exactly meets the closest side in each dimension.
- if (gradient.shape === 0 /* CIRCLE */) {
- rx = ry = Math.min(Math.abs(x), Math.abs(x - width), Math.abs(y), Math.abs(y - height));
- }
- else if (gradient.shape === 1 /* ELLIPSE */) {
- rx = Math.min(Math.abs(x), Math.abs(x - width));
- ry = Math.min(Math.abs(y), Math.abs(y - height));
- }
- break;
- case 2 /* CLOSEST_CORNER */:
- // The ending shape is sized so that that it passes through the corner of the gradient box closest to the gradient’s center.
- // If the shape is an ellipse, the ending shape is given the same aspect-ratio it would have if closest-side were specified.
- if (gradient.shape === 0 /* CIRCLE */) {
- rx = ry = Math.min(distance(x, y), distance(x, y - height), distance(x - width, y), distance(x - width, y - height));
- }
- else if (gradient.shape === 1 /* ELLIPSE */) {
- // Compute the ratio ry/rx (which is to be the same as for "closest-side")
- var c = Math.min(Math.abs(y), Math.abs(y - height)) / Math.min(Math.abs(x), Math.abs(x - width));
- var _a = findCorner(width, height, x, y, true), cx = _a[0], cy = _a[1];
- rx = distance(cx - x, (cy - y) / c);
- ry = c * rx;
- }
- break;
- case 1 /* FARTHEST_SIDE */:
- // Same as closest-side, except the ending shape is sized based on the farthest side(s)
- if (gradient.shape === 0 /* CIRCLE */) {
- rx = ry = Math.max(Math.abs(x), Math.abs(x - width), Math.abs(y), Math.abs(y - height));
- }
- else if (gradient.shape === 1 /* ELLIPSE */) {
- rx = Math.max(Math.abs(x), Math.abs(x - width));
- ry = Math.max(Math.abs(y), Math.abs(y - height));
- }
- break;
- case 3 /* FARTHEST_CORNER */:
- // Same as closest-corner, except the ending shape is sized based on the farthest corner.
- // If the shape is an ellipse, the ending shape is given the same aspect ratio it would have if farthest-side were specified.
- if (gradient.shape === 0 /* CIRCLE */) {
- rx = ry = Math.max(distance(x, y), distance(x, y - height), distance(x - width, y), distance(x - width, y - height));
- }
- else if (gradient.shape === 1 /* ELLIPSE */) {
- // Compute the ratio ry/rx (which is to be the same as for "farthest-side")
- var c = Math.max(Math.abs(y), Math.abs(y - height)) / Math.max(Math.abs(x), Math.abs(x - width));
- var _b = findCorner(width, height, x, y, false), cx = _b[0], cy = _b[1];
- rx = distance(cx - x, (cy - y) / c);
- ry = c * rx;
- }
- break;
- }
- if (Array.isArray(gradient.size)) {
- rx = getAbsoluteValue(gradient.size[0], width);
- ry = gradient.size.length === 2 ? getAbsoluteValue(gradient.size[1], height) : rx;
- }
- return [rx, ry];
- };
-
- var linearGradient = function (context, tokens) {
- var angle$1 = deg(180);
- var stops = [];
- parseFunctionArgs(tokens).forEach(function (arg, i) {
- if (i === 0) {
- var firstToken = arg[0];
- if (firstToken.type === 20 /* IDENT_TOKEN */ && firstToken.value === 'to') {
- angle$1 = parseNamedSide(arg);
- return;
- }
- else if (isAngle(firstToken)) {
- angle$1 = angle.parse(context, firstToken);
- return;
- }
- }
- var colorStop = parseColorStop(context, arg);
- stops.push(colorStop);
- });
- return { angle: angle$1, stops: stops, type: 1 /* LINEAR_GRADIENT */ };
- };
-
- var prefixLinearGradient = function (context, tokens) {
- var angle$1 = deg(180);
- var stops = [];
- parseFunctionArgs(tokens).forEach(function (arg, i) {
- if (i === 0) {
- var firstToken = arg[0];
- if (firstToken.type === 20 /* IDENT_TOKEN */ &&
- ['top', 'left', 'right', 'bottom'].indexOf(firstToken.value) !== -1) {
- angle$1 = parseNamedSide(arg);
- return;
- }
- else if (isAngle(firstToken)) {
- angle$1 = (angle.parse(context, firstToken) + deg(270)) % deg(360);
- return;
- }
- }
- var colorStop = parseColorStop(context, arg);
- stops.push(colorStop);
- });
- return {
- angle: angle$1,
- stops: stops,
- type: 1 /* LINEAR_GRADIENT */
- };
- };
-
- var webkitGradient = function (context, tokens) {
- var angle = deg(180);
- var stops = [];
- var type = 1 /* LINEAR_GRADIENT */;
- var shape = 0 /* CIRCLE */;
- var size = 3 /* FARTHEST_CORNER */;
- var position = [];
- parseFunctionArgs(tokens).forEach(function (arg, i) {
- var firstToken = arg[0];
- if (i === 0) {
- if (isIdentToken(firstToken) && firstToken.value === 'linear') {
- type = 1 /* LINEAR_GRADIENT */;
- return;
- }
- else if (isIdentToken(firstToken) && firstToken.value === 'radial') {
- type = 2 /* RADIAL_GRADIENT */;
- return;
- }
- }
- if (firstToken.type === 18 /* FUNCTION */) {
- if (firstToken.name === 'from') {
- var color = color$1.parse(context, firstToken.values[0]);
- stops.push({ stop: ZERO_LENGTH, color: color });
- }
- else if (firstToken.name === 'to') {
- var color = color$1.parse(context, firstToken.values[0]);
- stops.push({ stop: HUNDRED_PERCENT, color: color });
- }
- else if (firstToken.name === 'color-stop') {
- var values = firstToken.values.filter(nonFunctionArgSeparator);
- if (values.length === 2) {
- var color = color$1.parse(context, values[1]);
- var stop_1 = values[0];
- if (isNumberToken(stop_1)) {
- stops.push({
- stop: { type: 16 /* PERCENTAGE_TOKEN */, number: stop_1.number * 100, flags: stop_1.flags },
- color: color
- });
- }
- }
- }
- }
- });
- return type === 1 /* LINEAR_GRADIENT */
- ? {
- angle: (angle + deg(180)) % deg(360),
- stops: stops,
- type: type
- }
- : { size: size, shape: shape, stops: stops, position: position, type: type };
- };
-
- var CLOSEST_SIDE = 'closest-side';
- var FARTHEST_SIDE = 'farthest-side';
- var CLOSEST_CORNER = 'closest-corner';
- var FARTHEST_CORNER = 'farthest-corner';
- var CIRCLE = 'circle';
- var ELLIPSE = 'ellipse';
- var COVER = 'cover';
- var CONTAIN = 'contain';
- var radialGradient = function (context, tokens) {
- var shape = 0 /* CIRCLE */;
- var size = 3 /* FARTHEST_CORNER */;
- var stops = [];
- var position = [];
- parseFunctionArgs(tokens).forEach(function (arg, i) {
- var isColorStop = true;
- if (i === 0) {
- var isAtPosition_1 = false;
- isColorStop = arg.reduce(function (acc, token) {
- if (isAtPosition_1) {
- if (isIdentToken(token)) {
- switch (token.value) {
- case 'center':
- position.push(FIFTY_PERCENT);
- return acc;
- case 'top':
- case 'left':
- position.push(ZERO_LENGTH);
- return acc;
- case 'right':
- case 'bottom':
- position.push(HUNDRED_PERCENT);
- return acc;
- }
- }
- else if (isLengthPercentage(token) || isLength(token)) {
- position.push(token);
- }
- }
- else if (isIdentToken(token)) {
- switch (token.value) {
- case CIRCLE:
- shape = 0 /* CIRCLE */;
- return false;
- case ELLIPSE:
- shape = 1 /* ELLIPSE */;
- return false;
- case 'at':
- isAtPosition_1 = true;
- return false;
- case CLOSEST_SIDE:
- size = 0 /* CLOSEST_SIDE */;
- return false;
- case COVER:
- case FARTHEST_SIDE:
- size = 1 /* FARTHEST_SIDE */;
- return false;
- case CONTAIN:
- case CLOSEST_CORNER:
- size = 2 /* CLOSEST_CORNER */;
- return false;
- case FARTHEST_CORNER:
- size = 3 /* FARTHEST_CORNER */;
- return false;
- }
- }
- else if (isLength(token) || isLengthPercentage(token)) {
- if (!Array.isArray(size)) {
- size = [];
- }
- size.push(token);
- return false;
- }
- return acc;
- }, isColorStop);
- }
- if (isColorStop) {
- var colorStop = parseColorStop(context, arg);
- stops.push(colorStop);
- }
- });
- return { size: size, shape: shape, stops: stops, position: position, type: 2 /* RADIAL_GRADIENT */ };
- };
-
- var prefixRadialGradient = function (context, tokens) {
- var shape = 0 /* CIRCLE */;
- var size = 3 /* FARTHEST_CORNER */;
- var stops = [];
- var position = [];
- parseFunctionArgs(tokens).forEach(function (arg, i) {
- var isColorStop = true;
- if (i === 0) {
- isColorStop = arg.reduce(function (acc, token) {
- if (isIdentToken(token)) {
- switch (token.value) {
- case 'center':
- position.push(FIFTY_PERCENT);
- return false;
- case 'top':
- case 'left':
- position.push(ZERO_LENGTH);
- return false;
- case 'right':
- case 'bottom':
- position.push(HUNDRED_PERCENT);
- return false;
- }
- }
- else if (isLengthPercentage(token) || isLength(token)) {
- position.push(token);
- return false;
- }
- return acc;
- }, isColorStop);
- }
- else if (i === 1) {
- isColorStop = arg.reduce(function (acc, token) {
- if (isIdentToken(token)) {
- switch (token.value) {
- case CIRCLE:
- shape = 0 /* CIRCLE */;
- return false;
- case ELLIPSE:
- shape = 1 /* ELLIPSE */;
- return false;
- case CONTAIN:
- case CLOSEST_SIDE:
- size = 0 /* CLOSEST_SIDE */;
- return false;
- case FARTHEST_SIDE:
- size = 1 /* FARTHEST_SIDE */;
- return false;
- case CLOSEST_CORNER:
- size = 2 /* CLOSEST_CORNER */;
- return false;
- case COVER:
- case FARTHEST_CORNER:
- size = 3 /* FARTHEST_CORNER */;
- return false;
- }
- }
- else if (isLength(token) || isLengthPercentage(token)) {
- if (!Array.isArray(size)) {
- size = [];
- }
- size.push(token);
- return false;
- }
- return acc;
- }, isColorStop);
- }
- if (isColorStop) {
- var colorStop = parseColorStop(context, arg);
- stops.push(colorStop);
- }
- });
- return { size: size, shape: shape, stops: stops, position: position, type: 2 /* RADIAL_GRADIENT */ };
- };
-
- var isLinearGradient = function (background) {
- return background.type === 1 /* LINEAR_GRADIENT */;
- };
- var isRadialGradient = function (background) {
- return background.type === 2 /* RADIAL_GRADIENT */;
- };
- var image = {
- name: 'image',
- parse: function (context, value) {
- if (value.type === 22 /* URL_TOKEN */) {
- var image_1 = { url: value.value, type: 0 /* URL */ };
- context.cache.addImage(value.value);
- return image_1;
- }
- if (value.type === 18 /* FUNCTION */) {
- var imageFunction = SUPPORTED_IMAGE_FUNCTIONS[value.name];
- if (typeof imageFunction === 'undefined') {
- throw new Error("Attempting to parse an unsupported image function \"" + value.name + "\"");
- }
- return imageFunction(context, value.values);
- }
- throw new Error("Unsupported image type " + value.type);
- }
- };
- function isSupportedImage(value) {
- return (!(value.type === 20 /* IDENT_TOKEN */ && value.value === 'none') &&
- (value.type !== 18 /* FUNCTION */ || !!SUPPORTED_IMAGE_FUNCTIONS[value.name]));
- }
- var SUPPORTED_IMAGE_FUNCTIONS = {
- 'linear-gradient': linearGradient,
- '-moz-linear-gradient': prefixLinearGradient,
- '-ms-linear-gradient': prefixLinearGradient,
- '-o-linear-gradient': prefixLinearGradient,
- '-webkit-linear-gradient': prefixLinearGradient,
- 'radial-gradient': radialGradient,
- '-moz-radial-gradient': prefixRadialGradient,
- '-ms-radial-gradient': prefixRadialGradient,
- '-o-radial-gradient': prefixRadialGradient,
- '-webkit-radial-gradient': prefixRadialGradient,
- '-webkit-gradient': webkitGradient
- };
-
- var backgroundImage = {
- name: 'background-image',
- initialValue: 'none',
- type: 1 /* LIST */,
- prefix: false,
- parse: function (context, tokens) {
- if (tokens.length === 0) {
- return [];
- }
- var first = tokens[0];
- if (first.type === 20 /* IDENT_TOKEN */ && first.value === 'none') {
- return [];
- }
- return tokens
- .filter(function (value) { return nonFunctionArgSeparator(value) && isSupportedImage(value); })
- .map(function (value) { return image.parse(context, value); });
- }
- };
-
- var backgroundOrigin = {
- name: 'background-origin',
- initialValue: 'border-box',
- prefix: false,
- type: 1 /* LIST */,
- parse: function (_context, tokens) {
- return tokens.map(function (token) {
- if (isIdentToken(token)) {
- switch (token.value) {
- case 'padding-box':
- return 1 /* PADDING_BOX */;
- case 'content-box':
- return 2 /* CONTENT_BOX */;
- }
- }
- return 0 /* BORDER_BOX */;
- });
- }
- };
-
- var backgroundPosition = {
- name: 'background-position',
- initialValue: '0% 0%',
- type: 1 /* LIST */,
- prefix: false,
- parse: function (_context, tokens) {
- return parseFunctionArgs(tokens)
- .map(function (values) { return values.filter(isLengthPercentage); })
- .map(parseLengthPercentageTuple);
- }
- };
-
- var backgroundRepeat = {
- name: 'background-repeat',
- initialValue: 'repeat',
- prefix: false,
- type: 1 /* LIST */,
- parse: function (_context, tokens) {
- return parseFunctionArgs(tokens)
- .map(function (values) {
- return values
- .filter(isIdentToken)
- .map(function (token) { return token.value; })
- .join(' ');
- })
- .map(parseBackgroundRepeat);
- }
- };
- var parseBackgroundRepeat = function (value) {
- switch (value) {
- case 'no-repeat':
- return 1 /* NO_REPEAT */;
- case 'repeat-x':
- case 'repeat no-repeat':
- return 2 /* REPEAT_X */;
- case 'repeat-y':
- case 'no-repeat repeat':
- return 3 /* REPEAT_Y */;
- case 'repeat':
- default:
- return 0 /* REPEAT */;
- }
- };
-
- var BACKGROUND_SIZE;
- (function (BACKGROUND_SIZE) {
- BACKGROUND_SIZE["AUTO"] = "auto";
- BACKGROUND_SIZE["CONTAIN"] = "contain";
- BACKGROUND_SIZE["COVER"] = "cover";
- })(BACKGROUND_SIZE || (BACKGROUND_SIZE = {}));
- var backgroundSize = {
- name: 'background-size',
- initialValue: '0',
- prefix: false,
- type: 1 /* LIST */,
- parse: function (_context, tokens) {
- return parseFunctionArgs(tokens).map(function (values) { return values.filter(isBackgroundSizeInfoToken); });
- }
- };
- var isBackgroundSizeInfoToken = function (value) {
- return isIdentToken(value) || isLengthPercentage(value);
- };
-
- var borderColorForSide = function (side) { return ({
- name: "border-" + side + "-color",
- initialValue: 'transparent',
- prefix: false,
- type: 3 /* TYPE_VALUE */,
- format: 'color'
- }); };
- var borderTopColor = borderColorForSide('top');
- var borderRightColor = borderColorForSide('right');
- var borderBottomColor = borderColorForSide('bottom');
- var borderLeftColor = borderColorForSide('left');
-
- var borderRadiusForSide = function (side) { return ({
- name: "border-radius-" + side,
- initialValue: '0 0',
- prefix: false,
- type: 1 /* LIST */,
- parse: function (_context, tokens) {
- return parseLengthPercentageTuple(tokens.filter(isLengthPercentage));
- }
- }); };
- var borderTopLeftRadius = borderRadiusForSide('top-left');
- var borderTopRightRadius = borderRadiusForSide('top-right');
- var borderBottomRightRadius = borderRadiusForSide('bottom-right');
- var borderBottomLeftRadius = borderRadiusForSide('bottom-left');
-
- var borderStyleForSide = function (side) { return ({
- name: "border-" + side + "-style",
- initialValue: 'solid',
- prefix: false,
- type: 2 /* IDENT_VALUE */,
- parse: function (_context, style) {
- switch (style) {
- case 'none':
- return 0 /* NONE */;
- case 'dashed':
- return 2 /* DASHED */;
- case 'dotted':
- return 3 /* DOTTED */;
- case 'double':
- return 4 /* DOUBLE */;
- }
- return 1 /* SOLID */;
- }
- }); };
- var borderTopStyle = borderStyleForSide('top');
- var borderRightStyle = borderStyleForSide('right');
- var borderBottomStyle = borderStyleForSide('bottom');
- var borderLeftStyle = borderStyleForSide('left');
-
- var borderWidthForSide = function (side) { return ({
- name: "border-" + side + "-width",
- initialValue: '0',
- type: 0 /* VALUE */,
- prefix: false,
- parse: function (_context, token) {
- if (isDimensionToken(token)) {
- return token.number;
- }
- return 0;
- }
- }); };
- var borderTopWidth = borderWidthForSide('top');
- var borderRightWidth = borderWidthForSide('right');
- var borderBottomWidth = borderWidthForSide('bottom');
- var borderLeftWidth = borderWidthForSide('left');
-
- var color = {
- name: "color",
- initialValue: 'transparent',
- prefix: false,
- type: 3 /* TYPE_VALUE */,
- format: 'color'
- };
-
- var direction = {
- name: 'direction',
- initialValue: 'ltr',
- prefix: false,
- type: 2 /* IDENT_VALUE */,
- parse: function (_context, direction) {
- switch (direction) {
- case 'rtl':
- return 1 /* RTL */;
- case 'ltr':
- default:
- return 0 /* LTR */;
- }
- }
- };
-
- var display = {
- name: 'display',
- initialValue: 'inline-block',
- prefix: false,
- type: 1 /* LIST */,
- parse: function (_context, tokens) {
- return tokens.filter(isIdentToken).reduce(function (bit, token) {
- return bit | parseDisplayValue(token.value);
- }, 0 /* NONE */);
- }
- };
- var parseDisplayValue = function (display) {
- switch (display) {
- case 'block':
- case '-webkit-box':
- return 2 /* BLOCK */;
- case 'inline':
- return 4 /* INLINE */;
- case 'run-in':
- return 8 /* RUN_IN */;
- case 'flow':
- return 16 /* FLOW */;
- case 'flow-root':
- return 32 /* FLOW_ROOT */;
- case 'table':
- return 64 /* TABLE */;
- case 'flex':
- case '-webkit-flex':
- return 128 /* FLEX */;
- case 'grid':
- case '-ms-grid':
- return 256 /* GRID */;
- case 'ruby':
- return 512 /* RUBY */;
- case 'subgrid':
- return 1024 /* SUBGRID */;
- case 'list-item':
- return 2048 /* LIST_ITEM */;
- case 'table-row-group':
- return 4096 /* TABLE_ROW_GROUP */;
- case 'table-header-group':
- return 8192 /* TABLE_HEADER_GROUP */;
- case 'table-footer-group':
- return 16384 /* TABLE_FOOTER_GROUP */;
- case 'table-row':
- return 32768 /* TABLE_ROW */;
- case 'table-cell':
- return 65536 /* TABLE_CELL */;
- case 'table-column-group':
- return 131072 /* TABLE_COLUMN_GROUP */;
- case 'table-column':
- return 262144 /* TABLE_COLUMN */;
- case 'table-caption':
- return 524288 /* TABLE_CAPTION */;
- case 'ruby-base':
- return 1048576 /* RUBY_BASE */;
- case 'ruby-text':
- return 2097152 /* RUBY_TEXT */;
- case 'ruby-base-container':
- return 4194304 /* RUBY_BASE_CONTAINER */;
- case 'ruby-text-container':
- return 8388608 /* RUBY_TEXT_CONTAINER */;
- case 'contents':
- return 16777216 /* CONTENTS */;
- case 'inline-block':
- return 33554432 /* INLINE_BLOCK */;
- case 'inline-list-item':
- return 67108864 /* INLINE_LIST_ITEM */;
- case 'inline-table':
- return 134217728 /* INLINE_TABLE */;
- case 'inline-flex':
- return 268435456 /* INLINE_FLEX */;
- case 'inline-grid':
- return 536870912 /* INLINE_GRID */;
- }
- return 0 /* NONE */;
- };
-
- var float = {
- name: 'float',
- initialValue: 'none',
- prefix: false,
- type: 2 /* IDENT_VALUE */,
- parse: function (_context, float) {
- switch (float) {
- case 'left':
- return 1 /* LEFT */;
- case 'right':
- return 2 /* RIGHT */;
- case 'inline-start':
- return 3 /* INLINE_START */;
- case 'inline-end':
- return 4 /* INLINE_END */;
- }
- return 0 /* NONE */;
- }
- };
-
- var letterSpacing = {
- name: 'letter-spacing',
- initialValue: '0',
- prefix: false,
- type: 0 /* VALUE */,
- parse: function (_context, token) {
- if (token.type === 20 /* IDENT_TOKEN */ && token.value === 'normal') {
- return 0;
- }
- if (token.type === 17 /* NUMBER_TOKEN */) {
- return token.number;
- }
- if (token.type === 15 /* DIMENSION_TOKEN */) {
- return token.number;
- }
- return 0;
- }
- };
-
- var LINE_BREAK;
- (function (LINE_BREAK) {
- LINE_BREAK["NORMAL"] = "normal";
- LINE_BREAK["STRICT"] = "strict";
- })(LINE_BREAK || (LINE_BREAK = {}));
- var lineBreak = {
- name: 'line-break',
- initialValue: 'normal',
- prefix: false,
- type: 2 /* IDENT_VALUE */,
- parse: function (_context, lineBreak) {
- switch (lineBreak) {
- case 'strict':
- return LINE_BREAK.STRICT;
- case 'normal':
- default:
- return LINE_BREAK.NORMAL;
- }
- }
- };
-
- var lineHeight = {
- name: 'line-height',
- initialValue: 'normal',
- prefix: false,
- type: 4 /* TOKEN_VALUE */
- };
- var computeLineHeight = function (token, fontSize) {
- if (isIdentToken(token) && token.value === 'normal') {
- return 1.2 * fontSize;
- }
- else if (token.type === 17 /* NUMBER_TOKEN */) {
- return fontSize * token.number;
- }
- else if (isLengthPercentage(token)) {
- return getAbsoluteValue(token, fontSize);
- }
- return fontSize;
- };
-
- var listStyleImage = {
- name: 'list-style-image',
- initialValue: 'none',
- type: 0 /* VALUE */,
- prefix: false,
- parse: function (context, token) {
- if (token.type === 20 /* IDENT_TOKEN */ && token.value === 'none') {
- return null;
- }
- return image.parse(context, token);
- }
- };
-
- var listStylePosition = {
- name: 'list-style-position',
- initialValue: 'outside',
- prefix: false,
- type: 2 /* IDENT_VALUE */,
- parse: function (_context, position) {
- switch (position) {
- case 'inside':
- return 0 /* INSIDE */;
- case 'outside':
- default:
- return 1 /* OUTSIDE */;
- }
- }
- };
-
- var listStyleType = {
- name: 'list-style-type',
- initialValue: 'none',
- prefix: false,
- type: 2 /* IDENT_VALUE */,
- parse: function (_context, type) {
- switch (type) {
- case 'disc':
- return 0 /* DISC */;
- case 'circle':
- return 1 /* CIRCLE */;
- case 'square':
- return 2 /* SQUARE */;
- case 'decimal':
- return 3 /* DECIMAL */;
- case 'cjk-decimal':
- return 4 /* CJK_DECIMAL */;
- case 'decimal-leading-zero':
- return 5 /* DECIMAL_LEADING_ZERO */;
- case 'lower-roman':
- return 6 /* LOWER_ROMAN */;
- case 'upper-roman':
- return 7 /* UPPER_ROMAN */;
- case 'lower-greek':
- return 8 /* LOWER_GREEK */;
- case 'lower-alpha':
- return 9 /* LOWER_ALPHA */;
- case 'upper-alpha':
- return 10 /* UPPER_ALPHA */;
- case 'arabic-indic':
- return 11 /* ARABIC_INDIC */;
- case 'armenian':
- return 12 /* ARMENIAN */;
- case 'bengali':
- return 13 /* BENGALI */;
- case 'cambodian':
- return 14 /* CAMBODIAN */;
- case 'cjk-earthly-branch':
- return 15 /* CJK_EARTHLY_BRANCH */;
- case 'cjk-heavenly-stem':
- return 16 /* CJK_HEAVENLY_STEM */;
- case 'cjk-ideographic':
- return 17 /* CJK_IDEOGRAPHIC */;
- case 'devanagari':
- return 18 /* DEVANAGARI */;
- case 'ethiopic-numeric':
- return 19 /* ETHIOPIC_NUMERIC */;
- case 'georgian':
- return 20 /* GEORGIAN */;
- case 'gujarati':
- return 21 /* GUJARATI */;
- case 'gurmukhi':
- return 22 /* GURMUKHI */;
- case 'hebrew':
- return 22 /* HEBREW */;
- case 'hiragana':
- return 23 /* HIRAGANA */;
- case 'hiragana-iroha':
- return 24 /* HIRAGANA_IROHA */;
- case 'japanese-formal':
- return 25 /* JAPANESE_FORMAL */;
- case 'japanese-informal':
- return 26 /* JAPANESE_INFORMAL */;
- case 'kannada':
- return 27 /* KANNADA */;
- case 'katakana':
- return 28 /* KATAKANA */;
- case 'katakana-iroha':
- return 29 /* KATAKANA_IROHA */;
- case 'khmer':
- return 30 /* KHMER */;
- case 'korean-hangul-formal':
- return 31 /* KOREAN_HANGUL_FORMAL */;
- case 'korean-hanja-formal':
- return 32 /* KOREAN_HANJA_FORMAL */;
- case 'korean-hanja-informal':
- return 33 /* KOREAN_HANJA_INFORMAL */;
- case 'lao':
- return 34 /* LAO */;
- case 'lower-armenian':
- return 35 /* LOWER_ARMENIAN */;
- case 'malayalam':
- return 36 /* MALAYALAM */;
- case 'mongolian':
- return 37 /* MONGOLIAN */;
- case 'myanmar':
- return 38 /* MYANMAR */;
- case 'oriya':
- return 39 /* ORIYA */;
- case 'persian':
- return 40 /* PERSIAN */;
- case 'simp-chinese-formal':
- return 41 /* SIMP_CHINESE_FORMAL */;
- case 'simp-chinese-informal':
- return 42 /* SIMP_CHINESE_INFORMAL */;
- case 'tamil':
- return 43 /* TAMIL */;
- case 'telugu':
- return 44 /* TELUGU */;
- case 'thai':
- return 45 /* THAI */;
- case 'tibetan':
- return 46 /* TIBETAN */;
- case 'trad-chinese-formal':
- return 47 /* TRAD_CHINESE_FORMAL */;
- case 'trad-chinese-informal':
- return 48 /* TRAD_CHINESE_INFORMAL */;
- case 'upper-armenian':
- return 49 /* UPPER_ARMENIAN */;
- case 'disclosure-open':
- return 50 /* DISCLOSURE_OPEN */;
- case 'disclosure-closed':
- return 51 /* DISCLOSURE_CLOSED */;
- case 'none':
- default:
- return -1 /* NONE */;
- }
- }
- };
-
- var marginForSide = function (side) { return ({
- name: "margin-" + side,
- initialValue: '0',
- prefix: false,
- type: 4 /* TOKEN_VALUE */
- }); };
- var marginTop = marginForSide('top');
- var marginRight = marginForSide('right');
- var marginBottom = marginForSide('bottom');
- var marginLeft = marginForSide('left');
-
- var overflow = {
- name: 'overflow',
- initialValue: 'visible',
- prefix: false,
- type: 1 /* LIST */,
- parse: function (_context, tokens) {
- return tokens.filter(isIdentToken).map(function (overflow) {
- switch (overflow.value) {
- case 'hidden':
- return 1 /* HIDDEN */;
- case 'scroll':
- return 2 /* SCROLL */;
- case 'clip':
- return 3 /* CLIP */;
- case 'auto':
- return 4 /* AUTO */;
- case 'visible':
- default:
- return 0 /* VISIBLE */;
- }
- });
- }
- };
-
- var overflowWrap = {
- name: 'overflow-wrap',
- initialValue: 'normal',
- prefix: false,
- type: 2 /* IDENT_VALUE */,
- parse: function (_context, overflow) {
- switch (overflow) {
- case 'break-word':
- return "break-word" /* BREAK_WORD */;
- case 'normal':
- default:
- return "normal" /* NORMAL */;
- }
- }
- };
-
- var paddingForSide = function (side) { return ({
- name: "padding-" + side,
- initialValue: '0',
- prefix: false,
- type: 3 /* TYPE_VALUE */,
- format: 'length-percentage'
- }); };
- var paddingTop = paddingForSide('top');
- var paddingRight = paddingForSide('right');
- var paddingBottom = paddingForSide('bottom');
- var paddingLeft = paddingForSide('left');
-
- var textAlign = {
- name: 'text-align',
- initialValue: 'left',
- prefix: false,
- type: 2 /* IDENT_VALUE */,
- parse: function (_context, textAlign) {
- switch (textAlign) {
- case 'right':
- return 2 /* RIGHT */;
- case 'center':
- case 'justify':
- return 1 /* CENTER */;
- case 'left':
- default:
- return 0 /* LEFT */;
- }
- }
- };
-
- var position = {
- name: 'position',
- initialValue: 'static',
- prefix: false,
- type: 2 /* IDENT_VALUE */,
- parse: function (_context, position) {
- switch (position) {
- case 'relative':
- return 1 /* RELATIVE */;
- case 'absolute':
- return 2 /* ABSOLUTE */;
- case 'fixed':
- return 3 /* FIXED */;
- case 'sticky':
- return 4 /* STICKY */;
- }
- return 0 /* STATIC */;
- }
- };
-
- var textShadow = {
- name: 'text-shadow',
- initialValue: 'none',
- type: 1 /* LIST */,
- prefix: false,
- parse: function (context, tokens) {
- if (tokens.length === 1 && isIdentWithValue(tokens[0], 'none')) {
- return [];
- }
- return parseFunctionArgs(tokens).map(function (values) {
- var shadow = {
- color: COLORS.TRANSPARENT,
- offsetX: ZERO_LENGTH,
- offsetY: ZERO_LENGTH,
- blur: ZERO_LENGTH
- };
- var c = 0;
- for (var i = 0; i < values.length; i++) {
- var token = values[i];
- if (isLength(token)) {
- if (c === 0) {
- shadow.offsetX = token;
- }
- else if (c === 1) {
- shadow.offsetY = token;
- }
- else {
- shadow.blur = token;
- }
- c++;
- }
- else {
- shadow.color = color$1.parse(context, token);
- }
- }
- return shadow;
- });
- }
- };
-
- var textTransform = {
- name: 'text-transform',
- initialValue: 'none',
- prefix: false,
- type: 2 /* IDENT_VALUE */,
- parse: function (_context, textTransform) {
- switch (textTransform) {
- case 'uppercase':
- return 2 /* UPPERCASE */;
- case 'lowercase':
- return 1 /* LOWERCASE */;
- case 'capitalize':
- return 3 /* CAPITALIZE */;
- }
- return 0 /* NONE */;
- }
- };
-
- var transform$1 = {
- name: 'transform',
- initialValue: 'none',
- prefix: true,
- type: 0 /* VALUE */,
- parse: function (_context, token) {
- if (token.type === 20 /* IDENT_TOKEN */ && token.value === 'none') {
- return null;
- }
- if (token.type === 18 /* FUNCTION */) {
- var transformFunction = SUPPORTED_TRANSFORM_FUNCTIONS[token.name];
- if (typeof transformFunction === 'undefined') {
- throw new Error("Attempting to parse an unsupported transform function \"" + token.name + "\"");
- }
- return transformFunction(token.values);
- }
- return null;
- }
- };
- var matrix = function (args) {
- var values = args.filter(function (arg) { return arg.type === 17 /* NUMBER_TOKEN */; }).map(function (arg) { return arg.number; });
- return values.length === 6 ? values : null;
- };
- // doesn't support 3D transforms at the moment
- var matrix3d = function (args) {
- var values = args.filter(function (arg) { return arg.type === 17 /* NUMBER_TOKEN */; }).map(function (arg) { return arg.number; });
- var a1 = values[0], b1 = values[1]; values[2]; values[3]; var a2 = values[4], b2 = values[5]; values[6]; values[7]; values[8]; values[9]; values[10]; values[11]; var a4 = values[12], b4 = values[13]; values[14]; values[15];
- return values.length === 16 ? [a1, b1, a2, b2, a4, b4] : null;
- };
- var SUPPORTED_TRANSFORM_FUNCTIONS = {
- matrix: matrix,
- matrix3d: matrix3d
- };
-
- var DEFAULT_VALUE = {
- type: 16 /* PERCENTAGE_TOKEN */,
- number: 50,
- flags: FLAG_INTEGER
- };
- var DEFAULT = [DEFAULT_VALUE, DEFAULT_VALUE];
- var transformOrigin = {
- name: 'transform-origin',
- initialValue: '50% 50%',
- prefix: true,
- type: 1 /* LIST */,
- parse: function (_context, tokens) {
- var origins = tokens.filter(isLengthPercentage);
- if (origins.length !== 2) {
- return DEFAULT;
- }
- return [origins[0], origins[1]];
- }
- };
-
- var visibility = {
- name: 'visible',
- initialValue: 'none',
- prefix: false,
- type: 2 /* IDENT_VALUE */,
- parse: function (_context, visibility) {
- switch (visibility) {
- case 'hidden':
- return 1 /* HIDDEN */;
- case 'collapse':
- return 2 /* COLLAPSE */;
- case 'visible':
- default:
- return 0 /* VISIBLE */;
- }
- }
- };
-
- var WORD_BREAK;
- (function (WORD_BREAK) {
- WORD_BREAK["NORMAL"] = "normal";
- WORD_BREAK["BREAK_ALL"] = "break-all";
- WORD_BREAK["KEEP_ALL"] = "keep-all";
- })(WORD_BREAK || (WORD_BREAK = {}));
- var wordBreak = {
- name: 'word-break',
- initialValue: 'normal',
- prefix: false,
- type: 2 /* IDENT_VALUE */,
- parse: function (_context, wordBreak) {
- switch (wordBreak) {
- case 'break-all':
- return WORD_BREAK.BREAK_ALL;
- case 'keep-all':
- return WORD_BREAK.KEEP_ALL;
- case 'normal':
- default:
- return WORD_BREAK.NORMAL;
- }
- }
- };
-
- var zIndex = {
- name: 'z-index',
- initialValue: 'auto',
- prefix: false,
- type: 0 /* VALUE */,
- parse: function (_context, token) {
- if (token.type === 20 /* IDENT_TOKEN */) {
- return { auto: true, order: 0 };
- }
- if (isNumberToken(token)) {
- return { auto: false, order: token.number };
- }
- throw new Error("Invalid z-index number parsed");
- }
- };
-
- var time = {
- name: 'time',
- parse: function (_context, value) {
- if (value.type === 15 /* DIMENSION_TOKEN */) {
- switch (value.unit.toLowerCase()) {
- case 's':
- return 1000 * value.number;
- case 'ms':
- return value.number;
- }
- }
- throw new Error("Unsupported time type");
- }
- };
-
- var opacity = {
- name: 'opacity',
- initialValue: '1',
- type: 0 /* VALUE */,
- prefix: false,
- parse: function (_context, token) {
- if (isNumberToken(token)) {
- return token.number;
- }
- return 1;
- }
- };
-
- var textDecorationColor = {
- name: "text-decoration-color",
- initialValue: 'transparent',
- prefix: false,
- type: 3 /* TYPE_VALUE */,
- format: 'color'
- };
-
- var textDecorationLine = {
- name: 'text-decoration-line',
- initialValue: 'none',
- prefix: false,
- type: 1 /* LIST */,
- parse: function (_context, tokens) {
- return tokens
- .filter(isIdentToken)
- .map(function (token) {
- switch (token.value) {
- case 'underline':
- return 1 /* UNDERLINE */;
- case 'overline':
- return 2 /* OVERLINE */;
- case 'line-through':
- return 3 /* LINE_THROUGH */;
- case 'none':
- return 4 /* BLINK */;
- }
- return 0 /* NONE */;
- })
- .filter(function (line) { return line !== 0 /* NONE */; });
- }
- };
-
- var fontFamily = {
- name: "font-family",
- initialValue: '',
- prefix: false,
- type: 1 /* LIST */,
- parse: function (_context, tokens) {
- var accumulator = [];
- var results = [];
- tokens.forEach(function (token) {
- switch (token.type) {
- case 20 /* IDENT_TOKEN */:
- case 0 /* STRING_TOKEN */:
- accumulator.push(token.value);
- break;
- case 17 /* NUMBER_TOKEN */:
- accumulator.push(token.number.toString());
- break;
- case 4 /* COMMA_TOKEN */:
- results.push(accumulator.join(' '));
- accumulator.length = 0;
- break;
- }
- });
- if (accumulator.length) {
- results.push(accumulator.join(' '));
- }
- return results.map(function (result) { return (result.indexOf(' ') === -1 ? result : "'" + result + "'"); });
- }
- };
-
- var fontSize = {
- name: "font-size",
- initialValue: '0',
- prefix: false,
- type: 3 /* TYPE_VALUE */,
- format: 'length'
- };
-
- var fontWeight = {
- name: 'font-weight',
- initialValue: 'normal',
- type: 0 /* VALUE */,
- prefix: false,
- parse: function (_context, token) {
- if (isNumberToken(token)) {
- return token.number;
- }
- if (isIdentToken(token)) {
- switch (token.value) {
- case 'bold':
- return 700;
- case 'normal':
- default:
- return 400;
- }
- }
- return 400;
- }
- };
-
- var fontVariant = {
- name: 'font-variant',
- initialValue: 'none',
- type: 1 /* LIST */,
- prefix: false,
- parse: function (_context, tokens) {
- return tokens.filter(isIdentToken).map(function (token) { return token.value; });
- }
- };
-
- var fontStyle = {
- name: 'font-style',
- initialValue: 'normal',
- prefix: false,
- type: 2 /* IDENT_VALUE */,
- parse: function (_context, overflow) {
- switch (overflow) {
- case 'oblique':
- return "oblique" /* OBLIQUE */;
- case 'italic':
- return "italic" /* ITALIC */;
- case 'normal':
- default:
- return "normal" /* NORMAL */;
- }
- }
- };
-
- var contains = function (bit, value) { return (bit & value) !== 0; };
-
- var content = {
- name: 'content',
- initialValue: 'none',
- type: 1 /* LIST */,
- prefix: false,
- parse: function (_context, tokens) {
- if (tokens.length === 0) {
- return [];
- }
- var first = tokens[0];
- if (first.type === 20 /* IDENT_TOKEN */ && first.value === 'none') {
- return [];
- }
- return tokens;
- }
- };
-
- var counterIncrement = {
- name: 'counter-increment',
- initialValue: 'none',
- prefix: true,
- type: 1 /* LIST */,
- parse: function (_context, tokens) {
- if (tokens.length === 0) {
- return null;
- }
- var first = tokens[0];
- if (first.type === 20 /* IDENT_TOKEN */ && first.value === 'none') {
- return null;
- }
- var increments = [];
- var filtered = tokens.filter(nonWhiteSpace);
- for (var i = 0; i < filtered.length; i++) {
- var counter = filtered[i];
- var next = filtered[i + 1];
- if (counter.type === 20 /* IDENT_TOKEN */) {
- var increment = next && isNumberToken(next) ? next.number : 1;
- increments.push({ counter: counter.value, increment: increment });
- }
- }
- return increments;
- }
- };
-
- var counterReset = {
- name: 'counter-reset',
- initialValue: 'none',
- prefix: true,
- type: 1 /* LIST */,
- parse: function (_context, tokens) {
- if (tokens.length === 0) {
- return [];
- }
- var resets = [];
- var filtered = tokens.filter(nonWhiteSpace);
- for (var i = 0; i < filtered.length; i++) {
- var counter = filtered[i];
- var next = filtered[i + 1];
- if (isIdentToken(counter) && counter.value !== 'none') {
- var reset = next && isNumberToken(next) ? next.number : 0;
- resets.push({ counter: counter.value, reset: reset });
- }
- }
- return resets;
- }
- };
-
- var duration = {
- name: 'duration',
- initialValue: '0s',
- prefix: false,
- type: 1 /* LIST */,
- parse: function (context, tokens) {
- return tokens.filter(isDimensionToken).map(function (token) { return time.parse(context, token); });
- }
- };
-
- var quotes = {
- name: 'quotes',
- initialValue: 'none',
- prefix: true,
- type: 1 /* LIST */,
- parse: function (_context, tokens) {
- if (tokens.length === 0) {
- return null;
- }
- var first = tokens[0];
- if (first.type === 20 /* IDENT_TOKEN */ && first.value === 'none') {
- return null;
- }
- var quotes = [];
- var filtered = tokens.filter(isStringToken);
- if (filtered.length % 2 !== 0) {
- return null;
- }
- for (var i = 0; i < filtered.length; i += 2) {
- var open_1 = filtered[i].value;
- var close_1 = filtered[i + 1].value;
- quotes.push({ open: open_1, close: close_1 });
- }
- return quotes;
- }
- };
- var getQuote = function (quotes, depth, open) {
- if (!quotes) {
- return '';
- }
- var quote = quotes[Math.min(depth, quotes.length - 1)];
- if (!quote) {
- return '';
- }
- return open ? quote.open : quote.close;
- };
-
- var paintOrder = {
- name: 'paint-order',
- initialValue: 'normal',
- prefix: false,
- type: 1 /* LIST */,
- parse: function (_context, tokens) {
- var DEFAULT_VALUE = [0 /* FILL */, 1 /* STROKE */, 2 /* MARKERS */];
- var layers = [];
- tokens.filter(isIdentToken).forEach(function (token) {
- switch (token.value) {
- case 'stroke':
- layers.push(1 /* STROKE */);
- break;
- case 'fill':
- layers.push(0 /* FILL */);
- break;
- case 'markers':
- layers.push(2 /* MARKERS */);
- break;
- }
- });
- DEFAULT_VALUE.forEach(function (value) {
- if (layers.indexOf(value) === -1) {
- layers.push(value);
- }
- });
- return layers;
- }
- };
-
- var webkitTextStrokeColor = {
- name: "-webkit-text-stroke-color",
- initialValue: 'currentcolor',
- prefix: false,
- type: 3 /* TYPE_VALUE */,
- format: 'color'
- };
-
- var webkitTextStrokeWidth = {
- name: "-webkit-text-stroke-width",
- initialValue: '0',
- type: 0 /* VALUE */,
- prefix: false,
- parse: function (_context, token) {
- if (isDimensionToken(token)) {
- return token.number;
- }
- return 0;
- }
- };
-
- var CSSParsedDeclaration = /** @class */ (function () {
- function CSSParsedDeclaration(context, declaration) {
- var _a, _b;
- this.animationDuration = parse(context, duration, declaration.animationDuration);
- this.backgroundClip = parse(context, backgroundClip, declaration.backgroundClip);
- this.backgroundColor = parse(context, backgroundColor, declaration.backgroundColor);
- this.backgroundImage = parse(context, backgroundImage, declaration.backgroundImage);
- this.backgroundOrigin = parse(context, backgroundOrigin, declaration.backgroundOrigin);
- this.backgroundPosition = parse(context, backgroundPosition, declaration.backgroundPosition);
- this.backgroundRepeat = parse(context, backgroundRepeat, declaration.backgroundRepeat);
- this.backgroundSize = parse(context, backgroundSize, declaration.backgroundSize);
- this.borderTopColor = parse(context, borderTopColor, declaration.borderTopColor);
- this.borderRightColor = parse(context, borderRightColor, declaration.borderRightColor);
- this.borderBottomColor = parse(context, borderBottomColor, declaration.borderBottomColor);
- this.borderLeftColor = parse(context, borderLeftColor, declaration.borderLeftColor);
- this.borderTopLeftRadius = parse(context, borderTopLeftRadius, declaration.borderTopLeftRadius);
- this.borderTopRightRadius = parse(context, borderTopRightRadius, declaration.borderTopRightRadius);
- this.borderBottomRightRadius = parse(context, borderBottomRightRadius, declaration.borderBottomRightRadius);
- this.borderBottomLeftRadius = parse(context, borderBottomLeftRadius, declaration.borderBottomLeftRadius);
- this.borderTopStyle = parse(context, borderTopStyle, declaration.borderTopStyle);
- this.borderRightStyle = parse(context, borderRightStyle, declaration.borderRightStyle);
- this.borderBottomStyle = parse(context, borderBottomStyle, declaration.borderBottomStyle);
- this.borderLeftStyle = parse(context, borderLeftStyle, declaration.borderLeftStyle);
- this.borderTopWidth = parse(context, borderTopWidth, declaration.borderTopWidth);
- this.borderRightWidth = parse(context, borderRightWidth, declaration.borderRightWidth);
- this.borderBottomWidth = parse(context, borderBottomWidth, declaration.borderBottomWidth);
- this.borderLeftWidth = parse(context, borderLeftWidth, declaration.borderLeftWidth);
- this.color = parse(context, color, declaration.color);
- this.direction = parse(context, direction, declaration.direction);
- this.display = parse(context, display, declaration.display);
- this.float = parse(context, float, declaration.cssFloat);
- this.fontFamily = parse(context, fontFamily, declaration.fontFamily);
- this.fontSize = parse(context, fontSize, declaration.fontSize);
- this.fontStyle = parse(context, fontStyle, declaration.fontStyle);
- this.fontVariant = parse(context, fontVariant, declaration.fontVariant);
- this.fontWeight = parse(context, fontWeight, declaration.fontWeight);
- this.letterSpacing = parse(context, letterSpacing, declaration.letterSpacing);
- this.lineBreak = parse(context, lineBreak, declaration.lineBreak);
- this.lineHeight = parse(context, lineHeight, declaration.lineHeight);
- this.listStyleImage = parse(context, listStyleImage, declaration.listStyleImage);
- this.listStylePosition = parse(context, listStylePosition, declaration.listStylePosition);
- this.listStyleType = parse(context, listStyleType, declaration.listStyleType);
- this.marginTop = parse(context, marginTop, declaration.marginTop);
- this.marginRight = parse(context, marginRight, declaration.marginRight);
- this.marginBottom = parse(context, marginBottom, declaration.marginBottom);
- this.marginLeft = parse(context, marginLeft, declaration.marginLeft);
- this.opacity = parse(context, opacity, declaration.opacity);
- var overflowTuple = parse(context, overflow, declaration.overflow);
- this.overflowX = overflowTuple[0];
- this.overflowY = overflowTuple[overflowTuple.length > 1 ? 1 : 0];
- this.overflowWrap = parse(context, overflowWrap, declaration.overflowWrap);
- this.paddingTop = parse(context, paddingTop, declaration.paddingTop);
- this.paddingRight = parse(context, paddingRight, declaration.paddingRight);
- this.paddingBottom = parse(context, paddingBottom, declaration.paddingBottom);
- this.paddingLeft = parse(context, paddingLeft, declaration.paddingLeft);
- this.paintOrder = parse(context, paintOrder, declaration.paintOrder);
- this.position = parse(context, position, declaration.position);
- this.textAlign = parse(context, textAlign, declaration.textAlign);
- this.textDecorationColor = parse(context, textDecorationColor, (_a = declaration.textDecorationColor) !== null && _a !== void 0 ? _a : declaration.color);
- this.textDecorationLine = parse(context, textDecorationLine, (_b = declaration.textDecorationLine) !== null && _b !== void 0 ? _b : declaration.textDecoration);
- this.textShadow = parse(context, textShadow, declaration.textShadow);
- this.textTransform = parse(context, textTransform, declaration.textTransform);
- this.transform = parse(context, transform$1, declaration.transform);
- this.transformOrigin = parse(context, transformOrigin, declaration.transformOrigin);
- this.visibility = parse(context, visibility, declaration.visibility);
- this.webkitTextStrokeColor = parse(context, webkitTextStrokeColor, declaration.webkitTextStrokeColor);
- this.webkitTextStrokeWidth = parse(context, webkitTextStrokeWidth, declaration.webkitTextStrokeWidth);
- this.wordBreak = parse(context, wordBreak, declaration.wordBreak);
- this.zIndex = parse(context, zIndex, declaration.zIndex);
- }
- CSSParsedDeclaration.prototype.isVisible = function () {
- return this.display > 0 && this.opacity > 0 && this.visibility === 0 /* VISIBLE */;
- };
- CSSParsedDeclaration.prototype.isTransparent = function () {
- return isTransparent(this.backgroundColor);
- };
- CSSParsedDeclaration.prototype.isTransformed = function () {
- return this.transform !== null;
- };
- CSSParsedDeclaration.prototype.isPositioned = function () {
- return this.position !== 0 /* STATIC */;
- };
- CSSParsedDeclaration.prototype.isPositionedWithZIndex = function () {
- return this.isPositioned() && !this.zIndex.auto;
- };
- CSSParsedDeclaration.prototype.isFloating = function () {
- return this.float !== 0 /* NONE */;
- };
- CSSParsedDeclaration.prototype.isInlineLevel = function () {
- return (contains(this.display, 4 /* INLINE */) ||
- contains(this.display, 33554432 /* INLINE_BLOCK */) ||
- contains(this.display, 268435456 /* INLINE_FLEX */) ||
- contains(this.display, 536870912 /* INLINE_GRID */) ||
- contains(this.display, 67108864 /* INLINE_LIST_ITEM */) ||
- contains(this.display, 134217728 /* INLINE_TABLE */));
- };
- return CSSParsedDeclaration;
- }());
- var CSSParsedPseudoDeclaration = /** @class */ (function () {
- function CSSParsedPseudoDeclaration(context, declaration) {
- this.content = parse(context, content, declaration.content);
- this.quotes = parse(context, quotes, declaration.quotes);
- }
- return CSSParsedPseudoDeclaration;
- }());
- var CSSParsedCounterDeclaration = /** @class */ (function () {
- function CSSParsedCounterDeclaration(context, declaration) {
- this.counterIncrement = parse(context, counterIncrement, declaration.counterIncrement);
- this.counterReset = parse(context, counterReset, declaration.counterReset);
- }
- return CSSParsedCounterDeclaration;
- }());
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- var parse = function (context, descriptor, style) {
- var tokenizer = new Tokenizer();
- var value = style !== null && typeof style !== 'undefined' ? style.toString() : descriptor.initialValue;
- tokenizer.write(value);
- var parser = new Parser(tokenizer.read());
- switch (descriptor.type) {
- case 2 /* IDENT_VALUE */:
- var token = parser.parseComponentValue();
- return descriptor.parse(context, isIdentToken(token) ? token.value : descriptor.initialValue);
- case 0 /* VALUE */:
- return descriptor.parse(context, parser.parseComponentValue());
- case 1 /* LIST */:
- return descriptor.parse(context, parser.parseComponentValues());
- case 4 /* TOKEN_VALUE */:
- return parser.parseComponentValue();
- case 3 /* TYPE_VALUE */:
- switch (descriptor.format) {
- case 'angle':
- return angle.parse(context, parser.parseComponentValue());
- case 'color':
- return color$1.parse(context, parser.parseComponentValue());
- case 'image':
- return image.parse(context, parser.parseComponentValue());
- case 'length':
- var length_1 = parser.parseComponentValue();
- return isLength(length_1) ? length_1 : ZERO_LENGTH;
- case 'length-percentage':
- var value_1 = parser.parseComponentValue();
- return isLengthPercentage(value_1) ? value_1 : ZERO_LENGTH;
- case 'time':
- return time.parse(context, parser.parseComponentValue());
- }
- break;
- }
- };
-
- var elementDebuggerAttribute = 'data-html2canvas-debug';
- var getElementDebugType = function (element) {
- var attribute = element.getAttribute(elementDebuggerAttribute);
- switch (attribute) {
- case 'all':
- return 1 /* ALL */;
- case 'clone':
- return 2 /* CLONE */;
- case 'parse':
- return 3 /* PARSE */;
- case 'render':
- return 4 /* RENDER */;
- default:
- return 0 /* NONE */;
- }
- };
- var isDebugging = function (element, type) {
- var elementType = getElementDebugType(element);
- return elementType === 1 /* ALL */ || type === elementType;
- };
-
- var ElementContainer = /** @class */ (function () {
- function ElementContainer(context, element) {
- this.context = context;
- this.textNodes = [];
- this.elements = [];
- this.flags = 0;
- if (isDebugging(element, 3 /* PARSE */)) {
- debugger;
- }
- this.styles = new CSSParsedDeclaration(context, window.getComputedStyle(element, null));
- if (isHTMLElementNode(element)) {
- if (this.styles.animationDuration.some(function (duration) { return duration > 0; })) {
- element.style.animationDuration = '0s';
- }
- if (this.styles.transform !== null) {
- // getBoundingClientRect takes transforms into account
- element.style.transform = 'none';
- }
- }
- this.bounds = parseBounds(this.context, element);
- if (isDebugging(element, 4 /* RENDER */)) {
- this.flags |= 16 /* DEBUG_RENDER */;
- }
- }
- return ElementContainer;
- }());
-
- /*
- * text-segmentation 1.0.3
- * Copyright (c) 2022 Niklas von Hertzen
- * Released under MIT License
- */
- var base64 = 'AAAAAAAAAAAAEA4AGBkAAFAaAAACAAAAAAAIABAAGAAwADgACAAQAAgAEAAIABAACAAQAAgAEAAIABAACAAQAAgAEAAIABAAQABIAEQATAAIABAACAAQAAgAEAAIABAAVABcAAgAEAAIABAACAAQAGAAaABwAHgAgACIAI4AlgAIABAAmwCjAKgAsAC2AL4AvQDFAMoA0gBPAVYBWgEIAAgACACMANoAYgFkAWwBdAF8AX0BhQGNAZUBlgGeAaMBlQGWAasBswF8AbsBwwF0AcsBYwHTAQgA2wG/AOMBdAF8AekB8QF0AfkB+wHiAHQBfAEIAAMC5gQIAAsCEgIIAAgAFgIeAggAIgIpAggAMQI5AkACygEIAAgASAJQAlgCYAIIAAgACAAKBQoFCgUTBRMFGQUrBSsFCAAIAAgACAAIAAgACAAIAAgACABdAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABoAmgCrwGvAQgAbgJ2AggAHgEIAAgACADnAXsCCAAIAAgAgwIIAAgACAAIAAgACACKAggAkQKZAggAPADJAAgAoQKkAqwCsgK6AsICCADJAggA0AIIAAgACAAIANYC3gIIAAgACAAIAAgACABAAOYCCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAkASoB+QIEAAgACAA8AEMCCABCBQgACABJBVAFCAAIAAgACAAIAAgACAAIAAgACABTBVoFCAAIAFoFCABfBWUFCAAIAAgACAAIAAgAbQUIAAgACAAIAAgACABzBXsFfQWFBYoFigWKBZEFigWKBYoFmAWfBaYFrgWxBbkFCAAIAAgACAAIAAgACAAIAAgACAAIAMEFCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAMgFCADQBQgACAAIAAgACAAIAAgACAAIAAgACAAIAO4CCAAIAAgAiQAIAAgACABAAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAD0AggACAD8AggACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIANYFCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAMDvwAIAAgAJAIIAAgACAAIAAgACAAIAAgACwMTAwgACAB9BOsEGwMjAwgAKwMyAwsFYgE3A/MEPwMIAEUDTQNRAwgAWQOsAGEDCAAIAAgACAAIAAgACABpAzQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFIQUoBSwFCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABtAwgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABMAEwACAAIAAgACAAIABgACAAIAAgACAC/AAgACAAyAQgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACACAAIAAwAAgACAAIAAgACAAIAAgACAAIAAAARABIAAgACAAIABQASAAIAAgAIABwAEAAjgCIABsAqAC2AL0AigDQAtwC+IJIQqVAZUBWQqVAZUBlQGVAZUBlQGrC5UBlQGVAZUBlQGVAZUBlQGVAXsKlQGVAbAK6wsrDGUMpQzlDJUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAfAKAAuZA64AtwCJALoC6ADwAAgAuACgA/oEpgO6AqsD+AAIAAgAswMIAAgACAAIAIkAuwP5AfsBwwPLAwgACAAIAAgACADRA9kDCAAIAOED6QMIAAgACAAIAAgACADuA/YDCAAIAP4DyQAIAAgABgQIAAgAXQAOBAgACAAIAAgACAAIABMECAAIAAgACAAIAAgACAD8AAQBCAAIAAgAGgQiBCoECAExBAgAEAEIAAgACAAIAAgACAAIAAgACAAIAAgACAA4BAgACABABEYECAAIAAgATAQYAQgAVAQIAAgACAAIAAgACAAIAAgACAAIAFoECAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAOQEIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAB+BAcACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAEABhgSMBAgACAAIAAgAlAQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAwAEAAQABAADAAMAAwADAAQABAAEAAQABAAEAAQABHATAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAdQMIAAgACAAIAAgACAAIAMkACAAIAAgAfQMIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACACFA4kDCAAIAAgACAAIAOcBCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAIcDCAAIAAgACAAIAAgACAAIAAgACAAIAJEDCAAIAAgACADFAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABgBAgAZgQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAbAQCBXIECAAIAHkECAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABAAJwEQACjBKoEsgQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAC6BMIECAAIAAgACAAIAAgACABmBAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAxwQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAGYECAAIAAgAzgQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAigWKBYoFigWKBYoFigWKBd0FXwUIAOIF6gXxBYoF3gT5BQAGCAaKBYoFigWKBYoFigWKBYoFigWKBYoFigXWBIoFigWKBYoFigWKBYoFigWKBYsFEAaKBYoFigWKBYoFigWKBRQGCACKBYoFigWKBQgACAAIANEECAAIABgGigUgBggAJgYIAC4GMwaKBYoF0wQ3Bj4GigWKBYoFigWKBYoFigWKBYoFigWKBYoFigUIAAgACAAIAAgACAAIAAgAigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWLBf///////wQABAAEAAQABAAEAAQABAAEAAQAAwAEAAQAAgAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAQADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAUAAAAFAAUAAAAFAAUAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEAAQABAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUAAQAAAAUABQAFAAUABQAFAAAAAAAFAAUAAAAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAFAAUAAQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABwAFAAUABQAFAAAABwAHAAcAAAAHAAcABwAFAAEAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAcABwAFAAUAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAQABAAAAAAAAAAAAAAAFAAUABQAFAAAABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAcABwAHAAcAAAAHAAcAAAAAAAUABQAHAAUAAQAHAAEABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABwABAAUABQAFAAUAAAAAAAAAAAAAAAEAAQABAAEAAQABAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABwAFAAUAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUAAQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABQANAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAAEAAQABAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEAAQABAAEAAQABAAEAAQABAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAABQAHAAUABQAFAAAAAAAAAAcABQAFAAUABQAFAAQABAAEAAQABAAEAAQABAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUAAAAFAAUABQAFAAUAAAAFAAUABQAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAAAAAAAAAAAAUABQAFAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAUAAAAHAAcABwAFAAUABQAFAAUABQAFAAUABwAHAAcABwAFAAcABwAAAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAUABwAHAAUABQAFAAUAAAAAAAcABwAAAAAABwAHAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAABQAFAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAABwAHAAcABQAFAAAAAAAAAAAABQAFAAAAAAAFAAUABQAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAFAAUABQAFAAUAAAAFAAUABwAAAAcABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAFAAUABwAFAAUABQAFAAAAAAAHAAcAAAAAAAcABwAFAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAcABwAAAAAAAAAHAAcABwAAAAcABwAHAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAABQAHAAcABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAHAAcABwAAAAUABQAFAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAcABQAHAAcABQAHAAcAAAAFAAcABwAAAAcABwAFAAUAAAAAAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAUABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAFAAcABwAFAAUABQAAAAUAAAAHAAcABwAHAAcABwAHAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAHAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAABwAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAUAAAAFAAAAAAAAAAAABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABwAFAAUABQAFAAUAAAAFAAUAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABwAFAAUABQAFAAUABQAAAAUABQAHAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABQAFAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAcABQAFAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAHAAUABQAFAAUABQAFAAUABwAHAAcABwAHAAcABwAHAAUABwAHAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABwAHAAcABwAFAAUABwAHAAcAAAAAAAAAAAAHAAcABQAHAAcABwAHAAcABwAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAcABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAHAAUABQAFAAUABQAFAAUAAAAFAAAABQAAAAAABQAFAAUABQAFAAUABQAFAAcABwAHAAcABwAHAAUABQAFAAUABQAFAAUABQAFAAUAAAAAAAUABQAFAAUABQAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABwAFAAcABwAHAAcABwAFAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAUABQAFAAUABwAHAAUABQAHAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAcABQAFAAcABwAHAAUABwAFAAUABQAHAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABwAHAAcABwAHAAUABQAFAAUABQAFAAUABQAHAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAcABQAFAAUABQAFAAUABQAAAAAAAAAAAAUAAAAAAAAAAAAAAAAABQAAAAAABwAFAAUAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUAAAAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAABQAAAAAAAAAFAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAUABQAHAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAHAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAHAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAcABwAFAAUABQAFAAcABwAFAAUABwAHAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAcABwAFAAUABwAHAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAFAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAFAAUABQAAAAAABQAFAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAFAAcABwAAAAAAAAAAAAAABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAFAAcABwAFAAcABwAAAAcABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAFAAUABQAAAAUABQAAAAAAAAAAAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABwAFAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABQAFAAUABQAFAAUABQAFAAUABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAHAAcABQAHAAUABQAAAAAAAAAAAAAAAAAFAAAABwAHAAcABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAHAAcABwAAAAAABwAHAAAAAAAHAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAAAAAAFAAUABQAFAAUABQAFAAAAAAAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAUABQAFAAUABwAHAAUABQAFAAcABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAcABQAFAAUABQAFAAUABwAFAAcABwAFAAcABQAFAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAcABQAFAAUABQAAAAAABwAHAAcABwAFAAUABwAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAHAAUABQAFAAUABQAFAAUABQAHAAcABQAHAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAFAAcABwAFAAUABQAFAAUABQAHAAUAAAAAAAAAAAAAAAAAAAAAAAcABwAFAAUABQAFAAcABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAUABQAFAAUABQAHAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAAAAAAFAAUABwAHAAcABwAFAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABwAHAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAFAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAcABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAAAHAAUABQAFAAUABQAFAAUABwAFAAUABwAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUAAAAAAAAABQAAAAUABQAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAHAAcAAAAFAAUAAAAHAAcABQAHAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAAAAAAAAAAAAAAAAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAUABQAFAAAAAAAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAABQAFAAUABQAFAAUABQAAAAUABQAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAFAAUABQAFAAUADgAOAA4ADgAOAA4ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAAAAAAAAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAMAAwADAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAAAAAAAAAAAAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAAAAAAAAAAAAsADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwACwAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAADgAOAA4AAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAAAA4ADgAOAA4ADgAOAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAAAA4AAAAOAAAAAAAAAAAAAAAAAA4AAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAADgAAAAAAAAAAAA4AAAAOAAAAAAAAAAAADgAOAA4AAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4AAAAAAA4ADgAOAA4ADgAOAA4ADgAOAAAADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4AAAAAAAAAAAAAAAAAAAAAAA4ADgAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAOAA4ADgAOAA4ADgAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAAAAAAAAA=';
-
- /*
- * utrie 1.0.2
- * Copyright (c) 2022 Niklas von Hertzen
- * Released under MIT License
- */
- var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
- // Use a lookup table to find the index.
- var lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
- for (var i$1 = 0; i$1 < chars$1.length; i$1++) {
- lookup$1[chars$1.charCodeAt(i$1)] = i$1;
- }
- var decode = function (base64) {
- var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
- if (base64[base64.length - 1] === '=') {
- bufferLength--;
- if (base64[base64.length - 2] === '=') {
- bufferLength--;
- }
- }
- var buffer = typeof ArrayBuffer !== 'undefined' &&
- typeof Uint8Array !== 'undefined' &&
- typeof Uint8Array.prototype.slice !== 'undefined'
- ? new ArrayBuffer(bufferLength)
- : new Array(bufferLength);
- var bytes = Array.isArray(buffer) ? buffer : new Uint8Array(buffer);
- for (i = 0; i < len; i += 4) {
- encoded1 = lookup$1[base64.charCodeAt(i)];
- encoded2 = lookup$1[base64.charCodeAt(i + 1)];
- encoded3 = lookup$1[base64.charCodeAt(i + 2)];
- encoded4 = lookup$1[base64.charCodeAt(i + 3)];
- bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
- bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
- bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
- }
- return buffer;
- };
- var polyUint16Array = function (buffer) {
- var length = buffer.length;
- var bytes = [];
- for (var i = 0; i < length; i += 2) {
- bytes.push((buffer[i + 1] << 8) | buffer[i]);
- }
- return bytes;
- };
- var polyUint32Array = function (buffer) {
- var length = buffer.length;
- var bytes = [];
- for (var i = 0; i < length; i += 4) {
- bytes.push((buffer[i + 3] << 24) | (buffer[i + 2] << 16) | (buffer[i + 1] << 8) | buffer[i]);
- }
- return bytes;
- };
-
- /** Shift size for getting the index-2 table offset. */
- var UTRIE2_SHIFT_2 = 5;
- /** Shift size for getting the index-1 table offset. */
- var UTRIE2_SHIFT_1 = 6 + 5;
- /**
- * Shift size for shifting left the index array values.
- * Increases possible data size with 16-bit index values at the cost
- * of compactability.
- * This requires data blocks to be aligned by UTRIE2_DATA_GRANULARITY.
- */
- var UTRIE2_INDEX_SHIFT = 2;
- /**
- * Difference between the two shift sizes,
- * for getting an index-1 offset from an index-2 offset. 6=11-5
- */
- var UTRIE2_SHIFT_1_2 = UTRIE2_SHIFT_1 - UTRIE2_SHIFT_2;
- /**
- * The part of the index-2 table for U+D800..U+DBFF stores values for
- * lead surrogate code _units_ not code _points_.
- * Values for lead surrogate code _points_ are indexed with this portion of the table.
- * Length=32=0x20=0x400>>UTRIE2_SHIFT_2. (There are 1024=0x400 lead surrogates.)
- */
- var UTRIE2_LSCP_INDEX_2_OFFSET = 0x10000 >> UTRIE2_SHIFT_2;
- /** Number of entries in a data block. 32=0x20 */
- var UTRIE2_DATA_BLOCK_LENGTH = 1 << UTRIE2_SHIFT_2;
- /** Mask for getting the lower bits for the in-data-block offset. */
- var UTRIE2_DATA_MASK = UTRIE2_DATA_BLOCK_LENGTH - 1;
- var UTRIE2_LSCP_INDEX_2_LENGTH = 0x400 >> UTRIE2_SHIFT_2;
- /** Count the lengths of both BMP pieces. 2080=0x820 */
- var UTRIE2_INDEX_2_BMP_LENGTH = UTRIE2_LSCP_INDEX_2_OFFSET + UTRIE2_LSCP_INDEX_2_LENGTH;
- /**
- * The 2-byte UTF-8 version of the index-2 table follows at offset 2080=0x820.
- * Length 32=0x20 for lead bytes C0..DF, regardless of UTRIE2_SHIFT_2.
- */
- var UTRIE2_UTF8_2B_INDEX_2_OFFSET = UTRIE2_INDEX_2_BMP_LENGTH;
- var UTRIE2_UTF8_2B_INDEX_2_LENGTH = 0x800 >> 6; /* U+0800 is the first code point after 2-byte UTF-8 */
- /**
- * The index-1 table, only used for supplementary code points, at offset 2112=0x840.
- * Variable length, for code points up to highStart, where the last single-value range starts.
- * Maximum length 512=0x200=0x100000>>UTRIE2_SHIFT_1.
- * (For 0x100000 supplementary code points U+10000..U+10ffff.)
- *
- * The part of the index-2 table for supplementary code points starts
- * after this index-1 table.
- *
- * Both the index-1 table and the following part of the index-2 table
- * are omitted completely if there is only BMP data.
- */
- var UTRIE2_INDEX_1_OFFSET = UTRIE2_UTF8_2B_INDEX_2_OFFSET + UTRIE2_UTF8_2B_INDEX_2_LENGTH;
- /**
- * Number of index-1 entries for the BMP. 32=0x20
- * This part of the index-1 table is omitted from the serialized form.
- */
- var UTRIE2_OMITTED_BMP_INDEX_1_LENGTH = 0x10000 >> UTRIE2_SHIFT_1;
- /** Number of entries in an index-2 block. 64=0x40 */
- var UTRIE2_INDEX_2_BLOCK_LENGTH = 1 << UTRIE2_SHIFT_1_2;
- /** Mask for getting the lower bits for the in-index-2-block offset. */
- var UTRIE2_INDEX_2_MASK = UTRIE2_INDEX_2_BLOCK_LENGTH - 1;
- var slice16 = function (view, start, end) {
- if (view.slice) {
- return view.slice(start, end);
- }
- return new Uint16Array(Array.prototype.slice.call(view, start, end));
- };
- var slice32 = function (view, start, end) {
- if (view.slice) {
- return view.slice(start, end);
- }
- return new Uint32Array(Array.prototype.slice.call(view, start, end));
- };
- var createTrieFromBase64 = function (base64, _byteLength) {
- var buffer = decode(base64);
- var view32 = Array.isArray(buffer) ? polyUint32Array(buffer) : new Uint32Array(buffer);
- var view16 = Array.isArray(buffer) ? polyUint16Array(buffer) : new Uint16Array(buffer);
- var headerLength = 24;
- var index = slice16(view16, headerLength / 2, view32[4] / 2);
- var data = view32[5] === 2
- ? slice16(view16, (headerLength + view32[4]) / 2)
- : slice32(view32, Math.ceil((headerLength + view32[4]) / 4));
- return new Trie(view32[0], view32[1], view32[2], view32[3], index, data);
- };
- var Trie = /** @class */ (function () {
- function Trie(initialValue, errorValue, highStart, highValueIndex, index, data) {
- this.initialValue = initialValue;
- this.errorValue = errorValue;
- this.highStart = highStart;
- this.highValueIndex = highValueIndex;
- this.index = index;
- this.data = data;
- }
- /**
- * Get the value for a code point as stored in the Trie.
- *
- * @param codePoint the code point
- * @return the value
- */
- Trie.prototype.get = function (codePoint) {
- var ix;
- if (codePoint >= 0) {
- if (codePoint < 0x0d800 || (codePoint > 0x0dbff && codePoint <= 0x0ffff)) {
- // Ordinary BMP code point, excluding leading surrogates.
- // BMP uses a single level lookup. BMP index starts at offset 0 in the Trie2 index.
- // 16 bit data is stored in the index array itself.
- ix = this.index[codePoint >> UTRIE2_SHIFT_2];
- ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK);
- return this.data[ix];
- }
- if (codePoint <= 0xffff) {
- // Lead Surrogate Code Point. A Separate index section is stored for
- // lead surrogate code units and code points.
- // The main index has the code unit data.
- // For this function, we need the code point data.
- // Note: this expression could be refactored for slightly improved efficiency, but
- // surrogate code points will be so rare in practice that it's not worth it.
- ix = this.index[UTRIE2_LSCP_INDEX_2_OFFSET + ((codePoint - 0xd800) >> UTRIE2_SHIFT_2)];
- ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK);
- return this.data[ix];
- }
- if (codePoint < this.highStart) {
- // Supplemental code point, use two-level lookup.
- ix = UTRIE2_INDEX_1_OFFSET - UTRIE2_OMITTED_BMP_INDEX_1_LENGTH + (codePoint >> UTRIE2_SHIFT_1);
- ix = this.index[ix];
- ix += (codePoint >> UTRIE2_SHIFT_2) & UTRIE2_INDEX_2_MASK;
- ix = this.index[ix];
- ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK);
- return this.data[ix];
- }
- if (codePoint <= 0x10ffff) {
- return this.data[this.highValueIndex];
- }
- }
- // Fall through. The code point is outside of the legal range of 0..0x10ffff.
- return this.errorValue;
- };
- return Trie;
- }());
-
- /*
- * base64-arraybuffer 1.0.2
- * Copyright (c) 2022 Niklas von Hertzen
- * Released under MIT License
- */
- var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
- // Use a lookup table to find the index.
- var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
- for (var i = 0; i < chars.length; i++) {
- lookup[chars.charCodeAt(i)] = i;
- }
-
- var Prepend = 1;
- var CR = 2;
- var LF = 3;
- var Control = 4;
- var Extend = 5;
- var SpacingMark = 7;
- var L = 8;
- var V = 9;
- var T = 10;
- var LV = 11;
- var LVT = 12;
- var ZWJ = 13;
- var Extended_Pictographic = 14;
- var RI = 15;
- var toCodePoints = function (str) {
- var codePoints = [];
- var i = 0;
- var length = str.length;
- while (i < length) {
- var value = str.charCodeAt(i++);
- if (value >= 0xd800 && value <= 0xdbff && i < length) {
- var extra = str.charCodeAt(i++);
- if ((extra & 0xfc00) === 0xdc00) {
- codePoints.push(((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000);
- }
- else {
- codePoints.push(value);
- i--;
- }
- }
- else {
- codePoints.push(value);
- }
- }
- return codePoints;
- };
- var fromCodePoint = function () {
- var codePoints = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- codePoints[_i] = arguments[_i];
- }
- if (String.fromCodePoint) {
- return String.fromCodePoint.apply(String, codePoints);
- }
- var length = codePoints.length;
- if (!length) {
- return '';
- }
- var codeUnits = [];
- var index = -1;
- var result = '';
- while (++index < length) {
- var codePoint = codePoints[index];
- if (codePoint <= 0xffff) {
- codeUnits.push(codePoint);
- }
- else {
- codePoint -= 0x10000;
- codeUnits.push((codePoint >> 10) + 0xd800, (codePoint % 0x400) + 0xdc00);
- }
- if (index + 1 === length || codeUnits.length > 0x4000) {
- result += String.fromCharCode.apply(String, codeUnits);
- codeUnits.length = 0;
- }
- }
- return result;
- };
- var UnicodeTrie = createTrieFromBase64(base64);
- var BREAK_NOT_ALLOWED = '×';
- var BREAK_ALLOWED = '÷';
- var codePointToClass = function (codePoint) { return UnicodeTrie.get(codePoint); };
- var _graphemeBreakAtIndex = function (_codePoints, classTypes, index) {
- var prevIndex = index - 2;
- var prev = classTypes[prevIndex];
- var current = classTypes[index - 1];
- var next = classTypes[index];
- // GB3 Do not break between a CR and LF
- if (current === CR && next === LF) {
- return BREAK_NOT_ALLOWED;
- }
- // GB4 Otherwise, break before and after controls.
- if (current === CR || current === LF || current === Control) {
- return BREAK_ALLOWED;
- }
- // GB5
- if (next === CR || next === LF || next === Control) {
- return BREAK_ALLOWED;
- }
- // Do not break Hangul syllable sequences.
- // GB6
- if (current === L && [L, V, LV, LVT].indexOf(next) !== -1) {
- return BREAK_NOT_ALLOWED;
- }
- // GB7
- if ((current === LV || current === V) && (next === V || next === T)) {
- return BREAK_NOT_ALLOWED;
- }
- // GB8
- if ((current === LVT || current === T) && next === T) {
- return BREAK_NOT_ALLOWED;
- }
- // GB9 Do not break before extending characters or ZWJ.
- if (next === ZWJ || next === Extend) {
- return BREAK_NOT_ALLOWED;
- }
- // Do not break before SpacingMarks, or after Prepend characters.
- // GB9a
- if (next === SpacingMark) {
- return BREAK_NOT_ALLOWED;
- }
- // GB9a
- if (current === Prepend) {
- return BREAK_NOT_ALLOWED;
- }
- // GB11 Do not break within emoji modifier sequences or emoji zwj sequences.
- if (current === ZWJ && next === Extended_Pictographic) {
- while (prev === Extend) {
- prev = classTypes[--prevIndex];
- }
- if (prev === Extended_Pictographic) {
- return BREAK_NOT_ALLOWED;
- }
- }
- // GB12 Do not break within emoji flag sequences.
- // That is, do not break between regional indicator (RI) symbols
- // if there is an odd number of RI characters before the break point.
- if (current === RI && next === RI) {
- var countRI = 0;
- while (prev === RI) {
- countRI++;
- prev = classTypes[--prevIndex];
- }
- if (countRI % 2 === 0) {
- return BREAK_NOT_ALLOWED;
- }
- }
- return BREAK_ALLOWED;
- };
- var GraphemeBreaker = function (str) {
- var codePoints = toCodePoints(str);
- var length = codePoints.length;
- var index = 0;
- var lastEnd = 0;
- var classTypes = codePoints.map(codePointToClass);
- return {
- next: function () {
- if (index >= length) {
- return { done: true, value: null };
- }
- var graphemeBreak = BREAK_NOT_ALLOWED;
- while (index < length &&
- (graphemeBreak = _graphemeBreakAtIndex(codePoints, classTypes, ++index)) === BREAK_NOT_ALLOWED) { }
- if (graphemeBreak !== BREAK_NOT_ALLOWED || index === length) {
- var value = fromCodePoint.apply(null, codePoints.slice(lastEnd, index));
- lastEnd = index;
- return { value: value, done: false };
- }
- return { done: true, value: null };
- },
- };
- };
- var splitGraphemes = function (str) {
- var breaker = GraphemeBreaker(str);
- var graphemes = [];
- var bk;
- while (!(bk = breaker.next()).done) {
- if (bk.value) {
- graphemes.push(bk.value.slice());
- }
- }
- return graphemes;
- };
-
- var testRangeBounds = function (document) {
- var TEST_HEIGHT = 123;
- if (document.createRange) {
- var range = document.createRange();
- if (range.getBoundingClientRect) {
- var testElement = document.createElement('boundtest');
- testElement.style.height = TEST_HEIGHT + "px";
- testElement.style.display = 'block';
- document.body.appendChild(testElement);
- range.selectNode(testElement);
- var rangeBounds = range.getBoundingClientRect();
- var rangeHeight = Math.round(rangeBounds.height);
- document.body.removeChild(testElement);
- if (rangeHeight === TEST_HEIGHT) {
- return true;
- }
- }
- }
- return false;
- };
- var testIOSLineBreak = function (document) {
- var testElement = document.createElement('boundtest');
- testElement.style.width = '50px';
- testElement.style.display = 'block';
- testElement.style.fontSize = '12px';
- testElement.style.letterSpacing = '0px';
- testElement.style.wordSpacing = '0px';
- document.body.appendChild(testElement);
- var range = document.createRange();
- testElement.innerHTML = typeof ''.repeat === 'function' ? '👨'.repeat(10) : '';
- var node = testElement.firstChild;
- var textList = toCodePoints$1(node.data).map(function (i) { return fromCodePoint$1(i); });
- var offset = 0;
- var prev = {};
- // ios 13 does not handle range getBoundingClientRect line changes correctly #2177
- var supports = textList.every(function (text, i) {
- range.setStart(node, offset);
- range.setEnd(node, offset + text.length);
- var rect = range.getBoundingClientRect();
- offset += text.length;
- var boundAhead = rect.x > prev.x || rect.y > prev.y;
- prev = rect;
- if (i === 0) {
- return true;
- }
- return boundAhead;
- });
- document.body.removeChild(testElement);
- return supports;
- };
- var testCORS = function () { return typeof new Image().crossOrigin !== 'undefined'; };
- var testResponseType = function () { return typeof new XMLHttpRequest().responseType === 'string'; };
- var testSVG = function (document) {
- var img = new Image();
- var canvas = document.createElement('canvas');
- var ctx = canvas.getContext('2d');
- if (!ctx) {
- return false;
- }
- img.src = "data:image/svg+xml,";
- try {
- ctx.drawImage(img, 0, 0);
- canvas.toDataURL();
- }
- catch (e) {
- return false;
- }
- return true;
- };
- var isGreenPixel = function (data) {
- return data[0] === 0 && data[1] === 255 && data[2] === 0 && data[3] === 255;
- };
- var testForeignObject = function (document) {
- var canvas = document.createElement('canvas');
- var size = 100;
- canvas.width = size;
- canvas.height = size;
- var ctx = canvas.getContext('2d');
- if (!ctx) {
- return Promise.reject(false);
- }
- ctx.fillStyle = 'rgb(0, 255, 0)';
- ctx.fillRect(0, 0, size, size);
- var img = new Image();
- var greenImageSrc = canvas.toDataURL();
- img.src = greenImageSrc;
- var svg = createForeignObjectSVG(size, size, 0, 0, img);
- ctx.fillStyle = 'red';
- ctx.fillRect(0, 0, size, size);
- return loadSerializedSVG$1(svg)
- .then(function (img) {
- ctx.drawImage(img, 0, 0);
- var data = ctx.getImageData(0, 0, size, size).data;
- ctx.fillStyle = 'red';
- ctx.fillRect(0, 0, size, size);
- var node = document.createElement('div');
- node.style.backgroundImage = "url(" + greenImageSrc + ")";
- node.style.height = size + "px";
- // Firefox 55 does not render inline tags
- return isGreenPixel(data)
- ? loadSerializedSVG$1(createForeignObjectSVG(size, size, 0, 0, node))
- : Promise.reject(false);
- })
- .then(function (img) {
- ctx.drawImage(img, 0, 0);
- // Edge does not render background-images
- return isGreenPixel(ctx.getImageData(0, 0, size, size).data);
- })
- .catch(function () { return false; });
- };
- var createForeignObjectSVG = function (width, height, x, y, node) {
- var xmlns = 'http://www.w3.org/2000/svg';
- var svg = document.createElementNS(xmlns, 'svg');
- var foreignObject = document.createElementNS(xmlns, 'foreignObject');
- svg.setAttributeNS(null, 'width', width.toString());
- svg.setAttributeNS(null, 'height', height.toString());
- foreignObject.setAttributeNS(null, 'width', '100%');
- foreignObject.setAttributeNS(null, 'height', '100%');
- foreignObject.setAttributeNS(null, 'x', x.toString());
- foreignObject.setAttributeNS(null, 'y', y.toString());
- foreignObject.setAttributeNS(null, 'externalResourcesRequired', 'true');
- svg.appendChild(foreignObject);
- foreignObject.appendChild(node);
- return svg;
- };
- var loadSerializedSVG$1 = function (svg) {
- return new Promise(function (resolve, reject) {
- var img = new Image();
- img.onload = function () { return resolve(img); };
- img.onerror = reject;
- img.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(new XMLSerializer().serializeToString(svg));
- });
- };
- var FEATURES = {
- get SUPPORT_RANGE_BOUNDS() {
- var value = testRangeBounds(document);
- Object.defineProperty(FEATURES, 'SUPPORT_RANGE_BOUNDS', { value: value });
- return value;
- },
- get SUPPORT_WORD_BREAKING() {
- var value = FEATURES.SUPPORT_RANGE_BOUNDS && testIOSLineBreak(document);
- Object.defineProperty(FEATURES, 'SUPPORT_WORD_BREAKING', { value: value });
- return value;
- },
- get SUPPORT_SVG_DRAWING() {
- var value = testSVG(document);
- Object.defineProperty(FEATURES, 'SUPPORT_SVG_DRAWING', { value: value });
- return value;
- },
- get SUPPORT_FOREIGNOBJECT_DRAWING() {
- var value = typeof Array.from === 'function' && typeof window.fetch === 'function'
- ? testForeignObject(document)
- : Promise.resolve(false);
- Object.defineProperty(FEATURES, 'SUPPORT_FOREIGNOBJECT_DRAWING', { value: value });
- return value;
- },
- get SUPPORT_CORS_IMAGES() {
- var value = testCORS();
- Object.defineProperty(FEATURES, 'SUPPORT_CORS_IMAGES', { value: value });
- return value;
- },
- get SUPPORT_RESPONSE_TYPE() {
- var value = testResponseType();
- Object.defineProperty(FEATURES, 'SUPPORT_RESPONSE_TYPE', { value: value });
- return value;
- },
- get SUPPORT_CORS_XHR() {
- var value = 'withCredentials' in new XMLHttpRequest();
- Object.defineProperty(FEATURES, 'SUPPORT_CORS_XHR', { value: value });
- return value;
- },
- get SUPPORT_NATIVE_TEXT_SEGMENTATION() {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- var value = !!(typeof Intl !== 'undefined' && Intl.Segmenter);
- Object.defineProperty(FEATURES, 'SUPPORT_NATIVE_TEXT_SEGMENTATION', { value: value });
- return value;
- }
- };
-
- var TextBounds = /** @class */ (function () {
- function TextBounds(text, bounds) {
- this.text = text;
- this.bounds = bounds;
- }
- return TextBounds;
- }());
- var parseTextBounds = function (context, value, styles, node) {
- var textList = breakText(value, styles);
- var textBounds = [];
- var offset = 0;
- textList.forEach(function (text) {
- if (styles.textDecorationLine.length || text.trim().length > 0) {
- if (FEATURES.SUPPORT_RANGE_BOUNDS) {
- var clientRects = createRange(node, offset, text.length).getClientRects();
- if (clientRects.length > 1) {
- var subSegments = segmentGraphemes(text);
- var subOffset_1 = 0;
- subSegments.forEach(function (subSegment) {
- textBounds.push(new TextBounds(subSegment, Bounds.fromDOMRectList(context, createRange(node, subOffset_1 + offset, subSegment.length).getClientRects())));
- subOffset_1 += subSegment.length;
- });
- }
- else {
- textBounds.push(new TextBounds(text, Bounds.fromDOMRectList(context, clientRects)));
- }
- }
- else {
- var replacementNode = node.splitText(text.length);
- textBounds.push(new TextBounds(text, getWrapperBounds(context, node)));
- node = replacementNode;
- }
- }
- else if (!FEATURES.SUPPORT_RANGE_BOUNDS) {
- node = node.splitText(text.length);
- }
- offset += text.length;
- });
- return textBounds;
- };
- var getWrapperBounds = function (context, node) {
- var ownerDocument = node.ownerDocument;
- if (ownerDocument) {
- var wrapper = ownerDocument.createElement('html2canvaswrapper');
- wrapper.appendChild(node.cloneNode(true));
- var parentNode = node.parentNode;
- if (parentNode) {
- parentNode.replaceChild(wrapper, node);
- var bounds = parseBounds(context, wrapper);
- if (wrapper.firstChild) {
- parentNode.replaceChild(wrapper.firstChild, wrapper);
- }
- return bounds;
- }
- }
- return Bounds.EMPTY;
- };
- var createRange = function (node, offset, length) {
- var ownerDocument = node.ownerDocument;
- if (!ownerDocument) {
- throw new Error('Node has no owner document');
- }
- var range = ownerDocument.createRange();
- range.setStart(node, offset);
- range.setEnd(node, offset + length);
- return range;
- };
- var segmentGraphemes = function (value) {
- if (FEATURES.SUPPORT_NATIVE_TEXT_SEGMENTATION) {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- var segmenter = new Intl.Segmenter(void 0, { granularity: 'grapheme' });
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- return Array.from(segmenter.segment(value)).map(function (segment) { return segment.segment; });
- }
- return splitGraphemes(value);
- };
- var segmentWords = function (value, styles) {
- if (FEATURES.SUPPORT_NATIVE_TEXT_SEGMENTATION) {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- var segmenter = new Intl.Segmenter(void 0, {
- granularity: 'word'
- });
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- return Array.from(segmenter.segment(value)).map(function (segment) { return segment.segment; });
- }
- return breakWords(value, styles);
- };
- var breakText = function (value, styles) {
- return styles.letterSpacing !== 0 ? segmentGraphemes(value) : segmentWords(value, styles);
- };
- // https://drafts.csswg.org/css-text/#word-separator
- var wordSeparators = [0x0020, 0x00a0, 0x1361, 0x10100, 0x10101, 0x1039, 0x1091];
- var breakWords = function (str, styles) {
- var breaker = LineBreaker(str, {
- lineBreak: styles.lineBreak,
- wordBreak: styles.overflowWrap === "break-word" /* BREAK_WORD */ ? 'break-word' : styles.wordBreak
- });
- var words = [];
- var bk;
- var _loop_1 = function () {
- if (bk.value) {
- var value = bk.value.slice();
- var codePoints = toCodePoints$1(value);
- var word_1 = '';
- codePoints.forEach(function (codePoint) {
- if (wordSeparators.indexOf(codePoint) === -1) {
- word_1 += fromCodePoint$1(codePoint);
- }
- else {
- if (word_1.length) {
- words.push(word_1);
- }
- words.push(fromCodePoint$1(codePoint));
- word_1 = '';
- }
- });
- if (word_1.length) {
- words.push(word_1);
- }
- }
- };
- while (!(bk = breaker.next()).done) {
- _loop_1();
- }
- return words;
- };
-
- var TextContainer = /** @class */ (function () {
- function TextContainer(context, node, styles) {
- this.text = transform(node.data, styles.textTransform);
- this.textBounds = parseTextBounds(context, this.text, styles, node);
- }
- return TextContainer;
- }());
- var transform = function (text, transform) {
- switch (transform) {
- case 1 /* LOWERCASE */:
- return text.toLowerCase();
- case 3 /* CAPITALIZE */:
- return text.replace(CAPITALIZE, capitalize);
- case 2 /* UPPERCASE */:
- return text.toUpperCase();
- default:
- return text;
- }
- };
- var CAPITALIZE = /(^|\s|:|-|\(|\))([a-z])/g;
- var capitalize = function (m, p1, p2) {
- if (m.length > 0) {
- return p1 + p2.toUpperCase();
- }
- return m;
- };
-
- var ImageElementContainer = /** @class */ (function (_super) {
- __extends(ImageElementContainer, _super);
- function ImageElementContainer(context, img) {
- var _this = _super.call(this, context, img) || this;
- _this.src = img.currentSrc || img.src;
- _this.intrinsicWidth = img.naturalWidth;
- _this.intrinsicHeight = img.naturalHeight;
- _this.context.cache.addImage(_this.src);
- return _this;
- }
- return ImageElementContainer;
- }(ElementContainer));
-
- var CanvasElementContainer = /** @class */ (function (_super) {
- __extends(CanvasElementContainer, _super);
- function CanvasElementContainer(context, canvas) {
- var _this = _super.call(this, context, canvas) || this;
- _this.canvas = canvas;
- _this.intrinsicWidth = canvas.width;
- _this.intrinsicHeight = canvas.height;
- return _this;
- }
- return CanvasElementContainer;
- }(ElementContainer));
-
- var SVGElementContainer = /** @class */ (function (_super) {
- __extends(SVGElementContainer, _super);
- function SVGElementContainer(context, img) {
- var _this = _super.call(this, context, img) || this;
- var s = new XMLSerializer();
- var bounds = parseBounds(context, img);
- img.setAttribute('width', bounds.width + "px");
- img.setAttribute('height', bounds.height + "px");
- _this.svg = "data:image/svg+xml," + encodeURIComponent(s.serializeToString(img));
- _this.intrinsicWidth = img.width.baseVal.value;
- _this.intrinsicHeight = img.height.baseVal.value;
- _this.context.cache.addImage(_this.svg);
- return _this;
- }
- return SVGElementContainer;
- }(ElementContainer));
-
- var LIElementContainer = /** @class */ (function (_super) {
- __extends(LIElementContainer, _super);
- function LIElementContainer(context, element) {
- var _this = _super.call(this, context, element) || this;
- _this.value = element.value;
- return _this;
- }
- return LIElementContainer;
- }(ElementContainer));
-
- var OLElementContainer = /** @class */ (function (_super) {
- __extends(OLElementContainer, _super);
- function OLElementContainer(context, element) {
- var _this = _super.call(this, context, element) || this;
- _this.start = element.start;
- _this.reversed = typeof element.reversed === 'boolean' && element.reversed === true;
- return _this;
- }
- return OLElementContainer;
- }(ElementContainer));
-
- var CHECKBOX_BORDER_RADIUS = [
- {
- type: 15 /* DIMENSION_TOKEN */,
- flags: 0,
- unit: 'px',
- number: 3
- }
- ];
- var RADIO_BORDER_RADIUS = [
- {
- type: 16 /* PERCENTAGE_TOKEN */,
- flags: 0,
- number: 50
- }
- ];
- var reformatInputBounds = function (bounds) {
- if (bounds.width > bounds.height) {
- return new Bounds(bounds.left + (bounds.width - bounds.height) / 2, bounds.top, bounds.height, bounds.height);
- }
- else if (bounds.width < bounds.height) {
- return new Bounds(bounds.left, bounds.top + (bounds.height - bounds.width) / 2, bounds.width, bounds.width);
- }
- return bounds;
- };
- var getInputValue = function (node) {
- var value = node.type === PASSWORD ? new Array(node.value.length + 1).join('\u2022') : node.value;
- return value.length === 0 ? node.placeholder || '' : value;
- };
- var CHECKBOX = 'checkbox';
- var RADIO = 'radio';
- var PASSWORD = 'password';
- var INPUT_COLOR = 0x2a2a2aff;
- var InputElementContainer = /** @class */ (function (_super) {
- __extends(InputElementContainer, _super);
- function InputElementContainer(context, input) {
- var _this = _super.call(this, context, input) || this;
- _this.type = input.type.toLowerCase();
- _this.checked = input.checked;
- _this.value = getInputValue(input);
- if (_this.type === CHECKBOX || _this.type === RADIO) {
- _this.styles.backgroundColor = 0xdededeff;
- _this.styles.borderTopColor =
- _this.styles.borderRightColor =
- _this.styles.borderBottomColor =
- _this.styles.borderLeftColor =
- 0xa5a5a5ff;
- _this.styles.borderTopWidth =
- _this.styles.borderRightWidth =
- _this.styles.borderBottomWidth =
- _this.styles.borderLeftWidth =
- 1;
- _this.styles.borderTopStyle =
- _this.styles.borderRightStyle =
- _this.styles.borderBottomStyle =
- _this.styles.borderLeftStyle =
- 1 /* SOLID */;
- _this.styles.backgroundClip = [0 /* BORDER_BOX */];
- _this.styles.backgroundOrigin = [0 /* BORDER_BOX */];
- _this.bounds = reformatInputBounds(_this.bounds);
- }
- switch (_this.type) {
- case CHECKBOX:
- _this.styles.borderTopRightRadius =
- _this.styles.borderTopLeftRadius =
- _this.styles.borderBottomRightRadius =
- _this.styles.borderBottomLeftRadius =
- CHECKBOX_BORDER_RADIUS;
- break;
- case RADIO:
- _this.styles.borderTopRightRadius =
- _this.styles.borderTopLeftRadius =
- _this.styles.borderBottomRightRadius =
- _this.styles.borderBottomLeftRadius =
- RADIO_BORDER_RADIUS;
- break;
- }
- return _this;
- }
- return InputElementContainer;
- }(ElementContainer));
-
- var SelectElementContainer = /** @class */ (function (_super) {
- __extends(SelectElementContainer, _super);
- function SelectElementContainer(context, element) {
- var _this = _super.call(this, context, element) || this;
- var option = element.options[element.selectedIndex || 0];
- _this.value = option ? option.text || '' : '';
- return _this;
- }
- return SelectElementContainer;
- }(ElementContainer));
-
- var TextareaElementContainer = /** @class */ (function (_super) {
- __extends(TextareaElementContainer, _super);
- function TextareaElementContainer(context, element) {
- var _this = _super.call(this, context, element) || this;
- _this.value = element.value;
- return _this;
- }
- return TextareaElementContainer;
- }(ElementContainer));
-
- var IFrameElementContainer = /** @class */ (function (_super) {
- __extends(IFrameElementContainer, _super);
- function IFrameElementContainer(context, iframe) {
- var _this = _super.call(this, context, iframe) || this;
- _this.src = iframe.src;
- _this.width = parseInt(iframe.width, 10) || 0;
- _this.height = parseInt(iframe.height, 10) || 0;
- _this.backgroundColor = _this.styles.backgroundColor;
- try {
- if (iframe.contentWindow &&
- iframe.contentWindow.document &&
- iframe.contentWindow.document.documentElement) {
- _this.tree = parseTree(context, iframe.contentWindow.document.documentElement);
- // http://www.w3.org/TR/css3-background/#special-backgrounds
- var documentBackgroundColor = iframe.contentWindow.document.documentElement
- ? parseColor(context, getComputedStyle(iframe.contentWindow.document.documentElement).backgroundColor)
- : COLORS.TRANSPARENT;
- var bodyBackgroundColor = iframe.contentWindow.document.body
- ? parseColor(context, getComputedStyle(iframe.contentWindow.document.body).backgroundColor)
- : COLORS.TRANSPARENT;
- _this.backgroundColor = isTransparent(documentBackgroundColor)
- ? isTransparent(bodyBackgroundColor)
- ? _this.styles.backgroundColor
- : bodyBackgroundColor
- : documentBackgroundColor;
- }
- }
- catch (e) { }
- return _this;
- }
- return IFrameElementContainer;
- }(ElementContainer));
-
- var LIST_OWNERS = ['OL', 'UL', 'MENU'];
- var parseNodeTree = function (context, node, parent, root) {
- for (var childNode = node.firstChild, nextNode = void 0; childNode; childNode = nextNode) {
- nextNode = childNode.nextSibling;
- if (isTextNode(childNode) && childNode.data.trim().length > 0) {
- parent.textNodes.push(new TextContainer(context, childNode, parent.styles));
- }
- else if (isElementNode(childNode)) {
- if (isSlotElement(childNode) && childNode.assignedNodes) {
- childNode.assignedNodes().forEach(function (childNode) { return parseNodeTree(context, childNode, parent, root); });
- }
- else {
- var container = createContainer(context, childNode);
- if (container.styles.isVisible()) {
- if (createsRealStackingContext(childNode, container, root)) {
- container.flags |= 4 /* CREATES_REAL_STACKING_CONTEXT */;
- }
- else if (createsStackingContext(container.styles)) {
- container.flags |= 2 /* CREATES_STACKING_CONTEXT */;
- }
- if (LIST_OWNERS.indexOf(childNode.tagName) !== -1) {
- container.flags |= 8 /* IS_LIST_OWNER */;
- }
- parent.elements.push(container);
- childNode.slot;
- if (childNode.shadowRoot) {
- parseNodeTree(context, childNode.shadowRoot, container, root);
- }
- else if (!isTextareaElement(childNode) &&
- !isSVGElement(childNode) &&
- !isSelectElement(childNode)) {
- parseNodeTree(context, childNode, container, root);
- }
- }
- }
- }
- }
- };
- var createContainer = function (context, element) {
- if (isImageElement(element)) {
- return new ImageElementContainer(context, element);
- }
- if (isCanvasElement(element)) {
- return new CanvasElementContainer(context, element);
- }
- if (isSVGElement(element)) {
- return new SVGElementContainer(context, element);
- }
- if (isLIElement(element)) {
- return new LIElementContainer(context, element);
- }
- if (isOLElement(element)) {
- return new OLElementContainer(context, element);
- }
- if (isInputElement(element)) {
- return new InputElementContainer(context, element);
- }
- if (isSelectElement(element)) {
- return new SelectElementContainer(context, element);
- }
- if (isTextareaElement(element)) {
- return new TextareaElementContainer(context, element);
- }
- if (isIFrameElement(element)) {
- return new IFrameElementContainer(context, element);
- }
- return new ElementContainer(context, element);
- };
- var parseTree = function (context, element) {
- var container = createContainer(context, element);
- container.flags |= 4 /* CREATES_REAL_STACKING_CONTEXT */;
- parseNodeTree(context, element, container, container);
- return container;
- };
- var createsRealStackingContext = function (node, container, root) {
- return (container.styles.isPositionedWithZIndex() ||
- container.styles.opacity < 1 ||
- container.styles.isTransformed() ||
- (isBodyElement(node) && root.styles.isTransparent()));
- };
- var createsStackingContext = function (styles) { return styles.isPositioned() || styles.isFloating(); };
- var isTextNode = function (node) { return node.nodeType === Node.TEXT_NODE; };
- var isElementNode = function (node) { return node.nodeType === Node.ELEMENT_NODE; };
- var isHTMLElementNode = function (node) {
- return isElementNode(node) && typeof node.style !== 'undefined' && !isSVGElementNode(node);
- };
- var isSVGElementNode = function (element) {
- return typeof element.className === 'object';
- };
- var isLIElement = function (node) { return node.tagName === 'LI'; };
- var isOLElement = function (node) { return node.tagName === 'OL'; };
- var isInputElement = function (node) { return node.tagName === 'INPUT'; };
- var isHTMLElement = function (node) { return node.tagName === 'HTML'; };
- var isSVGElement = function (node) { return node.tagName === 'svg'; };
- var isBodyElement = function (node) { return node.tagName === 'BODY'; };
- var isCanvasElement = function (node) { return node.tagName === 'CANVAS'; };
- var isVideoElement = function (node) { return node.tagName === 'VIDEO'; };
- var isImageElement = function (node) { return node.tagName === 'IMG'; };
- var isIFrameElement = function (node) { return node.tagName === 'IFRAME'; };
- var isStyleElement = function (node) { return node.tagName === 'STYLE'; };
- var isScriptElement = function (node) { return node.tagName === 'SCRIPT'; };
- var isTextareaElement = function (node) { return node.tagName === 'TEXTAREA'; };
- var isSelectElement = function (node) { return node.tagName === 'SELECT'; };
- var isSlotElement = function (node) { return node.tagName === 'SLOT'; };
- // https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name
- var isCustomElement = function (node) { return node.tagName.indexOf('-') > 0; };
-
- var CounterState = /** @class */ (function () {
- function CounterState() {
- this.counters = {};
- }
- CounterState.prototype.getCounterValue = function (name) {
- var counter = this.counters[name];
- if (counter && counter.length) {
- return counter[counter.length - 1];
- }
- return 1;
- };
- CounterState.prototype.getCounterValues = function (name) {
- var counter = this.counters[name];
- return counter ? counter : [];
- };
- CounterState.prototype.pop = function (counters) {
- var _this = this;
- counters.forEach(function (counter) { return _this.counters[counter].pop(); });
- };
- CounterState.prototype.parse = function (style) {
- var _this = this;
- var counterIncrement = style.counterIncrement;
- var counterReset = style.counterReset;
- var canReset = true;
- if (counterIncrement !== null) {
- counterIncrement.forEach(function (entry) {
- var counter = _this.counters[entry.counter];
- if (counter && entry.increment !== 0) {
- canReset = false;
- if (!counter.length) {
- counter.push(1);
- }
- counter[Math.max(0, counter.length - 1)] += entry.increment;
- }
- });
- }
- var counterNames = [];
- if (canReset) {
- counterReset.forEach(function (entry) {
- var counter = _this.counters[entry.counter];
- counterNames.push(entry.counter);
- if (!counter) {
- counter = _this.counters[entry.counter] = [];
- }
- counter.push(entry.reset);
- });
- }
- return counterNames;
- };
- return CounterState;
- }());
- var ROMAN_UPPER = {
- integers: [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
- values: ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
- };
- var ARMENIAN = {
- integers: [
- 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90, 80, 70,
- 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
- ],
- values: [
- 'Ք',
- 'Փ',
- 'Ւ',
- 'Ց',
- 'Ր',
- 'Տ',
- 'Վ',
- 'Ս',
- 'Ռ',
- 'Ջ',
- 'Պ',
- 'Չ',
- 'Ո',
- 'Շ',
- 'Ն',
- 'Յ',
- 'Մ',
- 'Ճ',
- 'Ղ',
- 'Ձ',
- 'Հ',
- 'Կ',
- 'Ծ',
- 'Խ',
- 'Լ',
- 'Ի',
- 'Ժ',
- 'Թ',
- 'Ը',
- 'Է',
- 'Զ',
- 'Ե',
- 'Դ',
- 'Գ',
- 'Բ',
- 'Ա'
- ]
- };
- var HEBREW = {
- integers: [
- 10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20,
- 19, 18, 17, 16, 15, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
- ],
- values: [
- 'י׳',
- 'ט׳',
- 'ח׳',
- 'ז׳',
- 'ו׳',
- 'ה׳',
- 'ד׳',
- 'ג׳',
- 'ב׳',
- 'א׳',
- 'ת',
- 'ש',
- 'ר',
- 'ק',
- 'צ',
- 'פ',
- 'ע',
- 'ס',
- 'נ',
- 'מ',
- 'ל',
- 'כ',
- 'יט',
- 'יח',
- 'יז',
- 'טז',
- 'טו',
- 'י',
- 'ט',
- 'ח',
- 'ז',
- 'ו',
- 'ה',
- 'ד',
- 'ג',
- 'ב',
- 'א'
- ]
- };
- var GEORGIAN = {
- integers: [
- 10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90,
- 80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
- ],
- values: [
- 'ჵ',
- 'ჰ',
- 'ჯ',
- 'ჴ',
- 'ხ',
- 'ჭ',
- 'წ',
- 'ძ',
- 'ც',
- 'ჩ',
- 'შ',
- 'ყ',
- 'ღ',
- 'ქ',
- 'ფ',
- 'ჳ',
- 'ტ',
- 'ს',
- 'რ',
- 'ჟ',
- 'პ',
- 'ო',
- 'ჲ',
- 'ნ',
- 'მ',
- 'ლ',
- 'კ',
- 'ი',
- 'თ',
- 'ჱ',
- 'ზ',
- 'ვ',
- 'ე',
- 'დ',
- 'გ',
- 'ბ',
- 'ა'
- ]
- };
- var createAdditiveCounter = function (value, min, max, symbols, fallback, suffix) {
- if (value < min || value > max) {
- return createCounterText(value, fallback, suffix.length > 0);
- }
- return (symbols.integers.reduce(function (string, integer, index) {
- while (value >= integer) {
- value -= integer;
- string += symbols.values[index];
- }
- return string;
- }, '') + suffix);
- };
- var createCounterStyleWithSymbolResolver = function (value, codePointRangeLength, isNumeric, resolver) {
- var string = '';
- do {
- if (!isNumeric) {
- value--;
- }
- string = resolver(value) + string;
- value /= codePointRangeLength;
- } while (value * codePointRangeLength >= codePointRangeLength);
- return string;
- };
- var createCounterStyleFromRange = function (value, codePointRangeStart, codePointRangeEnd, isNumeric, suffix) {
- var codePointRangeLength = codePointRangeEnd - codePointRangeStart + 1;
- return ((value < 0 ? '-' : '') +
- (createCounterStyleWithSymbolResolver(Math.abs(value), codePointRangeLength, isNumeric, function (codePoint) {
- return fromCodePoint$1(Math.floor(codePoint % codePointRangeLength) + codePointRangeStart);
- }) +
- suffix));
- };
- var createCounterStyleFromSymbols = function (value, symbols, suffix) {
- if (suffix === void 0) { suffix = '. '; }
- var codePointRangeLength = symbols.length;
- return (createCounterStyleWithSymbolResolver(Math.abs(value), codePointRangeLength, false, function (codePoint) { return symbols[Math.floor(codePoint % codePointRangeLength)]; }) + suffix);
- };
- var CJK_ZEROS = 1 << 0;
- var CJK_TEN_COEFFICIENTS = 1 << 1;
- var CJK_TEN_HIGH_COEFFICIENTS = 1 << 2;
- var CJK_HUNDRED_COEFFICIENTS = 1 << 3;
- var createCJKCounter = function (value, numbers, multipliers, negativeSign, suffix, flags) {
- if (value < -9999 || value > 9999) {
- return createCounterText(value, 4 /* CJK_DECIMAL */, suffix.length > 0);
- }
- var tmp = Math.abs(value);
- var string = suffix;
- if (tmp === 0) {
- return numbers[0] + string;
- }
- for (var digit = 0; tmp > 0 && digit <= 4; digit++) {
- var coefficient = tmp % 10;
- if (coefficient === 0 && contains(flags, CJK_ZEROS) && string !== '') {
- string = numbers[coefficient] + string;
- }
- else if (coefficient > 1 ||
- (coefficient === 1 && digit === 0) ||
- (coefficient === 1 && digit === 1 && contains(flags, CJK_TEN_COEFFICIENTS)) ||
- (coefficient === 1 && digit === 1 && contains(flags, CJK_TEN_HIGH_COEFFICIENTS) && value > 100) ||
- (coefficient === 1 && digit > 1 && contains(flags, CJK_HUNDRED_COEFFICIENTS))) {
- string = numbers[coefficient] + (digit > 0 ? multipliers[digit - 1] : '') + string;
- }
- else if (coefficient === 1 && digit > 0) {
- string = multipliers[digit - 1] + string;
- }
- tmp = Math.floor(tmp / 10);
- }
- return (value < 0 ? negativeSign : '') + string;
- };
- var CHINESE_INFORMAL_MULTIPLIERS = '十百千萬';
- var CHINESE_FORMAL_MULTIPLIERS = '拾佰仟萬';
- var JAPANESE_NEGATIVE = 'マイナス';
- var KOREAN_NEGATIVE = '마이너스';
- var createCounterText = function (value, type, appendSuffix) {
- var defaultSuffix = appendSuffix ? '. ' : '';
- var cjkSuffix = appendSuffix ? '、' : '';
- var koreanSuffix = appendSuffix ? ', ' : '';
- var spaceSuffix = appendSuffix ? ' ' : '';
- switch (type) {
- case 0 /* DISC */:
- return '•' + spaceSuffix;
- case 1 /* CIRCLE */:
- return '◦' + spaceSuffix;
- case 2 /* SQUARE */:
- return '◾' + spaceSuffix;
- case 5 /* DECIMAL_LEADING_ZERO */:
- var string = createCounterStyleFromRange(value, 48, 57, true, defaultSuffix);
- return string.length < 4 ? "0" + string : string;
- case 4 /* CJK_DECIMAL */:
- return createCounterStyleFromSymbols(value, '〇一二三四五六七八九', cjkSuffix);
- case 6 /* LOWER_ROMAN */:
- return createAdditiveCounter(value, 1, 3999, ROMAN_UPPER, 3 /* DECIMAL */, defaultSuffix).toLowerCase();
- case 7 /* UPPER_ROMAN */:
- return createAdditiveCounter(value, 1, 3999, ROMAN_UPPER, 3 /* DECIMAL */, defaultSuffix);
- case 8 /* LOWER_GREEK */:
- return createCounterStyleFromRange(value, 945, 969, false, defaultSuffix);
- case 9 /* LOWER_ALPHA */:
- return createCounterStyleFromRange(value, 97, 122, false, defaultSuffix);
- case 10 /* UPPER_ALPHA */:
- return createCounterStyleFromRange(value, 65, 90, false, defaultSuffix);
- case 11 /* ARABIC_INDIC */:
- return createCounterStyleFromRange(value, 1632, 1641, true, defaultSuffix);
- case 12 /* ARMENIAN */:
- case 49 /* UPPER_ARMENIAN */:
- return createAdditiveCounter(value, 1, 9999, ARMENIAN, 3 /* DECIMAL */, defaultSuffix);
- case 35 /* LOWER_ARMENIAN */:
- return createAdditiveCounter(value, 1, 9999, ARMENIAN, 3 /* DECIMAL */, defaultSuffix).toLowerCase();
- case 13 /* BENGALI */:
- return createCounterStyleFromRange(value, 2534, 2543, true, defaultSuffix);
- case 14 /* CAMBODIAN */:
- case 30 /* KHMER */:
- return createCounterStyleFromRange(value, 6112, 6121, true, defaultSuffix);
- case 15 /* CJK_EARTHLY_BRANCH */:
- return createCounterStyleFromSymbols(value, '子丑寅卯辰巳午未申酉戌亥', cjkSuffix);
- case 16 /* CJK_HEAVENLY_STEM */:
- return createCounterStyleFromSymbols(value, '甲乙丙丁戊己庚辛壬癸', cjkSuffix);
- case 17 /* CJK_IDEOGRAPHIC */:
- case 48 /* TRAD_CHINESE_INFORMAL */:
- return createCJKCounter(value, '零一二三四五六七八九', CHINESE_INFORMAL_MULTIPLIERS, '負', cjkSuffix, CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
- case 47 /* TRAD_CHINESE_FORMAL */:
- return createCJKCounter(value, '零壹貳參肆伍陸柒捌玖', CHINESE_FORMAL_MULTIPLIERS, '負', cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
- case 42 /* SIMP_CHINESE_INFORMAL */:
- return createCJKCounter(value, '零一二三四五六七八九', CHINESE_INFORMAL_MULTIPLIERS, '负', cjkSuffix, CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
- case 41 /* SIMP_CHINESE_FORMAL */:
- return createCJKCounter(value, '零壹贰叁肆伍陆柒捌玖', CHINESE_FORMAL_MULTIPLIERS, '负', cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
- case 26 /* JAPANESE_INFORMAL */:
- return createCJKCounter(value, '〇一二三四五六七八九', '十百千万', JAPANESE_NEGATIVE, cjkSuffix, 0);
- case 25 /* JAPANESE_FORMAL */:
- return createCJKCounter(value, '零壱弐参四伍六七八九', '拾百千万', JAPANESE_NEGATIVE, cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS);
- case 31 /* KOREAN_HANGUL_FORMAL */:
- return createCJKCounter(value, '영일이삼사오육칠팔구', '십백천만', KOREAN_NEGATIVE, koreanSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS);
- case 33 /* KOREAN_HANJA_INFORMAL */:
- return createCJKCounter(value, '零一二三四五六七八九', '十百千萬', KOREAN_NEGATIVE, koreanSuffix, 0);
- case 32 /* KOREAN_HANJA_FORMAL */:
- return createCJKCounter(value, '零壹貳參四五六七八九', '拾百千', KOREAN_NEGATIVE, koreanSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS);
- case 18 /* DEVANAGARI */:
- return createCounterStyleFromRange(value, 0x966, 0x96f, true, defaultSuffix);
- case 20 /* GEORGIAN */:
- return createAdditiveCounter(value, 1, 19999, GEORGIAN, 3 /* DECIMAL */, defaultSuffix);
- case 21 /* GUJARATI */:
- return createCounterStyleFromRange(value, 0xae6, 0xaef, true, defaultSuffix);
- case 22 /* GURMUKHI */:
- return createCounterStyleFromRange(value, 0xa66, 0xa6f, true, defaultSuffix);
- case 22 /* HEBREW */:
- return createAdditiveCounter(value, 1, 10999, HEBREW, 3 /* DECIMAL */, defaultSuffix);
- case 23 /* HIRAGANA */:
- return createCounterStyleFromSymbols(value, 'あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわゐゑをん');
- case 24 /* HIRAGANA_IROHA */:
- return createCounterStyleFromSymbols(value, 'いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす');
- case 27 /* KANNADA */:
- return createCounterStyleFromRange(value, 0xce6, 0xcef, true, defaultSuffix);
- case 28 /* KATAKANA */:
- return createCounterStyleFromSymbols(value, 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン', cjkSuffix);
- case 29 /* KATAKANA_IROHA */:
- return createCounterStyleFromSymbols(value, 'イロハニホヘトチリヌルヲワカヨタレソツネナラムウヰノオクヤマケフコエテアサキユメミシヱヒモセス', cjkSuffix);
- case 34 /* LAO */:
- return createCounterStyleFromRange(value, 0xed0, 0xed9, true, defaultSuffix);
- case 37 /* MONGOLIAN */:
- return createCounterStyleFromRange(value, 0x1810, 0x1819, true, defaultSuffix);
- case 38 /* MYANMAR */:
- return createCounterStyleFromRange(value, 0x1040, 0x1049, true, defaultSuffix);
- case 39 /* ORIYA */:
- return createCounterStyleFromRange(value, 0xb66, 0xb6f, true, defaultSuffix);
- case 40 /* PERSIAN */:
- return createCounterStyleFromRange(value, 0x6f0, 0x6f9, true, defaultSuffix);
- case 43 /* TAMIL */:
- return createCounterStyleFromRange(value, 0xbe6, 0xbef, true, defaultSuffix);
- case 44 /* TELUGU */:
- return createCounterStyleFromRange(value, 0xc66, 0xc6f, true, defaultSuffix);
- case 45 /* THAI */:
- return createCounterStyleFromRange(value, 0xe50, 0xe59, true, defaultSuffix);
- case 46 /* TIBETAN */:
- return createCounterStyleFromRange(value, 0xf20, 0xf29, true, defaultSuffix);
- case 3 /* DECIMAL */:
- default:
- return createCounterStyleFromRange(value, 48, 57, true, defaultSuffix);
- }
- };
-
- var IGNORE_ATTRIBUTE = 'data-html2canvas-ignore';
- var DocumentCloner = /** @class */ (function () {
- function DocumentCloner(context, element, options) {
- this.context = context;
- this.options = options;
- this.scrolledElements = [];
- this.referenceElement = element;
- this.counters = new CounterState();
- this.quoteDepth = 0;
- if (!element.ownerDocument) {
- throw new Error('Cloned element does not have an owner document');
- }
- this.documentElement = this.cloneNode(element.ownerDocument.documentElement, false);
- }
- DocumentCloner.prototype.toIFrame = function (ownerDocument, windowSize) {
- var _this = this;
- var iframe = createIFrameContainer(ownerDocument, windowSize);
- if (!iframe.contentWindow) {
- return Promise.reject("Unable to find iframe window");
- }
- var scrollX = ownerDocument.defaultView.pageXOffset;
- var scrollY = ownerDocument.defaultView.pageYOffset;
- var cloneWindow = iframe.contentWindow;
- var documentClone = cloneWindow.document;
- /* Chrome doesn't detect relative background-images assigned in inline
-
-
-
-