diff --git a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Corel Draw X7 Crack Serial Number How to Unlock the Full Potential of Corel Draw X7 for Free.md b/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Corel Draw X7 Crack Serial Number How to Unlock the Full Potential of Corel Draw X7 for Free.md deleted file mode 100644 index 361d821cffe75855deb47464e9a7322cf160d2f0..0000000000000000000000000000000000000000 --- a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Corel Draw X7 Crack Serial Number How to Unlock the Full Potential of Corel Draw X7 for Free.md +++ /dev/null @@ -1,28 +0,0 @@ -
-# Corel Draw X7 Crack Serial Number Free Download - -

If you are looking for a powerful and versatile graphic design software, you might want to try Corel Draw X7. Corel Draw X7 is a professional-grade vector graphics editor that can help you create stunning logos, illustrations, flyers, brochures, posters, and more. Corel Draw X7 also comes with a suite of tools and features that can enhance your creativity and productivity, such as advanced typography, color management, layout, photo editing, web graphics, and animation.

- -

However, Corel Draw X7 is not a cheap software. The official price of Corel Draw X7 is $499 for the full version and $199 for the upgrade version. If you want to use Corel Draw X7 without paying for it, you might be tempted to download Corel Draw X7 crack serial number for free from the internet. Corel Draw X7 crack serial number is a code that can activate the software and unlock all its features without requiring a license key or registration.

-

corel draw x7 crack serial number free download


Download File ····· https://byltly.com/2uKA1D



- -## How to Download Corel Draw X7 Crack Serial Number for Free? - -

To download Corel Draw X7 crack serial number for free, you need to follow these steps:

- -
    -
  1. Go to the website that provides the link for the Corel Draw X7 crack serial number download. There are many websites that claim to offer the crack serial number, but some of them might be fake or malicious. To avoid getting scammed or infected by viruses, you should only use trusted and verified sources that have positive reviews and feedback from other users.
  2. -
  3. Click on the download button and wait for the file to be downloaded. The file size might vary depending on the website, but it should be around 500 MB. You might need to complete some surveys or offers before you can access the download link, but they are usually easy and quick to do.
  4. -
  5. Extract the file using a program like WinRAR or 7-Zip. You will get a folder that contains the crack serial number and the installation instructions. Make sure you have enough space on your hard drive to store the extracted files.
  6. -
  7. Follow the installation instructions carefully and enter the crack serial number when prompted. This will install Corel Draw X7 on your computer and activate it with the crack serial number.
  8. -
  9. Launch Corel Draw X7 by double-clicking on the icon on your desktop. You might need to run it as administrator or disable your antivirus software if you encounter any errors or problems.
  10. -
  11. Enjoy using Corel Draw X7 for free!
  12. -
- -## Is Corel Draw X7 Crack Serial Number Safe and Legal? - -

Downloading and using Corel Draw X7 crack serial number is not safe or legal. The crack serial number might contain viruses, malware, or spyware that can harm your computer or steal your personal information. The crack serial number might also cause errors, crashes, or performance issues that can ruin your graphic design projects. Moreover, downloading and using Corel Draw X7 crack serial number is illegal and violates the copyright laws and terms of service of Corel Corporation. You might face legal consequences or penalties if you are caught using the crack serial number.

- -

Therefore, we do not recommend downloading or using Corel Draw X7 crack serial number for free. The best way to use Corel Draw X7 is to buy a legitimate copy of the software from an authorized retailer or online platform. This way, you can support the developers and enjoy the software without any risks or troubles.

ddb901b051
-
-
\ No newline at end of file diff --git a/spaces/1gistliPinn/ChatGPT4/Descargar-Tecaudio-Bat-Para-Vice-City.md b/spaces/1gistliPinn/ChatGPT4/Descargar-Tecaudio-Bat-Para-Vice-City.md deleted file mode 100644 index 0016d516aa7832922d020e1e249da777059f0b15..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Descargar-Tecaudio-Bat-Para-Vice-City.md +++ /dev/null @@ -1,34 +0,0 @@ -Descargar Tecaudio Bat Para Vice City - - - -Click Here ::: [https://gohhs.com/2tvpaa](https://gohhs.com/2tvpaa) - - - - - - - - - -Here is a possible title and article with HTML formatting for the keyword "Descargar Tecaudio Bat Para Vice City": - -How to Fix Audio Problems in GTA Vice City with Tecaudio -GTA Vice City is one of the most popular games in the Grand Theft Auto series, but it also has some common audio issues that can affect the gameplay experience. Some players may encounter a message saying "no audio hardware" or have no sound at all in the game. Fortunately, there is a simple solution that involves using a file called Tecaudio. -Tecaudio is a MS-DOS batch file that can decode the audio files in GTA Vice City and make them compatible with your system. It is usually located in the GTA Vice City folder, but if you don't have it, you can download it from various websites. Here are the steps to use Tecaudio to fix audio problems in GTA Vice City: - -Download Tecaudio from a reliable source and save it in your GTA Vice City folder. -Right-click on Tecaudio and select "Edit". -Delete the line that says "startw wav2raw" and save the file. -Run Tecaudio as administrator and wait for it to process the audio files. -Launch GTA Vice City and enjoy the sound. - -If you still have audio issues after using Tecaudio, you may need to update your sound drivers or check your sound settings. You can also try other solutions such as changing the compatibility mode of GTA Vice City or installing patches or mods that improve the audio quality. However, Tecaudio is usually the easiest and most effective way to fix audio problems in GTA Vice City.Here are some more paragraphs for the article: - -GTA Vice City is set in the fictional city of Vice City, which is based on Miami in the 1980s. The game follows the story of Tommy Vercetti, a former mobster who is sent to Vice City by his boss to establish a criminal empire. The game features a large open world that can be explored by foot or by various vehicles, such as cars, motorcycles, boats, and helicopters. The game also has many side missions and activities that can be completed for money, weapons, or other rewards. -The game has received critical acclaim for its graphics, gameplay, music, and voice acting. It has also been praised for its depiction of the 1980s culture and atmosphere, as well as its satire of American society and politics. The game has sold over 17.5 million copies worldwide and is considered one of the best games of all time. It has also spawned several sequels and spin-offs, such as GTA San Andreas and GTA Vice City Stories. -However, the game has also faced some controversy and criticism for its violence, sexual content, drug use, and portrayal of certain groups and issues. The game has been banned or censored in some countries and has been the subject of several lawsuits and investigations. Some critics have also argued that the game glorifies crime and violence and has a negative influence on young players. Despite these controversies, the game remains popular and influential among fans and developers alike. dfd1c89656 - - - diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/Download ATH Swift Shader DX9 SM3 Build 3383x86 Rar TOP.md b/spaces/1gistliPinn/ChatGPT4/Examples/Download ATH Swift Shader DX9 SM3 Build 3383x86 Rar TOP.md deleted file mode 100644 index 365621188629824c5f7099e95f1be39ab1a8dd63..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/Download ATH Swift Shader DX9 SM3 Build 3383x86 Rar TOP.md +++ /dev/null @@ -1,6 +0,0 @@ -

Download ATH Swift Shader DX9 SM3 Build 3383x86 Rar


Download >> https://imgfil.com/2uxZCF



-
-Download ATH Swift Shader DX9 SM3 Build 3383(x86) rar · Freaky Loops Complextro and Dubstep 3 Massive Presets ( Lumfile - Ul ).rar 1fdad05405
-
-
-

diff --git a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Download GTA 5 APK OBB Data for Android (Highly Compressed 670MB).md b/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Download GTA 5 APK OBB Data for Android (Highly Compressed 670MB).md deleted file mode 100644 index 60237596f5b4afc4bdca76626b02d6742f7c248a..0000000000000000000000000000000000000000 --- a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Download GTA 5 APK OBB Data for Android (Highly Compressed 670MB).md +++ /dev/null @@ -1,88 +0,0 @@ -
-

GTA 5 Android APK + OBB Data Highly Compressed 670MB Download

-

Introduction

-

If you are a fan of action-adventure games, you must have heard of GTA 5, one of the most popular and successful games of all time. GTA 5 is the fifth installment in the Grand Theft Auto series, developed by Rockstar Games and released in 2013 for PlayStation 3, PlayStation 4, Xbox 360, Xbox One, and PC. But did you know that you can also play GTA 5 on your Android device?

-

gta 5 android apk + obb data highly compressed 670mb download


Download File ===== https://urlin.us/2uSYt5



-

What is GTA 5?

-

GTA 5 is a game that lets you experience the life of a criminal in the fictional city of Los Santos, based on Los Angeles. You can explore the city, engage in various activities, such as robbing banks, stealing cars, shooting enemies, and more. You can also follow the story mode, which involves three main characters: Michael, a retired bank robber; Franklin, a street hustler; and Trevor, a psychopathic drug dealer. You can switch between these characters at any time and see how their lives intertwine.

-

Why download GTA 5 for Android?

-

Downloading GTA 5 for Android has many advantages. First of all, you can enjoy the game on the go, without needing a console or a PC. You can play it anytime, anywhere, as long as you have an internet connection. Second, you can save a lot of storage space on your device, as the game is highly compressed to only 670MB. Third, you can experience the same features and quality as the original version, with no compromise on graphics or gameplay.

-

How to download and install GTA 5 for Android

-

Requirements

-

Before you download GTA 5 for Android, you need to make sure that your device meets the following requirements:

- -

Steps

-

Here are the steps to download and install GTA 5 for Android:

-

gta 5 mod apk + obb for android download 670mb compressed
-download gta 5 android apk + obb data highly compressed 2023
-gta 5 apk + obb android free download highly compressed 670mb
-how to install gta 5 android apk + obb data compressed 670mb
-gta 5 beta apk + obb for android highly compressed 670mb
-gta 5 android apk + obb data download link highly compressed 670mb
-gta 5 android apk + obb data highly compressed offline 670mb
-gta 5 apk + obb data for android highly compressed latest version 670mb
-gta 5 android apk + obb data highly compressed no verification 670mb
-gta 5 apk + obb data highly compressed zip file download for android 670mb
-gta 5 android apk + obb data highly compressed working 100% 670mb
-gta 5 mod menu apk + obb for android highly compressed download 670mb
-gta 5 android apk + obb data highly compressed free download mediafıre 670mb
-gta 5 real apk + obb for android highly compressed download link 670mb
-gta 5 apk + obb data for android highly compressed no password 670mb
-gta 5 android apk + obb data highly compressed google drive download link 670mb
-gta 5 lite apk + obb for android highly compressed download latest version 670mb
-gta 5 full game apk + obb for android highly compressed free download 670mb
-gta 5 online apk + obb for android highly compressed download without human verification 670mb
-gta 5 original apk + obb for android highly compressed download from rockstar games 670mb
-gta 5 premium edition apk + obb for android highly compressed free download link 670mb
-gta 5 redux apk + obb for android highly compressed download latest update 670mb
-gta 5 remastered apk + obb for android highly compressed free download modded version 670mb
-gta 5 rp apk + obb for android highly compressed download roleplay mod server link 670mb
-gta 5 ultra graphics apk + obb for android highly compressed free download realistic mod link 670mb

-
    -
  1. Click on this link to download the GTA 5 APK file.
  2. -
  3. After downloading the APK file, go to your device settings and enable the installation of unknown sources.
  4. -
  5. Install the APK file on your device.
  6. -
  7. Download the OBB data file from this link and extract it using any file manager app.
  8. -
  9. Copy the extracted folder named "com.rockstargames.gtav" to your device's internal storage in this path: Android/obb/.
  10. -
  11. Launch the game from your app drawer and enjoy!
  12. -
-

Features of GTA 5 for Android

-

Stunning graphics and gameplay

-

GTA 5 for Android boasts amazing graphics and gameplay that will make you feel like you are playing on a console or a PC. The game uses advanced technologies, such as dynamic lighting, shadows, reflections, textures, and animations, to create a realistic and immersive environment. The game also runs smoothly and seamlessly on most devices, thanks to its optimization and compression.

-

Open-world freedom and exploration

-

GTA 5 for Android offers you a huge open-world map that you can explore at your own pace. You can visit different locations, such as the city, the countryside, the desert, the mountains, and the ocean. You can also interact with various characters, objects, and vehicles that populate the world. You can drive, fly, swim, bike, or walk around and discover new places and secrets.

-

Multiple characters and missions

-

GTA 5 for Android lets you play as three different characters: Michael, Franklin, and Trevor. Each character has their own personality, skills, and story. You can switch between them at any time and see how their lives affect each other. You can also complete various missions that involve action, stealth, racing, shooting, and more. You can choose to follow the main storyline or do some side quests and activities for fun and rewards.

-

Online multiplayer mode

-

GTA 5 for Android also features an online multiplayer mode called GTA Online. In this mode, you can create your own character and join other players from around the world. You can cooperate or compete with them in various modes, such as deathmatches, races, heists, and more. You can also customize your character, weapons, vehicles, and properties. GTA Online is constantly updated with new content and events to keep you entertained.

-

Tips and tricks for GTA 5 for Android

-

Use the map and radar

-

GTA 5 for Android has a large map that can be overwhelming at first. To help you navigate and find your way around, you should use the map and radar on your screen. The map shows you the locations of missions, shops, safe houses, and more. The radar shows you the direction of your objective, enemies, allies, and police. You can also zoom in and out of the map and set waypoints to guide you.

-

Switch between characters wisely

-

GTA 5 for Android allows you to switch between three characters at any time. However, you should not do it randomly or too often. You should switch between characters when it is necessary or beneficial for your situation. For example, you can switch to Trevor when you need to use his special ability of rage mode, which makes him deal more damage and take less damage. You can also switch to another character when you are in trouble or want to avoid the police.

-

Customize your weapons and vehicles

-

GTA 5 for Android gives you a lot of options to customize your weapons and vehicles. You can buy new weapons or upgrade your existing ones with attachments, such as scopes, silencers, extended magazines, and more. You can also buy new vehicles or modify your current ones with enhancements, such as armor, turbo, spoilers, paint jobs, and more. Customizing your weapons and vehicles can improve their performance and appearance.

-

Save your game often

-

GTA 5 for Android is a game that can be unpredictable and challenging at times. You may encounter enemies, accidents, glitches, or bugs that can ruin your progress or experience. To avoid losing your data or having to repeat a mission or activity, you should save your game often. You can save your game manually by using your phone or automatically by entering a safe house or completing a mission.

-

Conclusion

-

GTA 5 for Android is a game that you should not miss if you love action-adventure games. It is a game that offers you a lot of features, such as stunning graphics and gameplay, open-world freedom and exploration, multiple characters and missions, online multiplayer mode, and more. You can download GTA 5 for Android easily by following the steps above. You can also enjoy GTA 5 for Android better by using the tips and tricks above. GTA 5 for Android is a game that will keep you entertained for hours and hours.

-

FAQs

-

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Download NFS Heat Studio App and Get Ready for NFS Heat Launch.md b/spaces/1phancelerku/anime-remove-background/Download NFS Heat Studio App and Get Ready for NFS Heat Launch.md deleted file mode 100644 index cffd27c7d89be37d54199c95688c9931de2dbe1f..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Download NFS Heat Studio App and Get Ready for NFS Heat Launch.md +++ /dev/null @@ -1,93 +0,0 @@ - -

NFS Heat Studio: How to Download and Customize Your Dream Cars

-

If you are a fan of racing games, you probably have heard of Need for Speed Heat, the latest installment in the popular franchise by Electronic Arts. But did you know that you can also enjoy the thrill of collecting and customizing the world's most amazing cars on your mobile device? That's right, with NFS Heat Studio, you can create your own unique designs and sync them with the game. In this article, we will tell you everything you need to know about NFS Heat Studio, including how to download it, what features it offers, and how to customize your cars like a pro.

-

nfs heat studio download


DOWNLOADhttps://jinyurl.com/2uNNUq



-

What is NFS Heat Studio?

-

A mobile app that lets you collect and customize cars for Need for Speed Heat

-

NFS Heat Studio is a mobile app that connects you directly to Need for Speed Heat, the upcoming racing game set in the neon-lit streets of Palm City. With NFS Heat Studio, you can expand your collection with weekly drops and complete challenges to unlock the most iconic cars on the streets today. You can also use the app to perfect your ride with a huge selection of body parts, wheels, exhausts, and more. You can even use the wrap editor to create truly custom designs. Once you have unlocked the car in Need for Speed Heat, simply press the studio button in the garage to import your creations. They'll then be ready and waiting for you to play with in NFS Heat when the game releases on November 5, 2019.

-

Features of NFS Heat Studio

-

Weekly car drops and challenges

-

Each week, a new container filled with the hottest cars will be yours to customize. Some are so special they'll need to be unlocked with progression points, earned by customizing your current rides, creating new wraps, or just spending time with your collection. You can also complete challenges to earn rewards and unlock more cars.

-

Wrap editor and color selector

-

This is your space to make each car your own. Go crazy with wild body-kits, wheels, exhausts, and more. Use the color selector to put your style on everything from the perfect finish to window tints. Even use the wrap editor to create custom designs. You can choose from a variety of decals, logos, patterns, shapes, and colors. You can also adjust the size, rotation, position, and opacity of each element.

-

Capture lab and AR mode

-

Once you are happy with your design, you can show it off to the world using the capture lab. You can set up still shots and videos in different locations and angles. You can also use the AR mode to instantly add your favorites anywhere - from your driveway to the highway. Then snap to share them on Facebook, Instagram, Twitter, or add them to your gallery.

-

Sync with Need for Speed Heat

-

The best part of NFS Heat Studio is that it connects you directly to Need for Speed Heat. All you need is an EA account (or create one) and you'll be able to sync your custom designs with the game. They'll then be ready and waiting for you to play with in NFS Heat when the game releases on November 5, 201

How to download NFS Heat Studio?

-

Available for free on iOS and Android devices

-

NFS Heat Studio is a free app that you can download on your iOS or Android device. You don't need to own Need for Speed Heat to use the app, but you will need an EA account to sync your designs with the game. You can create an EA account for free if you don't have one already.

-

QR code in-game or links to app stores

-

There are two ways to download NFS Heat Studio. One is to scan the QR code that appears in the garage of Need for Speed Heat. This will take you directly to the app store of your device. The other way is to use the links below to access the app store of your choice.

-

Download NFS Heat Studio for iOS

-

nfs heat studio download for pc
-nfs heat studio download apk
-nfs heat studio download ios
-nfs heat studio download android
-nfs heat studio download free
-nfs heat studio download windows 10
-nfs heat studio download mac
-nfs heat studio download link
-nfs heat studio download size
-nfs heat studio download error
-nfs heat studio app download
-nfs heat studio mobile download
-nfs heat studio qr code download
-nfs heat studio mod apk download
-nfs heat studio hack apk download
-nfs heat studio custom cars download
-nfs heat studio game download
-nfs heat studio online download
-nfs heat studio offline download
-nfs heat studio latest version download
-how to download nfs heat studio on pc
-how to download nfs heat studio on ios
-how to download nfs heat studio on android
-how to download nfs heat studio on mac
-how to download nfs heat studio app
-how to fix nfs heat studio download error
-how to scan qr code for nfs heat studio download
-how to get nfs heat studio mod apk download
-how to use nfs heat studio custom cars download
-how to update nfs heat studio latest version download
-need for speed heat studio pc download
-need for speed heat studio apk download
-need for speed heat studio ios download
-need for speed heat studio android download
-need for speed heat studio free download
-need for speed heat studio windows 10 download
-need for speed heat studio mac download
-need for speed heat studio link download
-need for speed heat studio size download
-need for speed heat studio error download

-

Download NFS Heat Studio for Android

-

Supported languages and devices

-

NFS Heat Studio supports the following languages: English, French, Italian, German, Spanish, Russian, Portuguese, Polish, Japanese, Korean, Traditional Chinese, and Simplified Chinese. The app requires iOS 11.0 or later and is compatible with iPhone, iPad, and iPod touch. The app requires Android 8.0 or later and is compatible with most Android devices.

-

How to customize your cars in NFS Heat Studio?

-

Access the Cars tab and the Workshop

-

To start customizing your cars, you need to access the Cars tab in the app. Here you will see your current collection of cars and the containers that contain new cars. You can tap on any car to enter the Workshop, where you can modify its appearance and performance.

-

Choose from a variety of body parts, wheels, exhausts, and more

-

In the Workshop, you can choose from a variety of body parts, wheels, exhausts, and more to make your car stand out. You can swipe left or right to switch between different categories of customization options. You can also tap on the icons at the bottom of the screen to access the color selector, the wrap editor, or the capture lab.

-

Use progression points to unlock special cars

-

Some cars are so special that they require progression points to unlock. You can earn progression points by customizing your current cars, creating new wraps, or just spending time with your collection. You can also complete challenges to earn more points and rewards. Once you have enough points, you can tap on the lock icon on the car to unlock it.

-

Share your designs on social media or in your Gallery

-

Once you are happy with your design, you can share it with the world using the capture lab. You can set up still shots and videos in different locations and angles. You can also use the AR mode to instantly add your favorites anywhere - from your driveway to the highway. Then snap to share them on Facebook, Instagram, Twitter, or add them to your gallery.

-

Conclusion

-

NFS Heat Studio is a fun and creative way to enhance your Need for Speed Heat experience

-

NFS Heat Studio is a mobile app that lets you collect and customize cars for Need for Speed Heat. You can enjoy weekly car drops and challenges, use the wrap editor and color selector to create custom designs, use the capture lab and AR mode to show off your creations, and sync them with Need for Speed Heat when the game releases on November 5, 2019.

-

Download the app today and start building your dream garage

-

If you are ready to unleash your creativity and passion for cars, download NFS Heat Studio today and start building your dream garage. You can download the app for free on iOS or Android devices using the links below or by scanning the QR code in-game. Have fun and see you on the streets of Palm City!

-

Download NFS Heat Studio for iOS

-

Download NFS Heat Studio for Android

-

Frequently Asked Questions

-

Do I need Need for Speed Heat to use NFS Heat Studio?

-

No, you don't need Need for Speed Heat to use NFS Heat Studio. However, you will need an EA account to sync your designs with the game when it releases on November 5, 2019.

-

How do I sync my designs with Need for Speed Heat?

-

To sync your designs with Need for Speed Heat, you need to have an EA account and be logged in on both NFS Heat Studio and the game. Once you have unlocked the car in Need for Speed Heat, simply press the studio button in the garage to import your creations. They'll then be ready and waiting for you to play with in NFS Heat.

-

How do I use the wrap editor and color selector?

-

To use the wrap editor and color selector, you need to enter the Workshop and tap on the icons at the bottom of the screen. You can choose from a variety of decals, logos, patterns, shapes, and colors. You can also adjust the size, rotation, position, and opacity of each element. You can use the color selector to put your style on everything from the perfect finish to window tints.

-

How do I use the capture lab and AR mode?

-

To use the capture lab and AR mode, you need to enter the Workshop and tap on the icons at the bottom of the screen. You can set up still shots and videos in different locations and angles. You can also use the AR mode to instantly add your favorites anywhere - from your driveway to the highway. Then snap to share them on Facebook, Instagram, Twitter, or add them to your gallery.

-

How do I complete challenges and earn progression points?

-

To complete challenges and earn progression points, you need to access the Cars tab in the app. Here you will see your current collection of cars and the containers that contain new cars. You can tap on any car to see its challenges and rewards. You can also earn progression points by customizing your current cars, creating new wraps, or just spending time with your collection. You can use progression points to unlock special cars.

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Enjoy These Offline RPG Games APK on Your Android Device [No Internet Required].md b/spaces/1phancelerku/anime-remove-background/Enjoy These Offline RPG Games APK on Your Android Device [No Internet Required].md deleted file mode 100644 index 03ae9eea5f7a48df4e8cd07a823875116d5fb66f..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Enjoy These Offline RPG Games APK on Your Android Device [No Internet Required].md +++ /dev/null @@ -1,148 +0,0 @@ - -

Game Offline RPG APK: What are they and why you should play them

-

If you are a fan of role-playing games (RPGs), you might have noticed that most of them require an internet connection to play. Whether it is to access online features, download additional content, or watch ads, online RPGs can be frustrating for gamers who have limited or no access to WiFi or cellular data.

-

Fortunately, there is a solution for this problem: game offline RPG APKs. These are games that you can download and install on your Android device as APK files, which are application packages that contain all the necessary data and code to run an app. Game offline RPG APKs do not require an internet connection to play, so you can enjoy them anytime and anywhere.

-

game offline rpg apk


DOWNLOAD ○○○ https://jinyurl.com/2uNLGC



-

But what are the benefits of playing game offline RPG APKs? And what are some of the best game offline RPG APKs for Android? In this article, we will answer these questions and show you how to download and install game offline RPG APKs on your device.

-

Game offline RPG APKs offer a variety of benefits for gamers who want to enjoy immersive role-playing games without internet connection or data usage.

-

The benefits of game offline RPG APKs

-

No internet connection required

-

One of the main advantages of game offline RPG APKs is that they do not require an internet connection to play. This means that you can play them whenever and wherever you want, without worrying about WiFi or cellular data availability or costs.

-

This is especially useful for gamers who live in areas with poor internet coverage, travel frequently, or have limited data plans. You can also save battery life by playing game offline RPG APKs, as they do not consume as much power as online games.

-

No ads or in-app purchases

-

Another benefit of game offline RPG APKs is that they are free from annoying ads or costly in-app purchases that can ruin the gaming experience. Unlike online games that rely on ads or microtransactions to generate revenue, game offline RPG APKs are usually paid or free apps that do not have any hidden fees or charges. You can enjoy the full game without being interrupted by ads or tempted by in-app purchases that can affect the game balance or progression.

-

No updates or downloads

-

A third benefit of game offline RPG APKs is that they do not require constant updates or additional downloads that can take up storage space or consume data. Once you download and install a game offline RPG APK, you can play it right away and do not have to worry about updating it to the latest version or downloading extra content that might not be compatible with your device.

-

game offline rpg apk mod
-game offline rpg apk no data
-game offline rpg apk free download
-game offline rpg apk terbaik
-game offline rpg apk 2023
-game offline rpg apk low mb
-game offline rpg apk hack
-game offline rpg apk android
-game offline rpg apk unlimited money
-game offline rpg apk high graphics
-game offline rpg apk adventure
-game offline rpg apk full version
-game offline rpg apk action
-game offline rpg apk strategy
-game offline rpg apk fantasy
-game offline rpg apk horror
-game offline rpg apk pixel art
-game offline rpg apk open world
-game offline rpg apk turn based
-game offline rpg apk anime
-game offline rpg apk medieval
-game offline rpg apk sci fi
-game offline rpg apk survival
-game offline rpg apk dungeon crawler
-game offline rpg apk dragon
-game offline rpg apk zombie
-game offline rpg apk vampire
-game offline rpg apk knight
-game offline rpg apk ninja
-game offline rpg apk samurai
-game offline rpg apk pirate
-game offline rpg apk superhero
-game offline rpg apk monster hunter
-game offline rpg apk diablo like
-game offline rpg apk final fantasy like
-game offline rpg apk star wars like
-game offline rpg apk baldur's gate like
-game offline rpg apk evoland like
-game offline rpg apk eternium like
-game offline rpg apk soul knight like

-

This also means that you can play game offline RPG APKs even if the developer stops supporting them or removes them from the app store. You do not have to depend on the availability or quality of the online service or server to enjoy your game.

-

The best game offline RPG APKs for Android

-

Now that you know the benefits of game offline RPG APKs, you might be wondering what are some of the best game offline RPG APKs for Android. There are many game offline RPG APKs available for download, but we have selected five of the most popular and highly rated ones for you to try out. Here they are:

-

Star Wars: Knights of the Old Republic

-

If you are a fan of Star Wars, you will love this game offline RPG APK. Star Wars: Knights of the Old Republic is a classic RPG that lets you create your own character and choose your path in the galaxy far, far away. You can join the Jedi or the Sith, fight with lightsabers or blasters, and interact with iconic characters like Darth Vader, Yoda, and Han Solo.

-

The game has an epic story, rich graphics, and immersive sound effects. It also has a lot of customization options, such as different classes, skills, feats, and items. You can play this game offline RPG APK for hours and hours without getting bored.

-

Star Wars: Knights of the Old Republic has a rating of 4.5 out of 5 stars on Google Play and costs $9.99 to download. It requires Android 4.1 or higher and 2.4 GB of storage space.

-

Baldur's Gate

-

If you are a fan of Dungeons & Dragons, you will love this game offline RPG APK. Baldur's Gate is a legendary RPG that is based on the famous tabletop game and set in the Forgotten Realms fantasy world. You can create your own hero and explore a vast and detailed world full of adventure, magic, and danger.

-

The game has a complex and engaging story, with multiple endings and choices that matter. It also has a lot of gameplay features, such as turn-based combat, party management, dialogue options, and quests. You can play this game offline RPG APK solo or with friends via local multiplayer.

-

Baldur's Gate has a rating of 4.4 out of 5 stars on Google Play and costs $9.99 to download. It requires Android 3.0 or higher and 2.6 GB of storage space.

Dungeon Quest

-

If you are a fan of hack and slash games, you will love this game offline RPG APK. Dungeon Quest is a fast-paced RPG that lets you loot and fight your way through endless dungeons full of monsters, traps, and bosses. You can choose from four different classes: Warrior, Rogue, Mage, or Shaman, and customize your character with various skills, weapons, and armor.

-

The game has a simple and addictive gameplay, with randomly generated levels and loot. It also has a lot of challenge modes, such as Arena, Survival, and Daily Dungeon. You can play this game offline RPG APK alone or with friends via local co-op.

-

Dungeon Quest has a rating of 4.5 out of 5 stars on Google Play and is free to download. It requires Android 4.0 or higher and 46 MB of storage space.

-

Eternium

-

If you are a fan of Diablo, you will love this game offline RPG APK. Eternium is a stylish RPG that lets you battle against evil forces in a dark fantasy world. You can choose from three different classes: Mage, Warrior, or Bounty Hunter, and use gestures to cast spells or attack enemies.

-

The game has a rich and immersive story, with over 90 levels and 10 worlds to explore. It also has a lot of gameplay features, such as crafting, fishing, mining, companions, and pets. You can play this game offline RPG APK without any restrictions or penalties.

-

Eternium has a rating of 4.8 out of 5 stars on Google Play and is free to download. It requires Android 4.0 or higher and 116 MB of storage space.

-

Soul Knight

-

If you are a fan of roguelike games, you will love this game offline RPG APK. Soul Knight is a fun and quirky RPG that lets you shoot your way through randomly generated dungeons full of aliens, robots, and magic. You can choose from over 170 different characters, each with their own unique abilities and weapons.

-

The game has a simple and smooth gameplay, with easy controls and colorful graphics. It also has a lot of content to unlock, such as new characters, weapons, pets, and items. You can play this game offline RPG APK solo or with friends via local multiplayer.

-

Soul Knight has a rating of 4.6 out of 5 stars on Google Play and is free to download. It requires Android 4.1 or higher and 100 MB of storage space.

-

How to download and install game offline RPG APKs

-

Find a reliable source

-

Before you can download and install game offline RPG APKs on your device, you need to find a reliable source that offers them for download. There are many websites and app stores that claim to provide game offline RPG APKs, but not all of them are trustworthy or safe.

-

Some sources might offer fake or modified game offline RPG APKs that contain malware or viruses that can harm your device or steal your personal information. Some sources might also offer outdated or incompatible game offline RPG APKs that do not work properly on your device.

-

To avoid these risks, you should only download game offline RPG APKs from reputable sources that have positive reviews and ratings from other users. You can also check the authenticity and quality of the game offline RPG APKs by looking at their file size, permissions, developer name, and version number.

-

Download the APK file

-

Once you have found a reliable source for the game offline RPG APK that you want to play, you need to download the APK file to your device. The APK file is the application package that contains all the data and code needed to run the app on your device.

-

To download the APK file, you need to click on the download link or button provided by the source and wait for the file to be downloaded to your device. Depending on the size of the file and the speed of your internet connection, this might take a few minutes or longer.

-

After the file is downloaded, you need to check its size and permissions before installing it on your device. The size of the file should match the size indicated by the source. The permissions of the file should match the functions of the app. If the file size or permissions are different from what you expected, you should delete the file and find another source.

-

Enable unknown sources

-

By default, Android devices do not allow users to install apps from unknown sources that are not verified by Google Play. This is a security measure that prevents users from installing malicious or harmful apps on their devices.

-

However, if you want to install game offline RPG APKs on your device, you need to enable the option to install apps from unknown sources in your device settings. This will allow you to install game offline RPG APKs that are not available on Google Play or that are not compatible with your device.

-

To enable unknown sources, you need to follow these steps:

-
    -
  1. Go to your device settings and tap on Security or Privacy.
  2. -
  3. Find the option that says Unknown sources or Install unknown apps and toggle it on.
  4. -
  5. A warning message will appear, telling you the risks of installing apps from unknown sources. Tap on OK or Allow to confirm.
  6. -
-

Once you have enabled unknown sources, you can proceed to install the game offline RPG APK on your device.

-

Install the APK file

-

After you have downloaded and checked the game offline RPG APK file and enabled unknown sources, you can install the game offline RPG APK on your device. To install the game offline RPG APK, you need to follow these steps:

-
    -
  1. Locate the game offline RPG APK file on your device using a file manager app or your device's Downloads folder.
  2. -
  3. Tap on the game offline RPG APK file and a prompt will appear, asking you if you want to install the app.
  4. -
  5. Tap on Install and wait for the installation process to complete.
  6. -
  7. Once the installation is done, you can tap on Open to launch the game or Done to exit the prompt.
  8. -
-

Congratulations! You have successfully installed a game offline RPG APK on your device. You can now enjoy playing your game offline RPG without any internet connection or data usage.

-

Conclusion

-

Game offline RPG APKs are games that you can download and install on your Android device as APK files, which are application packages that contain all the data and code to run an app. Game offline RPG APKs do not require an internet connection to play, so you can enjoy them anytime and anywhere.

-

Game offline RPG APKs offer a variety of benefits for gamers who want to enjoy immersive role-playing games without internet connection or data usage. Some of these benefits are:

- -

Some of the best game offline RPG APKs for Android are:

- -

To download and install game offline RPG APKs on your device, you need to find a reliable source that offers them for download, download the APK file to your device and check its size and permissions, enable unknown sources in your device settings, and install the APK file on your device.

-

If you are looking for some great game offline RPG APKs to play on your Android device, we hope this article has helped you find some of them. Why not give them a try and see for yourself how much fun they are? You might be surprised by how much you enjoy playing game offline RPG APKs without any internet connection or data usage.

-

Frequently Asked Questions

-

What is an APK file?

-

An APK file is an application package that contains all the data and code needed to run an app on an Android device. It is similar to an EXE file for Windows or a DMG file for Mac. You can download and install APK files from various sources, such as websites or app stores, as long as they are compatible with your device and trustworthy.

-

What is an RPG?

-

An RPG is a role-playing game, which is a type of video game that lets you create your own character and immerse yourself in a fictional world where you can interact with other characters, complete quests, and fight enemies. RPGs are usually divided into two categories: online RPGs, which require an internet connection to play and offer online features, such as multiplayer, chat, or leaderboards; and offline RPGs, which do not require an internet connection to play and offer offline features, such as single-player, customization, or replayability.

-

What are some of the disadvantages of game offline RPG APKs?

-

Game offline RPG APKs are not perfect and have some disadvantages that you should be aware of before playing them. Some of these disadvantages are:

- -

To avoid these disadvantages, you should only download game offline RPG APKs from reliable sources, check their file size and permissions before installing them, and update your device and operating system regularly.

-

How can I delete game offline RPG APKs from my device?

-

If you want to delete game offline RPG APKs from your device, you can follow these steps:

-
    -
  1. Go to your device settings and tap on Apps or Applications.
  2. -
  3. Find the game offline RPG APK that you want to delete and tap on it.
  4. -
  5. Tap on Uninstall and confirm your choice.
  6. -
  7. The game offline RPG APK will be deleted from your device and its storage space will be freed up.
  8. -
-

Can I play game offline RPG APKs on other devices?

-

Yes, you can play game offline RPG APKs on other devices as long as they are Android devices that support the game offline RPG APK that you want to play. You can transfer the game offline RPG APK file from one device to another using a USB cable, Bluetooth, Wi-Fi, or cloud storage. You can also download the game offline RPG APK file again from the same source that you used before. However, you might lose your game progress or data if you switch devices or delete the game offline RPG APK from your device.

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/1toTree/lora_test/ppdiffusers/schedulers/scheduling_euler_ancestral_discrete.py b/spaces/1toTree/lora_test/ppdiffusers/schedulers/scheduling_euler_ancestral_discrete.py deleted file mode 100644 index 99e5d13abc40762a11171c4e7e1ee6d18f8ea7ac..0000000000000000000000000000000000000000 --- a/spaces/1toTree/lora_test/ppdiffusers/schedulers/scheduling_euler_ancestral_discrete.py +++ /dev/null @@ -1,233 +0,0 @@ -# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. -# Copyright 2022 Katherine Crowson and The HuggingFace Team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from dataclasses import dataclass -from typing import List, Optional, Tuple, Union - -import numpy as np -import paddle - -from ..configuration_utils import ConfigMixin, register_to_config -from ..utils import _COMPATIBLE_STABLE_DIFFUSION_SCHEDULERS, BaseOutput, logging -from .scheduling_utils import SchedulerMixin - -logger = logging.get_logger(__name__) # pylint: disable=invalid-name - - -@dataclass -# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerAncestralDiscrete -class EulerAncestralDiscreteSchedulerOutput(BaseOutput): - """ - Output class for the scheduler's step function output. - - Args: - prev_sample (`paddle.Tensor` of shape `(batch_size, num_channels, height, width)` for images): - Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the - denoising loop. - pred_original_sample (`paddle.Tensor` of shape `(batch_size, num_channels, height, width)` for images): - The predicted denoised sample (x_{0}) based on the model output from the current timestep. - `pred_original_sample` can be used to preview progress or for guidance. - """ - - prev_sample: paddle.Tensor - pred_original_sample: Optional[paddle.Tensor] = None - - -class EulerAncestralDiscreteScheduler(SchedulerMixin, ConfigMixin): - """ - Ancestral sampling with Euler method steps. Based on the original k-diffusion implementation by Katherine Crowson: - https://github.com/crowsonkb/k-diffusion/blob/481677d114f6ea445aa009cf5bd7a9cdee909e47/k_diffusion/sampling.py#L72 - - [`~ConfigMixin`] takes care of storing all config attributes that are passed in the scheduler's `__init__` - function, such as `num_train_timesteps`. They can be accessed via `scheduler.config.num_train_timesteps`. - [`SchedulerMixin`] provides general loading and saving functionality via the [`SchedulerMixin.save_pretrained`] and - [`~SchedulerMixin.from_pretrained`] functions. - - Args: - num_train_timesteps (`int`): number of diffusion steps used to train the model. - beta_start (`float`): the starting `beta` value of inference. - beta_end (`float`): the final `beta` value. - beta_schedule (`str`): - the beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from - `linear` or `scaled_linear`. - trained_betas (`np.ndarray`, optional): - option to pass an array of betas directly to the constructor to bypass `beta_start`, `beta_end` etc. - prediction_type (`str`, default `epsilon`, optional): - prediction type of the scheduler function, one of `epsilon` (predicting the noise of the diffusion - process), `sample` (directly predicting the noisy sample`) or `v_prediction` (see section 2.4 - https://imagen.research.google/video/paper.pdf) - """ - - _compatibles = _COMPATIBLE_STABLE_DIFFUSION_SCHEDULERS.copy() - order = 1 - - @register_to_config - def __init__( - self, - num_train_timesteps: int = 1000, - beta_start: float = 0.0001, - beta_end: float = 0.02, - beta_schedule: str = "linear", - trained_betas: Optional[Union[np.ndarray, List[float]]] = None, - prediction_type: str = "epsilon", - ): - if trained_betas is not None: - self.betas = paddle.to_tensor(trained_betas, dtype="float32") - elif beta_schedule == "linear": - self.betas = paddle.linspace(beta_start, beta_end, num_train_timesteps, dtype="float32") - elif beta_schedule == "scaled_linear": - # this schedule is very specific to the latent diffusion model. - self.betas = paddle.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype="float32") ** 2 - else: - raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}") - - self.alphas = 1.0 - self.betas - self.alphas_cumprod = paddle.cumprod(self.alphas, 0) - - sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5) - sigmas = np.concatenate([sigmas[::-1], [0.0]]).astype(np.float32) - self.sigmas = paddle.to_tensor(sigmas) - - # standard deviation of the initial noise distribution - self.init_noise_sigma = self.sigmas.max() - - # setable values - self.num_inference_steps = None - timesteps = np.linspace(0, num_train_timesteps - 1, num_train_timesteps, dtype=float)[::-1].copy() - self.timesteps = paddle.to_tensor(timesteps, dtype="float32") - self.is_scale_input_called = False - - def scale_model_input(self, sample: paddle.Tensor, timestep: Union[float, paddle.Tensor]) -> paddle.Tensor: - """ - Scales the denoising model input by `(sigma**2 + 1) ** 0.5` to match the Euler algorithm. - - Args: - sample (`paddle.Tensor`): input sample - timestep (`float` or `paddle.Tensor`): the current timestep in the diffusion chain - - Returns: - `paddle.Tensor`: scaled input sample - """ - step_index = (self.timesteps == timestep).nonzero().item() - sigma = self.sigmas[step_index] - sample = sample / ((sigma**2 + 1) ** 0.5) - self.is_scale_input_called = True - return sample - - def set_timesteps(self, num_inference_steps: int): - """ - Sets the timesteps used for the diffusion chain. Supporting function to be run before inference. - - Args: - num_inference_steps (`int`): - the number of diffusion steps used when generating samples with a pre-trained model. - """ - self.num_inference_steps = num_inference_steps - - timesteps = np.linspace(0, self.config.num_train_timesteps - 1, num_inference_steps, dtype=float)[::-1].copy() - sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5) - sigmas = np.interp(timesteps, np.arange(0, len(sigmas)), sigmas) - sigmas = np.concatenate([sigmas, [0.0]]).astype(np.float32) - self.sigmas = paddle.to_tensor(sigmas) - self.timesteps = paddle.to_tensor(timesteps, dtype="float32") - - def step( - self, - model_output: paddle.Tensor, - timestep: Union[float, paddle.Tensor], - sample: paddle.Tensor, - generator: Optional[Union[paddle.Generator, List[paddle.Generator]]] = None, - return_dict: bool = True, - ) -> Union[EulerAncestralDiscreteSchedulerOutput, Tuple]: - """ - Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion - process from the learned model outputs (most often the predicted noise). - - Args: - model_output (`paddle.Tensor`): direct output from learned diffusion model. - timestep (`float`): current timestep in the diffusion chain. - sample (`paddle.Tensor`): - current instance of sample being created by diffusion process. - generator (`paddle.Generator`, optional): Random number generator. - return_dict (`bool`): option for returning tuple rather than EulerAncestralDiscreteSchedulerOutput class - - Returns: - [`~schedulers.scheduling_utils.EulerAncestralDiscreteSchedulerOutput`] or `tuple`: - [`~schedulers.scheduling_utils.EulerAncestralDiscreteSchedulerOutput`] if `return_dict` is True, otherwise - a `tuple`. When returning a tuple, the first element is the sample tensor. - - """ - if not self.is_scale_input_called: - logger.warning( - "The `scale_model_input` function should be called before `step` to ensure correct denoising. " - "See `StableDiffusionPipeline` for a usage example." - ) - step_index = (self.timesteps == timestep).nonzero().item() - sigma = self.sigmas[step_index] - - # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise - if self.config.prediction_type == "epsilon": - pred_original_sample = sample - sigma * model_output - elif self.config.prediction_type == "v_prediction": - # * c_out + input * c_skip - pred_original_sample = model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1)) - else: - raise ValueError( - f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`" - ) - sigma_from = self.sigmas[step_index] - sigma_to = self.sigmas[step_index + 1] - sigma_up = (sigma_to**2 * (sigma_from**2 - sigma_to**2) / sigma_from**2) ** 0.5 - sigma_down = (sigma_to**2 - sigma_up**2) ** 0.5 - - # 2. Convert to an ODE derivative - derivative = (sample - pred_original_sample) / sigma - - dt = sigma_down - sigma - - prev_sample = sample + derivative * dt - - noise = paddle.randn(model_output.shape, dtype=model_output.dtype, generator=generator) - - prev_sample = prev_sample + noise * sigma_up - - if not return_dict: - return (prev_sample,) - - return EulerAncestralDiscreteSchedulerOutput( - prev_sample=prev_sample, pred_original_sample=pred_original_sample - ) - - def add_noise( - self, - original_samples: paddle.Tensor, - noise: paddle.Tensor, - timesteps: paddle.Tensor, - ) -> paddle.Tensor: - # Make sure sigmas and timesteps have the same dtype as original_samples - self.sigmas = self.sigmas.cast(original_samples.dtype) - - schedule_timesteps = self.timesteps - step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps] - - sigma = self.sigmas[step_indices].flatten() - while len(sigma.shape) < len(original_samples.shape): - sigma = sigma.unsqueeze(-1) - - noisy_samples = original_samples + noise * sigma - return noisy_samples - - def __len__(self): - return self.config.num_train_timesteps diff --git a/spaces/7hao/bingo/src/pages/api/image.ts b/spaces/7hao/bingo/src/pages/api/image.ts deleted file mode 100644 index 4b894bea86050c0f3888cc56f60c0cb7f8b57cfc..0000000000000000000000000000000000000000 --- a/spaces/7hao/bingo/src/pages/api/image.ts +++ /dev/null @@ -1,40 +0,0 @@ -'use server' - -import { NextApiRequest, NextApiResponse } from 'next' -import { debug } from '@/lib/isomorphic' -import { createHeaders } from '@/lib/utils' -import { createImage } from '@/lib/bots/bing/utils' - -export default async function handler(req: NextApiRequest, res: NextApiResponse) { - const { prompt, id } = req.query - if (!prompt) { - return res.json({ - result: { - value: 'Image', - message: 'No Prompt' - } - }) - } - try { - const headers = createHeaders(req.cookies, { - IMAGE_BING_COOKIE: process.env.IMAGE_BING_COOKIE - }) - - debug('headers', headers) - const response = await createImage(String(prompt), String(id), { - ...headers, - 'x-ms-useragent': 'azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/Win32', - }) - res.writeHead(200, { - 'Content-Type': 'text/plain; charset=UTF-8', - }) - return res.end(response) - } catch (e) { - return res.json({ - result: { - value: 'Error', - message: `${e}` - } - }) - } -} diff --git a/spaces/AIFILMS/generate_human_motion/VQ-Trans/render_final.py b/spaces/AIFILMS/generate_human_motion/VQ-Trans/render_final.py deleted file mode 100644 index 41b3bfdb2e6bff74aeaceb8f1a7ebac9dc1acaba..0000000000000000000000000000000000000000 --- a/spaces/AIFILMS/generate_human_motion/VQ-Trans/render_final.py +++ /dev/null @@ -1,194 +0,0 @@ -from models.rotation2xyz import Rotation2xyz -import numpy as np -from trimesh import Trimesh -import os -os.environ['PYOPENGL_PLATFORM'] = "osmesa" - -import torch -from visualize.simplify_loc2rot import joints2smpl -import pyrender -import matplotlib.pyplot as plt - -import io -import imageio -from shapely import geometry -import trimesh -from pyrender.constants import RenderFlags -import math -# import ffmpeg -from PIL import Image - -class WeakPerspectiveCamera(pyrender.Camera): - def __init__(self, - scale, - translation, - znear=pyrender.camera.DEFAULT_Z_NEAR, - zfar=None, - name=None): - super(WeakPerspectiveCamera, self).__init__( - znear=znear, - zfar=zfar, - name=name, - ) - self.scale = scale - self.translation = translation - - def get_projection_matrix(self, width=None, height=None): - P = np.eye(4) - P[0, 0] = self.scale[0] - P[1, 1] = self.scale[1] - P[0, 3] = self.translation[0] * self.scale[0] - P[1, 3] = -self.translation[1] * self.scale[1] - P[2, 2] = -1 - return P - -def render(motions, outdir='test_vis', device_id=0, name=None, pred=True): - frames, njoints, nfeats = motions.shape - MINS = motions.min(axis=0).min(axis=0) - MAXS = motions.max(axis=0).max(axis=0) - - height_offset = MINS[1] - motions[:, :, 1] -= height_offset - trajec = motions[:, 0, [0, 2]] - - j2s = joints2smpl(num_frames=frames, device_id=0, cuda=True) - rot2xyz = Rotation2xyz(device=torch.device("cuda:0")) - faces = rot2xyz.smpl_model.faces - - if (not os.path.exists(outdir + name+'_pred.pt') and pred) or (not os.path.exists(outdir + name+'_gt.pt') and not pred): - print(f'Running SMPLify, it may take a few minutes.') - motion_tensor, opt_dict = j2s.joint2smpl(motions) # [nframes, njoints, 3] - - vertices = rot2xyz(torch.tensor(motion_tensor).clone(), mask=None, - pose_rep='rot6d', translation=True, glob=True, - jointstype='vertices', - vertstrans=True) - - if pred: - torch.save(vertices, outdir + name+'_pred.pt') - else: - torch.save(vertices, outdir + name+'_gt.pt') - else: - if pred: - vertices = torch.load(outdir + name+'_pred.pt') - else: - vertices = torch.load(outdir + name+'_gt.pt') - frames = vertices.shape[3] # shape: 1, nb_frames, 3, nb_joints - print (vertices.shape) - MINS = torch.min(torch.min(vertices[0], axis=0)[0], axis=1)[0] - MAXS = torch.max(torch.max(vertices[0], axis=0)[0], axis=1)[0] - # vertices[:,:,1,:] -= MINS[1] + 1e-5 - - - out_list = [] - - minx = MINS[0] - 0.5 - maxx = MAXS[0] + 0.5 - minz = MINS[2] - 0.5 - maxz = MAXS[2] + 0.5 - polygon = geometry.Polygon([[minx, minz], [minx, maxz], [maxx, maxz], [maxx, minz]]) - polygon_mesh = trimesh.creation.extrude_polygon(polygon, 1e-5) - - vid = [] - for i in range(frames): - if i % 10 == 0: - print(i) - - mesh = Trimesh(vertices=vertices[0, :, :, i].squeeze().tolist(), faces=faces) - - base_color = (0.11, 0.53, 0.8, 0.5) - ## OPAQUE rendering without alpha - ## BLEND rendering consider alpha - material = pyrender.MetallicRoughnessMaterial( - metallicFactor=0.7, - alphaMode='OPAQUE', - baseColorFactor=base_color - ) - - - mesh = pyrender.Mesh.from_trimesh(mesh, material=material) - - polygon_mesh.visual.face_colors = [0, 0, 0, 0.21] - polygon_render = pyrender.Mesh.from_trimesh(polygon_mesh, smooth=False) - - bg_color = [1, 1, 1, 0.8] - scene = pyrender.Scene(bg_color=bg_color, ambient_light=(0.4, 0.4, 0.4)) - - sx, sy, tx, ty = [0.75, 0.75, 0, 0.10] - - camera = pyrender.PerspectiveCamera(yfov=(np.pi / 3.0)) - - light = pyrender.DirectionalLight(color=[1,1,1], intensity=300) - - scene.add(mesh) - - c = np.pi / 2 - - scene.add(polygon_render, pose=np.array([[ 1, 0, 0, 0], - - [ 0, np.cos(c), -np.sin(c), MINS[1].cpu().numpy()], - - [ 0, np.sin(c), np.cos(c), 0], - - [ 0, 0, 0, 1]])) - - light_pose = np.eye(4) - light_pose[:3, 3] = [0, -1, 1] - scene.add(light, pose=light_pose.copy()) - - light_pose[:3, 3] = [0, 1, 1] - scene.add(light, pose=light_pose.copy()) - - light_pose[:3, 3] = [1, 1, 2] - scene.add(light, pose=light_pose.copy()) - - - c = -np.pi / 6 - - scene.add(camera, pose=[[ 1, 0, 0, (minx+maxx).cpu().numpy()/2], - - [ 0, np.cos(c), -np.sin(c), 1.5], - - [ 0, np.sin(c), np.cos(c), max(4, minz.cpu().numpy()+(1.5-MINS[1].cpu().numpy())*2, (maxx-minx).cpu().numpy())], - - [ 0, 0, 0, 1] - ]) - - # render scene - r = pyrender.OffscreenRenderer(960, 960) - - color, _ = r.render(scene, flags=RenderFlags.RGBA) - # Image.fromarray(color).save(outdir+'/'+name+'_'+str(i)+'.png') - - vid.append(color) - - r.delete() - - out = np.stack(vid, axis=0) - if pred: - imageio.mimsave(outdir + name+'_pred.gif', out, fps=20) - else: - imageio.mimsave(outdir + name+'_gt.gif', out, fps=20) - - - - - -if __name__ == "__main__": - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("--filedir", type=str, default=None, help='motion npy file dir') - parser.add_argument('--motion-list', default=None, nargs="+", type=str, help="motion name list") - args = parser.parse_args() - - filename_list = args.motion_list - filedir = args.filedir - - for filename in filename_list: - motions = np.load(filedir + filename+'_pred.npy') - print('pred', motions.shape, filename) - render(motions[0], outdir=filedir, device_id=0, name=filename, pred=True) - - motions = np.load(filedir + filename+'_gt.npy') - print('gt', motions.shape, filename) - render(motions[0], outdir=filedir, device_id=0, name=filename, pred=False) diff --git a/spaces/AIFILMS/scene-edit-detection/app.py b/spaces/AIFILMS/scene-edit-detection/app.py deleted file mode 100644 index 0c41facca6aa63cc2ab71d4e7cb00fbe42e4fcde..0000000000000000000000000000000000000000 --- a/spaces/AIFILMS/scene-edit-detection/app.py +++ /dev/null @@ -1,154 +0,0 @@ -# Dependencies, see also requirement.txt ;) -import gradio as gr -import cv2 -import numpy as np -import os - -from scenedetect import open_video, SceneManager -from scenedetect.detectors import ContentDetector - -from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip - -# ————————————————————————————————————————————————— - -title = "Scene Edit Detection" -description = "

Gradio demo of PySceneDetect.
Automatically find every shots in a video sequence

1. gives you timecode in/out for each shot. 2. saves each shot as a splitted mp4 video chunk for you to download. 3. diplays a thumbnail for each shot as a gallery output.
visitor badge

" -article = "

PySceneDetect website | Github Repo

" - -# ————————————————————————————————————————————————— - -# SET INPUTS -video_input = gr.Video(source="upload", format="mp4", label="Video Sequence", mirror_webcam=False) -threshold = gr.Slider(label="Threshold pixel comparison: if exceeded, triggers a scene cut. Default: 27.0", minimum=15.0, maximum=40.0, value=27.0) - -# ————————————————————————————————————————————————— - -def convert_to_tuple(list): - return tuple(list); - - -def find_scenes(video_path, threshold): - # file name without extension - filename = os.path.splitext(os.path.basename(video_path))[0] - # Open our video, create a scene manager, and add a detector. - video = open_video(video_path) - scene_manager = SceneManager() - scene_manager.add_detector( - ContentDetector(threshold=threshold)) - - # Start detection - scene_manager.detect_scenes(video, show_progress=True) - scene_list = scene_manager.get_scene_list() - - # Push the list of scenes into data_outputs - data_outputs.append(scene_list) - gradio_components_outputs.append("json") - #print(scene_list) - - timecodes = [] - timecodes.append({"title": filename + ".mp4", "fps": scene_list[0][0].get_framerate()}) - - shots = [] - stills = [] - - # For each shot found, set entry and exit points as seconds from frame number - # Then split video into chunks and store them into shots List - # Then extract first frame of each shot as thumbnail for the gallery - for i, shot in enumerate(scene_list): - - # STEP 1 - # Get timecode in seconds - framerate = shot[0].get_framerate() - shot_in = shot[0].get_frames() / framerate - shot_out = shot[1].get_frames() / framerate - - tc_in = shot[0].get_timecode() - tc_out = shot[1].get_timecode() - - frame_in = shot[0].get_frames() - frame_out = shot[1].get_frames() - - timecode = {"tc_in": tc_in, "tc_out": tc_out, "frame_in": frame_in, "frame_out": frame_out} - timecodes.append(timecode) - - # Set name template for each shot - target_name = "shot_" + str(i+1) + "_" + str(filename) + ".mp4" - - # Split chunk - ffmpeg_extract_subclip(video_path, shot_in, shot_out, targetname=target_name) - - # Push chunk into shots List - shots.append(target_name) - - # Push each chunk into data_outputs - data_outputs.append(target_name) - gradio_components_outputs.append("video") - - # ————————————————————————————————————————————————— - - # STEP 2 - # extract first frame of each shot with cv2 - vid = cv2.VideoCapture(video_path) - fps = vid.get(cv2.CAP_PROP_FPS) - print('frames per second =',fps) - - frame_id = shot[0].get_frames() # value from scene_list from step 1 - - vid.set(cv2.CAP_PROP_POS_FRAMES, frame_id) - ret, frame = vid.read() - - # Save frame as PNG file - img = str(frame_id) + '_screenshot.png' - cv2.imwrite(img,frame) - - # Push image into stills List - stills.append((img, 'shot ' + str(i+1))) - - # Push the list of video shots into data_outputs for Gradio file component - data_outputs.append(shots) - gradio_components_outputs.append("file") - - # Push the list of still images into data_outputs - data_outputs.append(stills) - gradio_components_outputs.append("gallery") - - # This would have been used as gradio outputs, - # if we could set number of outputs after the interface launch - # That's not (yet ?) possible - results = convert_to_tuple(data_outputs) - print(results) - - # return List of shots as JSON, List of video chunks, List of still images - # * - # Would be nice to be able to return my results tuple as outputs, - # while number of chunks found is not fixed: - # return results - return timecodes, shots, stills - -# ————————————————————————————————————————————————— - -# SET DATA AND COMPONENTS OUTPUTS - -# This would be filled like this: -# data_outputs = [ [List from detection], "video_chunk_n0.mp4", "video_chunk_n1.mp4", ... , "video_chunk_n.mp4", [List of video filepath to download], [List of still images from each shot found] ] -data_outputs = [] - -# This would be filled like this: -# gradio_components_outputs = [ "json", "video", "video", ... , "video", "file", "gallery" ] -gradio_components_outputs = [] - - -#SET OUTPUTS - -# This would be nice if number of outputs could be set after Interface Launch: -# because we do not know how many shots will be detected -# gradio_components_outputs = [ "json", "video", "video", ... , "video", "file", "gallery" ] -# outputs = gradio_components_outputs - -# ANOTHER SOLUTION WOULD BE USING A (FUTURE ?) "VIDEO GALLERY" GRADIO COMPONENT FROM LIST :) - -outputs = [gr.JSON(label="Shots detected"), gr.File(label="Downloadable Shots"), gr.Gallery(label="Still Images from each shot").style(grid=3)] - -# ————————————————————————————————————————————————— -print('Hello Sylvain') -gr.Interface(fn=find_scenes, inputs=[video_input, threshold], outputs=outputs, title=title, description=description, article=article).launch() \ No newline at end of file diff --git a/spaces/AIGC-Audio/AudioGPT/text_to_speech/modules/vocoder/parallel_wavegan/models/source.py b/spaces/AIGC-Audio/AudioGPT/text_to_speech/modules/vocoder/parallel_wavegan/models/source.py deleted file mode 100644 index f2a006e53c0e2194036fd08ea9d6ed4d9a10d6cf..0000000000000000000000000000000000000000 --- a/spaces/AIGC-Audio/AudioGPT/text_to_speech/modules/vocoder/parallel_wavegan/models/source.py +++ /dev/null @@ -1,538 +0,0 @@ -import torch -import numpy as np -import sys -import torch.nn.functional as torch_nn_func - - -class SineGen(torch.nn.Module): - """ Definition of sine generator - SineGen(samp_rate, harmonic_num = 0, - sine_amp = 0.1, noise_std = 0.003, - voiced_threshold = 0, - flag_for_pulse=False) - - samp_rate: sampling rate in Hz - harmonic_num: number of harmonic overtones (default 0) - sine_amp: amplitude of sine-wavefrom (default 0.1) - noise_std: std of Gaussian noise (default 0.003) - voiced_thoreshold: F0 threshold for U/V classification (default 0) - flag_for_pulse: this SinGen is used inside PulseGen (default False) - - Note: when flag_for_pulse is True, the first time step of a voiced - segment is always sin(np.pi) or cos(0) - """ - - def __init__(self, samp_rate, harmonic_num=0, - sine_amp=0.1, noise_std=0.003, - voiced_threshold=0, - flag_for_pulse=False): - super(SineGen, self).__init__() - self.sine_amp = sine_amp - self.noise_std = noise_std - self.harmonic_num = harmonic_num - self.dim = self.harmonic_num + 1 - self.sampling_rate = samp_rate - self.voiced_threshold = voiced_threshold - self.flag_for_pulse = flag_for_pulse - - def _f02uv(self, f0): - # generate uv signal - uv = torch.ones_like(f0) - uv = uv * (f0 > self.voiced_threshold) - return uv - - def _f02sine(self, f0_values): - """ f0_values: (batchsize, length, dim) - where dim indicates fundamental tone and overtones - """ - # convert to F0 in rad. The interger part n can be ignored - # because 2 * np.pi * n doesn't affect phase - rad_values = (f0_values / self.sampling_rate) % 1 - - # initial phase noise (no noise for fundamental component) - rand_ini = torch.rand(f0_values.shape[0], f0_values.shape[2], \ - device=f0_values.device) - rand_ini[:, 0] = 0 - rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini - - # instantanouse phase sine[t] = sin(2*pi \sum_i=1 ^{t} rad) - if not self.flag_for_pulse: - # for normal case - - # To prevent torch.cumsum numerical overflow, - # it is necessary to add -1 whenever \sum_k=1^n rad_value_k > 1. - # Buffer tmp_over_one_idx indicates the time step to add -1. - # This will not change F0 of sine because (x-1) * 2*pi = x * 2*pi - tmp_over_one = torch.cumsum(rad_values, 1) % 1 - tmp_over_one_idx = (tmp_over_one[:, 1:, :] - - tmp_over_one[:, :-1, :]) < 0 - cumsum_shift = torch.zeros_like(rad_values) - cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0 - - sines = torch.sin(torch.cumsum(rad_values + cumsum_shift, dim=1) - * 2 * np.pi) - else: - # If necessary, make sure that the first time step of every - # voiced segments is sin(pi) or cos(0) - # This is used for pulse-train generation - - # identify the last time step in unvoiced segments - uv = self._f02uv(f0_values) - uv_1 = torch.roll(uv, shifts=-1, dims=1) - uv_1[:, -1, :] = 1 - u_loc = (uv < 1) * (uv_1 > 0) - - # get the instantanouse phase - tmp_cumsum = torch.cumsum(rad_values, dim=1) - # different batch needs to be processed differently - for idx in range(f0_values.shape[0]): - temp_sum = tmp_cumsum[idx, u_loc[idx, :, 0], :] - temp_sum[1:, :] = temp_sum[1:, :] - temp_sum[0:-1, :] - # stores the accumulation of i.phase within - # each voiced segments - tmp_cumsum[idx, :, :] = 0 - tmp_cumsum[idx, u_loc[idx, :, 0], :] = temp_sum - - # rad_values - tmp_cumsum: remove the accumulation of i.phase - # within the previous voiced segment. - i_phase = torch.cumsum(rad_values - tmp_cumsum, dim=1) - - # get the sines - sines = torch.cos(i_phase * 2 * np.pi) - return sines - - def forward(self, f0): - """ sine_tensor, uv = forward(f0) - input F0: tensor(batchsize=1, length, dim=1) - f0 for unvoiced steps should be 0 - output sine_tensor: tensor(batchsize=1, length, dim) - output uv: tensor(batchsize=1, length, 1) - """ - with torch.no_grad(): - f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, - device=f0.device) - # fundamental component - f0_buf[:, :, 0] = f0[:, :, 0] - for idx in np.arange(self.harmonic_num): - # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic - f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * (idx + 2) - - # generate sine waveforms - sine_waves = self._f02sine(f0_buf) * self.sine_amp - - # generate uv signal - # uv = torch.ones(f0.shape) - # uv = uv * (f0 > self.voiced_threshold) - uv = self._f02uv(f0) - - # noise: for unvoiced should be similar to sine_amp - # std = self.sine_amp/3 -> max value ~ self.sine_amp - # . for voiced regions is self.noise_std - noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3 - noise = noise_amp * torch.randn_like(sine_waves) - - # first: set the unvoiced part to 0 by uv - # then: additive noise - sine_waves = sine_waves * uv + noise - return sine_waves, uv, noise - - -class PulseGen(torch.nn.Module): - """ Definition of Pulse train generator - - There are many ways to implement pulse generator. - Here, PulseGen is based on SinGen. For a perfect - """ - def __init__(self, samp_rate, pulse_amp = 0.1, - noise_std = 0.003, voiced_threshold = 0): - super(PulseGen, self).__init__() - self.pulse_amp = pulse_amp - self.sampling_rate = samp_rate - self.voiced_threshold = voiced_threshold - self.noise_std = noise_std - self.l_sinegen = SineGen(self.sampling_rate, harmonic_num=0, \ - sine_amp=self.pulse_amp, noise_std=0, \ - voiced_threshold=self.voiced_threshold, \ - flag_for_pulse=True) - - def forward(self, f0): - """ Pulse train generator - pulse_train, uv = forward(f0) - input F0: tensor(batchsize=1, length, dim=1) - f0 for unvoiced steps should be 0 - output pulse_train: tensor(batchsize=1, length, dim) - output uv: tensor(batchsize=1, length, 1) - - Note: self.l_sine doesn't make sure that the initial phase of - a voiced segment is np.pi, the first pulse in a voiced segment - may not be at the first time step within a voiced segment - """ - with torch.no_grad(): - sine_wav, uv, noise = self.l_sinegen(f0) - - # sine without additive noise - pure_sine = sine_wav - noise - - # step t corresponds to a pulse if - # sine[t] > sine[t+1] & sine[t] > sine[t-1] - # & sine[t-1], sine[t+1], and sine[t] are voiced - # or - # sine[t] is voiced, sine[t-1] is unvoiced - # we use torch.roll to simulate sine[t+1] and sine[t-1] - sine_1 = torch.roll(pure_sine, shifts=1, dims=1) - uv_1 = torch.roll(uv, shifts=1, dims=1) - uv_1[:, 0, :] = 0 - sine_2 = torch.roll(pure_sine, shifts=-1, dims=1) - uv_2 = torch.roll(uv, shifts=-1, dims=1) - uv_2[:, -1, :] = 0 - - loc = (pure_sine > sine_1) * (pure_sine > sine_2) \ - * (uv_1 > 0) * (uv_2 > 0) * (uv > 0) \ - + (uv_1 < 1) * (uv > 0) - - # pulse train without noise - pulse_train = pure_sine * loc - - # additive noise to pulse train - # note that noise from sinegen is zero in voiced regions - pulse_noise = torch.randn_like(pure_sine) * self.noise_std - - # with additive noise on pulse, and unvoiced regions - pulse_train += pulse_noise * loc + pulse_noise * (1 - uv) - return pulse_train, sine_wav, uv, pulse_noise - - -class SignalsConv1d(torch.nn.Module): - """ Filtering input signal with time invariant filter - Note: FIRFilter conducted filtering given fixed FIR weight - SignalsConv1d convolves two signals - Note: this is based on torch.nn.functional.conv1d - - """ - - def __init__(self): - super(SignalsConv1d, self).__init__() - - def forward(self, signal, system_ir): - """ output = forward(signal, system_ir) - - signal: (batchsize, length1, dim) - system_ir: (length2, dim) - - output: (batchsize, length1, dim) - """ - if signal.shape[-1] != system_ir.shape[-1]: - print("Error: SignalsConv1d expects shape:") - print("signal (batchsize, length1, dim)") - print("system_id (batchsize, length2, dim)") - print("But received signal: {:s}".format(str(signal.shape))) - print(" system_ir: {:s}".format(str(system_ir.shape))) - sys.exit(1) - padding_length = system_ir.shape[0] - 1 - groups = signal.shape[-1] - - # pad signal on the left - signal_pad = torch_nn_func.pad(signal.permute(0, 2, 1), \ - (padding_length, 0)) - # prepare system impulse response as (dim, 1, length2) - # also flip the impulse response - ir = torch.flip(system_ir.unsqueeze(1).permute(2, 1, 0), \ - dims=[2]) - # convolute - output = torch_nn_func.conv1d(signal_pad, ir, groups=groups) - return output.permute(0, 2, 1) - - -class CyclicNoiseGen_v1(torch.nn.Module): - """ CyclicnoiseGen_v1 - Cyclic noise with a single parameter of beta. - Pytorch v1 implementation assumes f_t is also fixed - """ - - def __init__(self, samp_rate, - noise_std=0.003, voiced_threshold=0): - super(CyclicNoiseGen_v1, self).__init__() - self.samp_rate = samp_rate - self.noise_std = noise_std - self.voiced_threshold = voiced_threshold - - self.l_pulse = PulseGen(samp_rate, pulse_amp=1.0, - noise_std=noise_std, - voiced_threshold=voiced_threshold) - self.l_conv = SignalsConv1d() - - def noise_decay(self, beta, f0mean): - """ decayed_noise = noise_decay(beta, f0mean) - decayed_noise = n[t]exp(-t * f_mean / beta / samp_rate) - - beta: (dim=1) or (batchsize=1, 1, dim=1) - f0mean (batchsize=1, 1, dim=1) - - decayed_noise (batchsize=1, length, dim=1) - """ - with torch.no_grad(): - # exp(-1.0 n / T) < 0.01 => n > -log(0.01)*T = 4.60*T - # truncate the noise when decayed by -40 dB - length = 4.6 * self.samp_rate / f0mean - length = length.int() - time_idx = torch.arange(0, length, device=beta.device) - time_idx = time_idx.unsqueeze(0).unsqueeze(2) - time_idx = time_idx.repeat(beta.shape[0], 1, beta.shape[2]) - - noise = torch.randn(time_idx.shape, device=beta.device) - - # due to Pytorch implementation, use f0_mean as the f0 factor - decay = torch.exp(-time_idx * f0mean / beta / self.samp_rate) - return noise * self.noise_std * decay - - def forward(self, f0s, beta): - """ Producde cyclic-noise - """ - # pulse train - pulse_train, sine_wav, uv, noise = self.l_pulse(f0s) - pure_pulse = pulse_train - noise - - # decayed_noise (length, dim=1) - if (uv < 1).all(): - # all unvoiced - cyc_noise = torch.zeros_like(sine_wav) - else: - f0mean = f0s[uv > 0].mean() - - decayed_noise = self.noise_decay(beta, f0mean)[0, :, :] - # convolute - cyc_noise = self.l_conv(pure_pulse, decayed_noise) - - # add noise in invoiced segments - cyc_noise = cyc_noise + noise * (1.0 - uv) - return cyc_noise, pulse_train, sine_wav, uv, noise - - -class SineGen(torch.nn.Module): - """ Definition of sine generator - SineGen(samp_rate, harmonic_num = 0, - sine_amp = 0.1, noise_std = 0.003, - voiced_threshold = 0, - flag_for_pulse=False) - - samp_rate: sampling rate in Hz - harmonic_num: number of harmonic overtones (default 0) - sine_amp: amplitude of sine-wavefrom (default 0.1) - noise_std: std of Gaussian noise (default 0.003) - voiced_thoreshold: F0 threshold for U/V classification (default 0) - flag_for_pulse: this SinGen is used inside PulseGen (default False) - - Note: when flag_for_pulse is True, the first time step of a voiced - segment is always sin(np.pi) or cos(0) - """ - - def __init__(self, samp_rate, harmonic_num=0, - sine_amp=0.1, noise_std=0.003, - voiced_threshold=0, - flag_for_pulse=False): - super(SineGen, self).__init__() - self.sine_amp = sine_amp - self.noise_std = noise_std - self.harmonic_num = harmonic_num - self.dim = self.harmonic_num + 1 - self.sampling_rate = samp_rate - self.voiced_threshold = voiced_threshold - self.flag_for_pulse = flag_for_pulse - - def _f02uv(self, f0): - # generate uv signal - uv = torch.ones_like(f0) - uv = uv * (f0 > self.voiced_threshold) - return uv - - def _f02sine(self, f0_values): - """ f0_values: (batchsize, length, dim) - where dim indicates fundamental tone and overtones - """ - # convert to F0 in rad. The interger part n can be ignored - # because 2 * np.pi * n doesn't affect phase - rad_values = (f0_values / self.sampling_rate) % 1 - - # initial phase noise (no noise for fundamental component) - rand_ini = torch.rand(f0_values.shape[0], f0_values.shape[2], \ - device=f0_values.device) - rand_ini[:, 0] = 0 - rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini - - # instantanouse phase sine[t] = sin(2*pi \sum_i=1 ^{t} rad) - if not self.flag_for_pulse: - # for normal case - - # To prevent torch.cumsum numerical overflow, - # it is necessary to add -1 whenever \sum_k=1^n rad_value_k > 1. - # Buffer tmp_over_one_idx indicates the time step to add -1. - # This will not change F0 of sine because (x-1) * 2*pi = x * 2*pi - tmp_over_one = torch.cumsum(rad_values, 1) % 1 - tmp_over_one_idx = (tmp_over_one[:, 1:, :] - - tmp_over_one[:, :-1, :]) < 0 - cumsum_shift = torch.zeros_like(rad_values) - cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0 - - sines = torch.sin(torch.cumsum(rad_values + cumsum_shift, dim=1) - * 2 * np.pi) - else: - # If necessary, make sure that the first time step of every - # voiced segments is sin(pi) or cos(0) - # This is used for pulse-train generation - - # identify the last time step in unvoiced segments - uv = self._f02uv(f0_values) - uv_1 = torch.roll(uv, shifts=-1, dims=1) - uv_1[:, -1, :] = 1 - u_loc = (uv < 1) * (uv_1 > 0) - - # get the instantanouse phase - tmp_cumsum = torch.cumsum(rad_values, dim=1) - # different batch needs to be processed differently - for idx in range(f0_values.shape[0]): - temp_sum = tmp_cumsum[idx, u_loc[idx, :, 0], :] - temp_sum[1:, :] = temp_sum[1:, :] - temp_sum[0:-1, :] - # stores the accumulation of i.phase within - # each voiced segments - tmp_cumsum[idx, :, :] = 0 - tmp_cumsum[idx, u_loc[idx, :, 0], :] = temp_sum - - # rad_values - tmp_cumsum: remove the accumulation of i.phase - # within the previous voiced segment. - i_phase = torch.cumsum(rad_values - tmp_cumsum, dim=1) - - # get the sines - sines = torch.cos(i_phase * 2 * np.pi) - return sines - - def forward(self, f0): - """ sine_tensor, uv = forward(f0) - input F0: tensor(batchsize=1, length, dim=1) - f0 for unvoiced steps should be 0 - output sine_tensor: tensor(batchsize=1, length, dim) - output uv: tensor(batchsize=1, length, 1) - """ - with torch.no_grad(): - f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, \ - device=f0.device) - # fundamental component - f0_buf[:, :, 0] = f0[:, :, 0] - for idx in np.arange(self.harmonic_num): - # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic - f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * (idx + 2) - - # generate sine waveforms - sine_waves = self._f02sine(f0_buf) * self.sine_amp - - # generate uv signal - # uv = torch.ones(f0.shape) - # uv = uv * (f0 > self.voiced_threshold) - uv = self._f02uv(f0) - - # noise: for unvoiced should be similar to sine_amp - # std = self.sine_amp/3 -> max value ~ self.sine_amp - # . for voiced regions is self.noise_std - noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3 - noise = noise_amp * torch.randn_like(sine_waves) - - # first: set the unvoiced part to 0 by uv - # then: additive noise - sine_waves = sine_waves * uv + noise - return sine_waves, uv, noise - - -class SourceModuleCycNoise_v1(torch.nn.Module): - """ SourceModuleCycNoise_v1 - SourceModule(sampling_rate, noise_std=0.003, voiced_threshod=0) - sampling_rate: sampling_rate in Hz - - noise_std: std of Gaussian noise (default: 0.003) - voiced_threshold: threshold to set U/V given F0 (default: 0) - - cyc, noise, uv = SourceModuleCycNoise_v1(F0_upsampled, beta) - F0_upsampled (batchsize, length, 1) - beta (1) - cyc (batchsize, length, 1) - noise (batchsize, length, 1) - uv (batchsize, length, 1) - """ - - def __init__(self, sampling_rate, noise_std=0.003, voiced_threshod=0): - super(SourceModuleCycNoise_v1, self).__init__() - self.sampling_rate = sampling_rate - self.noise_std = noise_std - self.l_cyc_gen = CyclicNoiseGen_v1(sampling_rate, noise_std, - voiced_threshod) - - def forward(self, f0_upsamped, beta): - """ - cyc, noise, uv = SourceModuleCycNoise_v1(F0, beta) - F0_upsampled (batchsize, length, 1) - beta (1) - cyc (batchsize, length, 1) - noise (batchsize, length, 1) - uv (batchsize, length, 1) - """ - # source for harmonic branch - cyc, pulse, sine, uv, add_noi = self.l_cyc_gen(f0_upsamped, beta) - - # source for noise branch, in the same shape as uv - noise = torch.randn_like(uv) * self.noise_std / 3 - return cyc, noise, uv - - -class SourceModuleHnNSF(torch.nn.Module): - """ SourceModule for hn-nsf - SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1, - add_noise_std=0.003, voiced_threshod=0) - sampling_rate: sampling_rate in Hz - harmonic_num: number of harmonic above F0 (default: 0) - sine_amp: amplitude of sine source signal (default: 0.1) - add_noise_std: std of additive Gaussian noise (default: 0.003) - note that amplitude of noise in unvoiced is decided - by sine_amp - voiced_threshold: threhold to set U/V given F0 (default: 0) - - Sine_source, noise_source = SourceModuleHnNSF(F0_sampled) - F0_sampled (batchsize, length, 1) - Sine_source (batchsize, length, 1) - noise_source (batchsize, length 1) - uv (batchsize, length, 1) - """ - - def __init__(self, sampling_rate, harmonic_num=0, sine_amp=0.1, - add_noise_std=0.003, voiced_threshod=0): - super(SourceModuleHnNSF, self).__init__() - - self.sine_amp = sine_amp - self.noise_std = add_noise_std - - # to produce sine waveforms - self.l_sin_gen = SineGen(sampling_rate, harmonic_num, - sine_amp, add_noise_std, voiced_threshod) - - # to merge source harmonics into a single excitation - self.l_linear = torch.nn.Linear(harmonic_num + 1, 1) - self.l_tanh = torch.nn.Tanh() - - def forward(self, x): - """ - Sine_source, noise_source = SourceModuleHnNSF(F0_sampled) - F0_sampled (batchsize, length, 1) - Sine_source (batchsize, length, 1) - noise_source (batchsize, length 1) - """ - # source for harmonic branch - sine_wavs, uv, _ = self.l_sin_gen(x) - sine_merge = self.l_tanh(self.l_linear(sine_wavs)) - - # source for noise branch, in the same shape as uv - noise = torch.randn_like(uv) * self.sine_amp / 3 - return sine_merge, noise, uv - - -if __name__ == '__main__': - source = SourceModuleCycNoise_v1(24000) - x = torch.randn(16, 25600, 1) - - diff --git a/spaces/AIWaves/Software_Company/gradio_base.py b/spaces/AIWaves/Software_Company/gradio_base.py deleted file mode 100644 index d9885b897b0fab5aa920d89cd4f202af83b9656c..0000000000000000000000000000000000000000 --- a/spaces/AIWaves/Software_Company/gradio_base.py +++ /dev/null @@ -1,574 +0,0 @@ -# coding=utf-8 -# Copyright 2023 The AIWaves Inc. team. - -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Emoji comes from this website: -# https://emojipedia.org/ -import subprocess -from gradio_config import GradioConfig as gc -import gradio as gr -from typing import List, Tuple, Any -import time -import socket -import psutil -import os -from abc import abstractmethod -import openai - -def test_apikey_connection(api_key=None, model="gpt-3.5-turbo"): - openai.api_key = api_key if api_key is not None else os.environ["API_KEY"] - if "PROXY" in os.environ: - openai.proxy = os.environ["PROXY"] - messages = [{"role": "user", "content": "what's your name?"}] - try: - response = openai.ChatCompletion.create( - model=model, - messages=messages, - ) - return True - except: - return False - -def convert2list4agentname(sop): - """ - Extract the agent names of all states - return: - only name: [name1, name2, ...] - agent_name: [name1(role1), name2(role2), ...] - """ - only_name = [] - agent_name = [] - roles_to_names = sop.roles_to_names - for state_name,roles_names in roles_to_names.items(): - for role,name in roles_names.items(): - agent_name.append(f"{name}({role})") - only_name.append(name) - agent_name = list(set(agent_name)) - agent_name.sort() - return agent_name, only_name - -def is_port_in_use(port): - """Check if the port is available""" - for conn in psutil.net_connections(): - if conn.laddr.port == port: - return True - return False - -def check_port(port): - """Determine available ports""" - if os.path.isfile("PORT.txt"): - port = int(open("PORT.txt","r",encoding='utf-8').readlines()[0]) - else: - for i in range(10): - if is_port_in_use(port+i) == False: - port += i - break - with open("PORT.txt", "w") as f: - f.writelines(str(port)) - return port - -# Determine some heads -SPECIAL_SIGN = { - "START": "", - "SPLIT": "", - "END": "" -} -HOST = "127.0.0.1" -# The starting port number for the search. -PORT = 15000 -PORT = check_port(PORT) - -def print_log(message:str): - print(f"[{time.ctime()}]{message}") - -global_dialog = { - "user": [], - "agent": {}, - "system": [] -} - -class UIHelper: - """Static Class""" - - @classmethod - def wrap_css(cls, content, name) -> str: - """ - Description: - Wrap CSS around each output, and return it in HTML format for rendering with Markdown. - Input: - content: Output content - name: Whose output is it - Output: - HTML - """ - assert name in gc.OBJECT_INFO, \ - f"The current name `{name}` is not registered with an image. The names of the currently registered agents are in `{gc.OBJECT_INFO.keys()}`. Please use `GradioConfig.add_agent()` from `Gradio_Config/gradio_config.py` to bind the name of the new agent." - output = "" - info = gc.OBJECT_INFO[name] - if info["id"] == "USER": - output = gc.BUBBLE_CSS["USER"].format( - info["bubble_color"], # Background-color - info["text_color"], # Color of the agent's name - name, # Agent name - info["text_color"], # Font color - info["font_size"], # Font size - content, # Content - info["head_url"] # URL of the avatar - ) - elif info["id"] == "SYSTEM": - output = gc.BUBBLE_CSS["SYSTEM"].format( - info["bubble_color"], # Background-color - info["font_size"], # Font size - info["text_color"], # Font color - name, # Agent name - content # Content - ) - elif info["id"] == "AGENT": - output = gc.BUBBLE_CSS["AGENT"].format( - info["head_url"], # URL of the avatar - info["bubble_color"], # Background-color - info["text_color"], # Font color - name, # Agent name - info["text_color"], # Font color - info["font_size"], # Font size - content, # Content - ) - else: - assert False, f"Id `{info['id']}` is invalid. The valid id is in ['SYSTEM', 'AGENT', 'USER']" - return output - - @classmethod - def novel_filter(cls, content, agent_name): - - """比如...,就应该输出CONTENT:...""" - IS_RECORDER = agent_name.lower() in ["recorder", "summary"] - if IS_RECORDER: - BOLD_FORMAT = """
- {} -
- -""" - else: - BOLD_FORMAT = "{}" - CENTER_FORMAT = """
- {} -
-""" - START_FORMAT = "<{}>" - END_FORMAT = "" - mapping = { - "TARGET": "🎯 Current Target: ", - "NUMBER": "🍖 Required Number: ", - "THOUGHT": "🤔 Overall Thought: ", - "FIRST NAME": "⚪ First Name: ", - "LAST NAME": "⚪ Last Name: ", - "ROLE": "🤠 Character Properties: ", - "RATIONALES": "🤔 Design Rationale: ", - "BACKGROUND": "🚊 Character Background: ", - "ID": "🔴 ID: ", - "TITLE": "🧩 Chapter Title: ", - "ABSTRACT": "🎬 Abstract: ", - "CHARACTER INVOLVED": "☃️ Character Involved: ", - "ADVICE": "💬 Advice:", - "NAME": "📛 Name: ", - "GENDER": "👩‍👩‍👦‍👦 Gender: ", - "AGE": "⏲️ Age: ", - "WORK": "👨‍🔧 Work: ", - "PERSONALITY": "🧲 Character Personality: ", - "SPEECH STYLE": "🗣️ Speaking Style: ", - "RELATION": "🏠 Relation with Others: ", - "WORD COUNT": "🎰 Word Count: ", - "CHARACTER DESIGN": "📈 Character Design: ", - "CHARACTER REQUIRE": "📈 Character Require: ", - "CHARACTER NAME": "📈 Character Naming Analysis: ", - "CHARACTER NOW": "📈 Character Now: ", - "OUTLINE DESIGN": "📈 Outline Design: ", - "OUTLINE REQUIRE": "📈 Outline Require: ", - "OUTLINE NOW": "📈 Outline Now: ", - "SUB TASK": "🎯 Current Sub Task: ", - "CHARACTER ADVICE": "💬 Character Design Advice: ", - "OUTLINE ADVANTAGE": "📈 Outline Advantage: ", - "OUTLINE DISADVANTAGE": "📈 Outline Disadvantage: ", - "OUTLINE ADVICE": "💬 Outline Advice: ", - "NEXT": "➡️ Next Advice: ", - "TOTAL NUMBER": "🔢 Total Number: " - } - for i in range(1, 10): - mapping[f"CHARACTER {i}"] = f"🦄 Character {i}" - mapping[f"SECTION {i}"] = f"🏷️ Chapter {i}" - for key in mapping: - if key in [f"CHARACTER {i}" for i in range(1, 10)] \ - or key in [f"SECTION {i}" for i in range(1, 10)] \ - : - content = content.replace( - START_FORMAT.format(key), CENTER_FORMAT.format(mapping[key]) - ) - elif key in ["TOTAL NUMBER"]: - content = content.replace( - START_FORMAT.format(key), CENTER_FORMAT.format(mapping[key]) + """""" - ) - content = content.replace( - END_FORMAT.format(key), "" - ) - else: - content = content.replace( - START_FORMAT.format(key), BOLD_FORMAT.format(mapping[key]) - ) - - content = content.replace( - END_FORMAT.format(key), "
" if IS_RECORDER else "" - ) - return content - - @classmethod - def singleagent_filter(cls, content, agent_name): - return content - - @classmethod - def debate_filter(cls, content, agent_name): - return content - - @classmethod - def code_filter(cls, content, agent_name): - # return content.replace("```python", "
").replace("```","
") - return content - - @classmethod - def general_filter(cls, content, agent_name): - return content - - @classmethod - def filter(cls, content: str, agent_name: str, ui_name: str): - """ - Description: - Make certain modifications to the output content to enhance its aesthetics when content is showed in gradio. - Input: - content: output content - agent_name: Whose output is it - ui_name: What UI is currently launching - Output: - Modified content - """ - mapping = { - "SingleAgentUI": cls.singleagent_filter, - "DebateUI": cls.debate_filter, - "NovelUI": cls.novel_filter, - "CodeUI": cls.code_filter, - "GeneralUI": cls.general_filter - } - if ui_name in mapping: - return mapping[ui_name](content, agent_name) - else: - return content - -class Client: - """ - For inter-process communication, this is the client. - `gradio_backend.PY` serves as the backend, while `run_gradio` is the frontend. - Communication between the frontend and backend is accomplished using Sockets. - """ - # =======================Radio Const String====================== - SINGLE_MODE = "Single Mode" - AUTO_MODE = "Auto Mode" - MODE_LABEL = "Select the execution mode" - MODE_INFO = "Single mode refers to when the current agent output ends, it will stop running until you click to continue. Auto mode refers to when you complete the input, all agents will continue to output until the task ends." - # =============================================================== - mode = AUTO_MODE - FIRST_RUN:bool = True - # if last agent is user, then next agent will be executed automatically rather than click button - LAST_USER:bool = False - - receive_server = None - send_server = None - current_node = None - cache = {} - - def __init__(self, host=HOST, port=PORT, bufsize=1024): - assert Client.mode in [Client.SINGLE_MODE, Client.AUTO_MODE] - self.SIGN = SPECIAL_SIGN - self.bufsize = bufsize - assert bufsize > 0 - self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.client_socket.connect((host, port)) - while True: - data = self.client_socket.recv(self.bufsize).decode('utf-8') - if data == "hi": - self.client_socket.send("hello agent".encode('utf-8')) - time.sleep(1) - elif data == "check": - break - print_log("Client: connecting successfully......") - - def start_server(self): - while True: - message = yield - if message == 'exit': - break - self.send_message(message=message) - - def send_message(self, message): - """Send the message to the server.""" - if isinstance(message, list) or isinstance(message, dict): - message = str(message) - assert isinstance(message, str) - message = message + self.SIGN["SPLIT"] - self.client_socket.send(message.encode('utf-8')) - - def receive_message(self, end_identifier: str = None, split_identifier: str = SPECIAL_SIGN["SPLIT"]) -> List: - """Receive messages from the server, and it will block the process. Supports receiving long text.""" - remaining = "" - while True: - # receive message - dataset = self.client_socket.recv(self.bufsize) - try: - # If decoding fails, it indicates that the current transmission is a long text. - dataset = dataset.decode('utf-8') - except UnicodeDecodeError: - if not isinstance(remaining, bytes): - remaining = remaining.encode('utf-8') - assert isinstance(dataset, bytes) - remaining += dataset - try: - dataset = remaining.decode('utf-8') - remaining = "" - except UnicodeDecodeError: - continue - assert isinstance(remaining, str) - dataset = remaining + dataset - list_dataset = dataset.split(split_identifier) - if len(list_dataset) == 1: - # If there is only one result from the split, it indicates that the current sequence itself has not yet ended. - remaining = list_dataset[0] - continue - else: - remaining = list_dataset[-1] - # Receive successfully - list_dataset = list_dataset[:-1] - return_value = [] - for item in list_dataset: - if end_identifier is not None and item == end_identifier: - break - return_value.append(item) - identifier = yield return_value - if identifier is not None: - end_identifier, split_identifier = identifier - - def listening_for_start_(self): - """ - When the server starts, the client is automatically launched. - At this point, process synchronization is required, - such as sending client data to the server for rendering, - then the server sending the modified data back to the client, - and simultaneously sending a startup command. - Once the client receives the data, it will start running. - """ - Client.receive_server = self.receive_message() - # Waiting for information from the server. - data: list = next(Client.receive_server) - assert len(data) == 1 - data = eval(data[0]) - assert isinstance(data, dict) - Client.cache.update(data) - # Waiting for start command from the server. - data:list = Client.receive_server.send(None) - assert len(data) == 1 - assert data[0] == "" - -class WebUI: - """ - The base class for the frontend, which encapsulates some functions for process information synchronization. - When a new frontend needs to be created, you should inherit from this class, - then implement the `construct_ui()` method and set up event listeners. - Finally, execute `run()` to load it. - """ - - def receive_message( - self, - end_identifier:str=None, - split_identifier:str=SPECIAL_SIGN["SPLIT"] - )->List: - """This is the same as in Client class.""" - yield "hello" - remaining = "" - while True: - dataset = self.client_socket.recv(self.bufsize) - try: - dataset = dataset.decode('utf-8') - except UnicodeDecodeError: - if not isinstance(remaining, bytes): - remaining = remaining.encode('utf-8') - assert isinstance(dataset, bytes) - remaining += dataset - try: - dataset = remaining.decode('utf-8') - remaining = "" - except UnicodeDecodeError: - continue - assert isinstance(remaining, str) - dataset = remaining + dataset - list_dataset = dataset.split(split_identifier) - if len(list_dataset) == 1: - remaining = list_dataset[0] - continue - else: - remaining = list_dataset[-1] - list_dataset = list_dataset[:-1] - return_value = [] - for item in list_dataset: - if end_identifier is not None and item == end_identifier: - break - return_value.append(item) - identifier = yield return_value - if identifier is not None: - end_identifier, split_identifier = identifier - - def send_message(self, message:str): - """Send message to client.""" - SEP = self.SIGN["SPLIT"] - self.client_socket.send( - (message+SEP).encode("utf-8") - ) - - def _connect(self): - # check - if self.server_socket: - self.server_socket.close() - assert not os.path.isfile("PORT.txt") - self.socket_port = check_port(PORT) - # Step1. initialize - self.server_socket = socket.socket( - socket.AF_INET, socket.SOCK_STREAM - ) - # Step2. binding ip and port - self.server_socket.bind((self.socket_host, self.socket_port)) - # Step3. run client - self._start_client() - - # Step4. listening for connect - self.server_socket.listen(1) - - # Step5. test connection - client_socket, client_address = self.server_socket.accept() - print_log("server: establishing connection......") - self.client_socket = client_socket - while True: - client_socket.send("hi".encode('utf-8')) - time.sleep(1) - data = client_socket.recv(self.bufsize).decode('utf-8') - if data == "hello agent": - client_socket.send("check".encode('utf-8')) - print_log("server: connect successfully") - break - assert os.path.isfile("PORT.txt") - os.remove("PORT.txt") - if self.receive_server: - del self.receive_server - self.receive_server = self.receive_message() - assert next(self.receive_server) == "hello" - - @abstractmethod - def render_and_register_ui(self): - # You need to implement this function. - # The function's purpose is to bind the name of the agent with an image. - # The name of the agent is stored in `self.cache[]`, - # and the function for binding is in the method `add_agents` of the class `GradioConfig` in `Gradio_Config/gradio_config.py``. - # This function will be executed in `self.first_recieve_from_client()` - pass - - def first_recieve_from_client(self, reset_mode:bool=False): - """ - This function is used to receive information from the client and is typically executed during the initialization of the class. - If `reset_mode` is False, it will bind the name of the agent with an image. - """ - self.FIRST_RECIEVE_FROM_CLIENT = True - data_list:List = self.receive_server.send(None) - assert len(data_list) == 1 - data = eval(data_list[0]) - assert isinstance(data, dict) - self.cache.update(data) - if not reset_mode: - self.render_and_register_ui() - - def _second_send(self, message:dict): - # Send the modified message. - # It will be executed in `self.send_start_cmd()` automatically. - self.send_message(str(message)) - - def _third_send(self): - # Send start command. - # It will be executed in `self.send_start_cmd()` automatically. - self.send_message(self.SIGN['START']) - - def send_start_cmd(self, message:dict={"hello":"hello"}): - # If you have no message to send, you can ignore the args `message`. - assert self.FIRST_RECIEVE_FROM_CLIENT, "Please make sure you have executed `self.first_recieve_from_client()` manually." - self._second_send(message=message) - time.sleep(1) - self._third_send() - self.FIRST_RECIEVE_FROM_CLIENT = False - - def __init__( - self, - client_cmd: list, # ['python','test.py','--a','b','--c','d'] - socket_host: str = HOST, - socket_port: int = PORT, - bufsize: int = 1024, - ui_name: str = "" - ): - self.ui_name = ui_name - self.server_socket = None - self.SIGN = SPECIAL_SIGN - self.socket_host = socket_host - self.socket_port = socket_port - self.bufsize = bufsize - self.client_cmd = client_cmd - - self.receive_server = None - self.cache = {} - assert self.bufsize > 0 - self._connect() - - def _start_client(self): - print(f"server: executing `{' '.join(self.client_cmd)}` ...") - self.backend = subprocess.Popen(self.client_cmd) - - def _close_client(self): - print(f"server: killing `{' '.join(self.client_cmd)}` ...") - self.backend.terminate() - - def reset(self): - print("server: restarting ...") - self._close_client() - time.sleep(1) - self._connect() - - def render_bubble(self, rendered_data, agent_response, node_name, render_node_name:bool=True): - # Rendered bubbles (HTML format) are used for gradio output. - output = f"**{node_name}**
" if render_node_name else "" - for item in agent_response: - for agent_name in item: - content = item[agent_name].replace("\n", "
") - content = UIHelper.filter(content, agent_name, self.ui_name) - output = f"{output}
{UIHelper.wrap_css(content, agent_name)}" - rendered_data[-1] = [rendered_data[-1][0], output] - return rendered_data - - def run(self,share: bool = True): - self.demo.queue() - self.demo.launch() - - -if __name__ == '__main__': - pass \ No newline at end of file diff --git a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/_base_/models/resnet34_gem.py b/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/_base_/models/resnet34_gem.py deleted file mode 100644 index 5c0e0d3e8dc5d7a0b259f1624ee2402af8a401cd..0000000000000000000000000000000000000000 --- a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/_base_/models/resnet34_gem.py +++ /dev/null @@ -1,17 +0,0 @@ -# model settings -model = dict( - type='ImageClassifier', - backbone=dict( - type='ResNet', - depth=34, - num_stages=4, - out_indices=(3, ), - style='pytorch'), - neck=dict(type='GeneralizedMeanPooling'), - head=dict( - type='LinearClsHead', - num_classes=1000, - in_channels=512, - loss=dict(type='CrossEntropyLoss', loss_weight=1.0), - topk=(1, 5), - )) diff --git a/spaces/Accel/media-converter/app.py b/spaces/Accel/media-converter/app.py deleted file mode 100644 index 9a11e585487333ec6f0f5b103685f39015a35f4d..0000000000000000000000000000000000000000 --- a/spaces/Accel/media-converter/app.py +++ /dev/null @@ -1,168 +0,0 @@ -import logging -import subprocess -from pprint import pprint -from tempfile import _TemporaryFileWrapper - -from ffmpy import FFmpeg - -import gradio as gr -from functions import (Clear, CommandBuilder, audio_channels, audio_codecs, - audio_quality, audio_sample_rates, - change_clipbox, containers, customBitrate, mediaChange, presets, supported_codecs, supported_presets, video_codecs, video_containers, - vf) - -logging.basicConfig(level=logging.INFO) - - -logging.info(msg=f"{video_containers}") - - -def convert(file: _TemporaryFileWrapper, options: str,state): - stderr="" - stdout="" - output_file="" - video="" - ffmpeg=FFmpeg() - try: - logging.info(f"File name: {file.name}") - new_name, _ = file.name.split(".") - logging.info(f"New filename:{new_name}") - output_file = f"{new_name}1.{options.lower()}" - ffmpeg = FFmpeg(inputs={file.name: None}, outputs={ - output_file: ffmpeg_commands.commands.split()}, global_options=["-y", "-hide_banner"]) - print(ffmpeg) - print(ffmpeg.cmd) - - ffmpeg.run(stderr=subprocess.PIPE) - # pprint(f"{stdout} {stderr}") - output=f"{ffmpeg.cmd}" - # video=gr.update(label=output_file,value=output_file) - - except Exception as e: - stderr=e - output=f"{stderr}" - return [None,None,None,output] - - state=output_file - - return [output_file,output_file,output_file,output,state] - - -with gr.Blocks(css="./styles.css") as dm: - with gr.Tabs(): - with gr.TabItem("Format"): - # Input Buttons - with gr.Row(): - with gr.Column() as inputs: - file_input = gr.File() - options = gr.Radio( - label="options", choices=containers,value=containers[0]) - with gr.Row(): - with gr.Row() as inputs_clip: - clip = gr.Dropdown( - choices=["None", "Enabled"], label="Clip:", value="None") - start_time = gr.Textbox( - label="Start Time:", placeholder="00:00", visible=False,interactive=True) - stop_time = gr.Textbox( - label="Stop Time:", placeholder="00:00", visible=False) - with gr.Row(): - clearBtn = gr.Button("Clear") - convertBtn = gr.Button("Convert", variant="primary") - - # Output Buttons - with gr.Column(): - # media_output = gr.Audio(label="Output") - with gr.Row(): - video_button=gr.Button("Video") - audio_button=gr.Button("Audio") - file_button=gr.Button("File") - media_output_audio = gr.Audio(type="filepath",label="Output",visible=True,interactive=False,source="filepath") - media_output_video = gr.Video(label="Output",visible=False) - media_output_file = gr.File(label="Output",visible=False) - with gr.Row() as command_output: - output_textbox = gr.Textbox(label="command",elem_id="outputtext") - - resetFormat=Clear(inputs,inputs_clip) - print(inputs_clip.children) - print(resetFormat) - state=gr.Variable() - clearBtn.click(resetFormat.clear, inputs=resetFormat(), outputs=resetFormat()) - convertBtn.click(convert, inputs=[file_input, options,state], outputs=[ - media_output_audio,media_output_file,media_output_video, output_textbox,state]) - - with gr.TabItem("Video"): - with gr.Row() as video_inputs: - video_options = gr.Dropdown( - label="video", choices=video_codecs,value=video_codecs[-1]) - preset_options = gr.Dropdown(choices=presets, label="presets",value=presets[-1]) - - - with gr.Row(elem_id="button"): - with gr.Column(): - clearBtn = gr.Button("Clear") - videoReset=Clear(video_inputs) - clearBtn.click(videoReset.clear, videoReset(), videoReset()) - - with gr.TabItem("Audio"): - with gr.Row() as audio_inputs: - # print(names[0]) - audio_options = gr.Dropdown( - label="audio", choices=audio_codecs, value=audio_codecs[-1]) - audio_bitrate=gr.Dropdown(choices=audio_quality, label="Audio Qualities", - value=audio_quality[0]) - custom_bitrate=gr.Number(label="Audio Qualities",visible=False) - gr.Dropdown(choices=audio_channels, - label="Audio Channels", value=audio_channels[0]) - gr.Dropdown(choices=audio_sample_rates, - label="Sample Rates", value=audio_sample_rates[0]) - - - with gr.Column(elem_id="button"): - clearBtn = gr.Button("Clear") - audioReset=Clear(audio_inputs) - clearBtn.click(audioReset.clear, audioReset(), audioReset()) - - with gr.TabItem("Filters") as filter_inputs: - gr.Markdown("## Video") - with gr.Row().style(equal_height=True) as filter_inputs: - for i in vf: - # print(i.values()) - # values = list(i.values()) - values=list(i.values())[0] - choices=[j for lst in values for j in [lst.get("name")]] - a=gr.Dropdown(label=list(i.keys()), - choices=choices, value=choices[0]) - gr.Markdown("## Audio") - with gr.Row(elem_id="acontrast") as filter_inputs_1: - acontrastSlider=gr.Slider(label="Acontrast", elem_id="acontrast") - - with gr.Column(elem_id="button"): - clearBtn = gr.Button("Clear") - - filterReset=Clear(filter_inputs,filter_inputs_1) - clearBtn.click(filterReset.clear, filterReset(), filterReset()) - - """ Format Tab change functions""" - ffmpeg_commands=CommandBuilder(inputs_clip,video_inputs,audio_inputs,filter_inputs,filter_inputs_1) - # ffmpeg_commands.do() - dm.load(fn=ffmpeg_commands.reset,inputs=[],outputs=[]) - pprint(ffmpeg_commands.commands) - ffmpeg_commands.update(output_textbox) - # file_input.change(fn=updateOutput,inputs=file_input,outputs=output_textbox) - clip.change(fn=change_clipbox, inputs=clip, - outputs=[start_time, stop_time]) - - options.change(supported_codecs,[options],[video_options,audio_options]) - # options.change(mediaChange,[options],[media_output_audio,media_output_video]) - # video_button.click(fn=videoChange,inputs=media_output_file,outputs=media_output_video) - audio_button.click(mediaChange,[audio_button,state],[media_output_audio,media_output_video,media_output_file]) - video_button.click(mediaChange,[video_button,state],[media_output_audio,media_output_video,media_output_file]) - # media_output_audio.change(lambda x:gr.update(value=x),[media_output_audio],[media_output_video]) - file_button.click(mediaChange,[file_button,state],[media_output_audio,media_output_video,media_output_file]) - """Video Tab change functions""" - video_options.change(supported_presets,[video_options],[preset_options]) - """Audio Tab change functions""" - audio_bitrate.change(customBitrate,[audio_bitrate],[custom_bitrate]) - -if __name__=='__main__': - dm.launch() diff --git a/spaces/AchyuthGamer/OpenGPT/g4f/Provider/Lockchat.py b/spaces/AchyuthGamer/OpenGPT/g4f/Provider/Lockchat.py deleted file mode 100644 index c15eec8dd99f6a50b7eb02cf8ff14494380f4b9a..0000000000000000000000000000000000000000 --- a/spaces/AchyuthGamer/OpenGPT/g4f/Provider/Lockchat.py +++ /dev/null @@ -1,64 +0,0 @@ -from __future__ import annotations - -import json - -import requests - -from ..typing import Any, CreateResult -from .base_provider import BaseProvider - - -class Lockchat(BaseProvider): - url: str = "http://supertest.lockchat.app" - supports_stream = True - supports_gpt_35_turbo = True - supports_gpt_4 = True - - @staticmethod - def create_completion( - model: str, - messages: list[dict[str, str]], - stream: bool, **kwargs: Any) -> CreateResult: - - temperature = float(kwargs.get("temperature", 0.7)) - payload = { - "temperature": temperature, - "messages" : messages, - "model" : model, - "stream" : True, - } - - headers = { - "user-agent": "ChatX/39 CFNetwork/1408.0.4 Darwin/22.5.0", - } - response = requests.post("http://supertest.lockchat.app/v1/chat/completions", - json=payload, headers=headers, stream=True) - - response.raise_for_status() - for token in response.iter_lines(): - if b"The model: `gpt-4` does not exist" in token: - print("error, retrying...") - Lockchat.create_completion( - model = model, - messages = messages, - stream = stream, - temperature = temperature, - **kwargs) - - if b"content" in token: - token = json.loads(token.decode("utf-8").split("data: ")[1]) - token = token["choices"][0]["delta"].get("content") - if token: - yield (token) - - @classmethod - @property - def params(cls): - params = [ - ("model", "str"), - ("messages", "list[dict[str, str]]"), - ("stream", "bool"), - ("temperature", "float"), - ] - param = ", ".join([": ".join(p) for p in params]) - return f"g4f.provider.{cls.__name__} supports: ({param})" diff --git a/spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/rules/base.py b/spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/rules/base.py deleted file mode 100644 index 83028a911d812536d91e04656d2f8056ef942cc8..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/rules/base.py +++ /dev/null @@ -1,98 +0,0 @@ -from __future__ import annotations - -from abc import abstractmethod -from typing import TYPE_CHECKING, Any, List, Optional - -from agentverse.environments.simulation_env.rules.describer import ( - BaseDescriber, - describer_registry, -) -from agentverse.environments.simulation_env.rules.order import BaseOrder, order_registry -from agentverse.environments.simulation_env.rules.selector import ( - BaseSelector, - selector_registry, -) -from agentverse.environments.simulation_env.rules.updater import ( - BaseUpdater, - updater_registry, -) -from agentverse.environments.simulation_env.rules.visibility import ( - BaseVisibility, - visibility_registry, -) -from agentverse.environments import BaseRule - -if TYPE_CHECKING: - from agentverse.environments.base import BaseEnvironment - -from agentverse.message import Message - - -# class Rule(BaseModel): -class SimulationRule(BaseRule): - """ - Rule for the environment. It controls the speaking order of the agents - and maintain the set of visible agents for each agent. - """ - - order: BaseOrder - visibility: BaseVisibility - selector: BaseSelector - updater: BaseUpdater - describer: BaseDescriber - - def __init__( - self, - order_config, - visibility_config, - selector_config, - updater_config, - describer_config, - ): - order = order_registry.build(**order_config) - visibility = visibility_registry.build(**visibility_config) - selector = selector_registry.build(**selector_config) - updater = updater_registry.build(**updater_config) - describer = describer_registry.build(**describer_config) - super().__init__( - order=order, - visibility=visibility, - selector=selector, - updater=updater, - describer=describer, - ) - - def get_next_agent_idx( - self, environment: BaseEnvironment, *args, **kwargs - ) -> List[int]: - """Return the index of the next agent to speak""" - return self.order.get_next_agent_idx(environment, *args, **kwargs) - - def update_visible_agents( - self, environment: BaseEnvironment, *args, **kwargs - ) -> None: - """Update the set of visible agents for the agent""" - self.visibility.update_visible_agents(environment, *args, **kwargs) - - def select_message( - self, environment: BaseEnvironment, messages: List[Message], *args, **kwargs - ) -> List[Message]: - """Select a set of valid messages from all the generated messages""" - return self.selector.select_message(environment, messages, *args, **kwargs) - - def update_memory(self, environment: BaseEnvironment, *args, **kwargs) -> None: - """For each message, add it to the memory of the agent who is able to see that message""" - self.updater.update_memory(environment, *args, **kwargs) - - def get_env_description( - self, environment: BaseEnvironment, *args, **kwargs - ) -> List[str]: - """Return the description of the environment for each agent""" - return self.describer.get_env_description(environment, *args, **kwargs) - - def reset(self) -> None: - self.order.reset() - self.visibility.reset() - self.selector.reset() - self.updater.reset() - self.describer.reset() diff --git a/spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/rules/selector/code_api.py b/spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/rules/selector/code_api.py deleted file mode 100644 index a134b649b3bf215bdf05dd847fdc755b1f0ab24e..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/rules/selector/code_api.py +++ /dev/null @@ -1,97 +0,0 @@ -import io -import sys -import ast -import json -import astunparse -import concurrent.futures -import traceback - - -def get_call_str(assert_statement: str) -> str: - call_str = ast.parse(assert_statement).body[0].test.left # type: ignore - return astunparse.unparse(call_str).strip() - -def get_output(func: str, assert_statement: str) -> str: - try: - func_call = get_call_str(assert_statement) - try: - exec(func, globals()) - output = eval(func_call) - return output - except Exception as e: - return str(e) - except: - return "get_call_str error" - -def worker(code, globals=None, locals=None): - old_stdout = sys.stdout - redirected_output = sys.stdout = io.StringIO() - if locals is None: - locals = {} - try: - # TODO: exec(code, globals, locals) could be buggy - # In cases where both import statement and function exits in the code, if the locals are given, - # the code will not find the imported package. - # For example, - # code = "import math\ndef f(x):\n\treturn math.pow(x, 2)\nassert f(2) == 4" - # It will return "NameError: name 'math' is not defined" - exec(code, locals, locals) - stdout = redirected_output.getvalue() - return stdout, globals, locals - except Exception as e: - trace_str = traceback.format_exc() - return f"Error: {trace_str}", globals, locals - finally: - sys.stdout = old_stdout # restore the original stdout - -def execute_code(code: str) -> str: - """Execute a snippet of python code and return the output or the error message. - """ - timeout = 5 - try: - with concurrent.futures.ThreadPoolExecutor() as executor: - future = executor.submit(worker, code) - result, _, _ = future.result(timeout) - return result - except concurrent.futures.TimeoutError: - return "Timeout" - -def execute_unit_tests(func_impl: str, tests: str) -> str: - """Run a python function on a bunch of unit tests tests and return detailed feedback. - """ - # tests = eval(tests) - # assert type(tests) == list - - # Combine function code and assert statement - func_test_list = [f'{func_impl}\n{test}' for test in tests] - - # Run the tests and collect the results - success_tests = [] - failed_tests = [] - is_passing = True - num_tests = len(func_test_list) - for i in range(num_tests): - output = execute_code(func_test_list[i]) - if output == "Timeout": - failed_tests += [f"{tests[i]} # output: Timeout"] - is_passing = False - elif output.startswith("Error: "): - # print(output) - func_output = get_output(func_impl, tests[i]) - if func_output == "get_call_str error": - func_output = output - failed_tests += [f"{tests[i]} # output: {func_output}"] - is_passing = False - else: - success_tests += [tests[i]] - - feedback = "Tested passed:\n\n" - for test in success_tests: - feedback += f"{test}\n\n" - feedback += "Tests failed:\n\n" - for test in failed_tests: - feedback += f"{test}\n\n" - - return json.dumps({"is_passing": is_passing, - "feedback": feedback}) - diff --git a/spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/rules/visibility/prisoner.py b/spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/rules/visibility/prisoner.py deleted file mode 100644 index c21217312bed0ffd447eeaa115e7eb28d53c680b..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/rules/visibility/prisoner.py +++ /dev/null @@ -1,48 +0,0 @@ -from __future__ import annotations - -import random -from typing import TYPE_CHECKING, Any, List, Union - -from . import visibility_registry as VisibilityRegistry -from .base import BaseVisibility - -if TYPE_CHECKING: - from agentverse.environments import BaseEnvironment - - -@VisibilityRegistry.register("prisoner") -class PrisonerVisibility(BaseVisibility): - """ - Visibility function for classroom, supports group discussion. - - Args: - student_per_group: - The number of students per group. - num_discussion_turn: - The number of turns for group discussion. - grouping: - The grouping information. If it is a string, then it should be a - grouping method, options are ["random", "sequential"]. If it is a - list of list of int, then it should be the grouping information. - """ - - current_turn: int = 0 - - def update_visible_agents(self, environment: BaseEnvironment): - self.update_receiver(environment, reset=False) - - def update_receiver(self, environment: BaseEnvironment, reset=False): - if reset: - for agent in environment.agents: - agent.set_receiver(["all"]) - else: - # 0:police 1: prisoner1 2: prisoner2 - # environment.agents[0].set_receiver({"Police", "Suspect1", "Suspect2"}) - # environment.agents[1].set_receiver({"Police", "Suspect1"}) - # environment.agents[2].set_receiver({"Police", "Suspect2"}) - - # we update receiver in environment - pass - - def reset(self): - self.current_turn = 0 diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/localstorage-data.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/localstorage-data.js deleted file mode 100644 index 898f8f9256f39b30d47106b3afdb158872108e31..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/localstorage-data.js +++ /dev/null @@ -1,2 +0,0 @@ -import DataManager from './storage/localstorage/data/DataManager.js'; -export default DataManager; \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/toucheventstop-plugin.d.ts b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/toucheventstop-plugin.d.ts deleted file mode 100644 index e97fd03909c54fa736961a3b3f55aafbd5bb6c3e..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/toucheventstop-plugin.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import TouchEventStop from './toucheventstop'; - -export default class TouchEventStopPlugin extends Phaser.Plugins.BasePlugin { - add( - gameObject: Phaser.GameObjects.GameObject, - config?: TouchEventStop.IConfig - ): TouchEventStop; - -} \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/spinner/spinner-plugin.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/spinner/spinner-plugin.js deleted file mode 100644 index df5d2cc999cceb328457f68e14f36a0742c04eb3..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/spinner/spinner-plugin.js +++ /dev/null @@ -1,35 +0,0 @@ -import ObjectFactory from './ObjectFactory.js'; - -import AudioFactory from './audio/Factory.js'; -import BallFactory from './ball/Factory.js'; -import BarsFactory from './bars/Factory.js'; -import BoxFactory from './box/Factory.js'; -import ClockFactory from './clock/Factory.js'; -import CubeFactory from './cube/Factory.js'; -import CustomFactory from './custom/Factory.js'; -import DotsFactory from './dots/Factory.js'; -import FacebookFactory from './facebook/Factory.js'; -import GridFactory from './grid/Factory.js'; -import LosFactory from './los/Factory.js'; -import OrbitFactory from './orbit/Factory.js'; -import OvalFactory from './oval/Factory.js'; -import PieFactory from './pie/Factory.js'; -import PuffFactory from './puff/Factory.js'; -import RadioFactory from './radio/Factory.js'; -import RingsFactory from './rings/Factory.js'; -import SpinnerFactory from './spinner/Factory.js'; - - -class SpinnerPlugin extends Phaser.Plugins.ScenePlugin { - constructor(scene, pluginManager) { - super(scene, pluginManager); - - this.add = new ObjectFactory(scene); - } - - start() { - var eventEmitter = this.scene.events; - eventEmitter.on('destroy', this.destroy, this); - } -} -export default SpinnerPlugin; \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/fixwidthsizer/Factory.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/fixwidthsizer/Factory.js deleted file mode 100644 index d32aee99a5a66db03a0cd01d77f01e33ae568cc6..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/fixwidthsizer/Factory.js +++ /dev/null @@ -1,13 +0,0 @@ -import FixWidthSizer from './FixWidthSizer.js'; -import ObjectFactory from '../ObjectFactory.js'; -import SetValue from '../../../plugins/utils/object/SetValue.js'; - -ObjectFactory.register('fixWidthSizer', function (x, y, minWidth, minHeight, config) { - var gameObject = new FixWidthSizer(this.scene, x, y, minWidth, minHeight, config); - this.scene.add.existing(gameObject); - return gameObject; -}); - -SetValue(window, 'RexPlugins.UI.FixWidthSizer', FixWidthSizer); - -export default FixWidthSizer; \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/perspectivecard/PerspectiveCard.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/perspectivecard/PerspectiveCard.js deleted file mode 100644 index a41a970f7d6db8f1cd0dd345e34300d9da1b7fd4..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/perspectivecard/PerspectiveCard.js +++ /dev/null @@ -1,161 +0,0 @@ -import OverlapSizer from '../overlapsizer/OverlapSizer.js'; -import CreatePerspectiveCardMesh from './CreatePerspectiveCardMesh.js'; -import PerspectiveMethods from './PerspectiveMethods.js'; - -const GetValue = Phaser.Utils.Objects.GetValue; - -class PerspectiveCard extends OverlapSizer { - constructor(scene, config) { - super(scene, config); - this.type = 'rexPerspectiveCard'; - - // Layout faces - var backFace = config.back; - var backFaceExpand = GetValue(config, 'expand.back', true); - this.add( - backFace, - { key: 'back', expand: backFaceExpand } - ); - - var frontFace = config.front; - var frontFaceExpand = GetValue(config, 'expand.front', true); - this.add( - frontFace, - { key: 'front', expand: frontFaceExpand } - ); - - // Add PerspectiveCardMesh - this.perspectiveCard = CreatePerspectiveCardMesh.call(this, config); - this.pin(this.perspectiveCard); - - this.exitPerspectiveMode(false); - } - - get flip() { - return this.perspectiveCard.flip; - } - - get face() { - return this.perspectiveCard.face; - } - - set face(index) { - // Can't set face during flipping - if (this.flip && this.flip.isRunning) { - return; - } - this.perspectiveCard.face = index; - - var isFrontFace = (index === 0); - var frontFace = this.childrenMap.front; - var backFace = this.childrenMap.back; - this.setChildVisible(frontFace, isFrontFace); - this.setChildVisible(backFace, !isFrontFace); - } - - setFace(face) { - this.face = face; - return this; - } - - toggleFace() { - var newFace = (this.face === 0) ? 1 : 0; - this.setFace(newFace); - return this; - } - - get isInPerspectiveMode() { - return this.perspectiveCard.visible; - } - - get rotationX() { - return this.perspectiveCard.rotationX; - } - - set rotationX(value) { - this.enterPerspectiveMode(); - this.perspectiveCard.rotationX = value; - } - - get angleX() { - return this.perspectiveCard.angleX; - } - - set angleX(value) { - this.enterPerspectiveMode(); - this.perspectiveCard.angleX = value; - } - - get rotationY() { - return this.perspectiveCard.rotationY; - } - - set rotationY(value) { - this.enterPerspectiveMode(); - this.perspectiveCard.rotationY = value; - } - - get angleY() { - return this.perspectiveCard.angleY; - } - - set angleY(value) { - this.enterPerspectiveMode(); - this.perspectiveCard.angleY = value; - } - - get rotationZ() { - return this.perspectiveCard.rotationZ; - } - - set rotationZ(value) { - this.enterPerspectiveMode(); - this.perspectiveCard.rotationZ = value; - } - - get angleZ() { - return this.perspectiveCard.angleZ; - } - - set angleZ(value) { - this.enterPerspectiveMode(); - this.perspectiveCard.angleZ = value; - } - - panX(v) { - this.enterPerspectiveMode(); - this.perspectiveCard.panX(v); - return this; - } - - panY(v) { - this.enterPerspectiveMode(); - this.perspectiveCard.panY(v); - return this; - } - - panZ(v) { - this.enterPerspectiveMode(); - this.perspectiveCard.panZ(v); - return this; - } - - transformVerts(x, y, z, rotateX, rotateY, rotateZ) { - this.enterPerspectiveMode(); - this.perspectiveCard.transformVerts(x, y, z, rotateX, rotateY, rotateZ); - return this; - } - - forEachFace(callback, scope, ignoreInvalid) { - this.enterPerspectiveMode(); - this.perspectiveCard.forEachFace(callback, scope, ignoreInvalid); - return this; - } -} - -Object.assign( - PerspectiveCard.prototype, - PerspectiveMethods -) - -export default PerspectiveCard; \ No newline at end of file diff --git a/spaces/Akmyradov/TurkmenTTSweSTT/vits/utils.py b/spaces/Akmyradov/TurkmenTTSweSTT/vits/utils.py deleted file mode 100644 index b445fb65836a0b97e46426300eea9a820179797a..0000000000000000000000000000000000000000 --- a/spaces/Akmyradov/TurkmenTTSweSTT/vits/utils.py +++ /dev/null @@ -1,258 +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): - 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 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, required=True, - help='Model name') - - args = parser.parse_args() - model_dir = os.path.join("./logs", args.model) - - if not os.path.exists(model_dir): - os.makedirs(model_dir) - - config_path = args.config - config_save_path = os.path.join(model_dir, "config.json") - if init: - with open(config_path, "r") as f: - data = f.read() - with open(config_save_path, "w") as f: - f.write(data) - else: - with open(config_save_path, "r") as f: - data = f.read() - config = json.loads(data) - - hparams = HParams(**config) - hparams.model_dir = model_dir - return hparams - - -def get_hparams_from_dir(model_dir): - config_save_path = os.path.join(model_dir, "config.json") - with open(config_save_path, "r") as f: - data = f.read() - config = json.loads(data) - - hparams =HParams(**config) - hparams.model_dir = model_dir - return hparams - - -def get_hparams_from_file(config_path): - with open(config_path, "r") as f: - data = f.read() - config = json.loads(data) - - hparams =HParams(**config) - return hparams - - -def check_git_hash(model_dir): - source_dir = os.path.dirname(os.path.realpath(__file__)) - if not os.path.exists(os.path.join(source_dir, ".git")): - logger.warn("{} is not a git repository, therefore hash value comparison will be ignored.".format( - source_dir - )) - return - - cur_hash = subprocess.getoutput("git rev-parse HEAD") - - path = os.path.join(model_dir, "githash") - if os.path.exists(path): - saved_hash = open(path).read() - if saved_hash != cur_hash: - logger.warn("git hash values are different. {}(saved) != {}(current)".format( - saved_hash[:8], cur_hash[:8])) - else: - open(path, "w").write(cur_hash) - - -def get_logger(model_dir, filename="train.log"): - global logger - logger = logging.getLogger(os.path.basename(model_dir)) - logger.setLevel(logging.DEBUG) - - formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s") - if not os.path.exists(model_dir): - os.makedirs(model_dir) - h = logging.FileHandler(os.path.join(model_dir, filename)) - h.setLevel(logging.DEBUG) - h.setFormatter(formatter) - logger.addHandler(h) - return logger - - -class HParams(): - def __init__(self, **kwargs): - for k, v in kwargs.items(): - if type(v) == dict: - v = HParams(**v) - self[k] = v - - def keys(self): - return self.__dict__.keys() - - def items(self): - return self.__dict__.items() - - def values(self): - return self.__dict__.values() - - def __len__(self): - return len(self.__dict__) - - def __getitem__(self, key): - return getattr(self, key) - - def __setitem__(self, key, value): - return setattr(self, key, value) - - def __contains__(self, key): - return key in self.__dict__ - - def __repr__(self): - return self.__dict__.__repr__() diff --git a/spaces/Al-Chan/Vits_League_of_Legends_Yuumi_TTS/models_infer.py b/spaces/Al-Chan/Vits_League_of_Legends_Yuumi_TTS/models_infer.py deleted file mode 100644 index 4b9bb82bf5831c5264f3e1e52b23e8e875f5fd9e..0000000000000000000000000000000000000000 --- a/spaces/Al-Chan/Vits_League_of_Legends_Yuumi_TTS/models_infer.py +++ /dev/null @@ -1,402 +0,0 @@ -import math -import torch -from torch import nn -from torch.nn import functional as F - -import commons -import modules -import attentions - -from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d -from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm -from commons import init_weights, get_padding - - -class StochasticDurationPredictor(nn.Module): - def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0): - super().__init__() - filter_channels = in_channels # it needs to be removed from future version. - self.in_channels = in_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.log_flow = modules.Log() - self.flows = nn.ModuleList() - self.flows.append(modules.ElementwiseAffine(2)) - for i in range(n_flows): - self.flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)) - self.flows.append(modules.Flip()) - - self.post_pre = nn.Conv1d(1, filter_channels, 1) - self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1) - self.post_convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout) - self.post_flows = nn.ModuleList() - self.post_flows.append(modules.ElementwiseAffine(2)) - for i in range(4): - self.post_flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)) - self.post_flows.append(modules.Flip()) - - self.pre = nn.Conv1d(in_channels, filter_channels, 1) - self.proj = nn.Conv1d(filter_channels, filter_channels, 1) - self.convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout) - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, filter_channels, 1) - - def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0): - x = torch.detach(x) - x = self.pre(x) - if g is not None: - g = torch.detach(g) - x = x + self.cond(g) - x = self.convs(x, x_mask) - x = self.proj(x) * x_mask - - if not reverse: - flows = self.flows - assert w is not None - - logdet_tot_q = 0 - h_w = self.post_pre(w) - h_w = self.post_convs(h_w, x_mask) - h_w = self.post_proj(h_w) * x_mask - e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask - z_q = e_q - for flow in self.post_flows: - z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w)) - logdet_tot_q += logdet_q - z_u, z1 = torch.split(z_q, [1, 1], 1) - u = torch.sigmoid(z_u) * x_mask - z0 = (w - u) * x_mask - logdet_tot_q += torch.sum((F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1,2]) - logq = torch.sum(-0.5 * (math.log(2*math.pi) + (e_q**2)) * x_mask, [1,2]) - logdet_tot_q - - logdet_tot = 0 - z0, logdet = self.log_flow(z0, x_mask) - logdet_tot += logdet - z = torch.cat([z0, z1], 1) - for flow in flows: - z, logdet = flow(z, x_mask, g=x, reverse=reverse) - logdet_tot = logdet_tot + logdet - nll = torch.sum(0.5 * (math.log(2*math.pi) + (z**2)) * x_mask, [1,2]) - logdet_tot - return nll + logq # [b] - else: - flows = list(reversed(self.flows)) - flows = flows[:-2] + [flows[-1]] # remove a useless vflow - z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale - for flow in flows: - z = flow(z, x_mask, g=x, reverse=reverse) - z0, z1 = torch.split(z, [1, 1], 1) - logw = z0 - return logw - - -class DurationPredictor(nn.Module): - def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0): - super().__init__() - - self.in_channels = in_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.gin_channels = gin_channels - - self.drop = nn.Dropout(p_dropout) - self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size//2) - self.norm_1 = modules.LayerNorm(filter_channels) - self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2) - self.norm_2 = modules.LayerNorm(filter_channels) - self.proj = nn.Conv1d(filter_channels, 1, 1) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, in_channels, 1) - - def forward(self, x, x_mask, g=None): - x = torch.detach(x) - if g is not None: - g = torch.detach(g) - x = x + self.cond(g) - x = self.conv_1(x * x_mask) - x = torch.relu(x) - x = self.norm_1(x) - x = self.drop(x) - x = self.conv_2(x * x_mask) - x = torch.relu(x) - x = self.norm_2(x) - x = self.drop(x) - x = self.proj(x * x_mask) - return x * x_mask - - -class TextEncoder(nn.Module): - def __init__(self, - n_vocab, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout): - super().__init__() - self.n_vocab = n_vocab - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - - self.emb = nn.Embedding(n_vocab, hidden_channels) - nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5) - - self.encoder = attentions.Encoder( - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout) - self.proj= nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, x, x_lengths): - x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h] - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype) - - x = self.encoder(x * x_mask, x_mask) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return x, m, logs, x_mask - - -class ResidualCouplingBlock(nn.Module): - def __init__(self, - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - n_flows=4, - gin_channels=0): - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.flows = nn.ModuleList() - for i in range(n_flows): - self.flows.append(modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels, mean_only=True)) - self.flows.append(modules.Flip()) - - def forward(self, x, x_mask, g=None, reverse=False): - if not reverse: - for flow in self.flows: - x, _ = flow(x, x_mask, g=g, reverse=reverse) - else: - for flow in reversed(self.flows): - x = flow(x, x_mask, g=g, reverse=reverse) - return x - - -class PosteriorEncoder(nn.Module): - def __init__(self, - in_channels, - out_channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=0): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.gin_channels = gin_channels - - self.pre = nn.Conv1d(in_channels, hidden_channels, 1) - self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, x, x_lengths, g=None): - x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype) - x = self.pre(x) * x_mask - x = self.enc(x, x_mask, g=g) - stats = self.proj(x) * x_mask - m, logs = torch.split(stats, self.out_channels, dim=1) - z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask - return z, m, logs, x_mask - - -class Generator(torch.nn.Module): - def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=0): - super(Generator, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3) - resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - self.ups.append(weight_norm( - ConvTranspose1d(upsample_initial_channel//(2**i), upsample_initial_channel//(2**(i+1)), - k, u, padding=(k-u)//2))) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel//(2**(i+1)) - for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - def forward(self, x, g=None): - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i*self.num_kernels+j](x) - else: - xs += self.resblocks[i*self.num_kernels+j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - - return x - - def remove_weight_norm(self): - print('Removing weight norm...') - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - - -class SynthesizerTrn(nn.Module): - """ - Synthesizer for Training - """ - - def __init__(self, - n_vocab, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - n_speakers=0, - gin_channels=0, - use_sdp=True, - **kwargs): - - super().__init__() - self.n_vocab = n_vocab - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.n_speakers = n_speakers - self.gin_channels = gin_channels - - self.use_sdp = use_sdp - - self.enc_p = TextEncoder(n_vocab, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout) - self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels) - self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels) - self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels) - - if use_sdp: - self.dp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels) - else: - self.dp = DurationPredictor(hidden_channels, 256, 3, 0.5, gin_channels=gin_channels) - - if n_speakers > 1: - self.emb_g = nn.Embedding(n_speakers, gin_channels) - - def infer(self, x, x_lengths, sid=None, noise_scale=1, length_scale=1, noise_scale_w=1., max_len=None): - x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths) - if self.n_speakers > 0: - g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1] - else: - g = None - - if self.use_sdp: - logw = self.dp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w) - else: - logw = self.dp(x, x_mask, g=g) - w = torch.exp(logw) * x_mask * length_scale - w_ceil = torch.ceil(w) - y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long() - y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype) - attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1) - attn = commons.generate_path(w_ceil, attn_mask) - - m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t'] - logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t'] - - z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale - z = self.flow(z_p, y_mask, g=g, reverse=True) - o = self.dec((z * y_mask)[:,:,:max_len], g=g) - return o, attn, y_mask, (z, z_p, m_p, logs_p) - - def voice_conversion(self, y, y_lengths, sid_src, sid_tgt): - assert self.n_speakers > 0, "n_speakers have to be larger than 0." - g_src = self.emb_g(sid_src).unsqueeze(-1) - g_tgt = self.emb_g(sid_tgt).unsqueeze(-1) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g_src) - z_p = self.flow(z, y_mask, g=g_src) - z_hat = self.flow(z_p, y_mask, g=g_tgt, reverse=True) - o_hat = self.dec(z_hat * y_mask, g=g_tgt) - return o_hat, y_mask, (z, z_p, z_hat) - diff --git a/spaces/Alichuan/VITS-Umamusume-voice-synthesizer/text/symbols.py b/spaces/Alichuan/VITS-Umamusume-voice-synthesizer/text/symbols.py deleted file mode 100644 index 053a7105f7ce95aa51614f6995399fa2172b3eb2..0000000000000000000000000000000000000000 --- a/spaces/Alichuan/VITS-Umamusume-voice-synthesizer/text/symbols.py +++ /dev/null @@ -1,76 +0,0 @@ -''' -Defines the set of symbols used in text input to the model. -''' - -# japanese_cleaners -_pad = '_' -_punctuation = ',.!?-' -_letters = 'AEINOQUabdefghijkmnoprstuvwyzʃʧ↓↑ ' - - -'''# japanese_cleaners2 -_pad = '_' -_punctuation = ',.!?-~…' -_letters = 'AEINOQUabdefghijkmnoprstuvwyzʃʧʦ↓↑ ' -''' - - -'''# korean_cleaners -_pad = '_' -_punctuation = ',.!?…~' -_letters = 'ㄱㄴㄷㄹㅁㅂㅅㅇㅈㅊㅋㅌㅍㅎㄲㄸㅃㅆㅉㅏㅓㅗㅜㅡㅣㅐㅔ ' -''' - -'''# chinese_cleaners -_pad = '_' -_punctuation = ',。!?—…' -_letters = 'ㄅㄆㄇㄈㄉㄊㄋㄌㄍㄎㄏㄐㄑㄒㄓㄔㄕㄖㄗㄘㄙㄚㄛㄜㄝㄞㄟㄠㄡㄢㄣㄤㄥㄦㄧㄨㄩˉˊˇˋ˙ ' -''' - -'''# zh_ja_mixture_cleaners -_pad = '_' -_punctuation = ',.!?-~…' -_letters = 'AEINOQUabdefghijklmnoprstuvwyzʃʧʦɯɹəɥ⁼ʰ`→↓↑ ' -''' - -'''# sanskrit_cleaners -_pad = '_' -_punctuation = '।' -_letters = 'ँंःअआइईउऊऋएऐओऔकखगघङचछजझञटठडढणतथदधनपफबभमयरलळवशषसहऽािीुूृॄेैोौ्ॠॢ ' -''' - -'''# cjks_cleaners -_pad = '_' -_punctuation = ',.!?-~…' -_letters = 'NQabdefghijklmnopstuvwxyzʃʧʥʦɯɹəɥçɸɾβŋɦː⁼ʰ`^#*=→↓↑ ' -''' - -'''# thai_cleaners -_pad = '_' -_punctuation = '.!? ' -_letters = 'กขฃคฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลวศษสหฬอฮฯะัาำิีึืุูเแโใไๅๆ็่้๊๋์' -''' - -'''# cjke_cleaners2 -_pad = '_' -_punctuation = ',.!?-~…' -_letters = 'NQabdefghijklmnopstuvwxyzɑæʃʑçɯɪɔɛɹðəɫɥɸʊɾʒθβŋɦ⁼ʰ`^#*=ˈˌ→↓↑ ' -''' - -'''# shanghainese_cleaners -_pad = '_' -_punctuation = ',.!?…' -_letters = 'abdfghiklmnopstuvyzøŋȵɑɔɕəɤɦɪɿʑʔʰ̩̃ᴀᴇ15678 ' -''' - -'''# chinese_dialect_cleaners -_pad = '_' -_punctuation = ',.!?~…─' -_letters = '#Nabdefghijklmnoprstuvwxyzæçøŋœȵɐɑɒɓɔɕɗɘəɚɛɜɣɤɦɪɭɯɵɷɸɻɾɿʂʅʊʋʌʏʑʔʦʮʰʷˀː˥˦˧˨˩̥̩̃̚ᴀᴇ↑↓∅ⱼ ' -''' - -# Export all symbols: -symbols = [_pad] + list(_punctuation) + list(_letters) - -# Special symbol ids -SPACE_ID = symbols.index(" ") diff --git a/spaces/Aloento/9Nine-PITS/analysis.py b/spaces/Aloento/9Nine-PITS/analysis.py deleted file mode 100644 index b9ea9a868f89d50d7dde8702771eeeabc4298502..0000000000000000000000000000000000000000 --- a/spaces/Aloento/9Nine-PITS/analysis.py +++ /dev/null @@ -1,141 +0,0 @@ -# modified from https://github.com/dhchoi99/NANSY -# We have modified the implementation of dhchoi99 to be fully differentiable. -import math - -from yin import * - - -class Pitch(torch.nn.Module): - - def __init__( - self, - sr=22050, - w_step=256, - W=2048, - tau_max=2048, - midi_start=5, - midi_end=85, - octave_range=12): - super(Pitch, self).__init__() - self.sr = sr - self.w_step = w_step - self.W = W - self.tau_max = tau_max - self.unfold = torch.nn.Unfold((1, self.W), - 1, - 0, - stride=(1, self.w_step)) - midis = list(range(midi_start, midi_end)) - self.len_midis = len(midis) - c_ms = torch.tensor([self.midi_to_lag(m, octave_range) for m in midis]) - self.register_buffer('c_ms', c_ms) - self.register_buffer('c_ms_ceil', torch.ceil(self.c_ms).long()) - self.register_buffer('c_ms_floor', torch.floor(self.c_ms).long()) - - def midi_to_lag(self, m: int, octave_range: float = 12): - """converts midi-to-lag, eq. (4) - - Args: - m: midi - sr: sample_rate - octave_range: - - Returns: - lag: time lag(tau, c(m)) calculated from midi, eq. (4) - - """ - f = 440 * math.pow(2, (m - 69) / octave_range) - lag = self.sr / f - return lag - - def yingram_from_cmndf(self, cmndfs: torch.Tensor) -> torch.Tensor: - """ yingram calculator from cMNDFs(cumulative Mean Normalized Difference Functions) - - Args: - cmndfs: torch.Tensor - calculated cumulative mean normalized difference function - for details, see models/yin.py or eq. (1) and (2) - ms: list of midi(int) - sr: sampling rate - - Returns: - y: - calculated batch yingram - - - """ - # c_ms = np.asarray([Pitch.midi_to_lag(m, sr) for m in ms]) - # c_ms = torch.from_numpy(c_ms).to(cmndfs.device) - - y = (cmndfs[:, self.c_ms_ceil] - - cmndfs[:, self.c_ms_floor]) / (self.c_ms_ceil - self.c_ms_floor).unsqueeze(0) * ( - self.c_ms - self.c_ms_floor).unsqueeze(0) + cmndfs[:, self.c_ms_floor] - return y - - def yingram(self, x: torch.Tensor): - """calculates yingram from raw audio (multi segment) - - Args: - x: raw audio, torch.Tensor of shape (t) - W: yingram Window Size - tau_max: - sr: sampling rate - w_step: yingram bin step size - - Returns: - yingram: yingram. torch.Tensor of shape (80 x t') - - """ - # x.shape: t -> B,T, B,T = x.shape - B, T = x.shape - w_len = self.W - - frames = self.unfold(x.view(B, 1, 1, T)) - frames = frames.permute(0, 2, - 1).contiguous().view(-1, - self.W) # [B* frames, W] - # If not using gpu, or torch not compatible, implemented numpy batch function is still fine - dfs = differenceFunctionTorch(frames, frames.shape[-1], self.tau_max) - cmndfs = cumulativeMeanNormalizedDifferenceFunctionTorch( - dfs, self.tau_max) - yingram = self.yingram_from_cmndf(cmndfs) # [B*frames,F] - yingram = yingram.view(B, -1, self.len_midis).permute(0, 2, - 1) # [B,F,T] - return yingram - - def crop_scope(self, x, yin_start, - scope_shift): # x: tensor [B,C,T] #scope_shift: tensor [B] - return torch.stack([ - x[i, yin_start + scope_shift[i]:yin_start + self.yin_scope + - scope_shift[i], :] for i in range(x.shape[0]) - ], - dim=0) - - -if __name__ == '__main__': - import torch - import librosa as rosa - import matplotlib.pyplot as plt - - wav = torch.tensor(rosa.load('LJ001-0002.wav', sr=22050, - mono=True)[0]).unsqueeze(0) - # wav = torch.randn(1,40965) - - wav = torch.nn.functional.pad(wav, (0, (-wav.shape[1]) % 256)) - # wav = wav[#:,:8096] - print(wav.shape) - pitch = Pitch() - - with torch.no_grad(): - ps = pitch.yingram(torch.nn.functional.pad(wav, (1024, 1024))) - ps = torch.nn.functional.pad(ps, (0, 0, 8, 8), mode='replicate') - print(ps.shape) - spec = torch.stft(wav, 1024, 256, return_complex=False) - print(spec.shape) - plt.subplot(2, 1, 1) - plt.pcolor(ps[0].numpy(), cmap='magma') - plt.colorbar() - plt.subplot(2, 1, 2) - plt.pcolor(ps[0][15:65, :].numpy(), cmap='magma') - plt.colorbar() - plt.show() diff --git a/spaces/Amrrs/portfolio/style.css b/spaces/Amrrs/portfolio/style.css deleted file mode 100644 index 363d0b7bb0dd45552039e3156a6350989e327db2..0000000000000000000000000000000000000000 --- a/spaces/Amrrs/portfolio/style.css +++ /dev/null @@ -1,190 +0,0 @@ -html { - margin: 0; - padding: 0; -} - -body { - font-family: 'Bellota', cursive; - font-size: 26pt; - background-color: #f2f2f2; - padding: 20px; - margin: 0; -} - -h1 { - font-size: 15pt; - color: #ffffff; - text-align: center; - padding: 18px 0 18px 0; - margin: 0 0 10px 0; -} - -h1 span { - border: 8px solid #666666; - border-radius: 8px; - background-image: url("https://media.giphy.com/media/KVZWZQoS0yqfIiTAKq/giphy.gif"); - padding: 12px; -} - -p { - padding: 0; - margin: 0; - color: #000000; -} - -.img-circle { - border: 8px solid white; - border-radius: 50%; -} - -.section { - background-color: #fff; - padding: 20px; - margin-bottom: 10px; - border-radius: 30px; -} - -#header { - background-image: url("https://media.giphy.com/media/KVZWZQoS0yqfIiTAKq/giphy.gif"); - background-size: cover; -} - -#header img { - display: block; - width: 500px; - height: 500px; - margin: auto; -} - -#header p { - font-size: 60pt; - color: #ffffff; - padding-top: 8px; - margin: 0; - font-weight: bold; - text-align: center; -} - -.quote { - font-size: 12pt; - text-align: right; - margin-top: 10px; - color: grey; -} - -#res { - text-align: center; - margin: 50px auto; -} - -#res a { - margin: 20px 20px; - display: inline-block; - text-decoration: none; - color: black; -} - -.selected { - background-color: #f36f48; - font-weight: bold; - color: white; -} - -li { - margin-bottom: 15px; - font-weight: bold; -} - -progress { - width: 70%; - height: 20px; - color: #3fb6b2; - background: #efefef; -} - -progress::-webkit-progress-bar { - background: #efefef; -} - -progress::-webkit-progress-value { - background: #3fb6b2; -} - -progress::-moz-progress-bar { - color: #3fb6b2; - background: #efefef; -} - -iframe, -audio { - display: block; - margin: 0 auto; - border: 3px solid #3fb6b2; - border-radius: 10px; -} - -hr { - border: 0; - height: 1px; - background: #f36f48; -} - -input { - text-align: center; - font-size: 25pt; - border: none; - border-radius: 12px; - padding: 30px 8%; - margin: 20px 5px 10px 5px; - background-color: #d7d7d7; -} - -input:focus { - background-color: #2f2f2f; - color: white; -} - -form { - text-align: center; - font-size: 30pt; - font-family: Helvetica; - font-weight: 500; - margin: 10% 15% 8% 15%; - border-radius: 12px; -} - -#insta-image { - display: block; - width: 100px; - height: 100px; - border: 5px solid #d7d7d7; - border-radius: 50%; - margin: auto; - margin-top: -75px; -} - -#contacts img { - height: 150px; - width: 150px; - margin-left: 7px; - margin-right: 7px; -} - -#contacts a { - text-decoration: none; -} - -#contacts img:hover { - opacity: 0.8; -} - -#contacts { - text-align: center; -} - -.copyright { - font-size: 8pt; - text-align: right; - padding-bottom: 10px; - color: grey; -} \ No newline at end of file diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/examples/controlnet/README_sdxl.md b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/examples/controlnet/README_sdxl.md deleted file mode 100644 index db8dada65427ddf2835fdeb667efa03febceb1fb..0000000000000000000000000000000000000000 --- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/examples/controlnet/README_sdxl.md +++ /dev/null @@ -1,131 +0,0 @@ -# DreamBooth training example for Stable Diffusion XL (SDXL) - -The `train_controlnet_sdxl.py` script shows how to implement the training procedure and adapt it for [Stable Diffusion XL](https://huggingface.co/papers/2307.01952). - -## Running locally with PyTorch - -### Installing the dependencies - -Before running the scripts, make sure to install the library's training dependencies: - -**Important** - -To make sure you can successfully run the latest versions of the example scripts, we highly recommend **installing from source** and keeping the install up to date as we update the example scripts frequently and install some example-specific requirements. To do this, execute the following steps in a new virtual environment: - -```bash -git clone https://github.com/huggingface/diffusers -cd diffusers -pip install -e . -``` - -Then cd in the `examples/controlnet` folder and run -```bash -pip install -r requirements_sdxl.txt -``` - -And initialize an [🤗Accelerate](https://github.com/huggingface/accelerate/) environment with: - -```bash -accelerate config -``` - -Or for a default accelerate configuration without answering questions about your environment - -```bash -accelerate config default -``` - -Or if your environment doesn't support an interactive shell (e.g., a notebook) - -```python -from accelerate.utils import write_basic_config -write_basic_config() -``` - -When running `accelerate config`, if we specify torch compile mode to True there can be dramatic speedups. - -## Circle filling dataset - -The original dataset is hosted in the [ControlNet repo](https://huggingface.co/lllyasviel/ControlNet/blob/main/training/fill50k.zip). We re-uploaded it to be compatible with `datasets` [here](https://huggingface.co/datasets/fusing/fill50k). Note that `datasets` handles dataloading within the training script. - -## Training - -Our training examples use two test conditioning images. They can be downloaded by running - -```sh -wget https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/controlnet_training/conditioning_image_1.png - -wget https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/controlnet_training/conditioning_image_2.png -``` - -Then run `huggingface-cli login` to log into your Hugging Face account. This is needed to be able to push the trained ControlNet parameters to Hugging Face Hub. - -```bash -export MODEL_DIR="stabilityai/stable-diffusion-xl-base-1.0" -export OUTPUT_DIR="path to save model" - -accelerate launch train_controlnet_sdxl.py \ - --pretrained_model_name_or_path=$MODEL_DIR \ - --output_dir=$OUTPUT_DIR \ - --dataset_name=fusing/fill50k \ - --mixed_precision="fp16" \ - --resolution=1024 \ - --learning_rate=1e-5 \ - --max_train_steps=15000 \ - --validation_image "./conditioning_image_1.png" "./conditioning_image_2.png" \ - --validation_prompt "red circle with blue background" "cyan circle with brown floral background" \ - --validation_steps=100 \ - --train_batch_size=1 \ - --gradient_accumulation_steps=4 \ - --report_to="wandb" \ - --seed=42 \ - --push_to_hub -``` - -To better track our training experiments, we're using the following flags in the command above: - -* `report_to="wandb` will ensure the training runs are tracked on Weights and Biases. To use it, be sure to install `wandb` with `pip install wandb`. -* `validation_image`, `validation_prompt`, and `validation_steps` to allow the script to do a few validation inference runs. This allows us to qualitatively check if the training is progressing as expected. - -Our experiments were conducted on a single 40GB A100 GPU. - -### Inference - -Once training is done, we can perform inference like so: - -```python -from diffusers import StableDiffusionXLControlNetPipeline, ControlNetModel, UniPCMultistepScheduler -from diffusers.utils import load_image -import torch - -base_model_path = "stabilityai/stable-diffusion-xl-base-1.0" -controlnet_path = "path to controlnet" - -controlnet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=torch.float16) -pipe = StableDiffusionXLControlNetPipeline.from_pretrained( - base_model_path, controlnet=controlnet, torch_dtype=torch.float16 -) - -# speed up diffusion process with faster scheduler and memory optimization -pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config) -# remove following line if xformers is not installed or when using Torch 2.0. -pipe.enable_xformers_memory_efficient_attention() -# memory optimization. -pipe.enable_model_cpu_offload() - -control_image = load_image("./conditioning_image_1.png") -prompt = "pale golden rod circle with old lace background" - -# generate image -generator = torch.manual_seed(0) -image = pipe( - prompt, num_inference_steps=20, generator=generator, image=control_image -).images[0] -image.save("./output.png") -``` - -## Notes - -### Specifying a better VAE - -SDXL's VAE is known to suffer from numerical instability issues. This is why we also expose a CLI argument namely `--pretrained_vae_model_name_or_path` that lets you specify the location of a better VAE (such as [this one](https://huggingface.co/madebyollin/sdxl-vae-fp16-fix)). \ No newline at end of file diff --git a/spaces/Andy1621/uniformer_image_detection/configs/cascade_rcnn/cascade_mask_rcnn_x101_64x4d_fpn_1x_coco.py b/spaces/Andy1621/uniformer_image_detection/configs/cascade_rcnn/cascade_mask_rcnn_x101_64x4d_fpn_1x_coco.py deleted file mode 100644 index 33629ee6cc2b903407372d68c6d7ab599fe6598e..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_detection/configs/cascade_rcnn/cascade_mask_rcnn_x101_64x4d_fpn_1x_coco.py +++ /dev/null @@ -1,13 +0,0 @@ -_base_ = './cascade_mask_rcnn_r50_fpn_1x_coco.py' -model = dict( - pretrained='open-mmlab://resnext101_64x4d', - backbone=dict( - type='ResNeXt', - depth=101, - groups=64, - base_width=4, - num_stages=4, - out_indices=(0, 1, 2, 3), - frozen_stages=1, - norm_cfg=dict(type='BN', requires_grad=True), - style='pytorch')) diff --git a/spaces/Andy1621/uniformer_image_detection/configs/deepfashion/README.md b/spaces/Andy1621/uniformer_image_detection/configs/deepfashion/README.md deleted file mode 100644 index c182bea0f2924a4d96bca6ea15eebeb36fce8027..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_detection/configs/deepfashion/README.md +++ /dev/null @@ -1,56 +0,0 @@ -# DeepFashion - -[DATASET] - -[MMFashion](https://github.com/open-mmlab/mmfashion) develops "fashion parsing and segmentation" module -based on the dataset -[DeepFashion-Inshop](https://drive.google.com/drive/folders/0B7EVK8r0v71pVDZFQXRsMDZCX1E?usp=sharing). -Its annotation follows COCO style. -To use it, you need to first download the data. Note that we only use "img_highres" in this task. -The file tree should be like this: - -```sh -mmdetection -├── mmdet -├── tools -├── configs -├── data -│ ├── DeepFashion -│ │ ├── In-shop -│ │ ├── Anno -│ │ │   ├── segmentation -│ │ │   | ├── DeepFashion_segmentation_train.json -│ │ │   | ├── DeepFashion_segmentation_query.json -│ │ │   | ├── DeepFashion_segmentation_gallery.json -│ │ │   ├── list_bbox_inshop.txt -│ │ │   ├── list_description_inshop.json -│ │ │   ├── list_item_inshop.txt -│ │ │   └── list_landmarks_inshop.txt -│ │ ├── Eval -│ │ │ └── list_eval_partition.txt -│ │ ├── Img -│ │ │ ├── img -│ │ │ │ ├──XXX.jpg -│ │ │ ├── img_highres -│ │ │ └── ├──XXX.jpg - -``` - -After that you can train the Mask RCNN r50 on DeepFashion-In-shop dataset by launching training with the `mask_rcnn_r50_fpn_1x.py` config -or creating your own config file. - -``` -@inproceedings{liuLQWTcvpr16DeepFashion, - author = {Liu, Ziwei and Luo, Ping and Qiu, Shi and Wang, Xiaogang and Tang, Xiaoou}, - title = {DeepFashion: Powering Robust Clothes Recognition and Retrieval with Rich Annotations}, - booktitle = {Proceedings of IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, - month = {June}, - year = {2016} -} -``` - -## Model Zoo - -| Backbone | Model type | Dataset | bbox detection Average Precision | segmentation Average Precision | Config | Download (Google) | -| :---------: | :----------: | :-----------------: | :--------------------------------: | :----------------------------: | :---------:| :-------------------------: | -| ResNet50 | Mask RCNN | DeepFashion-In-shop | 0.599 | 0.584 |[config](https://github.com/open-mmlab/mmdetection/blob/master/configs/deepfashion/mask_rcnn_r50_fpn_15e_deepfashion.py)| [model](https://drive.google.com/open?id=1q6zF7J6Gb-FFgM87oIORIt6uBozaXp5r) | [log](https://drive.google.com/file/d/1qTK4Dr4FFLa9fkdI6UVko408gkrfTRLP/view?usp=sharing) | diff --git a/spaces/Andy1621/uniformer_image_detection/mmdet/models/roi_heads/__init__.py b/spaces/Andy1621/uniformer_image_detection/mmdet/models/roi_heads/__init__.py deleted file mode 100644 index ca0a38ec42cd41fbd97e07589a13d1af46f47f2f..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_detection/mmdet/models/roi_heads/__init__.py +++ /dev/null @@ -1,34 +0,0 @@ -from .base_roi_head import BaseRoIHead -from .bbox_heads import (BBoxHead, ConvFCBBoxHead, DoubleConvFCBBoxHead, - SCNetBBoxHead, Shared2FCBBoxHead, - Shared4Conv1FCBBoxHead) -from .cascade_roi_head import CascadeRoIHead -from .double_roi_head import DoubleHeadRoIHead -from .dynamic_roi_head import DynamicRoIHead -from .grid_roi_head import GridRoIHead -from .htc_roi_head import HybridTaskCascadeRoIHead -from .mask_heads import (CoarseMaskHead, FCNMaskHead, FeatureRelayHead, - FusedSemanticHead, GlobalContextHead, GridHead, - HTCMaskHead, MaskIoUHead, MaskPointHead, - SCNetMaskHead, SCNetSemanticHead) -from .mask_scoring_roi_head import MaskScoringRoIHead -from .pisa_roi_head import PISARoIHead -from .point_rend_roi_head import PointRendRoIHead -from .roi_extractors import SingleRoIExtractor -from .scnet_roi_head import SCNetRoIHead -from .shared_heads import ResLayer -from .sparse_roi_head import SparseRoIHead -from .standard_roi_head import StandardRoIHead -from .trident_roi_head import TridentRoIHead - -__all__ = [ - 'BaseRoIHead', 'CascadeRoIHead', 'DoubleHeadRoIHead', 'MaskScoringRoIHead', - 'HybridTaskCascadeRoIHead', 'GridRoIHead', 'ResLayer', 'BBoxHead', - 'ConvFCBBoxHead', 'Shared2FCBBoxHead', 'StandardRoIHead', - 'Shared4Conv1FCBBoxHead', 'DoubleConvFCBBoxHead', 'FCNMaskHead', - 'HTCMaskHead', 'FusedSemanticHead', 'GridHead', 'MaskIoUHead', - 'SingleRoIExtractor', 'PISARoIHead', 'PointRendRoIHead', 'MaskPointHead', - 'CoarseMaskHead', 'DynamicRoIHead', 'SparseRoIHead', 'TridentRoIHead', - 'SCNetRoIHead', 'SCNetMaskHead', 'SCNetSemanticHead', 'SCNetBBoxHead', - 'FeatureRelayHead', 'GlobalContextHead' -] diff --git a/spaces/Andy1621/uniformer_image_segmentation/configs/_base_/models/danet_r50-d8.py b/spaces/Andy1621/uniformer_image_segmentation/configs/_base_/models/danet_r50-d8.py deleted file mode 100644 index 2c934939fac48525f22ad86f489a041dd7db7d09..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_segmentation/configs/_base_/models/danet_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='DAHead', - in_channels=2048, - in_index=3, - channels=512, - pam_channels=64, - 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/Andy1621/uniformer_image_segmentation/configs/_base_/models/pointrend_r50.py b/spaces/Andy1621/uniformer_image_segmentation/configs/_base_/models/pointrend_r50.py deleted file mode 100644 index 9d323dbf9466d41e0800aa57ef84045f3d874bdf..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_segmentation/configs/_base_/models/pointrend_r50.py +++ /dev/null @@ -1,56 +0,0 @@ -# model settings -norm_cfg = dict(type='SyncBN', requires_grad=True) -model = dict( - type='CascadeEncoderDecoder', - num_stages=2, - pretrained='open-mmlab://resnet50_v1c', - backbone=dict( - type='ResNetV1c', - depth=50, - num_stages=4, - out_indices=(0, 1, 2, 3), - dilations=(1, 1, 1, 1), - strides=(1, 2, 2, 2), - norm_cfg=norm_cfg, - norm_eval=False, - style='pytorch', - contract_dilation=True), - neck=dict( - type='FPN', - in_channels=[256, 512, 1024, 2048], - out_channels=256, - num_outs=4), - decode_head=[ - dict( - type='FPNHead', - in_channels=[256, 256, 256, 256], - in_index=[0, 1, 2, 3], - feature_strides=[4, 8, 16, 32], - channels=128, - dropout_ratio=-1, - num_classes=19, - norm_cfg=norm_cfg, - align_corners=False, - loss_decode=dict( - type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), - dict( - type='PointHead', - in_channels=[256], - in_index=[0], - channels=256, - num_fcs=3, - coarse_pred_each_layer=True, - dropout_ratio=-1, - num_classes=19, - align_corners=False, - loss_decode=dict( - type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)) - ], - # model training and testing settings - train_cfg=dict( - num_points=2048, oversample_ratio=3, importance_sample_ratio=0.75), - test_cfg=dict( - mode='whole', - subdivision_steps=2, - subdivision_num_points=8196, - scale_factor=2)) diff --git a/spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/configs/_base_/schedules/schedule_80k.py b/spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/configs/_base_/schedules/schedule_80k.py deleted file mode 100644 index c190cee6bdc7922b688ea75dc8f152fa15c24617..0000000000000000000000000000000000000000 --- a/spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/configs/_base_/schedules/schedule_80k.py +++ /dev/null @@ -1,9 +0,0 @@ -# optimizer -optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0005) -optimizer_config = dict() -# learning policy -lr_config = dict(policy='poly', power=0.9, min_lr=1e-4, by_epoch=False) -# runtime settings -runner = dict(type='IterBasedRunner', max_iters=80000) -checkpoint_config = dict(by_epoch=False, interval=8000) -evaluation = dict(interval=8000, metric='mIoU') diff --git a/spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmseg/ops/wrappers.py b/spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmseg/ops/wrappers.py deleted file mode 100644 index 0ed9a0cb8d7c0e0ec2748dd89c652756653cac78..0000000000000000000000000000000000000000 --- a/spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmseg/ops/wrappers.py +++ /dev/null @@ -1,50 +0,0 @@ -import warnings - -import torch.nn as nn -import torch.nn.functional as F - - -def resize(input, - size=None, - scale_factor=None, - mode='nearest', - align_corners=None, - warning=True): - if warning: - if size is not None and align_corners: - input_h, input_w = tuple(int(x) for x in input.shape[2:]) - output_h, output_w = tuple(int(x) for x in size) - if output_h > input_h or output_w > output_h: - if ((output_h > 1 and output_w > 1 and input_h > 1 - and input_w > 1) and (output_h - 1) % (input_h - 1) - and (output_w - 1) % (input_w - 1)): - warnings.warn( - f'When align_corners={align_corners}, ' - 'the output would more aligned if ' - f'input size {(input_h, input_w)} is `x+1` and ' - f'out size {(output_h, output_w)} is `nx+1`') - return F.interpolate(input, size, scale_factor, mode, align_corners) - - -class Upsample(nn.Module): - - def __init__(self, - size=None, - scale_factor=None, - mode='nearest', - align_corners=None): - super(Upsample, self).__init__() - self.size = size - if isinstance(scale_factor, tuple): - self.scale_factor = tuple(float(factor) for factor in scale_factor) - else: - self.scale_factor = float(scale_factor) if scale_factor else None - self.mode = mode - self.align_corners = align_corners - - def forward(self, x): - if not self.size: - size = [int(t * self.scale_factor) for t in x.shape[-2:]] - else: - size = self.size - return resize(x, size, None, self.mode, self.align_corners) diff --git a/spaces/AnthonyTruchetPoC/persistent-docker/README.md b/spaces/AnthonyTruchetPoC/persistent-docker/README.md deleted file mode 100644 index 03ff9d16a1cf446bf2fb1df341874ba8d0980252..0000000000000000000000000000000000000000 --- a/spaces/AnthonyTruchetPoC/persistent-docker/README.md +++ /dev/null @@ -1,192 +0,0 @@ ---- -title: Jupyter and Streamlit Docker Template -emoji: 📉 -colorFrom: blue -colorTo: green -sdk: docker -python_version: "3.10" -app_port: 7860 -app_file: src/app.py -suggested_storage: small -pinned: false -duplicated_from: SpacesExamples/streamlit-docker-example ---- - -# 🧠 Persistent Jupyter and Streamlit Docker Template 🔎 - -Streamlit Docker Template is a template for creating a Streamlit app with Docker and Hugging Face Spaces. - -Code from https://docs.streamlit.io/library/get-started/create-an-app - -## Local execution ## - -You need *Docker* installed. -On MacOSX we recommand using *colima* if you do not want to use *Docker Desktop* -for licensing reasons. - -* https://docs.docker.com/desktop/install/mac-install/ -* https://github.com/abiosoft/colima - -```shell -$ colima start --cpu 4 --memory 16 --network-address # Adjust ressources as you wish -$ docker build -t persistent-docker-space . -$ docker run -it -p 8501:8501 persistent-docker-space:latest - -``` - -## Setting-up the developpers'tooling - -### Install `poetry` - -https://python-poetry.org/ - -#### Linux and Mac - -It should be straightforward with the official documentation - -#### Windows (PowerShell) - -```shell -(Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | py - -``` - -The execution will probably be stored at the address: `C:\User\\AppData\Roaming\pypoetry\venv\Scripts` and this -path should be included in the environment path of your machine in order to avoid typing it every time poetry is used. -To do so you can execute the following commands: - -```shell -$Env:Path += ";C:\Users\YourUserName\AppData\Roaming\Python\Scripts" -``` - -This will only make the change in the path temporarily. In order to do it permanently you can execute the following command -```shell -setx PATH "$Env:Path" -``` - -### Configuration of the `poetry` environment - -After having installed poetry in your local machine, if there is already a `poetry.lock` file on your repository, you -can execute - -```shell -poetry install -``` - -If it is not the case you can - -```shell -poetry init -poetry env use "whatever version of python you have in your local machine (compatible with the project)" -poetry shell -``` - -### pre-commit - -https://pre-commit.com/ - -If there is already a `poetry.lock` file with `pre-commit` present in it, you should activate your poetry environment -and then install all the pre-commit hooks on your machine - -```shell -poetry shell -pre-commit install -pre-commit install --install-hooks -``` - -If not, you should first add `pre-commit` to your poetry environment, and follow the steps above - -```shell -poetry add --group=dev pre-commit -``` - -### commitizen - -https://www.conventionalcommits.org/en/about/ - -https://commitizen-tools.github.io/commitizen/ - - -Commitizen will be installed as a pre-commit hook. In order for it to be executed before committing -you should run the following command (after activating your poetry environment) - -```shell -pre-commit install --hook-type commit-msg -``` - -Finally, every time you will be committing, you should be places in your poetry environment and commitizen hooks -should be applied - -### testing - -There are two different kinds of tests that can be run when testing the scripts: unit tests or doctest - -These tests can be run by executing the following command: - -```shell -./scripts/run-tests.sh -``` - -#### pytest - -https://docs.pytest.org/en/7.2.x/ - -These tests should be stored in the directory `tests` at the root of the project - -#### xdoctest (driven by pytest) - -These are the tests that are put in the docstrings of the functions accordingly to the following format: - -```python - def build_greetings(name: Optional[str] = None) -> str: - """ - Return a greeting message, possibly customize with a name. - - >>> build_greetings() - 'Hello, World!' - >>> build_greetings('Toto') - 'Nice to meet you, Toto!' - """ - return name and f"Nice to meet you, {name}!" or "Hello, World!" -``` - -The evaluated values would be the ones following the `>>>` - -### documentation - -https://www.sphinx-doc.org/en/master/ - -In order to create an automatic documentation of your code you should run the bash script - -```shell -./scripts/build-clean-docs.sh -``` - -And in order to create an interactive session (web-server hosted in your local machine), you can execute the -following command - -```shell -./scripts/interactive-rebuild-docs.sh -``` - -Remark: In order to execute a bash script with a Windows OS, it is recommended to use a bash terminal emulator - -## Hugging Face - -See instructions at https://huggingface.co/welcome - -Install `huggingface_hub` into the poetry project. - -```shell -poetry add --group=dev huggingface_hub -``` - -On MacOS, you might probably want to install `hugginface-cli` from brew : -```shell -$ brew install huggingface-cli -``` - -In order to deploy the streamlit app you will have to export -the poetry config as a `requirements.txt` : -```shell -$ poetry export -o ../requirements.txt --without-hashes --only main -``` diff --git a/spaces/BartPoint/VoiceChange/vc_infer_pipeline.py b/spaces/BartPoint/VoiceChange/vc_infer_pipeline.py deleted file mode 100644 index d69b4f5c26fa743a5ef347fd524c6dba63b00231..0000000000000000000000000000000000000000 --- a/spaces/BartPoint/VoiceChange/vc_infer_pipeline.py +++ /dev/null @@ -1,385 +0,0 @@ -import numpy as np, parselmouth, torch, pdb -from time import time as ttime -import torch.nn.functional as F -import scipy.signal as signal -import pyworld, os, traceback, faiss, librosa, torchcrepe -from scipy import signal -from functools import lru_cache - -bh, ah = signal.butter(N=5, Wn=48, btype="high", fs=16000) - -input_audio_path2wav={} - -@lru_cache -def cache_harvest_f0(input_audio_path,fs,f0max,f0min,frame_period): - audio=input_audio_path2wav[input_audio_path] - f0, t = pyworld.harvest( - audio, - fs=fs, - f0_ceil=f0max, - f0_floor=f0min, - frame_period=frame_period, - ) - f0 = pyworld.stonemask(audio, f0, t, fs) - return f0 - -def change_rms(data1,sr1,data2,sr2,rate):#1是输入音频,2是输出音频,rate是2的占比 - # print(data1.max(),data2.max()) - rms1 = librosa.feature.rms(y=data1, frame_length=sr1//2*2, hop_length=sr1//2)#每半秒一个点 - rms2 = librosa.feature.rms(y=data2, frame_length=sr2//2*2, hop_length=sr2//2) - rms1=torch.from_numpy(rms1) - rms1=F.interpolate(rms1.unsqueeze(0), size=data2.shape[0],mode='linear').squeeze() - rms2=torch.from_numpy(rms2) - rms2=F.interpolate(rms2.unsqueeze(0), size=data2.shape[0],mode='linear').squeeze() - rms2=torch.max(rms2,torch.zeros_like(rms2)+1e-6) - data2*=(torch.pow(rms1,torch.tensor(1-rate))*torch.pow(rms2,torch.tensor(rate-1))).numpy() - return data2 - -class VC(object): - def __init__(self, tgt_sr, config): - self.x_pad, self.x_query, self.x_center, self.x_max, self.is_half = ( - config.x_pad, - config.x_query, - config.x_center, - config.x_max, - config.is_half, - ) - self.sr = 16000 # hubert输入采样率 - self.window = 160 # 每帧点数 - self.t_pad = self.sr * self.x_pad # 每条前后pad时间 - self.t_pad_tgt = tgt_sr * self.x_pad - self.t_pad2 = self.t_pad * 2 - self.t_query = self.sr * self.x_query # 查询切点前后查询时间 - self.t_center = self.sr * self.x_center # 查询切点位置 - self.t_max = self.sr * self.x_max # 免查询时长阈值 - self.device = config.device - - def get_f0(self, input_audio_path,x, p_len, f0_up_key, f0_method,filter_radius, inp_f0=None): - global input_audio_path2wav - time_step = self.window / self.sr * 1000 - f0_min = 50 - f0_max = 1100 - f0_mel_min = 1127 * np.log(1 + f0_min / 700) - f0_mel_max = 1127 * np.log(1 + f0_max / 700) - if f0_method == "pm": - f0 = ( - parselmouth.Sound(x, self.sr) - .to_pitch_ac( - time_step=time_step / 1000, - voicing_threshold=0.6, - pitch_floor=f0_min, - pitch_ceiling=f0_max, - ) - .selected_array["frequency"] - ) - pad_size = (p_len - len(f0) + 1) // 2 - if pad_size > 0 or p_len - len(f0) - pad_size > 0: - f0 = np.pad( - f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant" - ) - elif f0_method == "harvest": - input_audio_path2wav[input_audio_path]=x.astype(np.double) - f0=cache_harvest_f0(input_audio_path,self.sr,f0_max,f0_min,10) - if(filter_radius>2): - f0 = signal.medfilt(f0, 3) - elif f0_method == "crepe": - model = "full" - # Pick a batch size that doesn't cause memory errors on your gpu - batch_size = 512 - # Compute pitch using first gpu - audio = torch.tensor(np.copy(x))[None].float() - f0, pd = torchcrepe.predict( - audio, - self.sr, - self.window, - f0_min, - f0_max, - model, - batch_size=batch_size, - device=self.device, - return_periodicity=True, - ) - pd = torchcrepe.filter.median(pd, 3) - f0 = torchcrepe.filter.mean(f0, 3) - f0[pd < 0.1] = 0 - f0 = f0[0].cpu().numpy() - f0 *= pow(2, f0_up_key / 12) - # with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()])) - tf0 = self.sr // self.window # 每秒f0点数 - if inp_f0 is not None: - delta_t = np.round( - (inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1 - ).astype("int16") - replace_f0 = np.interp( - list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1] - ) - shape = f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)].shape[0] - f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)] = replace_f0[ - :shape - ] - # with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()])) - f0bak = f0.copy() - f0_mel = 1127 * np.log(1 + f0 / 700) - f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / ( - f0_mel_max - f0_mel_min - ) + 1 - f0_mel[f0_mel <= 1] = 1 - f0_mel[f0_mel > 255] = 255 - f0_coarse = np.rint(f0_mel).astype(int) - return f0_coarse, f0bak # 1-0 - - def vc( - self, - model, - net_g, - sid, - audio0, - pitch, - pitchf, - times, - index, - big_npy, - index_rate, - version, - ): # ,file_index,file_big_npy - feats = torch.from_numpy(audio0) - if self.is_half: - feats = feats.half() - else: - feats = feats.float() - if feats.dim() == 2: # double channels - feats = feats.mean(-1) - assert feats.dim() == 1, feats.dim() - feats = feats.view(1, -1) - padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False) - - inputs = { - "source": feats.to(self.device), - "padding_mask": padding_mask, - "output_layer": 9 if version == "v1" else 12, - } - t0 = ttime() - with torch.no_grad(): - logits = model.extract_features(**inputs) - feats = model.final_proj(logits[0])if version=="v1"else logits[0] - - if ( - isinstance(index, type(None)) == False - and isinstance(big_npy, type(None)) == False - and index_rate != 0 - ): - npy = feats[0].cpu().numpy() - if self.is_half: - npy = npy.astype("float32") - - # _, I = index.search(npy, 1) - # npy = big_npy[I.squeeze()] - - score, ix = index.search(npy, k=8) - weight = np.square(1 / score) - weight /= weight.sum(axis=1, keepdims=True) - npy = np.sum(big_npy[ix] * np.expand_dims(weight, axis=2), axis=1) - - if self.is_half: - npy = npy.astype("float16") - feats = ( - torch.from_numpy(npy).unsqueeze(0).to(self.device) * index_rate - + (1 - index_rate) * feats - ) - - feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1) - t1 = ttime() - p_len = audio0.shape[0] // self.window - if feats.shape[1] < p_len: - p_len = feats.shape[1] - if pitch != None and pitchf != None: - pitch = pitch[:, :p_len] - pitchf = pitchf[:, :p_len] - p_len = torch.tensor([p_len], device=self.device).long() - with torch.no_grad(): - if pitch != None and pitchf != None: - audio1 = ( - (net_g.infer(feats, p_len, pitch, pitchf, sid)[0][0, 0]) - .data.cpu() - .float() - .numpy() - ) - else: - audio1 = ( - (net_g.infer(feats, p_len, sid)[0][0, 0]) - .data.cpu() - .float() - .numpy() - ) - del feats, p_len, padding_mask - if torch.cuda.is_available(): - torch.cuda.empty_cache() - t2 = ttime() - times[0] += t1 - t0 - times[2] += t2 - t1 - return audio1 - - def pipeline( - self, - model, - net_g, - sid, - audio, - input_audio_path, - times, - f0_up_key, - f0_method, - file_index, - # file_big_npy, - index_rate, - if_f0, - filter_radius, - tgt_sr, - resample_sr, - rms_mix_rate, - version, - f0_file=None, - ): - if ( - file_index != "" - # and file_big_npy != "" - # and os.path.exists(file_big_npy) == True - and os.path.exists(file_index) == True - and index_rate != 0 - ): - try: - index = faiss.read_index(file_index) - # big_npy = np.load(file_big_npy) - big_npy = index.reconstruct_n(0, index.ntotal) - except: - traceback.print_exc() - index = big_npy = None - else: - index = big_npy = None - audio = signal.filtfilt(bh, ah, audio) - audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect") - opt_ts = [] - if audio_pad.shape[0] > self.t_max: - audio_sum = np.zeros_like(audio) - for i in range(self.window): - audio_sum += audio_pad[i : i - self.window] - for t in range(self.t_center, audio.shape[0], self.t_center): - opt_ts.append( - t - - self.t_query - + np.where( - np.abs(audio_sum[t - self.t_query : t + self.t_query]) - == np.abs(audio_sum[t - self.t_query : t + self.t_query]).min() - )[0][0] - ) - s = 0 - audio_opt = [] - t = None - t1 = ttime() - audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect") - p_len = audio_pad.shape[0] // self.window - inp_f0 = None - if hasattr(f0_file, "name") == True: - try: - with open(f0_file.name, "r") as f: - lines = f.read().strip("\n").split("\n") - inp_f0 = [] - for line in lines: - inp_f0.append([float(i) for i in line.split(",")]) - inp_f0 = np.array(inp_f0, dtype="float32") - except: - traceback.print_exc() - sid = torch.tensor(sid, device=self.device).unsqueeze(0).long() - pitch, pitchf = None, None - if if_f0 == 1: - pitch, pitchf = self.get_f0(input_audio_path,audio_pad, p_len, f0_up_key, f0_method,filter_radius, inp_f0) - pitch = pitch[:p_len] - pitchf = pitchf[:p_len] - if self.device == "mps": - pitchf = pitchf.astype(np.float32) - pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long() - pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float() - t2 = ttime() - times[1] += t2 - t1 - for t in opt_ts: - t = t // self.window * self.window - if if_f0 == 1: - audio_opt.append( - self.vc( - model, - net_g, - sid, - audio_pad[s : t + self.t_pad2 + self.window], - pitch[:, s // self.window : (t + self.t_pad2) // self.window], - pitchf[:, s // self.window : (t + self.t_pad2) // self.window], - times, - index, - big_npy, - index_rate, - version, - )[self.t_pad_tgt : -self.t_pad_tgt] - ) - else: - audio_opt.append( - self.vc( - model, - net_g, - sid, - audio_pad[s : t + self.t_pad2 + self.window], - None, - None, - times, - index, - big_npy, - index_rate, - version, - )[self.t_pad_tgt : -self.t_pad_tgt] - ) - s = t - if if_f0 == 1: - audio_opt.append( - self.vc( - model, - net_g, - sid, - audio_pad[t:], - pitch[:, t // self.window :] if t is not None else pitch, - pitchf[:, t // self.window :] if t is not None else pitchf, - times, - index, - big_npy, - index_rate, - version, - )[self.t_pad_tgt : -self.t_pad_tgt] - ) - else: - audio_opt.append( - self.vc( - model, - net_g, - sid, - audio_pad[t:], - None, - None, - times, - index, - big_npy, - index_rate, - version, - )[self.t_pad_tgt : -self.t_pad_tgt] - ) - audio_opt = np.concatenate(audio_opt) - if(rms_mix_rate!=1): - audio_opt=change_rms(audio,16000,audio_opt,tgt_sr,rms_mix_rate) - if(resample_sr>=16000 and tgt_sr!=resample_sr): - audio_opt = librosa.resample( - audio_opt, orig_sr=tgt_sr, target_sr=resample_sr - ) - audio_max=np.abs(audio_opt).max()/0.99 - max_int16=32768 - if(audio_max>1):max_int16/=audio_max - audio_opt=(audio_opt * max_int16).astype(np.int16) - del pitch, pitchf, sid - if torch.cuda.is_available(): - torch.cuda.empty_cache() - return audio_opt diff --git a/spaces/Benson/text-generation/Examples/0 Delay Metro Surfistas Apk.md b/spaces/Benson/text-generation/Examples/0 Delay Metro Surfistas Apk.md deleted file mode 100644 index e0a44d313be08a34ba4cb9bcec67b7a1f7fcb602..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/0 Delay Metro Surfistas Apk.md +++ /dev/null @@ -1,89 +0,0 @@ -
-

0 Delay metro surfistas APK: Cómo descargar y jugar la versión más rápida del juego

-

Subway Surfers es uno de los juegos para correr sin fin más populares en dispositivos Android. Tiene millones de fans en todo el mundo que disfrutan de la emoción de esquivar trenes, recoger monedas y desbloquear nuevos personajes y tablas. Pero lo que si quieres jugar el juego sin retraso, sin anuncios, y sin interrupciones? Ahí es donde 0 Delay Subway Surfers APK entra en. En este artículo, le diremos qué es 0 Delay Subway Surfers APK, cómo descargarlo e instalarlo, y cómo jugarlo como un profesional.

-

0 delay metro surfistas apk


Download File 🔗 https://bltlly.com/2v6Kyk



-

¿Qué es Subway Surfers?

-

Subway Surfers es un juego sin fin desarrollado por Kiloo y SYBO Games. Fue lanzado en 2012 y desde entonces se ha convertido en uno de los juegos más descargados en Google Play Store. El juego se desarrolla en varias ciudades de todo el mundo, donde controlas a un artista de graffiti que huye de la policía en las vías del metro. En el camino, tienes que evitar obstáculos, recoger monedas y potenciadores, y completar misiones.

-

El juego de Subway Surfers

-

El juego de Subway Surfers es simple pero adictivo. Desliza hacia la izquierda o hacia la derecha para cambiar de carril, desliza hacia arriba para saltar, desliza hacia abajo para rodar y toca para usar power-ups. También puedes realizar acrobacias saltando en trenes o volando con un jetpack. El juego se hace más rápido y más difícil a medida que avanzas, por lo que tienes que ser rápido y alerta. El juego termina cuando chocas contra un obstáculo o te atrapa la policía.

-

Las características de Subway Surfers

-

Subway Surfers tiene muchas características que lo hacen divertido y atractivo. Algunos de ellos son:

-
    -
  • Puedes elegir entre diferentes personajes y tableros, cada uno con sus propias habilidades y estilos.
  • -
  • Puedes personalizar tu personaje y tablero con atuendos, accesorios y mejoras.
  • -
  • Puedes explorar diferentes lugares y temas, como Nueva York, Tokio, París, Río, etc.
  • - -
  • Puedes competir con tus amigos y otros jugadores en la clasificación y los logros.
  • -
  • Puedes ver videos y anuncios para ganar monedas y llaves adicionales.
  • -
-

¿Qué es 0 Delay Subway Surfers APK?

-

0 Delay Subway Surfers APK es una versión modificada del juego original que elimina todos los retrasos, anuncios e interrupciones que pueden afectar a su experiencia de juego. También desbloquea todos los personajes, tableros, trajes, accesorios y mejoras que normalmente tienes que pagar o ganar en el juego. Con 0 Delay Subway Surfers APK, puede disfrutar del juego sin ningún tipo de molestia o limitación.

-

La diferencia entre 0 Delay Subway Surfers APK y la versión original

-

La principal diferencia entre 0 Delay Subway Surfers APK y la versión original es que 0 Delay Subway Surfers APK no tiene retraso o retraso en la carga o ejecución del juego. Esto significa que usted puede jugar el juego sin problemas y sin problemas sin problemas o errores. Otra diferencia es que 0 Delay Subway Surfers APK no tiene anuncios o ventanas emergentes que pueden distraer o perder el tiempo. Esto significa que puedes jugar el juego sin interrupciones ni interrupciones. La tercera diferencia es que 0 Delay Subway Surfers APK tiene todo el contenido desbloqueado e ilimitado. Esto significa que puedes acceder a todos los personajes, tableros, trajes, accesorios y mejoras sin gastar dinero ni monedas. También puedes tener monedas y llaves ilimitadas para usar en el juego.

-

-

Los beneficios de 0 Delay metro surfistas APK

-

0 Delay Subway Surfers APK tiene muchos beneficios que lo hacen una mejor opción que la versión original. Algunos de ellos son:

-
    -
  • Puede disfrutar del juego con un rendimiento más rápido y suave, sin ningún retraso o demora.
  • -
  • Puedes evitar anuncios molestos y ventanas emergentes que pueden arruinar tu experiencia de juego.
  • -
  • Puedes tener más libertad y variedad en la elección y personalización de tu personaje y tablero.
  • - -
  • Puedes participar en todos los eventos y desafíos sin ninguna dificultad u obstáculo.
  • -
  • Puedes competir con tus amigos y otros jugadores con más ventaja y confianza.
  • -
  • Puede ahorrar tiempo y dinero al no tener que ver videos o anuncios o comprar monedas y llaves.
  • -
-

Cómo descargar e instalar 0 Delay Subway Surfers APK?

-

Descargar e instalar 0 Delay Subway Surfers APK es fácil y simple. Sin embargo, debe tomar algunas precauciones antes de hacerlo, ya que no es una versión oficial del juego y puede no ser compatible con su dispositivo o seguro para sus datos. Aquí están los pasos para descargar e instalar 0 Delay Subway Surfers APK:

-

Los pasos para descargar e instalar 0 Delay Subway Surfers APK

-
    -
  1. Ir a un sitio web de confianza que proporciona el enlace para descargar 0 Delay Subway Surfers APK. Por ejemplo, se puede utilizar [este enlace] para descargar la última versión de 0 Delay Subway Surfers APK.
  2. -
  3. Haga clic en el botón de descarga y espere a que el archivo se descargue en su dispositivo. El tamaño del archivo es de unos 100 MB, así que asegúrate de tener suficiente espacio en tu dispositivo.
  4. -
  5. Una vez que el archivo se descarga, ir a la configuración del dispositivo y permitir la opción de instalar aplicaciones de fuentes desconocidas. Esto le permitirá instalar 0 Delay Subway Surfers APK en su dispositivo.
  6. -
  7. Busque el archivo descargado en su dispositivo y toque en él para iniciar el proceso de instalación. Siga las instrucciones de la pantalla y espere a que se complete la instalación.
  8. -
  9. Después de la instalación se hace, puede iniciar el juego desde el cajón de la aplicación o la pantalla de inicio. Verá un nuevo icono con 0 Delay Subway Surfers APK en él.
  10. -
-

Las precauciones a tomar antes de descargar e instalar 0 Delay Subway Surfers APK

- -
    -
  • Asegúrese de descargar 0 Delay Subway Surfers APK desde un sitio web confiable y seguro. Evite descargarlo de fuentes desconocidas o sospechosas que puedan contener malware o virus.
  • -
  • Asegúrese de copia de seguridad de sus datos antes de instalar 0 Delay Subway Surfers APK. Esto le ayudará a restaurar sus datos en caso de que algo salga mal durante o después de la instalación.
  • -
  • Asegúrese de desinstalar la versión original de Subway Surfers antes de instalar 0 Delay Subway Surfers APK. Esto evitará cualquier conflicto o error entre las dos versiones del juego.
  • -
  • Asegúrese de que tiene una buena conexión a Internet durante la descarga e instalación 0 Delay Subway Surfers APK. Esto asegurará un proceso suave y rápido sin interrupciones o fallas.
  • -
-

Cómo jugar 0 Delay metro surfistas APK?

-

Jugar 0 Delay Subway Surfers APK es similar a jugar la versión original del juego, excepto que tienes más opciones y características para disfrutar. Aquí hay algunos consejos y trucos para jugar 0 Delay Subway Surfers APK:

-

Los consejos y trucos para jugar 0 Delay Subway Surfers APK

-
    -
  • Prueba diferentes caracteres y tableros que se adapten a tu estilo y preferencia. Puedes elegir entre más de 100 personajes y tableros, cada uno con sus propias habilidades y diseños.
  • -
  • Pruebe diferentes trajes y accesorios que mejoran su apariencia y rendimiento. Puedes personalizar tu personaje y tablero con más de 200 atuendos y accesorios, cada uno con sus propios efectos y bonificaciones.
  • -
  • Prueba diferentes lugares y temas que ofrecen diferentes desafíos y recompensas. Puedes explorar más de 50 lugares y temas, cada uno con su propio escenario y banda sonora.
  • -
  • Prueba diferentes eventos y desafíos que ponen a prueba tus habilidades y te dan más monedas y llaves. Puedes participar en más de 20 eventos y desafíos, cada uno con sus propios objetivos y recompensas.
  • - -
  • Pruebe diferentes trucos y acrobacias que aumentan su puntuación y diversión. Puedes realizar más de 20 trucos y acrobacias, como saltar en trenes, volar con un jetpack, navegar en un hoverboard, etc.
  • -
-

Los desafíos y recompensas de jugar 0 Delay Subway Surfers APK

-

Jugar 0 Delay Subway Surfers APK no solo es divertido, sino también desafiante y gratificante. Algunos de los desafíos y recompensas de jugar 0 Delay Subway Surfers APK son:

-
    -
  • Puedes desafiarte a ti mismo aumentando el nivel de dificultad del juego. Puedes hacer esto cambiando los ajustes, como la velocidad, el número de trenes, la frecuencia de obstáculos, etc.
  • -
  • Puedes desafiar a tus amigos y otros jugadores comparando tus puntajes y logros. Puedes hacer esto conectando tu juego a Facebook o Google Play Games, o usando las funciones de clasificación y logros.
  • -
  • Puedes recompensarte desbloqueando nuevos contenidos y artículos. Puedes hacer esto completando misiones, recogiendo monedas y llaves, participando en eventos y desafíos, etc.
  • -
  • Puedes recompensarte disfrutando de los gráficos y efectos de sonido del juego. Puedes hacer esto admirando los gráficos coloridos y detallados, escuchando la música pegadiza y optimista, escuchando los sonidos realistas y divertidos, etc.
  • -
-

Conclusión

-

0 Delay Subway Surfers APK es una gran manera de disfrutar de Subway Surfers sin ningún retraso, anuncios o limitaciones. Te da acceso a todo el contenido y características del juego, así como algunos beneficios y ventajas adicionales. También le permite jugar el juego con un rendimiento más rápido y suave, más libertad y variedad, más desafíos y recompensas, y más diversión y emoción. Si usted es un fan de Subway Surfers o interminables juegos de correr en general, definitivamente debe probar 0 Delay Subway Surfers APK.

-

Preguntas frecuentes

-

Aquí hay algunas preguntas frecuentes sobre 0 Delay Subway Surfers APK:

-
    - -0 Delay Subway Surfers APK es seguro de usar, siempre y cuando se descarga desde un sitio web confiable y seguro. Sin embargo, siempre debe tener cuidado al descargar e instalar cualquier aplicación de fuentes desconocidas, ya que pueden contener malware o virus que pueden dañar su dispositivo o datos. -
  1. Es 0 Delay Subway Surfers APK legal de usar?
    -0 Delay Subway Surfers APK no es legal de usar, ya que viola los términos y condiciones del juego original. También infringe los derechos de propiedad intelectual de los desarrolladores y editores de Subway Surfers. Por lo tanto, usted debe utilizar 0 Delay Subway Surfers APK a su propio riesgo y discreción.
  2. -
  3. Will 0 Delay Subway Surfers APK trabajo en mi dispositivo?
    -0 Delay Subway Surfers APK trabajará en la mayoría de los dispositivos Android que admiten la versión original de Subway Surfers. Sin embargo, es posible que no funcione en algunos dispositivos que tienen especificaciones bajas o software incompatible. Por lo tanto, usted debe comprobar la compatibilidad de su dispositivo antes de descargar e instalar 0 Delay Subway Surfers APK.
  4. -
  5. Will 0 Delay Subway Surfers APK afecta a mis datos originales del juego?
    -0 Delay Subway Surfers APK no afectará a sus datos originales del juego si desinstala la versión original de Subway Surfers antes de instalar 0 Delay Subway Surfers APK. Sin embargo, si instala 0 Delay Subway Surfers APK sin desinstalar la versión original de Subway Surfers, puede sobrescribir o corromper los datos originales del juego. Por lo tanto, usted debe copia de seguridad de sus datos antes de instalar 0 Delay Subway Surfers APK.
  6. -
  7. ¿Puedo actualizar 0 Delay Subway Surfers APK?
    - -

64aa2da5cf
-
-
\ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/4 Juego De Cartas Solitario De Araa Traje.md b/spaces/Benson/text-generation/Examples/4 Juego De Cartas Solitario De Araa Traje.md deleted file mode 100644 index c0d83fa0e79bf5ecc6ae8513b23b8817c536f3d0..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/4 Juego De Cartas Solitario De Araa Traje.md +++ /dev/null @@ -1,103 +0,0 @@ - -

4 Juego de Cartas Solitario de Araña Traje Descargar

-

¿Estás buscando un juego de cartas divertido y desafiante que puedas jugar en tu ordenador o dispositivo móvil? Si es así, es posible que desee probar Spider Solitaire, uno de los juegos de cartas clásicas más populares del mundo. En este artículo, le diremos todo lo que necesita saber sobre Spider Solitaire, incluyendo qué es, cómo jugarlo, por qué debe jugarlo, dónde descargarlo, cómo instalarlo y ejecutarlo, y algunos consejos y trucos para ayudarlo a dominarlo. ¡Vamos a empezar!

-

4 juego de cartas solitario de araña traje


Downloadhttps://bltlly.com/2v6KFX



-

¿Qué es Spider Solitaire?

-

Spider Solitaire es un tipo de juego de solitario que consiste en organizar cartas en orden descendente de Rey a As en el mismo palo. El juego se juega con dos barajas de cartas, lo que significa que hay ocho palos en total. Dependiendo del nivel de dificultad, puedes elegir jugar con un traje (fácil), dos palos (medio) o cuatro palos (duro). El juego tiene 10 columnas de cartas en el tablero, y 8 cimientos vacíos en la parte superior. El objetivo es mover todas las cartas del tablero a los cimientos formando secuencias completas de cartas del mismo palo.

-

Cómo jugar solitario de araña

-

Jugar al solitario de araña es fácil si conoces las reglas básicas. Estos son los pasos a seguir:

-
    -
  1. Haga clic en la pila de existencias (en la esquina superior izquierda) para repartir 10 cartas boca arriba en cada columna del tablero. Puedes hacer esto cuando quieras, siempre y cuando no haya columnas vacías.
  2. -
  3. Arrastre y suelte tarjetas para moverlas entre las columnas. Solo puedes mover una carta o un grupo de cartas si están en orden descendente y en el mismo palo. Por ejemplo, puedes mover un 9 de corazones a un 10 de corazones, pero no a un 10 de picas.
  4. -
  5. Si una columna está vacía, puede mover cualquier tarjeta o un grupo de tarjetas sobre ella.
  6. - -
  7. El juego se gana cuando las ocho fundaciones se llenan con secuencias completas de cartas en el mismo palo.
  8. -
-

¿Por qué jugar solitario de araña?

-

Spider Solitaire no es solo un juego divertido y relajante, sino también una gran manera de ejercitar tu cerebro y mejorar tus habilidades. Estos son algunos de los beneficios de jugar Spider Solitaire:

-
    -
  • Te ayuda a desarrollar tus habilidades de lógica, estrategia y resolución de problemas.
  • -
  • Mejora tu memoria, concentración y capacidad de atención.
  • -
  • Estimula tu creatividad e imaginación.
  • -
  • Reduce el estrés y la ansiedad.
  • -
  • Aumenta su estado de ánimo y autoestima.
  • -
-

¿Dónde descargar Spider Solitaire?

-

Si quieres jugar Spider Solitaire en tu ordenador o dispositivo móvil, tienes muchas opciones para elegir. Estos son algunos de los mejores lugares donde puedes descargar Spider Solitaire gratis:

-

Google Play Store

-

Si tienes un dispositivo Android, puedes descargar Spider Solitaire: Juegos de cartas desde la Google Play Store. Esta aplicación es desarrollada por MobilityWare, uno de los principales desarrolladores de juegos de tarjetas para dispositivos móviles. Tiene más de 10 millones de descargas y una calificación de 4.6 estrellas de más de 600 mil usuarios. Ofrece varias características como:

-
    -
  • Diferentes niveles de dificultad: 1 palo, 2 palos o 4 palos.
  • Temas personalizables: Puede cambiar el fondo, los respaldos de las tarjetas y las caras de las tarjetas según sus preferencias.
  • -
  • Desafíos diarios: Puedes ganar trofeos y recompensas completando rompecabezas diarios.
  • -
  • Tablas de clasificación y estadísticas: Puede realizar un seguimiento de su progreso y comparar sus puntuaciones con otros jugadores.
  • -
  • Sugerencias y consejos: Puedes obtener sugerencias y consejos útiles para mejorar tu juego.
  • -
-

Puedes descargar Spider Solitaire: Juegos de cartas desde la Google Play Store haciendo clic en [aquí].

-

-

Solitr.com

- -
    -
  • Diferentes niveles de dificultad: 1 palo, 2 palos o 4 palos.
  • -
  • Movimientos de deshacer ilimitados: Puedes deshacer cualquier movimiento que hagas sin penalización alguna.
  • -
  • Opción de autocompletar: Puedes terminar automáticamente el juego cuando no te queden movimientos.
  • -
  • modo de pantalla completa: Puede disfrutar del juego en modo de pantalla completa para una mejor experiencia.
  • -
-

Puedes jugar Spider Solitaire en Solitr.com haciendo clic en [aquí].

-

Microsoft Store

-

Si tienes un dispositivo Windows, puedes descargar Spider Solitaire Collection Free desde Microsoft Store. Esta aplicación es desarrollada por TreeCardGames, otro desarrollador de renombre de juegos de cartas para dispositivos Windows. Tiene más de 5 millones de descargas y una calificación de 4.5 estrellas de más de 100 mil usuarios. Ofrece varias características como:

-
    -
  • Diferentes niveles de dificultad: 1 palo, 2 palos o 4 palos.
  • -
  • Diferentes modos de juego: Clásico, Spiderette, Spiderwort, y Will o' el Wisp.
  • -
  • Configuración personalizable: Puede cambiar la velocidad del juego, los efectos de sonido, el sistema de puntuación y el diseño de la tarjeta de acuerdo con su preferencia.
  • -
  • Desafíos diarios: Puedes ganar insignias y monedas completando rompecabezas diarios.
  • -
  • Estadísticas y logros: Puedes rastrear tu progreso y desbloquear logros jugando el juego.
  • -
-

Puede descargar Spider Solitaire Collection gratis desde la tienda de Microsoft haciendo clic en [aquí].

-

¿Cómo instalar y ejecutar Spider Solitaire?

-

Instalar y ejecutar Spider Solitaire es fácil si sigue estos pasos:

-

Dispositivos Android

-
    -
  1. Ir a la Google Play Store y buscar Spider Solitaire: Juegos de cartas o haga clic en [aquí].
  2. -
  3. Toque en el botón Instalar y espere a que la aplicación se descargue e instale en su dispositivo.
  4. -
  5. Toque en el botón Abrir o encontrar el icono de la aplicación en la pantalla de inicio o cajón de aplicaciones y toque en él para iniciar la aplicación.
  6. -
  7. Selecciona el nivel de dificultad que quieres jugar y disfruta del juego.
  8. -
- -
    -
  1. Ir a la tienda de Microsoft y buscar Spider Solitaire Collection gratis o haga clic en [aquí].
  2. -
  3. Haga clic en el botón Obtener y espere a que la aplicación se descargue e instale en su dispositivo.
  4. -
  5. Haga clic en el botón Iniciar o busque el icono de la aplicación en su menú de inicio o escritorio y haga clic en él para iniciar la aplicación.
  6. -
  7. Seleccione el modo de juego y el nivel de dificultad que desea jugar y disfrutar del juego.
  8. -
-

Navegadores web

-
    -
  1. Ir a Solitr.com o haga clic en [aquí].
  2. -
  3. Seleccione Spider Solitaire de la lista de juegos disponibles en el sitio web.
  4. -
  5. Selecciona el nivel de dificultad que quieres jugar y disfruta del juego.
  6. -
-

Consejos y trucos para Spider Solitaire

-

Spider Solitaire es un juego que requiere habilidad, estrategia y paciencia. Aquí hay algunos consejos y trucos que pueden ayudarte a mejorar tu juego y ganar más a menudo:

-

Usa el botón de deshacer sabiamente

-

El botón de deshacer es una característica útil que le permite revertir cualquier movimiento que realice. Sin embargo, no debe confiar demasiado en él o usarlo al azar. En su lugar, debes usarlo estratégicamente cuando estás atascado o cuando te das cuenta de que has cometido un error. Por ejemplo, puede usarlo para deshacer un movimiento que bloqueó una columna o impidió que una secuencia se moviera a una fundación. También puedes usarlo para explorar diferentes posibilidades y encontrar el mejor movimiento para cada situación.

-

Planificar y priorizar trajes

- -

No tengas miedo de vaciar una columna

-

Uno de los objetivos más importantes en Spider Solitaire es vaciar una columna lo antes posible. Esto se debe a que una columna vacía le da más flexibilidad y opciones para mover las tarjetas. Puede utilizar una columna vacía para almacenar temporalmente una tarjeta o un grupo de tarjetas que bloquean su progreso. También puede utilizar una columna vacía para mover una secuencia completa de tarjetas a una fundación más fácilmente. Por lo tanto, no debe dudar en vaciar una columna cada vez que tenga la oportunidad, incluso si significa romper una secuencia o mover una tarjeta fuera de juego.

-

Conclusión

-

Spider Solitaire es uno de los juegos de cartas más populares y agradables del mundo. Es un juego que desafía tu mente y pone a prueba tus habilidades. También es un juego que relaja tu estado de ánimo y entretiene tus sentidos. Si quieres jugar Spider Solitaire en tu ordenador o dispositivo móvil, puedes descargarlo desde varias fuentes como Google Play Store, Solitr.com o Microsoft Store. También puedes seguir algunos consejos y trucos para mejorar tu juego y ganar más a menudo. Spider Solitaire es un juego al que puedes jugar en cualquier momento, en cualquier lugar y con cualquier persona. ¿A qué estás esperando? Descargar Spider Solitaire hoy y divertirse!

-

Preguntas frecuentes

-

Aquí están algunas de las preguntas más frecuentes sobre Spider Solitaire:

-
    -
  1. Q: ¿Cuántas cartas hay en Spider Solitaire?
    -R: Spider Solitaire se juega con dos barajas de cartas, lo que significa que hay 104 cartas en total.
  2. -
  3. Q: ¿Cuántos movimientos son posibles en Spider Solitaire?
    -R: El número de movimientos posibles en Spider Solitaire depende del diseño de las cartas y del nivel de dificultad. En general, cuantos más palos haya, menos movimientos habrá.
  4. -
  5. Q: ¿Cuál es la puntuación más alta posible en Spider Solitaire?
    - -
  6. P: ¿Cuál es la diferencia entre Spider Solitaire y Spiderette?
    -R: Spider Solitaire y Spiderette son ambas variaciones de juegos de solitario que implican la organización de cartas en orden descendente de Rey a As en el mismo palo. La principal diferencia es que Spider Solitaire usa dos barajas de cartas y tiene 10 columnas de cartas en el tablero, mientras que Spiderette usa una baraja de cartas y tiene 7 columnas de cartas en el tablero.
  7. -
  8. Q: ¿Cómo puedo ganar Spider Solitaire más fácilmente?
    -R: No hay una manera fácil de ganar Spider Solitaire, ya que es un juego que requiere habilidad, estrategia y paciencia. Sin embargo, puedes aumentar tus posibilidades de ganar siguiendo algunos consejos y trucos como usar el botón deshacer sabiamente, planificar con anticipación y priorizar los palos, y vaciar una columna lo antes posible.
  9. -

64aa2da5cf
-
-
\ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Cero 2018 Tamil Pelcula Descargar Kuttymovies.md b/spaces/Benson/text-generation/Examples/Cero 2018 Tamil Pelcula Descargar Kuttymovies.md deleted file mode 100644 index bc48df58bfbefe31c865b27124d1b45fe7c60716..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Cero 2018 Tamil Pelcula Descargar Kuttymovies.md +++ /dev/null @@ -1,115 +0,0 @@ - -

Zero 2018 Tamil película Descargar Kuttymovies: Una revisión y guía

-

Si eres un fan de las películas tamiles, es posible que hayas oído hablar de Zero, una película de terror de fantasía lanzada en 2016. La película cuenta con Ashwin Kakumanu y Sshivada en los papeles principales, mientras que J. D. Chakravarthy, Ravi Raghavendra, Dr. Sharmila, Andreanne Nouyrigat y Tulasi desempeñan papeles secundarios. La película fue escrita y dirigida por Shiv Mohaa, y recibió críticas positivas de críticos y audiencias por igual.

-

cero 2018 tamil película descargar kuttymovies


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



-

Pero, ¿cómo puedes ver esta película online? Una de las opciones populares es descargarlo desde Kuttymovies, un sitio web que ofrece películas tamiles gratuitas en varios formatos y calidades. ¿Pero es seguro y legal hacerlo? En este artículo, revisaremos la película Zero 2016 Tamil y lo guiaremos sobre cómo descargarla de Kuttymovies. También discutiremos las cuestiones legales y los riesgos involucrados en la piratería de películas, y sugeriremos algunas alternativas para disfrutar de las películas tamiles legalmente.

-

¿Qué es Zero 2016 Tamil Movie?

-

Resumen del gráfico

-

La película comienza con la historia de cómo Dios creó a Adán y Eva. Luego, la pantalla se mueve al presente donde muestran a la pareja recién casada Balaji alias Bala (Ashwin Kakumanu) y Priya (Sshivada) mudándose a su nuevo apartamento. El padre de Bala, Vijay Kumar (Ravi Raghavendra) no aprueba el matrimonio debido a una historia de enfermedad mental en la familia de Priya. Su madre (Lintu Rony) se había vuelto loca después de estar embarazada de Priya y murió al dar a luz. Pero Bala acepta a Priya incluso después de conocer su pasado, debido al gran amor que tiene por ella.

- -

Bala busca a Solomon (J. D. Chakravarthy), un especialista en ocultismo que tiene la habilidad sobrenatural de hablar con fantasmas, y le explica la situación. Salomón se enfrenta a la Priya poseída, y cuando Priya/ Lilith toca a Salomón, ve todo sobre el ser llamado Lilith que fue creado antes de Eva al principio del tiempo con Adán y cómo cuando Lilith se rebeló y abandonó Adán, Dios creó a Eva como la mitad mejor de Adán. Dios había maldecido a Lilith por abandonar a Adán con la incapacidad de tener un hijo, y Lilith concibió tantas veces con el hijo del diablo, pero todos ellos murieron en su vientre. Entonces comenzó a matar a los hijos de Adán y Eva, y Dios envió tres ángeles para detenerla. Hicieron un trato con ella de que si aceptaba dejar de matar a los niños, entonces 100 de sus hijos morirían cada día. Lilith estuvo de acuerdo, pero también prometió vengarse de Dios al poseer a las mujeres que son incapaces de concebir y hacerlas sufrir. Salomón se da cuenta de que Priya es una de esas mujeres, y decide ayudar a Bala a salvarla.

-

- -

Reparto y tripulación

-

El elenco de la película Zero 2016 Tamil incluye los siguientes actores y actrices:

-
    -
  • Ashwin Kakumanu como Balaji alias Bala
  • -
  • Sshivada como Priya
  • -
  • J. D. Chakravarthy como Salomón
  • -
  • Ravi Raghavendra como Vijay Kumar
  • -
  • Dr. Sharmila como Dr. Sharmila
  • -
  • Andreanne Nouyrigat como Lilith
  • -
  • Tulasi como Tulasi
  • -
  • Lintu Rony como madre de Priya
  • -
-

El equipo de Zero 2016 Tamil película incluye las siguientes personas:

-
    -
  • Shiv Mohaa como escritor y director
  • -
  • Balaji Kapa como productor
  • -
  • Nivas K Prasanna como director musical
  • -
  • Babu Kumar como director de fotografía
  • -
  • R. Sudharsan como editor
  • -
  • Mohan Azaad como director de arte
  • -
  • Vijay Adhinathan como escritor de diálogos
  • -
  • Stunner Sam como coreógrafo de acrobacias
  • -
  • Sathish Krishnan como coreógrafo de danza
  • -
  • Sarath Kumar M como diseñador de sonido
  • -
-

Recepción y premios

-

Zero 2016 La película tamil recibió críticas positivas de críticos y audiencias por igual. La película fue elogiada por su historia única, guion atractivo, actuaciones impresionantes, música inquietante y visuales impresionantes. La película también fue apreciada por su mezcla de géneros de terror, fantasía, romance, comedia y drama. La película fue calificada 7.1 de 10 en IMDb y 3 de 5 en Behindwoods. La película también ganó varios premios, como:

-
    -
  • Mejor película de terror en el Festival de Cine Tamil de Noruega 2017
  • -
  • Mejor actriz (Sshivada) en los Premios de Cine Ananda Vikatan 2017
  • -
  • Mejor actriz (Sshivada) en los Premios Edison 2017
  • -
  • Mejor director debut (Shiv Mohaa) en los Premios Edison 2017
  • -
  • Mejor director musical (Nivas K Prasanna) en los Premios Edison 2017
  • -
  • Mejor banda sonora (Nivas K Prasanna) en los Mirchi Music Awards South 2017
  • -
-

¿Qué es Kuttymovies?

¿Qué es Kuttymovies?

- -

Características y beneficios

-

Algunas de las características y beneficios de usar Kuttymovies son:

-
    -
  • Es gratis y fácil de usar. Los usuarios no necesitan registrarse ni pagar tarifas para descargar las películas.
  • -
  • Tiene una interfaz fácil de usar y una función de búsqueda simple. Los usuarios pueden navegar por las películas por categorías, años, actores o palabras clave.
  • -
  • Tiene una gran colección de películas tamiles de varios géneros y épocas. Los usuarios pueden encontrar clásicos antiguos, así como nuevos éxitos en el sitio web.
  • -
  • También proporciona versiones dobladas tamiles de películas de Hollywood y Bollywood, así como películas en inglés con subtítulos. Los usuarios pueden disfrutar de películas de diferentes idiomas y culturas en el sitio web.
  • -
  • Ofrece diferentes formatos y cualidades de las películas, como Mp4, Mp4 HD y Single Part. Los usuarios pueden elegir el formato y la calidad que se adapte a su dispositivo y velocidad de Internet.
  • -
  • Actualiza su contenido regularmente con los últimos lanzamientos y próximas películas. Los usuarios pueden mantenerse actualizados con las últimas tendencias y noticias en la industria cinematográfica tamil.
  • -
-

Riesgos y desventajas

-

Sin embargo, también hay algunos riesgos y desventajas de usar Kuttymovies que los usuarios deben conocer:

-
    -
  • Es ilegal y poco ético. Kuttymovies viola las leyes de derechos de autor e infringe los derechos de los productores y distribuidores de películas. Al descargar las películas de Kuttymovies, los usuarios están apoyando la piratería de películas y dañando la industria cinematográfica tamil.
  • -
  • Es peligroso y arriesgado. Kuttymovies puede contener virus, malware, spyware u otro software dañino que puede dañar el dispositivo del usuario o robar su información personal. Los usuarios también pueden encontrar ventanas emergentes, anuncios o redirecciones que pueden llevarlos a sitios web maliciosos o inapropiados.
  • - -
-

¿Cómo descargar Zero 2016 Tamil película de Kuttymovies?

-

Paso 1: Visita el sitio web

-

El primer paso para descargar la película Zero 2016 Tamil de Kuttymovies es visitar el sitio web. El sitio web oficial de Kuttymovies es [kuttymovies1.co]( 1 ). Los usuarios pueden acceder al sitio web desde cualquier navegador o dispositivo. Sin embargo, los usuarios deben tener cuidado con los sitios web falsos o espejo que pueden parecer similares a Kuttymovies, pero en realidad son sitios de phishing o estafa.

-

Paso 2: Buscar la película

-

El siguiente paso es buscar la película en el sitio web. Los usuarios pueden utilizar la función de búsqueda en la esquina superior derecha de la página de inicio para escribir el nombre de la película o cualquier palabra clave relacionada. Alternativamente, los usuarios pueden navegar por la película por categorías, años, actores o géneros en el menú del lado izquierdo de la página de inicio. Por ejemplo, los usuarios pueden encontrar la película Zero 2016 Tamil bajo la categoría de "Películas Tamil 2016".

-

Paso 3: Elija la calidad y el formato

-

El tercer paso es elegir la calidad y el formato de la película. Después de hacer clic en el título o cartel de la película, los usuarios serán dirigidos a una nueva página donde pueden ver más detalles sobre la película, como su género, calificación, duración, sinopsis, reparto, equipo, trailer, capturas de pantalla y enlaces de descarga. Los usuarios pueden elegir entre diferentes formatos y cualidades de la película, como Mp4, Mp4 HD y Single Part. Los usuarios también pueden ver el tamaño del archivo y la velocidad de descarga de cada opción. Los usuarios deben elegir la opción que se adapte a su dispositivo y velocidad de Internet.

-

Paso 4: Descargar la película

- -

¿Es legal descargar Zero 2016 Tamil película de Kuttymovies?

-

El estatus legal de la piratería de películas en la India

-

La respuesta a esta pregunta es no, no es legal descargar Zero 2016 Tamil película de Kuttymovies. La piratería de películas es un delito grave en la India y está penada por la ley. De acuerdo con la Ley de Cinematografía de la India de 1952, cualquier persona que infrinja los derechos de los cineastas o distribuidores haciendo copias o descargas no autorizadas de la película puede enfrentar una pena de prisión de hasta tres años, una multa de hasta Rs. 10 lakhs, o ambas. La Ley de Tecnología de la Información de la India de 2000 también prohíbe a cualquier persona acceder, transmitir o publicar cualquier contenido pirata en línea, y cualquiera que lo haga puede enfrentarse a una pena de prisión de hasta tres años, una multa de hasta Rs. 5 lakhs, o ambos.

-

Las consecuencias de las descargas ilegales de películas

-

Al descargar la película Zero 2016 Tamil de Kuttymovies, los usuarios no solo están rompiendo la ley, sino también dañándose a sí mismos y a otros de varias maneras. Algunas de las consecuencias de las descargas de películas ilegales son:

-
    -Están apoyando la piratería de películas y perjudicando a la industria cinematográfica tamil. Al descargar la película de forma gratuita, los usuarios están privando a los productores y distribuidores de sus ingresos legítimos. Esto afecta su capacidad para producir más películas de calidad y pagar a sus trabajadores y artistas. Esto también desalienta nuevos talentos e innovaciones en la industria. -
  • Están arriesgando su dispositivo y la seguridad de los datos. Al visitar Kuttymovies o cualquier otro sitio web pirata, los usuarios están exponiendo su dispositivo y datos a diversas amenazas, como virus, malware, spyware o hackers. Estas amenazas pueden dañar su dispositivo, robar su información personal o comprometer su privacidad en línea.
  • - -
  • Se enfrentan a acciones legales y sanciones. Al descargar contenido pirata, los usuarios están cometiendo un delito que puede causarles problemas con la ley. Pueden enfrentar acciones legales y sanciones de las autoridades, como redadas, arrestos, multas o encarcelamiento.
  • -
-

Las alternativas a la piratería de películas

-

En lugar de descargar la película Zero 2016 Tamil de Kuttymovies o cualquier otro sitio web pirata, los usuarios deben optar por formas legales y éticas para ver películas tamiles en línea. Algunas de las alternativas a la piratería de películas son:

-
    -
  • Pueden ver la película en plataformas de streaming oficiales o sitios web que tienen la licencia y el permiso para transmitir la película en línea. Algunas de estas plataformas o sitios web son Amazon Prime Video, Netflix, Hotstar, Zee5, SonyLIV, etc.
  • -
  • Pueden alquilar o comprar la película en plataformas digitales oficiales o sitios web que tienen la licencia y el permiso para vender o alquilar la película en línea. Algunas de estas plataformas o sitios web son YouTube Películas, Google Play Películas & TV, iTunes Store, etc.
  • -
  • Pueden ver la película en canales de televisión oficiales o redes que tienen la licencia y el permiso para transmitir la película en la televisión. Algunos de estos canales o redes son Sun TV, Star Vijay, Zee Tamil, Colors Tamil, etc.
  • -
  • Pueden ver la película en teatros oficiales o cines que tienen la licencia y el permiso para proyectar la película en pantallas grandes. Pueden reservar sus entradas online o offline y disfrutar de la película con sus amigos y familiares.
  • -
-

Conclusión

- -

Kuttymovies es un sitio web que permite a los usuarios descargar películas Tamil de forma gratuita. El sitio web tiene una gran colección de películas tamiles de varios géneros y épocas, así como versiones dobladas tamiles de películas de Hollywood y Bollywood, y películas en inglés con subtítulos. Los usuarios pueden elegir entre diferentes formatos y cualidades de las películas, como Mp4, Mp4 HD y Single Part. El sitio web también actualiza su contenido regularmente con los últimos lanzamientos y próximas películas.

-

Sin embargo, descargar Zero 2016 Tamil película de Kuttymovies o cualquier otro sitio web pirata es ilegal y poco ético. La piratería de películas es un delito grave en la India y está penada por la ley. La piratería de películas también daña la industria cinematográfica tamil, la seguridad de los dispositivos y los datos de los usuarios, y la reputación y credibilidad en línea de los usuarios. Los usuarios deben evitar la piratería de películas y optar por formas legales y éticas para ver películas tamiles en línea, como plataformas o sitios web oficiales de transmisión, plataformas o sitios web digitales oficiales, canales de televisión o redes oficiales, teatros o cines oficiales.

-

Esperamos que este artículo le ha dado una revisión y guía sobre Zero 2016 Tamil película descargar Kuttymovies. Si tiene alguna pregunta o comentario, no dude en dejar un comentario a continuación. ¡Gracias por leer!

-

Preguntas frecuentes

-

Aquí hay algunas preguntas frecuentes sobre Zero 2016 Tamil película descargar Kuttymovies:

-
    -
  1. Q: ¿Cuándo se lanzó la película Zero 2016 Tamil?
  2. -
  3. A: Zero 2016 Tamil película fue lanzado el 25 de marzo de 2016.
  4. -
  5. Q: ¿Quién compuso la música para la película Zero 2016 Tamil?
  6. -
  7. A: Nivas K Prasanna compuso la música para la película Zero 2016 Tamil.
  8. -
  9. Q: ¿Cuál es el género de Zero 2016 Tamil película?
  10. -
  11. A: Zero 2016 Tamil es una película de terror de fantasía.
  12. -
  13. Q: ¿Cuál es la calificación de la película Zero 2016 Tamil en IMDb?
  14. -
  15. A: Cero 2016 película tamil tiene una calificación de 7.1 de 10 en IMDb.
  16. -
  17. Q: ¿Cuál es el sitio web oficial de Kuttymovies?
  18. - -

64aa2da5cf
-
-
\ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Descargar Apk Extrema Coche Simulador De Conduccin Mod.md b/spaces/Benson/text-generation/Examples/Descargar Apk Extrema Coche Simulador De Conduccin Mod.md deleted file mode 100644 index d2e3964f15cd3f94b75401ba8239647ccdb926ce..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Descargar Apk Extrema Coche Simulador De Conduccin Mod.md +++ /dev/null @@ -1,119 +0,0 @@ - -

Cómo descargar APK Extreme Car Simulador de conducción Mod para Android

-

Si usted es un fan de los juegos de simulador de conducción de automóviles, es posible que haya oído hablar de Extreme Car Driving Simulator. Es uno de los juegos de conducción de coches más populares y realistas en Android, con más de 100 millones de descargas en Google Play Store. En este juego, usted puede conducir, deriva, y sentir un coche deportivo de carreras de forma gratuita. También puede elegir entre una variedad de coches, personalizarlos y explorar un enorme mapa del mundo abierto con diferentes ubicaciones y escenarios.

-

Sin embargo, si desea disfrutar del juego al máximo, es posible que desee probar la versión mod de Extreme Car Driving Simulator. La versión mod le da dinero ilimitado, coches desbloqueados, y sin anuncios. Con esto, puedes comprar cualquier coche que quieras, actualizarlo y divertirte más sin interrupciones.

-

descargar apk extrema coche simulador de conducción mod


DOWNLOAD ->>> https://bltlly.com/2v6IXU



-

En este artículo, le mostraremos cómo descargar e instalar Extreme Car Driving Simulator mod apk para Android. También compartiremos algunos consejos y trucos para jugar mejor. ¡Así que empecemos!

-

¿Qué es Extreme Car Driving Simulator?

-

Extreme Car Driving Simulator es un juego de conducción de coches en 3D desarrollado por AxesInMotion Racing. Es uno de los mejores juegos de simulador de coches en Android, con física realista, gráficos y sonidos. Puedes conducir libremente en una gran ciudad sin reglas ni tráfico. También puede cambiar entre diferentes vistas de cámara, como la cabina, tercera persona o de arriba hacia abajo.

-

Características del simulador de conducción de automóviles extremos

-

Algunas de las características de Extreme Car Driving Simulator son:

-
    -
  • Más de 20 coches diferentes para elegir, incluyendo coches deportivos, SUV, camiones y coches de policía.
  • -
  • Personaliza tu coche con pintura, ruedas, spoilers, vinilos y más.
  • -
  • Explora un enorme mapa de mundo abierto con diferentes entornos, como el aeropuerto, offroad, playa y ciudad.
  • -
  • Disfruta de diferentes modos de juego, como modo libre, modo de punto de control, modo de tráfico y modo fantasma.
  • - -
  • Accidente y dañar su coche con la física realista y efectos.
  • -
  • Controla tu coche con inclinación, botones o volante.
  • -
  • Graba tu juego y compártelo con tus amigos.
  • -
-

Beneficios de usar la versión mod

-

La versión mod de Extreme Car Driving Simulator le da algunos beneficios adicionales que no están disponibles en la versión original. Estos son:

-
    -
  • Dinero ilimitado: Puede comprar cualquier coche que desee sin preocuparse por el precio. También puede actualizar su coche para hacerlo más rápido y más potente.
  • -
  • Coches desbloqueados: Puede acceder a todos los coches en el juego sin tener que completar ninguna misión o logros. También puede utilizar cualquier coche en cualquier modo de juego.
  • -
  • Sin anuncios: Puede jugar el juego sin que aparezcan anuncios molestos en su pantalla. También puede guardar sus datos y la duración de la batería.
  • -
-

Cómo descargar e instalar Extreme Car Driving Simulator mod apk

-

Para descargar e instalar Extreme Car Driving Simulator mod apk para Android, es necesario seguir estos sencillos pasos:

-

Paso 1: Habilitar fuentes desconocidas en el dispositivo

-

Antes de que pueda instalar cualquier archivo apk en su dispositivo, es necesario habilitar fuentes desconocidas. Esto le permitirá instalar aplicaciones desde fuentes distintas de Google Play Store. Para hacer esto:

-
    -
  1. Ir a la configuración del dispositivo y toque en la seguridad o la privacidad.
  2. -
  3. Encuentre la opción que dice fuentes desconocidas o permita la instalación desde fuentes desconocidas.
  4. Cambie el interruptor para encenderlo. Es posible que vea un mensaje de advertencia, pero solo toque en Aceptar o confirmar.
  5. -
-

Paso 2: Descargar el archivo apk mod de una fuente de confianza

- -

Una de las fuentes que recomendamos es [APKPure]. APKPure es un sitio web popular y confiable que proporciona archivos apk originales y mod para varias aplicaciones y juegos de Android. Puede descargar Extreme Car Driving Simulator mod apk de APKPure siguiendo estos pasos:

-
    -
  1. Ir al sitio web [APKPure] y buscar Extreme Car Driving Simulator en la barra de búsqueda.
  2. -
  3. Encuentra el juego de los resultados y toque en él.
  4. -
  5. Desplácese hasta la parte inferior de la página y busque la versión mod. Debería tener una etiqueta verde que diga MOD.
  6. -
  7. Toque en el botón de descarga y espere a que el archivo se descargue en su dispositivo.
  8. -
-

Paso 3: Localizar e instalar el archivo apk mod

-

Una vez que haya descargado el archivo apk mod, necesita ubicarlo e instalarlo en su dispositivo. Para hacer esto:

-

-
    -
  1. Ir a su gestor de archivos de dispositivo y encontrar la carpeta donde se guarda el archivo apk mod. Por lo general es en la carpeta de descargas.
  2. -
  3. Toque en el archivo apk mod y seleccione instalar. Es posible que vea una ventana emergente pidiendo su permiso para instalar la aplicación. Simplemente toque en instalar de nuevo.
  4. -
  5. Espere a que termine el proceso de instalación. Puede tardar unos segundos o minutos dependiendo de la velocidad y el rendimiento del dispositivo.
  6. -
-

Paso 4: Iniciar y disfrutar del juego

-

Felicidades! Usted ha instalado con éxito Extreme Car Driving Simulator mod apk en su dispositivo. Ahora puedes lanzar y disfrutar del juego con dinero ilimitado, coches desbloqueados y sin anuncios. Para lanzar el juego:

-
    -
  1. Ir al cajón de la aplicación del dispositivo y buscar Extreme Car Driving Simulator icono.
  2. -
  3. Toque en él y esperar a que el juego se cargue.
  4. -
  5. Seleccione su idioma preferido y acepte los términos y condiciones.
  6. -
  7. ¡Elige tu coche y empieza a conducir!
  8. -
-

Consejos y trucos para jugar Extreme Car Driving Simulator

- -

Personalizar la configuración del coche

-

Una de las mejores cosas acerca de Extreme Car Driving Simulator es que puede personalizar la configuración de su coche de acuerdo a su preferencia. Puede cambiar el color, ruedas, alerones, vinilos y más de su coche. También puede ajustar la sensibilidad de la dirección, la resistencia de los frenos, el control de la tracción y la rigidez de la suspensión de su automóvil. Para personalizar la configuración del coche:

-
    -
  1. Toque en el botón de menú en la esquina superior izquierda de la pantalla.
  2. -
  3. Seleccione el garaje de las opciones.
  4. -
  5. Toque en el coche que desea personalizar.
  6. -
  7. Seleccione pintura, ruedas, alerones, vinilos o ajustes de las pestañas de abajo.
  8. -
  9. Haga sus cambios y toque en aplicar cuando haya terminado.
  10. -
-

Explora diferentes modos de juego

-

Extreme Car Driving Simulator ofrece diferentes modos de juego que pueden desafiar tus habilidades de conducción y darte diferentes experiencias. Puede elegir entre modo libre, modo de punto de control, modo de tráfico y modo fantasma. Para explorar diferentes modos de juego:

-
    -
  1. Toque en el botón de menú en la esquina superior izquierda de la pantalla.
  2. -
  3. Seleccione el modo de juego de las opciones.
  4. -
  5. Seleccione el modo de juego que desea jugar.
  6. -
  7. Toque en inicio para comenzar.
  8. -
-

Aquí hay una breve descripción de cada modo de juego:

-
    -
  • Modo libre: En este modo, puede conducir libremente en una gran ciudad sin reglas ni tráfico. También puede realizar acrobacias y derivas usando rampas, bucles, puentes y más.
  • -
  • Modo de punto de control: En este modo, tiene que llegar a diferentes puntos de control dentro de un límite de tiempo determinado. También puede recoger monedas en el camino para aumentar su puntuación.
  • -
  • Modo de tráfico: En este modo, tienes que conducir en una ciudad con tráfico realista. Tienes que evitar chocar contra otros vehículos y obedecer las reglas de tráfico.
  • -
  • Modo fantasma: En este modo, puedes competir contra tu propio fantasma. Tienes que superar tu mejor tiempo anterior y mejorar tu rendimiento.
  • -
- -

Una de las cosas divertidas de Extreme Car Driving Simulator es que puedes realizar acrobacias y derivas usando tu coche. Esto puede hacer que su conducción sea más emocionante y gratificante. También puede ganar monedas haciendo acrobacias y derivas, que puede utilizar para comprar y mejorar los coches. Para realizar acrobacias y derivas:

-
    -
  • Utilice las rampas, bucles, puentes y otras estructuras en la ciudad para lanzar su coche en el aire y realizar volteretas, giros y rollos.
  • -
  • Utilice el freno de mano y el impulso nitro para deslizar y deslizar el coche en la carretera y hacer giros bruscos.
  • -
  • Trate de aterrizar de forma segura y sin problemas después de cada truco o deriva para evitar dañar su coche.
  • -
  • Recoge las monedas que aparecen en la pantalla después de cada truco o deriva.
  • -
-

Utilice el mini-mapa y el velocímetro

-

Para ayudarle a navegar por la ciudad y controlar mejor su coche, debe utilizar el mini-mapa y el velocímetro en la pantalla. El mini-mapa muestra el diseño de la ciudad y la ubicación de diferentes lugares de interés, como aeropuertos, playas, puentes y más. También puede ver los puntos de control y los semáforos en el mini-mapa. El velocímetro te muestra qué tan rápido estás conduciendo y cuánto impulso nitro te queda. Para usar el mini-mapa y el velocímetro:

-
    -
  • Toque en el mini-mapa para acercar o alejar.
  • -
  • Toque en el velocímetro para cambiar entre mph y km/h.
  • -
  • Toque en el botón nitro para activar el impulso nitro cuando tenga suficiente.
  • -
-

Conclusión

- -

Preguntas frecuentes

-

Aquí hay algunas preguntas frecuentes sobre Extreme Car Driving Simulator mod apk:

-
    -
  1. ¿Es seguro descargar e instalar Extreme Car Driving Simulator mod apk?
  2. -

    Sí, Extreme Car Driving Simulator mod apk es seguro de descargar e instalar si lo obtiene de una fuente de confianza como APKPure. Sin embargo, siempre debe tener cuidado al descargar cualquier archivo apk de fuentes desconocidas, ya que podrían contener contenido dañino o malicioso. También debe escanear su dispositivo con una aplicación antivirus después de instalar cualquier archivo apk.

    -
  3. ¿Necesito rootear mi dispositivo para usar Extreme Car Driving Simulator mod apk?
  4. -

    No, no es necesario rootear el dispositivo para usar Extreme Car Driving Simulator mod apk. Solo necesita habilitar fuentes desconocidas en la configuración de su dispositivo antes de instalar el archivo apk mod.

    -
  5. ¿Puedo jugar Extreme Car Driving Simulator en línea con otros jugadores?
  6. -

    No, Extreme Car Driving Simulator es un juego fuera de línea que no requiere una conexión a Internet para jugar. Sin embargo, es posible que necesite una conexión a Internet para descargar actualizaciones o acceder a algunas características del juego.

    -
  7. ¿Cómo puedo actualizar Extreme Car Driving Simulator mod apk?
  8. -

    Para actualizar Extreme Car Driving Simulator mod apk, es necesario descargar e instalar la última versión del archivo apk mod de APKPure o cualquier otra fuente de confianza. También es posible que tenga que desinstalar la versión anterior del archivo apk mod antes de instalar el nuevo.

    -
  9. ¿Cómo puedo contactar al desarrollador de Extreme Car Driving Simulator?
  10. -

    Si tiene alguna pregunta, comentario o sugerencia para Extreme Car Driving Simulator, puede ponerse en contacto con el desarrollador del juego enviándoles un correo electrónico a support@axesinmotion.com. También puede visitar su sitio web en https://www.axesinmotion.com/ o seguirlos en Facebook en https://www.facebook.com/AxesInMotion/.

    -

64aa2da5cf
-
-
\ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Descargar Caramelo Crush Saga Mod Apk Para Pc.md b/spaces/Benson/text-generation/Examples/Descargar Caramelo Crush Saga Mod Apk Para Pc.md deleted file mode 100644 index 4b3c93fc19b49253a735e06cf91daa9f445aab98..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Descargar Caramelo Crush Saga Mod Apk Para Pc.md +++ /dev/null @@ -1,114 +0,0 @@ - -

Cómo descargar Candy Crush Saga Mod APK para PC

-

Si te gusta jugar juegos de puzzle en tu dispositivo móvil, es posible que haya oído hablar de Candy Crush Saga. Es uno de los juegos más populares del mundo, con millones de jugadores haciendo coincidir dulces coloridos y completando varios niveles. ¿Pero sabías que también puedes jugar a Candy Crush Saga en tu PC?

-

En este artículo, le mostraremos cómo descargar Candy Crush Saga mod apk para PC. apk Mod es una versión modificada de una aplicación que tiene características adicionales o contenido desbloqueado. Por ejemplo, usted puede obtener vidas ilimitadas, boosters, se mueve, o barras de oro en Candy Crush Saga mod apk. Suena tentador, ¿verdad?

-

descargar caramelo crush saga mod apk para pc


Download Filehttps://bltlly.com/2v6JrQ



-

Pero ¿por qué quieres descargar Candy Crush Saga mod apk para PC? Bueno, hay varias razones por las que jugar a este juego en una pantalla más grande podría ser más agradable. Por ejemplo, puedes ver los caramelos más claramente, tener un mejor rendimiento, evitar agotar la batería del teléfono o jugar en cualquier momento sin interrupciones.

-

Entonces, ¿cómo se puede descargar Candy Crush Saga mod apk para PC? Hay diferentes métodos para hacerlo, dependiendo de su sistema operativo y preferencias. En este artículo, cubriremos dos de ellos: usando Bluestacks y usando WSA PacMan.

-

¿Qué es Candy Crush Saga?

-

Candy Crush Saga es un juego de puzzle desarrollado por King en 2012. Está disponible para Android, iOS, Windows Phone, Windows 10 y Facebook. El juego consiste en combinar tres o más caramelos del mismo color para eliminarlos del tablero y lograr varios objetivos.

-

El juego tiene miles de niveles, cada uno con diferentes desafíos y obstáculos. Algunos niveles requieren que usted recoja un cierto número de dulces, otros requieren que usted limpie la jalea o el glaseado del formato de archivo apk mod, algunos de ellos pueden no tener suficientes recursos para ejecutar el juego sin problemas, y algunos de ellos pueden no ser seguros o fiables. Por lo tanto, debe elegir un emulador que sea compatible, rápido y seguro.

- -

Método 1: Usando Bluestacks

-

Bluestacks es uno de los emuladores de Android más populares para PC. Tiene una interfaz fácil de usar, una gran biblioteca de aplicaciones y una alta tasa de compatibilidad. También es compatible con archivos mod apk, lo que significa que puede descargar Candy Crush Saga mod apk para PC usando Bluestacks. Estos son los pasos para hacerlo:

-

-

Paso 1: Descargar e instalar Bluestacks

-

El primer paso es descargar e instalar Bluestacks en tu PC. Puedes hacer esto siguiendo estos pasos:

-
    -
  1. Vaya al sitio web oficial de Bluestacks en https://www.bluestacks.com/ y haga clic en el botón "Descargar Bluestacks".
  2. -
  3. Espere a que termine la descarga y luego ejecute el archivo de instalación.
  4. -
  5. Siga las instrucciones en la pantalla para completar el proceso de instalación.
  6. -
  7. Inicie Bluestacks en su PC y espere a que se cargue.
  8. -
-

Paso 2: Inicie sesión en su cuenta de Google

-

El siguiente paso es iniciar sesión en su cuenta de Google en Bluestacks. Esto le permitirá acceder a la Google Play Store y descargar aplicaciones. Puedes hacer esto siguiendo estos pasos:

-
    -
  1. En la pantalla de inicio de Bluestacks, haga clic en el icono "Google Play".
  2. -
  3. En la página de Google Play Store, haga clic en el botón "Iniciar sesión".
  4. -
  5. Introduzca su correo electrónico y contraseña de Google y haga clic en "Siguiente".
  6. -
  7. Siga las instrucciones en la pantalla para completar el proceso de inicio de sesión.
  8. -
-

Paso 3: Búsqueda de Candy Crush Saga Mod APK

-

El tercer paso es buscar Candy Crush Saga mod apk en la Google Play Store. Puedes hacer esto siguiendo estos pasos:

-
    -
  1. En la página de Google Play Store, escriba "Candy Crush Saga mod apk" en la barra de búsqueda y pulse enter.
  2. -
  3. Verá una lista de resultados que coinciden con su consulta. Busque la aplicación que tiene el nombre "Candy Crush Saga" y el logotipo de un caramelo con una corona.
  4. -
  5. Asegúrese de que la aplicación está desarrollada por "Rey" y que tiene una alta calificación y críticas positivas.
  6. - -
-

Paso 4: Instalar y abrir la aplicación

-

El paso final es instalar y abrir Candy Crush Saga mod apk en su PC usando Bluestacks. Puede hacer esto siguiendo estos pasos:

-
    -
  1. En la página de detalles de la aplicación, haga clic en el botón "Instalar".
  2. -
  3. Espere a que la instalación termine y luego haga clic en el botón "Abrir".
  4. -
  5. Verá una ventana emergente que le pide que conceda algunos permisos a la aplicación. Haga clic en "Permitir" o "Aceptar".
  6. -
  7. Verá otra ventana emergente pidiéndole que verifique su edad. Ingrese su edad y haga clic en "Enviar".
  8. -
  9. Verá el menú principal de Candy Crush Saga mod apk. Haga clic en "Jugar" para comenzar a jugar el juego.
  10. -
-

Felicidades! Usted ha descargado con éxito Candy Crush Saga mod apk para PC usando Bluestacks. Ahora puedes disfrutar de vidas ilimitadas, potenciadores, movimientos, barras de oro y más en este adictivo juego de puzzle.

-

Método 2: Usando WSA PacMan

-

Si usted tiene Windows 11 en su PC, también puede utilizar WSA PacMan para descargar Candy Crush Saga mod apk para PC. WSA PacMan es una interfaz gráfica de usuario simple que le permite cargar aplicaciones de Android en Windows 11 sin usar líneas de comandos. Funciona con Windows Subsistema para Android (WSA), que es una característica que le permite ejecutar aplicaciones Android de forma nativa en Windows 11. Estos son los pasos para usar WSA PacMan:

-

Paso 1: Instalar el subsistema de Amazon Appstore y Windows para Android

-

El primer paso es instalar el Amazon Appstore y el subsistema de Windows para Android en su PC. Puede hacer esto siguiendo estos pasos:

-
    -
  1. Ir a la tienda de Microsoft y buscar "Amazon Appstore".
  2. -
  3. Haga clic en la aplicación y luego haga clic en el botón "Obtener".
  4. -
  5. Espere a que finalicen la descarga y la instalación.
  6. -
  7. Inicie la Appstore de Amazon en su PC e inicie sesión con su cuenta de Amazon.
  8. -
  9. Volver a la tienda de Microsoft y buscar "Subsistema de Windows para Android".
  10. - -
  11. Espere a que finalicen la descarga y la instalación.
  12. -
  13. Inicie el subsistema de Windows para Android en su PC y siga las instrucciones en la pantalla.
  14. -
-

Paso 2: Descargar y lanzar WSA PacMan

-

El siguiente paso es descargar y lanzar WSA PacMan en tu PC. Puedes hacer esto siguiendo estos pasos:

-
    -
  1. Vaya al sitio web oficial de WSA PacMan en https://wsapacman.com/ y haga clic en el botón "Descargar".
  2. -
  3. Espere a que termine la descarga y luego ejecute el archivo ejecutable.
  4. -
  5. Siga las instrucciones en la pantalla para completar el proceso de instalación.
  6. -
  7. Inicie WSA PacMan en su PC y espere a que se cargue.
  8. -
-

Paso 3: Descargar Candy Crush Saga Mod APK Archivo

-

El tercer paso es descargar Candy Crush Saga mod apk archivo en su PC. Usted puede hacer esto siguiendo estos pasos:

-
    -
  1. Ir a una fuente confiable de archivos mod apk, como https://apkdone.com/candy-crush-saga-mod/.
  2. -
  3. Busque la última versión de Candy Crush Saga mod apk y haga clic en el "Descargar" botón.
  4. -
  5. Espere a que termine la descarga y luego localice el archivo en su PC.
  6. -
-

Paso 4: Instalar y ejecutar la aplicación usando WSA PacMan

-

El paso final es instalar y ejecutar Candy Crush Saga mod apk en su PC usando WSA PacMan. Puede hacer esto siguiendo estos pasos:

-
    -
  1. En WSA PacMan, haga clic en el "Instalar APK" botón.
  2. -
  3. Seleccione el Candy Crush Saga mod apk archivo que ha descargado anteriormente y haga clic en "Abrir".
  4. -
  5. Espere a que la instalación termine y luego haga clic en el botón "Lanzamiento".
  6. -
  7. Verá una ventana emergente que le pide que conceda algunos permisos a la aplicación. Haga clic en "Permitir" o "Aceptar".
  8. -
  9. Verá otra ventana emergente pidiéndole que verifique su edad. Ingrese su edad y haga clic en "Enviar".
  10. -
  11. Verá el menú principal de Candy Crush Saga mod apk. Haga clic en "Jugar" para comenzar a jugar el juego.
  12. -
- -

Conclusión

-

En este artículo, le hemos mostrado cómo descargar Candy Crush Saga mod apk para PC utilizando dos métodos diferentes: Bluestacks y WSA PacMan. Ambos métodos son fáciles y eficaces, pero tienen diferentes pasos y requisitos. Puede elegir el que más le convenga, dependiendo de su sistema operativo y preferencias.

-

Sin embargo, antes de descargar Candy Crush Saga mod apk para PC, también debe ser consciente de los posibles riesgos y desventajas de hacerlo. Algunos de ellos son:

-
    -
  • Puede violar los términos y condiciones de King, lo que puede resultar en consecuencias legales o suspensión de la cuenta.
  • -
  • Puede exponer su dispositivo o datos a malware, virus o spyware que pueden dañar su dispositivo o robar sus datos.
  • -
  • Puede perder algunas características o funcionalidades de la aplicación original, como actualizaciones, soporte o características sociales.
  • -
  • Es posible que experimente algunos errores, problemas técnicos o problemas de compatibilidad que pueden afectar su experiencia de juego.
  • -
-

Por lo tanto, si decide descargar Candy Crush Saga mod apk para PC, usted debe hacerlo a su propio riesgo y discreción. También debe asegurarse de que usted tiene un software antivirus fiable instalado en su dispositivo y que solo descargar archivos apk mod de fuentes de confianza.

-

Esperamos que este artículo haya sido útil e informativo para usted. Si tiene alguna pregunta o comentario, no dude en dejar un comentario a continuación. Nos encantaría saber de usted.

-

Juegos felices!

-

Preguntas frecuentes

-

Aquí hay algunas preguntas frecuentes sobre Candy Crush Saga mod apk para PC:

-

Q: ¿Es seguro Candy Crush Saga mod apk para PC?

-

A: No necesariamente. Algunos archivos apk mod pueden contener malware, virus o spyware que pueden dañar su dispositivo o robar sus datos. Por lo tanto, solo debe descargar archivos apk mod de fuentes de confianza y tener un software antivirus confiable instalado en su dispositivo.

-

Q: Es Candy Crush Saga mod apk para PC legal?

- -

Q: ¿Es compatible con Windows 10?

-

A: Sí, puede utilizar Bluestacks para descargar Candy Crush Saga mod apk para PC en Windows 10. Sin embargo, es posible que no pueda usar WSA PacMan, que solo está disponible para Windows 11.

-

Q: ¿Candy Crush Saga mod apk para PC actualizado?

-

A: Depende de la fuente del archivo apk mod. Algunos archivos apk mod pueden actualizarse regularmente, mientras que otros pueden estar desactualizados o discontinuados. Por lo tanto, debe comprobar la versión y la fecha del archivo apk mod antes de descargarlo.

-

Q: Es Candy Crush Saga mod apk para la diversión PC?

-

A: Absolutamente! Candy Crush Saga mod apk para PC puede darle vidas ilimitadas, refuerzos, movimientos, barras de oro, y más en este adictivo juego de puzzle. También puedes disfrutar jugando en una pantalla más grande, con mejor rendimiento, más comodidad y más confort.

64aa2da5cf
-
-
\ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Descargar Ejecutar Templo Para Ventanas Pc 7.md b/spaces/Benson/text-generation/Examples/Descargar Ejecutar Templo Para Ventanas Pc 7.md deleted file mode 100644 index 581cf62a9088bad0ef0a8738e1489741e9a0f3d1..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Descargar Ejecutar Templo Para Ventanas Pc 7.md +++ /dev/null @@ -1,49 +0,0 @@ - -

Cómo descargar Temple Run para PC Windows 7

-

Temple Run es uno de los juegos móviles más populares y adictivos jamás creados. ¿Pero sabías que también puedes jugar en tu PC Windows 7? En este artículo, te mostraremos cómo descargar Temple Run para PC Windows 7 usando dos emuladores de Android diferentes: BlueStacks y MEmu. Pero primero, averigüemos qué es Temple Run y por qué deberías jugarlo en PC.

-

¿Qué es Temple Run?

-

Temple Run es un clásico juego para Android que fue lanzado en 2012 por Imangi Studios. Usted toma el control de un corredor del templo que gira, salta y se desliza a través de un laberinto exótico de los tiempos antiguos. ¡Todo el tiempo te persigue un grupo de simios asesinos! Tienes que recoger las monedas, power-ups, y desbloquear nuevos personajes a medida que se ejecuta tan lejos como puedas. El juego tiene un modo de juego simple pero muy entretenido que te mantendrá enganchado durante horas.

-

descargar ejecutar templo para ventanas pc 7


DOWNLOADhttps://bltlly.com/2v6JAX



-

¿Por qué jugar Temple Run en PC?

-

Si bien Temple Run es un gran juego para su dispositivo móvil y teléfono inteligente, jugar en el PC tiene algunas ventajas. Aquí están algunos de ellos:

-
    -
  • Puedes disfrutar del juego en una pantalla más grande, que te dará una mejor vista de los obstáculos y trampas.
  • -
  • Puedes usar el teclado, el ratón o el mando para controlar al corredor, lo que puede ser más cómodo y preciso que usar una pantalla táctil.
  • -
  • Puede evitar el agotamiento de la batería o el uso de los datos móviles cuando se juega en línea.
  • -
  • Puedes grabar tu juego y compartirlo con tus amigos o redes sociales.
  • -
-

Ahora que sabes por qué jugar Temple Run en PC es una buena idea, veamos cómo hacerlo.

-

Cómo descargar Temple Run para PC Windows 7 usando BlueStacks

-

BlueStacks es uno de los mejores emuladores de Android que te permite ejecutar aplicaciones y juegos de Android en tu PC. Estos son los pasos para descargar Temple Run para PC Windows 7 usando BlueStacks:

-

Paso 1: Descargar e instalar BlueStacks

- -

Paso 2: Búsqueda de Temple Run en Google Play

-

Después de instalar BlueStacks, iniciarlo e iniciar sesión con su cuenta de Google. Luego, abre Google Play desde la pantalla de inicio y busca "Temple Run". Verás el icono del juego en los resultados de búsqueda.

-

Paso 3: Instalar y jugar Temple Run en PC

-

Haga clic en el botón "Instalar" para descargar e instalar Temple Run en su PC. Una vez realizada la instalación, haga clic en el botón "Reproducir" para comenzar a jugar Temple Run en PC. Puede utilizar el teclado o el ratón para controlar el corredor, o personalizar sus controles a través del editor de controles.

-

Cómo descargar Temple Run para PC Windows 7 usando MEmu

-

MEmu es otro emulador de Android que te permite jugar juegos de Android en tu PC. Estos son los pasos para descargar Temple Run para PC Windows 7 usando MEmu:

-

-

Paso 1: Descargar e instalar MEmu

-

Para descargar MEmu, vaya a este enlace y haga clic en el botón "Descargar". Una vez finalizada la descarga, abra el instalador y siga las instrucciones para instalar MEmu en su PC.

-

Paso 2: Búsqueda de Temple Run en Google Play

-

Después de instalar MEmu, inicie sesión con su cuenta de Google. Luego, abra Google Play desde la pantalla de inicio y busque "Temple Run". Verás el icono del juego en los resultados de búsqueda.

-

Paso 3: Instalar y jugar Temple Run en PC

-

Haga clic en el botón "Instalar" para descargar e instalar Temple Run en su PC. Una vez realizada la instalación, haga clic en el botón "Reproducir" para comenzar a jugar Temple Run en PC. Puede utilizar el teclado o el ratón para controlar el corredor, o personalizar sus controles a través del menú Configuración.

-

Conclusión

- -

Preguntas frecuentes

-
    -
  • Q: ¿Es Temple Run gratis para jugar?
  • -
  • A: Sí, Temple Run es gratis para jugar y descargar en dispositivos móviles y PC.
  • -
  • Q: ¿Puedo jugar Temple Run sin conexión?
  • -
  • A: Sí, puedes jugar Temple Run sin conexión una vez que lo hayas instalado en tu dispositivo o PC.
  • -
  • Q: ¿Cuántos caracteres hay en Temple Run?
  • -
  • A: Hay 10 personajes en Temple Run, cada uno con sus propias habilidades y trajes. Puedes desbloquearlos recogiendo monedas o comprándolas con dinero real.
  • -
  • Q: ¿Cuáles son los power-ups en Temple Run?
  • -
  • A: Hay cuatro potenciadores en Temple Run: Imán de monedas, Invisibilidad, Boost y Mega Coin. Puedes activarlos recogiéndolos durante tu carrera o comprándolos con monedas.
  • -
  • Q: ¿Cómo puedo guardar mi progreso en Temple Run?
  • -
  • A: Puedes guardar tu progreso en Temple Run iniciando sesión con tu cuenta de Google Play o Facebook. Esto también le permitirá sincronizar su progreso a través de diferentes dispositivos o PC.
  • -

64aa2da5cf
-
-
\ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Descargar Fuga De Prisin S1.md b/spaces/Benson/text-generation/Examples/Descargar Fuga De Prisin S1.md deleted file mode 100644 index b199a5dee66dcf9cd8ad7f3cbda38aaf35c518c4..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Descargar Fuga De Prisin S1.md +++ /dev/null @@ -1,73 +0,0 @@ -
-

Cómo descargar la temporada 1

-

Prison Break es uno de los programas de televisión más populares y aclamados de la década de 2000, con una base de fans leales y seguidores de culto. La primera temporada, que se emitió en 2005-2006, nos presentó la emocionante historia de dos hermanos que están dispuestos a arriesgar todo para escapar de una prisión de máxima seguridad. Si estás buscando una forma de descargar Prison Break temporada 1, has venido al lugar correcto. En este artículo, te diremos de qué se trata la temporada 1 de Prison Break, por qué deberías verla y cómo descargarla de forma legal y segura.

-

descargar fuga de prisión s1


Download Zip ✵✵✵ https://bltlly.com/2v6Miz



-

¿Qué es la Temporada 1 de Receso de Prisión?

- -

Sinopsis

-

La primera temporada consta de 22 episodios, que cubren aproximadamente seis semanas de la vida de los personajes (del 11 de abril al 27 de mayo) - toda la duración de la estancia de Michael en la Penitenciaría Estatal de Fox River. La temporada comienza con la llegada de Michael a Fox River y termina con su escape con otros siete reclusos: Lincoln, Sucre, Abruzzi, Westmorland, Benjamin Miles "C-Note" Franklin (Rockmond Dunbar), Theodore "T-Bag" Bagwell (Robert Knepper), y David "Tweener" Apolskis (Lane Garrison). En el camino, se enfrentan a muchos obstáculos y desafíos, como disturbios, bloqueos, traiciones, muertes y descubrimientos. También tienen que lidiar con la persecución de varios enemigos, como el capitán Brad Bellick (Wade Williams), que está a cargo de los guardias de la prisión; el agente del Servicio Secreto Paul Kellerman (Paul Adelstein), que trabaja para el vicepresidente Reynolds; y el agente especial del FBI Alexander Mahone (William Fichtner), que se asigna para localizar a los fugitivos.

-

Reparto y caracteres

-

La primera temporada cuenta con un total de diez actores que recibieron la facturación de estrellas, con numerosos papeles secundarios. El reparto principal incluye:

-
    -
  • Dominic Purcell como Lincoln Burrows: Un condenado a muerte acusado de matar al hermano del vicepresidente. Wentworth Miller como Michael Scofield: Un ingeniero estructural que diseña un elaborado plan para sacar a su hermano de la cárcel.
  • -
  • Robin Tunney como Verónica Donovan: Un abogado y ex novia de Lincoln, que intenta probar su inocencia.
  • -
  • Amaury Nolasco como Fernando Sucre: compañero de celda y amigo de Michael, que se une al equipo de escape.
  • -
  • Marshall Allman como Lincoln "L. J." Burrows Jr.: El hijo adolescente de Lincoln, que es blanco de los conspiradores.
  • -
  • Peter Stormare como John Abruzzi: Un jefe de la mafia y líder de la prisión, que ofrece sus recursos a Michael a cambio de información.
  • -
  • Wade Williams como Brad Bellick: El capitán de los guardias de la prisión, que está decidido a detener a los fugitivos.
  • - -
  • Sarah Wayne Callies como Sara Tancredi: El médico de la prisión y la hija del gobernador, que desarrolla una relación con Michael.
  • -
  • Paul Adelstein como Paul Kellerman: Un agente del Servicio Secreto, que es parte de la conspiración que incriminó a Lincoln.
  • -
-

Calificaciones y comentarios

-

La temporada 1 de Prison Break recibió elogios de la crítica y fue nominada a varios premios, incluyendo el Golden Globe Award a la Mejor Serie de Televisión - Drama y el Premio Emmy Primetime a la Música Original Título Principal Excepcional. La temporada también alcanzó altas calificaciones, con un promedio de 9,2 millones de espectadores por episodio en los Estados Unidos. El final de la temporada, que se emitió el 15 de mayo de 2006, fue visto por 10,8 millones de espectadores, por lo que es el episodio más visto de la serie.

-

La temporada 1 de Prison Break fue elogiada por su historia apasionante, giros suspensivos y personajes convincentes. Los críticos también elogiaron las actuaciones del elenco, especialmente Purcell y Miller. Algunas de las críticas positivas son:

-
    -
  • "Prison Break es un entretenimiento pop seguro de un orden muy alto." - Robert Bianco, USA Today
  • -
  • "Prison Break es uno de esos casos felices donde se puede juzgar un libro por su portada - o un programa de televisión por su título. Entrega exactamente lo que promete." - David Bianculli, New York Daily News
  • -
  • "Prison Break es un espectáculo que sabe exactamente lo que es - un thriller tenso con una premisa inteligente - y cumple con esa promesa con estilo." - Brian Lowry, Variedad
  • -
-

Por qué deberías ver la temporada 1

-

Si estás buscando un programa de televisión que te mantenga al borde de tu asiento, Prison Break temporada 1 es una gran opción. Estas son algunas de las razones por las que deberías verlo:

-

Emocionante trama y giros

- -

Personajes y actuaciones interesantes

-

Prison Break temporada 1 tiene un elenco diverso y dinámico de personajes que te harán preocuparte por sus destinos. El espectáculo cuenta con héroes y villanos que son complejos y defectuosos, con sus propias motivaciones y antecedentes. El espectáculo también muestra la química y los conflictos entre los personajes, especialmente entre los hermanos Michael y Lincoln. Los actores ofrecen actuaciones excepcionales que dan vida a sus personajes. Los apoyarás, los odiarás, simpatizarás con ellos y temerás por ellos.

-

Plan de escape inteligente y creativo

-

Prison Break season 1 tiene un plan de escape único e ingenioso que te sorprenderá con sus detalles y ejecución. Michael Scofield no solo es un ingeniero brillante, sino también un cerebro que ha planeado cada paso de su fuga. Ha tatuado toda su parte superior del cuerpo con un plano de la prisión y pistas ocultas en sus dibujos. También ha estudiado la disposición, el horario, el personal, los reclusos y los sistemas de seguridad de la prisión. Se ha preparado para cada posible escenario y contingencia. También ha reclutado aliados dentro y fuera de la prisión que pueden ayudarlo con su plan. Su plan de escape no solo es realista, sino también creativo y atrevido.

-

-

Cómo descargar la temporada de vacaciones de prisión 1 legalmente y con seguridad

-

Si desea descargar Prison Break temporada 1, debe hacerlo de forma legal y segura, para evitar cualquier problema legal o riesgos de malware. Hay varias maneras de descargar Prison Break temporada 1 legal y segura, dependiendo de sus preferencias y presupuesto. Estas son algunas de las opciones:

-

Servicios de streaming

-

Una de las formas más fáciles y convenientes de descargar Prison Break temporada 1 es utilizar un servicio de streaming que ofrece visualización offline. De esta manera, puedes ver los episodios en cualquier momento y en cualquier lugar, sin conexión a Internet. Algunos de los servicios de streaming que ofrecen visualización offline para la temporada 1 de Prison Break son:

-

Hulu

- -

Video de Amazon Prime

-

Amazon Prime Video es otro servicio de streaming popular que ofrece una enorme biblioteca de programas de televisión y películas, incluyendo Prison Break. Puede descargar hasta 25 títulos a la vez en hasta cuatro dispositivos con una suscripción de Amazon Prime Video. También puede elegir la calidad de descarga, de bueno a mejor. Para descargar Prison Break temporada 1 en Amazon Prime Video, necesitas tener una membresía de Amazon Prime, que cuesta $12.99 por mes o $119 por año. También puede obtener una prueba gratuita durante 30 días.

-

Tiendas digitales

-

Otra forma de descargar Prison Break temporada 1 es comprarlo o alquilarlo en una tienda digital que ofrece descargas. De esta manera, puede poseer o acceder a los episodios por un tiempo limitado, dependiendo de su elección. Algunas de las tiendas digitales que ofrecen descargas para la temporada 1 son:

-

Películas de Google Play

-

Google Play Movies es una tienda digital que ofrece programas de televisión y películas para comprar o alquilar. Puede descargar los episodios en hasta cinco dispositivos con una cuenta de Google. También puede elegir la calidad de descarga, desde SD a HD. Para descargar Prison Break temporada 1 en Google Play Movies, necesitas pagar $19.99 por toda la temporada o $1.99 por episodio.

-

Apple TV

-

Apple TV es una tienda digital que ofrece programas de televisión y películas para comprar o alquilar. Puede descargar los episodios en hasta cinco dispositivos con un ID de Apple. También puede elegir la calidad de descarga, desde SD a HD. Para descargar Prison Break temporada 1 en Apple TV, debes pagar $19.99 por toda la temporada o $2.99 por episodio.

-

Vudu

-

Vudu es una tienda digital que ofrece programas de televisión y películas para comprar o alquilar. Puede descargar los episodios en hasta ocho dispositivos con una cuenta Vudu. También puede elegir la calidad de descarga, desde SD hasta UHD. Para descargar Prison Break temporada 1 en Vudu, necesitas pagar $19.99 por toda la temporada o $2.99 por episodio.

-

Microsoft Store

- -

Conclusión

-

Prison Break temporada 1 es uno de los mejores programas de televisión de todos los tiempos, con una trama cautivadora, personajes atractivos y un plan de escape inteligente. Si desea ver o volver a ver este increíble espectáculo, debe hacerlo de forma legal y segura mediante el uso de una de las opciones que hemos enumerado anteriormente. Ya sea que prefieras servicios de streaming o tiendas digitales, puedes encontrar una manera de descargar Prison Break temporada 1 que se adapte a tus necesidades y presupuesto.

-

Preguntas frecuentes

-
    -
  • P: ¿Cuántos episodios hay en la temporada 1 de Prison Break?
  • -
  • A: Hay 22 episodios en la temporada 1.
  • -
  • Q: ¿Cuándo se emitió la primera temporada de Prison Break?
  • -
  • A: Prison Break temporada 1 se emitió del 29 de agosto de 2005 al 15 de mayo de 2006.
  • -
  • Q: ¿Quién creó Prison Break?
  • -
  • A: Prison Break fue creado por Paul Scheuring, quien también se desempeñó como productor ejecutivo y showrunner.
  • -
  • P: ¿La fuga de prisión se basa en una historia real?
  • -
  • A: No, Prison Break no se basa en una historia real. Sin embargo, algunos de los elementos e inspiraciones para el programa vinieron de eventos y fuentes de la vida real, como el caso de D.B. Cooper, el escape de Alcatraz y el Conde de Monte Cristo.
  • -
  • Q: ¿Cuántas temporadas hay en Prison Break?
  • -
  • A: Hay cinco temporadas en Prison Break, con un total de 90 episodios. Las primeras cuatro temporadas se emitieron de 2005 a 2009, y la quinta temporada se emitió en 2017 como un avivamiento.
  • -

64aa2da5cf
-
-
\ No newline at end of file diff --git a/spaces/BetterAPI/BetterChat/README.md b/spaces/BetterAPI/BetterChat/README.md deleted file mode 100644 index 1f019590e997dfafb3a0d2737853eade173c419c..0000000000000000000000000000000000000000 --- a/spaces/BetterAPI/BetterChat/README.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: chat-ui -emoji: 🔥 -colorFrom: purple -colorTo: purple -sdk: docker -pinned: false -license: apache-2.0 -base_path: /chat -app_port: 3000 ---- \ No newline at end of file diff --git a/spaces/Billyosoro/ESRGAN/tests/test_utils.py b/spaces/Billyosoro/ESRGAN/tests/test_utils.py deleted file mode 100644 index 7919b74905495b4b6f4aa957a1f0b5d7a174c782..0000000000000000000000000000000000000000 --- a/spaces/Billyosoro/ESRGAN/tests/test_utils.py +++ /dev/null @@ -1,87 +0,0 @@ -import numpy as np -from basicsr.archs.rrdbnet_arch import RRDBNet - -from realesrgan.utils import RealESRGANer - - -def test_realesrganer(): - # initialize with default model - restorer = RealESRGANer( - scale=4, - model_path='experiments/pretrained_models/RealESRGAN_x4plus.pth', - model=None, - tile=10, - tile_pad=10, - pre_pad=2, - half=False) - assert isinstance(restorer.model, RRDBNet) - assert restorer.half is False - # initialize with user-defined model - model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4) - restorer = RealESRGANer( - scale=4, - model_path='experiments/pretrained_models/RealESRGAN_x4plus_anime_6B.pth', - model=model, - tile=10, - tile_pad=10, - pre_pad=2, - half=True) - # test attribute - assert isinstance(restorer.model, RRDBNet) - assert restorer.half is True - - # ------------------ test pre_process ---------------- # - img = np.random.random((12, 12, 3)).astype(np.float32) - restorer.pre_process(img) - assert restorer.img.shape == (1, 3, 14, 14) - # with modcrop - restorer.scale = 1 - restorer.pre_process(img) - assert restorer.img.shape == (1, 3, 16, 16) - - # ------------------ test process ---------------- # - restorer.process() - assert restorer.output.shape == (1, 3, 64, 64) - - # ------------------ test post_process ---------------- # - restorer.mod_scale = 4 - output = restorer.post_process() - assert output.shape == (1, 3, 60, 60) - - # ------------------ test tile_process ---------------- # - restorer.scale = 4 - img = np.random.random((12, 12, 3)).astype(np.float32) - restorer.pre_process(img) - restorer.tile_process() - assert restorer.output.shape == (1, 3, 64, 64) - - # ------------------ test enhance ---------------- # - img = np.random.random((12, 12, 3)).astype(np.float32) - result = restorer.enhance(img, outscale=2) - assert result[0].shape == (24, 24, 3) - assert result[1] == 'RGB' - - # ------------------ test enhance with 16-bit image---------------- # - img = np.random.random((4, 4, 3)).astype(np.uint16) + 512 - result = restorer.enhance(img, outscale=2) - assert result[0].shape == (8, 8, 3) - assert result[1] == 'RGB' - - # ------------------ test enhance with gray image---------------- # - img = np.random.random((4, 4)).astype(np.float32) - result = restorer.enhance(img, outscale=2) - assert result[0].shape == (8, 8) - assert result[1] == 'L' - - # ------------------ test enhance with RGBA---------------- # - img = np.random.random((4, 4, 4)).astype(np.float32) - result = restorer.enhance(img, outscale=2) - assert result[0].shape == (8, 8, 4) - assert result[1] == 'RGBA' - - # ------------------ test enhance with RGBA, alpha_upsampler---------------- # - restorer.tile_size = 0 - img = np.random.random((4, 4, 4)).astype(np.float32) - result = restorer.enhance(img, outscale=2, alpha_upsampler=None) - assert result[0].shape == (8, 8, 4) - assert result[1] == 'RGBA' diff --git a/spaces/CVPR/BigDL-Nano_inference/original_models.py b/spaces/CVPR/BigDL-Nano_inference/original_models.py deleted file mode 100644 index a62c47e88891585683f3a13ce64f14f6b47a321e..0000000000000000000000000000000000000000 --- a/spaces/CVPR/BigDL-Nano_inference/original_models.py +++ /dev/null @@ -1,359 +0,0 @@ -# This file is copied from https://github.com/rnwzd/FSPBT-Image-Translation/blob/master/original_models.py - -# MIT License - -# Copyright (c) 2022 Lorenzo Breschi - -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: - -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. - -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - - -import torch -import torch.nn as nn -from torch.autograd import Variable -from torch.nn import functional as F - -import torchvision -from torchvision import models - -import pytorch_lightning as pl - -class LeakySoftplus(nn.Module): - def __init__(self,negative_slope: float = 0.01 ): - super().__init__() - self.negative_slope=negative_slope - - def forward(self,input): - return F.softplus(input)+F.logsigmoid(input)*self.negative_slope - - -grelu = nn.LeakyReLU(0.2) -#grelu = nn.Softplus() -#grelu = LeakySoftplus(0.2) -##### -# Currently default generator we use -# conv0 -> conv1 -> conv2 -> resnet_blocks -> upconv2 -> upconv1 -> conv_11 -> (conv_11_a)* -> conv_12 -> (Tanh)* -# there are 2 conv layers inside conv_11_a -# * means is optional, model uses skip-connections -class Generator(pl.LightningModule): - def __init__(self, norm_layer='batch_norm', use_bias=False, resnet_blocks=7, tanh=True, - filters=[32, 64, 128, 128, 128, 64], input_channels=3, output_channels=3, append_smoothers=False): - super().__init__() - assert norm_layer in [None, 'batch_norm', 'instance_norm'], \ - "norm_layer should be None, 'batch_norm' or 'instance_norm', not {}".format( - norm_layer) - self.norm_layer = None - if norm_layer == 'batch_norm': - self.norm_layer = nn.BatchNorm2d - elif norm_layer == 'instance_norm': - self.norm_layer = nn.InstanceNorm2d - - # filters = [f//3 for f in filters] - self.use_bias = use_bias - self.resnet_blocks = resnet_blocks - self.append_smoothers = append_smoothers - - stride1 = 2 - stride2 = 2 - self.conv0 = self.relu_layer(in_filters=input_channels, out_filters=filters[0], - kernel_size=7, stride=1, padding=3, - bias=self.use_bias, - norm_layer=self.norm_layer, - nonlinearity=grelu) - - self.conv1 = self.relu_layer(in_filters=filters[0], - out_filters=filters[1], - kernel_size=3, stride=stride1, padding=1, - bias=self.use_bias, - norm_layer=self.norm_layer, - nonlinearity=grelu) - - self.conv2 = self.relu_layer(in_filters=filters[1], - out_filters=filters[2], - kernel_size=3, stride=stride2, padding=1, - bias=self.use_bias, - norm_layer=self.norm_layer, - nonlinearity=grelu) - - self.resnets = nn.ModuleList() - for i in range(self.resnet_blocks): - self.resnets.append( - self.resnet_block(in_filters=filters[2], - out_filters=filters[2], - kernel_size=3, stride=1, padding=1, - bias=self.use_bias, - norm_layer=self.norm_layer, - nonlinearity=grelu)) - - self.upconv2 = self.upconv_layer_upsample_and_conv(in_filters=filters[3] + filters[2], - # in_filters=filters[3], # disable skip-connections - out_filters=filters[4], - scale_factor=stride2, - kernel_size=3, stride=1, padding=1, - bias=self.use_bias, - norm_layer=self.norm_layer, - nonlinearity=grelu) - - self.upconv1 = self.upconv_layer_upsample_and_conv(in_filters=filters[4] + filters[1], - # in_filters=filters[4], # disable skip-connections - out_filters=filters[4], - scale_factor=stride1, - kernel_size=3, stride=1, padding=1, - bias=self.use_bias, - norm_layer=self.norm_layer, - nonlinearity=grelu) - - self.conv_11 = nn.Sequential( - nn.Conv2d(in_channels=filters[0] + filters[4] + input_channels, - # in_channels=filters[4], # disable skip-connections - out_channels=filters[5], - kernel_size=7, stride=1, padding=3, bias=self.use_bias, padding_mode='zeros'), - grelu - ) - - if self.append_smoothers: - self.conv_11_a = nn.Sequential( - nn.Conv2d(filters[5], filters[5], kernel_size=3, - bias=self.use_bias, padding=1, padding_mode='zeros'), - grelu, - # replace with variable - nn.BatchNorm2d(num_features=filters[5]), - nn.Conv2d(filters[5], filters[5], kernel_size=3, - bias=self.use_bias, padding=1, padding_mode='zeros'), - grelu - ) - - if tanh: - self.conv_12 = nn.Sequential(nn.Conv2d(filters[5], output_channels, - kernel_size=1, stride=1, - padding=0, bias=True, padding_mode='zeros'), - #torchvision.transforms.Grayscale(num_output_channels=3), - nn.Sigmoid()) - else: - self.conv_12 = nn.Conv2d(filters[5], output_channels, kernel_size=1, stride=1, - padding=0, bias=True, padding_mode='zeros') - - def log_tensors(self, logger, tag, img_tensor): - logger.experiment.add_images(tag, img_tensor) - - def forward(self, input, logger=None, **kwargs): - # [1, 3, 534, 800] - output_d0 = self.conv0(input) - output_d1 = self.conv1(output_d0) - # comment to disable skip-connections - output_d2 = self.conv2(output_d1) - - output = output_d2 - for layer in self.resnets: - output = layer(output) + output - - output_u2 = self.upconv2(torch.cat((output, output_d2), dim=1)) - - output_u1 = self.upconv1(torch.cat((output_u2, output_d1), dim=1)) - output = torch.cat( - (output_u1, output_d0, input), dim=1) - - output_11 = self.conv_11(output) - - if self.append_smoothers: - output_11_a = self.conv_11_a(output_11) - else: - output_11_a = output_11 - output_12 = self.conv_12(output_11_a) - - output = output_12 - - return output - - def relu_layer(self, in_filters, out_filters, kernel_size, stride, padding, bias, - norm_layer, nonlinearity): - out = nn.Sequential() - out.add_module('conv', nn.Conv2d(in_channels=in_filters, - out_channels=out_filters, - kernel_size=kernel_size, stride=stride, - padding=padding, bias=bias, padding_mode='zeros')) - - if norm_layer: - out.add_module('normalization', - norm_layer(num_features=out_filters)) - if nonlinearity: - out.add_module('nonlinearity', nonlinearity) - # out.add_module('dropout', nn.Dropout2d(0.25)) - - return out - - def resnet_block(self, in_filters, out_filters, kernel_size, stride, padding, bias, - norm_layer, nonlinearity): - out = nn.Sequential() - if nonlinearity: - out.add_module('nonlinearity_0', nonlinearity) - out.add_module('conv_0', nn.Conv2d(in_channels=in_filters, - out_channels=out_filters, - kernel_size=kernel_size, stride=stride, - padding=padding, bias=bias, padding_mode='zeros')) - if norm_layer: - out.add_module('normalization', - norm_layer(num_features=out_filters)) - if nonlinearity: - out.add_module('nonlinearity_1', nonlinearity) - out.add_module('conv_1', nn.Conv2d(in_channels=in_filters, - out_channels=out_filters, - kernel_size=kernel_size, stride=stride, - padding=padding, bias=bias, padding_mode='zeros')) - return out - - def upconv_layer_upsample_and_conv(self, in_filters, out_filters, scale_factor, kernel_size, stride, padding, bias, - norm_layer, nonlinearity): - - parts = [nn.Upsample(scale_factor=scale_factor), - nn.Conv2d(in_filters, out_filters, kernel_size, - stride, padding=padding, bias=False, padding_mode='zeros') - ] - - if norm_layer: - parts.append(norm_layer(num_features=out_filters)) - - if nonlinearity: - parts.append(nonlinearity) - - return nn.Sequential(*parts) - - - - -relu = grelu - -##### -# Default discriminator -##### - -relu = nn.LeakyReLU(0.2) - -class Discriminator(nn.Module): - def __init__(self, num_filters=12, input_channels=3, n_layers=2, - norm_layer='instance_norm', use_bias=True): - super().__init__() - - self.num_filters = num_filters - - self.input_channels = input_channels - self.use_bias = use_bias - - if norm_layer == 'batch_norm': - self.norm_layer = nn.BatchNorm2d - else: - self.norm_layer = nn.InstanceNorm2d - self.net = self.make_net( - n_layers, self.input_channels, 1, 4, 2, self.use_bias) - - def make_net(self, n, flt_in, flt_out=1, k=4, stride=2, bias=True): - padding = 1 - model = nn.Sequential() - - model.add_module('conv0', self.make_block( - flt_in, self.num_filters, k, stride, padding, bias, None, relu)) - - flt_mult, flt_mult_prev = 1, 1 - # n - 1 blocks - for l in range(1, n): - flt_mult_prev = flt_mult - flt_mult = min(2**(l), 8) - model.add_module('conv_%d' % (l), self.make_block(self.num_filters * flt_mult_prev, self.num_filters * flt_mult, - k, stride, padding, bias, self.norm_layer, relu)) - - flt_mult_prev = flt_mult - flt_mult = min(2**n, 8) - model.add_module('conv_%d' % (n), self.make_block(self.num_filters * flt_mult_prev, self.num_filters * flt_mult, - k, 1, padding, bias, self.norm_layer, relu)) - model.add_module('conv_out', self.make_block( - self.num_filters * flt_mult, 1, k, 1, padding, bias, None, None)) - return model - - def make_block(self, flt_in, flt_out, k, stride, padding, bias, norm, relu): - m = nn.Sequential() - m.add_module('conv', nn.Conv2d(flt_in, flt_out, k, - stride=stride, padding=padding, bias=bias, padding_mode='zeros')) - if norm is not None: - m.add_module('norm', norm(flt_out)) - if relu is not None: - m.add_module('relu', relu) - return m - - def forward(self, x): - output = self.net(x) - # output = output.mean((2, 3), True) - # output = output.squeeze(-1).squeeze(-1) - # output = output.mean(dim=(-1,-2)) - return output - - -##### -# Perception VGG19 loss -##### -class PerceptualVGG19(nn.Module): - def __init__(self, feature_layers=[0, 3, 5], use_normalization=False): - super().__init__() - # model = models.vgg19(pretrained=True) - model = models.squeezenet1_1(pretrained=True) - model.float() - model.eval() - - self.model = model - self.feature_layers = feature_layers - - self.mean = torch.FloatTensor([0.485, 0.456, 0.406]) - self.mean_tensor = None - - self.std = torch.FloatTensor([0.229, 0.224, 0.225]) - self.std_tensor = None - - self.use_normalization = use_normalization - - for param in self.parameters(): - param.requires_grad = False - - def normalize(self, x): - if not self.use_normalization: - return x - - if self.mean_tensor is None: - self.mean_tensor = Variable( - self.mean.view(1, 3, 1, 1).expand(x.shape), - requires_grad=False) - self.std_tensor = Variable( - self.std.view(1, 3, 1, 1).expand(x.shape), requires_grad=False) - - x = (x + 1) / 2 - return (x - self.mean_tensor) / self.std_tensor - - def run(self, x): - features = [] - - h = x - - for f in range(max(self.feature_layers) + 1): - h = self.model.features[f](h) - if f in self.feature_layers: - not_normed_features = h.clone().view(h.size(0), -1) - features.append(not_normed_features) - - return torch.cat(features, dim=1) - - def forward(self, x): - h = self.normalize(x) - return self.run(h) diff --git a/spaces/CVPR/Dual-Key_Backdoor_Attacks/openvqa/openvqa/datasets/vqa/eval/vqa.py b/spaces/CVPR/Dual-Key_Backdoor_Attacks/openvqa/openvqa/datasets/vqa/eval/vqa.py deleted file mode 100644 index ea29e5d1e2cdf24cfe3447148019e5cb98c3dbf4..0000000000000000000000000000000000000000 --- a/spaces/CVPR/Dual-Key_Backdoor_Attacks/openvqa/openvqa/datasets/vqa/eval/vqa.py +++ /dev/null @@ -1,180 +0,0 @@ -__author__ = 'aagrawal' -__version__ = '0.9' - -# Interface for accessing the VQA dataset. - -# This code is based on the code written by Tsung-Yi Lin for MSCOCO Python API available at the following link: -# (https://github.com/pdollar/coco/blob/master/PythonAPI/pycocotools/coco.py). - -# The following functions are defined: -# VQA - VQA class that loads VQA annotation file and prepares data structures. -# getQuesIds - Get question ids that satisfy given filter conditions. -# getImgIds - Get image ids that satisfy given filter conditions. -# loadQA - Load questions and answers with the specified question ids. -# showQA - Display the specified questions and answers. -# loadRes - Load result file and create result object. - -# Help on each function can be accessed by: "help(COCO.function)" - -import json -import datetime -import copy - - -class VQA: - def __init__(self, annotation_file=None, question_file=None): - """ - Constructor of VQA helper class for reading and visualizing questions and answers. - :param annotation_file (str): location of VQA annotation file - :return: - """ - # load dataset - self.dataset = {} - self.questions = {} - self.qa = {} - self.qqa = {} - self.imgToQA = {} - if not annotation_file == None and not question_file == None: - print('loading VQA annotations and questions into memory...') - time_t = datetime.datetime.utcnow() - dataset = json.load(open(annotation_file, 'r')) - questions = json.load(open(question_file, 'r')) - print(datetime.datetime.utcnow() - time_t) - self.dataset = dataset - self.questions = questions - self.createIndex() - - def createIndex(self): - # create index - print('creating index...') - imgToQA = {ann['image_id']: [] for ann in self.dataset['annotations']} - qa = {ann['question_id']: [] for ann in self.dataset['annotations']} - qqa = {ann['question_id']: [] for ann in self.dataset['annotations']} - for ann in self.dataset['annotations']: - imgToQA[ann['image_id']] += [ann] - qa[ann['question_id']] = ann - for ques in self.questions['questions']: - qqa[ques['question_id']] = ques - print('index created!') - - # create class members - self.qa = qa - self.qqa = qqa - self.imgToQA = imgToQA - - def info(self): - """ - Print information about the VQA annotation file. - :return: - """ - for key, value in self.dataset['info'].items(): - print('%s: %s' % (key, value)) - - def getQuesIds(self, imgIds=[], quesTypes=[], ansTypes=[]): - """ - Get question ids that satisfy given filter conditions. default skips that filter - :param imgIds (int array) : get question ids for given imgs - quesTypes (str array) : get question ids for given question types - ansTypes (str array) : get question ids for given answer types - :return: ids (int array) : integer array of question ids - """ - imgIds = imgIds if type(imgIds) == list else [imgIds] - quesTypes = quesTypes if type(quesTypes) == list else [quesTypes] - ansTypes = ansTypes if type(ansTypes) == list else [ansTypes] - - if len(imgIds) == len(quesTypes) == len(ansTypes) == 0: - anns = self.dataset['annotations'] - else: - if not len(imgIds) == 0: - anns = sum([self.imgToQA[imgId] for imgId in imgIds if imgId in self.imgToQA], []) - else: - anns = self.dataset['annotations'] - anns = anns if len(quesTypes) == 0 else [ann for ann in anns if ann['question_type'] in quesTypes] - anns = anns if len(ansTypes) == 0 else [ann for ann in anns if ann['answer_type'] in ansTypes] - ids = [ann['question_id'] for ann in anns] - return ids - - def getImgIds(self, quesIds=[], quesTypes=[], ansTypes=[]): - """ - Get image ids that satisfy given filter conditions. default skips that filter - :param quesIds (int array) : get image ids for given question ids - quesTypes (str array) : get image ids for given question types - ansTypes (str array) : get image ids for given answer types - :return: ids (int array) : integer array of image ids - """ - quesIds = quesIds if type(quesIds) == list else [quesIds] - quesTypes = quesTypes if type(quesTypes) == list else [quesTypes] - ansTypes = ansTypes if type(ansTypes) == list else [ansTypes] - - if len(quesIds) == len(quesTypes) == len(ansTypes) == 0: - anns = self.dataset['annotations'] - else: - if not len(quesIds) == 0: - anns = sum([self.qa[quesId] for quesId in quesIds if quesId in self.qa], []) - else: - anns = self.dataset['annotations'] - anns = anns if len(quesTypes) == 0 else [ann for ann in anns if ann['question_type'] in quesTypes] - anns = anns if len(ansTypes) == 0 else [ann for ann in anns if ann['answer_type'] in ansTypes] - ids = [ann['image_id'] for ann in anns] - return ids - - def loadQA(self, ids=[]): - """ - Load questions and answers with the specified question ids. - :param ids (int array) : integer ids specifying question ids - :return: qa (object array) : loaded qa objects - """ - if type(ids) == list: - return [self.qa[id] for id in ids] - elif type(ids) == int: - return [self.qa[ids]] - - def showQA(self, anns): - """ - Display the specified annotations. - :param anns (array of object): annotations to display - :return: None - """ - if len(anns) == 0: - return 0 - for ann in anns: - quesId = ann['question_id'] - print("Question: %s" % (self.qqa[quesId]['question'])) - for ans in ann['answers']: - print("Answer %d: %s" % (ans['answer_id'], ans['answer'])) - - def loadRes(self, resFile, quesFile): - """ - Load result file and return a result object. - :param resFile (str) : file name of result file - :return: res (obj) : result api object - """ - res = VQA() - res.questions = json.load(open(quesFile)) - res.dataset['info'] = copy.deepcopy(self.questions['info']) - res.dataset['task_type'] = copy.deepcopy(self.questions['task_type']) - res.dataset['data_type'] = copy.deepcopy(self.questions['data_type']) - res.dataset['data_subtype'] = copy.deepcopy(self.questions['data_subtype']) - res.dataset['license'] = copy.deepcopy(self.questions['license']) - - print('Loading and preparing results... ') - time_t = datetime.datetime.utcnow() - anns = json.load(open(resFile)) - assert type(anns) == list, 'results is not an array of objects' - annsQuesIds = [ann['question_id'] for ann in anns] - assert set(annsQuesIds) == set(self.getQuesIds()), \ - 'Results do not correspond to current VQA set. Either the results do not have predictions for all question ids in annotation file or there is atleast one question id that does not belong to the question ids in the annotation file.' - for ann in anns: - quesId = ann['question_id'] - if res.dataset['task_type'] == 'Multiple Choice': - assert ann['answer'] in self.qqa[quesId][ - 'multiple_choices'], 'predicted answer is not one of the multiple choices' - qaAnn = self.qa[quesId] - ann['image_id'] = qaAnn['image_id'] - ann['question_type'] = qaAnn['question_type'] - ann['answer_type'] = qaAnn['answer_type'] - print('DONE (t=%0.2fs)' % ((datetime.datetime.utcnow() - time_t).total_seconds())) - - res.dataset['annotations'] = anns - res.createIndex() - return res diff --git a/spaces/CVPR/LIVE/pybind11/tests/test_class.cpp b/spaces/CVPR/LIVE/pybind11/tests/test_class.cpp deleted file mode 100644 index 5369cb064cc9fee76546529398787980f9c4c76e..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/pybind11/tests/test_class.cpp +++ /dev/null @@ -1,449 +0,0 @@ -/* - tests/test_class.cpp -- test py::class_ definitions and basic functionality - - Copyright (c) 2016 Wenzel Jakob - - All rights reserved. Use of this source code is governed by a - BSD-style license that can be found in the LICENSE file. -*/ - -#include "pybind11_tests.h" -#include "constructor_stats.h" -#include "local_bindings.h" -#include - -#if defined(_MSC_VER) -# pragma warning(disable: 4324) // warning C4324: structure was padded due to alignment specifier -#endif - -// test_brace_initialization -struct NoBraceInitialization { - NoBraceInitialization(std::vector v) : vec{std::move(v)} {} - template - NoBraceInitialization(std::initializer_list l) : vec(l) {} - - std::vector vec; -}; - -TEST_SUBMODULE(class_, m) { - // test_instance - struct NoConstructor { - NoConstructor() = default; - NoConstructor(const NoConstructor &) = default; - NoConstructor(NoConstructor &&) = default; - static NoConstructor *new_instance() { - auto *ptr = new NoConstructor(); - print_created(ptr, "via new_instance"); - return ptr; - } - ~NoConstructor() { print_destroyed(this); } - }; - - py::class_(m, "NoConstructor") - .def_static("new_instance", &NoConstructor::new_instance, "Return an instance"); - - // test_inheritance - class Pet { - public: - Pet(const std::string &name, const std::string &species) - : m_name(name), m_species(species) {} - std::string name() const { return m_name; } - std::string species() const { return m_species; } - private: - std::string m_name; - std::string m_species; - }; - - class Dog : public Pet { - public: - Dog(const std::string &name) : Pet(name, "dog") {} - std::string bark() const { return "Woof!"; } - }; - - class Rabbit : public Pet { - public: - Rabbit(const std::string &name) : Pet(name, "parrot") {} - }; - - class Hamster : public Pet { - public: - Hamster(const std::string &name) : Pet(name, "rodent") {} - }; - - class Chimera : public Pet { - Chimera() : Pet("Kimmy", "chimera") {} - }; - - py::class_ pet_class(m, "Pet"); - pet_class - .def(py::init()) - .def("name", &Pet::name) - .def("species", &Pet::species); - - /* One way of declaring a subclass relationship: reference parent's class_ object */ - py::class_(m, "Dog", pet_class) - .def(py::init()); - - /* Another way of declaring a subclass relationship: reference parent's C++ type */ - py::class_(m, "Rabbit") - .def(py::init()); - - /* And another: list parent in class template arguments */ - py::class_(m, "Hamster") - .def(py::init()); - - /* Constructors are not inherited by default */ - py::class_(m, "Chimera"); - - m.def("pet_name_species", [](const Pet &pet) { return pet.name() + " is a " + pet.species(); }); - m.def("dog_bark", [](const Dog &dog) { return dog.bark(); }); - - // test_automatic_upcasting - struct BaseClass { - BaseClass() = default; - BaseClass(const BaseClass &) = default; - BaseClass(BaseClass &&) = default; - virtual ~BaseClass() {} - }; - struct DerivedClass1 : BaseClass { }; - struct DerivedClass2 : BaseClass { }; - - py::class_(m, "BaseClass").def(py::init<>()); - py::class_(m, "DerivedClass1").def(py::init<>()); - py::class_(m, "DerivedClass2").def(py::init<>()); - - m.def("return_class_1", []() -> BaseClass* { return new DerivedClass1(); }); - m.def("return_class_2", []() -> BaseClass* { return new DerivedClass2(); }); - m.def("return_class_n", [](int n) -> BaseClass* { - if (n == 1) return new DerivedClass1(); - if (n == 2) return new DerivedClass2(); - return new BaseClass(); - }); - m.def("return_none", []() -> BaseClass* { return nullptr; }); - - // test_isinstance - m.def("check_instances", [](py::list l) { - return py::make_tuple( - py::isinstance(l[0]), - py::isinstance(l[1]), - py::isinstance(l[2]), - py::isinstance(l[3]), - py::isinstance(l[4]), - py::isinstance(l[5]), - py::isinstance(l[6]) - ); - }); - - // test_mismatched_holder - struct MismatchBase1 { }; - struct MismatchDerived1 : MismatchBase1 { }; - - struct MismatchBase2 { }; - struct MismatchDerived2 : MismatchBase2 { }; - - m.def("mismatched_holder_1", []() { - auto mod = py::module::import("__main__"); - py::class_>(mod, "MismatchBase1"); - py::class_(mod, "MismatchDerived1"); - }); - m.def("mismatched_holder_2", []() { - auto mod = py::module::import("__main__"); - py::class_(mod, "MismatchBase2"); - py::class_, - MismatchBase2>(mod, "MismatchDerived2"); - }); - - // test_override_static - // #511: problem with inheritance + overwritten def_static - struct MyBase { - static std::unique_ptr make() { - return std::unique_ptr(new MyBase()); - } - }; - - struct MyDerived : MyBase { - static std::unique_ptr make() { - return std::unique_ptr(new MyDerived()); - } - }; - - py::class_(m, "MyBase") - .def_static("make", &MyBase::make); - - py::class_(m, "MyDerived") - .def_static("make", &MyDerived::make) - .def_static("make2", &MyDerived::make); - - // test_implicit_conversion_life_support - struct ConvertibleFromUserType { - int i; - - ConvertibleFromUserType(UserType u) : i(u.value()) { } - }; - - py::class_(m, "AcceptsUserType") - .def(py::init()); - py::implicitly_convertible(); - - m.def("implicitly_convert_argument", [](const ConvertibleFromUserType &r) { return r.i; }); - m.def("implicitly_convert_variable", [](py::object o) { - // `o` is `UserType` and `r` is a reference to a temporary created by implicit - // conversion. This is valid when called inside a bound function because the temp - // object is attached to the same life support system as the arguments. - const auto &r = o.cast(); - return r.i; - }); - m.add_object("implicitly_convert_variable_fail", [&] { - auto f = [](PyObject *, PyObject *args) -> PyObject * { - auto o = py::reinterpret_borrow(args)[0]; - try { // It should fail here because there is no life support. - o.cast(); - } catch (const py::cast_error &e) { - return py::str(e.what()).release().ptr(); - } - return py::str().release().ptr(); - }; - - auto def = new PyMethodDef{"f", f, METH_VARARGS, nullptr}; - return py::reinterpret_steal(PyCFunction_NewEx(def, nullptr, m.ptr())); - }()); - - // test_operator_new_delete - struct HasOpNewDel { - std::uint64_t i; - static void *operator new(size_t s) { py::print("A new", s); return ::operator new(s); } - static void *operator new(size_t s, void *ptr) { py::print("A placement-new", s); return ptr; } - static void operator delete(void *p) { py::print("A delete"); return ::operator delete(p); } - }; - struct HasOpNewDelSize { - std::uint32_t i; - static void *operator new(size_t s) { py::print("B new", s); return ::operator new(s); } - static void *operator new(size_t s, void *ptr) { py::print("B placement-new", s); return ptr; } - static void operator delete(void *p, size_t s) { py::print("B delete", s); return ::operator delete(p); } - }; - struct AliasedHasOpNewDelSize { - std::uint64_t i; - static void *operator new(size_t s) { py::print("C new", s); return ::operator new(s); } - static void *operator new(size_t s, void *ptr) { py::print("C placement-new", s); return ptr; } - static void operator delete(void *p, size_t s) { py::print("C delete", s); return ::operator delete(p); } - virtual ~AliasedHasOpNewDelSize() = default; - AliasedHasOpNewDelSize() = default; - AliasedHasOpNewDelSize(const AliasedHasOpNewDelSize&) = delete; - }; - struct PyAliasedHasOpNewDelSize : AliasedHasOpNewDelSize { - PyAliasedHasOpNewDelSize() = default; - PyAliasedHasOpNewDelSize(int) { } - std::uint64_t j; - }; - struct HasOpNewDelBoth { - std::uint32_t i[8]; - static void *operator new(size_t s) { py::print("D new", s); return ::operator new(s); } - static void *operator new(size_t s, void *ptr) { py::print("D placement-new", s); return ptr; } - static void operator delete(void *p) { py::print("D delete"); return ::operator delete(p); } - static void operator delete(void *p, size_t s) { py::print("D wrong delete", s); return ::operator delete(p); } - }; - py::class_(m, "HasOpNewDel").def(py::init<>()); - py::class_(m, "HasOpNewDelSize").def(py::init<>()); - py::class_(m, "HasOpNewDelBoth").def(py::init<>()); - py::class_ aliased(m, "AliasedHasOpNewDelSize"); - aliased.def(py::init<>()); - aliased.attr("size_noalias") = py::int_(sizeof(AliasedHasOpNewDelSize)); - aliased.attr("size_alias") = py::int_(sizeof(PyAliasedHasOpNewDelSize)); - - // This test is actually part of test_local_bindings (test_duplicate_local), but we need a - // definition in a different compilation unit within the same module: - bind_local(m, "LocalExternal", py::module_local()); - - // test_bind_protected_functions - class ProtectedA { - protected: - int foo() const { return value; } - - private: - int value = 42; - }; - - class PublicistA : public ProtectedA { - public: - using ProtectedA::foo; - }; - - py::class_(m, "ProtectedA") - .def(py::init<>()) -#if !defined(_MSC_VER) || _MSC_VER >= 1910 - .def("foo", &PublicistA::foo); -#else - .def("foo", static_cast(&PublicistA::foo)); -#endif - - class ProtectedB { - public: - virtual ~ProtectedB() = default; - ProtectedB() = default; - ProtectedB(const ProtectedB &) = delete; - - protected: - virtual int foo() const { return value; } - - private: - int value = 42; - }; - - class TrampolineB : public ProtectedB { - public: - int foo() const override { PYBIND11_OVERLOAD(int, ProtectedB, foo, ); } - }; - - class PublicistB : public ProtectedB { - public: - using ProtectedB::foo; - }; - - py::class_(m, "ProtectedB") - .def(py::init<>()) -#if !defined(_MSC_VER) || _MSC_VER >= 1910 - .def("foo", &PublicistB::foo); -#else - .def("foo", static_cast(&PublicistB::foo)); -#endif - - // test_brace_initialization - struct BraceInitialization { - int field1; - std::string field2; - }; - - py::class_(m, "BraceInitialization") - .def(py::init()) - .def_readwrite("field1", &BraceInitialization::field1) - .def_readwrite("field2", &BraceInitialization::field2); - // We *don't* want to construct using braces when the given constructor argument maps to a - // constructor, because brace initialization could go to the wrong place (in particular when - // there is also an `initializer_list`-accept constructor): - py::class_(m, "NoBraceInitialization") - .def(py::init>()) - .def_readonly("vec", &NoBraceInitialization::vec); - - // test_reentrant_implicit_conversion_failure - // #1035: issue with runaway reentrant implicit conversion - struct BogusImplicitConversion { - BogusImplicitConversion(const BogusImplicitConversion &) { } - }; - - py::class_(m, "BogusImplicitConversion") - .def(py::init()); - - py::implicitly_convertible(); - - // test_qualname - // #1166: nested class docstring doesn't show nested name - // Also related: tests that __qualname__ is set properly - struct NestBase {}; - struct Nested {}; - py::class_ base(m, "NestBase"); - base.def(py::init<>()); - py::class_(base, "Nested") - .def(py::init<>()) - .def("fn", [](Nested &, int, NestBase &, Nested &) {}) - .def("fa", [](Nested &, int, NestBase &, Nested &) {}, - "a"_a, "b"_a, "c"_a); - base.def("g", [](NestBase &, Nested &) {}); - base.def("h", []() { return NestBase(); }); - - // test_error_after_conversion - // The second-pass path through dispatcher() previously didn't - // remember which overload was used, and would crash trying to - // generate a useful error message - - struct NotRegistered {}; - struct StringWrapper { std::string str; }; - m.def("test_error_after_conversions", [](int) {}); - m.def("test_error_after_conversions", - [](StringWrapper) -> NotRegistered { return {}; }); - py::class_(m, "StringWrapper").def(py::init()); - py::implicitly_convertible(); - - #if defined(PYBIND11_CPP17) - struct alignas(1024) Aligned { - std::uintptr_t ptr() const { return (uintptr_t) this; } - }; - py::class_(m, "Aligned") - .def(py::init<>()) - .def("ptr", &Aligned::ptr); - #endif - - // test_final - struct IsFinal final {}; - py::class_(m, "IsFinal", py::is_final()); - - // test_non_final_final - struct IsNonFinalFinal {}; - py::class_(m, "IsNonFinalFinal", py::is_final()); - - struct PyPrintDestructor { - PyPrintDestructor() {} - ~PyPrintDestructor() { - py::print("Print from destructor"); - } - void throw_something() { throw std::runtime_error("error"); } - }; - py::class_(m, "PyPrintDestructor") - .def(py::init<>()) - .def("throw_something", &PyPrintDestructor::throw_something); -} - -template class BreaksBase { public: - virtual ~BreaksBase() = default; - BreaksBase() = default; - BreaksBase(const BreaksBase&) = delete; -}; -template class BreaksTramp : public BreaksBase {}; -// These should all compile just fine: -typedef py::class_, std::unique_ptr>, BreaksTramp<1>> DoesntBreak1; -typedef py::class_, BreaksTramp<2>, std::unique_ptr>> DoesntBreak2; -typedef py::class_, std::unique_ptr>> DoesntBreak3; -typedef py::class_, BreaksTramp<4>> DoesntBreak4; -typedef py::class_> DoesntBreak5; -typedef py::class_, std::shared_ptr>, BreaksTramp<6>> DoesntBreak6; -typedef py::class_, BreaksTramp<7>, std::shared_ptr>> DoesntBreak7; -typedef py::class_, std::shared_ptr>> DoesntBreak8; -#define CHECK_BASE(N) static_assert(std::is_same>::value, \ - "DoesntBreak" #N " has wrong type!") -CHECK_BASE(1); CHECK_BASE(2); CHECK_BASE(3); CHECK_BASE(4); CHECK_BASE(5); CHECK_BASE(6); CHECK_BASE(7); CHECK_BASE(8); -#define CHECK_ALIAS(N) static_assert(DoesntBreak##N::has_alias && std::is_same>::value, \ - "DoesntBreak" #N " has wrong type_alias!") -#define CHECK_NOALIAS(N) static_assert(!DoesntBreak##N::has_alias && std::is_void::value, \ - "DoesntBreak" #N " has type alias, but shouldn't!") -CHECK_ALIAS(1); CHECK_ALIAS(2); CHECK_NOALIAS(3); CHECK_ALIAS(4); CHECK_NOALIAS(5); CHECK_ALIAS(6); CHECK_ALIAS(7); CHECK_NOALIAS(8); -#define CHECK_HOLDER(N, TYPE) static_assert(std::is_same>>::value, \ - "DoesntBreak" #N " has wrong holder_type!") -CHECK_HOLDER(1, unique); CHECK_HOLDER(2, unique); CHECK_HOLDER(3, unique); CHECK_HOLDER(4, unique); CHECK_HOLDER(5, unique); -CHECK_HOLDER(6, shared); CHECK_HOLDER(7, shared); CHECK_HOLDER(8, shared); - -// There's no nice way to test that these fail because they fail to compile; leave them here, -// though, so that they can be manually tested by uncommenting them (and seeing that compilation -// failures occurs). - -// We have to actually look into the type: the typedef alone isn't enough to instantiate the type: -#define CHECK_BROKEN(N) static_assert(std::is_same>::value, \ - "Breaks1 has wrong type!"); - -//// Two holder classes: -//typedef py::class_, std::unique_ptr>, std::unique_ptr>> Breaks1; -//CHECK_BROKEN(1); -//// Two aliases: -//typedef py::class_, BreaksTramp<-2>, BreaksTramp<-2>> Breaks2; -//CHECK_BROKEN(2); -//// Holder + 2 aliases -//typedef py::class_, std::unique_ptr>, BreaksTramp<-3>, BreaksTramp<-3>> Breaks3; -//CHECK_BROKEN(3); -//// Alias + 2 holders -//typedef py::class_, std::unique_ptr>, BreaksTramp<-4>, std::shared_ptr>> Breaks4; -//CHECK_BROKEN(4); -//// Invalid option (not a subclass or holder) -//typedef py::class_, BreaksTramp<-4>> Breaks5; -//CHECK_BROKEN(5); -//// Invalid option: multiple inheritance not supported: -//template <> struct BreaksBase<-8> : BreaksBase<-6>, BreaksBase<-7> {}; -//typedef py::class_, BreaksBase<-6>, BreaksBase<-7>> Breaks8; -//CHECK_BROKEN(8); diff --git a/spaces/CVPR/LIVE/thrust/thrust/system/cuda/detail/async/sort.h b/spaces/CVPR/LIVE/thrust/thrust/system/cuda/detail/async/sort.h deleted file mode 100644 index 3e357fde691ad27f70058120653ea1bdc0b39e91..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/thrust/thrust/system/cuda/detail/async/sort.h +++ /dev/null @@ -1,522 +0,0 @@ -/****************************************************************************** - * Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the NVIDIA CORPORATION nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ******************************************************************************/ - -// TODO: Move into system::cuda - -#pragma once - -#include -#include - -#if THRUST_CPP_DIALECT >= 2014 - -#if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -namespace thrust -{ - -namespace system { namespace cuda { namespace detail -{ - -// Non-ContiguousIterator input and output iterators -template < - typename DerivedPolicy -, typename ForwardIt, typename Size, typename StrictWeakOrdering -> -auto async_stable_sort_n( - execution_policy& policy, - ForwardIt first, - Size n, - StrictWeakOrdering comp -) -> - typename std::enable_if< - negation>::value - , unique_eager_event - >::type -{ - using T = typename iterator_traits::value_type; - - auto const device_alloc = get_async_device_allocator(policy); - - // Create device-side buffer. - - // FIXME: Combine this temporary allocation with the main one for CUB. - auto device_buffer = uninitialized_allocate_unique_n(device_alloc, n); - - auto const device_buffer_ptr = device_buffer.get(); - - // Synthesize a suitable new execution policy, because we don't want to - // try and extract twice from the one we were passed. - typename remove_cvref_t::tag_type tag_policy{}; - - // Copy from the input into the buffer. - - auto new_policy0 = thrust::detail::derived_cast(policy).rebind_after( - std::move(device_buffer) - ); - - THRUST_STATIC_ASSERT(( - std::tuple_size::value + 1 - <= - std::tuple_size::value - )); - - auto f0 = async_copy_n( - new_policy0 - , tag_policy - , first - , n - , device_buffer_ptr - ); - - // Sort the buffer. - - auto new_policy1 = thrust::detail::derived_cast(policy).rebind_after( - std::move(f0) - ); - - THRUST_STATIC_ASSERT(( - std::tuple_size::value + 1 - <= - std::tuple_size::value - )); - - auto f1 = async_sort_n( - new_policy1 - , tag_policy - , device_buffer_ptr - , n - , comp - ); - - // Copy from the buffer into the input. - // FIXME: Combine this with the potential memcpy at the end of the main sort - // routine. - - auto new_policy2 = thrust::detail::derived_cast(policy).rebind_after( - std::move(f1) - ); - - THRUST_STATIC_ASSERT(( - std::tuple_size::value + 1 - <= - std::tuple_size::value - )); - - return async_copy_n( - new_policy2 - , tag_policy - , device_buffer_ptr - , n - , first - ); -} - -// ContiguousIterator iterators -// Non-Scalar value type or user-defined StrictWeakOrdering -template < - typename DerivedPolicy -, typename ForwardIt, typename Size, typename StrictWeakOrdering -> -auto async_stable_sort_n( - execution_policy& policy, - ForwardIt first, - Size n, - StrictWeakOrdering comp -) -> - typename std::enable_if< - conjunction< - is_contiguous_iterator - , disjunction< - negation< - std::is_scalar< - typename iterator_traits::value_type - > - > - , negation< - is_operator_less_or_greater_function_object - > - > - >::value - , unique_eager_event - >::type -{ - auto const device_alloc = get_async_device_allocator(policy); - - unique_eager_event e; - - // Determine temporary device storage requirements. - - size_t tmp_size = 0; - thrust::cuda_cub::throw_on_error( - thrust::cuda_cub::__merge_sort::doit_step< - /* Sort items? */ std::false_type, /* Stable? */ std::true_type - >( - nullptr - , tmp_size - , first - , static_cast(nullptr) // Items. - , n - , comp - , nullptr // Null stream, just for sizing. - , THRUST_DEBUG_SYNC_FLAG - ) - , "after merge sort sizing" - ); - - // Allocate temporary storage. - - auto content = uninitialized_allocate_unique_n( - device_alloc, tmp_size - ); - - // The array was dynamically allocated, so we assume that it's suitably - // aligned for any type of data. `malloc`/`cudaMalloc`/`new`/`std::allocator` - // make this guarantee. - auto const content_ptr = content.get(); - - void* const tmp_ptr = static_cast( - raw_pointer_cast(content_ptr) - ); - - // Set up stream with dependencies. - - cudaStream_t const user_raw_stream = thrust::cuda_cub::stream(policy); - - if (thrust::cuda_cub::default_stream() != user_raw_stream) - { - e = make_dependent_event( - std::tuple_cat( - std::make_tuple( - std::move(content) - , unique_stream(nonowning, user_raw_stream) - ) - , extract_dependencies( - std::move(thrust::detail::derived_cast(policy)) - ) - ) - ); - } - else - { - e = make_dependent_event( - std::tuple_cat( - std::make_tuple( - std::move(content) - ) - , extract_dependencies( - std::move(thrust::detail::derived_cast(policy)) - ) - ) - ); - } - - // Run merge sort. - - thrust::cuda_cub::throw_on_error( - thrust::cuda_cub::__merge_sort::doit_step< - /* Sort items? */ std::false_type, /* Stable? */ std::true_type - >( - tmp_ptr - , tmp_size - , first - , static_cast(nullptr) // Items. - , n - , comp - , e.stream().native_handle() - , THRUST_DEBUG_SYNC_FLAG - ) - , "after merge sort sizing" - ); - - return e; -} - -template -typename std::enable_if< - is_operator_less_function_object::value -, cudaError_t ->::type -invoke_radix_sort( - cudaStream_t stream -, void* tmp_ptr -, std::size_t& tmp_size -, cub::DoubleBuffer& keys -, Size& n -, StrictWeakOrdering -) -{ - return cub::DeviceRadixSort::SortKeys( - tmp_ptr - , tmp_size - , keys - , n - , 0 - , sizeof(T) * 8 - , stream - , THRUST_DEBUG_SYNC_FLAG - ); -} - -template -typename std::enable_if< - is_operator_greater_function_object::value -, cudaError_t ->::type -invoke_radix_sort( - cudaStream_t stream -, void* tmp_ptr -, std::size_t& tmp_size -, cub::DoubleBuffer& keys -, Size& n -, StrictWeakOrdering -) -{ - return cub::DeviceRadixSort::SortKeysDescending( - tmp_ptr - , tmp_size - , keys - , n - , 0 - , sizeof(T) * 8 - , stream - , THRUST_DEBUG_SYNC_FLAG - ); -} - -// ContiguousIterator iterators -// Scalar value type -// operator< or operator> -template < - typename DerivedPolicy -, typename ForwardIt, typename Size, typename StrictWeakOrdering -> -auto async_stable_sort_n( - execution_policy& policy -, ForwardIt first -, Size n -, StrictWeakOrdering comp -) -> - typename std::enable_if< - conjunction< - is_contiguous_iterator - , std::is_scalar< - typename iterator_traits::value_type - > - , is_operator_less_or_greater_function_object - >::value - , unique_eager_event - >::type -{ - using T = typename iterator_traits::value_type; - - auto const device_alloc = get_async_device_allocator(policy); - - unique_eager_event e; - - cub::DoubleBuffer keys( - raw_pointer_cast(&*first), nullptr - ); - - // Determine temporary device storage requirements. - - size_t tmp_size = 0; - thrust::cuda_cub::throw_on_error( - invoke_radix_sort( - nullptr // Null stream, just for sizing. - , nullptr - , tmp_size - , keys - , n - , comp - ) - , "after radix sort sizing" - ); - - // Allocate temporary storage. - - size_t keys_temp_storage = thrust::detail::aligned_storage_size( - sizeof(T) * n, 128 - ); - - auto content = uninitialized_allocate_unique_n( - device_alloc, keys_temp_storage + tmp_size - ); - - // The array was dynamically allocated, so we assume that it's suitably - // aligned for any type of data. `malloc`/`cudaMalloc`/`new`/`std::allocator` - // make this guarantee. - auto const content_ptr = content.get(); - - keys.d_buffers[1] = thrust::detail::aligned_reinterpret_cast( - raw_pointer_cast(content_ptr) - ); - - void* const tmp_ptr = static_cast( - raw_pointer_cast(content_ptr + keys_temp_storage) - ); - - // Set up stream with dependencies. - - cudaStream_t const user_raw_stream = thrust::cuda_cub::stream(policy); - - if (thrust::cuda_cub::default_stream() != user_raw_stream) - { - e = make_dependent_event( - std::tuple_cat( - std::make_tuple( - std::move(content) - , unique_stream(nonowning, user_raw_stream) - ) - , extract_dependencies( - std::move(thrust::detail::derived_cast(policy)) - ) - ) - ); - } - else - { - e = make_dependent_event( - std::tuple_cat( - std::make_tuple( - std::move(content) - ) - , extract_dependencies( - std::move(thrust::detail::derived_cast(policy)) - ) - ) - ); - } - - // Run radix sort. - - thrust::cuda_cub::throw_on_error( - invoke_radix_sort( - e.stream().native_handle() - , tmp_ptr - , tmp_size - , keys - , n - , comp - ) - , "after radix sort launch" - ); - - if (0 != keys.selector) - { - auto new_policy0 = thrust::detail::derived_cast(policy).rebind_after( - std::move(e) - ); - - THRUST_STATIC_ASSERT(( - std::tuple_size::value + 1 - <= - std::tuple_size::value - )); - - // Synthesize a suitable new execution policy, because we don't want to - // try and extract twice from the one we were passed. - typename remove_cvref_t::tag_type tag_policy{}; - - using return_future = decltype(e); - return return_future(async_copy_n( - new_policy0 - , tag_policy - , keys.d_buffers[1] - , n - , keys.d_buffers[0] - )); - } - else - return e; -} - -}}} // namespace system::cuda::detail - -namespace cuda_cub -{ - -// ADL entry point. -template < - typename DerivedPolicy -, typename ForwardIt, typename Sentinel, typename StrictWeakOrdering -> -auto async_stable_sort( - execution_policy& policy, - ForwardIt first, - Sentinel last, - StrictWeakOrdering comp -) -// A GCC 5 bug requires an explicit trailing return type here, so stick with -// THRUST_DECLTYPE_RETURNS for now. -THRUST_DECLTYPE_RETURNS( - thrust::system::cuda::detail::async_stable_sort_n( - policy, first, distance(first, last), comp - ) -) - -} // cuda_cub - -} // end namespace thrust - -#endif // THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC - -#endif - diff --git a/spaces/DAMO-NLP-SG/Video-LLaMA/video_llama/conversation/conversation_video.py b/spaces/DAMO-NLP-SG/Video-LLaMA/video_llama/conversation/conversation_video.py deleted file mode 100644 index cd96a7a275f691519cd86200d7ed178d7cd2b75f..0000000000000000000000000000000000000000 --- a/spaces/DAMO-NLP-SG/Video-LLaMA/video_llama/conversation/conversation_video.py +++ /dev/null @@ -1,248 +0,0 @@ -""" -Conversation prompt template of Video-LLaMA. -Adapted from: https://github.com/Vision-CAIR/MiniGPT-4/blob/main/minigpt4/conversation/conversation.py -""" -import argparse -import time -from PIL import Image - -import torch -from transformers import AutoTokenizer, AutoModelForCausalLM, LlamaTokenizer -from transformers import StoppingCriteria, StoppingCriteriaList - -import dataclasses -from enum import auto, Enum -from typing import List, Tuple, Any -import os -from video_llama.common.registry import registry -from video_llama.processors.video_processor import ToTHWC,ToUint8,load_video -from video_llama.processors import Blip2ImageEvalProcessor -class SeparatorStyle(Enum): - """Different separator style.""" - SINGLE = auto() - TWO = auto() - - -@dataclasses.dataclass -class Conversation: - """A class that keeps all conversation history.""" - system: str - roles: List[str] - messages: List[List[str]] - offset: int - # system_img: List[Image.Image] = [] - sep_style: SeparatorStyle = SeparatorStyle.SINGLE - sep: str = "###" - sep2: str = None - - skip_next: bool = False - conv_id: Any = None - - def get_prompt(self): - if self.sep_style == SeparatorStyle.SINGLE: - ret = self.system + self.sep - for role, message in self.messages: - if message: - ret += role + ": " + message + self.sep - else: - ret += role + ":" - return ret - elif self.sep_style == SeparatorStyle.TWO: - seps = [self.sep, self.sep2] - ret = self.system + seps[0] - for i, (role, message) in enumerate(self.messages): - if message: - ret += role + ": " + message + seps[i % 2] - else: - ret += role + ":" - return ret - else: - raise ValueError(f"Invalid style: {self.sep_style}") - - def append_message(self, role, message): - self.messages.append([role, message]) - - def to_gradio_chatbot(self): - ret = [] - for i, (role, msg) in enumerate(self.messages[self.offset:]): - if i % 2 == 0: - ret.append([msg, None]) - else: - ret[-1][-1] = msg - return ret - - def copy(self): - return Conversation( - system=self.system, - # system_img=self.system_img, - roles=self.roles, - messages=[[x, y] for x, y in self.messages], - offset=self.offset, - sep_style=self.sep_style, - sep=self.sep, - sep2=self.sep2, - conv_id=self.conv_id) - - def dict(self): - return { - "system": self.system, - # "system_img": self.system_img, - "roles": self.roles, - "messages": self.messages, - "offset": self.offset, - "sep": self.sep, - "sep2": self.sep2, - "conv_id": self.conv_id, - } - - -class StoppingCriteriaSub(StoppingCriteria): - - def __init__(self, stops=[], encounters=1): - super().__init__() - self.stops = stops - - def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor): - for stop in self.stops: - if torch.all((stop == input_ids[0][-len(stop):])).item(): - return True - - return False - - -CONV_VISION = Conversation( - system="Give the following image: ImageContent. " - "You will be able to see the image once I provide it to you. Please answer my questions.", - roles=("Human", "Assistant"), - messages=[], - offset=0, - sep_style=SeparatorStyle.SINGLE, - sep="###", -) - -default_conversation = Conversation( - system="", - roles=("Human", "Assistant"), - messages=[], - offset=0, - sep_style=SeparatorStyle.SINGLE, - sep="###", -) - -class Chat: - def __init__(self, model, vis_processor, device='cuda:0'): - self.device = device - self.model = model - self.vis_processor = vis_processor - self.image_vis_processor = Blip2ImageEvalProcessor() - stop_words_ids = [torch.tensor([835]).to(self.device), - torch.tensor([2277, 29937]).to(self.device)] # '###' can be encoded in two different ways. - self.stopping_criteria = StoppingCriteriaList([StoppingCriteriaSub(stops=stop_words_ids)]) - - def ask(self, text, conv): - if len(conv.messages) > 0 and conv.messages[-1][0] == conv.roles[0] \ - and ('' in conv.messages[-1][1] or '' in conv.messages[-1][1]): # last message is image. - conv.messages[-1][1] = ' '.join([conv.messages[-1][1], text]) - else: - conv.append_message(conv.roles[0], text) - - def answer(self, conv, img_list, max_new_tokens=300, num_beams=1, min_length=1, top_p=0.9, - repetition_penalty=1.0, length_penalty=1, temperature=1.0, max_length=2000): - conv.append_message(conv.roles[1], None) - embs = self.get_context_emb(conv, img_list) - - current_max_len = embs.shape[1] + max_new_tokens - if current_max_len - max_length > 0: - print('Warning: The number of tokens in current conversation exceeds the max length. ' - 'The model will not see the contexts outside the range.') - begin_idx = max(0, current_max_len - max_length) - - embs = embs[:, begin_idx:] - - outputs = self.model.llama_model.generate( - inputs_embeds=embs, - max_new_tokens=max_new_tokens, - stopping_criteria=self.stopping_criteria, - num_beams=num_beams, - do_sample=True, - min_length=min_length, - top_p=top_p, - repetition_penalty=repetition_penalty, - length_penalty=length_penalty, - temperature=temperature, - ) - output_token = outputs[0] - if output_token[0] == 0: # the model might output a unknow token at the beginning. remove it - output_token = output_token[1:] - if output_token[0] == 1: # some users find that there is a start token at the beginning. remove it - output_token = output_token[1:] - output_text = self.model.llama_tokenizer.decode(output_token, add_special_tokens=False) - output_text = output_text.split('###')[0] # remove the stop sign '###' - output_text = output_text.split('Assistant:')[-1].strip() - conv.messages[-1][1] = output_text - return output_text, output_token.cpu().numpy() - - def upload_video(self, video, conv, img_list): - - msg = "" - if isinstance(video, str): # is a video path - ext = os.path.splitext(video)[-1].lower() - print(video) - # image = self.vis_processor(image).unsqueeze(0).to(self.device) - video, msg = load_video( - video_path=video, - n_frms=8, - height=224, - width=224, - sampling ="uniform", return_msg = True - ) - video = self.vis_processor.transform(video) - video = video.unsqueeze(0).to(self.device) - # print(image) - else: - raise NotImplementedError - - image_emb, _ = self.model.encode_img(video) - img_list.append(image_emb) - conv.append_message(conv.roles[0], " "+ msg) - return "Received." - - def upload_img(self, image, conv, img_list): - - msg = "" - if isinstance(image, str): # is a image path - raw_image = Image.open(image).convert('RGB') # 增加一个时间维度 - image = self.image_vis_processor(raw_image).unsqueeze(0).unsqueeze(2).to(self.device) - elif isinstance(image, Image.Image): - raw_image = image - image = self.image_vis_processor(raw_image).unsqueeze(0).unsqueeze(2).to(self.device) - elif isinstance(image, torch.Tensor): - if len(image.shape) == 3: - image = image.unsqueeze(0) - image = image.to(self.device) - else: - raise NotImplementedError - - image_emb, _ = self.model.encode_img(image) - img_list.append(image_emb) - # Todo msg="" - conv.append_message(conv.roles[0], " "+ msg) - - return "Received." - - def get_context_emb(self, conv, img_list): - prompt = conv.get_prompt() - prompt_segs = prompt.split('') - assert len(prompt_segs) == len(img_list) + 1, "Unmatched numbers of image placeholders and images." - seg_tokens = [ - self.model.llama_tokenizer( - seg, return_tensors="pt", add_special_tokens=i == 0).to(self.device).input_ids - # only add bos to the first seg - for i, seg in enumerate(prompt_segs) - ] - seg_embs = [self.model.llama_model.model.embed_tokens(seg_t) for seg_t in seg_tokens] - mixed_embs = [emb for pair in zip(seg_embs[:-1], img_list) for emb in pair] + [seg_embs[-1]] - mixed_embs = torch.cat(mixed_embs, dim=1) - return mixed_embs - - diff --git a/spaces/DHEIVER/endoscopy_multiClassification/app.py b/spaces/DHEIVER/endoscopy_multiClassification/app.py deleted file mode 100644 index fd8c5972d961a83d3e3c146c46144c5f664b7c8f..0000000000000000000000000000000000000000 --- a/spaces/DHEIVER/endoscopy_multiClassification/app.py +++ /dev/null @@ -1,53 +0,0 @@ -import gradio as gr -import tensorflow as tf -import numpy as np -from PIL import Image -import json - -# Carregue o modelo previamente treinado -model = tf.keras.models.load_model("model_acc_0.7240.h5") - -# Carregue o arquivo JSON com as categorias indexadas e descrições de diagnóstico -with open("categories.json", "r") as json_file: - categories_data = json.load(json_file) - -categories = [entry["category"] for entry in categories_data] -diagnoses = [entry["diagnosis"] for entry in categories_data] - -# Descrição do modelo e seu objetivo em português -model_description = ( - "Este modelo foi treinado para classificar imagens médicas do trato gastrointestinal humano em várias categorias " - "com diagnósticos associados. Ele pode ajudar a identificar condições médicas a partir de imagens." -) - -# Crie uma função para realizar a classificação -def classify_image(image): - try: - # Redimensione a imagem para 100x100 pixels - image = Image.fromarray(image.astype('uint8')) - image = image.resize((100, 100)) # Redimensione para 100x100 - image = np.array(image) - - # Realize a classificação - prediction = model.predict(image[None, ...]) - - # Decodifique a classe prevista - class_idx = np.argmax(prediction) - class_label = categories[class_idx] - diagnosis = diagnoses[class_idx] - - return f"Classe prevista: {class_label}\nDiagnóstico: {diagnosis}" - except Exception as e: - return str(e) - -# Crie uma interface Gradio com descrição completa e título informativo em português -iface = gr.Interface( - fn=classify_image, - inputs=gr.inputs.Image(), # Entrada de imagem - outputs="text", # Saída de texto com a classe prevista e diagnóstico - title="Sistema de Classificação de Anomalias Gastrointestinais por Imagem", - description=model_description -) - -# Inicie a interface Gradio -iface.launch() diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/PIL/MpegImagePlugin.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/PIL/MpegImagePlugin.py deleted file mode 100644 index d96d3a11c4966e94a53c67f13c3bf8f7987c0c83..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/PIL/MpegImagePlugin.py +++ /dev/null @@ -1,82 +0,0 @@ -# -# The Python Imaging Library. -# $Id$ -# -# MPEG file handling -# -# History: -# 95-09-09 fl Created -# -# Copyright (c) Secret Labs AB 1997. -# Copyright (c) Fredrik Lundh 1995. -# -# See the README file for information on usage and redistribution. -# - - -from . import Image, ImageFile -from ._binary import i8 - -# -# Bitstream parser - - -class BitStream: - def __init__(self, fp): - self.fp = fp - self.bits = 0 - self.bitbuffer = 0 - - def next(self): - return i8(self.fp.read(1)) - - def peek(self, bits): - while self.bits < bits: - c = self.next() - if c < 0: - self.bits = 0 - continue - self.bitbuffer = (self.bitbuffer << 8) + c - self.bits += 8 - return self.bitbuffer >> (self.bits - bits) & (1 << bits) - 1 - - def skip(self, bits): - while self.bits < bits: - self.bitbuffer = (self.bitbuffer << 8) + i8(self.fp.read(1)) - self.bits += 8 - self.bits = self.bits - bits - - def read(self, bits): - v = self.peek(bits) - self.bits = self.bits - bits - return v - - -## -# Image plugin for MPEG streams. This plugin can identify a stream, -# but it cannot read it. - - -class MpegImageFile(ImageFile.ImageFile): - format = "MPEG" - format_description = "MPEG" - - def _open(self): - s = BitStream(self.fp) - - if s.read(32) != 0x1B3: - msg = "not an MPEG file" - raise SyntaxError(msg) - - self.mode = "RGB" - self._size = s.read(12), s.read(12) - - -# -------------------------------------------------------------------- -# Registry stuff - -Image.register_open(MpegImageFile.format, MpegImageFile) - -Image.register_extensions(MpegImageFile.format, [".mpg", ".mpeg"]) - -Image.register_mime(MpegImageFile.format, "video/mpeg") diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/anyio/__init__.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/anyio/__init__.py deleted file mode 100644 index 29fb3561e4f2dc9d3a764e756439c0dea2c9897a..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/anyio/__init__.py +++ /dev/null @@ -1,169 +0,0 @@ -from __future__ import annotations - -__all__ = ( - "maybe_async", - "maybe_async_cm", - "run", - "sleep", - "sleep_forever", - "sleep_until", - "current_time", - "get_all_backends", - "get_cancelled_exc_class", - "BrokenResourceError", - "BrokenWorkerProcess", - "BusyResourceError", - "ClosedResourceError", - "DelimiterNotFound", - "EndOfStream", - "ExceptionGroup", - "IncompleteRead", - "TypedAttributeLookupError", - "WouldBlock", - "AsyncFile", - "Path", - "open_file", - "wrap_file", - "aclose_forcefully", - "open_signal_receiver", - "connect_tcp", - "connect_unix", - "create_tcp_listener", - "create_unix_listener", - "create_udp_socket", - "create_connected_udp_socket", - "getaddrinfo", - "getnameinfo", - "wait_socket_readable", - "wait_socket_writable", - "create_memory_object_stream", - "run_process", - "open_process", - "create_lock", - "CapacityLimiter", - "CapacityLimiterStatistics", - "Condition", - "ConditionStatistics", - "Event", - "EventStatistics", - "Lock", - "LockStatistics", - "Semaphore", - "SemaphoreStatistics", - "create_condition", - "create_event", - "create_semaphore", - "create_capacity_limiter", - "open_cancel_scope", - "fail_after", - "move_on_after", - "current_effective_deadline", - "TASK_STATUS_IGNORED", - "CancelScope", - "create_task_group", - "TaskInfo", - "get_current_task", - "get_running_tasks", - "wait_all_tasks_blocked", - "run_sync_in_worker_thread", - "run_async_from_thread", - "run_sync_from_thread", - "current_default_worker_thread_limiter", - "create_blocking_portal", - "start_blocking_portal", - "typed_attribute", - "TypedAttributeSet", - "TypedAttributeProvider", -) - -from typing import Any - -from ._core._compat import maybe_async, maybe_async_cm -from ._core._eventloop import ( - current_time, - get_all_backends, - get_cancelled_exc_class, - run, - sleep, - sleep_forever, - sleep_until, -) -from ._core._exceptions import ( - BrokenResourceError, - BrokenWorkerProcess, - BusyResourceError, - ClosedResourceError, - DelimiterNotFound, - EndOfStream, - ExceptionGroup, - IncompleteRead, - TypedAttributeLookupError, - WouldBlock, -) -from ._core._fileio import AsyncFile, Path, open_file, wrap_file -from ._core._resources import aclose_forcefully -from ._core._signals import open_signal_receiver -from ._core._sockets import ( - connect_tcp, - connect_unix, - create_connected_udp_socket, - create_tcp_listener, - create_udp_socket, - create_unix_listener, - getaddrinfo, - getnameinfo, - wait_socket_readable, - wait_socket_writable, -) -from ._core._streams import create_memory_object_stream -from ._core._subprocesses import open_process, run_process -from ._core._synchronization import ( - CapacityLimiter, - CapacityLimiterStatistics, - Condition, - ConditionStatistics, - Event, - EventStatistics, - Lock, - LockStatistics, - Semaphore, - SemaphoreStatistics, - create_capacity_limiter, - create_condition, - create_event, - create_lock, - create_semaphore, -) -from ._core._tasks import ( - TASK_STATUS_IGNORED, - CancelScope, - create_task_group, - current_effective_deadline, - fail_after, - move_on_after, - open_cancel_scope, -) -from ._core._testing import ( - TaskInfo, - get_current_task, - get_running_tasks, - wait_all_tasks_blocked, -) -from ._core._typedattr import TypedAttributeProvider, TypedAttributeSet, typed_attribute - -# Re-exported here, for backwards compatibility -# isort: off -from .to_thread import current_default_worker_thread_limiter, run_sync_in_worker_thread -from .from_thread import ( - create_blocking_portal, - run_async_from_thread, - run_sync_from_thread, - start_blocking_portal, -) - -# Re-export imports so they look like they live directly in this package -key: str -value: Any -for key, value in list(locals().items()): - if getattr(value, "__module__", "").startswith("anyio."): - value.__module__ = __name__ diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/feaLib/ast.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/feaLib/ast.py deleted file mode 100644 index 17c6cc3fbe494a076d2b59f4664ab9fe56ecd20f..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/feaLib/ast.py +++ /dev/null @@ -1,2134 +0,0 @@ -from fontTools.feaLib.error import FeatureLibError -from fontTools.feaLib.location import FeatureLibLocation -from fontTools.misc.encodingTools import getEncoding -from fontTools.misc.textTools import byteord, tobytes -from collections import OrderedDict -import itertools - -SHIFT = " " * 4 - -__all__ = [ - "Element", - "FeatureFile", - "Comment", - "GlyphName", - "GlyphClass", - "GlyphClassName", - "MarkClassName", - "AnonymousBlock", - "Block", - "FeatureBlock", - "NestedBlock", - "LookupBlock", - "GlyphClassDefinition", - "GlyphClassDefStatement", - "MarkClass", - "MarkClassDefinition", - "AlternateSubstStatement", - "Anchor", - "AnchorDefinition", - "AttachStatement", - "AxisValueLocationStatement", - "BaseAxis", - "CVParametersNameStatement", - "ChainContextPosStatement", - "ChainContextSubstStatement", - "CharacterStatement", - "ConditionsetStatement", - "CursivePosStatement", - "ElidedFallbackName", - "ElidedFallbackNameID", - "Expression", - "FeatureNameStatement", - "FeatureReferenceStatement", - "FontRevisionStatement", - "HheaField", - "IgnorePosStatement", - "IgnoreSubstStatement", - "IncludeStatement", - "LanguageStatement", - "LanguageSystemStatement", - "LigatureCaretByIndexStatement", - "LigatureCaretByPosStatement", - "LigatureSubstStatement", - "LookupFlagStatement", - "LookupReferenceStatement", - "MarkBasePosStatement", - "MarkLigPosStatement", - "MarkMarkPosStatement", - "MultipleSubstStatement", - "NameRecord", - "OS2Field", - "PairPosStatement", - "ReverseChainSingleSubstStatement", - "ScriptStatement", - "SinglePosStatement", - "SingleSubstStatement", - "SizeParameters", - "Statement", - "STATAxisValueStatement", - "STATDesignAxisStatement", - "STATNameStatement", - "SubtableStatement", - "TableBlock", - "ValueRecord", - "ValueRecordDefinition", - "VheaField", -] - - -def deviceToString(device): - if device is None: - return "" - else: - return "" % ", ".join("%d %d" % t for t in device) - - -fea_keywords = set( - [ - "anchor", - "anchordef", - "anon", - "anonymous", - "by", - "contour", - "cursive", - "device", - "enum", - "enumerate", - "excludedflt", - "exclude_dflt", - "feature", - "from", - "ignore", - "ignorebaseglyphs", - "ignoreligatures", - "ignoremarks", - "include", - "includedflt", - "include_dflt", - "language", - "languagesystem", - "lookup", - "lookupflag", - "mark", - "markattachmenttype", - "markclass", - "nameid", - "null", - "parameters", - "pos", - "position", - "required", - "righttoleft", - "reversesub", - "rsub", - "script", - "sub", - "substitute", - "subtable", - "table", - "usemarkfilteringset", - "useextension", - "valuerecorddef", - "base", - "gdef", - "head", - "hhea", - "name", - "vhea", - "vmtx", - ] -) - - -def asFea(g): - if hasattr(g, "asFea"): - return g.asFea() - elif isinstance(g, tuple) and len(g) == 2: - return asFea(g[0]) + " - " + asFea(g[1]) # a range - elif g.lower() in fea_keywords: - return "\\" + g - else: - return g - - -class Element(object): - """A base class representing "something" in a feature file.""" - - def __init__(self, location=None): - #: location of this element as a `FeatureLibLocation` object. - if location and not isinstance(location, FeatureLibLocation): - location = FeatureLibLocation(*location) - self.location = location - - def build(self, builder): - pass - - def asFea(self, indent=""): - """Returns this element as a string of feature code. For block-type - elements (such as :class:`FeatureBlock`), the `indent` string is - added to the start of each line in the output.""" - raise NotImplementedError - - def __str__(self): - return self.asFea() - - -class Statement(Element): - pass - - -class Expression(Element): - pass - - -class Comment(Element): - """A comment in a feature file.""" - - def __init__(self, text, location=None): - super(Comment, self).__init__(location) - #: Text of the comment - self.text = text - - def asFea(self, indent=""): - return self.text - - -class NullGlyph(Expression): - """The NULL glyph, used in glyph deletion substitutions.""" - - def __init__(self, location=None): - Expression.__init__(self, location) - #: The name itself as a string - - def glyphSet(self): - """The glyphs in this class as a tuple of :class:`GlyphName` objects.""" - return () - - def asFea(self, indent=""): - return "NULL" - - -class GlyphName(Expression): - """A single glyph name, such as ``cedilla``.""" - - def __init__(self, glyph, location=None): - Expression.__init__(self, location) - #: The name itself as a string - self.glyph = glyph - - def glyphSet(self): - """The glyphs in this class as a tuple of :class:`GlyphName` objects.""" - return (self.glyph,) - - def asFea(self, indent=""): - return asFea(self.glyph) - - -class GlyphClass(Expression): - """A glyph class, such as ``[acute cedilla grave]``.""" - - def __init__(self, glyphs=None, location=None): - Expression.__init__(self, location) - #: The list of glyphs in this class, as :class:`GlyphName` objects. - self.glyphs = glyphs if glyphs is not None else [] - self.original = [] - self.curr = 0 - - def glyphSet(self): - """The glyphs in this class as a tuple of :class:`GlyphName` objects.""" - return tuple(self.glyphs) - - def asFea(self, indent=""): - if len(self.original): - if self.curr < len(self.glyphs): - self.original.extend(self.glyphs[self.curr :]) - self.curr = len(self.glyphs) - return "[" + " ".join(map(asFea, self.original)) + "]" - else: - return "[" + " ".join(map(asFea, self.glyphs)) + "]" - - def extend(self, glyphs): - """Add a list of :class:`GlyphName` objects to the class.""" - self.glyphs.extend(glyphs) - - def append(self, glyph): - """Add a single :class:`GlyphName` object to the class.""" - self.glyphs.append(glyph) - - def add_range(self, start, end, glyphs): - """Add a range (e.g. ``A-Z``) to the class. ``start`` and ``end`` - are either :class:`GlyphName` objects or strings representing the - start and end glyphs in the class, and ``glyphs`` is the full list of - :class:`GlyphName` objects in the range.""" - if self.curr < len(self.glyphs): - self.original.extend(self.glyphs[self.curr :]) - self.original.append((start, end)) - self.glyphs.extend(glyphs) - self.curr = len(self.glyphs) - - def add_cid_range(self, start, end, glyphs): - """Add a range to the class by glyph ID. ``start`` and ``end`` are the - initial and final IDs, and ``glyphs`` is the full list of - :class:`GlyphName` objects in the range.""" - if self.curr < len(self.glyphs): - self.original.extend(self.glyphs[self.curr :]) - self.original.append(("\\{}".format(start), "\\{}".format(end))) - self.glyphs.extend(glyphs) - self.curr = len(self.glyphs) - - def add_class(self, gc): - """Add glyphs from the given :class:`GlyphClassName` object to the - class.""" - if self.curr < len(self.glyphs): - self.original.extend(self.glyphs[self.curr :]) - self.original.append(gc) - self.glyphs.extend(gc.glyphSet()) - self.curr = len(self.glyphs) - - -class GlyphClassName(Expression): - """A glyph class name, such as ``@FRENCH_MARKS``. This must be instantiated - with a :class:`GlyphClassDefinition` object.""" - - def __init__(self, glyphclass, location=None): - Expression.__init__(self, location) - assert isinstance(glyphclass, GlyphClassDefinition) - self.glyphclass = glyphclass - - def glyphSet(self): - """The glyphs in this class as a tuple of :class:`GlyphName` objects.""" - return tuple(self.glyphclass.glyphSet()) - - def asFea(self, indent=""): - return "@" + self.glyphclass.name - - -class MarkClassName(Expression): - """A mark class name, such as ``@FRENCH_MARKS`` defined with ``markClass``. - This must be instantiated with a :class:`MarkClass` object.""" - - def __init__(self, markClass, location=None): - Expression.__init__(self, location) - assert isinstance(markClass, MarkClass) - self.markClass = markClass - - def glyphSet(self): - """The glyphs in this class as a tuple of :class:`GlyphName` objects.""" - return self.markClass.glyphSet() - - def asFea(self, indent=""): - return "@" + self.markClass.name - - -class AnonymousBlock(Statement): - """An anonymous data block.""" - - def __init__(self, tag, content, location=None): - Statement.__init__(self, location) - self.tag = tag #: string containing the block's "tag" - self.content = content #: block data as string - - def asFea(self, indent=""): - res = "anon {} {{\n".format(self.tag) - res += self.content - res += "}} {};\n\n".format(self.tag) - return res - - -class Block(Statement): - """A block of statements: feature, lookup, etc.""" - - def __init__(self, location=None): - Statement.__init__(self, location) - self.statements = [] #: Statements contained in the block - - def build(self, builder): - """When handed a 'builder' object of comparable interface to - :class:`fontTools.feaLib.builder`, walks the statements in this - block, calling the builder callbacks.""" - for s in self.statements: - s.build(builder) - - def asFea(self, indent=""): - indent += SHIFT - return ( - indent - + ("\n" + indent).join([s.asFea(indent=indent) for s in self.statements]) - + "\n" - ) - - -class FeatureFile(Block): - """The top-level element of the syntax tree, containing the whole feature - file in its ``statements`` attribute.""" - - def __init__(self): - Block.__init__(self, location=None) - self.markClasses = {} # name --> ast.MarkClass - - def asFea(self, indent=""): - return "\n".join(s.asFea(indent=indent) for s in self.statements) - - -class FeatureBlock(Block): - """A named feature block.""" - - def __init__(self, name, use_extension=False, location=None): - Block.__init__(self, location) - self.name, self.use_extension = name, use_extension - - def build(self, builder): - """Call the ``start_feature`` callback on the builder object, visit - all the statements in this feature, and then call ``end_feature``.""" - # TODO(sascha): Handle use_extension. - builder.start_feature(self.location, self.name) - # language exclude_dflt statements modify builder.features_ - # limit them to this block with temporary builder.features_ - features = builder.features_ - builder.features_ = {} - Block.build(self, builder) - for key, value in builder.features_.items(): - features.setdefault(key, []).extend(value) - builder.features_ = features - builder.end_feature() - - def asFea(self, indent=""): - res = indent + "feature %s " % self.name.strip() - if self.use_extension: - res += "useExtension " - res += "{\n" - res += Block.asFea(self, indent=indent) - res += indent + "} %s;\n" % self.name.strip() - return res - - -class NestedBlock(Block): - """A block inside another block, for example when found inside a - ``cvParameters`` block.""" - - def __init__(self, tag, block_name, location=None): - Block.__init__(self, location) - self.tag = tag - self.block_name = block_name - - def build(self, builder): - Block.build(self, builder) - if self.block_name == "ParamUILabelNameID": - builder.add_to_cv_num_named_params(self.tag) - - def asFea(self, indent=""): - res = "{}{} {{\n".format(indent, self.block_name) - res += Block.asFea(self, indent=indent) - res += "{}}};\n".format(indent) - return res - - -class LookupBlock(Block): - """A named lookup, containing ``statements``.""" - - def __init__(self, name, use_extension=False, location=None): - Block.__init__(self, location) - self.name, self.use_extension = name, use_extension - - def build(self, builder): - # TODO(sascha): Handle use_extension. - builder.start_lookup_block(self.location, self.name) - Block.build(self, builder) - builder.end_lookup_block() - - def asFea(self, indent=""): - res = "lookup {} ".format(self.name) - if self.use_extension: - res += "useExtension " - res += "{\n" - res += Block.asFea(self, indent=indent) - res += "{}}} {};\n".format(indent, self.name) - return res - - -class TableBlock(Block): - """A ``table ... { }`` block.""" - - def __init__(self, name, location=None): - Block.__init__(self, location) - self.name = name - - def asFea(self, indent=""): - res = "table {} {{\n".format(self.name.strip()) - res += super(TableBlock, self).asFea(indent=indent) - res += "}} {};\n".format(self.name.strip()) - return res - - -class GlyphClassDefinition(Statement): - """Example: ``@UPPERCASE = [A-Z];``.""" - - def __init__(self, name, glyphs, location=None): - Statement.__init__(self, location) - self.name = name #: class name as a string, without initial ``@`` - self.glyphs = glyphs #: a :class:`GlyphClass` object - - def glyphSet(self): - """The glyphs in this class as a tuple of :class:`GlyphName` objects.""" - return tuple(self.glyphs.glyphSet()) - - def asFea(self, indent=""): - return "@" + self.name + " = " + self.glyphs.asFea() + ";" - - -class GlyphClassDefStatement(Statement): - """Example: ``GlyphClassDef @UPPERCASE, [B], [C], [D];``. The parameters - must be either :class:`GlyphClass` or :class:`GlyphClassName` objects, or - ``None``.""" - - def __init__( - self, baseGlyphs, markGlyphs, ligatureGlyphs, componentGlyphs, location=None - ): - Statement.__init__(self, location) - self.baseGlyphs, self.markGlyphs = (baseGlyphs, markGlyphs) - self.ligatureGlyphs = ligatureGlyphs - self.componentGlyphs = componentGlyphs - - def build(self, builder): - """Calls the builder's ``add_glyphClassDef`` callback.""" - base = self.baseGlyphs.glyphSet() if self.baseGlyphs else tuple() - liga = self.ligatureGlyphs.glyphSet() if self.ligatureGlyphs else tuple() - mark = self.markGlyphs.glyphSet() if self.markGlyphs else tuple() - comp = self.componentGlyphs.glyphSet() if self.componentGlyphs else tuple() - builder.add_glyphClassDef(self.location, base, liga, mark, comp) - - def asFea(self, indent=""): - return "GlyphClassDef {}, {}, {}, {};".format( - self.baseGlyphs.asFea() if self.baseGlyphs else "", - self.ligatureGlyphs.asFea() if self.ligatureGlyphs else "", - self.markGlyphs.asFea() if self.markGlyphs else "", - self.componentGlyphs.asFea() if self.componentGlyphs else "", - ) - - -class MarkClass(object): - """One `or more` ``markClass`` statements for the same mark class. - - While glyph classes can be defined only once, the feature file format - allows expanding mark classes with multiple definitions, each using - different glyphs and anchors. The following are two ``MarkClassDefinitions`` - for the same ``MarkClass``:: - - markClass [acute grave] @FRENCH_ACCENTS; - markClass [cedilla] @FRENCH_ACCENTS; - - The ``MarkClass`` object is therefore just a container for a list of - :class:`MarkClassDefinition` statements. - """ - - def __init__(self, name): - self.name = name - self.definitions = [] - self.glyphs = OrderedDict() # glyph --> ast.MarkClassDefinitions - - def addDefinition(self, definition): - """Add a :class:`MarkClassDefinition` statement to this mark class.""" - assert isinstance(definition, MarkClassDefinition) - self.definitions.append(definition) - for glyph in definition.glyphSet(): - if glyph in self.glyphs: - otherLoc = self.glyphs[glyph].location - if otherLoc is None: - end = "" - else: - end = f" at {otherLoc}" - raise FeatureLibError( - "Glyph %s already defined%s" % (glyph, end), definition.location - ) - self.glyphs[glyph] = definition - - def glyphSet(self): - """The glyphs in this class as a tuple of :class:`GlyphName` objects.""" - return tuple(self.glyphs.keys()) - - def asFea(self, indent=""): - res = "\n".join(d.asFea() for d in self.definitions) - return res - - -class MarkClassDefinition(Statement): - """A single ``markClass`` statement. The ``markClass`` should be a - :class:`MarkClass` object, the ``anchor`` an :class:`Anchor` object, - and the ``glyphs`` parameter should be a `glyph-containing object`_ . - - Example: - - .. code:: python - - mc = MarkClass("FRENCH_ACCENTS") - mc.addDefinition( MarkClassDefinition(mc, Anchor(350, 800), - GlyphClass([ GlyphName("acute"), GlyphName("grave") ]) - ) ) - mc.addDefinition( MarkClassDefinition(mc, Anchor(350, -200), - GlyphClass([ GlyphName("cedilla") ]) - ) ) - - mc.asFea() - # markClass [acute grave] @FRENCH_ACCENTS; - # markClass [cedilla] @FRENCH_ACCENTS; - - """ - - def __init__(self, markClass, anchor, glyphs, location=None): - Statement.__init__(self, location) - assert isinstance(markClass, MarkClass) - assert isinstance(anchor, Anchor) and isinstance(glyphs, Expression) - self.markClass, self.anchor, self.glyphs = markClass, anchor, glyphs - - def glyphSet(self): - """The glyphs in this class as a tuple of :class:`GlyphName` objects.""" - return self.glyphs.glyphSet() - - def asFea(self, indent=""): - return "markClass {} {} @{};".format( - self.glyphs.asFea(), self.anchor.asFea(), self.markClass.name - ) - - -class AlternateSubstStatement(Statement): - """A ``sub ... from ...`` statement. - - ``prefix``, ``glyph``, ``suffix`` and ``replacement`` should be lists of - `glyph-containing objects`_. ``glyph`` should be a `one element list`.""" - - def __init__(self, prefix, glyph, suffix, replacement, location=None): - Statement.__init__(self, location) - self.prefix, self.glyph, self.suffix = (prefix, glyph, suffix) - self.replacement = replacement - - def build(self, builder): - """Calls the builder's ``add_alternate_subst`` callback.""" - glyph = self.glyph.glyphSet() - assert len(glyph) == 1, glyph - glyph = list(glyph)[0] - prefix = [p.glyphSet() for p in self.prefix] - suffix = [s.glyphSet() for s in self.suffix] - replacement = self.replacement.glyphSet() - builder.add_alternate_subst(self.location, prefix, glyph, suffix, replacement) - - def asFea(self, indent=""): - res = "sub " - if len(self.prefix) or len(self.suffix): - if len(self.prefix): - res += " ".join(map(asFea, self.prefix)) + " " - res += asFea(self.glyph) + "'" # even though we really only use 1 - if len(self.suffix): - res += " " + " ".join(map(asFea, self.suffix)) - else: - res += asFea(self.glyph) - res += " from " - res += asFea(self.replacement) - res += ";" - return res - - -class Anchor(Expression): - """An ``Anchor`` element, used inside a ``pos`` rule. - - If a ``name`` is given, this will be used in preference to the coordinates. - Other values should be integer. - """ - - def __init__( - self, - x, - y, - name=None, - contourpoint=None, - xDeviceTable=None, - yDeviceTable=None, - location=None, - ): - Expression.__init__(self, location) - self.name = name - self.x, self.y, self.contourpoint = x, y, contourpoint - self.xDeviceTable, self.yDeviceTable = xDeviceTable, yDeviceTable - - def asFea(self, indent=""): - if self.name is not None: - return "".format(self.name) - res = "" - exit = self.exitAnchor.asFea() if self.exitAnchor else "" - return "pos cursive {} {} {};".format(self.glyphclass.asFea(), entry, exit) - - -class FeatureReferenceStatement(Statement): - """Example: ``feature salt;``""" - - def __init__(self, featureName, location=None): - Statement.__init__(self, location) - self.location, self.featureName = (location, featureName) - - def build(self, builder): - """Calls the builder object's ``add_feature_reference`` callback.""" - builder.add_feature_reference(self.location, self.featureName) - - def asFea(self, indent=""): - return "feature {};".format(self.featureName) - - -class IgnorePosStatement(Statement): - """An ``ignore pos`` statement, containing `one or more` contexts to ignore. - - ``chainContexts`` should be a list of ``(prefix, glyphs, suffix)`` tuples, - with each of ``prefix``, ``glyphs`` and ``suffix`` being - `glyph-containing objects`_ .""" - - def __init__(self, chainContexts, location=None): - Statement.__init__(self, location) - self.chainContexts = chainContexts - - def build(self, builder): - """Calls the builder object's ``add_chain_context_pos`` callback on each - rule context.""" - for prefix, glyphs, suffix in self.chainContexts: - prefix = [p.glyphSet() for p in prefix] - glyphs = [g.glyphSet() for g in glyphs] - suffix = [s.glyphSet() for s in suffix] - builder.add_chain_context_pos(self.location, prefix, glyphs, suffix, []) - - def asFea(self, indent=""): - contexts = [] - for prefix, glyphs, suffix in self.chainContexts: - res = "" - if len(prefix) or len(suffix): - if len(prefix): - res += " ".join(map(asFea, prefix)) + " " - res += " ".join(g.asFea() + "'" for g in glyphs) - if len(suffix): - res += " " + " ".join(map(asFea, suffix)) - else: - res += " ".join(map(asFea, glyphs)) - contexts.append(res) - return "ignore pos " + ", ".join(contexts) + ";" - - -class IgnoreSubstStatement(Statement): - """An ``ignore sub`` statement, containing `one or more` contexts to ignore. - - ``chainContexts`` should be a list of ``(prefix, glyphs, suffix)`` tuples, - with each of ``prefix``, ``glyphs`` and ``suffix`` being - `glyph-containing objects`_ .""" - - def __init__(self, chainContexts, location=None): - Statement.__init__(self, location) - self.chainContexts = chainContexts - - def build(self, builder): - """Calls the builder object's ``add_chain_context_subst`` callback on - each rule context.""" - for prefix, glyphs, suffix in self.chainContexts: - prefix = [p.glyphSet() for p in prefix] - glyphs = [g.glyphSet() for g in glyphs] - suffix = [s.glyphSet() for s in suffix] - builder.add_chain_context_subst(self.location, prefix, glyphs, suffix, []) - - def asFea(self, indent=""): - contexts = [] - for prefix, glyphs, suffix in self.chainContexts: - res = "" - if len(prefix): - res += " ".join(map(asFea, prefix)) + " " - res += " ".join(g.asFea() + "'" for g in glyphs) - if len(suffix): - res += " " + " ".join(map(asFea, suffix)) - contexts.append(res) - return "ignore sub " + ", ".join(contexts) + ";" - - -class IncludeStatement(Statement): - """An ``include()`` statement.""" - - def __init__(self, filename, location=None): - super(IncludeStatement, self).__init__(location) - self.filename = filename #: String containing name of file to include - - def build(self): - # TODO: consider lazy-loading the including parser/lexer? - raise FeatureLibError( - "Building an include statement is not implemented yet. " - "Instead, use Parser(..., followIncludes=True) for building.", - self.location, - ) - - def asFea(self, indent=""): - return indent + "include(%s);" % self.filename - - -class LanguageStatement(Statement): - """A ``language`` statement within a feature.""" - - def __init__(self, language, include_default=True, required=False, location=None): - Statement.__init__(self, location) - assert len(language) == 4 - self.language = language #: A four-character language tag - self.include_default = include_default #: If false, "exclude_dflt" - self.required = required - - def build(self, builder): - """Call the builder object's ``set_language`` callback.""" - builder.set_language( - location=self.location, - language=self.language, - include_default=self.include_default, - required=self.required, - ) - - def asFea(self, indent=""): - res = "language {}".format(self.language.strip()) - if not self.include_default: - res += " exclude_dflt" - if self.required: - res += " required" - res += ";" - return res - - -class LanguageSystemStatement(Statement): - """A top-level ``languagesystem`` statement.""" - - def __init__(self, script, language, location=None): - Statement.__init__(self, location) - self.script, self.language = (script, language) - - def build(self, builder): - """Calls the builder object's ``add_language_system`` callback.""" - builder.add_language_system(self.location, self.script, self.language) - - def asFea(self, indent=""): - return "languagesystem {} {};".format(self.script, self.language.strip()) - - -class FontRevisionStatement(Statement): - """A ``head`` table ``FontRevision`` statement. ``revision`` should be a - number, and will be formatted to three significant decimal places.""" - - def __init__(self, revision, location=None): - Statement.__init__(self, location) - self.revision = revision - - def build(self, builder): - builder.set_font_revision(self.location, self.revision) - - def asFea(self, indent=""): - return "FontRevision {:.3f};".format(self.revision) - - -class LigatureCaretByIndexStatement(Statement): - """A ``GDEF`` table ``LigatureCaretByIndex`` statement. ``glyphs`` should be - a `glyph-containing object`_, and ``carets`` should be a list of integers.""" - - def __init__(self, glyphs, carets, location=None): - Statement.__init__(self, location) - self.glyphs, self.carets = (glyphs, carets) - - def build(self, builder): - """Calls the builder object's ``add_ligatureCaretByIndex_`` callback.""" - glyphs = self.glyphs.glyphSet() - builder.add_ligatureCaretByIndex_(self.location, glyphs, set(self.carets)) - - def asFea(self, indent=""): - return "LigatureCaretByIndex {} {};".format( - self.glyphs.asFea(), " ".join(str(x) for x in self.carets) - ) - - -class LigatureCaretByPosStatement(Statement): - """A ``GDEF`` table ``LigatureCaretByPos`` statement. ``glyphs`` should be - a `glyph-containing object`_, and ``carets`` should be a list of integers.""" - - def __init__(self, glyphs, carets, location=None): - Statement.__init__(self, location) - self.glyphs, self.carets = (glyphs, carets) - - def build(self, builder): - """Calls the builder object's ``add_ligatureCaretByPos_`` callback.""" - glyphs = self.glyphs.glyphSet() - builder.add_ligatureCaretByPos_(self.location, glyphs, set(self.carets)) - - def asFea(self, indent=""): - return "LigatureCaretByPos {} {};".format( - self.glyphs.asFea(), " ".join(str(x) for x in self.carets) - ) - - -class LigatureSubstStatement(Statement): - """A chained contextual substitution statement. - - ``prefix``, ``glyphs``, and ``suffix`` should be lists of - `glyph-containing objects`_; ``replacement`` should be a single - `glyph-containing object`_. - - If ``forceChain`` is True, this is expressed as a chaining rule - (e.g. ``sub f' i' by f_i``) even when no context is given.""" - - def __init__(self, prefix, glyphs, suffix, replacement, forceChain, location=None): - Statement.__init__(self, location) - self.prefix, self.glyphs, self.suffix = (prefix, glyphs, suffix) - self.replacement, self.forceChain = replacement, forceChain - - def build(self, builder): - prefix = [p.glyphSet() for p in self.prefix] - glyphs = [g.glyphSet() for g in self.glyphs] - suffix = [s.glyphSet() for s in self.suffix] - builder.add_ligature_subst( - self.location, prefix, glyphs, suffix, self.replacement, self.forceChain - ) - - def asFea(self, indent=""): - res = "sub " - if len(self.prefix) or len(self.suffix) or self.forceChain: - if len(self.prefix): - res += " ".join(g.asFea() for g in self.prefix) + " " - res += " ".join(g.asFea() + "'" for g in self.glyphs) - if len(self.suffix): - res += " " + " ".join(g.asFea() for g in self.suffix) - else: - res += " ".join(g.asFea() for g in self.glyphs) - res += " by " - res += asFea(self.replacement) - res += ";" - return res - - -class LookupFlagStatement(Statement): - """A ``lookupflag`` statement. The ``value`` should be an integer value - representing the flags in use, but not including the ``markAttachment`` - class and ``markFilteringSet`` values, which must be specified as - glyph-containing objects.""" - - def __init__( - self, value=0, markAttachment=None, markFilteringSet=None, location=None - ): - Statement.__init__(self, location) - self.value = value - self.markAttachment = markAttachment - self.markFilteringSet = markFilteringSet - - def build(self, builder): - """Calls the builder object's ``set_lookup_flag`` callback.""" - markAttach = None - if self.markAttachment is not None: - markAttach = self.markAttachment.glyphSet() - markFilter = None - if self.markFilteringSet is not None: - markFilter = self.markFilteringSet.glyphSet() - builder.set_lookup_flag(self.location, self.value, markAttach, markFilter) - - def asFea(self, indent=""): - res = [] - flags = ["RightToLeft", "IgnoreBaseGlyphs", "IgnoreLigatures", "IgnoreMarks"] - curr = 1 - for i in range(len(flags)): - if self.value & curr != 0: - res.append(flags[i]) - curr = curr << 1 - if self.markAttachment is not None: - res.append("MarkAttachmentType {}".format(self.markAttachment.asFea())) - if self.markFilteringSet is not None: - res.append("UseMarkFilteringSet {}".format(self.markFilteringSet.asFea())) - if not res: - res = ["0"] - return "lookupflag {};".format(" ".join(res)) - - -class LookupReferenceStatement(Statement): - """Represents a ``lookup ...;`` statement to include a lookup in a feature. - - The ``lookup`` should be a :class:`LookupBlock` object.""" - - def __init__(self, lookup, location=None): - Statement.__init__(self, location) - self.location, self.lookup = (location, lookup) - - def build(self, builder): - """Calls the builder object's ``add_lookup_call`` callback.""" - builder.add_lookup_call(self.lookup.name) - - def asFea(self, indent=""): - return "lookup {};".format(self.lookup.name) - - -class MarkBasePosStatement(Statement): - """A mark-to-base positioning rule. The ``base`` should be a - `glyph-containing object`_. The ``marks`` should be a list of - (:class:`Anchor`, :class:`MarkClass`) tuples.""" - - def __init__(self, base, marks, location=None): - Statement.__init__(self, location) - self.base, self.marks = base, marks - - def build(self, builder): - """Calls the builder object's ``add_mark_base_pos`` callback.""" - builder.add_mark_base_pos(self.location, self.base.glyphSet(), self.marks) - - def asFea(self, indent=""): - res = "pos base {}".format(self.base.asFea()) - for a, m in self.marks: - res += "\n" + indent + SHIFT + "{} mark @{}".format(a.asFea(), m.name) - res += ";" - return res - - -class MarkLigPosStatement(Statement): - """A mark-to-ligature positioning rule. The ``ligatures`` must be a - `glyph-containing object`_. The ``marks`` should be a list of lists: each - element in the top-level list represents a component glyph, and is made - up of a list of (:class:`Anchor`, :class:`MarkClass`) tuples representing - mark attachment points for that position. - - Example:: - - m1 = MarkClass("TOP_MARKS") - m2 = MarkClass("BOTTOM_MARKS") - # ... add definitions to mark classes... - - glyph = GlyphName("lam_meem_jeem") - marks = [ - [ (Anchor(625,1800), m1) ], # Attachments on 1st component (lam) - [ (Anchor(376,-378), m2) ], # Attachments on 2nd component (meem) - [ ] # No attachments on the jeem - ] - mlp = MarkLigPosStatement(glyph, marks) - - mlp.asFea() - # pos ligature lam_meem_jeem mark @TOP_MARKS - # ligComponent mark @BOTTOM_MARKS; - - """ - - def __init__(self, ligatures, marks, location=None): - Statement.__init__(self, location) - self.ligatures, self.marks = ligatures, marks - - def build(self, builder): - """Calls the builder object's ``add_mark_lig_pos`` callback.""" - builder.add_mark_lig_pos(self.location, self.ligatures.glyphSet(), self.marks) - - def asFea(self, indent=""): - res = "pos ligature {}".format(self.ligatures.asFea()) - ligs = [] - for l in self.marks: - temp = "" - if l is None or not len(l): - temp = "\n" + indent + SHIFT * 2 + "" - else: - for a, m in l: - temp += ( - "\n" - + indent - + SHIFT * 2 - + "{} mark @{}".format(a.asFea(), m.name) - ) - ligs.append(temp) - res += ("\n" + indent + SHIFT + "ligComponent").join(ligs) - res += ";" - return res - - -class MarkMarkPosStatement(Statement): - """A mark-to-mark positioning rule. The ``baseMarks`` must be a - `glyph-containing object`_. The ``marks`` should be a list of - (:class:`Anchor`, :class:`MarkClass`) tuples.""" - - def __init__(self, baseMarks, marks, location=None): - Statement.__init__(self, location) - self.baseMarks, self.marks = baseMarks, marks - - def build(self, builder): - """Calls the builder object's ``add_mark_mark_pos`` callback.""" - builder.add_mark_mark_pos(self.location, self.baseMarks.glyphSet(), self.marks) - - def asFea(self, indent=""): - res = "pos mark {}".format(self.baseMarks.asFea()) - for a, m in self.marks: - res += "\n" + indent + SHIFT + "{} mark @{}".format(a.asFea(), m.name) - res += ";" - return res - - -class MultipleSubstStatement(Statement): - """A multiple substitution statement. - - Args: - prefix: a list of `glyph-containing objects`_. - glyph: a single glyph-containing object. - suffix: a list of glyph-containing objects. - replacement: a list of glyph-containing objects. - forceChain: If true, the statement is expressed as a chaining rule - (e.g. ``sub f' i' by f_i``) even when no context is given. - """ - - def __init__( - self, prefix, glyph, suffix, replacement, forceChain=False, location=None - ): - Statement.__init__(self, location) - self.prefix, self.glyph, self.suffix = prefix, glyph, suffix - self.replacement = replacement - self.forceChain = forceChain - - def build(self, builder): - """Calls the builder object's ``add_multiple_subst`` callback.""" - prefix = [p.glyphSet() for p in self.prefix] - suffix = [s.glyphSet() for s in self.suffix] - if hasattr(self.glyph, "glyphSet"): - originals = self.glyph.glyphSet() - else: - originals = [self.glyph] - count = len(originals) - replaces = [] - for r in self.replacement: - if hasattr(r, "glyphSet"): - replace = r.glyphSet() - else: - replace = [r] - if len(replace) == 1 and len(replace) != count: - replace = replace * count - replaces.append(replace) - replaces = list(zip(*replaces)) - - seen_originals = set() - for i, original in enumerate(originals): - if original not in seen_originals: - seen_originals.add(original) - builder.add_multiple_subst( - self.location, - prefix, - original, - suffix, - replaces and replaces[i] or (), - self.forceChain, - ) - - def asFea(self, indent=""): - res = "sub " - if len(self.prefix) or len(self.suffix) or self.forceChain: - if len(self.prefix): - res += " ".join(map(asFea, self.prefix)) + " " - res += asFea(self.glyph) + "'" - if len(self.suffix): - res += " " + " ".join(map(asFea, self.suffix)) - else: - res += asFea(self.glyph) - replacement = self.replacement or [NullGlyph()] - res += " by " - res += " ".join(map(asFea, replacement)) - res += ";" - return res - - -class PairPosStatement(Statement): - """A pair positioning statement. - - ``glyphs1`` and ``glyphs2`` should be `glyph-containing objects`_. - ``valuerecord1`` should be a :class:`ValueRecord` object; - ``valuerecord2`` should be either a :class:`ValueRecord` object or ``None``. - If ``enumerated`` is true, then this is expressed as an - `enumerated pair `_. - """ - - def __init__( - self, - glyphs1, - valuerecord1, - glyphs2, - valuerecord2, - enumerated=False, - location=None, - ): - Statement.__init__(self, location) - self.enumerated = enumerated - self.glyphs1, self.valuerecord1 = glyphs1, valuerecord1 - self.glyphs2, self.valuerecord2 = glyphs2, valuerecord2 - - def build(self, builder): - """Calls a callback on the builder object: - - * If the rule is enumerated, calls ``add_specific_pair_pos`` on each - combination of first and second glyphs. - * If the glyphs are both single :class:`GlyphName` objects, calls - ``add_specific_pair_pos``. - * Else, calls ``add_class_pair_pos``. - """ - if self.enumerated: - g = [self.glyphs1.glyphSet(), self.glyphs2.glyphSet()] - seen_pair = False - for glyph1, glyph2 in itertools.product(*g): - seen_pair = True - builder.add_specific_pair_pos( - self.location, glyph1, self.valuerecord1, glyph2, self.valuerecord2 - ) - if not seen_pair: - raise FeatureLibError( - "Empty glyph class in positioning rule", self.location - ) - return - - is_specific = isinstance(self.glyphs1, GlyphName) and isinstance( - self.glyphs2, GlyphName - ) - if is_specific: - builder.add_specific_pair_pos( - self.location, - self.glyphs1.glyph, - self.valuerecord1, - self.glyphs2.glyph, - self.valuerecord2, - ) - else: - builder.add_class_pair_pos( - self.location, - self.glyphs1.glyphSet(), - self.valuerecord1, - self.glyphs2.glyphSet(), - self.valuerecord2, - ) - - def asFea(self, indent=""): - res = "enum " if self.enumerated else "" - if self.valuerecord2: - res += "pos {} {} {} {};".format( - self.glyphs1.asFea(), - self.valuerecord1.asFea(), - self.glyphs2.asFea(), - self.valuerecord2.asFea(), - ) - else: - res += "pos {} {} {};".format( - self.glyphs1.asFea(), self.glyphs2.asFea(), self.valuerecord1.asFea() - ) - return res - - -class ReverseChainSingleSubstStatement(Statement): - """A reverse chaining substitution statement. You don't see those every day. - - Note the unusual argument order: ``suffix`` comes `before` ``glyphs``. - ``old_prefix``, ``old_suffix``, ``glyphs`` and ``replacements`` should be - lists of `glyph-containing objects`_. ``glyphs`` and ``replacements`` should - be one-item lists. - """ - - def __init__(self, old_prefix, old_suffix, glyphs, replacements, location=None): - Statement.__init__(self, location) - self.old_prefix, self.old_suffix = old_prefix, old_suffix - self.glyphs = glyphs - self.replacements = replacements - - def build(self, builder): - prefix = [p.glyphSet() for p in self.old_prefix] - suffix = [s.glyphSet() for s in self.old_suffix] - originals = self.glyphs[0].glyphSet() - replaces = self.replacements[0].glyphSet() - if len(replaces) == 1: - replaces = replaces * len(originals) - builder.add_reverse_chain_single_subst( - self.location, prefix, suffix, dict(zip(originals, replaces)) - ) - - def asFea(self, indent=""): - res = "rsub " - if len(self.old_prefix) or len(self.old_suffix): - if len(self.old_prefix): - res += " ".join(asFea(g) for g in self.old_prefix) + " " - res += " ".join(asFea(g) + "'" for g in self.glyphs) - if len(self.old_suffix): - res += " " + " ".join(asFea(g) for g in self.old_suffix) - else: - res += " ".join(map(asFea, self.glyphs)) - res += " by {};".format(" ".join(asFea(g) for g in self.replacements)) - return res - - -class SingleSubstStatement(Statement): - """A single substitution statement. - - Note the unusual argument order: ``prefix`` and suffix come `after` - the replacement ``glyphs``. ``prefix``, ``suffix``, ``glyphs`` and - ``replace`` should be lists of `glyph-containing objects`_. ``glyphs`` and - ``replace`` should be one-item lists. - """ - - def __init__(self, glyphs, replace, prefix, suffix, forceChain, location=None): - Statement.__init__(self, location) - self.prefix, self.suffix = prefix, suffix - self.forceChain = forceChain - self.glyphs = glyphs - self.replacements = replace - - def build(self, builder): - """Calls the builder object's ``add_single_subst`` callback.""" - prefix = [p.glyphSet() for p in self.prefix] - suffix = [s.glyphSet() for s in self.suffix] - originals = self.glyphs[0].glyphSet() - replaces = self.replacements[0].glyphSet() - if len(replaces) == 1: - replaces = replaces * len(originals) - builder.add_single_subst( - self.location, - prefix, - suffix, - OrderedDict(zip(originals, replaces)), - self.forceChain, - ) - - def asFea(self, indent=""): - res = "sub " - if len(self.prefix) or len(self.suffix) or self.forceChain: - if len(self.prefix): - res += " ".join(asFea(g) for g in self.prefix) + " " - res += " ".join(asFea(g) + "'" for g in self.glyphs) - if len(self.suffix): - res += " " + " ".join(asFea(g) for g in self.suffix) - else: - res += " ".join(asFea(g) for g in self.glyphs) - res += " by {};".format(" ".join(asFea(g) for g in self.replacements)) - return res - - -class ScriptStatement(Statement): - """A ``script`` statement.""" - - def __init__(self, script, location=None): - Statement.__init__(self, location) - self.script = script #: the script code - - def build(self, builder): - """Calls the builder's ``set_script`` callback.""" - builder.set_script(self.location, self.script) - - def asFea(self, indent=""): - return "script {};".format(self.script.strip()) - - -class SinglePosStatement(Statement): - """A single position statement. ``prefix`` and ``suffix`` should be - lists of `glyph-containing objects`_. - - ``pos`` should be a one-element list containing a (`glyph-containing object`_, - :class:`ValueRecord`) tuple.""" - - def __init__(self, pos, prefix, suffix, forceChain, location=None): - Statement.__init__(self, location) - self.pos, self.prefix, self.suffix = pos, prefix, suffix - self.forceChain = forceChain - - def build(self, builder): - """Calls the builder object's ``add_single_pos`` callback.""" - prefix = [p.glyphSet() for p in self.prefix] - suffix = [s.glyphSet() for s in self.suffix] - pos = [(g.glyphSet(), value) for g, value in self.pos] - builder.add_single_pos(self.location, prefix, suffix, pos, self.forceChain) - - def asFea(self, indent=""): - res = "pos " - if len(self.prefix) or len(self.suffix) or self.forceChain: - if len(self.prefix): - res += " ".join(map(asFea, self.prefix)) + " " - res += " ".join( - [ - asFea(x[0]) + "'" + ((" " + x[1].asFea()) if x[1] else "") - for x in self.pos - ] - ) - if len(self.suffix): - res += " " + " ".join(map(asFea, self.suffix)) - else: - res += " ".join( - [asFea(x[0]) + " " + (x[1].asFea() if x[1] else "") for x in self.pos] - ) - res += ";" - return res - - -class SubtableStatement(Statement): - """Represents a subtable break.""" - - def __init__(self, location=None): - Statement.__init__(self, location) - - def build(self, builder): - """Calls the builder objects's ``add_subtable_break`` callback.""" - builder.add_subtable_break(self.location) - - def asFea(self, indent=""): - return "subtable;" - - -class ValueRecord(Expression): - """Represents a value record.""" - - def __init__( - self, - xPlacement=None, - yPlacement=None, - xAdvance=None, - yAdvance=None, - xPlaDevice=None, - yPlaDevice=None, - xAdvDevice=None, - yAdvDevice=None, - vertical=False, - location=None, - ): - Expression.__init__(self, location) - self.xPlacement, self.yPlacement = (xPlacement, yPlacement) - self.xAdvance, self.yAdvance = (xAdvance, yAdvance) - self.xPlaDevice, self.yPlaDevice = (xPlaDevice, yPlaDevice) - self.xAdvDevice, self.yAdvDevice = (xAdvDevice, yAdvDevice) - self.vertical = vertical - - def __eq__(self, other): - return ( - self.xPlacement == other.xPlacement - and self.yPlacement == other.yPlacement - and self.xAdvance == other.xAdvance - and self.yAdvance == other.yAdvance - and self.xPlaDevice == other.xPlaDevice - and self.xAdvDevice == other.xAdvDevice - ) - - def __ne__(self, other): - return not self.__eq__(other) - - def __hash__(self): - return ( - hash(self.xPlacement) - ^ hash(self.yPlacement) - ^ hash(self.xAdvance) - ^ hash(self.yAdvance) - ^ hash(self.xPlaDevice) - ^ hash(self.yPlaDevice) - ^ hash(self.xAdvDevice) - ^ hash(self.yAdvDevice) - ) - - def asFea(self, indent=""): - if not self: - return "" - - x, y = self.xPlacement, self.yPlacement - xAdvance, yAdvance = self.xAdvance, self.yAdvance - xPlaDevice, yPlaDevice = self.xPlaDevice, self.yPlaDevice - xAdvDevice, yAdvDevice = self.xAdvDevice, self.yAdvDevice - vertical = self.vertical - - # Try format A, if possible. - if x is None and y is None: - if xAdvance is None and vertical: - return str(yAdvance) - elif yAdvance is None and not vertical: - return str(xAdvance) - - # Make any remaining None value 0 to avoid generating invalid records. - x = x or 0 - y = y or 0 - xAdvance = xAdvance or 0 - yAdvance = yAdvance or 0 - - # Try format B, if possible. - if ( - xPlaDevice is None - and yPlaDevice is None - and xAdvDevice is None - and yAdvDevice is None - ): - return "<%s %s %s %s>" % (x, y, xAdvance, yAdvance) - - # Last resort is format C. - return "<%s %s %s %s %s %s %s %s>" % ( - x, - y, - xAdvance, - yAdvance, - deviceToString(xPlaDevice), - deviceToString(yPlaDevice), - deviceToString(xAdvDevice), - deviceToString(yAdvDevice), - ) - - def __bool__(self): - return any( - getattr(self, v) is not None - for v in [ - "xPlacement", - "yPlacement", - "xAdvance", - "yAdvance", - "xPlaDevice", - "yPlaDevice", - "xAdvDevice", - "yAdvDevice", - ] - ) - - __nonzero__ = __bool__ - - -class ValueRecordDefinition(Statement): - """Represents a named value record definition.""" - - def __init__(self, name, value, location=None): - Statement.__init__(self, location) - self.name = name #: Value record name as string - self.value = value #: :class:`ValueRecord` object - - def asFea(self, indent=""): - return "valueRecordDef {} {};".format(self.value.asFea(), self.name) - - -def simplify_name_attributes(pid, eid, lid): - if pid == 3 and eid == 1 and lid == 1033: - return "" - elif pid == 1 and eid == 0 and lid == 0: - return "1" - else: - return "{} {} {}".format(pid, eid, lid) - - -class NameRecord(Statement): - """Represents a name record. (`Section 9.e. `_)""" - - def __init__(self, nameID, platformID, platEncID, langID, string, location=None): - Statement.__init__(self, location) - self.nameID = nameID #: Name ID as integer (e.g. 9 for designer's name) - self.platformID = platformID #: Platform ID as integer - self.platEncID = platEncID #: Platform encoding ID as integer - self.langID = langID #: Language ID as integer - self.string = string #: Name record value - - def build(self, builder): - """Calls the builder object's ``add_name_record`` callback.""" - builder.add_name_record( - self.location, - self.nameID, - self.platformID, - self.platEncID, - self.langID, - self.string, - ) - - def asFea(self, indent=""): - def escape(c, escape_pattern): - # Also escape U+0022 QUOTATION MARK and U+005C REVERSE SOLIDUS - if c >= 0x20 and c <= 0x7E and c not in (0x22, 0x5C): - return chr(c) - else: - return escape_pattern % c - - encoding = getEncoding(self.platformID, self.platEncID, self.langID) - if encoding is None: - raise FeatureLibError("Unsupported encoding", self.location) - s = tobytes(self.string, encoding=encoding) - if encoding == "utf_16_be": - escaped_string = "".join( - [ - escape(byteord(s[i]) * 256 + byteord(s[i + 1]), r"\%04x") - for i in range(0, len(s), 2) - ] - ) - else: - escaped_string = "".join([escape(byteord(b), r"\%02x") for b in s]) - plat = simplify_name_attributes(self.platformID, self.platEncID, self.langID) - if plat != "": - plat += " " - return 'nameid {} {}"{}";'.format(self.nameID, plat, escaped_string) - - -class FeatureNameStatement(NameRecord): - """Represents a ``sizemenuname`` or ``name`` statement.""" - - def build(self, builder): - """Calls the builder object's ``add_featureName`` callback.""" - NameRecord.build(self, builder) - builder.add_featureName(self.nameID) - - def asFea(self, indent=""): - if self.nameID == "size": - tag = "sizemenuname" - else: - tag = "name" - plat = simplify_name_attributes(self.platformID, self.platEncID, self.langID) - if plat != "": - plat += " " - return '{} {}"{}";'.format(tag, plat, self.string) - - -class STATNameStatement(NameRecord): - """Represents a STAT table ``name`` statement.""" - - def asFea(self, indent=""): - plat = simplify_name_attributes(self.platformID, self.platEncID, self.langID) - if plat != "": - plat += " " - return 'name {}"{}";'.format(plat, self.string) - - -class SizeParameters(Statement): - """A ``parameters`` statement.""" - - def __init__(self, DesignSize, SubfamilyID, RangeStart, RangeEnd, location=None): - Statement.__init__(self, location) - self.DesignSize = DesignSize - self.SubfamilyID = SubfamilyID - self.RangeStart = RangeStart - self.RangeEnd = RangeEnd - - def build(self, builder): - """Calls the builder object's ``set_size_parameters`` callback.""" - builder.set_size_parameters( - self.location, - self.DesignSize, - self.SubfamilyID, - self.RangeStart, - self.RangeEnd, - ) - - def asFea(self, indent=""): - res = "parameters {:.1f} {}".format(self.DesignSize, self.SubfamilyID) - if self.RangeStart != 0 or self.RangeEnd != 0: - res += " {} {}".format(int(self.RangeStart * 10), int(self.RangeEnd * 10)) - return res + ";" - - -class CVParametersNameStatement(NameRecord): - """Represent a name statement inside a ``cvParameters`` block.""" - - def __init__( - self, nameID, platformID, platEncID, langID, string, block_name, location=None - ): - NameRecord.__init__( - self, nameID, platformID, platEncID, langID, string, location=location - ) - self.block_name = block_name - - def build(self, builder): - """Calls the builder object's ``add_cv_parameter`` callback.""" - item = "" - if self.block_name == "ParamUILabelNameID": - item = "_{}".format(builder.cv_num_named_params_.get(self.nameID, 0)) - builder.add_cv_parameter(self.nameID) - self.nameID = (self.nameID, self.block_name + item) - NameRecord.build(self, builder) - - def asFea(self, indent=""): - plat = simplify_name_attributes(self.platformID, self.platEncID, self.langID) - if plat != "": - plat += " " - return 'name {}"{}";'.format(plat, self.string) - - -class CharacterStatement(Statement): - """ - Statement used in cvParameters blocks of Character Variant features (cvXX). - The Unicode value may be written with either decimal or hexadecimal - notation. The value must be preceded by '0x' if it is a hexadecimal value. - The largest Unicode value allowed is 0xFFFFFF. - """ - - def __init__(self, character, tag, location=None): - Statement.__init__(self, location) - self.character = character - self.tag = tag - - def build(self, builder): - """Calls the builder object's ``add_cv_character`` callback.""" - builder.add_cv_character(self.character, self.tag) - - def asFea(self, indent=""): - return "Character {:#x};".format(self.character) - - -class BaseAxis(Statement): - """An axis definition, being either a ``VertAxis.BaseTagList/BaseScriptList`` - pair or a ``HorizAxis.BaseTagList/BaseScriptList`` pair.""" - - def __init__(self, bases, scripts, vertical, location=None): - Statement.__init__(self, location) - self.bases = bases #: A list of baseline tag names as strings - self.scripts = scripts #: A list of script record tuplets (script tag, default baseline tag, base coordinate) - self.vertical = vertical #: Boolean; VertAxis if True, HorizAxis if False - - def build(self, builder): - """Calls the builder object's ``set_base_axis`` callback.""" - builder.set_base_axis(self.bases, self.scripts, self.vertical) - - def asFea(self, indent=""): - direction = "Vert" if self.vertical else "Horiz" - scripts = [ - "{} {} {}".format(a[0], a[1], " ".join(map(str, a[2]))) - for a in self.scripts - ] - return "{}Axis.BaseTagList {};\n{}{}Axis.BaseScriptList {};".format( - direction, " ".join(self.bases), indent, direction, ", ".join(scripts) - ) - - -class OS2Field(Statement): - """An entry in the ``OS/2`` table. Most ``values`` should be numbers or - strings, apart from when the key is ``UnicodeRange``, ``CodePageRange`` - or ``Panose``, in which case it should be an array of integers.""" - - def __init__(self, key, value, location=None): - Statement.__init__(self, location) - self.key = key - self.value = value - - def build(self, builder): - """Calls the builder object's ``add_os2_field`` callback.""" - builder.add_os2_field(self.key, self.value) - - def asFea(self, indent=""): - def intarr2str(x): - return " ".join(map(str, x)) - - numbers = ( - "FSType", - "TypoAscender", - "TypoDescender", - "TypoLineGap", - "winAscent", - "winDescent", - "XHeight", - "CapHeight", - "WeightClass", - "WidthClass", - "LowerOpSize", - "UpperOpSize", - ) - ranges = ("UnicodeRange", "CodePageRange") - keywords = dict([(x.lower(), [x, str]) for x in numbers]) - keywords.update([(x.lower(), [x, intarr2str]) for x in ranges]) - keywords["panose"] = ["Panose", intarr2str] - keywords["vendor"] = ["Vendor", lambda y: '"{}"'.format(y)] - if self.key in keywords: - return "{} {};".format( - keywords[self.key][0], keywords[self.key][1](self.value) - ) - return "" # should raise exception - - -class HheaField(Statement): - """An entry in the ``hhea`` table.""" - - def __init__(self, key, value, location=None): - Statement.__init__(self, location) - self.key = key - self.value = value - - def build(self, builder): - """Calls the builder object's ``add_hhea_field`` callback.""" - builder.add_hhea_field(self.key, self.value) - - def asFea(self, indent=""): - fields = ("CaretOffset", "Ascender", "Descender", "LineGap") - keywords = dict([(x.lower(), x) for x in fields]) - return "{} {};".format(keywords[self.key], self.value) - - -class VheaField(Statement): - """An entry in the ``vhea`` table.""" - - def __init__(self, key, value, location=None): - Statement.__init__(self, location) - self.key = key - self.value = value - - def build(self, builder): - """Calls the builder object's ``add_vhea_field`` callback.""" - builder.add_vhea_field(self.key, self.value) - - def asFea(self, indent=""): - fields = ("VertTypoAscender", "VertTypoDescender", "VertTypoLineGap") - keywords = dict([(x.lower(), x) for x in fields]) - return "{} {};".format(keywords[self.key], self.value) - - -class STATDesignAxisStatement(Statement): - """A STAT table Design Axis - - Args: - tag (str): a 4 letter axis tag - axisOrder (int): an int - names (list): a list of :class:`STATNameStatement` objects - """ - - def __init__(self, tag, axisOrder, names, location=None): - Statement.__init__(self, location) - self.tag = tag - self.axisOrder = axisOrder - self.names = names - self.location = location - - def build(self, builder): - builder.addDesignAxis(self, self.location) - - def asFea(self, indent=""): - indent += SHIFT - res = f"DesignAxis {self.tag} {self.axisOrder} {{ \n" - res += ("\n" + indent).join([s.asFea(indent=indent) for s in self.names]) + "\n" - res += "};" - return res - - -class ElidedFallbackName(Statement): - """STAT table ElidedFallbackName - - Args: - names: a list of :class:`STATNameStatement` objects - """ - - def __init__(self, names, location=None): - Statement.__init__(self, location) - self.names = names - self.location = location - - def build(self, builder): - builder.setElidedFallbackName(self.names, self.location) - - def asFea(self, indent=""): - indent += SHIFT - res = "ElidedFallbackName { \n" - res += ("\n" + indent).join([s.asFea(indent=indent) for s in self.names]) + "\n" - res += "};" - return res - - -class ElidedFallbackNameID(Statement): - """STAT table ElidedFallbackNameID - - Args: - value: an int pointing to an existing name table name ID - """ - - def __init__(self, value, location=None): - Statement.__init__(self, location) - self.value = value - self.location = location - - def build(self, builder): - builder.setElidedFallbackName(self.value, self.location) - - def asFea(self, indent=""): - return f"ElidedFallbackNameID {self.value};" - - -class STATAxisValueStatement(Statement): - """A STAT table Axis Value Record - - Args: - names (list): a list of :class:`STATNameStatement` objects - locations (list): a list of :class:`AxisValueLocationStatement` objects - flags (int): an int - """ - - def __init__(self, names, locations, flags, location=None): - Statement.__init__(self, location) - self.names = names - self.locations = locations - self.flags = flags - - def build(self, builder): - builder.addAxisValueRecord(self, self.location) - - def asFea(self, indent=""): - res = "AxisValue {\n" - for location in self.locations: - res += location.asFea() - - for nameRecord in self.names: - res += nameRecord.asFea() - res += "\n" - - if self.flags: - flags = ["OlderSiblingFontAttribute", "ElidableAxisValueName"] - flagStrings = [] - curr = 1 - for i in range(len(flags)): - if self.flags & curr != 0: - flagStrings.append(flags[i]) - curr = curr << 1 - res += f"flag {' '.join(flagStrings)};\n" - res += "};" - return res - - -class AxisValueLocationStatement(Statement): - """ - A STAT table Axis Value Location - - Args: - tag (str): a 4 letter axis tag - values (list): a list of ints and/or floats - """ - - def __init__(self, tag, values, location=None): - Statement.__init__(self, location) - self.tag = tag - self.values = values - - def asFea(self, res=""): - res += f"location {self.tag} " - res += f"{' '.join(str(i) for i in self.values)};\n" - return res - - -class ConditionsetStatement(Statement): - """ - A variable layout conditionset - - Args: - name (str): the name of this conditionset - conditions (dict): a dictionary mapping axis tags to a - tuple of (min,max) userspace coordinates. - """ - - def __init__(self, name, conditions, location=None): - Statement.__init__(self, location) - self.name = name - self.conditions = conditions - - def build(self, builder): - builder.add_conditionset(self.location, self.name, self.conditions) - - def asFea(self, res="", indent=""): - res += indent + f"conditionset {self.name} " + "{\n" - for tag, (minvalue, maxvalue) in self.conditions.items(): - res += indent + SHIFT + f"{tag} {minvalue} {maxvalue};\n" - res += indent + "}" + f" {self.name};\n" - return res - - -class VariationBlock(Block): - """A variation feature block, applicable in a given set of conditions.""" - - def __init__(self, name, conditionset, use_extension=False, location=None): - Block.__init__(self, location) - self.name, self.conditionset, self.use_extension = ( - name, - conditionset, - use_extension, - ) - - def build(self, builder): - """Call the ``start_feature`` callback on the builder object, visit - all the statements in this feature, and then call ``end_feature``.""" - builder.start_feature(self.location, self.name) - if ( - self.conditionset != "NULL" - and self.conditionset not in builder.conditionsets_ - ): - raise FeatureLibError( - f"variation block used undefined conditionset {self.conditionset}", - self.location, - ) - - # language exclude_dflt statements modify builder.features_ - # limit them to this block with temporary builder.features_ - features = builder.features_ - builder.features_ = {} - Block.build(self, builder) - for key, value in builder.features_.items(): - items = builder.feature_variations_.setdefault(key, {}).setdefault( - self.conditionset, [] - ) - items.extend(value) - if key not in features: - features[key] = [] # Ensure we make a feature record - builder.features_ = features - builder.end_feature() - - def asFea(self, indent=""): - res = indent + "variation %s " % self.name.strip() - res += self.conditionset + " " - if self.use_extension: - res += "useExtension " - res += "{\n" - res += Block.asFea(self, indent=indent) - res += indent + "} %s;\n" % self.name.strip() - return res diff --git a/spaces/Datasculptor/3D-Room-Layout-Estimation_LGT-Net/dataset/communal/read.py b/spaces/Datasculptor/3D-Room-Layout-Estimation_LGT-Net/dataset/communal/read.py deleted file mode 100644 index 1098a9838110b48eac32c84909ae7407bbcc719f..0000000000000000000000000000000000000000 --- a/spaces/Datasculptor/3D-Room-Layout-Estimation_LGT-Net/dataset/communal/read.py +++ /dev/null @@ -1,214 +0,0 @@ -""" -@Date: 2021/07/28 -@description: -""" -import os -import numpy as np -import cv2 -import json -from PIL import Image -from utils.conversion import xyz2uv, pixel2uv -from utils.height import calc_ceil_ratio - - -def read_image(image_path, shape=None): - if shape is None: - shape = [512, 1024] - img = np.array(Image.open(image_path)).astype(np.float32) / 255 - if img.shape[0] != shape[0] or img.shape[1] != shape[1]: - img = cv2.resize(img, dsize=tuple(shape[::-1]), interpolation=cv2.INTER_AREA) - - return np.array(img) - - -def read_label(label_path, data_type='MP3D'): - - if data_type == 'MP3D': - with open(label_path, 'r') as f: - label = json.load(f) - point_idx = [one['pointsIdx'][0] for one in label['layoutWalls']['walls']] - camera_height = label['cameraHeight'] - room_height = label['layoutHeight'] - camera_ceiling_height = room_height - camera_height - ratio = camera_ceiling_height / camera_height - - xyz = [one['xyz'] for one in label['layoutPoints']['points']] - assert len(xyz) == len(point_idx), "len(xyz) != len(point_idx)" - xyz = [xyz[i] for i in point_idx] - xyz = np.asarray(xyz, dtype=np.float32) - xyz[:, 2] *= -1 - xyz[:, 1] = camera_height - corners = xyz2uv(xyz) - elif data_type == 'Pano_S2D3D': - with open(label_path, 'r') as f: - lines = [line for line in f.readlines() if - len([c for c in line.split(' ') if c[0].isnumeric()]) > 1] - - corners_list = np.array([line.strip().split() for line in lines], np.float32) - uv_list = pixel2uv(corners_list) - ceil_uv = uv_list[::2] - floor_uv = uv_list[1::2] - ratio = calc_ceil_ratio([ceil_uv, floor_uv], mode='mean') - corners = floor_uv - else: - return None - - output = { - 'ratio': np.array([ratio], dtype=np.float32), - 'corners': corners, - 'id': os.path.basename(label_path).split('.')[0] - } - return output - - -def move_not_simple_image(data_dir, simple_panos): - import shutil - for house_index in os.listdir(data_dir): - house_path = os.path.join(data_dir, house_index) - if not os.path.isdir(house_path) or house_index == 'visualization': - continue - - floor_plan_path = os.path.join(house_path, 'floor_plans') - if os.path.exists(floor_plan_path): - print(f'move:{floor_plan_path}') - dst_floor_plan_path = floor_plan_path.replace('zind', 'zind2') - os.makedirs(dst_floor_plan_path, exist_ok=True) - shutil.move(floor_plan_path, dst_floor_plan_path) - - panos_path = os.path.join(house_path, 'panos') - for pano in os.listdir(panos_path): - pano_path = os.path.join(panos_path, pano) - pano_index = '_'.join(pano.split('.')[0].split('_')[-2:]) - if f'{house_index}_{pano_index}' not in simple_panos and os.path.exists(pano_path): - print(f'move:{pano_path}') - dst_pano_path = pano_path.replace('zind', 'zind2') - os.makedirs(os.path.dirname(dst_pano_path), exist_ok=True) - shutil.move(pano_path, dst_pano_path) - - -def read_zind(partition_path, simplicity_path, data_dir, mode, is_simple=True, - layout_type='layout_raw', is_ceiling_flat=False, plan_y=1): - with open(simplicity_path, 'r') as f: - simple_tag = json.load(f) - simple_panos = {} - for k in simple_tag.keys(): - if not simple_tag[k]: - continue - split = k.split('_') - house_index = split[0] - pano_index = '_'.join(split[-2:]) - simple_panos[f'{house_index}_{pano_index}'] = True - - # move_not_simple_image(data_dir, simple_panos) - - pano_list = [] - with open(partition_path, 'r') as f1: - house_list = json.load(f1)[mode] - - for house_index in house_list: - with open(os.path.join(data_dir, house_index, f"zind_data.json"), 'r') as f2: - data = json.load(f2) - - panos = [] - merger = data['merger'] - for floor in merger.values(): - for complete_room in floor.values(): - for partial_room in complete_room.values(): - for pano_index in partial_room: - pano = partial_room[pano_index] - pano['index'] = pano_index - panos.append(pano) - - for pano in panos: - if layout_type not in pano: - continue - pano_index = pano['index'] - - if is_simple and f'{house_index}_{pano_index}' not in simple_panos.keys(): - continue - - if is_ceiling_flat and not pano['is_ceiling_flat']: - continue - - layout = pano[layout_type] - # corners - corner_xz = np.array(layout['vertices']) - corner_xz[..., 0] = -corner_xz[..., 0] - corner_xyz = np.insert(corner_xz, 1, pano['camera_height'], axis=1) - corners = xyz2uv(corner_xyz).astype(np.float32) - - # ratio - ratio = np.array([(pano['ceiling_height'] - pano['camera_height']) / pano['camera_height']], dtype=np.float32) - - # Ours future work: detection window, door, opening - objects = { - 'windows': [], - 'doors': [], - 'openings': [], - } - for label_index, wdo_type in enumerate(["windows", "doors", "openings"]): - if wdo_type not in layout: - continue - - wdo_vertices = np.array(layout[wdo_type]) - if len(wdo_vertices) == 0: - continue - - assert len(wdo_vertices) % 3 == 0 - - for i in range(0, len(wdo_vertices), 3): - # In the Zind dataset, the camera height is 1, and the default camera height in our code is also 1, - # so the xyz coordinate here can be used directly - # Since we're taking the opposite z-axis, we're changing the order of left and right - - left_bottom_xyz = np.array( - [-wdo_vertices[i + 1][0], -wdo_vertices[i + 2][0], wdo_vertices[i + 1][1]]) - right_bottom_xyz = np.array( - [-wdo_vertices[i][0], -wdo_vertices[i + 2][0], wdo_vertices[i][1]]) - center_bottom_xyz = (left_bottom_xyz + right_bottom_xyz) / 2 - - center_top_xyz = center_bottom_xyz.copy() - center_top_xyz[1] = -wdo_vertices[i + 2][1] - - center_boundary_xyz = center_bottom_xyz.copy() - center_boundary_xyz[1] = plan_y - - uv = xyz2uv(np.array([left_bottom_xyz, right_bottom_xyz, - center_bottom_xyz, center_top_xyz, - center_boundary_xyz])) - - left_bottom_uv = uv[0] - right_bottom_uv = uv[1] - width_u = abs(right_bottom_uv[0] - left_bottom_uv[0]) - width_u = 1 - width_u if width_u > 0.5 else width_u - assert width_u > 0, width_u - - center_bottom_uv = uv[2] - center_top_uv = uv[3] - height_v = center_bottom_uv[1] - center_top_uv[1] - - if height_v < 0: - continue - - center_boundary_uv = uv[4] - boundary_v = center_boundary_uv[1] - center_bottom_uv[1] if wdo_type == 'windows' else 0 - boundary_v = 0 if boundary_v < 0 else boundary_v - - center_u = center_bottom_uv[0] - - objects[wdo_type].append({ - 'width_u': width_u, - 'height_v': height_v, - 'boundary_v': boundary_v, - 'center_u': center_u - }) - - pano_list.append({ - 'img_path': os.path.join(data_dir, house_index, pano['image_path']), - 'corners': corners, - 'objects': objects, - 'ratio': ratio, - 'id': f'{house_index}_{pano_index}', - 'is_inside': pano['is_inside'] - }) - return pano_list diff --git a/spaces/Dauzy/whisper-webui/LICENSE.md b/spaces/Dauzy/whisper-webui/LICENSE.md deleted file mode 100644 index f5f4b8b5ecd27c09e4ef16e9662bcb7bb2bfc76f..0000000000000000000000000000000000000000 --- a/spaces/Dauzy/whisper-webui/LICENSE.md +++ /dev/null @@ -1,195 +0,0 @@ -Apache License -============== - -_Version 2.0, January 2004_ -_<>_ - -### Terms and Conditions for use, reproduction, and distribution - -#### 1. Definitions - -“License” shall mean the terms and conditions for use, reproduction, and -distribution as defined by Sections 1 through 9 of this document. - -“Licensor” shall mean the copyright owner or entity authorized by the copyright -owner that is granting the License. - -“Legal Entity” shall mean the union of the acting entity and all other entities -that control, are controlled by, or are under common control with that entity. -For the purposes of this definition, “control” means **(i)** the power, direct or -indirect, to cause the direction or management of such entity, whether by -contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the -outstanding shares, or **(iii)** beneficial ownership of such entity. - -“You” (or “Your”) shall mean an individual or Legal Entity exercising -permissions granted by this License. - -“Source” form shall mean the preferred form for making modifications, including -but not limited to software source code, documentation source, and configuration -files. - -“Object” form shall mean any form resulting from mechanical transformation or -translation of a Source form, including but not limited to compiled object code, -generated documentation, and conversions to other media types. - -“Work” shall mean the work of authorship, whether in Source or Object form, made -available under the License, as indicated by a copyright notice that is included -in or attached to the work (an example is provided in the Appendix below). - -“Derivative Works” shall mean any work, whether in Source or Object form, that -is based on (or derived from) the Work and for which the editorial revisions, -annotations, elaborations, or other modifications represent, as a whole, an -original work of authorship. For the purposes of this License, Derivative Works -shall not include works that remain separable from, or merely link (or bind by -name) to the interfaces of, the Work and Derivative Works thereof. - -“Contribution” shall mean any work of authorship, including the original version -of the Work and any modifications or additions to that Work or Derivative Works -thereof, that is intentionally submitted to Licensor for inclusion in the Work -by the copyright owner or by an individual or Legal Entity authorized to submit -on behalf of the copyright owner. For the purposes of this definition, -“submitted” means any form of electronic, verbal, or written communication sent -to the Licensor or its representatives, including but not limited to -communication on electronic mailing lists, source code control systems, and -issue tracking systems that are managed by, or on behalf of, the Licensor for -the purpose of discussing and improving the Work, but excluding communication -that is conspicuously marked or otherwise designated in writing by the copyright -owner as “Not a Contribution.” - -“Contributor” shall mean Licensor and any individual or Legal Entity on behalf -of whom a Contribution has been received by Licensor and subsequently -incorporated within the Work. - -#### 2. Grant of Copyright License - -Subject to the terms and conditions of this License, each Contributor hereby -grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable copyright license to reproduce, prepare Derivative Works of, -publicly display, publicly perform, sublicense, and distribute the Work and such -Derivative Works in Source or Object form. - -#### 3. Grant of Patent License - -Subject to the terms and conditions of this License, each Contributor hereby -grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable (except as stated in this section) patent license to make, have -made, use, offer to sell, sell, import, and otherwise transfer the Work, where -such license applies only to those patent claims licensable by such Contributor -that are necessarily infringed by their Contribution(s) alone or by combination -of their Contribution(s) with the Work to which such Contribution(s) was -submitted. If You institute patent litigation against any entity (including a -cross-claim or counterclaim in a lawsuit) alleging that the Work or a -Contribution incorporated within the Work constitutes direct or contributory -patent infringement, then any patent licenses granted to You under this License -for that Work shall terminate as of the date such litigation is filed. - -#### 4. Redistribution - -You may reproduce and distribute copies of the Work or Derivative Works thereof -in any medium, with or without modifications, and in Source or Object form, -provided that You meet the following conditions: - -* **(a)** You must give any other recipients of the Work or Derivative Works a copy of -this License; and -* **(b)** You must cause any modified files to carry prominent notices stating that You -changed the files; and -* **(c)** You must retain, in the Source form of any Derivative Works that You distribute, -all copyright, patent, trademark, and attribution notices from the Source form -of the Work, excluding those notices that do not pertain to any part of the -Derivative Works; and -* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any -Derivative Works that You distribute must include a readable copy of the -attribution notices contained within such NOTICE file, excluding those notices -that do not pertain to any part of the Derivative Works, in at least one of the -following places: within a NOTICE text file distributed as part of the -Derivative Works; within the Source form or documentation, if provided along -with the Derivative Works; or, within a display generated by the Derivative -Works, if and wherever such third-party notices normally appear. The contents of -the NOTICE file are for informational purposes only and do not modify the -License. You may add Your own attribution notices within Derivative Works that -You distribute, alongside or as an addendum to the NOTICE text from the Work, -provided that such additional attribution notices cannot be construed as -modifying the License. - -You may add Your own copyright statement to Your modifications and may provide -additional or different license terms and conditions for use, reproduction, or -distribution of Your modifications, or for any such Derivative Works as a whole, -provided Your use, reproduction, and distribution of the Work otherwise complies -with the conditions stated in this License. - -#### 5. Submission of Contributions - -Unless You explicitly state otherwise, any Contribution intentionally submitted -for inclusion in the Work by You to the Licensor shall be under the terms and -conditions of this License, without any additional terms or conditions. -Notwithstanding the above, nothing herein shall supersede or modify the terms of -any separate license agreement you may have executed with Licensor regarding -such Contributions. - -#### 6. Trademarks - -This License does not grant permission to use the trade names, trademarks, -service marks, or product names of the Licensor, except as required for -reasonable and customary use in describing the origin of the Work and -reproducing the content of the NOTICE file. - -#### 7. Disclaimer of Warranty - -Unless required by applicable law or agreed to in writing, Licensor provides the -Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, -including, without limitation, any warranties or conditions of TITLE, -NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are -solely responsible for determining the appropriateness of using or -redistributing the Work and assume any risks associated with Your exercise of -permissions under this License. - -#### 8. Limitation of Liability - -In no event and under no legal theory, whether in tort (including negligence), -contract, or otherwise, unless required by applicable law (such as deliberate -and grossly negligent acts) or agreed to in writing, shall any Contributor be -liable to You for damages, including any direct, indirect, special, incidental, -or consequential damages of any character arising as a result of this License or -out of the use or inability to use the Work (including but not limited to -damages for loss of goodwill, work stoppage, computer failure or malfunction, or -any and all other commercial damages or losses), even if such Contributor has -been advised of the possibility of such damages. - -#### 9. Accepting Warranty or Additional Liability - -While redistributing the Work or Derivative Works thereof, You may choose to -offer, and charge a fee for, acceptance of support, warranty, indemnity, or -other liability obligations and/or rights consistent with this License. However, -in accepting such obligations, You may act only on Your own behalf and on Your -sole responsibility, not on behalf of any other Contributor, and only if You -agree to indemnify, defend, and hold each Contributor harmless for any liability -incurred by, or claims asserted against, such Contributor by reason of your -accepting any such warranty or additional liability. - -_END OF TERMS AND CONDITIONS_ - -### APPENDIX: How to apply the Apache License to your work - -To apply the Apache License to your work, attach the following boilerplate -notice, with the fields enclosed by brackets `[]` replaced with your own -identifying information. (Don't include the brackets!) The text should be -enclosed in the appropriate comment syntax for the file format. We also -recommend that a file or class name and description of purpose be included on -the same “printed page” as the copyright notice for easier identification within -third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. - diff --git a/spaces/Detomo/ai-comic-generation/src/app/engine/community.ts b/spaces/Detomo/ai-comic-generation/src/app/engine/community.ts deleted file mode 100644 index 33bc412fac7767d707861e125d1c1434e7cd286c..0000000000000000000000000000000000000000 --- a/spaces/Detomo/ai-comic-generation/src/app/engine/community.ts +++ /dev/null @@ -1,135 +0,0 @@ -"use server" - -import { v4 as uuidv4 } from "uuid" - -import { CreatePostResponse, GetAppPostsResponse, Post, PostVisibility } from "@/types" -import { filterOutBadWords } from "./censorship" - -const apiUrl = `${process.env.COMMUNITY_API_URL || ""}` -const apiToken = `${process.env.COMMUNITY_API_TOKEN || ""}` -const appId = `${process.env.COMMUNITY_API_ID || ""}` - -export async function postToCommunity({ - prompt, - assetUrl, -}: { - prompt: string - assetUrl: string -}): Promise { - - prompt = filterOutBadWords(prompt) - - // if the community API is disabled, - // we don't fail, we just mock - if (!apiUrl) { - const mockPost: Post = { - postId: uuidv4(), - appId: "mock", - prompt, - previewUrl: assetUrl, - assetUrl, - createdAt: new Date().toISOString(), - visibility: "normal", - upvotes: 0, - downvotes: 0 - } - return mockPost - } - - if (!prompt) { - console.error(`cannot call the community API without a prompt, aborting..`) - throw new Error(`cannot call the community API without a prompt, aborting..`) - } - if (!assetUrl) { - console.error(`cannot call the community API without an assetUrl, aborting..`) - throw new Error(`cannot call the community API without an assetUrl, aborting..`) - } - - try { - console.log(`calling POST ${apiUrl}/posts/${appId} with prompt: ${prompt}`) - - const postId = uuidv4() - - const post: Partial = { postId, appId, prompt, assetUrl } - - console.table(post) - - const res = await fetch(`${apiUrl}/posts/${appId}`, { - method: "POST", - headers: { - Accept: "application/json", - "Content-Type": "application/json", - Authorization: `Bearer ${apiToken}`, - }, - body: JSON.stringify(post), - cache: 'no-store', - // we can also use this (see https://vercel.com/blog/vercel-cache-api-nextjs-cache) - // next: { revalidate: 1 } - }) - - // console.log("res:", res) - // The return value is *not* serialized - // You can return Date, Map, Set, etc. - - // Recommendation: handle errors - if (res.status !== 200) { - // This will activate the closest `error.js` Error Boundary - throw new Error('Failed to fetch data') - } - - const response = (await res.json()) as CreatePostResponse - // console.log("response:", response) - return response.post - } catch (err) { - const error = `failed to post to community: ${err}` - console.error(error) - throw new Error(error) - } -} - -export async function getLatestPosts(visibility?: PostVisibility): Promise { - - let posts: Post[] = [] - - // if the community API is disabled we don't fail, - // we just mock - if (!apiUrl) { - return posts - } - - try { - // console.log(`calling GET ${apiUrl}/posts with renderId: ${renderId}`) - const res = await fetch(`${apiUrl}/posts/${appId}/${ - visibility || "all" - }`, { - method: "GET", - headers: { - Accept: "application/json", - "Content-Type": "application/json", - Authorization: `Bearer ${apiToken}`, - }, - cache: 'no-store', - // we can also use this (see https://vercel.com/blog/vercel-cache-api-nextjs-cache) - // next: { revalidate: 1 } - }) - - // console.log("res:", res) - // The return value is *not* serialized - // You can return Date, Map, Set, etc. - - // Recommendation: handle errors - if (res.status !== 200) { - // This will activate the closest `error.js` Error Boundary - throw new Error('Failed to fetch data') - } - - const response = (await res.json()) as GetAppPostsResponse - // console.log("response:", response) - return Array.isArray(response?.posts) ? response?.posts : [] - } catch (err) { - // const error = `failed to get posts: ${err}` - // console.error(error) - // throw new Error(error) - return [] - } -} \ No newline at end of file diff --git a/spaces/DragGan/DragGan-Inversion/PTI/configs/global_config.py b/spaces/DragGan/DragGan-Inversion/PTI/configs/global_config.py deleted file mode 100644 index bf3a20e61b0baf5e85377570cdf0f235bade21bd..0000000000000000000000000000000000000000 --- a/spaces/DragGan/DragGan-Inversion/PTI/configs/global_config.py +++ /dev/null @@ -1,12 +0,0 @@ -# Device -cuda_visible_devices = '0' -device = 'cuda:0' - -# Logs -training_step = 1 -image_rec_result_log_snapshot = 100 -pivotal_training_steps = 0 -model_snapshot_interval = 400 - -# Run name to be updated during PTI -run_name = '' diff --git a/spaces/DragGan/DragGan/stylegan_human/torch_utils/custom_ops.py b/spaces/DragGan/DragGan/stylegan_human/torch_utils/custom_ops.py deleted file mode 100644 index fda77a69777a69bd3eda96713c29f66fe3b016b9..0000000000000000000000000000000000000000 --- a/spaces/DragGan/DragGan/stylegan_human/torch_utils/custom_ops.py +++ /dev/null @@ -1,238 +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. - -import os -import glob -import torch -import torch.utils.cpp_extension -import importlib -import hashlib -import shutil -from pathlib import Path -import re -import uuid - -from torch.utils.file_baton import FileBaton - -#---------------------------------------------------------------------------- -# Global options. - -verbosity = 'brief' # Verbosity level: 'none', 'brief', 'full' - -#---------------------------------------------------------------------------- -# Internal helper funcs. - -def _find_compiler_bindir(): - patterns = [ - 'C:/Program Files (x86)/Microsoft Visual Studio/*/Professional/VC/Tools/MSVC/*/bin/Hostx64/x64', - 'C:/Program Files (x86)/Microsoft Visual Studio/*/BuildTools/VC/Tools/MSVC/*/bin/Hostx64/x64', - 'C:/Program Files (x86)/Microsoft Visual Studio/*/Community/VC/Tools/MSVC/*/bin/Hostx64/x64', - 'C:/Program Files (x86)/Microsoft Visual Studio */vc/bin', - ] - for pattern in patterns: - matches = sorted(glob.glob(pattern)) - if len(matches): - return matches[-1] - return None - -def _get_mangled_gpu_name(): - name = torch.cuda.get_device_name().lower() - out = [] - for c in name: - if re.match('[a-z0-9_-]+', c): - out.append(c) - else: - out.append('-') - return ''.join(out) - - -#---------------------------------------------------------------------------- -# Main entry point for compiling and loading C++/CUDA plugins. - -_cached_plugins = dict() - -def get_plugin(module_name, sources, **build_kwargs): - assert verbosity in ['none', 'brief', 'full'] - - # Already cached? - if module_name in _cached_plugins: - return _cached_plugins[module_name] - - # Print status. - if verbosity == 'full': - print(f'Setting up PyTorch plugin "{module_name}"...') - elif verbosity == 'brief': - print(f'Setting up PyTorch plugin "{module_name}"... ', end='', flush=True) - - try: # pylint: disable=too-many-nested-blocks - # Make sure we can find the necessary compiler binaries. - if os.name == 'nt' and os.system("where cl.exe >nul 2>nul") != 0: - compiler_bindir = _find_compiler_bindir() - if compiler_bindir is None: - raise RuntimeError(f'Could not find MSVC/GCC/CLANG installation on this computer. Check _find_compiler_bindir() in "{__file__}".') - os.environ['PATH'] += ';' + compiler_bindir - - # Compile and load. - verbose_build = (verbosity == 'full') - - # Incremental build md5sum trickery. Copies all the input source files - # into a cached build directory under a combined md5 digest of the input - # source files. Copying is done only if the combined digest has changed. - # This keeps input file timestamps and filenames the same as in previous - # extension builds, allowing for fast incremental rebuilds. - # - # This optimization is done only in case all the source files reside in - # a single directory (just for simplicity) and if the TORCH_EXTENSIONS_DIR - # environment variable is set (we take this as a signal that the user - # actually cares about this.) - source_dirs_set = set(os.path.dirname(source) for source in sources) - if len(source_dirs_set) == 1 and ('TORCH_EXTENSIONS_DIR' in os.environ): - all_source_files = sorted(list(x for x in Path(list(source_dirs_set)[0]).iterdir() if x.is_file())) - - # Compute a combined hash digest for all source files in the same - # custom op directory (usually .cu, .cpp, .py and .h files). - hash_md5 = hashlib.md5() - for src in all_source_files: - with open(src, 'rb') as f: - hash_md5.update(f.read()) - build_dir = torch.utils.cpp_extension._get_build_directory(module_name, verbose=verbose_build) # pylint: disable=protected-access - digest_build_dir = os.path.join(build_dir, hash_md5.hexdigest()) - - if not os.path.isdir(digest_build_dir): - os.makedirs(digest_build_dir, exist_ok=True) - baton = FileBaton(os.path.join(digest_build_dir, 'lock')) - if baton.try_acquire(): - try: - for src in all_source_files: - shutil.copyfile(src, os.path.join(digest_build_dir, os.path.basename(src))) - finally: - baton.release() - else: - # Someone else is copying source files under the digest dir, - # wait until done and continue. - baton.wait() - digest_sources = [os.path.join(digest_build_dir, os.path.basename(x)) for x in sources] - torch.utils.cpp_extension.load(name=module_name, build_directory=build_dir, - verbose=verbose_build, sources=digest_sources, **build_kwargs) - else: - torch.utils.cpp_extension.load(name=module_name, verbose=verbose_build, sources=sources, **build_kwargs) - module = importlib.import_module(module_name) - - except: - if verbosity == 'brief': - print('Failed!') - raise - - # Print status and add to cache. - if verbosity == 'full': - print(f'Done setting up PyTorch plugin "{module_name}".') - elif verbosity == 'brief': - print('Done.') - _cached_plugins[module_name] = module - return module - -#---------------------------------------------------------------------------- -def get_plugin_v3(module_name, sources, headers=None, source_dir=None, **build_kwargs): - assert verbosity in ['none', 'brief', 'full'] - if headers is None: - headers = [] - if source_dir is not None: - sources = [os.path.join(source_dir, fname) for fname in sources] - headers = [os.path.join(source_dir, fname) for fname in headers] - - # Already cached? - if module_name in _cached_plugins: - return _cached_plugins[module_name] - - # Print status. - if verbosity == 'full': - print(f'Setting up PyTorch plugin "{module_name}"...') - elif verbosity == 'brief': - print(f'Setting up PyTorch plugin "{module_name}"... ', end='', flush=True) - verbose_build = (verbosity == 'full') - - # Compile and load. - try: # pylint: disable=too-many-nested-blocks - # Make sure we can find the necessary compiler binaries. - if os.name == 'nt' and os.system("where cl.exe >nul 2>nul") != 0: - compiler_bindir = _find_compiler_bindir() - if compiler_bindir is None: - raise RuntimeError(f'Could not find MSVC/GCC/CLANG installation on this computer. Check _find_compiler_bindir() in "{__file__}".') - os.environ['PATH'] += ';' + compiler_bindir - - # Some containers set TORCH_CUDA_ARCH_LIST to a list that can either - # break the build or unnecessarily restrict what's available to nvcc. - # Unset it to let nvcc decide based on what's available on the - # machine. - os.environ['TORCH_CUDA_ARCH_LIST'] = '' - - # Incremental build md5sum trickery. Copies all the input source files - # into a cached build directory under a combined md5 digest of the input - # source files. Copying is done only if the combined digest has changed. - # This keeps input file timestamps and filenames the same as in previous - # extension builds, allowing for fast incremental rebuilds. - # - # This optimization is done only in case all the source files reside in - # a single directory (just for simplicity) and if the TORCH_EXTENSIONS_DIR - # environment variable is set (we take this as a signal that the user - # actually cares about this.) - # - # EDIT: We now do it regardless of TORCH_EXTENSIOS_DIR, in order to work - # around the *.cu dependency bug in ninja config. - # - all_source_files = sorted(sources + headers) - all_source_dirs = set(os.path.dirname(fname) for fname in all_source_files) - if len(all_source_dirs) == 1: # and ('TORCH_EXTENSIONS_DIR' in os.environ): - - # Compute combined hash digest for all source files. - hash_md5 = hashlib.md5() - for src in all_source_files: - with open(src, 'rb') as f: - hash_md5.update(f.read()) - - # Select cached build directory name. - source_digest = hash_md5.hexdigest() - build_top_dir = torch.utils.cpp_extension._get_build_directory(module_name, verbose=verbose_build) # pylint: disable=protected-access - cached_build_dir = os.path.join(build_top_dir, f'{source_digest}-{_get_mangled_gpu_name()}') - - if not os.path.isdir(cached_build_dir): - tmpdir = f'{build_top_dir}/srctmp-{uuid.uuid4().hex}' - os.makedirs(tmpdir) - for src in all_source_files: - shutil.copyfile(src, os.path.join(tmpdir, os.path.basename(src))) - try: - os.replace(tmpdir, cached_build_dir) # atomic - except OSError: - # source directory already exists, delete tmpdir and its contents. - shutil.rmtree(tmpdir) - if not os.path.isdir(cached_build_dir): raise - - # Compile. - cached_sources = [os.path.join(cached_build_dir, os.path.basename(fname)) for fname in sources] - torch.utils.cpp_extension.load(name=module_name, build_directory=cached_build_dir, - verbose=verbose_build, sources=cached_sources, **build_kwargs) - else: - torch.utils.cpp_extension.load(name=module_name, verbose=verbose_build, sources=sources, **build_kwargs) - - # Load. - module = importlib.import_module(module_name) - - except: - if verbosity == 'brief': - print('Failed!') - raise - - # Print status and add to cache dict. - if verbosity == 'full': - print(f'Done setting up PyTorch plugin "{module_name}".') - elif verbosity == 'brief': - print('Done.') - _cached_plugins[module_name] = module - return module \ No newline at end of file diff --git a/spaces/Duskfallcrew/duskfall-s-general-digital-art-model/README.md b/spaces/Duskfallcrew/duskfall-s-general-digital-art-model/README.md deleted file mode 100644 index 6143c1cf38bdc506cf23051c443942373cc8dafc..0000000000000000000000000000000000000000 --- a/spaces/Duskfallcrew/duskfall-s-general-digital-art-model/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Duskfall S General Digital Art Model -emoji: 👁 -colorFrom: blue -colorTo: purple -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/ECCV2022/bytetrack/deploy/ncnn/cpp/include/lapjv.h b/spaces/ECCV2022/bytetrack/deploy/ncnn/cpp/include/lapjv.h deleted file mode 100644 index 0e34385a647bec225827370ff0041a391e628477..0000000000000000000000000000000000000000 --- a/spaces/ECCV2022/bytetrack/deploy/ncnn/cpp/include/lapjv.h +++ /dev/null @@ -1,63 +0,0 @@ -#ifndef LAPJV_H -#define LAPJV_H - -#define LARGE 1000000 - -#if !defined TRUE -#define TRUE 1 -#endif -#if !defined FALSE -#define FALSE 0 -#endif - -#define NEW(x, t, n) if ((x = (t *)malloc(sizeof(t) * (n))) == 0) { return -1; } -#define FREE(x) if (x != 0) { free(x); x = 0; } -#define SWAP_INDICES(a, b) { int_t _temp_index = a; a = b; b = _temp_index; } - -#if 0 -#include -#define ASSERT(cond) assert(cond) -#define PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__) -#define PRINT_COST_ARRAY(a, n) \ - while (1) { \ - printf(#a" = ["); \ - if ((n) > 0) { \ - printf("%f", (a)[0]); \ - for (uint_t j = 1; j < n; j++) { \ - printf(", %f", (a)[j]); \ - } \ - } \ - printf("]\n"); \ - break; \ - } -#define PRINT_INDEX_ARRAY(a, n) \ - while (1) { \ - printf(#a" = ["); \ - if ((n) > 0) { \ - printf("%d", (a)[0]); \ - for (uint_t j = 1; j < n; j++) { \ - printf(", %d", (a)[j]); \ - } \ - } \ - printf("]\n"); \ - break; \ - } -#else -#define ASSERT(cond) -#define PRINTF(fmt, ...) -#define PRINT_COST_ARRAY(a, n) -#define PRINT_INDEX_ARRAY(a, n) -#endif - - -typedef signed int int_t; -typedef unsigned int uint_t; -typedef double cost_t; -typedef char boolean; -typedef enum fp_t { FP_1 = 1, FP_2 = 2, FP_DYNAMIC = 3 } fp_t; - -extern int_t lapjv_internal( - const uint_t n, cost_t *cost[], - int_t *x, int_t *y); - -#endif // LAPJV_H \ No newline at end of file diff --git a/spaces/Ebost/animeganv2-self/README.md b/spaces/Ebost/animeganv2-self/README.md deleted file mode 100644 index f6e37a93842200b7bdaf81afa0e346a734f38733..0000000000000000000000000000000000000000 --- a/spaces/Ebost/animeganv2-self/README.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: Animeganv2 Self -emoji: 🚀 -colorFrom: red -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/Falah/object_detection/app.py b/spaces/Falah/object_detection/app.py deleted file mode 100644 index d630c6e624870210aefc1eefa02735d460a85f01..0000000000000000000000000000000000000000 --- a/spaces/Falah/object_detection/app.py +++ /dev/null @@ -1,49 +0,0 @@ -import gradio as gr -from transformers import pipeline -from PIL import Image, ImageDraw - -checkpoint = "google/owlvit-base-patch32" -detector = pipeline(model=checkpoint, task="zero-shot-object-detection") - -def detect_and_visualize_objects(image): - # Convert the image to RGB format - image = image.convert("RGB") - - # Process the image using the object detection model - predictions = detector( - image, - candidate_labels=["human face", "rocket"], - ) - - # Draw bounding boxes and labels on the image - draw = ImageDraw.Draw(image) - if len(predictions) == 0: - draw.text((100, 100), "Object not found in image", fill="red") - else: - for prediction in predictions: - box = prediction["box"] - label = prediction["label"] - score = prediction["score"] - - xmin, ymin, xmax, ymax = box.values() - draw.rectangle((xmin, ymin, xmax, ymax), outline="red", width=1) - draw.text((xmin, ymin), f"{label}: {round(score, 2)}", fill="white") - - # Return the annotated image - return image - -# Define the Gradio interface -image_input = gr.inputs.Image(type="pil") -image_output = gr.outputs.Image(type="pil") -iface = gr.Interface( - fn=detect_and_visualize_objects, - inputs=image_input, - outputs=image_output, - title="Space and War Missile Detection System", - description="Detect objects in an image using a pre-trained model and visualize the results.", - - -) - -# Launch the Gradio interface -iface.launch(debug=True) diff --git a/spaces/GEM/DatasetCardForm/datacards/overview.py b/spaces/GEM/DatasetCardForm/datacards/overview.py deleted file mode 100644 index b048753fb9c25e3e8375ec6ec8e33d5cb9d646de..0000000000000000000000000000000000000000 --- a/spaces/GEM/DatasetCardForm/datacards/overview.py +++ /dev/null @@ -1,276 +0,0 @@ -import json -import streamlit as st - -from os.path import join as pjoin - -from .streamlit_utils import ( - make_multiselect, - make_selectbox, - make_text_area, - make_text_input, - make_radio, -) - -N_FIELDS_WHERE = 9 -N_FIELDS_LANGUAGES = 8 -N_FIELDS_CREDIT = 5 -N_FIELDS_STRUCTURE = 7 - -N_FIELDS = N_FIELDS_WHERE + N_FIELDS_LANGUAGES + N_FIELDS_CREDIT + N_FIELDS_STRUCTURE - - -languages_bcp47 = [ - x - for x in json.load(open(pjoin("resources", "bcp47.json"), encoding="utf-8"))[ - "subtags" - ] - if x["type"] == "language" -] - -license_list = json.load(open(pjoin("resources", "licenses.json"), encoding="utf-8")) - - -def overview_page(): - st.session_state.card_dict["overview"] = st.session_state.card_dict.get( - "overview", {} - ) - with st.expander("What is this dataset?", expanded=True): - key_pref = ["overview", "what"] - st.session_state.card_dict["overview"]["what"] = st.session_state.card_dict[ - "overview" - ].get("what", {}) - make_text_area( - label="Provide a summary of this dataset in 3-4 sentences.", - key_list=key_pref + ["dataset"], - help="[free text]", - ) - with st.expander("Where to find the data and its documentation", expanded=False): - key_pref = ["overview", "where"] - st.session_state.card_dict["overview"]["where"] = st.session_state.card_dict[ - "overview" - ].get("where", {}) - make_text_input( - label="What is the webpage for the dataset (if it exists)?", - key_list=key_pref + ["website"], - help="[URL]", - ) - make_text_input( - label="What is the link to where the original dataset is hosted?", - key_list=key_pref + ["data-url"], - help="[URL]", - ) - make_text_input( - label="What is the link to the paper describing the dataset (open access preferred)?", - key_list=key_pref + ["paper-url"], - help="[URL]", - ) - make_text_area( - label="Provide the BibTex-formatted reference for the dataset. Please use the correct published version (ACL anthology, etc.) instead of google scholar created Bibtex.", - key_list=key_pref + ["paper-bibtext"], - help="[free text]", - ) - make_radio( - label="Does the dataset have an active leaderboard?", - options=["no", "yes"], - key_list=key_pref + ["has-leaderboard"], - help="If no, enter N/A for the following two fields", - ) - if st.session_state.card_dict["overview"]["where"]["has-leaderboard"] == "yes": - make_text_input( - label="Provide a link to the leaderboard.", - key_list=key_pref + ["leaderboard-url"], - help="[URL] or N/A", - ) - make_text_area( - label="Briefly describe how the leaderboard evaluates models.", - key_list=key_pref + ["leaderboard-description"], - help="[free text; a paragraph] or N/A", - ) - else: - st.session_state.card_dict["overview"]["where"]["leaderboard-url"] = "N/A" - st.session_state.card_dict["overview"]["where"]["leaderboard-description"] = "N/A" - make_text_input( - label="If known, provide the name of at least one person the reader can contact for questions about the dataset.", - key_list=key_pref + ["contact-name"], - help="[free text]", - ) - make_text_input( - label="If known, provide the email of at least one person the reader can contact for questions about the dataset.", - key_list=key_pref + ["contact-email"], - help="[free text]", - ) - with st.expander("Languages and Intended Use", expanded=False): - key_pref = ["overview", "languages"] - st.session_state.card_dict["overview"][ - "languages" - ] = st.session_state.card_dict["overview"].get("languages", {}) - make_radio( - label="Is the dataset multilingual?", - options=["no", "yes"], - key_list=key_pref + ["is-multilingual"], - help="More than one language present in all of the text fields", - ) - make_multiselect( - label="What languages/dialects are covered in the dataset?", - key_list=key_pref + ["language-names"], - options=[", ".join(x["description"]) for x in languages_bcp47], - help="This is a comprehensive list of languages obtained from the BCP-47 standard list.", - ) - make_text_area( - label="What dialects are covered? Are there multiple dialects per language?", - key_list=key_pref + ["language-dialects"], - help="[free text, paragraphs] - Describe the dialect(s) as appropriate.", - ) - make_text_area( - label="Whose language is in the dataset?", - key_list=key_pref + ["language-speakers"], - help="[free text, paragraphs] - Provide locally appropriate demographic information about the language producers, if available. Use ranges where reasonable in order to protect individuals’ privacy.", - ) - make_text_area( - label="What is the intended use of the dataset?", - key_list=key_pref + ["intended-use"], - help="[free text, paragraphs] - Describe how the dataset creators describe its purpose and intended use.", - ) - make_selectbox( - label="What is the license of the dataset?", - key_list=key_pref + ["license"], - options=license_list, - help="select `other` if missing from list, `unkown` if not provided.", - ) - if "other" in st.session_state.card_dict["overview"]["languages"].get("license", []): - make_text_input( - label="What is the 'other' license of the dataset?", - key_list=key_pref + ["license-other"], - help="[free text]", - ) - else: - st.session_state.card_dict["overview"]["languages"]["license-other"] = "N/A" - - - make_selectbox( - label="What primary task does the dataset support?", - key_list=key_pref + ["task"], - options=[ - "", # default needs to be invalid value to make sure people actually fill in - "Content Transfer", - "Data-to-Text", - "Dialog Response Generation", - "Paraphrasing", - "Question Generation", - "Reasoning", - "Simplification", - "Style Transfer", - "Summarization", - "Text-to-Slide", - "Other" - ], - help="Select `other` if the task is not included in the list.", - ) - if "Other" in st.session_state.card_dict["overview"]["languages"].get("task", []): - make_text_input( - label="What is the primary task?", - key_list=key_pref + ["task-other"], - help="[free text]", - ) - else: - st.session_state.card_dict["overview"]["languages"]["task-other"] = "N/A" - - make_text_area( - label="Provide a short description of the communicative goal of a model trained for this task on this dataset.", - key_list=key_pref + ["communicative"], - help="[free text, a paragraph] (e.g., describe a restaurant from a structured representation of its attributes)", - ) - with st.expander("Credit", expanded=False): - key_pref = ["overview", "credit"] - st.session_state.card_dict["overview"][ - "credit" - ] = st.session_state.card_dict["overview"].get("credit", {}) - make_multiselect( - label="In what kind of organization did the dataset curation happen?", - options=["industry", "academic", "independent", "other"], - key_list=key_pref + ["organization-type"], - ) - make_text_input( - label="Name the organization(s).", - key_list=key_pref + ["organization-names"], - help="comma-separated", - ) - make_text_input( - label="Who created the original dataset? List the people involved in collecting the dataset and their affiliation(s).", - key_list=key_pref + ["creators"], - help="name (affiliation); comma-separated", - ) - make_text_input( - label="Who funded the data creation?", - key_list=key_pref + ["funding"], - help="[free text] enter N/A if unkown", - ) - make_text_input( - label="Who contributed to the data card and adding the dataset to GEM? List the people+affiliations involved in creating this data card and who helped integrate this dataset into GEM.", - key_list=key_pref + ["gem-added-by"], - help="name (affiliation); comma-separated", - ) - with st.expander("Structure", expanded=False): - key_pref = ["overview", "structure"] - st.session_state.card_dict["overview"]["structure"] = st.session_state.card_dict[ - "overview" - ].get("structure", {}) - data_fields_help = """ - [free text; paragraphs] - - Mention their data type, and whether and how they are used as part of the generation pipeline. - - Describe each fields' attributes, such as whether they are at the character level or word level, whether they are contiguous or not, etc. - - If the datasets contain example IDs, state whether they have an inherent meaning, such as a mapping to other datasets or pointing to relationships between data points. - """ - make_text_area( - label="List and describe the fields present in the dataset.", - key_list=key_pref + ["data-fields"], - help=data_fields_help, - ) - make_text_area( - label="How was the dataset structure determined?", - key_list=key_pref + ["structure-description"], - help="[free text; paragraph]", - ) - make_text_area( - label="How were the labels chosen?", - key_list=key_pref + ["structure-labels"], - help="[free text; paragraph]", - ) - make_text_area( - label="Provide a JSON formatted example of a typical instance in the dataset.", - key_list=key_pref + ["structure-example"], - help="[JSON]", - ) - make_text_area( - label="Describe and name the splits in the dataset if there are more than one.", - key_list=key_pref + ["structure-splits"], - help="[free text, paragraphs] - As appropriate, provide any descriptive statistics for the features, such as size, average lengths of input and output.", - ) - make_text_area( - label="Describe any criteria for splitting the data, if used. If there are differences between the splits (e.g., if the training annotations are machine-generated and the dev and test ones are created by humans, or if different numbers of annotators contributed to each example), describe them here.", - key_list=key_pref + ["structure-splits-criteria"], - help="[free text, paragraphs]", - ) - make_text_area( - label="What does an outlier of the dataset in terms of length/perplexity/embedding look like?", - key_list=key_pref + ["structure-outlier"], - help="[free text + json formatted text/file for an example]", - ) - - -def overview_summary(): - total_filled = sum( - [len(dct) for dct in st.session_state.card_dict.get("overview", {}).values()] - ) - with st.expander( - f"Dataset Overview Completion - {total_filled} of {N_FIELDS}", expanded=False - ): - completion_markdown = "" - completion_markdown += ( - f"- **Overall completion:**\n - {total_filled} of {N_FIELDS} fields\n" - ) - completion_markdown += f"- **Sub-section - Where to find:**\n - {len(st.session_state.card_dict.get('overview', {}).get('where', {}))} of {N_FIELDS_WHERE} fields\n" - completion_markdown += f"- **Sub-section - Languages and Intended Use:**\n - {len(st.session_state.card_dict.get('overview', {}).get('languages', {}))} of {N_FIELDS_LANGUAGES} fields\n" - completion_markdown += f"- **Sub-section - Credit:**\n - {len(st.session_state.card_dict.get('overview', {}).get('credit', {}))} of {N_FIELDS_CREDIT} fields\n" - completion_markdown += f"- **Sub-section - Structure:**\n - {len(st.session_state.card_dict.get('overview', {}).get('structure', {}))} of {N_FIELDS_STRUCTURE} fields\n" - st.markdown(completion_markdown) diff --git a/spaces/GT4SD/geodiff/README.md b/spaces/GT4SD/geodiff/README.md deleted file mode 100644 index 73d215d09dcaba0f509e0ff40e69cebb47b1835c..0000000000000000000000000000000000000000 --- a/spaces/GT4SD/geodiff/README.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -title: GeoDiff -emoji: 💡 -colorFrom: green -colorTo: blue -sdk: gradio -sdk_version: 3.46.0 -app_file: app.py -pinned: false -python_version: 3.8.13 -pypi_version: 20.2.4 -duplicated_from: jannisborn/gt4sd-diffusers ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/spaces/GaenKoki/voicevox/voicevox_engine/morphing.py b/spaces/GaenKoki/voicevox/voicevox_engine/morphing.py deleted file mode 100644 index d857aa11d8857772c4e119edfd57730932ced6fa..0000000000000000000000000000000000000000 --- a/spaces/GaenKoki/voicevox/voicevox_engine/morphing.py +++ /dev/null @@ -1,208 +0,0 @@ -from copy import deepcopy -from dataclasses import dataclass -from itertools import chain -from typing import Dict, List, Tuple - -import numpy as np -import pyworld as pw -from scipy.signal import resample - -from .metas.Metas import Speaker, SpeakerSupportPermittedSynthesisMorphing, StyleInfo -from .metas.MetasStore import construct_lookup -from .model import AudioQuery, MorphableTargetInfo, SpeakerNotFoundError -from .synthesis_engine import SynthesisEngine - - -# FIXME: ndarray type hint, https://github.com/JeremyCCHsu/Python-Wrapper-for-World-Vocoder/blob/2b64f86197573497c685c785c6e0e743f407b63e/pyworld/pyworld.pyx#L398 # noqa -@dataclass(frozen=True) -class MorphingParameter: - fs: int - frame_period: float - base_f0: np.ndarray - base_aperiodicity: np.ndarray - base_spectrogram: np.ndarray - target_spectrogram: np.ndarray - - -def create_morphing_parameter( - base_wave: np.ndarray, - target_wave: np.ndarray, - fs: int, -) -> MorphingParameter: - frame_period = 1.0 - base_f0, base_time_axis = pw.harvest(base_wave, fs, frame_period=frame_period) - base_spectrogram = pw.cheaptrick(base_wave, base_f0, base_time_axis, fs) - base_aperiodicity = pw.d4c(base_wave, base_f0, base_time_axis, fs) - - target_f0, morph_time_axis = pw.harvest(target_wave, fs, frame_period=frame_period) - target_spectrogram = pw.cheaptrick(target_wave, target_f0, morph_time_axis, fs) - target_spectrogram.resize(base_spectrogram.shape) - - return MorphingParameter( - fs=fs, - frame_period=frame_period, - base_f0=base_f0, - base_aperiodicity=base_aperiodicity, - base_spectrogram=base_spectrogram, - target_spectrogram=target_spectrogram, - ) - - -def get_morphable_targets( - speakers: List[Speaker], - base_speakers: List[int], -) -> List[Dict[int, MorphableTargetInfo]]: - """ - speakers: 全話者の情報 - base_speakers: モーフィング可能か判定したいベースの話者リスト(スタイルID) - """ - speaker_lookup = construct_lookup(speakers) - - morphable_targets_arr = [] - for base_speaker in base_speakers: - morphable_targets = dict() - for style in chain.from_iterable(speaker.styles for speaker in speakers): - morphable_targets[style.id] = MorphableTargetInfo( - is_morphable=is_synthesis_morphing_permitted( - speaker_lookup=speaker_lookup, - base_speaker=base_speaker, - target_speaker=style.id, - ) - ) - morphable_targets_arr.append(morphable_targets) - - return morphable_targets_arr - - -def is_synthesis_morphing_permitted( - speaker_lookup: Dict[int, Tuple[Speaker, StyleInfo]], - base_speaker: int, - target_speaker: int, -) -> bool: - """ - 指定されたspeakerがモーフィング可能かどうか返す - speakerが見つからない場合はSpeakerNotFoundErrorを送出する - """ - - base_speaker_data = speaker_lookup[base_speaker] - target_speaker_data = speaker_lookup[target_speaker] - - if base_speaker_data is None or target_speaker_data is None: - raise SpeakerNotFoundError( - base_speaker if base_speaker_data is None else target_speaker - ) - - base_speaker_info, _ = base_speaker_data - target_speaker_info, _ = target_speaker_data - - base_speaker_uuid = base_speaker_info.speaker_uuid - target_speaker_uuid = target_speaker_info.speaker_uuid - - base_speaker_morphing_info: SpeakerSupportPermittedSynthesisMorphing = ( - base_speaker_info.supported_features.permitted_synthesis_morphing - ) - - target_speaker_morphing_info: SpeakerSupportPermittedSynthesisMorphing = ( - target_speaker_info.supported_features.permitted_synthesis_morphing - ) - - # 禁止されている場合はFalse - if ( - base_speaker_morphing_info == SpeakerSupportPermittedSynthesisMorphing.NOTHING - or target_speaker_morphing_info - == SpeakerSupportPermittedSynthesisMorphing.NOTHING - ): - return False - # 同一話者のみの場合は同一話者判定 - if ( - base_speaker_morphing_info == SpeakerSupportPermittedSynthesisMorphing.SELF_ONLY - or target_speaker_morphing_info - == SpeakerSupportPermittedSynthesisMorphing.SELF_ONLY - ): - return base_speaker_uuid == target_speaker_uuid - # 念のため許可されているかチェック - return ( - base_speaker_morphing_info == SpeakerSupportPermittedSynthesisMorphing.ALL - and target_speaker_morphing_info == SpeakerSupportPermittedSynthesisMorphing.ALL - ) - - -def synthesis_morphing_parameter( - engine: SynthesisEngine, - query: AudioQuery, - base_speaker: int, - target_speaker: int, -) -> MorphingParameter: - query = deepcopy(query) - - # 不具合回避のためデフォルトのサンプリングレートでWORLDに掛けた後に指定のサンプリングレートに変換する - query.outputSamplingRate = engine.default_sampling_rate - - # WORLDに掛けるため合成はモノラルで行う - query.outputStereo = False - - base_wave = engine.synthesis(query=query, speaker_id=base_speaker).astype("float") - target_wave = engine.synthesis(query=query, speaker_id=target_speaker).astype( - "float" - ) - - return create_morphing_parameter( - base_wave=base_wave, - target_wave=target_wave, - fs=query.outputSamplingRate, - ) - - -def synthesis_morphing( - morph_param: MorphingParameter, - morph_rate: float, - output_fs: int, - output_stereo: bool = False, -) -> np.ndarray: - """ - 指定した割合で、パラメータをもとにモーフィングした音声を生成します。 - - Parameters - ---------- - morph_param : MorphingParameter - `synthesis_morphing_parameter`または`create_morphing_parameter`で作成したパラメータ - - morph_rate : float - モーフィングの割合 - 0.0でベースの話者、1.0でターゲットの話者に近づきます。 - - Returns - ------- - generated : np.ndarray - モーフィングした音声 - - Raises - ------- - ValueError - morph_rate ∈ [0, 1] - """ - - if morph_rate < 0.0 or morph_rate > 1.0: - raise ValueError("morph_rateは0.0から1.0の範囲で指定してください") - - morph_spectrogram = ( - morph_param.base_spectrogram * (1.0 - morph_rate) - + morph_param.target_spectrogram * morph_rate - ) - - y_h = pw.synthesize( - morph_param.base_f0, - morph_spectrogram, - morph_param.base_aperiodicity, - morph_param.fs, - morph_param.frame_period, - ) - - # TODO: synthesis_engine.py でのリサンプル処理と共通化する - if output_fs != morph_param.fs: - y_h = resample(y_h, output_fs * len(y_h) // morph_param.fs) - - if output_stereo: - y_h = np.array([y_h, y_h]).T - - return y_h diff --git a/spaces/Gradio-Blocks/protGPT2_gradioFold/alphafold/alphafold/model/tf/proteins_dataset.py b/spaces/Gradio-Blocks/protGPT2_gradioFold/alphafold/alphafold/model/tf/proteins_dataset.py deleted file mode 100644 index e0b1c038a41c6e276275a7904e748ea9e31e6083..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/protGPT2_gradioFold/alphafold/alphafold/model/tf/proteins_dataset.py +++ /dev/null @@ -1,166 +0,0 @@ -# Copyright 2021 DeepMind Technologies Limited -# -# 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. - -"""Datasets consisting of proteins.""" -from typing import Dict, Mapping, Optional, Sequence -from alphafold.model.tf import protein_features -import numpy as np -import tensorflow.compat.v1 as tf - -TensorDict = Dict[str, tf.Tensor] - - -def parse_tfexample( - raw_data: bytes, - features: protein_features.FeaturesMetadata, - key: Optional[str] = None) -> Dict[str, tf.train.Feature]: - """Read a single TF Example proto and return a subset of its features. - - Args: - raw_data: A serialized tf.Example proto. - features: A dictionary of features, mapping string feature names to a tuple - (dtype, shape). This dictionary should be a subset of - protein_features.FEATURES (or the dictionary itself for all features). - key: Optional string with the SSTable key of that tf.Example. This will be - added into features as a 'key' but only if requested in features. - - Returns: - A dictionary of features mapping feature names to features. Only the given - features are returned, all other ones are filtered out. - """ - feature_map = { - k: tf.io.FixedLenSequenceFeature(shape=(), dtype=v[0], allow_missing=True) - for k, v in features.items() - } - parsed_features = tf.io.parse_single_example(raw_data, feature_map) - reshaped_features = parse_reshape_logic(parsed_features, features, key=key) - - return reshaped_features - - -def _first(tensor: tf.Tensor) -> tf.Tensor: - """Returns the 1st element - the input can be a tensor or a scalar.""" - return tf.reshape(tensor, shape=(-1,))[0] - - -def parse_reshape_logic( - parsed_features: TensorDict, - features: protein_features.FeaturesMetadata, - key: Optional[str] = None) -> TensorDict: - """Transforms parsed serial features to the correct shape.""" - # Find out what is the number of sequences and the number of alignments. - num_residues = tf.cast(_first(parsed_features["seq_length"]), dtype=tf.int32) - - if "num_alignments" in parsed_features: - num_msa = tf.cast(_first(parsed_features["num_alignments"]), dtype=tf.int32) - else: - num_msa = 0 - - if "template_domain_names" in parsed_features: - num_templates = tf.cast( - tf.shape(parsed_features["template_domain_names"])[0], dtype=tf.int32) - else: - num_templates = 0 - - if key is not None and "key" in features: - parsed_features["key"] = [key] # Expand dims from () to (1,). - - # Reshape the tensors according to the sequence length and num alignments. - for k, v in parsed_features.items(): - new_shape = protein_features.shape( - feature_name=k, - num_residues=num_residues, - msa_length=num_msa, - num_templates=num_templates, - features=features) - new_shape_size = tf.constant(1, dtype=tf.int32) - for dim in new_shape: - new_shape_size *= tf.cast(dim, tf.int32) - - assert_equal = tf.assert_equal( - tf.size(v), new_shape_size, - name="assert_%s_shape_correct" % k, - message="The size of feature %s (%s) could not be reshaped " - "into %s" % (k, tf.size(v), new_shape)) - if "template" not in k: - # Make sure the feature we are reshaping is not empty. - assert_non_empty = tf.assert_greater( - tf.size(v), 0, name="assert_%s_non_empty" % k, - message="The feature %s is not set in the tf.Example. Either do not " - "request the feature or use a tf.Example that has the " - "feature set." % k) - with tf.control_dependencies([assert_non_empty, assert_equal]): - parsed_features[k] = tf.reshape(v, new_shape, name="reshape_%s" % k) - else: - with tf.control_dependencies([assert_equal]): - parsed_features[k] = tf.reshape(v, new_shape, name="reshape_%s" % k) - - return parsed_features - - -def _make_features_metadata( - feature_names: Sequence[str]) -> protein_features.FeaturesMetadata: - """Makes a feature name to type and shape mapping from a list of names.""" - # Make sure these features are always read. - required_features = ["aatype", "sequence", "seq_length"] - feature_names = list(set(feature_names) | set(required_features)) - - features_metadata = {name: protein_features.FEATURES[name] - for name in feature_names} - return features_metadata - - -def create_tensor_dict( - raw_data: bytes, - features: Sequence[str], - key: Optional[str] = None, - ) -> TensorDict: - """Creates a dictionary of tensor features. - - Args: - raw_data: A serialized tf.Example proto. - features: A list of strings of feature names to be returned in the dataset. - key: Optional string with the SSTable key of that tf.Example. This will be - added into features as a 'key' but only if requested in features. - - Returns: - A dictionary of features mapping feature names to features. Only the given - features are returned, all other ones are filtered out. - """ - features_metadata = _make_features_metadata(features) - return parse_tfexample(raw_data, features_metadata, key) - - -def np_to_tensor_dict( - np_example: Mapping[str, np.ndarray], - features: Sequence[str], - ) -> TensorDict: - """Creates dict of tensors from a dict of NumPy arrays. - - Args: - np_example: A dict of NumPy feature arrays. - features: A list of strings of feature names to be returned in the dataset. - - Returns: - A dictionary of features mapping feature names to features. Only the given - features are returned, all other ones are filtered out. - """ - features_metadata = _make_features_metadata(features) - tensor_dict = {k: tf.constant(v) for k, v in np_example.items() - if k in features_metadata} - - # Ensures shapes are as expected. Needed for setting size of empty features - # e.g. when no template hits were found. - tensor_dict = parse_reshape_logic(tensor_dict, features_metadata) - return tensor_dict diff --git a/spaces/Gradio-Blocks/uniformer_image_detection/configs/ms_rcnn/ms_rcnn_x101_64x4d_fpn_1x_coco.py b/spaces/Gradio-Blocks/uniformer_image_detection/configs/ms_rcnn/ms_rcnn_x101_64x4d_fpn_1x_coco.py deleted file mode 100644 index 61a0cefe4e20b55cd3caaab7dde325a111275726..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_detection/configs/ms_rcnn/ms_rcnn_x101_64x4d_fpn_1x_coco.py +++ /dev/null @@ -1,13 +0,0 @@ -_base_ = './ms_rcnn_r50_fpn_1x_coco.py' -model = dict( - pretrained='open-mmlab://resnext101_64x4d', - backbone=dict( - type='ResNeXt', - depth=101, - groups=64, - base_width=4, - num_stages=4, - out_indices=(0, 1, 2, 3), - frozen_stages=1, - norm_cfg=dict(type='BN', requires_grad=True), - style='pytorch')) diff --git a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/dnlnet/dnl_r101-d8_769x769_40k_cityscapes.py b/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/dnlnet/dnl_r101-d8_769x769_40k_cityscapes.py deleted file mode 100644 index 575e9d01343a4563e0d3ba89b361ea8e358d2dee..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/dnlnet/dnl_r101-d8_769x769_40k_cityscapes.py +++ /dev/null @@ -1,2 +0,0 @@ -_base_ = './dnl_r50-d8_769x769_40k_cityscapes.py' -model = dict(pretrained='open-mmlab://resnet101_v1c', backbone=dict(depth=101)) diff --git a/spaces/GuujiYae/Grand-Narukami-Shrine/Dockerfile b/spaces/GuujiYae/Grand-Narukami-Shrine/Dockerfile deleted file mode 100644 index 5a74751c01e45d69dcaedffd79895255d009f95c..0000000000000000000000000000000000000000 --- a/spaces/GuujiYae/Grand-Narukami-Shrine/Dockerfile +++ /dev/null @@ -1,12 +0,0 @@ -FROM node:18-bullseye-slim -RUN apt-get update && \ - apt-get install -y git -RUN git clone https://gitgud.io/yae-miko/oai-reverse-proxy.git /app -WORKDIR /app -RUN npm install -COPY Dockerfile greeting.md* .env* ./ -COPY public/ ./public -RUN npm run build -EXPOSE 7860 -ENV NODE_ENV=production -CMD [ "npm", "start" ] \ No newline at end of file diff --git a/spaces/HCMUT-GraduateThesis-HNTThinh/rgbdsod-multimae-demo/s_multimae/utils.py b/spaces/HCMUT-GraduateThesis-HNTThinh/rgbdsod-multimae-demo/s_multimae/utils.py deleted file mode 100644 index 56fb4b3ba0db3d94896f6f4a2ea05af630ade552..0000000000000000000000000000000000000000 --- a/spaces/HCMUT-GraduateThesis-HNTThinh/rgbdsod-multimae-demo/s_multimae/utils.py +++ /dev/null @@ -1,159 +0,0 @@ -import random -from typing import List, Tuple -from torch import nn, Tensor -import os, shutil -import torch -import matplotlib.pyplot as plt -import numpy as np -import gc, cv2 - -from .visualizer import post_processing_depth - -''' -This module should not depend on other s_multimae modules. -''' - -num_format = "{:,}".format - -def clean_cache() -> None: - torch.cuda.empty_cache() - gc.collect() - -def count_parameters(model: nn.Module) -> str: - '''Count the number of learnable parameters of a model''' - return num_format(sum(p.numel() for p in model.parameters() if p.requires_grad)) - -def random_choice(p: float) -> bool: - '''Return True if random float <= p ''' - return random.random() <= p - -def list_files( - root_dir_path: str, max_files: int = None -) -> Tuple[List[str], List[str], List[str]]: - '''List all files in a directory that has extensions - Folder structure: - root_dir_path - |---GT - | |---image1.jpg - | |---image2.jpg - |---RGB - | |---image1.png - | |---image2.png - |---depths - | |---image1.png - | |---image2.png - Returns: rgbs, depths, gts - ''' - depths_dir = os.path.join(root_dir_path, 'depths') - gts_dir = os.path.join(root_dir_path, 'GT') - rgbs_dir = os.path.join(root_dir_path, 'RGB') - - depth_files = list(sorted(os.listdir(depths_dir))) - gt_files = list(sorted(os.listdir(gts_dir))) - rgb_files = list(sorted(os.listdir(rgbs_dir))) - - depth_files_names = [f.split('.')[0] for f in depth_files] - gt_files_names = [f.split('.')[0] for f in gt_files] - rgb_files_names = [f.split('.')[0] for f in rgb_files] - - # Ensure integrity - assert depth_files_names == gt_files_names == rgb_files_names, \ - f"Dataset {root_dir_path} not integrity" - - depths: List[str] = [] - gts: List[str] = [] - rgbs: List[str] = [] - - if max_files is not None: - depth_files = depth_files[:max_files] - gt_files = gt_files[:max_files] - rgb_files = rgb_files[:max_files] - - for depth_file, gt_file, rgb_file in zip(depth_files, gt_files, rgb_files): - depths.append(os.path.join(depths_dir, depth_file)) - gts.append(os.path.join(gts_dir, gt_file)) - rgbs.append(os.path.join(rgbs_dir, rgb_file)) - - return rgbs, depths, gts - -def scale_saliency_maps(inputs: Tensor) -> Tensor: - '''Input: Tensor, shape of (B, C, H, W)''' - min_v = torch.min(torch.flatten(inputs, 1), dim=1)[0].unsqueeze(1).unsqueeze(1).unsqueeze(1) - max_v = torch.max(torch.flatten(inputs, 1), dim=1)[0].unsqueeze(1).unsqueeze(1).unsqueeze(1) - return (inputs - min_v) / (max_v - min_v + 1e-8) - -def get_epoch_from_ckpt_path(ckpt_path: str) -> int: - '''Example ckpt_path - os.path.join(experiment_dir_path, 'exp_v2.3', 'checkpoint_100.pt') - ''' - return int(ckpt_path.split('_')[-1].split('.')[0]) - -def clean_dir(dir_path: str) -> None: - '''Remove a directory if existed and create an empty directory''' - if os.path.isdir(dir_path): - shutil.rmtree(dir_path) - os.makedirs(dir_path, exist_ok=True) - -def get_sota_type(experiment_name: str) -> int: - ''' 0 for SOTAs, 4 for experiment version 4, e.g. ...''' - if "exp_v" not in experiment_name: - return 0 - - half_right = experiment_name.split("exp_v")[1] - return int(half_right.split('.')[0]) - -def get_production_ckpt_path(experiment_name: str, epoch: int) -> str: - return os.path.join('pretrained_models', 'multimae', experiment_name, f'checkpoint_{epoch}.pt') - -def convert_batch_tensors_to_numpy_images(images: Tensor) -> np.ndarray: - ''' images of shape (batch_size, channels, width, height) ''' - images = torch.permute(images, (0, 2, 3, 1)) - images = images.numpy() - if images.shape[3] == 1: - return np.squeeze(images, axis=3) - else: - return images - -def join_horizontally(lst: List[np.ndarray]) -> np.ndarray: - return np.concatenate(lst, axis=1) - -def join_vertically(lst: List[np.ndarray]) -> np.ndarray: - return np.concatenate(lst, axis=0) - -def plot_batch_of_pairs( - images: Tensor, - depths: Tensor, - gts: Tensor, - save_file_path: str, -) -> None: - images = convert_batch_tensors_to_numpy_images(images) - depths = convert_batch_tensors_to_numpy_images(depths) - gts = convert_batch_tensors_to_numpy_images(gts) - batch_size = images.shape[0] - samples: List[np.ndarray] = [] - - # fig, axes = plt.subplots(batch_size, 3, figsize=(3*batch_size, 20)) # (number of images, 3) - for i in range(batch_size): - samples.append(join_horizontally([ - ((images[i]+1.0)/2 * 255).astype(np.uint8), - post_processing_depth(depths[i]), - post_processing_depth(gts[i]), - ])) - # axes[i, 0].imshow(images[i]) - # axes[i, 1].imshow(depths[i]) - # axes[i, 2].imshow(gts[i]) - # plt.show() - - final = join_vertically(samples) - cv2.imwrite(save_file_path, cv2.cvtColor(final, cv2.COLOR_RGB2BGR)) - print(f'Saved to file {save_file_path}') - -def plot_pairs(image: np.ndarray, depth: np.ndarray, gt: np.ndarray) -> None: - batch_size = 1 - fig, axes = plt.subplots(batch_size, 3, figsize=(3*batch_size, 20)) # (number of images, 3) - for i in range(batch_size): - axes[i, 0].imshow(image) - axes[i, 1].imshow(depth) - axes[i, 2].imshow(gt) - plt.show() - diff --git a/spaces/Harveenchadha/Vakyansh-Malayalam-TTS/ttsv/utils/inference/api.py b/spaces/Harveenchadha/Vakyansh-Malayalam-TTS/ttsv/utils/inference/api.py deleted file mode 100644 index d6bcabd194a4531801941d5e1d248dc134ce255f..0000000000000000000000000000000000000000 --- a/spaces/Harveenchadha/Vakyansh-Malayalam-TTS/ttsv/utils/inference/api.py +++ /dev/null @@ -1,66 +0,0 @@ -from starlette.responses import StreamingResponse -from tts import MelToWav, TextToMel -from advanced_tts import load_all_models, run_tts_paragraph -from typing import Optional -from pydantic import BaseModel -from fastapi import FastAPI, HTTPException -import uvicorn -import base64 -import argparse -import json -import time -from argparse import Namespace - -app = FastAPI() - - -class TextJson(BaseModel): - text: str - lang: Optional[str] = "hi" - noise_scale: Optional[float]=0.667 - length_scale: Optional[float]=1.0 - transliteration: Optional[int]=1 - number_conversion: Optional[int]=1 - split_sentences: Optional[int]=1 - - - - -@app.post("/TTS/") -async def tts(input: TextJson): - text = input.text - lang = input.lang - - args = Namespace(**input.dict()) - - args.wav = '../../results/api/'+str(int(time.time())) + '.wav' - - if text: - sr, audio = run_tts_paragraph(args) - else: - raise HTTPException(status_code=400, detail={"error": "No text"}) - - ## to return outpur as a file - audio = open(args.wav, mode='rb') - return StreamingResponse(audio, media_type="audio/wav") - - # with open(args.wav, "rb") as audio_file: - # encoded_bytes = base64.b64encode(audio_file.read()) - # encoded_string = encoded_bytes.decode() - # return {"encoding": "base64", "data": encoded_string, "sr": sr} - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("-a", "--acoustic", required=True, type=str) - parser.add_argument("-v", "--vocoder", required=True, type=str) - parser.add_argument("-d", "--device", type=str, default="cpu") - parser.add_argument("-L", "--lang", type=str, required=True) - - args = parser.parse_args() - - load_all_models(args) - - uvicorn.run( - "api:app", host="0.0.0.0", port=6006, log_level="debug" - ) diff --git a/spaces/Hazem/roop/roop/face_analyser.py b/spaces/Hazem/roop/roop/face_analyser.py deleted file mode 100644 index 9c0afe458763edb22dc2332f527dfdba48575b1d..0000000000000000000000000000000000000000 --- a/spaces/Hazem/roop/roop/face_analyser.py +++ /dev/null @@ -1,34 +0,0 @@ -import threading -from typing import Any -import insightface - -import roop.globals -from roop.typing import Frame - -FACE_ANALYSER = None -THREAD_LOCK = threading.Lock() - - -def get_face_analyser() -> Any: - global FACE_ANALYSER - - with THREAD_LOCK: - if FACE_ANALYSER is None: - FACE_ANALYSER = insightface.app.FaceAnalysis(name='buffalo_l', providers=roop.globals.execution_providers) - FACE_ANALYSER.prepare(ctx_id=0, det_size=(640, 640)) - return FACE_ANALYSER - - -def get_one_face(frame: Frame) -> Any: - face = get_face_analyser().get(frame) - try: - return min(face, key=lambda x: x.bbox[0]) - except ValueError: - return None - - -def get_many_faces(frame: Frame) -> Any: - try: - return get_face_analyser().get(frame) - except IndexError: - return None diff --git a/spaces/Hila/RobustViT/imagenet_finetune_rrr.py b/spaces/Hila/RobustViT/imagenet_finetune_rrr.py deleted file mode 100644 index e6f8bc0f6f7f8f0c8966270f6d306121d38ac534..0000000000000000000000000000000000000000 --- a/spaces/Hila/RobustViT/imagenet_finetune_rrr.py +++ /dev/null @@ -1,570 +0,0 @@ -import argparse -import os -import random -import shutil -import time -import warnings - -import torch -import torch.nn as nn -import torch.nn.parallel -import torch.backends.cudnn as cudnn -import torch.distributed as dist -import torch.optim -import torch.multiprocessing as mp -import torch.utils.data -import torch.utils.data.distributed -import torchvision.transforms as transforms -import torchvision.datasets as datasets -import torchvision.models as models -import torch.nn.functional as F -from segmentation_dataset import SegmentationDataset, VAL_PARTITION, TRAIN_PARTITION -import numpy as np - -# Uncomment the expected model below - -# ViT -from ViT.ViT import vit_base_patch16_224 as vit -# from ViT.ViT import vit_large_patch16_224 as vit - -# ViT-AugReg -# from ViT.ViT_new import vit_small_patch16_224 as vit -# from ViT.ViT_new import vit_base_patch16_224 as vit -# from ViT.ViT_new import vit_large_patch16_224 as vit - -# DeiT -# from ViT.ViT import deit_base_patch16_224 as vit -# from ViT.ViT import deit_small_patch16_224 as vit - -from ViT.explainer import generate_relevance, get_image_with_relevance -import torchvision -import cv2 -from torch.utils.tensorboard import SummaryWriter -import json - -model_names = sorted(name for name in models.__dict__ - if name.islower() and not name.startswith("__") - and callable(models.__dict__[name])) -model_names.append("vit") - -parser = argparse.ArgumentParser(description='PyTorch ImageNet Training') -parser.add_argument('--data', metavar='DATA', - help='path to dataset') -parser.add_argument('--seg_data', metavar='SEG_DATA', - help='path to segmentation dataset') -parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet18', - choices=model_names, - help='model architecture: ' + - ' | '.join(model_names) + - ' (default: resnet18)') -parser.add_argument('-j', '--workers', default=4, type=int, metavar='N', - help='number of data loading workers (default: 4)') -parser.add_argument('--epochs', default=50, type=int, metavar='N', - help='number of total epochs to run') -parser.add_argument('--start-epoch', default=0, type=int, metavar='N', - help='manual epoch number (useful on restarts)') -parser.add_argument('-b', '--batch-size', default=8, type=int, - metavar='N', - help='mini-batch size (default: 256), this is the total ' - 'batch size of all GPUs on the current node when ' - 'using Data Parallel or Distributed Data Parallel') -parser.add_argument('--lr', '--learning-rate', default=3e-6, type=float, - metavar='LR', help='initial learning rate', dest='lr') -parser.add_argument('--momentum', default=0.9, type=float, metavar='M', - help='momentum') -parser.add_argument('--wd', '--weight-decay', default=1e-4, type=float, - metavar='W', help='weight decay (default: 1e-4)', - dest='weight_decay') -parser.add_argument('-p', '--print-freq', default=10, type=int, - metavar='N', help='print frequency (default: 10)') -parser.add_argument('--resume', default='', type=str, metavar='PATH', - help='path to latest checkpoint (default: none)') -parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true', - help='evaluate model on validation set') -parser.add_argument('--pretrained', dest='pretrained', action='store_true', - help='use pre-trained model') -parser.add_argument('--world-size', default=-1, type=int, - help='number of nodes for distributed training') -parser.add_argument('--rank', default=-1, type=int, - help='node rank for distributed training') -parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str, - help='url used to set up distributed training') -parser.add_argument('--dist-backend', default='nccl', type=str, - help='distributed backend') -parser.add_argument('--seed', default=None, type=int, - help='seed for initializing training. ') -parser.add_argument('--gpu', default=None, type=int, - help='GPU id to use.') -parser.add_argument('--save_interval', default=20, type=int, - help='interval to save segmentation results.') -parser.add_argument('--num_samples', default=3, type=int, - help='number of samples per class for training') -parser.add_argument('--multiprocessing-distributed', action='store_true', - help='Use multi-processing distributed training to launch ' - 'N processes per node, which has N GPUs. This is the ' - 'fastest way to use PyTorch for either single node or ' - 'multi node data parallel training') -parser.add_argument('--lambda_seg', default=0.8, type=float, - help='influence of segmentation loss.') -parser.add_argument('--lambda_acc', default=0.2, type=float, - help='influence of accuracy loss.') -parser.add_argument('--experiment_folder', default=None, type=str, - help='path to folder to use for experiment.') -parser.add_argument('--num_classes', default=500, type=int, - help='coefficient of loss for segmentation foreground.') -parser.add_argument('--temperature', default=1, type=float, - help='temperature for softmax (mostly for DeiT).') - -best_loss = float('inf') - -def main(): - args = parser.parse_args() - - if args.experiment_folder is None: - args.experiment_folder = f'experiment/' \ - f'lr_{args.lr}_seg_{args.lambda_seg}_acc_{args.lambda_acc}' - if args.temperature != 1: - args.experiment_folder = args.experiment_folder + f'_tempera_{args.temperature}' - if args.batch_size != 8: - args.experiment_folder = args.experiment_folder + f'_bs_{args.batch_size}' - if args.num_classes != 500: - args.experiment_folder = args.experiment_folder + f'_num_classes_{args.num_classes}' - if args.num_samples != 3: - args.experiment_folder = args.experiment_folder + f'_num_samples_{args.num_samples}' - if args.epochs != 150: - args.experiment_folder = args.experiment_folder + f'_num_epochs_{args.epochs}' - - if os.path.exists(args.experiment_folder): - raise Exception(f"Experiment path {args.experiment_folder} already exists!") - os.mkdir(args.experiment_folder) - os.mkdir(f'{args.experiment_folder}/train_samples') - os.mkdir(f'{args.experiment_folder}/val_samples') - - with open(f'{args.experiment_folder}/commandline_args.txt', 'w') as f: - json.dump(args.__dict__, f, indent=2) - - if args.seed is not None: - random.seed(args.seed) - torch.manual_seed(args.seed) - cudnn.deterministic = True - warnings.warn('You have chosen to seed training. ' - 'This will turn on the CUDNN deterministic setting, ' - 'which can slow down your training considerably! ' - 'You may see unexpected behavior when restarting ' - 'from checkpoints.') - - if args.gpu is not None: - warnings.warn('You have chosen a specific GPU. This will completely ' - 'disable data parallelism.') - - if args.dist_url == "env://" and args.world_size == -1: - args.world_size = int(os.environ["WORLD_SIZE"]) - - args.distributed = args.world_size > 1 or args.multiprocessing_distributed - - ngpus_per_node = torch.cuda.device_count() - if args.multiprocessing_distributed: - # Since we have ngpus_per_node processes per node, the total world_size - # needs to be adjusted accordingly - args.world_size = ngpus_per_node * args.world_size - # Use torch.multiprocessing.spawn to launch distributed processes: the - # main_worker process function - mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args)) - else: - # Simply call main_worker function - main_worker(args.gpu, ngpus_per_node, args) - - -def main_worker(gpu, ngpus_per_node, args): - global best_loss - args.gpu = gpu - - if args.gpu is not None: - print("Use GPU: {} for training".format(args.gpu)) - - if args.distributed: - if args.dist_url == "env://" and args.rank == -1: - args.rank = int(os.environ["RANK"]) - if args.multiprocessing_distributed: - # For multiprocessing distributed training, rank needs to be the - # global rank among all the processes - args.rank = args.rank * ngpus_per_node + gpu - dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url, - world_size=args.world_size, rank=args.rank) - # create model - print("=> creating model") - model = vit(pretrained=True).cuda() - model.train() - print("done") - - if not torch.cuda.is_available(): - print('using CPU, this will be slow') - elif args.distributed: - # For multiprocessing distributed, DistributedDataParallel constructor - # should always set the single device scope, otherwise, - # DistributedDataParallel will use all available devices. - if args.gpu is not None: - torch.cuda.set_device(args.gpu) - model.cuda(args.gpu) - # When using a single GPU per process and per - # DistributedDataParallel, we need to divide the batch size - # ourselves based on the total number of GPUs we have - args.batch_size = int(args.batch_size / ngpus_per_node) - args.workers = int((args.workers + ngpus_per_node - 1) / ngpus_per_node) - model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) - else: - model.cuda() - # DistributedDataParallel will divide and allocate batch_size to all - # available GPUs if device_ids are not set - model = torch.nn.parallel.DistributedDataParallel(model) - elif args.gpu is not None: - torch.cuda.set_device(args.gpu) - model = model.cuda(args.gpu) - else: - # DataParallel will divide and allocate batch_size to all available GPUs - print("start") - model = torch.nn.DataParallel(model).cuda() - - # define loss function (criterion) and optimizer - criterion = nn.CrossEntropyLoss().cuda(args.gpu) - optimizer = torch.optim.AdamW(model.parameters(), args.lr, weight_decay=args.weight_decay) - - # optionally resume from a checkpoint - if args.resume: - if os.path.isfile(args.resume): - print("=> loading checkpoint '{}'".format(args.resume)) - if args.gpu is None: - checkpoint = torch.load(args.resume) - else: - # Map model to be loaded to specified single gpu. - loc = 'cuda:{}'.format(args.gpu) - checkpoint = torch.load(args.resume, map_location=loc) - args.start_epoch = checkpoint['epoch'] - best_loss = checkpoint['best_loss'] - if args.gpu is not None: - # best_loss may be from a checkpoint from a different GPU - best_loss = best_loss.to(args.gpu) - model.load_state_dict(checkpoint['state_dict']) - optimizer.load_state_dict(checkpoint['optimizer']) - print("=> loaded checkpoint '{}' (epoch {})" - .format(args.resume, checkpoint['epoch'])) - else: - print("=> no checkpoint found at '{}'".format(args.resume)) - - cudnn.benchmark = True - - train_dataset = SegmentationDataset(args.seg_data, args.data, partition=TRAIN_PARTITION, train_classes=args.num_classes, - num_samples=args.num_samples) - - if args.distributed: - train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset) - else: - train_sampler = None - - train_loader = torch.utils.data.DataLoader( - train_dataset, batch_size=args.batch_size, shuffle=False, - num_workers=args.workers, pin_memory=True, sampler=train_sampler) - - val_dataset = SegmentationDataset(args.seg_data, args.data, partition=VAL_PARTITION, train_classes=args.num_classes, - num_samples=1) - - val_loader = torch.utils.data.DataLoader( - val_dataset, batch_size=5, shuffle=False, - num_workers=args.workers, pin_memory=True) - - if args.evaluate: - validate(val_loader, model, criterion, 0, args) - return - - for epoch in range(args.start_epoch, args.epochs): - if args.distributed: - train_sampler.set_epoch(epoch) - adjust_learning_rate(optimizer, epoch, args) - - log_dir = os.path.join(args.experiment_folder, 'logs') - logger = SummaryWriter(log_dir=log_dir) - args.logger = logger - - # train for one epoch - train(train_loader, model, criterion, optimizer, epoch, args) - - # evaluate on validation set - loss1 = validate(val_loader, model, criterion, epoch, args) - - # remember best acc@1 and save checkpoint - is_best = loss1 < best_loss - best_loss = min(loss1, best_loss) - - if not args.multiprocessing_distributed or (args.multiprocessing_distributed - and args.rank % ngpus_per_node == 0): - save_checkpoint({ - 'epoch': epoch + 1, - 'state_dict': model.state_dict(), - 'best_loss': best_loss, - 'optimizer' : optimizer.state_dict(), - }, is_best, folder=args.experiment_folder) - -def train(train_loader, model, criterion, optimizer, epoch, args): - losses = AverageMeter('Loss', ':.4e') - top1 = AverageMeter('Acc@1', ':6.2f') - top5 = AverageMeter('Acc@5', ':6.2f') - orig_top1 = AverageMeter('Acc@1_orig', ':6.2f') - orig_top5 = AverageMeter('Acc@5_orig', ':6.2f') - progress = ProgressMeter( - len(train_loader), - [losses, top1, top5, orig_top1, orig_top5], - prefix="Epoch: [{}]".format(epoch)) - - orig_model = vit(pretrained=True).cuda() - orig_model.eval() - - # switch to train mode - model.train() - - for i, (seg_map, image_ten, class_name) in enumerate(train_loader): - if torch.cuda.is_available(): - image_ten = image_ten.cuda(args.gpu, non_blocking=True) - seg_map = seg_map.cuda(args.gpu, non_blocking=True) - class_name = class_name.cuda(args.gpu, non_blocking=True) - - - image_ten.requires_grad = True - output = model(image_ten) - - # segmentation loss - EPS = 10e-12 - y_pred = torch.sum(torch.log(F.softmax(output, dim=1) + EPS)) - relevance = torch.autograd.grad(y_pred, image_ten, retain_graph=True)[0] - reverse_seg_map = seg_map.clone() - reverse_seg_map[reverse_seg_map == 1] = -1 - reverse_seg_map[reverse_seg_map == 0] = 1 - reverse_seg_map[reverse_seg_map == -1] = 0 - rrr_loss = (relevance * reverse_seg_map)**2 - segmentation_loss = rrr_loss.sum() - - # classification loss - with torch.no_grad(): - output_orig = orig_model(image_ten) - if args.temperature != 1: - output = output / args.temperature - classification_loss = criterion(output, class_name.flatten()) - - loss = args.lambda_seg * segmentation_loss + args.lambda_acc * classification_loss - - # debugging output - if i % args.save_interval == 0: - orig_relevance = generate_relevance(orig_model, image_ten, index=class_name) - for j in range(image_ten.shape[0]): - image = get_image_with_relevance(image_ten[j], torch.ones_like(image_ten[j])) - new_vis = get_image_with_relevance(image_ten[j]*relevance[j], torch.ones_like(image_ten[j])) - old_vis = get_image_with_relevance(image_ten[j], orig_relevance[j]) - gt = get_image_with_relevance(image_ten[j], seg_map[j]) - h_img = cv2.hconcat([image, gt, old_vis, new_vis]) - cv2.imwrite(f'{args.experiment_folder}/train_samples/res_{i}_{j}.jpg', h_img) - - # measure accuracy and record loss - acc1, acc5 = accuracy(output, class_name, topk=(1, 5)) - losses.update(loss.item(), image_ten.size(0)) - top1.update(acc1[0], image_ten.size(0)) - top5.update(acc5[0], image_ten.size(0)) - - # metrics for original vit - acc1_orig, acc5_orig = accuracy(output_orig, class_name, topk=(1, 5)) - orig_top1.update(acc1_orig[0], image_ten.size(0)) - orig_top5.update(acc5_orig[0], image_ten.size(0)) - - # compute gradient and do SGD step - optimizer.zero_grad() - loss.backward() - optimizer.step() - - if i % args.print_freq == 0: - progress.display(i) - args.logger.add_scalar('{}/{}'.format('train', 'segmentation_loss'), segmentation_loss, - epoch*len(train_loader)+i) - args.logger.add_scalar('{}/{}'.format('train', 'classification_loss'), classification_loss, - epoch * len(train_loader) + i) - args.logger.add_scalar('{}/{}'.format('train', 'orig_top1'), acc1_orig, - epoch * len(train_loader) + i) - args.logger.add_scalar('{}/{}'.format('train', 'top1'), acc1, - epoch * len(train_loader) + i) - args.logger.add_scalar('{}/{}'.format('train', 'orig_top5'), acc5_orig, - epoch * len(train_loader) + i) - args.logger.add_scalar('{}/{}'.format('train', 'top5'), acc5, - epoch * len(train_loader) + i) - args.logger.add_scalar('{}/{}'.format('train', 'tot_loss'), loss, - epoch * len(train_loader) + i) - - -def validate(val_loader, model, criterion, epoch, args): - mse_criterion = torch.nn.MSELoss(reduction='mean') - - losses = AverageMeter('Loss', ':.4e') - top1 = AverageMeter('Acc@1', ':6.2f') - top5 = AverageMeter('Acc@5', ':6.2f') - orig_top1 = AverageMeter('Acc@1_orig', ':6.2f') - orig_top5 = AverageMeter('Acc@5_orig', ':6.2f') - progress = ProgressMeter( - len(val_loader), - [losses, top1, top5, orig_top1, orig_top5], - prefix="Epoch: [{}]".format(val_loader)) - - # switch to evaluate mode - model.eval() - - orig_model = vit(pretrained=True).cuda() - orig_model.eval() - - with torch.no_grad(): - for i, (seg_map, image_ten, class_name) in enumerate(val_loader): - if args.gpu is not None: - image_ten = image_ten.cuda(args.gpu, non_blocking=True) - if torch.cuda.is_available(): - seg_map = seg_map.cuda(args.gpu, non_blocking=True) - class_name = class_name.cuda(args.gpu, non_blocking=True) - - with torch.enable_grad(): - image_ten.requires_grad = True - output = model(image_ten) - - # segmentation loss - EPS = 10e-12 - y_pred = torch.sum(torch.log(F.softmax(output, dim=1) + EPS)) - relevance = torch.autograd.grad(y_pred, image_ten, retain_graph=True)[0] - - reverse_seg_map = seg_map.clone() - reverse_seg_map[reverse_seg_map == 1] = -1 - reverse_seg_map[reverse_seg_map == 0] = 1 - reverse_seg_map[reverse_seg_map == -1] = 0 - rrr_loss = (relevance * reverse_seg_map) ** 2 - segmentation_loss = rrr_loss.sum() - - # classification loss - output = model(image_ten) - with torch.no_grad(): - output_orig = orig_model(image_ten) - if args.temperature != 1: - output = output / args.temperature - classification_loss = criterion(output, class_name.flatten()) - - loss = args.lambda_seg * segmentation_loss + args.lambda_acc * classification_loss - - # save results - if i % args.save_interval == 0: - with torch.enable_grad(): - orig_relevance = generate_relevance(orig_model, image_ten, index=class_name) - for j in range(image_ten.shape[0]): - image = get_image_with_relevance(image_ten[j], torch.ones_like(image_ten[j])) - new_vis = get_image_with_relevance(image_ten[j]*relevance[j], torch.ones_like(image_ten[j])) - old_vis = get_image_with_relevance(image_ten[j], orig_relevance[j]) - gt = get_image_with_relevance(image_ten[j], seg_map[j]) - h_img = cv2.hconcat([image, gt, old_vis, new_vis]) - cv2.imwrite(f'{args.experiment_folder}/val_samples/res_{i}_{j}.jpg', h_img) - - # measure accuracy and record loss - acc1, acc5 = accuracy(output, class_name, topk=(1, 5)) - losses.update(loss.item(), image_ten.size(0)) - top1.update(acc1[0], image_ten.size(0)) - top5.update(acc5[0], image_ten.size(0)) - - # metrics for original vit - acc1_orig, acc5_orig = accuracy(output_orig, class_name, topk=(1, 5)) - orig_top1.update(acc1_orig[0], image_ten.size(0)) - orig_top5.update(acc5_orig[0], image_ten.size(0)) - - if i % args.print_freq == 0: - progress.display(i) - args.logger.add_scalar('{}/{}'.format('val', 'segmentation_loss'), segmentation_loss, - epoch * len(val_loader) + i) - args.logger.add_scalar('{}/{}'.format('val', 'classification_loss'), classification_loss, - epoch * len(val_loader) + i) - args.logger.add_scalar('{}/{}'.format('val', 'orig_top1'), acc1_orig, - epoch * len(val_loader) + i) - args.logger.add_scalar('{}/{}'.format('val', 'top1'), acc1, - epoch * len(val_loader) + i) - args.logger.add_scalar('{}/{}'.format('val', 'orig_top5'), acc5_orig, - epoch * len(val_loader) + i) - args.logger.add_scalar('{}/{}'.format('val', 'top5'), acc5, - epoch * len(val_loader) + i) - args.logger.add_scalar('{}/{}'.format('val', 'tot_loss'), loss, - epoch * len(val_loader) + i) - - # TODO: this should also be done with the ProgressMeter - print(' * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}' - .format(top1=top1, top5=top5)) - - return losses.avg - - -def save_checkpoint(state, is_best, folder, filename='checkpoint.pth.tar'): - torch.save(state, f'{folder}/{filename}') - if is_best: - shutil.copyfile(f'{folder}/{filename}', f'{folder}/model_best.pth.tar') - - -class AverageMeter(object): - """Computes and stores the average and current value""" - def __init__(self, name, fmt=':f'): - self.name = name - self.fmt = fmt - self.reset() - - def reset(self): - self.val = 0 - self.avg = 0 - self.sum = 0 - self.count = 0 - - def update(self, val, n=1): - self.val = val - self.sum += val * n - self.count += n - self.avg = self.sum / self.count - - def __str__(self): - fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})' - return fmtstr.format(**self.__dict__) - - -class ProgressMeter(object): - def __init__(self, num_batches, meters, prefix=""): - self.batch_fmtstr = self._get_batch_fmtstr(num_batches) - self.meters = meters - self.prefix = prefix - - def display(self, batch): - entries = [self.prefix + self.batch_fmtstr.format(batch)] - entries += [str(meter) for meter in self.meters] - print('\t'.join(entries)) - - def _get_batch_fmtstr(self, num_batches): - num_digits = len(str(num_batches // 1)) - fmt = '{:' + str(num_digits) + 'd}' - return '[' + fmt + '/' + fmt.format(num_batches) + ']' - -def adjust_learning_rate(optimizer, epoch, args): - """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" - lr = args.lr * (0.85 ** (epoch // 2)) - for param_group in optimizer.param_groups: - param_group['lr'] = lr - - -def accuracy(output, target, topk=(1,)): - """Computes the accuracy over the k top predictions for the specified values of k""" - with torch.no_grad(): - maxk = max(topk) - batch_size = target.size(0) - - _, pred = output.topk(maxk, 1, True, True) - pred = pred.t() - correct = pred.eq(target.view(1, -1).expand_as(pred)) - - res = [] - for k in topk: - correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True) - res.append(correct_k.mul_(100.0 / batch_size)) - return res - - -if __name__ == '__main__': - main() \ No newline at end of file diff --git a/spaces/ICML2022/OFA/fairseq/fairseq/data/shorten_dataset.py b/spaces/ICML2022/OFA/fairseq/fairseq/data/shorten_dataset.py deleted file mode 100644 index 6ebb5d88feb3f29d1512a0873df304915d051209..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/fairseq/data/shorten_dataset.py +++ /dev/null @@ -1,78 +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 numpy as np -from fairseq.data import data_utils - -from . import BaseWrapperDataset - - -class TruncateDataset(BaseWrapperDataset): - """Truncate a sequence by returning the first truncation_length tokens""" - - def __init__(self, dataset, truncation_length): - super().__init__(dataset) - assert truncation_length is not None - self.truncation_length = truncation_length - self.dataset = dataset - - def __getitem__(self, index): - item = self.dataset[index] - item_len = item.size(0) - if item_len > self.truncation_length: - item = item[: self.truncation_length] - return item - - @property - def sizes(self): - return np.minimum(self.dataset.sizes, self.truncation_length) - - def __len__(self): - return len(self.dataset) - - -class RandomCropDataset(TruncateDataset): - """Truncate a sequence by returning a random crop of truncation_length tokens""" - - def __init__(self, dataset, truncation_length, seed=1): - super().__init__(dataset, truncation_length) - self.seed = seed - self.epoch = 0 - - @property - def can_reuse_epoch_itr_across_epochs(self): - return True # only the crop changes, not item sizes - - def set_epoch(self, epoch, **unused): - super().set_epoch(epoch) - self.epoch = epoch - - def __getitem__(self, index): - with data_utils.numpy_seed(self.seed, self.epoch, index): - item = self.dataset[index] - item_len = item.size(0) - excess = item_len - self.truncation_length - if excess > 0: - start_idx = np.random.randint(0, excess) - item = item[start_idx : start_idx + self.truncation_length] - return item - - -def maybe_shorten_dataset( - dataset, - split, - shorten_data_split_list, - shorten_method, - tokens_per_sample, - seed, -): - truncate_split = ( - split in shorten_data_split_list.split(",") or len(shorten_data_split_list) == 0 - ) - if shorten_method == "truncate" and truncate_split: - dataset = TruncateDataset(dataset, tokens_per_sample) - elif shorten_method == "random_crop" and truncate_split: - dataset = RandomCropDataset(dataset, tokens_per_sample, seed) - return dataset diff --git a/spaces/ICML2022/OFA/fairseq/fairseq/modules/linearized_convolution.py b/spaces/ICML2022/OFA/fairseq/fairseq/modules/linearized_convolution.py deleted file mode 100644 index f7e156cb0c75cb375447859c8b6749311372c35e..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/fairseq/modules/linearized_convolution.py +++ /dev/null @@ -1,110 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import torch -import torch.nn.functional as F -from fairseq import utils -from fairseq.incremental_decoding_utils import with_incremental_state - -from .conv_tbc import ConvTBC - -from typing import Dict, Optional -from torch import Tensor - -@with_incremental_state -class LinearizedConvolution(ConvTBC): - """An optimized version of nn.Conv1d. - - At training time, this module uses ConvTBC, which is an optimized version - of Conv1d. At inference time, it optimizes incremental generation (i.e., - one time step at a time) by replacing the convolutions with linear layers. - Note that the input order changes from training to inference. - """ - - def __init__(self, in_channels, out_channels, kernel_size, **kwargs): - super().__init__(in_channels, out_channels, kernel_size, **kwargs) - self._linearized_weight = None - self.register_backward_hook(self._clear_linearized_weight) - - def state_dict(self, destination=None, prefix="", keep_vars=False): - state = ConvTBC.state_dict(self, destination, prefix, keep_vars=keep_vars) - # don't store redundant _linearized_weight in checkpoints - if prefix + "_linearized_weight" in state: - del state[prefix + "_linearized_weight"] - return state - - def upgrade_state_dict_named(self, state_dict, name): - prefix = name + "." if name != "" else "" - if prefix + "_linearized_weight" in state_dict: - del state_dict[prefix + "_linearized_weight"] - - @torch.jit.export - def forward(self, input, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None): - """ - Args: - incremental_state: Used to buffer signal; if not None, then input is - expected to contain a single frame. If the input order changes - between time steps, call reorder_incremental_state. - Input: - Time x Batch x Channel during training - Batch x Time x Channel during inference - """ - if incremental_state is None: - output = self.conv_tbc(input) - if self.kernel_size[0] > 1 and self.padding[0] > 0: - # remove future timesteps added by padding - output = output[: -self.padding[0], :, :] - return output - - # reshape weight - weight = self._get_linearized_weight() - kw = self.kernel_size[0] - - bsz = input.size(0) # input: bsz x len x dim - if kw > 1: - input = input.data - input_buffer = self._get_input_buffer(incremental_state) - if input_buffer is None: - input_buffer = input.new(bsz, kw, input.size(2)).zero_() - self._set_input_buffer(incremental_state, input_buffer) - else: - # shift buffer - input_buffer[:, :-1, :] = input_buffer[:, 1:, :].clone() - # append next input - input_buffer[:, -1, :] = input[:, -1, :] - input = input_buffer - with torch.no_grad(): - output = F.linear(input.view(bsz, -1), weight, self.bias) - return output.view(bsz, 1, -1) - - @torch.jit.unused - def reorder_incremental_state(self, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]], new_order): - input_buffer = self._get_input_buffer(incremental_state) - if input_buffer is not None: - input_buffer = input_buffer.index_select(0, new_order) - self._set_input_buffer(incremental_state, input_buffer) - - @torch.jit.unused - def _get_input_buffer(self, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]]): - return utils.get_incremental_state(self, incremental_state, "input_buffer") - - @torch.jit.unused - def _set_input_buffer(self, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]], new_buffer): - return utils.set_incremental_state( - self, incremental_state, "input_buffer", new_buffer - ) - - @torch.jit.unused - def _get_linearized_weight(self): - if self._linearized_weight is None: - kw = self.kernel_size[0] - weight = self.weight.transpose(2, 1).transpose(1, 0).contiguous() - assert weight.size() == (self.out_channels, kw, self.in_channels) - return weight.view(self.out_channels, -1) - return self._linearized_weight - - @torch.jit.unused - def _clear_linearized_weight(self, *args): - self._linearized_weight = None diff --git a/spaces/Illumotion/Koboldcpp/examples/main/README.md b/spaces/Illumotion/Koboldcpp/examples/main/README.md deleted file mode 100644 index a9561c383c0cba7873808626cc4114e25dc1865d..0000000000000000000000000000000000000000 --- a/spaces/Illumotion/Koboldcpp/examples/main/README.md +++ /dev/null @@ -1,310 +0,0 @@ -# llama.cpp/example/main - -This example program allows you to use various LLaMA language models in an easy and efficient way. It is specifically designed to work with the [llama.cpp](https://github.com/ggerganov/llama.cpp) project, which provides a plain C/C++ implementation with optional 4-bit quantization support for faster, lower memory inference, and is optimized for desktop CPUs. This program can be used to perform various inference tasks with LLaMA models, including generating text based on user-provided prompts and chat-like interactions with reverse prompts. - -## Table of Contents - -1. [Quick Start](#quick-start) -2. [Common Options](#common-options) -3. [Input Prompts](#input-prompts) -4. [Interaction](#interaction) -5. [Context Management](#context-management) -6. [Generation Flags](#generation-flags) -7. [Performance Tuning and Memory Options](#performance-tuning-and-memory-options) -8. [Additional Options](#additional-options) - -## Quick Start - -To get started right away, run the following command, making sure to use the correct path for the model you have: - -#### Unix-based systems (Linux, macOS, etc.): - -```bash -./main -m models/7B/ggml-model.bin --prompt "Once upon a time" -``` - -#### Windows: - -```powershell -main.exe -m models\7B\ggml-model.bin --prompt "Once upon a time" -``` - -For an interactive experience, try this command: - -#### Unix-based systems (Linux, macOS, etc.): - -```bash -./main -m models/7B/ggml-model.bin -n -1 --color -r "User:" --in-prefix " " -i -p \ -'User: Hi -AI: Hello. I am an AI chatbot. Would you like to talk? -User: Sure! -AI: What would you like to talk about? -User:' -``` - -#### Windows: - -```powershell -main.exe -m models\7B\ggml-model.bin -n -1 --color -r "User:" --in-prefix " " -i -e -p "User: Hi\nAI: Hello. I am an AI chatbot. Would you like to talk?\nUser: Sure!\nAI: What would you like to talk about?\nUser:" -``` - -The following command generates "infinite" text from a starting prompt (you can use `Ctrl-C` to stop it): - -#### Unix-based systems (Linux, macOS, etc.): - -```bash -./main -m models/7B/ggml-model.bin --ignore-eos -n -1 --random-prompt -``` - -#### Windows: - -```powershell -main.exe -m models\7B\ggml-model.bin --ignore-eos -n -1 --random-prompt -``` - -## Common Options - -In this section, we cover the most commonly used options for running the `main` program with the LLaMA models: - -- `-m FNAME, --model FNAME`: Specify the path to the LLaMA model file (e.g., `models/7B/ggml-model.bin`). -- `-i, --interactive`: Run the program in interactive mode, allowing you to provide input directly and receive real-time responses. -- `-ins, --instruct`: Run the program in instruction mode, which is particularly useful when working with Alpaca models. -- `-n N, --n-predict N`: Set the number of tokens to predict when generating text. Adjusting this value can influence the length of the generated text. -- `-c N, --ctx-size N`: Set the size of the prompt context. The default is 512, but LLaMA models were built with a context of 2048, which will provide better results for longer input/inference. - -## Input Prompts - -The `main` program provides several ways to interact with the LLaMA models using input prompts: - -- `--prompt PROMPT`: Provide a prompt directly as a command-line option. -- `--file FNAME`: Provide a file containing a prompt or multiple prompts. -- `--interactive-first`: Run the program in interactive mode and wait for input right away. (More on this below.) -- `--random-prompt`: Start with a randomized prompt. - -## Interaction - -The `main` program offers a seamless way to interact with LLaMA models, allowing users to engage in real-time conversations or provide instructions for specific tasks. The interactive mode can be triggered using various options, including `--interactive`, `--interactive-first`, and `--instruct`. - -In interactive mode, users can participate in text generation by injecting their input during the process. Users can press `Ctrl+C` at any time to interject and type their input, followed by pressing `Return` to submit it to the LLaMA model. To submit additional lines without finalizing input, users can end the current line with a backslash (`\`) and continue typing. - -### Interaction Options - -- `-i, --interactive`: Run the program in interactive mode, allowing users to engage in real-time conversations or provide specific instructions to the model. -- `--interactive-first`: Run the program in interactive mode and immediately wait for user input before starting the text generation. -- `-ins, --instruct`: Run the program in instruction mode, which is specifically designed to work with Alpaca models that excel in completing tasks based on user instructions. -- `--color`: Enable colorized output to differentiate visually distinguishing between prompts, user input, and generated text. - -By understanding and utilizing these interaction options, you can create engaging and dynamic experiences with the LLaMA models, tailoring the text generation process to your specific needs. - -### Reverse Prompts - -Reverse prompts are a powerful way to create a chat-like experience with a LLaMA model by pausing the text generation when specific text strings are encountered: - -- `-r PROMPT, --reverse-prompt PROMPT`: Specify one or multiple reverse prompts to pause text generation and switch to interactive mode. For example, `-r "User:"` can be used to jump back into the conversation whenever it's the user's turn to speak. This helps create a more interactive and conversational experience. However, the reverse prompt doesn't work when it ends with a space. - -To overcome this limitation, you can use the `--in-prefix` flag to add a space or any other characters after the reverse prompt. - -### In-Prefix - -The `--in-prefix` flag is used to add a prefix to your input, primarily, this is used to insert a space after the reverse prompt. Here's an example of how to use the `--in-prefix` flag in conjunction with the `--reverse-prompt` flag: - -```sh -./main -r "User:" --in-prefix " " -``` - -### In-Suffix - -The `--in-suffix` flag is used to add a suffix after your input. This is useful for adding an "Assistant:" prompt after the user's input. It's added after the new-line character (`\n`) that's automatically added to the end of the user's input. Here's an example of how to use the `--in-suffix` flag in conjunction with the `--reverse-prompt` flag: - -```sh -./main -r "User:" --in-prefix " " --in-suffix "Assistant:" -``` - -### Instruction Mode - -Instruction mode is particularly useful when working with Alpaca models, which are designed to follow user instructions for specific tasks: - -- `-ins, --instruct`: Enable instruction mode to leverage the capabilities of Alpaca models in completing tasks based on user-provided instructions. - -Technical detail: the user's input is internally prefixed with the reverse prompt (or `### Instruction:` as the default), and followed by `### Response:` (except if you just press Return without any input, to keep generating a longer response). - -By understanding and utilizing these interaction options, you can create engaging and dynamic experiences with the LLaMA models, tailoring the text generation process to your specific needs. - -## Context Management - -During text generation, LLaMA models have a limited context size, which means they can only consider a certain number of tokens from the input and generated text. When the context fills up, the model resets internally, potentially losing some information from the beginning of the conversation or instructions. Context management options help maintain continuity and coherence in these situations. - -### Context Size - -The `--ctx-size` option allows you to set the size of the prompt context used by the LLaMA models during text generation. A larger context size helps the model to better comprehend and generate responses for longer input or conversations. - -- `-c N, --ctx-size N`: Set the size of the prompt context (default: 512). The LLaMA models were built with a context of 2048, which will yield the best results on longer input/inference. However, increasing the context size beyond 2048 may lead to unpredictable results. - -### Extended Context Size - -Some fine-tuned models have extened the context length by scaling RoPE. For example, if the original pretrained model have a context length (max sequence length) of 4096 (4k) and the fine-tuned model have 32k. That is a scaling factor of 8, and should work by setting the above `--ctx-size` to 32768 (32k) and `--rope-scale` to 8. - -- `--rope-scale N`: Where N is the linear scaling factor used by the fine-tuned model. - -### Keep Prompt - -The `--keep` option allows users to retain the original prompt when the model runs out of context, ensuring a connection to the initial instruction or conversation topic is maintained. - -- `--keep N`: Specify the number of tokens from the initial prompt to retain when the model resets its internal context. By default, this value is set to 0 (meaning no tokens are kept). Use `-1` to retain all tokens from the initial prompt. - -By utilizing context management options like `--ctx-size` and `--keep`, you can maintain a more coherent and consistent interaction with the LLaMA models, ensuring that the generated text remains relevant to the original prompt or conversation. - -## Generation Flags - -The following options allow you to control the text generation process and fine-tune the diversity, creativity, and quality of the generated text according to your needs. By adjusting these options and experimenting with different combinations of values, you can find the best settings for your specific use case. - -### Number of Tokens to Predict - -- `-n N, --n-predict N`: Set the number of tokens to predict when generating text (default: 128, -1 = infinity, -2 = until context filled) - -The `--n-predict` option controls the number of tokens the model generates in response to the input prompt. By adjusting this value, you can influence the length of the generated text. A higher value will result in longer text, while a lower value will produce shorter text. - -A value of -1 will enable infinite text generation, even though we have a finite context window. When the context window is full, some of the earlier tokens (half of the tokens after `--n-keep`) will be discarded. The context must then be re-evaluated before generation can resume. On large models and/or large context windows, this will result in significant pause in output. - -If the pause is undesirable, a value of -2 will stop generation immediately when the context is filled. - -It is important to note that the generated text may be shorter than the specified number of tokens if an End-of-Sequence (EOS) token or a reverse prompt is encountered. In interactive mode text generation will pause and control will be returned to the user. In non-interactive mode, the program will end. In both cases, the text generation may stop before reaching the specified `n-predict` value. If you want the model to keep going without ever producing End-of-Sequence on its own, you can use the `--ignore-eos` parameter. - -### Temperature - -- `--temp N`: Adjust the randomness of the generated text (default: 0.8). - -Temperature is a hyperparameter that controls the randomness of the generated text. It affects the probability distribution of the model's output tokens. A higher temperature (e.g., 1.5) makes the output more random and creative, while a lower temperature (e.g., 0.5) makes the output more focused, deterministic, and conservative. The default value is 0.8, which provides a balance between randomness and determinism. At the extreme, a temperature of 0 will always pick the most likely next token, leading to identical outputs in each run. - -Example usage: `--temp 0.5` - -### Repeat Penalty - -- `--repeat-penalty N`: Control the repetition of token sequences in the generated text (default: 1.1). -- `--repeat-last-n N`: Last n tokens to consider for penalizing repetition (default: 64, 0 = disabled, -1 = ctx-size). -- `--no-penalize-nl`: Disable penalization for newline tokens when applying the repeat penalty. - -The `repeat-penalty` option helps prevent the model from generating repetitive or monotonous text. A higher value (e.g., 1.5) will penalize repetitions more strongly, while a lower value (e.g., 0.9) will be more lenient. The default value is 1.1. - -The `repeat-last-n` option controls the number of tokens in the history to consider for penalizing repetition. A larger value will look further back in the generated text to prevent repetitions, while a smaller value will only consider recent tokens. A value of 0 disables the penalty, and a value of -1 sets the number of tokens considered equal to the context size (`ctx-size`). - -Use the `--no-penalize-nl` option to disable newline penalization when applying the repeat penalty. This option is particularly useful for generating chat conversations, dialogues, code, poetry, or any text where newline tokens play a significant role in structure and formatting. Disabling newline penalization helps maintain the natural flow and intended formatting in these specific use cases. - -Example usage: `--repeat-penalty 1.15 --repeat-last-n 128 --no-penalize-nl` - -### Top-K Sampling - -- `--top-k N`: Limit the next token selection to the K most probable tokens (default: 40). - -Top-k sampling is a text generation method that selects the next token only from the top k most likely tokens predicted by the model. It helps reduce the risk of generating low-probability or nonsensical tokens, but it may also limit the diversity of the output. A higher value for top-k (e.g., 100) will consider more tokens and lead to more diverse text, while a lower value (e.g., 10) will focus on the most probable tokens and generate more conservative text. The default value is 40. - -Example usage: `--top-k 30` - -### Top-P Sampling - -- `--top-p N`: Limit the next token selection to a subset of tokens with a cumulative probability above a threshold P (default: 0.9). - -Top-p sampling, also known as nucleus sampling, is another text generation method that selects the next token from a subset of tokens that together have a cumulative probability of at least p. This method provides a balance between diversity and quality by considering both the probabilities of tokens and the number of tokens to sample from. A higher value for top-p (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text. The default value is 0.9. - -Example usage: `--top-p 0.95` - -### Tail Free Sampling (TFS) - -- `--tfs N`: Enable tail free sampling with parameter z (default: 1.0, 1.0 = disabled). - -Tail free sampling (TFS) is a text generation technique that aims to reduce the impact of less likely tokens, which may be less relevant, less coherent, or nonsensical, on the output. Similar to Top-P it tries to determine the bulk of the most likely tokens dynamically. But TFS filters out logits based on the second derivative of their probabilities. Adding tokens is stopped after the sum of the second derivatives reaches the parameter z. In short: TFS looks how quickly the probabilities of the tokens decrease and cuts off the tail of unlikely tokens using the parameter z. Typical values for z are in the range of 0.9 to 0.95. A value of 1.0 would include all tokens, and thus disables the effect of TFS. - -Example usage: `--tfs 0.95` - -### Locally Typical Sampling - -- `--typical N`: Enable locally typical sampling with parameter p (default: 1.0, 1.0 = disabled). - -Locally typical sampling promotes the generation of contextually coherent and diverse text by sampling tokens that are typical or expected based on the surrounding context. By setting the parameter p between 0 and 1, you can control the balance between producing text that is locally coherent and diverse. A value closer to 1 will promote more contextually coherent tokens, while a value closer to 0 will promote more diverse tokens. A value equal to 1 disables locally typical sampling. - -Example usage: `--typical 0.9` - -### Mirostat Sampling - -- `--mirostat N`: Enable Mirostat sampling, controlling perplexity during text generation (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0). -- `--mirostat-lr N`: Set the Mirostat learning rate, parameter eta (default: 0.1). -- `--mirostat-ent N`: Set the Mirostat target entropy, parameter tau (default: 5.0). - -Mirostat is an algorithm that actively maintains the quality of generated text within a desired range during text generation. It aims to strike a balance between coherence and diversity, avoiding low-quality output caused by excessive repetition (boredom traps) or incoherence (confusion traps). - -The `--mirostat-lr` option sets the Mirostat learning rate (eta). The learning rate influences how quickly the algorithm responds to feedback from the generated text. A lower learning rate will result in slower adjustments, while a higher learning rate will make the algorithm more responsive. The default value is `0.1`. - -The `--mirostat-ent` option sets the Mirostat target entropy (tau), which represents the desired perplexity value for the generated text. Adjusting the target entropy allows you to control the balance between coherence and diversity in the generated text. A lower value will result in more focused and coherent text, while a higher value will lead to more diverse and potentially less coherent text. The default value is `5.0`. - -Example usage: `--mirostat 2 --mirostat-lr 0.05 --mirostat-ent 3.0` - -### Logit Bias - -- `-l TOKEN_ID(+/-)BIAS, --logit-bias TOKEN_ID(+/-)BIAS`: Modify the likelihood of a token appearing in the generated text completion. - -The logit bias option allows you to manually adjust the likelihood of specific tokens appearing in the generated text. By providing a token ID and a positive or negative bias value, you can increase or decrease the probability of that token being generated. - -For example, use `--logit-bias 15043+1` to increase the likelihood of the token 'Hello', or `--logit-bias 15043-1` to decrease its likelihood. Using a value of negative infinity, `--logit-bias 15043-inf` ensures that the token `Hello` is never produced. - -A more practical use case might be to prevent the generation of `\code{begin}` and `\code{end}` by setting the `\` token (29905) to negative infinity with `-l 29905-inf`. (This is due to the prevalence of LaTeX codes that show up in LLaMA model inference.) - -Example usage: `--logit-bias 29905-inf` - -### RNG Seed - -- `-s SEED, --seed SEED`: Set the random number generator (RNG) seed (default: -1, -1 = random seed). - -The RNG seed is used to initialize the random number generator that influences the text generation process. By setting a specific seed value, you can obtain consistent and reproducible results across multiple runs with the same input and settings. This can be helpful for testing, debugging, or comparing the effects of different options on the generated text to see when they diverge. If the seed is set to a value less than 0, a random seed will be used, which will result in different outputs on each run. - -## Performance Tuning and Memory Options - -These options help improve the performance and memory usage of the LLaMA models. By adjusting these settings, you can fine-tune the model's behavior to better suit your system's capabilities and achieve optimal performance for your specific use case. - -### Number of Threads - -- `-t N, --threads N`: Set the number of threads to use during generation. For optimal performance, it is recommended to set this value to the number of physical CPU cores your system has (as opposed to the logical number of cores). Using the correct number of threads can greatly improve performance. -- `-tb N, --threads-batch N`: Set the number of threads to use during batch and prompt processing. In some systems, it is beneficial to use a higher number of threads during batch processing than during generation. If not specified, the number of threads used for batch processing will be the same as the number of threads used for generation. - -### Mlock - -- `--mlock`: Lock the model in memory, preventing it from being swapped out when memory-mapped. This can improve performance but trades away some of the advantages of memory-mapping by requiring more RAM to run and potentially slowing down load times as the model loads into RAM. - -### No Memory Mapping - -- `--no-mmap`: Do not memory-map the model. By default, models are mapped into memory, which allows the system to load only the necessary parts of the model as needed. However, if the model is larger than your total amount of RAM or if your system is low on available memory, using mmap might increase the risk of pageouts, negatively impacting performance. Disabling mmap results in slower load times but may reduce pageouts if you're not using `--mlock`. Note that if the model is larger than the total amount of RAM, turning off mmap would prevent the model from loading at all. - -### NUMA support - -- `--numa`: Attempt optimizations that help on some systems with non-uniform memory access. This currently consists of pinning an equal proportion of the threads to the cores on each NUMA node, and disabling prefetch and readahead for mmap. The latter causes mapped pages to be faulted in on first access instead of all at once, and in combination with pinning threads to NUMA nodes, more of the pages end up on the NUMA node where they are used. Note that if the model is already in the system page cache, for example because of a previous run without this option, this will have little effect unless you drop the page cache first. This can be done by rebooting the system or on Linux by writing '3' to '/proc/sys/vm/drop_caches' as root. - -### Memory Float 32 - -- `--memory-f32`: Use 32-bit floats instead of 16-bit floats for memory key+value. This doubles the context memory requirement and cached prompt file size but does not appear to increase generation quality in a measurable way. Not recommended. - -### Batch Size - -- `-b N, --batch-size N`: Set the batch size for prompt processing (default: 512). This large batch size benefits users who have BLAS installed and enabled it during the build. If you don't have BLAS enabled ("BLAS=0"), you can use a smaller number, such as 8, to see the prompt progress as it's evaluated in some situations. - -### Prompt Caching - -- `--prompt-cache FNAME`: Specify a file to cache the model state after the initial prompt. This can significantly speed up the startup time when you're using longer prompts. The file is created during the first run and is reused and updated in subsequent runs. **Note**: Restoring a cached prompt does not imply restoring the exact state of the session at the point it was saved. So even when specifying a specific seed, you are not guaranteed to get the same sequence of tokens as the original generation. - -### Grammars - -- `--grammar GRAMMAR`, `--grammar-file FILE`: Specify a grammar (defined inline or in a file) to constrain model output to a specific format. For example, you could force the model to output JSON or to speak only in emojis. See the [GBNF guide](../../grammars/README.md) for details on the syntax. - -### Quantization - -For information about 4-bit quantization, which can significantly improve performance and reduce memory usage, please refer to llama.cpp's primary [README](../../README.md#prepare-data--run). - -## Additional Options - -These options provide extra functionality and customization when running the LLaMA models: - -- `-h, --help`: Display a help message showing all available options and their default values. This is particularly useful for checking the latest options and default values, as they can change frequently, and the information in this document may become outdated. -- `--verbose-prompt`: Print the prompt before generating text. -- `-ngl N, --n-gpu-layers N`: When compiled with appropriate support (currently CLBlast or cuBLAS), this option allows offloading some layers to the GPU for computation. Generally results in increased performance. -- `-mg i, --main-gpu i`: When using multiple GPUs this option controls which GPU is used for small tensors for which the overhead of splitting the computation across all GPUs is not worthwhile. The GPU in question will use slightly more VRAM to store a scratch buffer for temporary results. By default GPU 0 is used. Requires cuBLAS. -- `-ts SPLIT, --tensor-split SPLIT`: When using multiple GPUs this option controls how large tensors should be split across all GPUs. `SPLIT` is a comma-separated list of non-negative values that assigns the proportion of data that each GPU should get in order. For example, "3,2" will assign 60% of the data to GPU 0 and 40% to GPU 1. By default the data is split in proportion to VRAM but this may not be optimal for performance. Requires cuBLAS. -- `--lora FNAME`: Apply a LoRA (Low-Rank Adaptation) adapter to the model (implies --no-mmap). This allows you to adapt the pretrained model to specific tasks or domains. -- `--lora-base FNAME`: Optional model to use as a base for the layers modified by the LoRA adapter. This flag is used in conjunction with the `--lora` flag, and specifies the base model for the adaptation. diff --git a/spaces/Insuz/Mocha/app.py b/spaces/Insuz/Mocha/app.py deleted file mode 100644 index 647661ef3c3718a18c9b5d6360abe337f1617095..0000000000000000000000000000000000000000 --- a/spaces/Insuz/Mocha/app.py +++ /dev/null @@ -1,145 +0,0 @@ -import time - -import gradio as gr -from gradio.themes.utils.theme_dropdown import create_theme_dropdown - -dropdown, js = create_theme_dropdown() - -with gr.Blocks(theme='Insuz/Mocha') as demo: - with gr.Row().style(equal_height=True): - with gr.Column(scale=10): - gr.Markdown( - """ - # Theme preview: `Mocha` - To use this theme, set `theme='Insuz/Mocha'` in `gr.Blocks()` or `gr.Interface()`. - You can append an `@` and a semantic version expression, e.g. @>=1.0.0,<2.0.0 to pin to a given version - of this theme. - """ - ) - with gr.Column(scale=3): - with gr.Box(): - dropdown.render() - toggle_dark = gr.Button(value="Toggle Dark").style(full_width=True) - - dropdown.change(None, dropdown, None, _js=js) - toggle_dark.click( - None, - _js=""" - () => { - document.body.classList.toggle('dark'); - } - """, - ) - - name = gr.Textbox( - label="Name", - info="Full name, including middle name. No special characters.", - placeholder="John Doe", - value="John Doe", - interactive=True, - ) - - with gr.Row(): - slider1 = gr.Slider(label="Slider 1") - slider2 = gr.Slider(label="Slider 2") - gr.CheckboxGroup(["A", "B", "C"], label="Checkbox Group") - - with gr.Row(): - with gr.Column(variant="panel", scale=1): - gr.Markdown("## Panel 1") - radio = gr.Radio( - ["A", "B", "C"], - label="Radio", - info="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", - ) - drop = gr.Dropdown(["Option 1", "Option 2", "Option 3"], show_label=False) - drop_2 = gr.Dropdown( - ["Option A", "Option B", "Option C"], - multiselect=True, - value=["Option A"], - label="Dropdown", - interactive=True, - ) - check = gr.Checkbox(label="Go") - with gr.Column(variant="panel", scale=2): - img = gr.Image( - "https://gradio.app/assets/img/header-image.jpg", label="Image" - ).style(height=320) - with gr.Row(): - go_btn = gr.Button("Go", label="Primary Button", variant="primary") - clear_btn = gr.Button( - "Clear", label="Secondary Button", variant="secondary" - ) - - def go(*args): - time.sleep(3) - return "https://gradio.app/assets/img/header-image.jpg" - - go_btn.click(go, [radio, drop, drop_2, check, name], img, api_name="go") - - def clear(): - time.sleep(0.2) - return None - - clear_btn.click(clear, None, img) - - with gr.Row(): - btn1 = gr.Button("Button 1").style(size="sm") - btn2 = gr.UploadButton().style(size="sm") - stop_btn = gr.Button("Stop", label="Stop Button", variant="stop").style( - size="sm" - ) - - with gr.Row(): - gr.Dataframe(value=[[1, 2, 3], [4, 5, 6], [7, 8, 9]], label="Dataframe") - gr.JSON( - value={"a": 1, "b": 2, "c": {"test": "a", "test2": [1, 2, 3]}}, label="JSON" - ) - gr.Label(value={"cat": 0.7, "dog": 0.2, "fish": 0.1}) - gr.File() - with gr.Row(): - gr.ColorPicker() - gr.Video("https://gradio-static-files.s3.us-west-2.amazonaws.com/world.mp4") - gr.Gallery( - [ - ( - "https://gradio-static-files.s3.us-west-2.amazonaws.com/lion.jpg", - "lion", - ), - ( - "https://gradio-static-files.s3.us-west-2.amazonaws.com/logo.png", - "logo", - ), - ( - "https://gradio-static-files.s3.us-west-2.amazonaws.com/tower.jpg", - "tower", - ), - ] - ).style(height="200px", grid=2) - - with gr.Row(): - with gr.Column(scale=2): - chatbot = gr.Chatbot([("Hello", "Hi")], label="Chatbot") - chat_btn = gr.Button("Add messages") - - def chat(history): - time.sleep(2) - yield [["How are you?", "I am good."]] - - chat_btn.click( - lambda history: history - + [["How are you?", "I am good."]] - + (time.sleep(2) or []), - chatbot, - chatbot, - ) - with gr.Column(scale=1): - with gr.Accordion("Advanced Settings"): - gr.Markdown("Hello") - gr.Number(label="Chatbot control 1") - gr.Number(label="Chatbot control 2") - gr.Number(label="Chatbot control 3") - - -if __name__ == "__main__": - demo.queue().launch() diff --git a/spaces/JUNGU/VToonify/vtoonify/model/stylegan/dataset.py b/spaces/JUNGU/VToonify/vtoonify/model/stylegan/dataset.py deleted file mode 100644 index 7713ea2f8bc94d202d2dfbe830af3cb96b1e803d..0000000000000000000000000000000000000000 --- a/spaces/JUNGU/VToonify/vtoonify/model/stylegan/dataset.py +++ /dev/null @@ -1,40 +0,0 @@ -from io import BytesIO - -import lmdb -from PIL import Image -from torch.utils.data import Dataset - - -class MultiResolutionDataset(Dataset): - def __init__(self, path, transform, resolution=256): - self.env = lmdb.open( - path, - max_readers=32, - readonly=True, - lock=False, - readahead=False, - meminit=False, - ) - - if not self.env: - raise IOError('Cannot open lmdb dataset', path) - - with self.env.begin(write=False) as txn: - self.length = int(txn.get('length'.encode('utf-8')).decode('utf-8')) - - self.resolution = resolution - self.transform = transform - - def __len__(self): - return self.length - - def __getitem__(self, index): - with self.env.begin(write=False) as txn: - key = f'{self.resolution}-{str(index).zfill(5)}'.encode('utf-8') - img_bytes = txn.get(key) - - buffer = BytesIO(img_bytes) - img = Image.open(buffer) - img = self.transform(img) - - return img diff --git a/spaces/Jasonyoyo/CodeFormer/CodeFormer/basicsr/metrics/psnr_ssim.py b/spaces/Jasonyoyo/CodeFormer/CodeFormer/basicsr/metrics/psnr_ssim.py deleted file mode 100644 index bbd950699c2495880236883861d9e199f900eae8..0000000000000000000000000000000000000000 --- a/spaces/Jasonyoyo/CodeFormer/CodeFormer/basicsr/metrics/psnr_ssim.py +++ /dev/null @@ -1,128 +0,0 @@ -import cv2 -import numpy as np - -from basicsr.metrics.metric_util import reorder_image, to_y_channel -from basicsr.utils.registry import METRIC_REGISTRY - - -@METRIC_REGISTRY.register() -def calculate_psnr(img1, img2, crop_border, input_order='HWC', test_y_channel=False): - """Calculate PSNR (Peak Signal-to-Noise Ratio). - - Ref: https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio - - Args: - img1 (ndarray): Images with range [0, 255]. - img2 (ndarray): Images with range [0, 255]. - crop_border (int): Cropped pixels in each edge of an image. These - pixels are not involved in the PSNR calculation. - input_order (str): Whether the input order is 'HWC' or 'CHW'. - Default: 'HWC'. - test_y_channel (bool): Test on Y channel of YCbCr. Default: False. - - Returns: - float: psnr result. - """ - - assert img1.shape == img2.shape, (f'Image shapes are differnet: {img1.shape}, {img2.shape}.') - if input_order not in ['HWC', 'CHW']: - raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' '"HWC" and "CHW"') - img1 = reorder_image(img1, input_order=input_order) - img2 = reorder_image(img2, input_order=input_order) - img1 = img1.astype(np.float64) - img2 = img2.astype(np.float64) - - if crop_border != 0: - img1 = img1[crop_border:-crop_border, crop_border:-crop_border, ...] - img2 = img2[crop_border:-crop_border, crop_border:-crop_border, ...] - - if test_y_channel: - img1 = to_y_channel(img1) - img2 = to_y_channel(img2) - - mse = np.mean((img1 - img2)**2) - if mse == 0: - return float('inf') - return 20. * np.log10(255. / np.sqrt(mse)) - - -def _ssim(img1, img2): - """Calculate SSIM (structural similarity) for one channel images. - - It is called by func:`calculate_ssim`. - - Args: - img1 (ndarray): Images with range [0, 255] with order 'HWC'. - img2 (ndarray): Images with range [0, 255] with order 'HWC'. - - Returns: - float: ssim result. - """ - - C1 = (0.01 * 255)**2 - C2 = (0.03 * 255)**2 - - img1 = img1.astype(np.float64) - img2 = img2.astype(np.float64) - kernel = cv2.getGaussianKernel(11, 1.5) - window = np.outer(kernel, kernel.transpose()) - - mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5] - mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5] - mu1_sq = mu1**2 - mu2_sq = mu2**2 - mu1_mu2 = mu1 * mu2 - sigma1_sq = cv2.filter2D(img1**2, -1, window)[5:-5, 5:-5] - mu1_sq - sigma2_sq = cv2.filter2D(img2**2, -1, window)[5:-5, 5:-5] - mu2_sq - sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2 - - ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)) - return ssim_map.mean() - - -@METRIC_REGISTRY.register() -def calculate_ssim(img1, img2, crop_border, input_order='HWC', test_y_channel=False): - """Calculate SSIM (structural similarity). - - Ref: - Image quality assessment: From error visibility to structural similarity - - The results are the same as that of the official released MATLAB code in - https://ece.uwaterloo.ca/~z70wang/research/ssim/. - - For three-channel images, SSIM is calculated for each channel and then - averaged. - - Args: - img1 (ndarray): Images with range [0, 255]. - img2 (ndarray): Images with range [0, 255]. - crop_border (int): Cropped pixels in each edge of an image. These - pixels are not involved in the SSIM calculation. - input_order (str): Whether the input order is 'HWC' or 'CHW'. - Default: 'HWC'. - test_y_channel (bool): Test on Y channel of YCbCr. Default: False. - - Returns: - float: ssim result. - """ - - assert img1.shape == img2.shape, (f'Image shapes are differnet: {img1.shape}, {img2.shape}.') - if input_order not in ['HWC', 'CHW']: - raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' '"HWC" and "CHW"') - img1 = reorder_image(img1, input_order=input_order) - img2 = reorder_image(img2, input_order=input_order) - img1 = img1.astype(np.float64) - img2 = img2.astype(np.float64) - - if crop_border != 0: - img1 = img1[crop_border:-crop_border, crop_border:-crop_border, ...] - img2 = img2[crop_border:-crop_border, crop_border:-crop_border, ...] - - if test_y_channel: - img1 = to_y_channel(img1) - img2 = to_y_channel(img2) - - ssims = [] - for i in range(img1.shape[2]): - ssims.append(_ssim(img1[..., i], img2[..., i])) - return np.array(ssims).mean() diff --git a/spaces/Jeff2323/ai-comic-factory/src/components/ui/select.tsx b/spaces/Jeff2323/ai-comic-factory/src/components/ui/select.tsx deleted file mode 100644 index 704239634b359b9e680dab25275e205e72579f82..0000000000000000000000000000000000000000 --- a/spaces/Jeff2323/ai-comic-factory/src/components/ui/select.tsx +++ /dev/null @@ -1,121 +0,0 @@ -"use client" - -import * as React from "react" -import * as SelectPrimitive from "@radix-ui/react-select" -import { Check, ChevronDown } from "lucide-react" - -import { cn } from "@/lib/utils" - -const Select = SelectPrimitive.Root - -const SelectGroup = SelectPrimitive.Group - -const SelectValue = SelectPrimitive.Value - -const SelectTrigger = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, children, ...props }, ref) => ( - - {children} - - - - -)) -SelectTrigger.displayName = SelectPrimitive.Trigger.displayName - -const SelectContent = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, children, position = "popper", ...props }, ref) => ( - - - - {children} - - - -)) -SelectContent.displayName = SelectPrimitive.Content.displayName - -const SelectLabel = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -SelectLabel.displayName = SelectPrimitive.Label.displayName - -const SelectItem = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, children, ...props }, ref) => ( - - - - - - - - {children} - -)) -SelectItem.displayName = SelectPrimitive.Item.displayName - -const SelectSeparator = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -SelectSeparator.displayName = SelectPrimitive.Separator.displayName - -export { - Select, - SelectGroup, - SelectValue, - SelectTrigger, - SelectContent, - SelectLabel, - SelectItem, - SelectSeparator, -} diff --git a/spaces/JohnSmith9982/VITS-Umamusume-voice-synthesizer/hubert_model.py b/spaces/JohnSmith9982/VITS-Umamusume-voice-synthesizer/hubert_model.py deleted file mode 100644 index 6c7f8716c268d0f371f5a9f7995f59bd4b9082d1..0000000000000000000000000000000000000000 --- a/spaces/JohnSmith9982/VITS-Umamusume-voice-synthesizer/hubert_model.py +++ /dev/null @@ -1,221 +0,0 @@ -import copy -from typing import Optional, Tuple -import random - -import torch -import torch.nn as nn -import torch.nn.functional as F -from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present - -class Hubert(nn.Module): - def __init__(self, num_label_embeddings: int = 100, mask: bool = True): - super().__init__() - self._mask = mask - self.feature_extractor = FeatureExtractor() - self.feature_projection = FeatureProjection() - self.positional_embedding = PositionalConvEmbedding() - self.norm = nn.LayerNorm(768) - self.dropout = nn.Dropout(0.1) - self.encoder = TransformerEncoder( - nn.TransformerEncoderLayer( - 768, 12, 3072, activation="gelu", batch_first=True - ), - 12, - ) - self.proj = nn.Linear(768, 256) - - self.masked_spec_embed = nn.Parameter(torch.FloatTensor(768).uniform_()) - self.label_embedding = nn.Embedding(num_label_embeddings, 256) - - def mask(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: - mask = None - if self.training and self._mask: - mask = _compute_mask((x.size(0), x.size(1)), 0.8, 10, x.device, 2) - x[mask] = self.masked_spec_embed.to(x.dtype) - return x, mask - - def encode( - self, x: torch.Tensor, layer: Optional[int] = None - ) -> Tuple[torch.Tensor, torch.Tensor]: - x = self.feature_extractor(x) - x = self.feature_projection(x.transpose(1, 2)) - x, mask = self.mask(x) - x = x + self.positional_embedding(x) - x = self.dropout(self.norm(x)) - x = self.encoder(x, output_layer=layer) - return x, mask - - def logits(self, x: torch.Tensor) -> torch.Tensor: - logits = torch.cosine_similarity( - x.unsqueeze(2), - self.label_embedding.weight.unsqueeze(0).unsqueeze(0), - dim=-1, - ) - return logits / 0.1 - - def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: - x, mask = self.encode(x) - x = self.proj(x) - logits = self.logits(x) - return logits, mask - - -class HubertSoft(Hubert): - def __init__(self): - super().__init__() - - @torch.inference_mode() - def units(self, wav: torch.Tensor) -> torch.Tensor: - wav = F.pad(wav, ((400 - 320) // 2, (400 - 320) // 2)) - x, _ = self.encode(wav) - return self.proj(x) - - -class FeatureExtractor(nn.Module): - def __init__(self): - super().__init__() - self.conv0 = nn.Conv1d(1, 512, 10, 5, bias=False) - self.norm0 = nn.GroupNorm(512, 512) - self.conv1 = nn.Conv1d(512, 512, 3, 2, bias=False) - self.conv2 = nn.Conv1d(512, 512, 3, 2, bias=False) - self.conv3 = nn.Conv1d(512, 512, 3, 2, bias=False) - self.conv4 = nn.Conv1d(512, 512, 3, 2, bias=False) - self.conv5 = nn.Conv1d(512, 512, 2, 2, bias=False) - self.conv6 = nn.Conv1d(512, 512, 2, 2, bias=False) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - x = F.gelu(self.norm0(self.conv0(x))) - x = F.gelu(self.conv1(x)) - x = F.gelu(self.conv2(x)) - x = F.gelu(self.conv3(x)) - x = F.gelu(self.conv4(x)) - x = F.gelu(self.conv5(x)) - x = F.gelu(self.conv6(x)) - return x - - -class FeatureProjection(nn.Module): - def __init__(self): - super().__init__() - self.norm = nn.LayerNorm(512) - self.projection = nn.Linear(512, 768) - self.dropout = nn.Dropout(0.1) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - x = self.norm(x) - x = self.projection(x) - x = self.dropout(x) - return x - - -class PositionalConvEmbedding(nn.Module): - def __init__(self): - super().__init__() - self.conv = nn.Conv1d( - 768, - 768, - kernel_size=128, - padding=128 // 2, - groups=16, - ) - self.conv = nn.utils.weight_norm(self.conv, name="weight", dim=2) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - x = self.conv(x.transpose(1, 2)) - x = F.gelu(x[:, :, :-1]) - return x.transpose(1, 2) - - -class TransformerEncoder(nn.Module): - def __init__( - self, encoder_layer: nn.TransformerEncoderLayer, num_layers: int - ) -> None: - super(TransformerEncoder, self).__init__() - self.layers = nn.ModuleList( - [copy.deepcopy(encoder_layer) for _ in range(num_layers)] - ) - self.num_layers = num_layers - - def forward( - self, - src: torch.Tensor, - mask: torch.Tensor = None, - src_key_padding_mask: torch.Tensor = None, - output_layer: Optional[int] = None, - ) -> torch.Tensor: - output = src - for layer in self.layers[:output_layer]: - output = layer( - output, src_mask=mask, src_key_padding_mask=src_key_padding_mask - ) - return output - - -def _compute_mask( - shape: Tuple[int, int], - mask_prob: float, - mask_length: int, - device: torch.device, - min_masks: int = 0, -) -> torch.Tensor: - batch_size, sequence_length = shape - - if mask_length < 1: - raise ValueError("`mask_length` has to be bigger than 0.") - - if mask_length > sequence_length: - raise ValueError( - f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length} and `sequence_length`: {sequence_length}`" - ) - - # compute number of masked spans in batch - num_masked_spans = int(mask_prob * sequence_length / mask_length + random.random()) - num_masked_spans = max(num_masked_spans, min_masks) - - # make sure num masked indices <= sequence_length - if num_masked_spans * mask_length > sequence_length: - num_masked_spans = sequence_length // mask_length - - # SpecAugment mask to fill - mask = torch.zeros((batch_size, sequence_length), device=device, dtype=torch.bool) - - # uniform distribution to sample from, make sure that offset samples are < sequence_length - uniform_dist = torch.ones( - (batch_size, sequence_length - (mask_length - 1)), device=device - ) - - # get random indices to mask - mask_indices = torch.multinomial(uniform_dist, num_masked_spans) - - # expand masked indices to masked spans - mask_indices = ( - mask_indices.unsqueeze(dim=-1) - .expand((batch_size, num_masked_spans, mask_length)) - .reshape(batch_size, num_masked_spans * mask_length) - ) - offsets = ( - torch.arange(mask_length, device=device)[None, None, :] - .expand((batch_size, num_masked_spans, mask_length)) - .reshape(batch_size, num_masked_spans * mask_length) - ) - mask_idxs = mask_indices + offsets - - # scatter indices to mask - mask = mask.scatter(1, mask_idxs, True) - - return mask - - -def hubert_soft( - path: str -) -> HubertSoft: - r"""HuBERT-Soft from `"A Comparison of Discrete and Soft Speech Units for Improved Voice Conversion"`. - Args: - path (str): path of a pretrained model - """ - hubert = HubertSoft() - checkpoint = torch.load(path) - consume_prefix_in_state_dict_if_present(checkpoint, "module.") - hubert.load_state_dict(checkpoint) - hubert.eval() - return hubert diff --git a/spaces/JohnSmith9982/VITS-Umamusume-voice-synthesizer/text/english.py b/spaces/JohnSmith9982/VITS-Umamusume-voice-synthesizer/text/english.py deleted file mode 100644 index 6817392ba8a9eb830351de89fb7afc5ad72f5e42..0000000000000000000000000000000000000000 --- a/spaces/JohnSmith9982/VITS-Umamusume-voice-synthesizer/text/english.py +++ /dev/null @@ -1,188 +0,0 @@ -""" from https://github.com/keithito/tacotron """ - -''' -Cleaners are transformations that run over the input text at both training and eval time. - -Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners" -hyperparameter. Some cleaners are English-specific. You'll typically want to use: - 1. "english_cleaners" for English text - 2. "transliteration_cleaners" for non-English text that can be transliterated to ASCII using - the Unidecode library (https://pypi.python.org/pypi/Unidecode) - 3. "basic_cleaners" if you do not want to transliterate (in this case, you should also update - the symbols in symbols.py to match your data). -''' - - -# Regular expression matching whitespace: - - -import re -import inflect -from unidecode import unidecode -import eng_to_ipa as ipa -_inflect = inflect.engine() -_comma_number_re = re.compile(r'([0-9][0-9\,]+[0-9])') -_decimal_number_re = re.compile(r'([0-9]+\.[0-9]+)') -_pounds_re = re.compile(r'£([0-9\,]*[0-9]+)') -_dollars_re = re.compile(r'\$([0-9\.\,]*[0-9]+)') -_ordinal_re = re.compile(r'[0-9]+(st|nd|rd|th)') -_number_re = re.compile(r'[0-9]+') - -# List of (regular expression, replacement) pairs for abbreviations: -_abbreviations = [(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [ - ('mrs', 'misess'), - ('mr', 'mister'), - ('dr', 'doctor'), - ('st', 'saint'), - ('co', 'company'), - ('jr', 'junior'), - ('maj', 'major'), - ('gen', 'general'), - ('drs', 'doctors'), - ('rev', 'reverend'), - ('lt', 'lieutenant'), - ('hon', 'honorable'), - ('sgt', 'sergeant'), - ('capt', 'captain'), - ('esq', 'esquire'), - ('ltd', 'limited'), - ('col', 'colonel'), - ('ft', 'fort'), -]] - - -# List of (ipa, lazy ipa) pairs: -_lazy_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [ - ('r', 'ɹ'), - ('æ', 'e'), - ('ɑ', 'a'), - ('ɔ', 'o'), - ('ð', 'z'), - ('θ', 's'), - ('ɛ', 'e'), - ('ɪ', 'i'), - ('ʊ', 'u'), - ('ʒ', 'ʥ'), - ('ʤ', 'ʥ'), - ('ˈ', '↓'), -]] - -# List of (ipa, lazy ipa2) pairs: -_lazy_ipa2 = [(re.compile('%s' % x[0]), x[1]) for x in [ - ('r', 'ɹ'), - ('ð', 'z'), - ('θ', 's'), - ('ʒ', 'ʑ'), - ('ʤ', 'dʑ'), - ('ˈ', '↓'), -]] - -# List of (ipa, ipa2) pairs -_ipa_to_ipa2 = [(re.compile('%s' % x[0]), x[1]) for x in [ - ('r', 'ɹ'), - ('ʤ', 'dʒ'), - ('ʧ', 'tʃ') -]] - - -def expand_abbreviations(text): - for regex, replacement in _abbreviations: - text = re.sub(regex, replacement, text) - return text - - -def collapse_whitespace(text): - return re.sub(r'\s+', ' ', text) - - -def _remove_commas(m): - return m.group(1).replace(',', '') - - -def _expand_decimal_point(m): - return m.group(1).replace('.', ' point ') - - -def _expand_dollars(m): - match = m.group(1) - parts = match.split('.') - if len(parts) > 2: - return match + ' dollars' # Unexpected format - dollars = int(parts[0]) if parts[0] else 0 - cents = int(parts[1]) if len(parts) > 1 and parts[1] else 0 - if dollars and cents: - dollar_unit = 'dollar' if dollars == 1 else 'dollars' - cent_unit = 'cent' if cents == 1 else 'cents' - return '%s %s, %s %s' % (dollars, dollar_unit, cents, cent_unit) - elif dollars: - dollar_unit = 'dollar' if dollars == 1 else 'dollars' - return '%s %s' % (dollars, dollar_unit) - elif cents: - cent_unit = 'cent' if cents == 1 else 'cents' - return '%s %s' % (cents, cent_unit) - else: - return 'zero dollars' - - -def _expand_ordinal(m): - return _inflect.number_to_words(m.group(0)) - - -def _expand_number(m): - num = int(m.group(0)) - if num > 1000 and num < 3000: - if num == 2000: - return 'two thousand' - elif num > 2000 and num < 2010: - return 'two thousand ' + _inflect.number_to_words(num % 100) - elif num % 100 == 0: - return _inflect.number_to_words(num // 100) + ' hundred' - else: - return _inflect.number_to_words(num, andword='', zero='oh', group=2).replace(', ', ' ') - else: - return _inflect.number_to_words(num, andword='') - - -def normalize_numbers(text): - text = re.sub(_comma_number_re, _remove_commas, text) - text = re.sub(_pounds_re, r'\1 pounds', text) - text = re.sub(_dollars_re, _expand_dollars, text) - text = re.sub(_decimal_number_re, _expand_decimal_point, text) - text = re.sub(_ordinal_re, _expand_ordinal, text) - text = re.sub(_number_re, _expand_number, text) - return text - - -def mark_dark_l(text): - return re.sub(r'l([^aeiouæɑɔəɛɪʊ ]*(?: |$))', lambda x: 'ɫ'+x.group(1), text) - - -def english_to_ipa(text): - text = unidecode(text).lower() - text = expand_abbreviations(text) - text = normalize_numbers(text) - phonemes = ipa.convert(text) - phonemes = collapse_whitespace(phonemes) - return phonemes - - -def english_to_lazy_ipa(text): - text = english_to_ipa(text) - for regex, replacement in _lazy_ipa: - text = re.sub(regex, replacement, text) - return text - - -def english_to_ipa2(text): - text = english_to_ipa(text) - text = mark_dark_l(text) - for regex, replacement in _ipa_to_ipa2: - text = re.sub(regex, replacement, text) - return text.replace('...', '…') - - -def english_to_lazy_ipa2(text): - text = english_to_ipa(text) - for regex, replacement in _lazy_ipa2: - text = re.sub(regex, replacement, text) - return text diff --git a/spaces/Jorgerv97/Herramienta_interactiva_ensenyanza_tecnicas_aprendizaje_supervisado_salud/AlgorithmsInfo/decTreeInfo.py b/spaces/Jorgerv97/Herramienta_interactiva_ensenyanza_tecnicas_aprendizaje_supervisado_salud/AlgorithmsInfo/decTreeInfo.py deleted file mode 100644 index e795c6fd7770ce2b66665c534686e0bfdb14872f..0000000000000000000000000000000000000000 --- a/spaces/Jorgerv97/Herramienta_interactiva_ensenyanza_tecnicas_aprendizaje_supervisado_salud/AlgorithmsInfo/decTreeInfo.py +++ /dev/null @@ -1,79 +0,0 @@ -from shiny import module, ui, reactive, render -from shiny.types import ImgData -from pathlib import Path - -explanation_img_path = Path(__file__).parent.parent / "images" - - -@module.ui -def decTree_def_ui(): - return ui.div( - ui.div( - ui.markdown("Un árbol de decisión es un algoritmo de aprendizaje automático que se utiliza para **clasificar elementos de datos siguiendo una estructura similar a un árbol**. Partiendo del nodo más alto, el nodo raíz, cada nodo del árbol representa una prueba en una variable de entrada o atributo. Dependiendo del resultado de dicha prueba, el algoritmo se bifurca hacia el siguiente nodo correspondiente en un nuevo nivel hasta llegar a un nodo hoja, que representa la decisión final de clasificación. Los nodos hoja contienen los resultados de clasificación. El árbol de decisión es una **forma intuitiva de modelar la lógica de toma de decisiones** y ha sido uno de los algoritmos más utilizados en el aprendizaje automático.") - , style="padding-right:50px; text-align: justify; text-justify: inter-word;" - ), - ui.div( - ui.markdown("A continuación, se muestra un ejemplo de una representación de un árbol de decisión simple, que cuenta con 3 variables (C1, C2 y C3). Según los resultados de las pruebas con dichas variables se termina clasificando la muestra en una de las dos clases existentes.") - , style="padding-right:50px; padding-bottom:10px; text-align: justify; text-justify: inter-word;" - ), - ui.output_image("dec_tree_expl_image", height="260px"), - ) - -@module.ui -def decTree_howTo_ui(): - return ui.div( - {"id": "dec_tree_how_generate"}, - ui.input_action_button("dec_tree_show_how_info", "¿Cómo se genera el modelo de árbol de decisión? ▽" - , style="padding: 30px 0px 10px 0px; background: white; border: none; font-weight: bold; text-decoration: underline; border: 0 !important; box-shadow: 0 0 !important; transition: 0.1s !important; background-color: transparent !important;"), - - ) - -@module.ui -def decTree_performance_ui(): - return ui.div( - ui.div( - ui.markdown("""**No hay un umbral exacto para considerar un modelo como bueno**, ya que depende del contexto y las necesidades del problema. En general, en aplicaciones relacionadas con el ámbito sanitario se busca maximizar tanto la precisión (para minimizar falsos positivos) como la sensibilidad o TVP (para minimizar falsos negativos), por lo que **se busca obtener un valor alto de F1**. En este ejemplo el valor de F1 puede superar el 90% pero es muy fácil sobreajustar el modelo con un árbol de decisión. - - -*Consejo: editar la profundidad máxima del árbol es un buen punto de inicio para evitar el sobreajuste.*""") - , style="padding-top:30px; padding-right:50px; text-align: justify; text-justify: inter-word;" - ), - ) - - -@module.server -def decTree_server(input, output, session): - - @reactive.Effect - @reactive.event(input.dec_tree_show_how_info) - def _(): - show_dec_tree_how_gen_button = input.dec_tree_show_how_info() - if show_dec_tree_how_gen_button % 2 == 1: - ui.update_action_button("dec_tree_show_how_info", label="¿Cómo se genera el modelo de árbol de decisión? △") - ui.insert_ui( - ui.div({"id": "inserted-dec-tree-how-gen-info"}, - ui.markdown("""Todos los modelos siguen los mismos pasos para ser creados: -- Primero debemos **elegir los ajustes del modelo** que queremos crear. En este caso, disponemos de los siguientes ajustes: - - **Criterion**: La función utilizada para medir la calidad de una división. - - **Splitter**: La estrategia utilizada para elegir la división en cada nodo. - - **Max Depth**: La profundidad máxima del árbol. Si es None, los nodos se expandirán hasta que todas las hojas sean puras o hasta que todas las hojas contengan menos muestras que min_samples_split. - - **Min samples split**: El número mínimo de muestras requeridas para dividir un nodo interno. - - **Min samples leaf**: El número mínimo de muestras requeridas para estar en un nodo hoja. - - **Max features**: El número de características a considerar al buscar la mejor división. -- Después debemos **elegir las características** que queremos usar para predecir el resultado. No todas las características pueden ser relevantes para el modelo y puede que nos encontremos algunas que aporten ruido a nuestros resultados. Si es la primera vez que creas el modelo, selecciona todas las características de momento. -- Por último, **¡genera el modelo!**""" - ), - style="border: solid 0px grey; border-radius: 10px; background:#eceef1 ;margin-right:50px; padding:15px 20px 10px 20px; text-align: justify; text-justify: inter-word;", - ), - selector="#dec_tree_how_generate", - where="beforeEnd", - ) - else: - ui.update_action_button("dec_tree_show_how_info", label="¿Cómo se genera el modelo de árbol de decisión? ▽") - ui.remove_ui("#inserted-dec-tree-how-gen-info") - - @output - @render.image - def dec_tree_expl_image(): - img: ImgData = {"src": str(explanation_img_path / "dec_tree_expl.png"), "height":"250px", "style":"display:block; margin-left:25%;"} - return img \ No newline at end of file diff --git a/spaces/KPCGD/bingo/src/components/button-scroll-to-bottom.tsx b/spaces/KPCGD/bingo/src/components/button-scroll-to-bottom.tsx deleted file mode 100644 index b68ab9c0e48320c356e51a52d11b9ca63909e6c5..0000000000000000000000000000000000000000 --- a/spaces/KPCGD/bingo/src/components/button-scroll-to-bottom.tsx +++ /dev/null @@ -1,34 +0,0 @@ -'use client' - -import * as React from 'react' - -import { cn } from '@/lib/utils' -import { useAtBottom } from '@/lib/hooks/use-at-bottom' -import { Button, type ButtonProps } from '@/components/ui/button' -import { IconArrowDown } from '@/components/ui/icons' - -export function ButtonScrollToBottom({ className, ...props }: ButtonProps) { - const isAtBottom = useAtBottom() - - return ( - - ) -} diff --git a/spaces/KatieChau/text-generator/app.py b/spaces/KatieChau/text-generator/app.py deleted file mode 100644 index 15a53d74b700aea82666da21941cf32142aafaa7..0000000000000000000000000000000000000000 --- a/spaces/KatieChau/text-generator/app.py +++ /dev/null @@ -1,15 +0,0 @@ -import gradio as gr -from gradio.mix import Parallel - -title="My First Text Generator" -description="Input text." - -#variables, functions and parameters -model1 = gr.Interface.load("huggingface/gpt2") -model2 = gr.Interface.load("huggingface/EleutherAI/gpt-j-6B") -model3 = gr.Interface.load("huggingface/EleutherAI/gpt-neo-1.3B") - -#functions, parameters and variables -gr.Parallel(model1, model2, model3,title=title,description=description).launch() - - diff --git a/spaces/KdaiP/yolov8-deepsort-tracking/deep_sort/deep_sort/sort/iou_matching.py b/spaces/KdaiP/yolov8-deepsort-tracking/deep_sort/deep_sort/sort/iou_matching.py deleted file mode 100644 index c7e0f7a41c1d95d4bd6ca04245c5abb9b3ed6156..0000000000000000000000000000000000000000 --- a/spaces/KdaiP/yolov8-deepsort-tracking/deep_sort/deep_sort/sort/iou_matching.py +++ /dev/null @@ -1,84 +0,0 @@ -# vim: expandtab:ts=4:sw=4 -from __future__ import absolute_import -import numpy as np -from . import linear_assignment - -#计算两个框的IOU -def iou(bbox, candidates): - """Computer intersection over union. - - Parameters - ---------- - bbox : ndarray - A bounding box in format `(top left x, top left y, width, height)`. - candidates : ndarray - A matrix of candidate bounding boxes (one per row) in the same format - as `bbox`. - - Returns - ------- - ndarray - The intersection over union in [0, 1] between the `bbox` and each - candidate. A higher score means a larger fraction of the `bbox` is - occluded by the candidate. - - """ - bbox_tl, bbox_br = bbox[:2], bbox[:2] + bbox[2:] - candidates_tl = candidates[:, :2] - candidates_br = candidates[:, :2] + candidates[:, 2:] - - # np.c_ Translates slice objects to concatenation along the second axis. - tl = np.c_[np.maximum(bbox_tl[0], candidates_tl[:, 0])[:, np.newaxis], - np.maximum(bbox_tl[1], candidates_tl[:, 1])[:, np.newaxis]] - br = np.c_[np.minimum(bbox_br[0], candidates_br[:, 0])[:, np.newaxis], - np.minimum(bbox_br[1], candidates_br[:, 1])[:, np.newaxis]] - wh = np.maximum(0., br - tl) - - area_intersection = wh.prod(axis=1) - area_bbox = bbox[2:].prod() - area_candidates = candidates[:, 2:].prod(axis=1) - return area_intersection / (area_bbox + area_candidates - area_intersection) - -# 计算tracks和detections之间的IOU距离成本矩阵 -def iou_cost(tracks, detections, track_indices=None, - detection_indices=None): - """An intersection over union distance metric. - - 用于计算tracks和detections之间的iou距离矩阵 - - Parameters - ---------- - tracks : List[deep_sort.track.Track] - A list of tracks. - detections : List[deep_sort.detection.Detection] - A list of detections. - track_indices : Optional[List[int]] - A list of indices to tracks that should be matched. Defaults to - all `tracks`. - detection_indices : Optional[List[int]] - A list of indices to detections that should be matched. Defaults - to all `detections`. - - Returns - ------- - ndarray - Returns a cost matrix of shape - len(track_indices), len(detection_indices) where entry (i, j) is - `1 - iou(tracks[track_indices[i]], detections[detection_indices[j]])`. - - """ - if track_indices is None: - track_indices = np.arange(len(tracks)) - if detection_indices is None: - detection_indices = np.arange(len(detections)) - - cost_matrix = np.zeros((len(track_indices), len(detection_indices))) - for row, track_idx in enumerate(track_indices): - if tracks[track_idx].time_since_update > 1: - cost_matrix[row, :] = linear_assignment.INFTY_COST - continue - - bbox = tracks[track_idx].to_tlwh() - candidates = np.asarray([detections[i].tlwh for i in detection_indices]) - cost_matrix[row, :] = 1. - iou(bbox, candidates) - return cost_matrix diff --git a/spaces/Kevin676/AutoGPT/autogpt/memory/pinecone.py b/spaces/Kevin676/AutoGPT/autogpt/memory/pinecone.py deleted file mode 100644 index 27fcd62482d0cf44e02fa1c339195be58cb745b0..0000000000000000000000000000000000000000 --- a/spaces/Kevin676/AutoGPT/autogpt/memory/pinecone.py +++ /dev/null @@ -1,75 +0,0 @@ -import pinecone -from colorama import Fore, Style - -from autogpt.llm_utils import create_embedding_with_ada -from autogpt.logs import logger -from autogpt.memory.base import MemoryProviderSingleton - - -class PineconeMemory(MemoryProviderSingleton): - def __init__(self, cfg): - pinecone_api_key = cfg.pinecone_api_key - pinecone_region = cfg.pinecone_region - pinecone.init(api_key=pinecone_api_key, environment=pinecone_region) - dimension = 1536 - metric = "cosine" - pod_type = "p1" - table_name = "auto-gpt" - # this assumes we don't start with memory. - # for now this works. - # we'll need a more complicated and robust system if we want to start with - # memory. - self.vec_num = 0 - - try: - pinecone.whoami() - except Exception as e: - logger.typewriter_log( - "FAILED TO CONNECT TO PINECONE", - Fore.RED, - Style.BRIGHT + str(e) + Style.RESET_ALL, - ) - logger.double_check( - "Please ensure you have setup and configured Pinecone properly for use." - + f"You can check out {Fore.CYAN + Style.BRIGHT}" - "https://github.com/Torantulino/Auto-GPT#-pinecone-api-key-setup" - f"{Style.RESET_ALL} to ensure you've set up everything correctly." - ) - exit(1) - - if table_name not in pinecone.list_indexes(): - pinecone.create_index( - table_name, dimension=dimension, metric=metric, pod_type=pod_type - ) - self.index = pinecone.Index(table_name) - - def add(self, data): - vector = create_embedding_with_ada(data) - # no metadata here. We may wish to change that long term. - self.index.upsert([(str(self.vec_num), vector, {"raw_text": data})]) - _text = f"Inserting data into memory at index: {self.vec_num}:\n data: {data}" - self.vec_num += 1 - return _text - - def get(self, data): - return self.get_relevant(data, 1) - - def clear(self): - self.index.delete(deleteAll=True) - return "Obliviated" - - def get_relevant(self, data, num_relevant=5): - """ - Returns all the data in the memory that is relevant to the given data. - :param data: The data to compare to. - :param num_relevant: The number of relevant data to return. Defaults to 5 - """ - query_embedding = create_embedding_with_ada(data) - results = self.index.query( - query_embedding, top_k=num_relevant, include_metadata=True - ) - sorted_results = sorted(results.matches, key=lambda x: x.score) - return [str(item["metadata"]["raw_text"]) for item in sorted_results] - - def get_stats(self): - return self.index.describe_index_stats() diff --git a/spaces/Kevin676/ChatGPT-with-Voice-Cloning-in-Chinese/vocoder/fregan/loss.py b/spaces/Kevin676/ChatGPT-with-Voice-Cloning-in-Chinese/vocoder/fregan/loss.py deleted file mode 100644 index e37dc64e29446ecdd9dce03290f4e0eba58fb3d7..0000000000000000000000000000000000000000 --- a/spaces/Kevin676/ChatGPT-with-Voice-Cloning-in-Chinese/vocoder/fregan/loss.py +++ /dev/null @@ -1,35 +0,0 @@ -import torch - - -def feature_loss(fmap_r, fmap_g): - loss = 0 - for dr, dg in zip(fmap_r, fmap_g): - for rl, gl in zip(dr, dg): - loss += torch.mean(torch.abs(rl - gl)) - - return loss*2 - - -def discriminator_loss(disc_real_outputs, disc_generated_outputs): - loss = 0 - r_losses = [] - g_losses = [] - for dr, dg in zip(disc_real_outputs, disc_generated_outputs): - r_loss = torch.mean((1-dr)**2) - g_loss = torch.mean(dg**2) - loss += (r_loss + g_loss) - r_losses.append(r_loss.item()) - g_losses.append(g_loss.item()) - - return loss, r_losses, g_losses - - -def generator_loss(disc_outputs): - loss = 0 - gen_losses = [] - for dg in disc_outputs: - l = torch.mean((1-dg)**2) - gen_losses.append(l) - loss += l - - return loss, gen_losses \ No newline at end of file diff --git a/spaces/Kevin676/Speechbrain-Speech-enhancement/README.md b/spaces/Kevin676/Speechbrain-Speech-enhancement/README.md deleted file mode 100644 index 7556741b5767c451105574636e9affff570c4960..0000000000000000000000000000000000000000 --- a/spaces/Kevin676/Speechbrain-Speech-enhancement/README.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -title: Speechbrain Speech Enhancement -emoji: 👁 -colorFrom: gray -colorTo: pink -sdk: gradio -app_file: app.py -pinned: false -duplicated_from: akhaliq/Speechbrain-Speech-enhancement ---- - -# 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/KyanChen/FunSR/test_inr_liif_metasr_aliif.py b/spaces/KyanChen/FunSR/test_inr_liif_metasr_aliif.py deleted file mode 100644 index e8c471fc58c54e710e5129ad88a0cf103f0de72b..0000000000000000000000000000000000000000 --- a/spaces/KyanChen/FunSR/test_inr_liif_metasr_aliif.py +++ /dev/null @@ -1,216 +0,0 @@ -import argparse -import json -import os - -import math -from functools import partial - -import cv2 -import numpy as np -import yaml -import torch -from einops import rearrange -from torch.utils.data import DataLoader -from tqdm import tqdm - -import datasets -import models -import utils - -device = 'cuda:0' if torch.cuda.is_available() else 'cpu' - -def batched_predict(model, inp, coord, bsize): - with torch.no_grad(): - pred = model(inp, coord) - return pred - - -def eval_psnr(loader, class_names, model, - data_norm=None, eval_type=None, save_fig=False, - scale_ratio=1, save_path=None, verbose=False, crop_border=4, - cal_metrics=True, - ): - crop_border = int(crop_border) if crop_border else crop_border - print('crop border: ', crop_border) - model.eval() - - if data_norm is None: - data_norm = { - 'inp': {'sub': [0], 'div': [1]}, - 'gt': {'sub': [0], 'div': [1]} - } - t = data_norm['inp'] - inp_sub = torch.FloatTensor(t['sub']).view(1, -1, 1, 1).to(device) - inp_div = torch.FloatTensor(t['div']).view(1, -1, 1, 1).to(device) - t = data_norm['gt'] - gt_sub = torch.FloatTensor(t['sub']).view(1, 1, -1).to(device) - gt_div = torch.FloatTensor(t['div']).view(1, 1, -1).to(device) - - if eval_type is None: - metric_fn = [utils.calculate_psnr_pt, utils.calculate_ssim_pt] - elif eval_type == 'psnr+ssim': - metric_fn = [utils.calculate_psnr_pt, utils.calculate_ssim_pt] - elif eval_type.startswith('div2k'): - scale = int(eval_type.split('-')[1]) - metric_fn = partial(utils.calc_psnr, dataset='div2k', scale=scale) - elif eval_type.startswith('benchmark'): - scale = int(eval_type.split('-')[1]) - metric_fn = partial(utils.calc_psnr, dataset='benchmark', scale=scale) - else: - raise NotImplementedError - - val_res_psnr = utils.Averager(class_names) - val_res_ssim = utils.Averager(class_names) - - pbar = tqdm(loader, leave=False, desc='val') - for batch in pbar: - for k, v in batch.items(): - if torch.is_tensor(v): - batch[k] = v.to(device) - - inp = (batch['inp'] - inp_sub) / inp_div - - with torch.no_grad(): - pred = model(inp, batch['coord'], batch['cell']) - pred = pred * gt_div + gt_sub - - if eval_type is not None: # reshape for shaving-eval - ih, iw = batch['inp'].shape[-2:] - s = math.sqrt(batch['coord'].shape[1] / (ih * iw)) - if s > 1: - shape = [batch['inp'].shape[0], round(ih * s), round(iw * s), 3] - else: - shape = [batch['inp'].shape[0], 32, batch['coord'].shape[1]//32, 3] - - pred = pred.view(*shape) \ - .permute(0, 3, 1, 2).contiguous() - batch['gt'] = batch['gt'].view(*shape) \ - .permute(0, 3, 1, 2).contiguous() - if cal_metrics: - res_psnr = metric_fn[0]( - pred, - batch['gt'], - crop_border=crop_border - ) - res_ssim = metric_fn[1]( - pred, - batch['gt'], - crop_border=crop_border - ) - else: - res_psnr = torch.ones(len(pred)) - res_ssim = torch.ones(len(pred)) - - file_names = batch.get('filename', None) - if file_names is not None and save_fig: - for idx in range(len(batch['inp'])): - ori_img = batch['inp'][idx].cpu().numpy() * 255 - ori_img = np.clip(ori_img, a_min=0, a_max=255) - ori_img = ori_img.astype(np.uint8) - ori_img = rearrange(ori_img, 'C H W -> H W C') - - pred_img = pred[idx].cpu().numpy() * 255 - pred_img = np.clip(pred_img, a_min=0, a_max=255) - pred_img = pred_img.astype(np.uint8) - pred_img = rearrange(pred_img, 'C H W -> H W C') - - gt_img = batch['gt'][idx].cpu().numpy() * 255 - gt_img = np.clip(gt_img, a_min=0, a_max=255) - gt_img = gt_img.astype(np.uint8) - gt_img = rearrange(gt_img, 'C H W -> H W C') - - psnr = res_psnr[idx].cpu().numpy() - ssim = res_ssim[idx].cpu().numpy() - ori_file_name = f'{save_path}/{file_names[idx]}_Ori.png' - cv2.imwrite(ori_file_name, ori_img) - pred_file_name = f'{save_path}/{file_names[idx]}_{scale_ratio}X_{psnr:.2f}_{ssim:.4f}.png' - cv2.imwrite(pred_file_name, pred_img) - gt_file_name = f'{save_path}/{file_names[idx]}_GT.png' - cv2.imwrite(gt_file_name, gt_img) - - val_res_psnr.add(batch['class_name'], res_psnr) - val_res_ssim.add(batch['class_name'], res_ssim) - - if verbose: - pbar.set_description( - 'val psnr: {:.4f} ssim: {:.4f}'.format(val_res_psnr.item()['all'], val_res_ssim.item()['all'])) - - return val_res_psnr.item(), val_res_ssim.item() - - -if __name__ == '__main__': - parser = argparse.ArgumentParser() - parser.add_argument('--config', default='configs/test_INR_mysr.yaml') - parser.add_argument('--model', default='checkpoints/EXP20220610_5/epoch-best.pth') - parser.add_argument('--scale_ratio', default=4, type=float) - parser.add_argument('--save_fig', default=False, type=bool) - parser.add_argument('--save_path', default='tmp', type=str) - parser.add_argument('--cal_metrics', default=True, type=bool) - parser.add_argument('--return_class_metrics', default=False, type=bool) - parser.add_argument('--dataset_name', default='UC', type=str) - args = parser.parse_args() - - with open(args.config, 'r') as f: - config = yaml.load(f, Loader=yaml.FullLoader) - root_split_file = {'UC': - { - 'root_path': '/data/kyanchen/datasets/UC/256', - 'split_file': 'data_split/UC_split.json' - }, - 'AID': - { - 'root_path': '/data/kyanchen/datasets/AID', - 'split_file': 'data_split/AID_split.json' - } - } - config['test_dataset']['dataset']['args']['root_path'] = root_split_file[args.dataset_name]['root_path'] - config['test_dataset']['dataset']['args']['split_file'] = root_split_file[args.dataset_name]['split_file'] - - config['test_dataset']['wrapper']['args']['scale_ratio'] = args.scale_ratio - - spec = config['test_dataset'] - dataset = datasets.make(spec['dataset']) - dataset = datasets.make(spec['wrapper'], args={'dataset': dataset}) - loader = DataLoader(dataset, batch_size=spec['batch_size'], num_workers=0, pin_memory=True, shuffle=False, - drop_last=False) - if not os.path.exists(args.model): - assert NameError - model_spec = torch.load(args.model)['model'] - print(model_spec['args']) - model = models.make(model_spec, load_sd=True).to(device) - - file_names = json.load(open(config['test_dataset']['dataset']['args']['split_file']))['test'] - class_names = list(set([os.path.basename(os.path.dirname(x)) for x in file_names])) - - crop_border = config['test_dataset']['wrapper']['args']['scale_ratio'] + 5 - dataset_name = os.path.basename(config['test_dataset']['dataset']['args']['split_file']).split('_')[0] - max_scale = {'UC': 5, 'AID': 12} - if args.scale_ratio > max_scale[dataset_name]: - crop_border = int((args.scale_ratio - max_scale[dataset_name]) / 2 * 48) - - if args.save_fig: - os.makedirs(args.save_path, exist_ok=True) - - res = eval_psnr( - loader, class_names, model, - data_norm=config.get('data_norm'), - eval_type=config.get('eval_type'), - crop_border=crop_border, - verbose=True, - save_fig=args.save_fig, - scale_ratio=args.scale_ratio, - save_path=args.save_path, - cal_metrics=args.cal_metrics - ) - - if args.return_class_metrics: - keys = list(res[0].keys()) - keys.sort() - print('psnr') - for k in keys: - print(f'{k}: {res[0][k]:0.2f}') - print('ssim') - for k in keys: - print(f'{k}: {res[1][k]:0.4f}') - print(f'psnr: {res[0]["all"]:0.2f}') - print(f'ssim: {res[1]["all"]:0.4f}') diff --git a/spaces/Lasion/NCKH_2023/app.py b/spaces/Lasion/NCKH_2023/app.py deleted file mode 100644 index 641ce8ac2e76d8999958b3a93185a882ad00079f..0000000000000000000000000000000000000000 --- a/spaces/Lasion/NCKH_2023/app.py +++ /dev/null @@ -1,20 +0,0 @@ -import gradio as gr -import cv2 -from ultralytics import YOLO - -def run(source): - global model - res = model(source, conf=.5, iou=.5) - res_plotted = res[0].plot() - # converting BGR to RGB - result = cv2.cvtColor(res_plotted, cv2.COLOR_BGR2RGB) - return result - -model = YOLO("yolov8n-nckh2023.pt") # Select YOLO model - -gr.Interface( - run, - inputs=gr.Image(label="Upload image", type="filepath"), - outputs=gr.Image(label="Your result"), - title="Motorcyclist, helmet, and license plate detection", -).launch() diff --git a/spaces/Latryna/roop/roop/globals.py b/spaces/Latryna/roop/roop/globals.py deleted file mode 100644 index 77fd391db235b878ce1f91765596bd76adb06697..0000000000000000000000000000000000000000 --- a/spaces/Latryna/roop/roop/globals.py +++ /dev/null @@ -1,17 +0,0 @@ -from typing import List - -source_path = None -target_path = None -output_path = None -frame_processors: List[str] = [] -keep_fps = None -keep_audio = None -keep_frames = None -many_faces = None -video_encoder = None -video_quality = None -max_memory = None -execution_providers: List[str] = [] -execution_threads = None -headless = None -log_level = 'error' diff --git a/spaces/LayBraid/SpaceVector_v0/app.py b/spaces/LayBraid/SpaceVector_v0/app.py deleted file mode 100644 index 02f8807780f02d540688fe3467c67782b9c59fbf..0000000000000000000000000000000000000000 --- a/spaces/LayBraid/SpaceVector_v0/app.py +++ /dev/null @@ -1,20 +0,0 @@ -import streamlit as st -import text_to_image -import home -import contributing - - -PAGES = { - "Home": home, - "Retrieve Images given Text": text_to_image, - "Contribute to Space Vector": contributing, -} - -st.sidebar.title("Space Vector") -st.sidebar.image("space.jpeg") -st.sidebar.markdown(""" - SpaceVector is a semantic search engine. It allows you to find your texts in images. -""") -selection = st.sidebar.radio("Go to", list(PAGES.keys())) -page = PAGES[selection] -page.app() diff --git a/spaces/LaynzKunz/Aesthetic_RVC_Inference_HF/lib/fixes/local_fixes.py b/spaces/LaynzKunz/Aesthetic_RVC_Inference_HF/lib/fixes/local_fixes.py deleted file mode 100644 index a7abad699332af42bdcb29f31eb3370423421cb4..0000000000000000000000000000000000000000 --- a/spaces/LaynzKunz/Aesthetic_RVC_Inference_HF/lib/fixes/local_fixes.py +++ /dev/null @@ -1,109 +0,0 @@ -import os -import time -import shutil -import requests -import zipfile - -def insert_new_line(file_name, line_to_find, text_to_insert): - lines = [] - with open(file_name, 'r', encoding='utf-8') as read_obj: - lines = read_obj.readlines() - already_exists = False - with open(file_name + '.tmp', 'w', encoding='utf-8') as write_obj: - for i in range(len(lines)): - write_obj.write(lines[i]) - if lines[i].strip() == line_to_find: - # If next line exists and starts with sys.path.append, skip - if i+1 < len(lines) and lines[i+1].strip().startswith("sys.path.append"): - print('It was already fixed! Skip adding a line...') - already_exists = True - break - else: - write_obj.write(text_to_insert + '\n') - # If no existing sys.path.append line was found, replace the original file - if not already_exists: - os.replace(file_name + '.tmp', file_name) - return True - else: - # If existing line was found, delete temporary file - os.remove(file_name + '.tmp') - return False - -def replace_in_file(file_name, old_text, new_text): - with open(file_name, 'r', encoding='utf-8') as file: - file_contents = file.read() - - if old_text in file_contents: - file_contents = file_contents.replace(old_text, new_text) - with open(file_name, 'w', encoding='utf-8') as file: - file.write(file_contents) - return True - - return False - - -def find_torchcrepe_directory(directory): - """ - Recursively searches for the topmost folder named 'torchcrepe' within a directory. - Returns the path of the directory found or None if none is found. - """ - for root, dirs, files in os.walk(directory): - if 'torchcrepe' in dirs: - return os.path.join(root, 'torchcrepe') - return None - -def download_and_extract_torchcrepe(): - url = 'https://github.com/maxrmorrison/torchcrepe/archive/refs/heads/master.zip' - temp_dir = 'temp_torchcrepe' - destination_dir = os.getcwd() - - try: - torchcrepe_dir_path = os.path.join(destination_dir, 'torchcrepe') - - if os.path.exists(torchcrepe_dir_path): - print("Skipping the torchcrepe download. The folder already exists.") - return - - # Download the file - print("Starting torchcrepe download...") - response = requests.get(url) - - # Raise an error if the GET request was unsuccessful - response.raise_for_status() - print("Download completed.") - - # Save the downloaded file - zip_file_path = os.path.join(temp_dir, 'master.zip') - os.makedirs(temp_dir, exist_ok=True) - with open(zip_file_path, 'wb') as file: - file.write(response.content) - print(f"Zip file saved to {zip_file_path}") - - # Extract the zip file - print("Extracting content...") - with zipfile.ZipFile(zip_file_path, 'r') as zip_file: - zip_file.extractall(temp_dir) - print("Extraction completed.") - - # Locate the torchcrepe folder and move it to the destination directory - torchcrepe_dir = find_torchcrepe_directory(temp_dir) - if torchcrepe_dir: - shutil.move(torchcrepe_dir, destination_dir) - print(f"Moved the torchcrepe directory to {destination_dir}!") - else: - print("The torchcrepe directory could not be located.") - - except Exception as e: - print("Torchcrepe not successfully downloaded", e) - - # Clean up temporary directory - if os.path.exists(temp_dir): - shutil.rmtree(temp_dir) - -# Run the function -download_and_extract_torchcrepe() - -temp_dir = 'temp_torchcrepe' - -if os.path.exists(temp_dir): - shutil.rmtree(temp_dir) diff --git a/spaces/Lianjd/stock_dashboard/backtrader/plot/scheme.py b/spaces/Lianjd/stock_dashboard/backtrader/plot/scheme.py deleted file mode 100644 index ac03acdef120e8e13ad4e0bb3c3569a2054c7076..0000000000000000000000000000000000000000 --- a/spaces/Lianjd/stock_dashboard/backtrader/plot/scheme.py +++ /dev/null @@ -1,189 +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) - - -tableau20 = [ - 'steelblue', # 0 - 'lightsteelblue', # 1 - 'darkorange', # 2 - 'peachpuff', # 3 - 'green', # 4 - 'lightgreen', # 5 - 'crimson', # 6 - 'lightcoral', # 7 - 'mediumpurple', # 8 - 'thistle', # 9 - 'saddlebrown', # 10 - 'rosybrown', # 11 - 'orchid', # 12 - 'lightpink', # 13 - 'gray', # 14 - 'lightgray', # 15 - 'olive', # 16 - 'palegoldenrod', # 17 - 'mediumturquoise', # 18 - 'paleturquoise', # 19 -] - -tableau10 = [ - 'blue', # 'steelblue', # 0 - 'darkorange', # 1 - 'green', # 2 - 'crimson', # 3 - 'mediumpurple', # 4 - 'saddlebrown', # 5 - 'orchid', # 6 - 'gray', # 7 - 'olive', # 8 - 'mediumturquoise', # 9 -] - -tableau10_light = [ - 'lightsteelblue', # 0 - 'peachpuff', # 1 - 'lightgreen', # 2 - 'lightcoral', # 3 - 'thistle', # 4 - 'rosybrown', # 5 - 'lightpink', # 6 - 'lightgray', # 7 - 'palegoldenrod', # 8 - 'paleturquoise', # 9 -] - -tab10_index = [3, 0, 2, 1, 2, 4, 5, 6, 7, 8, 9] - - -class PlotScheme(object): - def __init__(self): - # to have a tight packing on the chart wether only the x axis or also - # the y axis have (see matplotlib) - self.ytight = False - - # y-margin (top/bottom) for the subcharts. This will not overrule the - # option plotinfo.plotymargin - self.yadjust = 0.0 - # Each new line is in z-order below the previous one. change it False - # to have lines paint above the previous line - self.zdown = True - # Rotation of the date labes on the x axis - self.tickrotation = 15 - - # How many "subparts" takes a major chart (datas) in the overall chart - # This is proportional to the total number of subcharts - self.rowsmajor = 5 - - # How many "subparts" takes a minor chart (indicators/observers) in the - # overall chart. This is proportional to the total number of subcharts - # Together with rowsmajor, this defines a proportion ratio betwen data - # charts and indicators/observers charts - self.rowsminor = 1 - - # Distance in between subcharts - self.plotdist = 0.0 - - # Have a grid in the background of all charts - self.grid = True - - # Default plotstyle for the OHLC bars which (line -> line on close) - # Other options: 'bar' and 'candle' - self.style = 'line' - - # Default color for the 'line on close' plot - self.loc = 'black' - # Default color for a bullish bar/candle (0.75 -> intensity of gray) - self.barup = '0.75' - # Default color for a bearish bar/candle - self.bardown = 'red' - # Level of transparency to apply to bars/cancles (NOT USED) - self.bartrans = 1.0 - - # Wether the candlesticks have to be filled or be transparent - self.barupfill = True - self.bardownfill = True - - # Opacity for the filled candlesticks (1.0 opaque - 0.0 transparent) - self.baralpha = 1.0 - - # Alpha blending for fill areas between lines (_fill_gt and _fill_lt) - self.fillalpha = 0.20 - - # Wether to plot volume or not. Note: if the data in question has no - # volume values, volume plotting will be skipped even if this is True - self.volume = True - - # Wether to overlay the volume on the data or use a separate subchart - self.voloverlay = True - # Scaling of the volume to the data when plotting as overlay - self.volscaling = 0.33 - # Pushing overlay volume up for better visibiliy. Experimentation - # needed if the volume and data overlap too much - self.volpushup = 0.00 - - # Default colour for the volume of a bullish day - self.volup = '#aaaaaa' # 0.66 of gray - # Default colour for the volume of a bearish day - self.voldown = '#cc6073' # (204, 96, 115) - # Transparency to apply to the volume when overlaying - self.voltrans = 0.50 - - # Transparency for text labels (NOT USED CURRENTLY) - self.subtxttrans = 0.66 - # Default font text size for labels on the chart - self.subtxtsize = 9 - - # Transparency for the legend (NOT USED CURRENTLY) - self.legendtrans = 0.25 - # Wether indicators have a leged displaey in their charts - self.legendind = True - # Location of the legend for indicators (see matplotlib) - self.legendindloc = 'upper left' - - # Location of the legend for datafeeds (see matplotlib) - self.legenddataloc = 'upper left' - - # Plot the last value of a line after the Object name - self.linevalues = True - - # Plot a tag at the end of each line with the last value - self.valuetags = True - - # Default color for horizontal lines (see plotinfo.plothlines) - self.hlinescolor = '0.66' # shade of gray - # Default style for horizontal lines - self.hlinesstyle = '--' - # Default width for horizontal lines - self.hlineswidth = 1.0 - - # Default color scheme: Tableau 10 - self.lcolors = tableau10 - - # strftime Format string for the display of ticks on the x axis - self.fmt_x_ticks = '%Y-%m-%d %H:%M' - - # strftime Format string for the display of data points values - self.fmt_x_data = None - - def color(self, idx): - colidx = tab10_index[idx % len(tab10_index)] - return self.lcolors[colidx] diff --git a/spaces/LightSY/W2L-TD/facelib/detection/retinaface/retinaface_utils.py b/spaces/LightSY/W2L-TD/facelib/detection/retinaface/retinaface_utils.py deleted file mode 100644 index 5fc7a505fad66f2903ce9f3cff06dea15b128080..0000000000000000000000000000000000000000 --- a/spaces/LightSY/W2L-TD/facelib/detection/retinaface/retinaface_utils.py +++ /dev/null @@ -1,478 +0,0 @@ -import numpy as np -# import torch -# import torchvision -from itertools import product as product -from math import ceil -from numpy import array - - -def box_area(boxes: array): - """ - :param boxes: [N, 4] - :return: [N] - """ - return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]) - - -def box_iou(box1: array, box2: array): - """ - :param box1: [N, 4] - :param box2: [M, 4] - :return: [N, M] - """ - area1 = box_area(box1) # N - area2 = box_area(box2) # M - # broadcasting, 两个数组各维度大小 从后往前对比一致, 或者 有一维度值为1; - lt = np.maximum(box1[:, np.newaxis, :2], box2[:, :2]) - rb = np.minimum(box1[:, np.newaxis, 2:], box2[:, 2:]) - wh = rb - lt - wh = np.maximum(0, wh) # [N, M, 2] - inter = wh[:, :, 0] * wh[:, :, 1] - iou = inter / (area1[:, np.newaxis] + area2 - inter) - return iou # NxM - - -def numpy_nms(boxes: array, scores: array, iou_threshold: float): - idxs = scores.argsort() # 按分数 降序排列的索引 [N] - keep = [] - while idxs.size > 0: # 统计数组中元素的个数 - max_score_index = idxs[-1] - max_score_box = boxes[max_score_index][None, :] - keep.append(max_score_index) - if idxs.size == 1: - break - idxs = idxs[:-1] # 将得分最大框 从索引中删除; 剩余索引对应的框 和 得分最大框 计算IoU; - other_boxes = boxes[idxs] # [?, 4] - ious = box_iou(max_score_box, other_boxes) # 一个框和其余框比较 1XM - idxs = idxs[ious[0] <= iou_threshold] - - keep = np.array(keep) - return keep - - -class PriorBox(object): - - def __init__(self, cfg, image_size=None, phase='train'): - super(PriorBox, self).__init__() - self.min_sizes = cfg['min_sizes'] - self.steps = cfg['steps'] - self.clip = cfg['clip'] - self.image_size = image_size - self.feature_maps = [[ceil(self.image_size[0] / step), ceil(self.image_size[1] / step)] for step in self.steps] - self.name = 's' - - def forward(self): - anchors = [] - for k, f in enumerate(self.feature_maps): - min_sizes = self.min_sizes[k] - for i, j in product(range(f[0]), range(f[1])): - for min_size in min_sizes: - s_kx = min_size / self.image_size[1] - s_ky = min_size / self.image_size[0] - dense_cx = [x * self.steps[k] / self.image_size[1] for x in [j + 0.5]] - dense_cy = [y * self.steps[k] / self.image_size[0] for y in [i + 0.5]] - for cy, cx in product(dense_cy, dense_cx): - anchors += [cx, cy, s_kx, s_ky] - - # back to torch land - # output = torch.Tensor(anchors).view(-1, 4) - output = np.array(anchors).reshape(-1, 4) - if self.clip: - output.clamp_(max=1, min=0) - return output - - -def py_cpu_nms(dets, thresh): - """Pure Python NMS baseline.""" - # keep = torchvision.ops.nms( - # boxes=torch.Tensor(dets[:, :4]), - # scores=torch.Tensor(dets[:, 4]), - # iou_threshold=thresh, - # ) - keep = numpy_nms(boxes=dets[:, :4], scores=dets[:, 4], iou_threshold=thresh) - return list(keep) - - -def point_form(boxes): - """ Convert prior_boxes to (xmin, ymin, xmax, ymax) - representation for comparison to point form ground truth data. - Args: - boxes: (tensor) center-size default boxes from priorbox layers. - Return: - boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes. - """ - return torch.cat( - ( - boxes[:, :2] - boxes[:, 2:] / 2, # xmin, ymin - boxes[:, :2] + boxes[:, 2:] / 2), - 1) # xmax, ymax - - -def center_size(boxes): - """ Convert prior_boxes to (cx, cy, w, h) - representation for comparison to center-size form ground truth data. - Args: - boxes: (tensor) point_form boxes - Return: - boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes. - """ - return torch.cat( - (boxes[:, 2:] + boxes[:, :2]) / 2, # cx, cy - boxes[:, 2:] - boxes[:, :2], - 1) # w, h - - -def intersect(box_a, box_b): - """ We resize both tensors to [A,B,2] without new malloc: - [A,2] -> [A,1,2] -> [A,B,2] - [B,2] -> [1,B,2] -> [A,B,2] - Then we compute the area of intersect between box_a and box_b. - Args: - box_a: (tensor) bounding boxes, Shape: [A,4]. - box_b: (tensor) bounding boxes, Shape: [B,4]. - Return: - (tensor) intersection area, Shape: [A,B]. - """ - A = box_a.size(0) - B = box_b.size(0) - max_xy = torch.min(box_a[:, 2:].unsqueeze(1).expand(A, B, 2), box_b[:, 2:].unsqueeze(0).expand(A, B, 2)) - min_xy = torch.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2), box_b[:, :2].unsqueeze(0).expand(A, B, 2)) - inter = torch.clamp((max_xy - min_xy), min=0) - return inter[:, :, 0] * inter[:, :, 1] - - -def jaccard(box_a, box_b): - """Compute the jaccard overlap of two sets of boxes. The jaccard overlap - is simply the intersection over union of two boxes. Here we operate on - ground truth boxes and default boxes. - E.g.: - A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B) - Args: - box_a: (tensor) Ground truth bounding boxes, Shape: [num_objects,4] - box_b: (tensor) Prior boxes from priorbox layers, Shape: [num_priors,4] - Return: - jaccard overlap: (tensor) Shape: [box_a.size(0), box_b.size(0)] - """ - inter = intersect(box_a, box_b) - area_a = ((box_a[:, 2] - box_a[:, 0]) * (box_a[:, 3] - box_a[:, 1])).unsqueeze(1).expand_as(inter) # [A,B] - area_b = ((box_b[:, 2] - box_b[:, 0]) * (box_b[:, 3] - box_b[:, 1])).unsqueeze(0).expand_as(inter) # [A,B] - union = area_a + area_b - inter - return inter / union # [A,B] - - -def matrix_iou(a, b): - """ - return iou of a and b, numpy version for data augenmentation - """ - lt = np.maximum(a[:, np.newaxis, :2], b[:, :2]) - rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:]) - - area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2) - area_a = np.prod(a[:, 2:] - a[:, :2], axis=1) - area_b = np.prod(b[:, 2:] - b[:, :2], axis=1) - return area_i / (area_a[:, np.newaxis] + area_b - area_i) - - -def matrix_iof(a, b): - """ - return iof of a and b, numpy version for data augenmentation - """ - lt = np.maximum(a[:, np.newaxis, :2], b[:, :2]) - rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:]) - - area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2) - area_a = np.prod(a[:, 2:] - a[:, :2], axis=1) - return area_i / np.maximum(area_a[:, np.newaxis], 1) - - -def match(threshold, truths, priors, variances, labels, landms, loc_t, conf_t, landm_t, idx): - """Match each prior box with the ground truth box of the highest jaccard - overlap, encode the bounding boxes, then return the matched indices - corresponding to both confidence and location preds. - Args: - threshold: (float) The overlap threshold used when matching boxes. - truths: (tensor) Ground truth boxes, Shape: [num_obj, 4]. - priors: (tensor) Prior boxes from priorbox layers, Shape: [n_priors,4]. - variances: (tensor) Variances corresponding to each prior coord, - Shape: [num_priors, 4]. - labels: (tensor) All the class labels for the image, Shape: [num_obj]. - landms: (tensor) Ground truth landms, Shape [num_obj, 10]. - loc_t: (tensor) Tensor to be filled w/ encoded location targets. - conf_t: (tensor) Tensor to be filled w/ matched indices for conf preds. - landm_t: (tensor) Tensor to be filled w/ encoded landm targets. - idx: (int) current batch index - Return: - The matched indices corresponding to 1)location 2)confidence - 3)landm preds. - """ - # jaccard index - overlaps = jaccard(truths, point_form(priors)) - # (Bipartite Matching) - # [1,num_objects] best prior for each ground truth - best_prior_overlap, best_prior_idx = overlaps.max(1, keepdim=True) - - # ignore hard gt - valid_gt_idx = best_prior_overlap[:, 0] >= 0.2 - best_prior_idx_filter = best_prior_idx[valid_gt_idx, :] - if best_prior_idx_filter.shape[0] <= 0: - loc_t[idx] = 0 - conf_t[idx] = 0 - return - - # [1,num_priors] best ground truth for each prior - best_truth_overlap, best_truth_idx = overlaps.max(0, keepdim=True) - best_truth_idx.squeeze_(0) - best_truth_overlap.squeeze_(0) - best_prior_idx.squeeze_(1) - best_prior_idx_filter.squeeze_(1) - best_prior_overlap.squeeze_(1) - best_truth_overlap.index_fill_(0, best_prior_idx_filter, 2) # ensure best prior - # TODO refactor: index best_prior_idx with long tensor - # ensure every gt matches with its prior of max overlap - for j in range(best_prior_idx.size(0)): # 判别此anchor是预测哪一个boxes - best_truth_idx[best_prior_idx[j]] = j - matches = truths[best_truth_idx] # Shape: [num_priors,4] 此处为每一个anchor对应的bbox取出来 - conf = labels[best_truth_idx] # Shape: [num_priors] 此处为每一个anchor对应的label取出来 - conf[best_truth_overlap < threshold] = 0 # label as background overlap<0.35的全部作为负样本 - loc = encode(matches, priors, variances) - - matches_landm = landms[best_truth_idx] - landm = encode_landm(matches_landm, priors, variances) - loc_t[idx] = loc # [num_priors,4] encoded offsets to learn - conf_t[idx] = conf # [num_priors] top class label for each prior - landm_t[idx] = landm - - -def encode(matched, priors, variances): - """Encode the variances from the priorbox layers into the ground truth boxes - we have matched (based on jaccard overlap) with the prior boxes. - Args: - matched: (tensor) Coords of ground truth for each prior in point-form - Shape: [num_priors, 4]. - priors: (tensor) Prior boxes in center-offset form - Shape: [num_priors,4]. - variances: (list[float]) Variances of priorboxes - Return: - encoded boxes (tensor), Shape: [num_priors, 4] - """ - - # dist b/t match center and prior's center - g_cxcy = (matched[:, :2] + matched[:, 2:]) / 2 - priors[:, :2] - # encode variance - g_cxcy /= (variances[0] * priors[:, 2:]) - # match wh / prior wh - g_wh = (matched[:, 2:] - matched[:, :2]) / priors[:, 2:] - g_wh = torch.log(g_wh) / variances[1] - # return target for smooth_l1_loss - return torch.cat([g_cxcy, g_wh], 1) # [num_priors,4] - - -def encode_landm(matched, priors, variances): - """Encode the variances from the priorbox layers into the ground truth boxes - we have matched (based on jaccard overlap) with the prior boxes. - Args: - matched: (tensor) Coords of ground truth for each prior in point-form - Shape: [num_priors, 10]. - priors: (tensor) Prior boxes in center-offset form - Shape: [num_priors,4]. - variances: (list[float]) Variances of priorboxes - Return: - encoded landm (tensor), Shape: [num_priors, 10] - """ - - # dist b/t match center and prior's center - matched = torch.reshape(matched, (matched.size(0), 5, 2)) - priors_cx = priors[:, 0].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2) - priors_cy = priors[:, 1].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2) - priors_w = priors[:, 2].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2) - priors_h = priors[:, 3].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2) - priors = torch.cat([priors_cx, priors_cy, priors_w, priors_h], dim=2) - g_cxcy = matched[:, :, :2] - priors[:, :, :2] - # encode variance - g_cxcy /= (variances[0] * priors[:, :, 2:]) - # g_cxcy /= priors[:, :, 2:] - g_cxcy = g_cxcy.reshape(g_cxcy.size(0), -1) - # return target for smooth_l1_loss - return g_cxcy - - -# Adapted from https://github.com/Hakuyume/chainer-ssd -def decode(loc, priors, variances): - """Decode locations from predictions using priors to undo - the encoding we did for offset regression at train time. - Args: - loc (tensor): location predictions for loc layers, - Shape: [num_priors,4] - priors (tensor): Prior boxes in center-offset form. - Shape: [num_priors,4]. - variances: (list[float]) Variances of priorboxes - Return: - decoded bounding box predictions - """ - - # boxes = torch.cat((priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:], - # priors[:, 2:] * torch.exp(loc[:, 2:] * variances[1])), 1) - - boxes = np.concatenate((priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:], - priors[:, 2:] * np.exp(loc[:, 2:] * variances[1])), 1) - - - boxes[:, :2] -= boxes[:, 2:] / 2 - boxes[:, 2:] += boxes[:, :2] - return boxes - - -def decode_landm(pre, priors, variances): - """Decode landm from predictions using priors to undo - the encoding we did for offset regression at train time. - Args: - pre (tensor): landm predictions for loc layers, - Shape: [num_priors,10] - priors (tensor): Prior boxes in center-offset form. - Shape: [num_priors,4]. - variances: (list[float]) Variances of priorboxes - Return: - decoded landm predictions - """ - tmp = ( - priors[:, :2] + pre[:, :2] * variances[0] * priors[:, 2:], - priors[:, :2] + pre[:, 2:4] * variances[0] * priors[:, 2:], - priors[:, :2] + pre[:, 4:6] * variances[0] * priors[:, 2:], - priors[:, :2] + pre[:, 6:8] * variances[0] * priors[:, 2:], - priors[:, :2] + pre[:, 8:10] * variances[0] * priors[:, 2:], - ) - # landms = torch.cat(tmp, dim=1) - landms = np.concatenate(tmp, axis=1) - return landms - - -def batched_decode(b_loc, priors, variances): - """Decode locations from predictions using priors to undo - the encoding we did for offset regression at train time. - Args: - b_loc (tensor): location predictions for loc layers, - Shape: [num_batches,num_priors,4] - priors (tensor): Prior boxes in center-offset form. - Shape: [1,num_priors,4]. - variances: (list[float]) Variances of priorboxes - Return: - decoded bounding box predictions - """ - # boxes = ( - # priors[:, :, :2] + b_loc[:, :, :2] * variances[0] * priors[:, :, 2:], - # priors[:, :, 2:] * torch.exp(b_loc[:, :, 2:] * variances[1]), - # ) - # boxes = torch.cat(boxes, dim=2) - boxes = ( - priors[:, :, :2] + b_loc[:, :, :2] * variances[0] * priors[:, :, 2:], - priors[:, :, 2:] * np.exp(b_loc[:, :, 2:] * variances[1]), - ) - boxes = np.concatenate(boxes, axis=2) - - boxes[:, :, :2] -= boxes[:, :, 2:] / 2 - boxes[:, :, 2:] += boxes[:, :, :2] - return boxes - - -def batched_decode_landm(pre, priors, variances): - """Decode landm from predictions using priors to undo - the encoding we did for offset regression at train time. - Args: - pre (tensor): landm predictions for loc layers, - Shape: [num_batches,num_priors,10] - priors (tensor): Prior boxes in center-offset form. - Shape: [1,num_priors,4]. - variances: (list[float]) Variances of priorboxes - Return: - decoded landm predictions - """ - landms = ( - priors[:, :, :2] + pre[:, :, :2] * variances[0] * priors[:, :, 2:], - priors[:, :, :2] + pre[:, :, 2:4] * variances[0] * priors[:, :, 2:], - priors[:, :, :2] + pre[:, :, 4:6] * variances[0] * priors[:, :, 2:], - priors[:, :, :2] + pre[:, :, 6:8] * variances[0] * priors[:, :, 2:], - priors[:, :, :2] + pre[:, :, 8:10] * variances[0] * priors[:, :, 2:], - ) - landms = torch.cat(landms, dim=2) - return landms - - -def log_sum_exp(x): - """Utility function for computing log_sum_exp while determining - This will be used to determine unaveraged confidence loss across - all examples in a batch. - Args: - x (Variable(tensor)): conf_preds from conf layers - """ - x_max = x.data.max() - return torch.log(torch.sum(torch.exp(x - x_max), 1, keepdim=True)) + x_max - - -# Original author: Francisco Massa: -# https://github.com/fmassa/object-detection.torch -# Ported to PyTorch by Max deGroot (02/01/2017) -def nms(boxes, scores, overlap=0.5, top_k=200): - """Apply non-maximum suppression at test time to avoid detecting too many - overlapping bounding boxes for a given object. - Args: - boxes: (tensor) The location preds for the img, Shape: [num_priors,4]. - scores: (tensor) The class predscores for the img, Shape:[num_priors]. - overlap: (float) The overlap thresh for suppressing unnecessary boxes. - top_k: (int) The Maximum number of box preds to consider. - Return: - The indices of the kept boxes with respect to num_priors. - """ - - keep = torch.Tensor(scores.size(0)).fill_(0).long() - if boxes.numel() == 0: - return keep - x1 = boxes[:, 0] - y1 = boxes[:, 1] - x2 = boxes[:, 2] - y2 = boxes[:, 3] - area = torch.mul(x2 - x1, y2 - y1) - v, idx = scores.sort(0) # sort in ascending order - # I = I[v >= 0.01] - idx = idx[-top_k:] # indices of the top-k largest vals - xx1 = boxes.new() - yy1 = boxes.new() - xx2 = boxes.new() - yy2 = boxes.new() - w = boxes.new() - h = boxes.new() - - # keep = torch.Tensor() - count = 0 - while idx.numel() > 0: - i = idx[-1] # index of current largest val - # keep.append(i) - keep[count] = i - count += 1 - if idx.size(0) == 1: - break - idx = idx[:-1] # remove kept element from view - # load bboxes of next highest vals - torch.index_select(x1, 0, idx, out=xx1) - torch.index_select(y1, 0, idx, out=yy1) - torch.index_select(x2, 0, idx, out=xx2) - torch.index_select(y2, 0, idx, out=yy2) - # store element-wise max with next highest score - xx1 = torch.clamp(xx1, min=x1[i]) - yy1 = torch.clamp(yy1, min=y1[i]) - xx2 = torch.clamp(xx2, max=x2[i]) - yy2 = torch.clamp(yy2, max=y2[i]) - w.resize_as_(xx2) - h.resize_as_(yy2) - w = xx2 - xx1 - h = yy2 - yy1 - # check sizes of xx1 and xx2.. after each iteration - w = torch.clamp(w, min=0.0) - h = torch.clamp(h, min=0.0) - inter = w * h - # IoU = i / (area(a) + area(b) - i) - rem_areas = torch.index_select(area, 0, idx) # load remaining areas) - union = (rem_areas - inter) + area[i] - IoU = inter / union # store result in iou - # keep only elements with an IoU <= overlap - idx = idx[IoU.le(overlap)] - return keep, count diff --git a/spaces/Lijiahui/bingAI/Dockerfile b/spaces/Lijiahui/bingAI/Dockerfile deleted file mode 100644 index d3bb59c4379a753da705c5b0783adedb89a0a6ab..0000000000000000000000000000000000000000 --- a/spaces/Lijiahui/bingAI/Dockerfile +++ /dev/null @@ -1,34 +0,0 @@ -# Build Stage -# 使用 golang:alpine 作为构建阶段的基础镜像 -FROM golang:alpine AS builder - -# 添加 git,以便之后能从GitHub克隆项目 -RUN apk --no-cache add git - -# 从 GitHub 克隆 go-proxy-bingai 项目到 /workspace/app 目录下 -RUN git clone https://github.com/Harry-zklcdc/go-proxy-bingai.git /workspace/app - -# 设置工作目录为之前克隆的项目目录 -WORKDIR /workspace/app - -# 编译 go 项目。-ldflags="-s -w" 是为了减少编译后的二进制大小 -RUN go build -ldflags="-s -w" -tags netgo -trimpath -o go-proxy-bingai main.go - -# Runtime Stage -# 使用轻量级的 alpine 镜像作为运行时的基础镜像 -FROM alpine - -# 设置工作目录 -WORKDIR /workspace/app - -# 从构建阶段复制编译后的二进制文件到运行时镜像中 -COPY --from=builder /workspace/app/go-proxy-bingai . - -# 设置环境变量,此处为随机字符 -ENV Go_Proxy_BingAI_USER_TOKEN_1="kJs8hD92ncMzLaoQWYtX5rG6bEL9J09R26D" - -# 暴露8080端口 -EXPOSE 8080 - -# 容器启动时运行的命令 -CMD ["/workspace/app/go-proxy-bingai"] \ No newline at end of file diff --git a/spaces/Liu-LAB/GPT-academic/crazy_functions/vt_fns/vt_state.py b/spaces/Liu-LAB/GPT-academic/crazy_functions/vt_fns/vt_state.py deleted file mode 100644 index 18187286383ce2f3e881510852cf3aba7e6c43d1..0000000000000000000000000000000000000000 --- a/spaces/Liu-LAB/GPT-academic/crazy_functions/vt_fns/vt_state.py +++ /dev/null @@ -1,28 +0,0 @@ -import pickle - -class VoidTerminalState(): - def __init__(self): - self.reset_state() - - def reset_state(self): - self.has_provided_explaination = False - - def lock_plugin(self, chatbot): - chatbot._cookies['lock_plugin'] = 'crazy_functions.虚空终端->虚空终端' - chatbot._cookies['plugin_state'] = pickle.dumps(self) - - def unlock_plugin(self, chatbot): - self.reset_state() - chatbot._cookies['lock_plugin'] = None - chatbot._cookies['plugin_state'] = pickle.dumps(self) - - def set_state(self, chatbot, key, value): - setattr(self, key, value) - chatbot._cookies['plugin_state'] = pickle.dumps(self) - - def get_state(chatbot): - state = chatbot._cookies.get('plugin_state', None) - if state is not None: state = pickle.loads(state) - else: state = VoidTerminalState() - state.chatbot = chatbot - return state \ No newline at end of file diff --git a/spaces/Mahiruoshi/Lovelive_Nijigasaki_VITS/export.py b/spaces/Mahiruoshi/Lovelive_Nijigasaki_VITS/export.py deleted file mode 100644 index 6ab01ef1fd122dfba0cad8a05468eb5d6cc5677b..0000000000000000000000000000000000000000 --- a/spaces/Mahiruoshi/Lovelive_Nijigasaki_VITS/export.py +++ /dev/null @@ -1,38 +0,0 @@ -import ONNXVITS_models -import utils -from text.symbols import symbols -from text import text_to_sequence -import torch -import commons - -def get_text(text, hps): - text_norm = text_to_sequence(text, symbols, hps.data.text_cleaners) - if hps.data.add_blank: - text_norm = commons.intersperse(text_norm, 0) - text_norm = torch.LongTensor(text_norm) - return text_norm - -def get_label(text, label): - if f'[{label}]' in text: - return True, text.replace(f'[{label}]', '') - else: - return False, text - -hps_ms = utils.get_hparams_from_file("/content/drive/MyDrive/moe/config.json") -net_g_ms = ONNXVITS_models.SynthesizerTrn( - len(symbols), - hps_ms.data.filter_length // 2 + 1, - hps_ms.train.segment_size // hps_ms.data.hop_length, - n_speakers=hps_ms.data.n_speakers, - **hps_ms.model) -_ = net_g_ms.eval() - -_ = utils.load_checkpoint("/content/drive/MyDrive/moe/G_909000.pth", net_g_ms) - -text1 = get_text("[JA]ありがとうございます。[JA]", hps_ms) -stn_tst = text1 -with torch.no_grad(): - x_tst = stn_tst.unsqueeze(0) - x_tst_lengths = torch.LongTensor([stn_tst.size(0)]) - sid = torch.tensor([0]) - o = net_g_ms(x_tst, x_tst_lengths, sid=sid, noise_scale=.667, noise_scale_w=0.8, length_scale=1) \ No newline at end of file diff --git a/spaces/Mahiruoshi/Lovelive_Nijigasaki_VITS/text/cleaners.py b/spaces/Mahiruoshi/Lovelive_Nijigasaki_VITS/text/cleaners.py deleted file mode 100644 index 7358b44249ffaef44c50c309b0fbb52c7527d547..0000000000000000000000000000000000000000 --- a/spaces/Mahiruoshi/Lovelive_Nijigasaki_VITS/text/cleaners.py +++ /dev/null @@ -1,176 +0,0 @@ -import re -#from text.english import english_to_lazy_ipa, english_to_ipa2, english_to_lazy_ipa2 -from text.japanese import japanese_to_romaji_with_accent, japanese_to_ipa, japanese_to_ipa2, japanese_to_ipa3 -from text.mandarin import number_to_chinese, chinese_to_bopomofo, latin_to_bopomofo, chinese_to_romaji, chinese_to_lazy_ipa, chinese_to_ipa, chinese_to_ipa2 -# from text.sanskrit import devanagari_to_ipa -# from text.english import english_to_lazy_ipa, english_to_ipa2, english_to_lazy_ipa2 -# from text.thai import num_to_thai, latin_to_thai -# from text.shanghainese import shanghainese_to_ipa -# from text.cantonese import cantonese_to_ipa -# from text.ngu_dialect import ngu_dialect_to_ipa - - -def japanese_cleaners(text): - text = japanese_to_romaji_with_accent(text) - if re.match('[A-Za-z]', text[-1]): - text += '.' - return text - - -def japanese_cleaners2(text): - return japanese_cleaners(text).replace('ts', 'ʦ').replace('...', '…') - - -def korean_cleaners(text): - '''Pipeline for Korean text''' - text = latin_to_hangul(text) - text = number_to_hangul(text) - text = divide_hangul(text) - if re.match('[\u3131-\u3163]', text[-1]): - text += '.' - return text - - -def chinese_cleaners(text): - '''Pipeline for Chinese text''' - text = number_to_chinese(text) - text = chinese_to_bopomofo(text) - text = latin_to_bopomofo(text) - if re.match('[ˉˊˇˋ˙]', text[-1]): - text += '。' - return text - - -def zh_ja_mixture_cleaners(text): - chinese_texts = re.findall(r'\[ZH\].*?\[ZH\]', text) - japanese_texts = re.findall(r'\[JA\].*?\[JA\]', text) - for chinese_text in chinese_texts: - cleaned_text = chinese_to_romaji(chinese_text[4:-4]) - text = text.replace(chinese_text, cleaned_text+' ', 1) - for japanese_text in japanese_texts: - cleaned_text = japanese_to_romaji_with_accent( - japanese_text[4:-4]).replace('ts', 'ʦ').replace('u', 'ɯ').replace('...', '…') - text = text.replace(japanese_text, cleaned_text+' ', 1) - text = text[:-1] - if re.match('[A-Za-zɯɹəɥ→↓↑]', text[-1]): - text += '.' - return text - - -def sanskrit_cleaners(text): - text = text.replace('॥', '।').replace('ॐ', 'ओम्') - if text[-1] != '।': - text += ' ।' - return text - - -def cjks_cleaners(text): - chinese_texts = re.findall(r'\[ZH\].*?\[ZH\]', text) - japanese_texts = re.findall(r'\[JA\].*?\[JA\]', text) - korean_texts = re.findall(r'\[KO\].*?\[KO\]', text) - sanskrit_texts = re.findall(r'\[SA\].*?\[SA\]', text) - english_texts = re.findall(r'\[EN\].*?\[EN\]', text) - for chinese_text in chinese_texts: - cleaned_text = chinese_to_lazy_ipa(chinese_text[4:-4]) - text = text.replace(chinese_text, cleaned_text+' ', 1) - for japanese_text in japanese_texts: - cleaned_text = japanese_to_ipa(japanese_text[4:-4]) - text = text.replace(japanese_text, cleaned_text+' ', 1) - for korean_text in korean_texts: - cleaned_text = korean_to_lazy_ipa(korean_text[4:-4]) - text = text.replace(korean_text, cleaned_text+' ', 1) - for sanskrit_text in sanskrit_texts: - cleaned_text = devanagari_to_ipa(sanskrit_text[4:-4]) - text = text.replace(sanskrit_text, cleaned_text+' ', 1) - for english_text in english_texts: - cleaned_text = english_to_lazy_ipa(english_text[4:-4]) - text = text.replace(english_text, cleaned_text+' ', 1) - text = text[:-1] - if re.match(r'[^\.,!\?\-…~]', text[-1]): - text += '.' - return text - - -def cjke_cleaners(text): - chinese_texts = re.findall(r'\[ZH\].*?\[ZH\]', text) - japanese_texts = re.findall(r'\[JA\].*?\[JA\]', text) - korean_texts = re.findall(r'\[KO\].*?\[KO\]', text) - english_texts = re.findall(r'\[EN\].*?\[EN\]', text) - for chinese_text in chinese_texts: - cleaned_text = chinese_to_lazy_ipa(chinese_text[4:-4]) - cleaned_text = cleaned_text.replace( - 'ʧ', 'tʃ').replace('ʦ', 'ts').replace('ɥan', 'ɥæn') - text = text.replace(chinese_text, cleaned_text+' ', 1) - for japanese_text in japanese_texts: - cleaned_text = japanese_to_ipa(japanese_text[4:-4]) - cleaned_text = cleaned_text.replace('ʧ', 'tʃ').replace( - 'ʦ', 'ts').replace('ɥan', 'ɥæn').replace('ʥ', 'dz') - text = text.replace(japanese_text, cleaned_text+' ', 1) - for korean_text in korean_texts: - cleaned_text = korean_to_ipa(korean_text[4:-4]) - text = text.replace(korean_text, cleaned_text+' ', 1) - #for english_text in english_texts: - # cleaned_text = english_to_ipa2(english_text[4:-4]) - # cleaned_text = cleaned_text.replace('ɑ', 'a').replace( - # 'ɔ', 'o').replace('ɛ', 'e').replace('ɪ', 'i').replace('ʊ', 'u') - # text = text.replace(english_text, cleaned_text+' ', 1) - text = text[:-1] - if re.match(r'[^\.,!\?\-…~]', text[-1]): - text += '.' - return text - - -def cjke_cleaners2(text): - chinese_texts = re.findall(r'\[ZH\].*?\[ZH\]', text) - japanese_texts = re.findall(r'\[JA\].*?\[JA\]', text) - korean_texts = re.findall(r'\[KO\].*?\[KO\]', text) - english_texts = re.findall(r'\[EN\].*?\[EN\]', text) - for chinese_text in chinese_texts: - cleaned_text = chinese_to_ipa(chinese_text[4:-4]) - text = text.replace(chinese_text, cleaned_text+' ', 1) - for japanese_text in japanese_texts: - cleaned_text = japanese_to_ipa2(japanese_text[4:-4]) - text = text.replace(japanese_text, cleaned_text+' ', 1) - for korean_text in korean_texts: - cleaned_text = korean_to_ipa(korean_text[4:-4]) - text = text.replace(korean_text, cleaned_text+' ', 1) - for english_text in english_texts: - cleaned_text = english_to_ipa2(english_text[4:-4]) - text = text.replace(english_text, cleaned_text+' ', 1) - text = text[:-1] - if re.match(r'[^\.,!\?\-…~]', text[-1]): - text += '.' - return text - - -def thai_cleaners(text): - text = num_to_thai(text) - text = latin_to_thai(text) - return text - - -def shanghainese_cleaners(text): - text = shanghainese_to_ipa(text) - if re.match(r'[^\.,!\?\-…~]', text[-1]): - text += '.' - return text - - -def chinese_dialect_cleaners(text): - text = re.sub(r'\[MD\](.*?)\[MD\]', - lambda x: chinese_to_ipa2(x.group(1))+' ', text) - text = re.sub(r'\[TW\](.*?)\[TW\]', - lambda x: chinese_to_ipa2(x.group(1), True)+' ', text) - text = re.sub(r'\[JA\](.*?)\[JA\]', - lambda x: japanese_to_ipa3(x.group(1)).replace('Q', 'ʔ')+' ', text) - text = re.sub(r'\[SH\](.*?)\[SH\]', lambda x: shanghainese_to_ipa(x.group(1)).replace('1', '˥˧').replace('5', - '˧˧˦').replace('6', '˩˩˧').replace('7', '˥').replace('8', '˩˨').replace('ᴀ', 'ɐ').replace('ᴇ', 'e')+' ', text) - text = re.sub(r'\[GD\](.*?)\[GD\]', - lambda x: cantonese_to_ipa(x.group(1))+' ', text) - text = re.sub(r'\[EN\](.*?)\[EN\]', - lambda x: english_to_lazy_ipa2(x.group(1))+' ', text) - text = re.sub(r'\[([A-Z]{2})\](.*?)\[\1\]', lambda x: ngu_dialect_to_ipa(x.group(2), x.group( - 1)).replace('ʣ', 'dz').replace('ʥ', 'dʑ').replace('ʦ', 'ts').replace('ʨ', 'tɕ')+' ', text) - text = re.sub(r'\s+$', '', text) - text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text) - return text diff --git a/spaces/Make-A-Protagonist/Make-A-Protagonist-inference/Make-A-Protagonist/experts/XMem/dataset/range_transform.py b/spaces/Make-A-Protagonist/Make-A-Protagonist-inference/Make-A-Protagonist/experts/XMem/dataset/range_transform.py deleted file mode 100644 index ae1b0b3b2a01a061b9b2220a93cdf7f7a6357bfb..0000000000000000000000000000000000000000 --- a/spaces/Make-A-Protagonist/Make-A-Protagonist-inference/Make-A-Protagonist/experts/XMem/dataset/range_transform.py +++ /dev/null @@ -1,12 +0,0 @@ -import torchvision.transforms as transforms - -im_mean = (124, 116, 104) - -im_normalization = transforms.Normalize( - mean=[0.485, 0.456, 0.406], - std=[0.229, 0.224, 0.225] - ) - -inv_im_trans = transforms.Normalize( - mean=[-0.485/0.229, -0.456/0.224, -0.406/0.225], - std=[1/0.229, 1/0.224, 1/0.225]) diff --git a/spaces/MarkMcCormack/Automated-Grading-Dashboard/app.py b/spaces/MarkMcCormack/Automated-Grading-Dashboard/app.py deleted file mode 100644 index bc2f7ca7387acda506545b95de28e83536eb0dd4..0000000000000000000000000000000000000000 --- a/spaces/MarkMcCormack/Automated-Grading-Dashboard/app.py +++ /dev/null @@ -1,60 +0,0 @@ -import streamlit as st -from studentDashboard import run as studentDashboardRun -from teacherDashboard import run as teacherDashboardRun -from langchain.llms import OpenAI -from langchain.chains import LLMChain -import pymongo -import utils - -st.set_page_config( - page_title="LLM/GPT Teacher Dashboard for Pedagogical Analysis of Students", - page_icon="🧮", - layout="wide", -) - -left, right = st.columns(2) - -def main(): - import studentDashboard as studentDashboard - - st.title("🤖🧮 LLM/GPT Teacher Dashboard for Pedagogical Analysis of Students") - - with left: - api_key = st.text_input("Enter your API key", type="password") - - if st.button("Submit API Key!"): - if api_key: - studentDashboard.llmOpenAI = OpenAI(openai_api_key=api_key, temperature=0.9) - studentDashboard.chain = LLMChain(llm=studentDashboard.llmOpenAI, prompt=studentDashboard.promptTemplate) - st.success("API key submitted successfully!") - else: - st.error("Please enter your API key.") - - with right: - db_credentials = st.text_input("Enter your MongoDB credentials", type="password") - - if st.button("Submit Credentials!") and not utils.database: - if db_credentials: - utils.database = pymongo.MongoClient(db_credentials) - st.success("Credentials submitted successfully!") - else: - st.error("Please enter your credentials.") - - studentDashboard, teacherDashboard, studentGroup = st.tabs([ - "Individual Student Profile", - "Teacher Classroom Dashboard", - "Student Group Dashboard" - ]) - - with studentDashboard: - studentDashboardRun() - - with teacherDashboard: - teacherDashboardRun() - - with studentGroup: - #run() - pass - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/spaces/Mayanand/emotion-recognition/face_module.py b/spaces/Mayanand/emotion-recognition/face_module.py deleted file mode 100644 index 19c83c1cd245d4a92db5215a1ad2649a14ebf1f6..0000000000000000000000000000000000000000 --- a/spaces/Mayanand/emotion-recognition/face_module.py +++ /dev/null @@ -1,24 +0,0 @@ -import mediapipe as mp -mp_face_detection = mp.solutions.face_detection - -def get_face_coords(image): - with mp_face_detection.FaceDetection( - model_selection=1, min_detection_confidence=0.5) as face_detection: - #image = cv2.imread(file) - # Convert the BGR image to RGB and process it with MediaPipe Face Detection. - results = face_detection.process(image) - # Draw face detections of each face. - if not results.detections: - return False - - # shape of image - h, w, _ = image.shape - - t = results.detections[0].location_data.relative_bounding_box - height = t.height * h - ymin = t.ymin * h - width = t.width * w - xmin = t.xmin * w - xmax = xmin + width - ymax = ymin + height - return int(xmin), int(ymin), int(xmax), int(ymax) \ No newline at end of file diff --git a/spaces/Mellow-ai/PhotoAI_Mellow/annotator/uniformer/mmcv_custom/__init__.py b/spaces/Mellow-ai/PhotoAI_Mellow/annotator/uniformer/mmcv_custom/__init__.py deleted file mode 100644 index 4b958738b9fd93bfcec239c550df1d9a44b8c536..0000000000000000000000000000000000000000 --- a/spaces/Mellow-ai/PhotoAI_Mellow/annotator/uniformer/mmcv_custom/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# -*- coding: utf-8 -*- - -from .checkpoint import load_checkpoint - -__all__ = ['load_checkpoint'] \ No newline at end of file diff --git a/spaces/Milancheeks/AI_Music_Team/app.py b/spaces/Milancheeks/AI_Music_Team/app.py deleted file mode 100644 index de81bdc0581576427849217a82ca2121a035f5a8..0000000000000000000000000000000000000000 --- a/spaces/Milancheeks/AI_Music_Team/app.py +++ /dev/null @@ -1,307 +0,0 @@ -import openai - - -ai_role_dict = { -"music_director": "You are an Experienced Music Director who has 15+ Years experience in the industry", -"lyricist": "You are an Experienced Lyricist, who has written hit songs in several languages", -"freelance_lyricist": "You are an Experienced Freelance Lyricist, who has helped writing songs in several languages", -"music_composer": "You are an Experienced Music Composer, who has composed songs of several genre and arrangements over the years", -"sound_engineer": "You are an Experienced Sound Engineer, who can provide expert feedback on the arrangement being used." -} - -languages = [ -"Afrikaans", -"Albanian", -"Amharic", -"Arabic", -"Armenian", -"Assamese", -"Aymara", -"Azerbaijani", -"Bhojpuri", -"Basque", -"Belarusian", -"Bengali", -"Bambara", -"Bosnian", -"Bulgarian", -"Burmese (Myanmar)", -"Catalan", -"Cebuano", -"Chewa (Chichewa)", -"Chinese (Simplified)", -"Chinese (Traditional)", -"Corsican", -"Croatian", -"Czech", -"Danish", -"Dogri", -"Dutch", -"English", -"Esperanto", -"Estonian", -"Ewe", -"Finnish", -"French", -"Galician", -"Georgian", -"German", -"Greek", -"Guarani", -"Gujarati", -"Haitian Creole", -"Hausa", -"Hawaiian", -"Hebrew", -"Hindi", -"Hmong", -"Hungarian", -"Icelandic", -"Igbo", -"Ilocano", -"Indonesian", -"Irish", -"Italian", -"Japanese", -"Javanese", -"Kannada", -"Kazakh", -"Khmer", -"Kinyarwanda", -"Konkani", -"Korean", -"Krio", -"Kurdish (Kurmanji)", -"Kurdish (Sorani)", -"Kyrgyz", -"Lao", -"Latin", -"Latvian", -"Lingala", -"Lithuanian", -"Luganda", -"Luxembourgish", -"Macedonian", -"Maithili", -"Malagasy", -"Malay", -"Malayalam", -"Maldivian (Dhivehi)", -"Maltese", -"Māori (Maori)", -"Marathi", -"Meitei (Manipuri, Meiteilon)", -"Mizo", -"Mongolian", -"Nepali", -"Northern Sotho (Sepedi)", -"Norwegian (Bokmål)", -"Odia (Oriya)", -"Oromo", -"Pashto", -"Persian", -"Polish", -"Portuguese", -"Punjabi (Gurmukhi)", -"Quechua", -"Romanian", -"Russian", -"Samoan", -"Sanskrit", -"Scottish Gaelic (Scots Gaelic)", -"Serbian", -"Shona", -"Sindhi", -"Sinhala", -"Slovak", -"Slovenian", -"Somali", -"Sotho (Sesotho)", -"Spanish", -"Sundanese", -"Swahili", -"Swedish", -"Tagalog (Filipino)", -"Tajik", -"Tamil", -"Tatar", -"Telugu", -"Thai", -"Tigrinya", -"Tsonga", -"Turkish", -"Turkmen", -"Twi", -"Ukrainian", -"Urdu", -"Uyghur", -"Uzbek", -"Vietnamese", -"Welsh", -"West Frisian (Frisian)", -"Xhosa", -"Yiddish", -"Yoruba", -"Zulu" -] - -from tenacity import ( - retry, - stop_after_attempt, - wait_random_exponential, -) # for exponential backoff - -@retry(wait=wait_random_exponential(min=1, max=100), stop=stop_after_attempt(8)) -def get_response(ai_role, query, model): - - response = openai.ChatCompletion.create( - model=model, - messages=[ - {"role": "system", "content": "{}".format(ai_role)}, - {"role": "user", "content": "{}".format(query)}, - ] - ) - - return response['choices'][0]['message']['content'] - -def write_intermediate_outputs(filename, text): - with open(filename, 'w') as fw: - fw.write(text) - - sample_file_path = f'./{filename}' - - return sample_file_path - -def write_and_compose(model, api_key, language, genre, keywords, emotion): - openai.api_key = api_key - initial_lyrics = get_response(ai_role_dict['freelance_lyricist'], "Write structured lyrics of a {} {} song with the following keywords - {}, and use the following emotion - {}".format(language, genre, keywords, emotion), model) - - query_feedback = '''The Freelance Lyricist submitted these lyrics: - -{} - -Provide suitable feedback (in bullet-points) -''' - - feedback1 = get_response(ai_role_dict['music_director'], query_feedback.format(initial_lyrics), model) - feedback2 = get_response(ai_role_dict['lyricist'], query_feedback.format(initial_lyrics), model) - - # Workflow: Step 3 - - feedback = '''After seeing the lyrics you initially submitted - - -{} - -the music director provided the following feedback - -{} - -the lyricist provided the following feedback as well - -{} - -Incorporate this feedback, and make suggested changes to the lyrics based on the feedback only -''' - - final_lyrics = get_response(ai_role_dict['freelance_lyricist'], feedback.format(initial_lyrics, feedback1, feedback2), model) - - # Workflow: Step 4 - - query_composer = '''Given the lyrics of the {} {} song on {} in the emotion - {} - - -{} - -write a suitable chord progression (for each line of the same lyrics), followed by the suitable arrangement required to sing and record the song (in bullet points)''' - - composition_1 = get_response(ai_role_dict['music_composer'], query_composer.format(language, genre, keywords, emotion, final_lyrics), model) - - query_sound_engineer = '''Given the lyrics of the {} {} song on {} in the emotion - {} - - -{} - -with a Chord Progression and Arrangement (suggested by the Music Composer) - - -{} - -could you write improvements that could be made to the Arrangement (in bullet points)? If the current arrangement is upto the mark, write "No change in the arrangement required" -''' - - composition_2 = get_response(ai_role_dict['sound_engineer'], query_sound_engineer.format(language, genre, keywords, emotion, final_lyrics, composition_1), model) - - final_query = '''Given the lyrics of the {} {} song on {} in the emotion - {} - - -{} - -with a Chord Progression and Arrangement (suggested by the Music Composer) - - -{} - -and further improvements on the Arrangement (suggested by the Sound Engineer) - -{} - -- suggest any further improvements that could be made to the (a) Chord Progression (b) Arrangement. -- After that, Write 10 "="s in the next line -- After that, Write the final Chord Progression and Arrangement -- Also, write a suitable title for the song - -''' - - final_response = get_response(ai_role_dict['music_director'], final_query.format(language, genre, keywords, emotion, final_lyrics, composition_1, composition_2), model) - - final_improvements = final_response.split('==========')[0] - - final_chord_prog_and_composition = final_response.split('==========')[-1] - - # return initial_lyrics, feedback1, feedback2, final_lyrics, composition_1, composition_2, final_improvements, final_chord_prog_and_composition - - output_file_list = [] - output_file_list.append(write_intermediate_outputs('step_2.txt', initial_lyrics)) - output_file_list.append(write_intermediate_outputs('step_3A.txt', feedback1)) - output_file_list.append(write_intermediate_outputs('step_3B.txt', feedback2)) - output_file_list.append(write_intermediate_outputs('step_5.txt', composition_1)) - output_file_list.append(write_intermediate_outputs('step_6.txt', composition_2)) - output_file_list.append(write_intermediate_outputs('step_7.txt', final_improvements)) - - return final_lyrics, final_chord_prog_and_composition, output_file_list - -import gradio as gr - -description = ''' - -# Objective - - -Given specific Language, Genre, Keywords, and Emotion of your choice, make a Brand New Song without lifting a finger! - -1. Get lyrics of a new song -2. Get a suitable chord progression -3. Get a suitable musical arrangement for singing and recording the song -4. Cherry on the top - Get a suitable song title! - - -# AI Music Team is composed of several GPT agents with the following "personas" - - -1. Experienced Music Director who has 15+ Years experience in the industry -2. Experienced Lyricist, who has written hit songs in several languages -3. Experienced Freelance Lyricist, who has helped writing songs in several languages -4. Experienced Music Composer, who has composed songs of several genre and arrangements over the years -5. Experienced Sound Engineer, who can provide expert feedback on the arrangement being used - - -# Workflow (Intermediate outputs/results are output as downloadable files) - - -1. Get Inputs from user (OpenAI API Endpoint, API Key, language, keywords, genre, emotion for the song). Check out [this link](https://platform.openai.com/account/api-keys) to get your API Key -2. Experienced Freelance Lyricist writes a lyrics draft (**see `step_2.txt`**) -3. Experienced Music Director and Experienced Lyricist provide feedback (**see `step_3A.txt` & `step_3B.txt` respectively**) -4. Experienced Freelance Lyricist incorporates the feedback, **Lyrics is finalized here** -5. Experienced Music Composer will provide a chord progression, and an arrangement of instruments (**see `step_5.txt`**) -6. Experienced Sound Engineer will provide ways to improve on the existing arrangement (**see `step_6.txt`**) -7. Finally, Music Director will provide improvements (**see `step_7.txt`**), resulting in the **final Chord Progression, Arrangement, and Song Title** - -''' - -demo = gr.Interface(title = 'Write and Compose brand new Songs using an Elite *AI Music Team*', description = description, - fn=write_and_compose, - inputs=[gr.Radio(["gpt-3.5-turbo", "gpt-4"], value="gpt-3.5-turbo", label = "Choose the OpenAI API Endpoint"), gr.Textbox(label="API Key (Check out [this link](https://platform.openai.com/account/api-keys) to get your API Key)"), gr.Dropdown(choices=languages, value='English', label="Language of the lyrics"), gr.Textbox(label="Genre"), gr.Textbox(label="Keywords (separated by comma)"), gr.Textbox(label="Emotion")], # model, api_key, language, genre, keywords, emotion - # outputs=[gr.Textbox(label="Lyrics after Step #2"), gr.Textbox(label="Feedback provided by Music Director in Step #3"), gr.Textbox(label="Feedback provided by Lyricist in Step #3"), gr.Textbox(label="Final Lyrics of the song after Step #4"), gr.Textbox(label="Chord Progression and Arrangement suggested by Music Composer in Step #5"), gr.Textbox(label="Arrangement improvements suggested by Sound Engineer in Step #6"), gr.Textbox(label="Chord and Arrangement improvements suggested by Music Director in Step #7"), gr.Textbox(label="Final Chord Progression, Arrangment, and Song Title")], # initial_lyrics, feedback1, feedback2, final_lyrics, composition_1, composition_2, final_improvements, final_chord_prog_and_composition - outputs=[gr.Textbox(label="Final Lyrics of the song after Step #4"), gr.Textbox(label="Final Chord Progression, Arrangement, and Song Title"), gr.File(label='Intermediate Outputs')], # initial_lyrics, feedback1, feedback2, final_lyrics, composition_1, composition_2, final_improvements, final_chord_prog_and_composition -) -demo.launch() \ No newline at end of file diff --git a/spaces/MirageML/lowpoly-landscape/README.md b/spaces/MirageML/lowpoly-landscape/README.md deleted file mode 100644 index 6191898eafb27be3c9417560ca2881780e458888..0000000000000000000000000000000000000000 --- a/spaces/MirageML/lowpoly-landscape/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Lowpoly Landscape -emoji: 😻 -colorFrom: red -colorTo: pink -sdk: gradio -sdk_version: 3.12.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Mountchicken/MAERec-Gradio/configs/kie/sdmgr/_base_sdmgr_novisual.py b/spaces/Mountchicken/MAERec-Gradio/configs/kie/sdmgr/_base_sdmgr_novisual.py deleted file mode 100644 index 5e85de2f78f020bd5695858098ad143dbbd09ed0..0000000000000000000000000000000000000000 --- a/spaces/Mountchicken/MAERec-Gradio/configs/kie/sdmgr/_base_sdmgr_novisual.py +++ /dev/null @@ -1,35 +0,0 @@ -num_classes = 26 - -model = dict( - type='SDMGR', - kie_head=dict( - type='SDMGRHead', - visual_dim=16, - num_classes=num_classes, - module_loss=dict(type='SDMGRModuleLoss'), - postprocessor=dict(type='SDMGRPostProcessor')), - dictionary=dict( - type='Dictionary', - dict_file='{{ fileDirname }}/../../../dicts/sdmgr_dict.txt', - with_padding=True, - with_unknown=True, - unknown_token=None), -) - -train_pipeline = [ - dict(type='LoadKIEAnnotations'), - dict(type='Resize', scale=(1024, 512), keep_ratio=True), - dict(type='PackKIEInputs') -] -test_pipeline = [ - dict(type='LoadKIEAnnotations'), - dict(type='Resize', scale=(1024, 512), keep_ratio=True), - dict(type='PackKIEInputs'), -] - -val_evaluator = dict( - type='F1Metric', - mode='macro', - num_classes=num_classes, - ignored_classes=[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 25]) -test_evaluator = val_evaluator diff --git a/spaces/NN520/AI/src/pages/api/blob.ts b/spaces/NN520/AI/src/pages/api/blob.ts deleted file mode 100644 index fecd48031916b2284b8958892196e0a1ad420421..0000000000000000000000000000000000000000 --- a/spaces/NN520/AI/src/pages/api/blob.ts +++ /dev/null @@ -1,40 +0,0 @@ -'use server' - -import { NextApiRequest, NextApiResponse } from 'next' -import { Readable } from 'node:stream' -import { fetch } from '@/lib/isomorphic' - -const API_DOMAIN = 'https://www.bing.com' - -export default async function handler(req: NextApiRequest, res: NextApiResponse) { - try { - const { bcid } = req.query - - const { headers, body } = await fetch(`${API_DOMAIN}/images/blob?bcid=${bcid}`, - { - method: 'GET', - headers: { - "sec-ch-ua": "\"Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"115\", \"Chromium\";v=\"115\"", - "sec-ch-ua-mobile": "?0", - "sec-ch-ua-platform": "\"Windows\"", - "Referrer-Policy": "origin-when-cross-origin", - }, - }, - ) - - res.writeHead(200, { - 'Content-Length': headers.get('content-length')!, - 'Content-Type': headers.get('content-type')!, - }) - // @ts-ignore - return Readable.fromWeb(body!).pipe(res) - } catch (e) { - console.log('Error', e) - return res.json({ - result: { - value: 'UploadFailed', - message: `${e}` - } - }) - } -} diff --git a/spaces/Nee001/bing0/src/components/chat-history.tsx b/spaces/Nee001/bing0/src/components/chat-history.tsx deleted file mode 100644 index feb81de66562edda8f40d3c0cc717202c92b6509..0000000000000000000000000000000000000000 --- a/spaces/Nee001/bing0/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/Nephele/bert-vits2-multi-voice/models.py b/spaces/Nephele/bert-vits2-multi-voice/models.py deleted file mode 100644 index d4afe44d883691610c5903e602a3ca245fcb3a5c..0000000000000000000000000000000000000000 --- a/spaces/Nephele/bert-vits2-multi-voice/models.py +++ /dev/null @@ -1,707 +0,0 @@ -import copy -import math -import torch -from torch import nn -from torch.nn import functional as F - -import commons -import modules -import attentions -import monotonic_align - -from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d -from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm - -from commons import init_weights, get_padding -from text import symbols, num_tones, num_languages -class DurationDiscriminator(nn.Module): #vits2 - def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0): - super().__init__() - - self.in_channels = in_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.gin_channels = gin_channels - - self.drop = nn.Dropout(p_dropout) - self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size//2) - self.norm_1 = modules.LayerNorm(filter_channels) - self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2) - self.norm_2 = modules.LayerNorm(filter_channels) - self.dur_proj = nn.Conv1d(1, filter_channels, 1) - - self.pre_out_conv_1 = nn.Conv1d(2*filter_channels, filter_channels, kernel_size, padding=kernel_size//2) - self.pre_out_norm_1 = modules.LayerNorm(filter_channels) - self.pre_out_conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2) - self.pre_out_norm_2 = modules.LayerNorm(filter_channels) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, in_channels, 1) - - self.output_layer = nn.Sequential( - nn.Linear(filter_channels, 1), - nn.Sigmoid() - ) - - def forward_probability(self, x, x_mask, dur, g=None): - dur = self.dur_proj(dur) - x = torch.cat([x, dur], dim=1) - x = self.pre_out_conv_1(x * x_mask) - x = torch.relu(x) - x = self.pre_out_norm_1(x) - x = self.drop(x) - x = self.pre_out_conv_2(x * x_mask) - x = torch.relu(x) - x = self.pre_out_norm_2(x) - x = self.drop(x) - x = x * x_mask - x = x.transpose(1, 2) - output_prob = self.output_layer(x) - return output_prob - - def forward(self, x, x_mask, dur_r, dur_hat, g=None): - x = torch.detach(x) - if g is not None: - g = torch.detach(g) - x = x + self.cond(g) - x = self.conv_1(x * x_mask) - x = torch.relu(x) - x = self.norm_1(x) - x = self.drop(x) - x = self.conv_2(x * x_mask) - x = torch.relu(x) - x = self.norm_2(x) - x = self.drop(x) - - output_probs = [] - for dur in [dur_r, dur_hat]: - output_prob = self.forward_probability(x, x_mask, dur, g) - output_probs.append(output_prob) - - return output_probs - -class TransformerCouplingBlock(nn.Module): - def __init__(self, - channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - n_flows=4, - gin_channels=0, - share_parameter=False - ): - - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.n_layers = n_layers - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.flows = nn.ModuleList() - - self.wn = attentions.FFT(hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, isflow = True, gin_channels = self.gin_channels) if share_parameter else None - - for i in range(n_flows): - self.flows.append( - modules.TransformerCouplingLayer(channels, hidden_channels, kernel_size, n_layers, n_heads, p_dropout, filter_channels, mean_only=True, wn_sharing_parameter=self.wn, gin_channels = self.gin_channels)) - self.flows.append(modules.Flip()) - - def forward(self, x, x_mask, g=None, reverse=False): - if not reverse: - for flow in self.flows: - x, _ = flow(x, x_mask, g=g, reverse=reverse) - else: - for flow in reversed(self.flows): - x = flow(x, x_mask, g=g, reverse=reverse) - return x - -class StochasticDurationPredictor(nn.Module): - def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0): - super().__init__() - filter_channels = in_channels # it needs to be removed from future version. - self.in_channels = in_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.log_flow = modules.Log() - self.flows = nn.ModuleList() - self.flows.append(modules.ElementwiseAffine(2)) - for i in range(n_flows): - self.flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)) - self.flows.append(modules.Flip()) - - self.post_pre = nn.Conv1d(1, filter_channels, 1) - self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1) - self.post_convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout) - self.post_flows = nn.ModuleList() - self.post_flows.append(modules.ElementwiseAffine(2)) - for i in range(4): - self.post_flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)) - self.post_flows.append(modules.Flip()) - - self.pre = nn.Conv1d(in_channels, filter_channels, 1) - self.proj = nn.Conv1d(filter_channels, filter_channels, 1) - self.convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout) - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, filter_channels, 1) - - def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0): - x = torch.detach(x) - x = self.pre(x) - if g is not None: - g = torch.detach(g) - x = x + self.cond(g) - x = self.convs(x, x_mask) - x = self.proj(x) * x_mask - - if not reverse: - flows = self.flows - assert w is not None - - logdet_tot_q = 0 - h_w = self.post_pre(w) - h_w = self.post_convs(h_w, x_mask) - h_w = self.post_proj(h_w) * x_mask - e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask - z_q = e_q - for flow in self.post_flows: - z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w)) - logdet_tot_q += logdet_q - z_u, z1 = torch.split(z_q, [1, 1], 1) - u = torch.sigmoid(z_u) * x_mask - z0 = (w - u) * x_mask - logdet_tot_q += torch.sum((F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1, 2]) - logq = torch.sum(-0.5 * (math.log(2 * math.pi) + (e_q ** 2)) * x_mask, [1, 2]) - logdet_tot_q - - logdet_tot = 0 - z0, logdet = self.log_flow(z0, x_mask) - logdet_tot += logdet - z = torch.cat([z0, z1], 1) - for flow in flows: - z, logdet = flow(z, x_mask, g=x, reverse=reverse) - logdet_tot = logdet_tot + logdet - nll = torch.sum(0.5 * (math.log(2 * math.pi) + (z ** 2)) * x_mask, [1, 2]) - logdet_tot - return nll + logq # [b] - else: - flows = list(reversed(self.flows)) - flows = flows[:-2] + [flows[-1]] # remove a useless vflow - z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale - for flow in flows: - z = flow(z, x_mask, g=x, reverse=reverse) - z0, z1 = torch.split(z, [1, 1], 1) - logw = z0 - return logw - - -class DurationPredictor(nn.Module): - def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0): - super().__init__() - - self.in_channels = in_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.gin_channels = gin_channels - - self.drop = nn.Dropout(p_dropout) - self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size // 2) - self.norm_1 = modules.LayerNorm(filter_channels) - self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size // 2) - self.norm_2 = modules.LayerNorm(filter_channels) - self.proj = nn.Conv1d(filter_channels, 1, 1) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, in_channels, 1) - - def forward(self, x, x_mask, g=None): - x = torch.detach(x) - if g is not None: - g = torch.detach(g) - x = x + self.cond(g) - x = self.conv_1(x * x_mask) - x = torch.relu(x) - x = self.norm_1(x) - x = self.drop(x) - x = self.conv_2(x * x_mask) - x = torch.relu(x) - x = self.norm_2(x) - x = self.drop(x) - x = self.proj(x * x_mask) - return x * x_mask - - -class TextEncoder(nn.Module): - def __init__(self, - n_vocab, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - gin_channels=0): - super().__init__() - self.n_vocab = n_vocab - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.gin_channels = gin_channels - self.emb = nn.Embedding(len(symbols), hidden_channels) - nn.init.normal_(self.emb.weight, 0.0, hidden_channels ** -0.5) - self.tone_emb = nn.Embedding(num_tones, hidden_channels) - nn.init.normal_(self.tone_emb.weight, 0.0, hidden_channels ** -0.5) - self.language_emb = nn.Embedding(num_languages, hidden_channels) - nn.init.normal_(self.language_emb.weight, 0.0, hidden_channels ** -0.5) - self.bert_proj = nn.Conv1d(1024, hidden_channels, 1) - - self.encoder = attentions.Encoder( - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - gin_channels=self.gin_channels) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, x, x_lengths, tone, language, bert, g=None): - x = (self.emb(x)+ self.tone_emb(tone)+ self.language_emb(language)+self.bert_proj(bert).transpose(1,2)) * math.sqrt(self.hidden_channels) # [b, t, h] - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype) - - x = self.encoder(x * x_mask, x_mask, g=g) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return x, m, logs, x_mask - - -class ResidualCouplingBlock(nn.Module): - def __init__(self, - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - n_flows=4, - gin_channels=0): - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.flows = nn.ModuleList() - for i in range(n_flows): - self.flows.append( - modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, - gin_channels=gin_channels, mean_only=True)) - self.flows.append(modules.Flip()) - - def forward(self, x, x_mask, g=None, reverse=False): - if not reverse: - for flow in self.flows: - x, _ = flow(x, x_mask, g=g, reverse=reverse) - else: - for flow in reversed(self.flows): - x = flow(x, x_mask, g=g, reverse=reverse) - return x - - -class PosteriorEncoder(nn.Module): - def __init__(self, - in_channels, - out_channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=0): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.gin_channels = gin_channels - - self.pre = nn.Conv1d(in_channels, hidden_channels, 1) - self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, x, x_lengths, g=None): - x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype) - x = self.pre(x) * x_mask - x = self.enc(x, x_mask, g=g) - stats = self.proj(x) * x_mask - m, logs = torch.split(stats, self.out_channels, dim=1) - z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask - return z, m, logs, x_mask - - -class Generator(torch.nn.Module): - def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, - upsample_initial_channel, upsample_kernel_sizes, gin_channels=0): - super(Generator, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3) - resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - self.ups.append(weight_norm( - ConvTranspose1d(upsample_initial_channel // (2 ** i), upsample_initial_channel // (2 ** (i + 1)), - k, u, padding=(k - u) // 2))) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - def forward(self, x, g=None): - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - - return x - - def remove_weight_norm(self): - print('Removing weight norm...') - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -class DiscriminatorP(torch.nn.Module): - def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): - super(DiscriminatorP, self).__init__() - self.period = period - self.use_spectral_norm = use_spectral_norm - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList([ - norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), - norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), - norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), - norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), - norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))), - ]) - self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0))) - - def forward(self, x): - fmap = [] - - # 1d to 2d - b, c, t = x.shape - if t % self.period != 0: # pad first - n_pad = self.period - (t % self.period) - x = F.pad(x, (0, n_pad), "reflect") - t = t + n_pad - x = x.view(b, c, t // self.period, self.period) - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap - - -class DiscriminatorS(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(DiscriminatorS, self).__init__() - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList([ - norm_f(Conv1d(1, 16, 15, 1, padding=7)), - norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)), - norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)), - norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)), - norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)), - norm_f(Conv1d(1024, 1024, 5, 1, padding=2)), - ]) - self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1)) - - def forward(self, x): - fmap = [] - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap - - -class MultiPeriodDiscriminator(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(MultiPeriodDiscriminator, self).__init__() - periods = [2, 3, 5, 7, 11] - - discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] - discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods] - self.discriminators = nn.ModuleList(discs) - - def forward(self, y, y_hat): - y_d_rs = [] - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y) - y_d_g, fmap_g = d(y_hat) - y_d_rs.append(y_d_r) - y_d_gs.append(y_d_g) - fmap_rs.append(fmap_r) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - -class ReferenceEncoder(nn.Module): - ''' - inputs --- [N, Ty/r, n_mels*r] mels - outputs --- [N, ref_enc_gru_size] - ''' - - def __init__(self, spec_channels, gin_channels=0): - - super().__init__() - self.spec_channels = spec_channels - ref_enc_filters = [32, 32, 64, 64, 128, 128] - K = len(ref_enc_filters) - filters = [1] + ref_enc_filters - convs = [weight_norm(nn.Conv2d(in_channels=filters[i], - out_channels=filters[i + 1], - kernel_size=(3, 3), - stride=(2, 2), - padding=(1, 1))) for i in range(K)] - self.convs = nn.ModuleList(convs) - # self.wns = nn.ModuleList([weight_norm(num_features=ref_enc_filters[i]) for i in range(K)]) - - out_channels = self.calculate_channels(spec_channels, 3, 2, 1, K) - self.gru = nn.GRU(input_size=ref_enc_filters[-1] * out_channels, - hidden_size=256 // 2, - batch_first=True) - self.proj = nn.Linear(128, gin_channels) - - def forward(self, inputs, mask=None): - N = inputs.size(0) - out = inputs.view(N, 1, -1, self.spec_channels) # [N, 1, Ty, n_freqs] - for conv in self.convs: - out = conv(out) - # out = wn(out) - out = F.relu(out) # [N, 128, Ty//2^K, n_mels//2^K] - - out = out.transpose(1, 2) # [N, Ty//2^K, 128, n_mels//2^K] - T = out.size(1) - N = out.size(0) - out = out.contiguous().view(N, T, -1) # [N, Ty//2^K, 128*n_mels//2^K] - - self.gru.flatten_parameters() - memory, out = self.gru(out) # out --- [1, N, 128] - - return self.proj(out.squeeze(0)) - - def calculate_channels(self, L, kernel_size, stride, pad, n_convs): - for i in range(n_convs): - L = (L - kernel_size + 2 * pad) // stride + 1 - return L - - -class SynthesizerTrn(nn.Module): - """ - Synthesizer for Training - """ - - def __init__(self, - n_vocab, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - n_speakers=256, - gin_channels=256, - use_sdp=True, - n_flow_layer = 4, - n_layers_trans_flow = 3, - flow_share_parameter = False, - use_transformer_flow = True, - **kwargs): - - super().__init__() - self.n_vocab = n_vocab - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.n_speakers = n_speakers - self.gin_channels = gin_channels - self.n_layers_trans_flow = n_layers_trans_flow - self.use_spk_conditioned_encoder = kwargs.get("use_spk_conditioned_encoder", True) - self.use_sdp = use_sdp - self.use_noise_scaled_mas = kwargs.get("use_noise_scaled_mas", False) - self.mas_noise_scale_initial = kwargs.get("mas_noise_scale_initial", 0.01) - self.noise_scale_delta = kwargs.get("noise_scale_delta", 2e-6) - self.current_mas_noise_scale = self.mas_noise_scale_initial - if self.use_spk_conditioned_encoder and gin_channels > 0: - self.enc_gin_channels = gin_channels - self.enc_p = TextEncoder(n_vocab, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - gin_channels=self.enc_gin_channels) - self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, - upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels) - self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, - gin_channels=gin_channels) - if use_transformer_flow: - self.flow = TransformerCouplingBlock(inter_channels, hidden_channels, filter_channels, n_heads, n_layers_trans_flow, 5, p_dropout, n_flow_layer, gin_channels=gin_channels,share_parameter= flow_share_parameter) - else: - self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, n_flow_layer, gin_channels=gin_channels) - self.sdp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels) - self.dp = DurationPredictor(hidden_channels, 256, 3, 0.5, gin_channels=gin_channels) - - if n_speakers >= 1: - self.emb_g = nn.Embedding(n_speakers, gin_channels) - else: - self.ref_enc = ReferenceEncoder(spec_channels, gin_channels) - - def forward(self, x, x_lengths, y, y_lengths, sid, tone, language, bert): - if self.n_speakers > 0: - g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1] - else: - g = self.ref_enc(y.transpose(1,2)).unsqueeze(-1) - x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert,g=g) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - - with torch.no_grad(): - # negative cross-entropy - s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t] - neg_cent1 = torch.sum(-0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True) # [b, 1, t_s] - neg_cent2 = torch.matmul(-0.5 * (z_p ** 2).transpose(1, 2), - s_p_sq_r) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s] - neg_cent3 = torch.matmul(z_p.transpose(1, 2), (m_p * s_p_sq_r)) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s] - neg_cent4 = torch.sum(-0.5 * (m_p ** 2) * s_p_sq_r, [1], keepdim=True) # [b, 1, t_s] - neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4 - if self.use_noise_scaled_mas: - epsilon = torch.std(neg_cent) * torch.randn_like(neg_cent) * self.current_mas_noise_scale - neg_cent = neg_cent + epsilon - - attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1) - attn = monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach() - - w = attn.sum(2) - - l_length_sdp = self.sdp(x, x_mask, w, g=g) - l_length_sdp = l_length_sdp / torch.sum(x_mask) - - logw_ = torch.log(w + 1e-6) * x_mask - logw = self.dp(x, x_mask, g=g) - l_length_dp = torch.sum((logw - logw_) ** 2, [1, 2]) / torch.sum(x_mask) # for averaging - - l_length = l_length_dp + l_length_sdp - - # expand prior - m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) - logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2) - - z_slice, ids_slice = commons.rand_slice_segments(z, y_lengths, self.segment_size) - o = self.dec(z_slice, g=g) - return o, l_length, attn, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q), (x, logw, logw_) - - def infer(self, x, x_lengths, sid, tone, language, bert, noise_scale=.667, length_scale=1, noise_scale_w=0.8, max_len=None, sdp_ratio=0,y=None): - #x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert) - # g = self.gst(y) - if self.n_speakers > 0: - g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1] - else: - g = self.ref_enc(y.transpose(1,2)).unsqueeze(-1) - x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert,g=g) - logw = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w) * (sdp_ratio) + self.dp(x, x_mask, g=g) * (1 - sdp_ratio) - w = torch.exp(logw) * x_mask * length_scale - w_ceil = torch.ceil(w) - y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long() - y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype) - attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1) - attn = commons.generate_path(w_ceil, attn_mask) - - m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t'] - logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, - 2) # [b, t', t], [b, t, d] -> [b, d, t'] - - z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale - z = self.flow(z_p, y_mask, g=g, reverse=True) - o = self.dec((z * y_mask)[:, :, :max_len], g=g) - return o, attn, y_mask, (z, z_p, m_p, logs_p) diff --git a/spaces/NikeZoldyck/green-screen-composition-transfer/README.md b/spaces/NikeZoldyck/green-screen-composition-transfer/README.md deleted file mode 100644 index ef17d16684705a79da2afb0d2e3298e089c71964..0000000000000000000000000000000000000000 --- a/spaces/NikeZoldyck/green-screen-composition-transfer/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Green Screen Composition Transfer -emoji: 🌍 -colorFrom: yellow -colorTo: yellow -sdk: gradio -sdk_version: 3.4.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/NimaBoscarino/climategan/eval_masker.py b/spaces/NimaBoscarino/climategan/eval_masker.py deleted file mode 100644 index 72b0671b2a62f72da6e600f929b4c735e5e3a5cc..0000000000000000000000000000000000000000 --- a/spaces/NimaBoscarino/climategan/eval_masker.py +++ /dev/null @@ -1,796 +0,0 @@ -""" -Compute metrics of the performance of the masker using a set of ground-truth labels - -run eval_masker.py --model "/miniscratch/_groups/ccai/checkpoints/model/" - -""" -print("Imports...", end="") -import os -import os.path -from argparse import ArgumentParser -from pathlib import Path - -import matplotlib.pyplot as plt -import numpy as np -import pandas as pd -from comet_ml import Experiment -import torch -import yaml -from skimage.color import rgba2rgb -from skimage.io import imread, imsave -from skimage.transform import resize -from skimage.util import img_as_ubyte -from torchvision.transforms import ToTensor - -from climategan.data import encode_mask_label -from climategan.eval_metrics import ( - masker_classification_metrics, - get_confusion_matrix, - edges_coherence_std_min, - boxplot_metric, - clustermap_metric, -) -from climategan.transforms import PrepareTest -from climategan.trainer import Trainer -from climategan.utils import find_images - -dict_metrics = { - "names": { - "tpr": "TPR, Recall, Sensitivity", - "tnr": "TNR, Specificity, Selectivity", - "fpr": "FPR", - "fpt": "False positives relative to image size", - "fnr": "FNR, Miss rate", - "fnt": "False negatives relative to image size", - "mpr": "May positive rate (MPR)", - "mnr": "May negative rate (MNR)", - "accuracy": "Accuracy (ignoring may)", - "error": "Error (ignoring may)", - "f05": "F0.05 score", - "precision": "Precision", - "edge_coherence": "Edge coherence", - "accuracy_must_may": "Accuracy (ignoring cannot)", - }, - "threshold": { - "tpr": 0.95, - "tnr": 0.95, - "fpr": 0.05, - "fpt": 0.01, - "fnr": 0.05, - "fnt": 0.01, - "accuracy": 0.95, - "error": 0.05, - "f05": 0.95, - "precision": 0.95, - "edge_coherence": 0.02, - "accuracy_must_may": 0.5, - }, - "key_metrics": ["f05", "error", "edge_coherence", "mnr"], -} - -print("Ok.") - - -def parsed_args(): - """Parse and returns command-line args - - Returns: - argparse.Namespace: the parsed arguments - """ - parser = ArgumentParser() - parser.add_argument( - "--model", - type=str, - help="Path to a pre-trained model", - ) - parser.add_argument( - "--images_dir", - default="/miniscratch/_groups/ccai/data/omnigan/masker-test-set/imgs", - type=str, - help="Directory containing the original test images", - ) - parser.add_argument( - "--labels_dir", - default="/miniscratch/_groups/ccai/data/omnigan/masker-test-set/labels", - type=str, - help="Directory containing the labeled images", - ) - parser.add_argument( - "--image_size", - default=640, - type=int, - help="The height and weight of the pre-processed images", - ) - parser.add_argument( - "--max_files", - default=-1, - type=int, - help="Limit loaded samples", - ) - parser.add_argument( - "--bin_value", default=0.5, type=float, help="Mask binarization threshold" - ) - parser.add_argument( - "-y", - "--yaml", - default=None, - type=str, - help="load a yaml file to parametrize the evaluation", - ) - parser.add_argument( - "-t", "--tags", nargs="*", help="Comet.ml tags", default=[], type=str - ) - parser.add_argument( - "-p", - "--plot", - action="store_true", - default=False, - help="Plot masker images & their metrics overlays", - ) - parser.add_argument( - "--no_paint", - action="store_true", - default=False, - help="Do not log painted images", - ) - parser.add_argument( - "--write_metrics", - action="store_true", - default=False, - help="If True, write CSV file and maps images in model's path directory", - ) - parser.add_argument( - "--load_metrics", - action="store_true", - default=False, - help="If True, load predictions and metrics instead of re-computing", - ) - parser.add_argument( - "--prepare_torch", - action="store_true", - default=False, - help="If True, pre-process images as torch tensors", - ) - parser.add_argument( - "--output_csv", - default=None, - type=str, - help="Filename of the output CSV with the metrics of all models", - ) - - return parser.parse_args() - - -def uint8(array): - return array.astype(np.uint8) - - -def crop_and_resize(image_path, label_path): - """ - Resizes an image so that it keeps the aspect ratio and the smallest dimensions - is 640, then crops this resized image in its center so that the output is 640x640 - without aspect ratio distortion - - Args: - image_path (Path or str): Path to an image - label_path (Path or str): Path to the image's associated label - - Returns: - tuple((np.ndarray, np.ndarray)): (new image, new label) - """ - - img = imread(image_path) - lab = imread(label_path) - - # if img.shape[-1] == 4: - # img = uint8(rgba2rgb(img) * 255) - - # TODO: remove (debug) - if img.shape[:2] != lab.shape[:2]: - print( - "\nWARNING: shape mismatch: im -> ({}) {}, lab -> ({}) {}".format( - img.shape[:2], image_path.name, lab.shape[:2], label_path.name - ) - ) - # breakpoint() - - # resize keeping aspect ratio: smallest dim is 640 - i_h, i_w = img.shape[:2] - if i_h < i_w: - i_size = (640, int(640 * i_w / i_h)) - else: - i_size = (int(640 * i_h / i_w), 640) - - l_h, l_w = img.shape[:2] - if l_h < l_w: - l_size = (640, int(640 * l_w / l_h)) - else: - l_size = (int(640 * l_h / l_w), 640) - - r_img = resize(img, i_size, preserve_range=True, anti_aliasing=True) - r_img = uint8(r_img) - - r_lab = resize(lab, l_size, preserve_range=True, anti_aliasing=False, order=0) - r_lab = uint8(r_lab) - - # crop in the center - H, W = r_img.shape[:2] - - top = (H - 640) // 2 - left = (W - 640) // 2 - - rc_img = r_img[top : top + 640, left : left + 640, :] - rc_lab = ( - r_lab[top : top + 640, left : left + 640, :] - if r_lab.ndim == 3 - else r_lab[top : top + 640, left : left + 640] - ) - - return rc_img, rc_lab - - -def plot_images( - output_filename, - img, - label, - pred, - metrics_dict, - maps_dict, - edge_coherence=-1, - pred_edge=None, - label_edge=None, - dpi=300, - alpha=0.5, - vmin=0.0, - vmax=1.0, - fontsize="xx-small", - cmap={ - "fp": "Reds", - "fn": "Reds", - "may_neg": "Oranges", - "may_pos": "Purples", - "pred": "Greens", - }, -): - f, axes = plt.subplots(1, 5, dpi=dpi) - - # FPR (predicted mask on cannot flood) - axes[0].imshow(img) - fp_map_plt = axes[0].imshow( # noqa: F841 - maps_dict["fp"], vmin=vmin, vmax=vmax, cmap=cmap["fp"], alpha=alpha - ) - axes[0].axis("off") - axes[0].set_title("FPR: {:.4f}".format(metrics_dict["fpr"]), fontsize=fontsize) - - # FNR (missed mask on must flood) - axes[1].imshow(img) - fn_map_plt = axes[1].imshow( # noqa: F841 - maps_dict["fn"], vmin=vmin, vmax=vmax, cmap=cmap["fn"], alpha=alpha - ) - axes[1].axis("off") - axes[1].set_title("FNR: {:.4f}".format(metrics_dict["fnr"]), fontsize=fontsize) - - # May flood - axes[2].imshow(img) - if edge_coherence != -1: - title = "MNR: {:.2f} | MPR: {:.2f}\nEdge coh.: {:.4f}".format( - metrics_dict["mnr"], metrics_dict["mpr"], edge_coherence - ) - # alpha_here = alpha / 4. - # pred_edge_plt = axes[2].imshow( - # 1.0 - pred_edge, cmap="gray", alpha=alpha_here - # ) - # label_edge_plt = axes[2].imshow( - # 1.0 - label_edge, cmap="gray", alpha=alpha_here - # ) - else: - title = "MNR: {:.2f} | MPR: {:.2f}".format(mnr, mpr) # noqa: F821 - # alpha_here = alpha / 2. - may_neg_map_plt = axes[2].imshow( # noqa: F841 - maps_dict["may_neg"], vmin=vmin, vmax=vmax, cmap=cmap["may_neg"], alpha=alpha - ) - may_pos_map_plt = axes[2].imshow( # noqa: F841 - maps_dict["may_pos"], vmin=vmin, vmax=vmax, cmap=cmap["may_pos"], alpha=alpha - ) - axes[2].set_title(title, fontsize=fontsize) - axes[2].axis("off") - - # Prediction - axes[3].imshow(img) - pred_mask = axes[3].imshow( # noqa: F841 - pred, vmin=vmin, vmax=vmax, cmap=cmap["pred"], alpha=alpha - ) - axes[3].set_title("Predicted mask", fontsize=fontsize) - axes[3].axis("off") - - # Labels - axes[4].imshow(img) - label_mask = axes[4].imshow(label, alpha=alpha) # noqa: F841 - axes[4].set_title("Labels", fontsize=fontsize) - axes[4].axis("off") - - f.savefig( - output_filename, - dpi=f.dpi, - bbox_inches="tight", - facecolor="white", - transparent=False, - ) - plt.close(f) - - -def load_ground(ground_output_path, ref_image_path): - gop = Path(ground_output_path) - rip = Path(ref_image_path) - - ground_paths = list((gop / "eval-metrics" / "pred").glob(f"{rip.stem}.jpg")) + list( - (gop / "eval-metrics" / "pred").glob(f"{rip.stem}.png") - ) - if len(ground_paths) == 0: - raise ValueError( - f"Could not find a ground match in {str(gop)} for image {str(rip)}" - ) - elif len(ground_paths) > 1: - raise ValueError( - f"Found more than 1 ground match in {str(gop)} for image {str(rip)}:" - + f" {list(map(str, ground_paths))}" - ) - ground_path = ground_paths[0] - _, ground = crop_and_resize(rip, ground_path) - if ground.ndim == 3: - ground = ground[:, :, 0] - ground = (ground > 0).astype(np.float32) - return torch.from_numpy(ground).unsqueeze(0).unsqueeze(0).cuda() - - -def get_inferences( - image_arrays, model_path, image_paths, paint=False, bin_value=0.5, verbose=0 -): - """ - Obtains the mask predictions of a model for a set of images - - Parameters - ---------- - image_arrays : array-like - A list of (1, CH, H, W) images - - image_paths: list(Path) - A list of paths for images, in the same order as image_arrays - - model_path : str - The path to a pre-trained model - - Returns - ------- - masks : list - A list of (H, W) predicted masks - """ - device = torch.device("cpu") - torch.set_grad_enabled(False) - to_tensor = ToTensor() - - is_ground = "ground" in Path(model_path).name - is_instagan = "instagan" in Path(model_path).name - - if is_ground or is_instagan: - # we just care about he painter here - ground_path = model_path - model_path = ( - "/miniscratch/_groups/ccai/experiments/runs/ablation-v1/out--38858350" - ) - - xs = [to_tensor(array).unsqueeze(0) for array in image_arrays] - xs = [x.to(torch.float32).to(device) for x in xs] - xs = [(x - 0.5) * 2 for x in xs] - trainer = Trainer.resume_from_path( - model_path, inference=True, new_exp=None, device=device - ) - masks = [] - painted = [] - for idx, x in enumerate(xs): - if verbose > 0: - print(idx, "/", len(xs), end="\r") - - if not is_ground and not is_instagan: - m = trainer.G.mask(x=x) - else: - m = load_ground(ground_path, image_paths[idx]) - - masks.append(m.squeeze().cpu()) - if paint: - p = trainer.G.paint(m > bin_value, x) - painted.append(p.squeeze().cpu()) - return masks, painted - - -if __name__ == "__main__": - # ----------------------------- - # ----- Parse arguments ----- - # ----------------------------- - args = parsed_args() - print("Args:\n" + "\n".join([f" {k:20}: {v}" for k, v in vars(args).items()])) - - # Determine output dir - try: - tmp_dir = Path(os.environ["SLURM_TMPDIR"]) - except Exception as e: - print(e) - tmp_dir = Path(input("Enter tmp output directory: ")).resolve() - - plot_dir = tmp_dir / "plots" - plot_dir.mkdir(parents=True, exist_ok=True) - - # Build paths to data - imgs_paths = sorted( - find_images(args.images_dir, recursive=False), key=lambda x: x.name - ) - labels_paths = sorted( - find_images(args.labels_dir, recursive=False), - key=lambda x: x.name.replace("_labeled.", "."), - ) - if args.max_files > 0: - imgs_paths = imgs_paths[: args.max_files] - labels_paths = labels_paths[: args.max_files] - - print(f"Loading {len(imgs_paths)} images and labels...") - - # Pre-process images: resize + crop - # TODO: ? make cropping more flexible, not only central - if not args.prepare_torch: - ims_labs = [crop_and_resize(i, l) for i, l in zip(imgs_paths, labels_paths)] - imgs = [d[0] for d in ims_labs] - labels = [d[1] for d in ims_labs] - else: - prepare = PrepareTest() - imgs = prepare(imgs_paths, normalize=False, rescale=False) - labels = prepare(labels_paths, normalize=False, rescale=False) - - imgs = [i.squeeze(0).permute(1, 2, 0).numpy().astype(np.uint8) for i in imgs] - labels = [ - lab.squeeze(0).permute(1, 2, 0).numpy().astype(np.uint8) for lab in labels - ] - imgs = [rgba2rgb(img) if img.shape[-1] == 4 else img for img in imgs] - print(" Done.") - - # Encode labels - print("Encode labels...", end="", flush=True) - # HW label - labels = [np.squeeze(encode_mask_label(label, "flood")) for label in labels] - print("Done.") - - if args.yaml: - y_path = Path(args.yaml) - assert y_path.exists() - assert y_path.suffix in {".yaml", ".yml"} - with y_path.open("r") as f: - data = yaml.safe_load(f) - assert "models" in data - - evaluations = [m for m in data["models"]] - else: - evaluations = [args.model] - - for e, eval_path in enumerate(evaluations): - print("\n>>>>> Evaluation", e, ":", eval_path) - print("=" * 50) - print("=" * 50) - - model_metrics_path = Path(eval_path) / "eval-metrics" - model_metrics_path.mkdir(exist_ok=True) - if args.load_metrics: - f_csv = model_metrics_path / "eval_masker.csv" - pred_out = model_metrics_path / "pred" - if f_csv.exists() and pred_out.exists(): - print("Skipping model because pre-computed metrics exist") - continue - - # Initialize New Comet Experiment - exp = Experiment( - project_name="climategan-masker-metrics", display_summary_level=0 - ) - - # Obtain mask predictions - # TODO: remove (debug) - print("Obtain mask predictions", end="", flush=True) - - preds, painted = get_inferences( - imgs, - eval_path, - imgs_paths, - paint=not args.no_paint, - bin_value=args.bin_value, - verbose=1, - ) - preds = [pred.numpy() for pred in preds] - print(" Done.") - - if args.bin_value > 0: - preds = [pred > args.bin_value for pred in preds] - - # Compute metrics - df = pd.DataFrame( - columns=[ - "tpr", - "tpt", - "tnr", - "tnt", - "fpr", - "fpt", - "fnr", - "fnt", - "mnr", - "mpr", - "accuracy", - "error", - "precision", - "f05", - "accuracy_must_may", - "edge_coherence", - "filename", - ] - ) - - print("Compute metrics and plot images") - for idx, (img, label, pred) in enumerate(zip(*(imgs, labels, preds))): - print(idx, "/", len(imgs), end="\r") - - # Basic classification metrics - metrics_dict, maps_dict = masker_classification_metrics( - pred, label, labels_dict={"cannot": 0, "must": 1, "may": 2} - ) - - # Edges coherence - edge_coherence, pred_edge, label_edge = edges_coherence_std_min(pred, label) - - series_dict = { - "tpr": metrics_dict["tpr"], - "tpt": metrics_dict["tpt"], - "tnr": metrics_dict["tnr"], - "tnt": metrics_dict["tnt"], - "fpr": metrics_dict["fpr"], - "fpt": metrics_dict["fpt"], - "fnr": metrics_dict["fnr"], - "fnt": metrics_dict["fnt"], - "mnr": metrics_dict["mnr"], - "mpr": metrics_dict["mpr"], - "accuracy": metrics_dict["accuracy"], - "error": metrics_dict["error"], - "precision": metrics_dict["precision"], - "f05": metrics_dict["f05"], - "accuracy_must_may": metrics_dict["accuracy_must_may"], - "edge_coherence": edge_coherence, - "filename": str(imgs_paths[idx].name), - } - df.loc[idx] = pd.Series(series_dict) - - for k, v in series_dict.items(): - if k == "filename": - continue - exp.log_metric(f"img_{k}", v, step=idx) - - # Confusion matrix - confmat, _ = get_confusion_matrix( - metrics_dict["tpr"], - metrics_dict["tnr"], - metrics_dict["fpr"], - metrics_dict["fnr"], - metrics_dict["mnr"], - metrics_dict["mpr"], - ) - confmat = np.around(confmat, decimals=3) - exp.log_confusion_matrix( - file_name=imgs_paths[idx].name + ".json", - title=imgs_paths[idx].name, - matrix=confmat, - labels=["Cannot", "Must", "May"], - row_label="Predicted", - column_label="Ground truth", - ) - - if args.plot: - # Plot prediction images - fig_filename = plot_dir / imgs_paths[idx].name - plot_images( - fig_filename, - img, - label, - pred, - metrics_dict, - maps_dict, - edge_coherence, - pred_edge, - label_edge, - ) - exp.log_image(fig_filename) - if not args.no_paint: - masked = img * (1 - pred[..., None]) - flooded = img_as_ubyte( - (painted[idx].permute(1, 2, 0).cpu().numpy() + 1) / 2 - ) - combined = np.concatenate([img, masked, flooded], 1) - exp.log_image(combined, imgs_paths[idx].name) - - if args.write_metrics: - pred_out = model_metrics_path / "pred" - pred_out.mkdir(exist_ok=True) - imsave( - pred_out / f"{imgs_paths[idx].stem}_pred.png", - pred.astype(np.uint8), - ) - for k, v in maps_dict.items(): - metric_out = model_metrics_path / k - metric_out.mkdir(exist_ok=True) - imsave( - metric_out / f"{imgs_paths[idx].stem}_{k}.png", - v.astype(np.uint8), - ) - - # -------------------------------- - # ----- END OF IMAGES LOOP ----- - # -------------------------------- - - if args.write_metrics: - print(f"Writing metrics in {str(model_metrics_path)}") - f_csv = model_metrics_path / "eval_masker.csv" - df.to_csv(f_csv, index_label="idx") - - print(" Done.") - # Summary statistics - means = df.mean(axis=0) - confmat_mean, confmat_std = get_confusion_matrix( - df.tpr, df.tnr, df.fpr, df.fnr, df.mpr, df.mnr - ) - confmat_mean = np.around(confmat_mean, decimals=3) - confmat_std = np.around(confmat_std, decimals=3) - - # Log to comet - exp.log_confusion_matrix( - file_name="confusion_matrix_mean.json", - title="confusion_matrix_mean.json", - matrix=confmat_mean, - labels=["Cannot", "Must", "May"], - row_label="Predicted", - column_label="Ground truth", - ) - exp.log_confusion_matrix( - file_name="confusion_matrix_std.json", - title="confusion_matrix_std.json", - matrix=confmat_std, - labels=["Cannot", "Must", "May"], - row_label="Predicted", - column_label="Ground truth", - ) - exp.log_metrics(dict(means)) - exp.log_table("metrics.csv", df) - exp.log_html(df.to_html(col_space="80px")) - exp.log_parameters(vars(args)) - exp.log_parameter("eval_path", str(eval_path)) - exp.add_tag("eval_masker") - if args.tags: - exp.add_tags(args.tags) - exp.log_parameter("model_id", Path(eval_path).name) - - # Close comet - exp.end() - - # -------------------------------- - # ----- END OF MODElS LOOP ----- - # -------------------------------- - - # Compare models - if (args.load_metrics or args.write_metrics) and len(evaluations) > 1: - print( - "Plots for comparing the input models will be created and logged to comet" - ) - - # Initialize New Comet Experiment - exp = Experiment( - project_name="climategan-masker-metrics", display_summary_level=0 - ) - if args.tags: - exp.add_tags(args.tags) - - # Build DataFrame with all models - print("Building pandas DataFrame...") - models_df = {} - for (m, model_path) in enumerate(evaluations): - model_path = Path(model_path) - with open(model_path / "opts.yaml", "r") as f: - opt = yaml.safe_load(f) - model_feats = ", ".join( - [ - t - for t in sorted(opt["comet"]["tags"]) - if "branch" not in t and "ablation" not in t and "trash" not in t - ] - ) - model_id = f"{model_path.parent.name[-2:]}/{model_path.name}" - df_m = pd.read_csv( - model_path / "eval-metrics" / "eval_masker.csv", index_col=False - ) - df_m["model"] = [model_id] * len(df_m) - df_m["model_idx"] = [m] * len(df_m) - df_m["model_feats"] = [model_feats] * len(df_m) - models_df.update({model_id: df_m}) - df = pd.concat(list(models_df.values()), ignore_index=True) - df["model_img_idx"] = df.model.astype(str) + "-" + df.idx.astype(str) - df.rename(columns={"idx": "img_idx"}, inplace=True) - dict_models_labels = { - k: f"{v['model_idx'][0]}: {v['model_feats'][0]}" - for k, v in models_df.items() - } - print("Done") - - if args.output_csv: - print(f"Writing DataFrame to {args.output_csv}") - df.to_csv(args.output_csv, index_label="model_img_idx") - - # Determine images with low metrics in any model - print("Constructing filter based on metrics thresholds...") - idx_not_good_in_any = [] - for idx in df.img_idx.unique(): - df_th = df.loc[ - ( - # TODO: rethink thresholds - (df.tpr <= dict_metrics["threshold"]["tpr"]) - | (df.fpr >= dict_metrics["threshold"]["fpr"]) - | (df.edge_coherence >= dict_metrics["threshold"]["edge_coherence"]) - ) - & ((df.img_idx == idx) & (df.model.isin(df.model.unique()))) - ] - if len(df_th) > 0: - idx_not_good_in_any.append(idx) - filters = {"all": df.img_idx.unique(), "not_good_in_any": idx_not_good_in_any} - print("Done") - - # Boxplots of metrics - print("Plotting boxplots of metrics...") - for k, f in filters.items(): - print(f"\tDistribution of [{k}] images...") - for metric in dict_metrics["names"].keys(): - fig_filename = plot_dir / f"boxplot_{metric}_{k}.png" - if metric in ["mnr", "mpr", "accuracy_must_may"]: - boxplot_metric( - fig_filename, - df.loc[df.img_idx.isin(f)], - metric=metric, - dict_metrics=dict_metrics["names"], - do_stripplot=True, - dict_models=dict_models_labels, - order=list(df.model.unique()), - ) - else: - boxplot_metric( - fig_filename, - df.loc[df.img_idx.isin(f)], - metric=metric, - dict_metrics=dict_metrics["names"], - dict_models=dict_models_labels, - fliersize=1.0, - order=list(df.model.unique()), - ) - exp.log_image(fig_filename) - print("Done") - - # Cluster Maps - print("Plotting clustermaps...") - for k, f in filters.items(): - print(f"\tDistribution of [{k}] images...") - for metric in dict_metrics["names"].keys(): - fig_filename = plot_dir / f"clustermap_{metric}_{k}.png" - df_mf = df.loc[df.img_idx.isin(f)].pivot("img_idx", "model", metric) - clustermap_metric( - output_filename=fig_filename, - df=df_mf, - metric=metric, - dict_metrics=dict_metrics["names"], - method="average", - cluster_metric="euclidean", - dict_models=dict_models_labels, - row_cluster=False, - ) - exp.log_image(fig_filename) - print("Done") - - # Close comet - exp.end() diff --git a/spaces/NoriZC/vits-models/monotonic_align/core.py b/spaces/NoriZC/vits-models/monotonic_align/core.py deleted file mode 100644 index 5ff728cd74c9228346a82ec64a9829cb98ad315e..0000000000000000000000000000000000000000 --- a/spaces/NoriZC/vits-models/monotonic_align/core.py +++ /dev/null @@ -1,36 +0,0 @@ -import numba - - -@numba.jit(numba.void(numba.int32[:, :, ::1], numba.float32[:, :, ::1], numba.int32[::1], numba.int32[::1]), - nopython=True, nogil=True) -def maximum_path_jit(paths, values, t_ys, t_xs): - b = paths.shape[0] - max_neg_val = -1e9 - for i in range(int(b)): - path = paths[i] - value = values[i] - t_y = t_ys[i] - t_x = t_xs[i] - - v_prev = v_cur = 0.0 - index = t_x - 1 - - for y in range(t_y): - for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): - if x == y: - v_cur = max_neg_val - else: - v_cur = value[y - 1, x] - if x == 0: - if y == 0: - v_prev = 0. - else: - v_prev = max_neg_val - else: - v_prev = value[y - 1, x - 1] - value[y, x] += max(v_prev, v_cur) - - for y in range(t_y - 1, -1, -1): - path[y, index] = 1 - if index != 0 and (index == y or value[y - 1, index] < value[y - 1, index - 1]): - index = index - 1 \ No newline at end of file diff --git a/spaces/Nunchakuka/FrenchAnonymizer/speaker_encoder/config.py b/spaces/Nunchakuka/FrenchAnonymizer/speaker_encoder/config.py deleted file mode 100644 index 1c21312f3de971bfa008254c6035cebc09f05e4c..0000000000000000000000000000000000000000 --- a/spaces/Nunchakuka/FrenchAnonymizer/speaker_encoder/config.py +++ /dev/null @@ -1,45 +0,0 @@ -librispeech_datasets = { - "train": { - "clean": ["LibriSpeech/train-clean-100", "LibriSpeech/train-clean-360"], - "other": ["LibriSpeech/train-other-500"] - }, - "test": { - "clean": ["LibriSpeech/test-clean"], - "other": ["LibriSpeech/test-other"] - }, - "dev": { - "clean": ["LibriSpeech/dev-clean"], - "other": ["LibriSpeech/dev-other"] - }, -} -libritts_datasets = { - "train": { - "clean": ["LibriTTS/train-clean-100", "LibriTTS/train-clean-360"], - "other": ["LibriTTS/train-other-500"] - }, - "test": { - "clean": ["LibriTTS/test-clean"], - "other": ["LibriTTS/test-other"] - }, - "dev": { - "clean": ["LibriTTS/dev-clean"], - "other": ["LibriTTS/dev-other"] - }, -} -voxceleb_datasets = { - "voxceleb1" : { - "train": ["VoxCeleb1/wav"], - "test": ["VoxCeleb1/test_wav"] - }, - "voxceleb2" : { - "train": ["VoxCeleb2/dev/aac"], - "test": ["VoxCeleb2/test_wav"] - } -} - -other_datasets = [ - "LJSpeech-1.1", - "VCTK-Corpus/wav48", -] - -anglophone_nationalites = ["australia", "canada", "ireland", "uk", "usa"] diff --git a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/examples/wav2vec/unsupervised/kaldi_self_train/st/cmd.sh b/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/examples/wav2vec/unsupervised/kaldi_self_train/st/cmd.sh deleted file mode 100644 index e74953194d41f0d93855d41b2acef08556d92477..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/examples/wav2vec/unsupervised/kaldi_self_train/st/cmd.sh +++ /dev/null @@ -1,15 +0,0 @@ -# you can change cmd.sh depending on what type of queue you are using. -# If you have no queueing system and want to run on a local machine, you -# can change all instances 'queue.pl' to run.pl (but be careful and run -# commands one by one: most recipes will exhaust the memory on your -# machine). queue.pl works with GridEngine (qsub). slurm.pl works -# with slurm. Different queues are configured differently, with different -# queue names and different ways of specifying things like memory; -# to account for these differences you can create and edit the file -# conf/queue.conf to match your queue's configuration. Search for -# conf/queue.conf in http://kaldi-asr.org/doc/queue.html for more information, -# or search for the string 'default_config' in utils/queue.pl or utils/slurm.pl. - -export train_cmd="run.pl --mem 2G" -export decode_cmd="run.pl --mem 4G" -export mkgraph_cmd="run.pl --mem 8G" diff --git a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/data/encoders/utils.py b/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/data/encoders/utils.py deleted file mode 100644 index d93eb532ef84f0e2bc708b777229ab2cb76ca14b..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/data/encoders/utils.py +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import torch -from fairseq.data import encoders - - -def get_whole_word_mask(args, dictionary): - bpe = encoders.build_bpe(args) - if bpe is not None: - - def is_beginning_of_word(i): - if i < dictionary.nspecial: - # special elements are always considered beginnings - return True - tok = dictionary[i] - if tok.startswith("madeupword"): - return True - try: - return bpe.is_beginning_of_word(tok) - except ValueError: - return True - - mask_whole_words = torch.ByteTensor( - list(map(is_beginning_of_word, range(len(dictionary)))) - ) - return mask_whole_words - return None diff --git a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/data/multilingual/multilingual_utils.py b/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/data/multilingual/multilingual_utils.py deleted file mode 100644 index b4e0f9828cabfdbe375d05d9152b58bdbd6de7dc..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/data/multilingual/multilingual_utils.py +++ /dev/null @@ -1,63 +0,0 @@ -from enum import Enum -from typing import Dict, List, Optional, Sequence - -import torch -from fairseq.data import Dictionary - - -class EncoderLangtok(Enum): - """ - Prepend to the beginning of source sentence either the - source or target language token. (src/tgt). - """ - - src = "src" - tgt = "tgt" - - -class LangTokSpec(Enum): - main = "main" - mono_dae = "mono_dae" - - -class LangTokStyle(Enum): - multilingual = "multilingual" - mbart = "mbart" - - -@torch.jit.export -def get_lang_tok( - lang: str, lang_tok_style: str, spec: str = LangTokSpec.main.value -) -> str: - # TOKEN_STYLES can't be defined outside this fn since it needs to be - # TorchScriptable. - TOKEN_STYLES: Dict[str, str] = { - LangTokStyle.mbart.value: "[{}]", - LangTokStyle.multilingual.value: "__{}__", - } - - if spec.endswith("dae"): - lang = f"{lang}_dae" - elif spec.endswith("mined"): - lang = f"{lang}_mined" - style = TOKEN_STYLES[lang_tok_style] - return style.format(lang) - - -def augment_dictionary( - dictionary: Dictionary, - language_list: List[str], - lang_tok_style: str, - langtoks_specs: Sequence[str] = (LangTokSpec.main.value,), - extra_data: Optional[Dict[str, str]] = None, -) -> None: - for spec in langtoks_specs: - for language in language_list: - dictionary.add_symbol( - get_lang_tok(lang=language, lang_tok_style=lang_tok_style, spec=spec) - ) - - if lang_tok_style == LangTokStyle.mbart.value or ( - extra_data is not None and LangTokSpec.mono_dae.value in extra_data - ): - dictionary.add_symbol("") diff --git a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/tasks/multilingual_translation.py b/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/tasks/multilingual_translation.py deleted file mode 100644 index 4f85ab4832a6c7cbe57a99a3efc6987125d956fc..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/tasks/multilingual_translation.py +++ /dev/null @@ -1,462 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import contextlib -import logging -import os -from collections import OrderedDict -from argparse import ArgumentError - -import torch -from fairseq import metrics, options, utils -from fairseq.data import ( - Dictionary, - LanguagePairDataset, - RoundRobinZipDatasets, - TransformEosLangPairDataset, -) -from fairseq.models import FairseqMultiModel -from fairseq.tasks.translation import load_langpair_dataset - -from . import LegacyFairseqTask, register_task - - -logger = logging.getLogger(__name__) - - -def _lang_token(lang: str): - return "__{}__".format(lang) - - -def _lang_token_index(dic: Dictionary, lang: str): - """Return language token index.""" - idx = dic.index(_lang_token(lang)) - assert idx != dic.unk_index, "cannot find language token for lang {}".format(lang) - return idx - - -@register_task("multilingual_translation") -class MultilingualTranslationTask(LegacyFairseqTask): - """A task for training multiple translation models simultaneously. - - We iterate round-robin over batches from multiple language pairs, ordered - according to the `--lang-pairs` argument. - - The training loop is roughly: - - for i in range(len(epoch)): - for lang_pair in args.lang_pairs: - batch = next_batch_for_lang_pair(lang_pair) - loss = criterion(model_for_lang_pair(lang_pair), batch) - loss.backward() - optimizer.step() - - In practice, `next_batch_for_lang_pair` is abstracted in a FairseqDataset - (e.g., `RoundRobinZipDatasets`) and `model_for_lang_pair` is a model that - implements the `FairseqMultiModel` interface. - - During inference it is required to specify a single `--source-lang` and - `--target-lang`, which indicates the inference langauge direction. - `--lang-pairs`, `--encoder-langtok`, `--decoder-langtok` have to be set to - the same value as training. - """ - - @staticmethod - def add_args(parser): - """Add task-specific arguments to the parser.""" - # fmt: off - parser.add_argument('data', metavar='DIR', help='path to data directory') - parser.add_argument('--lang-pairs', default=None, metavar='PAIRS', - help='comma-separated list of language pairs (in training order): en-de,en-fr,de-fr') - parser.add_argument('-s', '--source-lang', default=None, metavar='SRC', - help='source language (only needed for inference)') - parser.add_argument('-t', '--target-lang', default=None, metavar='TARGET', - help='target language (only needed for inference)') - parser.add_argument('--left-pad-source', default='True', type=str, metavar='BOOL', - help='pad the source on the left (default: True)') - parser.add_argument('--left-pad-target', default='False', type=str, metavar='BOOL', - help='pad the target on the left (default: False)') - try: - parser.add_argument('--max-source-positions', default=1024, type=int, metavar='N', - help='max number of tokens in the source sequence') - parser.add_argument('--max-target-positions', default=1024, type=int, metavar='N', - help='max number of tokens in the target sequence') - except ArgumentError: - # this might have already been defined. Once we transition this to hydra it should be fine to add it here. - pass - parser.add_argument('--upsample-primary', default=1, type=int, - help='amount to upsample primary dataset') - parser.add_argument('--encoder-langtok', default=None, type=str, choices=['src', 'tgt'], - metavar='SRCTGT', - help='replace beginning-of-sentence in source sentence with source or target ' - 'language token. (src/tgt)') - parser.add_argument('--decoder-langtok', action='store_true', - help='replace beginning-of-sentence in target sentence with target language token') - # fmt: on - - def __init__(self, args, dicts, training): - super().__init__(args) - self.dicts = dicts - self.training = training - if training: - self.lang_pairs = args.lang_pairs - else: - self.lang_pairs = ["{}-{}".format(args.source_lang, args.target_lang)] - # eval_lang_pairs for multilingual translation is usually all of the - # lang_pairs. However for other multitask settings or when we want to - # optimize for certain languages we want to use a different subset. Thus - # the eval_lang_pairs class variable is provided for classes that extend - # this class. - self.eval_lang_pairs = self.lang_pairs - # model_lang_pairs will be used to build encoder-decoder model pairs in - # models.build_model(). This allows multitask type of sub-class can - # build models other than the input lang_pairs - self.model_lang_pairs = self.lang_pairs - self.langs = list(dicts.keys()) - - @classmethod - def setup_task(cls, args, **kwargs): - dicts, training = cls.prepare(args, **kwargs) - return cls(args, dicts, training) - - @classmethod - def update_args(cls, args): - args.left_pad_source = utils.eval_bool(args.left_pad_source) - args.left_pad_target = utils.eval_bool(args.left_pad_target) - - if args.lang_pairs is None: - raise ValueError( - "--lang-pairs is required. List all the language pairs in the training objective." - ) - if isinstance(args.lang_pairs, str): - args.lang_pairs = args.lang_pairs.split(",") - - @classmethod - def prepare(cls, args, **kargs): - cls.update_args(args) - sorted_langs = sorted( - list({x for lang_pair in args.lang_pairs for x in lang_pair.split("-")}) - ) - if args.source_lang is not None or args.target_lang is not None: - training = False - else: - training = True - - # load dictionaries - dicts = OrderedDict() - for lang in sorted_langs: - paths = utils.split_paths(args.data) - assert len(paths) > 0 - dicts[lang] = cls.load_dictionary( - os.path.join(paths[0], "dict.{}.txt".format(lang)) - ) - if len(dicts) > 0: - assert dicts[lang].pad() == dicts[sorted_langs[0]].pad() - assert dicts[lang].eos() == dicts[sorted_langs[0]].eos() - assert dicts[lang].unk() == dicts[sorted_langs[0]].unk() - if args.encoder_langtok is not None or args.decoder_langtok: - for lang_to_add in sorted_langs: - dicts[lang].add_symbol(_lang_token(lang_to_add)) - logger.info("[{}] dictionary: {} types".format(lang, len(dicts[lang]))) - return dicts, training - - def get_encoder_langtok(self, src_lang, tgt_lang): - if self.args.encoder_langtok is None: - return self.dicts[src_lang].eos() - if self.args.encoder_langtok == "src": - return _lang_token_index(self.dicts[src_lang], src_lang) - else: - return _lang_token_index(self.dicts[src_lang], tgt_lang) - - def get_decoder_langtok(self, tgt_lang): - if not self.args.decoder_langtok: - return self.dicts[tgt_lang].eos() - return _lang_token_index(self.dicts[tgt_lang], tgt_lang) - - def alter_dataset_langtok( - self, - lang_pair_dataset, - src_eos=None, - src_lang=None, - tgt_eos=None, - tgt_lang=None, - ): - if self.args.encoder_langtok is None and not self.args.decoder_langtok: - return lang_pair_dataset - - new_src_eos = None - if ( - self.args.encoder_langtok is not None - and src_eos is not None - and src_lang is not None - and tgt_lang is not None - ): - new_src_eos = self.get_encoder_langtok(src_lang, tgt_lang) - else: - src_eos = None - - new_tgt_bos = None - if self.args.decoder_langtok and tgt_eos is not None and tgt_lang is not None: - new_tgt_bos = self.get_decoder_langtok(tgt_lang) - else: - tgt_eos = None - - return TransformEosLangPairDataset( - lang_pair_dataset, - src_eos=src_eos, - new_src_eos=new_src_eos, - tgt_bos=tgt_eos, - new_tgt_bos=new_tgt_bos, - ) - - def load_dataset(self, split, epoch=1, **kwargs): - """Load a dataset split.""" - paths = utils.split_paths(self.args.data) - assert len(paths) > 0 - data_path = paths[(epoch - 1) % len(paths)] - - def language_pair_dataset(lang_pair): - src, tgt = lang_pair.split("-") - langpair_dataset = load_langpair_dataset( - data_path, - split, - src, - self.dicts[src], - tgt, - self.dicts[tgt], - combine=True, - dataset_impl=self.args.dataset_impl, - upsample_primary=self.args.upsample_primary, - left_pad_source=self.args.left_pad_source, - left_pad_target=self.args.left_pad_target, - max_source_positions=self.args.max_source_positions, - max_target_positions=self.args.max_target_positions, - ) - return self.alter_dataset_langtok( - langpair_dataset, - src_eos=self.dicts[src].eos(), - src_lang=src, - tgt_eos=self.dicts[tgt].eos(), - tgt_lang=tgt, - ) - - self.datasets[split] = RoundRobinZipDatasets( - OrderedDict( - [ - (lang_pair, language_pair_dataset(lang_pair)) - for lang_pair in self.lang_pairs - ] - ), - eval_key=None - if self.training - else "%s-%s" % (self.args.source_lang, self.args.target_lang), - ) - - def build_dataset_for_inference(self, src_tokens, src_lengths, constraints=None): - if constraints is not None: - raise NotImplementedError( - "Constrained decoding with the multilingual_translation task is not supported" - ) - - lang_pair = "%s-%s" % (self.args.source_lang, self.args.target_lang) - return RoundRobinZipDatasets( - OrderedDict( - [ - ( - lang_pair, - self.alter_dataset_langtok( - LanguagePairDataset( - src_tokens, src_lengths, self.source_dictionary - ), - src_eos=self.source_dictionary.eos(), - src_lang=self.args.source_lang, - tgt_eos=self.target_dictionary.eos(), - tgt_lang=self.args.target_lang, - ), - ) - ] - ), - eval_key=lang_pair, - ) - - def build_model(self, args): - def check_args(): - messages = [] - if ( - len(set(self.args.lang_pairs).symmetric_difference(args.lang_pairs)) - != 0 - ): - messages.append( - "--lang-pairs should include all the language pairs {}.".format( - args.lang_pairs - ) - ) - if self.args.encoder_langtok != args.encoder_langtok: - messages.append( - "--encoder-langtok should be {}.".format(args.encoder_langtok) - ) - if self.args.decoder_langtok != args.decoder_langtok: - messages.append( - "--decoder-langtok should {} be set.".format( - "" if args.decoder_langtok else "not" - ) - ) - - if len(messages) > 0: - raise ValueError(" ".join(messages)) - - # Update args -> the fact that the constructor here - # changes the args object doesn't mean you get the same one here - self.update_args(args) - - # Check if task args are consistant with model args - check_args() - - from fairseq import models - - model = models.build_model(args, self) - if not isinstance(model, FairseqMultiModel): - raise ValueError( - "MultilingualTranslationTask requires a FairseqMultiModel architecture" - ) - return model - - def _per_lang_pair_train_loss( - self, lang_pair, model, update_num, criterion, sample, optimizer, ignore_grad - ): - loss, sample_size, logging_output = criterion( - model.models[lang_pair], sample[lang_pair] - ) - if ignore_grad: - loss *= 0 - optimizer.backward(loss) - return loss, sample_size, logging_output - - def train_step( - self, sample, model, criterion, optimizer, update_num, ignore_grad=False - ): - model.train() - from collections import defaultdict - - agg_loss, agg_sample_size, agg_logging_output = 0.0, 0.0, defaultdict(float) - curr_lang_pairs = [ - lang_pair - for lang_pair in self.model_lang_pairs - if sample[lang_pair] is not None and len(sample[lang_pair]) != 0 - ] - - for idx, lang_pair in enumerate(curr_lang_pairs): - - def maybe_no_sync(): - if ( - self.args.distributed_world_size > 1 - and hasattr(model, "no_sync") - and idx < len(curr_lang_pairs) - 1 - ): - return model.no_sync() - else: - return contextlib.ExitStack() # dummy contextmanager - - with maybe_no_sync(): - loss, sample_size, logging_output = self._per_lang_pair_train_loss( - lang_pair, - model, - update_num, - criterion, - sample, - optimizer, - ignore_grad, - ) - agg_loss += loss.detach().item() - # TODO make summing of the sample sizes configurable - agg_sample_size += sample_size - for k in logging_output: - agg_logging_output[k] += logging_output[k] - agg_logging_output[f"{lang_pair}:{k}"] += logging_output[k] - return agg_loss, agg_sample_size, agg_logging_output - - def _per_lang_pair_valid_loss(self, lang_pair, model, criterion, sample): - return criterion(model.models[lang_pair], sample[lang_pair]) - - def valid_step(self, sample, model, criterion): - model.eval() - with torch.no_grad(): - from collections import defaultdict - - agg_loss, agg_sample_size, agg_logging_output = 0.0, 0.0, defaultdict(float) - for lang_pair in self.eval_lang_pairs: - if ( - lang_pair not in sample - or sample[lang_pair] is None - or len(sample[lang_pair]) == 0 - ): - continue - loss, sample_size, logging_output = self._per_lang_pair_valid_loss( - lang_pair, model, criterion, sample - ) - agg_loss += loss.data.item() - # TODO make summing of the sample sizes configurable - agg_sample_size += sample_size - for k in logging_output: - agg_logging_output[k] += logging_output[k] - agg_logging_output[f"{lang_pair}:{k}"] += logging_output[k] - return agg_loss, agg_sample_size, agg_logging_output - - def inference_step( - self, generator, models, sample, prefix_tokens=None, constraints=None - ): - with torch.no_grad(): - if self.args.decoder_langtok: - bos_token = _lang_token_index( - self.target_dictionary, self.args.target_lang - ) - else: - bos_token = self.target_dictionary.eos() - return generator.generate( - models, - sample, - prefix_tokens=prefix_tokens, - constraints=constraints, - bos_token=bos_token, - ) - - def reduce_metrics(self, logging_outputs, criterion): - with metrics.aggregate(): - # pass 'sample_size', 'nsentences', 'ntokens' stats to fairseq_task - super().reduce_metrics(logging_outputs, criterion) - for k in ["sample_size", "nsentences", "ntokens"]: - metrics.log_scalar(k, sum(l[k] for l in logging_outputs)) - - @property - def source_dictionary(self): - if self.training: - return next(iter(self.dicts.values())) - else: - return self.dicts[self.args.source_lang] - - @property - def target_dictionary(self): - if self.training: - return next(iter(self.dicts.values())) - else: - return self.dicts[self.args.target_lang] - - def max_positions(self): - """Return the max sentence length allowed by the task.""" - if len(self.datasets.values()) == 0: - return { - "%s-%s" - % (self.args.source_lang, self.args.target_lang): ( - self.args.max_source_positions, - self.args.max_target_positions, - ) - } - return OrderedDict( - [ - (key, (self.args.max_source_positions, self.args.max_target_positions)) - for split in self.datasets.keys() - for key in self.datasets[split].datasets.keys() - ] - ) diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/models/nat/fairseq_nat_model.py b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/models/nat/fairseq_nat_model.py deleted file mode 100644 index b09394112f57d9e82f2a4cbc371af888281b9e8a..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/models/nat/fairseq_nat_model.py +++ /dev/null @@ -1,170 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import math - -import torch -from fairseq.models.transformer import ( - TransformerDecoder, - TransformerEncoder, - TransformerModel, -) -from fairseq.modules.transformer_sentence_encoder import init_bert_params - - -def ensemble_encoder(func): - def wrapper(self, *args, **kwargs): - if self.ensemble_models is None or len(self.ensemble_models) == 1: - return func(self, *args, **kwargs) - encoder_outs = [func(model, *args, **kwargs, return_all_hiddens=True) for model in self.ensemble_models] - _encoder_out = encoder_outs[0].copy() - - def stack(key): - outs = [e[key][0] for e in encoder_outs] - return [torch.stack(outs, -1) if outs[0] is not None else None] - - _encoder_out["encoder_out"] = stack("encoder_out") - _encoder_out["encoder_embedding"] = stack("encoder_embedding") - - num_layers = len(_encoder_out["encoder_states"]) - if num_layers > 0: - _encoder_out["encoder_states"] = [ - torch.stack([e["encoder_states"][i] for e in encoder_outs], -1) - for i in range(num_layers) - ] - return _encoder_out - - return wrapper - - -def ensemble_decoder(func): - def wrapper(self, normalize=False, encoder_out=None, *args, **kwargs): - if self.ensemble_models is None or len(self.ensemble_models) == 1: - return func( - self, normalize=normalize, encoder_out=encoder_out, *args, **kwargs - ) - - def _replace(encoder_out, new_val): - new_encoder_out = encoder_out.copy() - new_encoder_out["encoder_out"] = [new_val] - return new_encoder_out - - action_outs = [ - func( - model, - normalize=normalize, - encoder_out=_replace( - encoder_out, - encoder_out["encoder_out"][0][:, :, :, i] - ), - *args, - **kwargs - ) - for i, model in enumerate(self.ensemble_models) - ] - - if not isinstance(action_outs[0], tuple): # return multiple values - action_outs = [[a] for a in action_outs] - else: - action_outs = [list(a) for a in action_outs] - - ensembled_outs = [] - for i in range(len(action_outs[0])): - if i == 0 and normalize: - ensembled_outs += [ - torch.logsumexp( - torch.stack([a[i] for a in action_outs], -1), dim=-1 - ) - - math.log(len(self.ensemble_models)) - ] - elif action_outs[0][i] is not None: - ensembled_outs += [torch.stack([a[i] for a in action_outs], -1)] - else: - ensembled_outs += [None] - - if len(ensembled_outs) == 1: - return ensembled_outs[0] - return tuple(ensembled_outs) - - return wrapper - - -class FairseqNATModel(TransformerModel): - """ - Abstract class for all nonautoregressive-based models - """ - - def __init__(self, args, encoder, decoder): - super().__init__(args, encoder, decoder) - self.tgt_dict = decoder.dictionary - self.bos = decoder.dictionary.bos() - self.eos = decoder.dictionary.eos() - self.pad = decoder.dictionary.pad() - self.unk = decoder.dictionary.unk() - - self.ensemble_models = None - - @property - def allow_length_beam(self): - return False - - @property - def allow_ensemble(self): - return True - - def enable_ensemble(self, models): - self.encoder.ensemble_models = [m.encoder for m in models] - self.decoder.ensemble_models = [m.decoder for m in models] - - @staticmethod - def add_args(parser): - TransformerModel.add_args(parser) - parser.add_argument( - "--apply-bert-init", - action="store_true", - help="use custom param initialization for BERT", - ) - - @classmethod - def build_decoder(cls, args, tgt_dict, embed_tokens): - decoder = FairseqNATDecoder(args, tgt_dict, embed_tokens) - if getattr(args, "apply_bert_init", False): - decoder.apply(init_bert_params) - return decoder - - @classmethod - def build_encoder(cls, args, src_dict, embed_tokens): - encoder = FairseqNATEncoder(args, src_dict, embed_tokens) - if getattr(args, "apply_bert_init", False): - encoder.apply(init_bert_params) - return encoder - - def forward_encoder(self, encoder_inputs): - return self.encoder(*encoder_inputs) - - def forward_decoder(self, *args, **kwargs): - return NotImplementedError - - def initialize_output_tokens(self, *args, **kwargs): - return NotImplementedError - - def forward(self, *args, **kwargs): - return NotImplementedError - - -class FairseqNATEncoder(TransformerEncoder): - def __init__(self, args, dictionary, embed_tokens): - super().__init__(args, dictionary, embed_tokens) - self.ensemble_models = None - - @ensemble_encoder - def forward(self, *args, **kwargs): - return super().forward(*args, **kwargs) - - -class FairseqNATDecoder(TransformerDecoder): - def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False): - super().__init__(args, dictionary, embed_tokens, no_encoder_attn) - self.ensemble_models = None diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/scripts/constraints/validate.py b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/scripts/constraints/validate.py deleted file mode 100644 index d531ad9f39b1df42c98fe8f26ad61fe53a9ac0c5..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/scripts/constraints/validate.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python3 -# -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import sys - - -"""Reads in a fairseq output file, and verifies that the constraints -(C- lines) are present in the output (the first H- line). Assumes that -constraints are listed prior to the first hypothesis. -""" - -constraints = [] -found = 0 -total = 0 -for line in sys.stdin: - if line.startswith("C-"): - constraints.append(line.rstrip().split("\t")[1]) - elif line.startswith("H-"): - text = line.split("\t")[2] - - for constraint in constraints: - total += 1 - if constraint in text: - found += 1 - else: - print(f"No {constraint} in {text}", file=sys.stderr) - - constraints = [] - -print(f"Found {found} / {total} = {100 * found / total:.1f}%") diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/speech_recognition/data/replabels.py b/spaces/OFA-Sys/OFA-vqa/fairseq/examples/speech_recognition/data/replabels.py deleted file mode 100644 index 441f1bd432b95865fc981c6c695cee299b07ed62..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/speech_recognition/data/replabels.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -""" -Replabel transforms for use with flashlight's ASG criterion. -""" - - -def replabel_symbol(i): - """ - Replabel symbols used in flashlight, currently just "1", "2", ... - This prevents training with numeral tokens, so this might change in the future - """ - return str(i) - - -def pack_replabels(tokens, dictionary, max_reps): - """ - Pack a token sequence so that repeated symbols are replaced by replabels - """ - if len(tokens) == 0 or max_reps <= 0: - return tokens - - replabel_value_to_idx = [0] * (max_reps + 1) - for i in range(1, max_reps + 1): - replabel_value_to_idx[i] = dictionary.index(replabel_symbol(i)) - - result = [] - prev_token = -1 - num_reps = 0 - for token in tokens: - if token == prev_token and num_reps < max_reps: - num_reps += 1 - else: - if num_reps > 0: - result.append(replabel_value_to_idx[num_reps]) - num_reps = 0 - result.append(token) - prev_token = token - if num_reps > 0: - result.append(replabel_value_to_idx[num_reps]) - return result - - -def unpack_replabels(tokens, dictionary, max_reps): - """ - Unpack a token sequence so that replabels are replaced by repeated symbols - """ - if len(tokens) == 0 or max_reps <= 0: - return tokens - - replabel_idx_to_value = {} - for i in range(1, max_reps + 1): - replabel_idx_to_value[dictionary.index(replabel_symbol(i))] = i - - result = [] - prev_token = -1 - for token in tokens: - try: - for _ in range(replabel_idx_to_value[token]): - result.append(prev_token) - prev_token = -1 - except KeyError: - result.append(token) - prev_token = token - return result diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/modules/dynamicconv_layer/setup.py b/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/modules/dynamicconv_layer/setup.py deleted file mode 100644 index 6a21f7e2ee0840a3b251522275a0b32a856951d7..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/modules/dynamicconv_layer/setup.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python3 -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -from setuptools import setup -from torch.utils.cpp_extension import BuildExtension, CUDAExtension - - -setup( - name="dynamicconv_layer", - ext_modules=[ - CUDAExtension( - name="dynamicconv_cuda", - sources=[ - "dynamicconv_cuda.cpp", - "dynamicconv_cuda_kernel.cu", - ], - ), - ], - cmdclass={"build_ext": BuildExtension}, -) diff --git a/spaces/OFA-Sys/OFA-vqa/run_scripts/caption/train_caption_stage1.sh b/spaces/OFA-Sys/OFA-vqa/run_scripts/caption/train_caption_stage1.sh deleted file mode 100644 index 08cf67ee91eebe144996fcf559c0684dc81e1494..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/run_scripts/caption/train_caption_stage1.sh +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env - -log_dir=./stage1_logs -save_dir=./stage1_checkpoints -mkdir -p $log_dir $save_dir - -bpe_dir=../../utils/BPE -user_dir=../../ofa_module - -data_dir=../../dataset/caption_data -data=${data_dir}/caption_stage1_train.tsv,${data_dir}/caption_val.tsv -restore_file=../../checkpoints/ofa_large.pt -selected_cols=0,4,2 - -task=caption -arch=ofa_large -criterion=ajust_label_smoothed_cross_entropy -label_smoothing=0.1 -lr=1e-5 -max_epoch=5 -warmup_ratio=0.06 -batch_size=8 -update_freq=4 -resnet_drop_path_rate=0.0 -encoder_drop_path_rate=0.1 -decoder_drop_path_rate=0.1 -dropout=0.1 -attention_dropout=0.0 -max_src_length=80 -max_tgt_length=20 -num_bins=1000 -patch_image_size=480 -eval_cider_cached=${data_dir}/cider_cached_tokens/coco-valid-words.p -drop_worst_ratio=0.2 - -for max_epoch in {2,}; do - echo "max_epoch "${max_epoch} - for warmup_ratio in {0.06,}; do - echo "warmup_ratio "${warmup_ratio} - for drop_worst_after in {2500,}; do - echo "drop_worst_after "${drop_worst_after} - - log_file=${log_dir}/${max_epoch}"_"${warmup_ratio}"_"${drop_worst_after}".log" - save_path=${save_dir}/${max_epoch}"_"${warmup_ratio}"_"${drop_worst_after} - mkdir -p $save_path - - CUDA_VISIBLE_DEVICES=0,1,2,3 python3 ../../train.py \ - $data \ - --selected-cols=${selected_cols} \ - --bpe-dir=${bpe_dir} \ - --user-dir=${user_dir} \ - --restore-file=${restore_file} \ - --reset-optimizer --reset-dataloader --reset-meters \ - --save-dir=${save_path} \ - --task=${task} \ - --arch=${arch} \ - --criterion=${criterion} \ - --label-smoothing=${label_smoothing} \ - --batch-size=${batch_size} \ - --update-freq=${update_freq} \ - --encoder-normalize-before \ - --decoder-normalize-before \ - --share-decoder-input-output-embed \ - --share-all-embeddings \ - --layernorm-embedding \ - --patch-layernorm-embedding \ - --code-layernorm-embedding \ - --resnet-drop-path-rate=${resnet_drop_path_rate} \ - --encoder-drop-path-rate=${encoder_drop_path_rate} \ - --decoder-drop-path-rate=${decoder_drop_path_rate} \ - --dropout=${dropout} \ - --attention-dropout=${attention_dropout} \ - --weight-decay=0.01 --optimizer=adam --adam-betas="(0.9,0.999)" --adam-eps=1e-08 --clip-norm=1.0 \ - --lr-scheduler=polynomial_decay --lr=${lr} \ - --max-epoch=${max_epoch} --warmup-ratio=${warmup_ratio} \ - --log-format=simple --log-interval=10 \ - --fixed-validation-seed=7 \ - --no-epoch-checkpoints --keep-best-checkpoints=1 \ - --save-interval=1 --validate-interval=1 \ - --save-interval-updates=500 --validate-interval-updates=500 \ - --eval-cider \ - --eval-cider-cached-tokens=${eval_cider_cached} \ - --eval-args='{"beam":5,"max_len_b":16,"no_repeat_ngram_size":3}' \ - --best-checkpoint-metric=cider --maximize-best-checkpoint-metric \ - --max-src-length=${max_src_length} \ - --max-tgt-length=${max_tgt_length} \ - --find-unused-parameters \ - --freeze-encoder-embedding \ - --freeze-decoder-embedding \ - --add-type-embedding \ - --scale-attn \ - --scale-fc \ - --scale-heads \ - --disable-entangle \ - --num-bins=${num_bins} \ - --patch-image-size=${patch_image_size} \ - --drop-worst-ratio=${drop_worst_ratio} \ - --drop-worst-after=${drop_worst_after} \ - --fp16 \ - --fp16-scale-window=512 \ - --num-workers=0 >> ${log_file} 2>&1 - done - done -done \ No newline at end of file diff --git a/spaces/Omnibus/MusicGen/audiocraft/modules/activations.py b/spaces/Omnibus/MusicGen/audiocraft/modules/activations.py deleted file mode 100644 index 8bd6f2917a56d72db56555d0ff54b2311bc21778..0000000000000000000000000000000000000000 --- a/spaces/Omnibus/MusicGen/audiocraft/modules/activations.py +++ /dev/null @@ -1,96 +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 -import torch.nn as nn -from torch import Tensor -from typing import Union, Callable - - -class CustomGLU(nn.Module): - """Custom Gated Linear Unit activation. - Applies a modified gated linear unit :math:`a * f(b)` where :math:`a` is the first half - of the input matrices, :math:`b` is the second half, and :math:`f` is a provided activation - function (i.e. sigmoid, swish, etc.). - - Args: - activation (nn.Module): The custom activation to apply in the Gated Linear Unit - dim (int): the dimension on which to split the input. Default: -1 - - Shape: - - Input: :math:`(\ast_1, N, \ast_2)` where `*` means, any number of additional - dimensions - - Output: :math:`(\ast_1, M, \ast_2)` where :math:`M=N/2` - - Examples:: - >>> m = CustomGLU(nn.Sigmoid()) - >>> input = torch.randn(4, 2) - >>> output = m(input) - """ - def __init__(self, activation: nn.Module, dim: int = -1): - super(CustomGLU, self).__init__() - self.dim = dim - self.activation = activation - - def forward(self, x: Tensor): - assert x.shape[self.dim] % 2 == 0 # M = N / 2 - a, b = torch.chunk(x, 2, dim=self.dim) - return a * self.activation(b) - - -class SwiGLU(CustomGLU): - """SiLU Gated Linear Unit activation. - Applies SiLU Gated Linear Unit :math:`a * SiLU(b)` where :math:`a` is - the first half of the input matrices, :math:`b` is the second half. - - Args: - dim (int): the dimension on which to split the input. Default: -1 - """ - def __init__(self, dim: int = -1): - super(SwiGLU, self).__init__(nn.SiLU(), dim) - - -class GeGLU(CustomGLU): - """GeLU Gated Linear Unit activation. - Applies GeLU Gated Linear Unit :math:`a * GELU(b)` where :math:`a` is - the first half of the input matrices, :math:`b` is the second half. - - Args: - dim (int): the dimension on which to split the input. Default: -1 - """ - def __init__(self, dim: int = -1): - super(GeGLU, self).__init__(nn.GELU(), dim) - - -class ReGLU(CustomGLU): - """ReLU Gated Linear Unit activation. - Applies ReLU Gated Linear Unit :math:`a * ReLU(b)` where :math:`a` is - the first half of the input matrices, :math:`b` is the second half. - - Args: - dim (int): the dimension on which to split the input. Default: -1 - """ - def __init__(self, dim: int = -1): - super(ReGLU, self).__init__(nn.ReLU(), dim) - - -def get_activation_fn( - activation: Union[str, Callable[[Tensor], Tensor]] -) -> Union[str, Callable[[Tensor], Tensor]]: - """Helper function to map an activation string to the activation class. - If the supplied activation is not a string that is recognized, the activation is passed back. - - Args: - activation (Union[str, Callable[[Tensor], Tensor]]): Activation to check - """ - if isinstance(activation, str): - if activation == "reglu": - return ReGLU() - elif activation == "geglu": - return GeGLU() - elif activation == "swiglu": - return SwiGLU() - return activation diff --git a/spaces/OpenDILabCommunity/DI-sheep/DI-sheep/ui/LICENSE.md b/spaces/OpenDILabCommunity/DI-sheep/DI-sheep/ui/LICENSE.md deleted file mode 100644 index f288702d2fa16d3cdf0035b15a9fcbc552cd88e7..0000000000000000000000000000000000000000 --- a/spaces/OpenDILabCommunity/DI-sheep/DI-sheep/ui/LICENSE.md +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - 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 . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/spaces/OpenGVLab/InternGPT/iGPT/__init__.py b/spaces/OpenGVLab/InternGPT/iGPT/__init__.py deleted file mode 100644 index aed4fa323c2c8001593fdfdcd878a21718800167..0000000000000000000000000000000000000000 --- a/spaces/OpenGVLab/InternGPT/iGPT/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .models import * diff --git a/spaces/OpenMotionLab/MotionGPT/mGPT/data/tools/easyconvert.py b/spaces/OpenMotionLab/MotionGPT/mGPT/data/tools/easyconvert.py deleted file mode 100644 index 3649a93f947d47beb872fdc3f933d0b81fc56b37..0000000000000000000000000000000000000000 --- a/spaces/OpenMotionLab/MotionGPT/mGPT/data/tools/easyconvert.py +++ /dev/null @@ -1,72 +0,0 @@ -from .geometry import * - -def nfeats_of(rottype): - if rottype in ["rotvec", "axisangle"]: - return 3 - elif rottype in ["rotquat", "quaternion"]: - return 4 - elif rottype in ["rot6d", "6drot", "rotation6d"]: - return 6 - elif rottype in ["rotmat"]: - return 9 - else: - return TypeError("This rotation type doesn't have features.") - - -def axis_angle_to(newtype, rotations): - if newtype in ["matrix"]: - rotations = axis_angle_to_matrix(rotations) - return rotations - elif newtype in ["rotmat"]: - rotations = axis_angle_to_matrix(rotations) - rotations = matrix_to("rotmat", rotations) - return rotations - elif newtype in ["rot6d", "6drot", "rotation6d"]: - rotations = axis_angle_to_matrix(rotations) - rotations = matrix_to("rot6d", rotations) - return rotations - elif newtype in ["rotquat", "quaternion"]: - rotations = axis_angle_to_quaternion(rotations) - return rotations - elif newtype in ["rotvec", "axisangle"]: - return rotations - else: - raise NotImplementedError - - -def matrix_to(newtype, rotations): - if newtype in ["matrix"]: - return rotations - if newtype in ["rotmat"]: - rotations = rotations.reshape((*rotations.shape[:-2], 9)) - return rotations - elif newtype in ["rot6d", "6drot", "rotation6d"]: - rotations = matrix_to_rotation_6d(rotations) - return rotations - elif newtype in ["rotquat", "quaternion"]: - rotations = matrix_to_quaternion(rotations) - return rotations - elif newtype in ["rotvec", "axisangle"]: - rotations = matrix_to_axis_angle(rotations) - return rotations - else: - raise NotImplementedError - - -def to_matrix(oldtype, rotations): - if oldtype in ["matrix"]: - return rotations - if oldtype in ["rotmat"]: - rotations = rotations.reshape((*rotations.shape[:-2], 3, 3)) - return rotations - elif oldtype in ["rot6d", "6drot", "rotation6d"]: - rotations = rotation_6d_to_matrix(rotations) - return rotations - elif oldtype in ["rotquat", "quaternion"]: - rotations = quaternion_to_matrix(rotations) - return rotations - elif oldtype in ["rotvec", "axisangle"]: - rotations = axis_angle_to_matrix(rotations) - return rotations - else: - raise NotImplementedError diff --git a/spaces/PKUWilliamYang/StyleGANEX/models/stylegan2/simple_augment.py b/spaces/PKUWilliamYang/StyleGANEX/models/stylegan2/simple_augment.py deleted file mode 100644 index 77776cd134046dc012e021d0ab80c1e0b90d2275..0000000000000000000000000000000000000000 --- a/spaces/PKUWilliamYang/StyleGANEX/models/stylegan2/simple_augment.py +++ /dev/null @@ -1,478 +0,0 @@ -import math - -import torch -from torch import autograd -from torch.nn import functional as F -import numpy as np - -from torch import distributed as dist -#from distributed import reduce_sum -from models.stylegan2.op2 import upfirdn2d - -def reduce_sum(tensor): - if not dist.is_available(): - return tensor - - if not dist.is_initialized(): - return tensor - - tensor = tensor.clone() - dist.all_reduce(tensor, op=dist.ReduceOp.SUM) - - return tensor - - -class AdaptiveAugment: - def __init__(self, ada_aug_target, ada_aug_len, update_every, device): - self.ada_aug_target = ada_aug_target - self.ada_aug_len = ada_aug_len - self.update_every = update_every - - self.ada_update = 0 - self.ada_aug_buf = torch.tensor([0.0, 0.0], device=device) - self.r_t_stat = 0 - self.ada_aug_p = 0 - - @torch.no_grad() - def tune(self, real_pred): - self.ada_aug_buf += torch.tensor( - (torch.sign(real_pred).sum().item(), real_pred.shape[0]), - device=real_pred.device, - ) - self.ada_update += 1 - - if self.ada_update % self.update_every == 0: - self.ada_aug_buf = reduce_sum(self.ada_aug_buf) - pred_signs, n_pred = self.ada_aug_buf.tolist() - - self.r_t_stat = pred_signs / n_pred - - if self.r_t_stat > self.ada_aug_target: - sign = 1 - - else: - sign = -1 - - self.ada_aug_p += sign * n_pred / self.ada_aug_len - self.ada_aug_p = min(1, max(0, self.ada_aug_p)) - self.ada_aug_buf.mul_(0) - self.ada_update = 0 - - return self.ada_aug_p - - -SYM6 = ( - 0.015404109327027373, - 0.0034907120842174702, - -0.11799011114819057, - -0.048311742585633, - 0.4910559419267466, - 0.787641141030194, - 0.3379294217276218, - -0.07263752278646252, - -0.021060292512300564, - 0.04472490177066578, - 0.0017677118642428036, - -0.007800708325034148, -) - - -def translate_mat(t_x, t_y, device="cpu"): - batch = t_x.shape[0] - - mat = torch.eye(3, device=device).unsqueeze(0).repeat(batch, 1, 1) - translate = torch.stack((t_x, t_y), 1) - mat[:, :2, 2] = translate - - return mat - - -def rotate_mat(theta, device="cpu"): - batch = theta.shape[0] - - mat = torch.eye(3, device=device).unsqueeze(0).repeat(batch, 1, 1) - sin_t = torch.sin(theta) - cos_t = torch.cos(theta) - rot = torch.stack((cos_t, -sin_t, sin_t, cos_t), 1).view(batch, 2, 2) - mat[:, :2, :2] = rot - - return mat - - -def scale_mat(s_x, s_y, device="cpu"): - batch = s_x.shape[0] - - mat = torch.eye(3, device=device).unsqueeze(0).repeat(batch, 1, 1) - mat[:, 0, 0] = s_x - mat[:, 1, 1] = s_y - - return mat - - -def translate3d_mat(t_x, t_y, t_z): - batch = t_x.shape[0] - - mat = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1) - translate = torch.stack((t_x, t_y, t_z), 1) - mat[:, :3, 3] = translate - - return mat - - -def rotate3d_mat(axis, theta): - batch = theta.shape[0] - - u_x, u_y, u_z = axis - - eye = torch.eye(3).unsqueeze(0) - cross = torch.tensor([(0, -u_z, u_y), (u_z, 0, -u_x), (-u_y, u_x, 0)]).unsqueeze(0) - outer = torch.tensor(axis) - outer = (outer.unsqueeze(1) * outer).unsqueeze(0) - - sin_t = torch.sin(theta).view(-1, 1, 1) - cos_t = torch.cos(theta).view(-1, 1, 1) - - rot = cos_t * eye + sin_t * cross + (1 - cos_t) * outer - - eye_4 = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1) - eye_4[:, :3, :3] = rot - - return eye_4 - - -def scale3d_mat(s_x, s_y, s_z): - batch = s_x.shape[0] - - mat = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1) - mat[:, 0, 0] = s_x - mat[:, 1, 1] = s_y - mat[:, 2, 2] = s_z - - return mat - - -def luma_flip_mat(axis, i): - batch = i.shape[0] - - eye = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1) - axis = torch.tensor(axis + (0,)) - flip = 2 * torch.ger(axis, axis) * i.view(-1, 1, 1) - - return eye - flip - - -def saturation_mat(axis, i): - batch = i.shape[0] - - eye = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1) - axis = torch.tensor(axis + (0,)) - axis = torch.ger(axis, axis) - saturate = axis + (eye - axis) * i.view(-1, 1, 1) - - return saturate - - -def lognormal_sample(size, mean=0, std=1, device="cpu"): - return torch.empty(size, device=device).log_normal_(mean=mean, std=std) - - -def category_sample(size, categories, device="cpu"): - category = torch.tensor(categories, device=device) - sample = torch.randint(high=len(categories), size=(size,), device=device) - - return category[sample] - - -def uniform_sample(size, low, high, device="cpu"): - return torch.empty(size, device=device).uniform_(low, high) - - -def normal_sample(size, mean=0, std=1, device="cpu"): - return torch.empty(size, device=device).normal_(mean, std) - - -def bernoulli_sample(size, p, device="cpu"): - return torch.empty(size, device=device).bernoulli_(p) - - -def random_mat_apply(p, transform, prev, eye, device="cpu"): - size = transform.shape[0] - select = bernoulli_sample(size, p, device=device).view(size, 1, 1) - select_transform = select * transform + (1 - select) * eye - - return select_transform @ prev - - -def sample_affine(p, size, height, width, device="cpu"): - G = torch.eye(3, device=device).unsqueeze(0).repeat(size, 1, 1) - eye = G - - # flip - #param = category_sample(size, (0, 1)) - #Gc = scale_mat(1 - 2.0 * param, torch.ones(size), device=device) - #G = random_mat_apply(p, Gc, G, eye, device=device) - # print('flip', G, scale_mat(1 - 2.0 * param, torch.ones(size)), sep='\n') - - # 90 rotate - #param = category_sample(size, (0, 3)) - #Gc = rotate_mat(-math.pi / 2 * param, device=device) - #G = random_mat_apply(p, Gc, G, eye, device=device) - # print('90 rotate', G, rotate_mat(-math.pi / 2 * param), sep='\n') - - # integer translate - param = uniform_sample(size, -0.125, 0.125) - param_height = torch.round(param * height) / height - param_width = torch.round(param * width) / width - Gc = translate_mat(param_width, param_height, device=device) - G = random_mat_apply(p, Gc, G, eye, device=device) - # print('integer translate', G, translate_mat(param_width, param_height), sep='\n') - - # isotropic scale - param = lognormal_sample(size, std=0.1 * math.log(2)) - Gc = scale_mat(param, param, device=device) - G = random_mat_apply(p, Gc, G, eye, device=device) - # print('isotropic scale', G, scale_mat(param, param), sep='\n') - - p_rot = 1 - math.sqrt(1 - p) - - # pre-rotate - param = uniform_sample(size, -math.pi * 0.25, math.pi * 0.25) - Gc = rotate_mat(-param, device=device) - G = random_mat_apply(p_rot, Gc, G, eye, device=device) - # print('pre-rotate', G, rotate_mat(-param), sep='\n') - - # anisotropic scale - param = lognormal_sample(size, std=0.1 * math.log(2)) - Gc = scale_mat(param, 1 / param, device=device) - G = random_mat_apply(p, Gc, G, eye, device=device) - # print('anisotropic scale', G, scale_mat(param, 1 / param), sep='\n') - - # post-rotate - param = uniform_sample(size, -math.pi * 0.25, math.pi * 0.25) - Gc = rotate_mat(-param, device=device) - G = random_mat_apply(p_rot, Gc, G, eye, device=device) - # print('post-rotate', G, rotate_mat(-param), sep='\n') - - # fractional translate - param = normal_sample(size, std=0.125) - Gc = translate_mat(param, param, device=device) - G = random_mat_apply(p, Gc, G, eye, device=device) - # print('fractional translate', G, translate_mat(param, param), sep='\n') - - return G - - -def sample_color(p, size): - C = torch.eye(4).unsqueeze(0).repeat(size, 1, 1) - eye = C - axis_val = 1 / math.sqrt(3) - axis = (axis_val, axis_val, axis_val) - - # brightness - param = normal_sample(size, std=0.2) - Cc = translate3d_mat(param, param, param) - C = random_mat_apply(p, Cc, C, eye) - - # contrast - param = lognormal_sample(size, std=0.5 * math.log(2)) - Cc = scale3d_mat(param, param, param) - C = random_mat_apply(p, Cc, C, eye) - - # luma flip - param = category_sample(size, (0, 1)) - Cc = luma_flip_mat(axis, param) - C = random_mat_apply(p, Cc, C, eye) - - # hue rotation - param = uniform_sample(size, -math.pi, math.pi) - Cc = rotate3d_mat(axis, param) - C = random_mat_apply(p, Cc, C, eye) - - # saturation - param = lognormal_sample(size, std=1 * math.log(2)) - Cc = saturation_mat(axis, param) - C = random_mat_apply(p, Cc, C, eye) - - return C - - -def make_grid(shape, x0, x1, y0, y1, device): - n, c, h, w = shape - grid = torch.empty(n, h, w, 3, device=device) - grid[:, :, :, 0] = torch.linspace(x0, x1, w, device=device) - grid[:, :, :, 1] = torch.linspace(y0, y1, h, device=device).unsqueeze(-1) - grid[:, :, :, 2] = 1 - - return grid - - -def affine_grid(grid, mat): - n, h, w, _ = grid.shape - return (grid.view(n, h * w, 3) @ mat.transpose(1, 2)).view(n, h, w, 2) - - -def get_padding(G, height, width, kernel_size): - device = G.device - - cx = (width - 1) / 2 - cy = (height - 1) / 2 - cp = torch.tensor( - [(-cx, -cy, 1), (cx, -cy, 1), (cx, cy, 1), (-cx, cy, 1)], device=device - ) - cp = G @ cp.T - - pad_k = kernel_size // 4 - - pad = cp[:, :2, :].permute(1, 0, 2).flatten(1) - pad = torch.cat((-pad, pad)).max(1).values - pad = pad + torch.tensor([pad_k * 2 - cx, pad_k * 2 - cy] * 2, device=device) - pad = pad.max(torch.tensor([0, 0] * 2, device=device)) - pad = pad.min(torch.tensor([width - 1, height - 1] * 2, device=device)) - - pad_x1, pad_y1, pad_x2, pad_y2 = pad.ceil().to(torch.int32) - - return pad_x1, pad_x2, pad_y1, pad_y2 - - -def try_sample_affine_and_pad(img, p, kernel_size, G=None): - batch, _, height, width = img.shape - - G_try = G - - if G is None: - G_try = torch.inverse(sample_affine(p, batch, height, width)) - - pad_x1, pad_x2, pad_y1, pad_y2 = get_padding(G_try, height, width, kernel_size) - - img_pad = F.pad(img, (pad_x1, pad_x2, pad_y1, pad_y2), mode="reflect") - - return img_pad, G_try, (pad_x1, pad_x2, pad_y1, pad_y2) - - -class GridSampleForward(autograd.Function): - @staticmethod - def forward(ctx, input, grid): - out = F.grid_sample( - input, grid, mode="bilinear", padding_mode="zeros", align_corners=False - ) - ctx.save_for_backward(input, grid) - - return out - - @staticmethod - def backward(ctx, grad_output): - input, grid = ctx.saved_tensors - grad_input, grad_grid = GridSampleBackward.apply(grad_output, input, grid) - - return grad_input, grad_grid - - -class GridSampleBackward(autograd.Function): - @staticmethod - def forward(ctx, grad_output, input, grid): - op = torch._C._jit_get_operation("aten::grid_sampler_2d_backward") - grad_input, grad_grid = op(grad_output, input, grid, 0, 0, False) - ctx.save_for_backward(grid) - - return grad_input, grad_grid - - @staticmethod - def backward(ctx, grad_grad_input, grad_grad_grid): - grid, = ctx.saved_tensors - grad_grad_output = None - - if ctx.needs_input_grad[0]: - grad_grad_output = GridSampleForward.apply(grad_grad_input, grid) - - return grad_grad_output, None, None - - -grid_sample = GridSampleForward.apply - - -def scale_mat_single(s_x, s_y): - return torch.tensor(((s_x, 0, 0), (0, s_y, 0), (0, 0, 1)), dtype=torch.float32) - - -def translate_mat_single(t_x, t_y): - return torch.tensor(((1, 0, t_x), (0, 1, t_y), (0, 0, 1)), dtype=torch.float32) - - -def random_apply_affine(img, p, G=None, antialiasing_kernel=SYM6): - kernel = antialiasing_kernel - len_k = len(kernel) - - kernel = torch.as_tensor(kernel).to(img) - # kernel = torch.ger(kernel, kernel).to(img) - kernel_flip = torch.flip(kernel, (0,)) - - img_pad, G, (pad_x1, pad_x2, pad_y1, pad_y2) = try_sample_affine_and_pad( - img, p, len_k, G - ) - - G_inv = ( - translate_mat_single((pad_x1 - pad_x2).item() / 2, (pad_y1 - pad_y2).item() / 2) - @ G - ) - up_pad = ( - (len_k + 2 - 1) // 2, - (len_k - 2) // 2, - (len_k + 2 - 1) // 2, - (len_k - 2) // 2, - ) - img_2x = upfirdn2d(img_pad, kernel.unsqueeze(0), up=(2, 1), pad=(*up_pad[:2], 0, 0)) - img_2x = upfirdn2d(img_2x, kernel.unsqueeze(1), up=(1, 2), pad=(0, 0, *up_pad[2:])) - G_inv = scale_mat_single(2, 2) @ G_inv @ scale_mat_single(1 / 2, 1 / 2) - G_inv = translate_mat_single(-0.5, -0.5) @ G_inv @ translate_mat_single(0.5, 0.5) - batch_size, channel, height, width = img.shape - pad_k = len_k // 4 - shape = (batch_size, channel, (height + pad_k * 2) * 2, (width + pad_k * 2) * 2) - G_inv = ( - scale_mat_single(2 / img_2x.shape[3], 2 / img_2x.shape[2]) - @ G_inv - @ scale_mat_single(1 / (2 / shape[3]), 1 / (2 / shape[2])) - ) - grid = F.affine_grid(G_inv[:, :2, :].to(img_2x), shape, align_corners=False) - img_affine = grid_sample(img_2x, grid) - d_p = -pad_k * 2 - down_pad = ( - d_p + (len_k - 2 + 1) // 2, - d_p + (len_k - 2) // 2, - d_p + (len_k - 2 + 1) // 2, - d_p + (len_k - 2) // 2, - ) - img_down = upfirdn2d( - img_affine, kernel_flip.unsqueeze(0), down=(2, 1), pad=(*down_pad[:2], 0, 0) - ) - img_down = upfirdn2d( - img_down, kernel_flip.unsqueeze(1), down=(1, 2), pad=(0, 0, *down_pad[2:]) - ) - - return img_down, G - - -def apply_color(img, mat): - batch = img.shape[0] - img = img.permute(0, 2, 3, 1) - mat_mul = mat[:, :3, :3].transpose(1, 2).view(batch, 1, 3, 3) - mat_add = mat[:, :3, 3].view(batch, 1, 1, 3) - img = img @ mat_mul + mat_add - img = img.permute(0, 3, 1, 2) - - return img - - -def random_apply_color(img, p, C=None): - if C is None: - C = sample_color(p, img.shape[0]) - - img = apply_color(img, C.to(img)) - - return img, C - - -def augment(img, p, transform_matrix=(None, None)): - img, G = random_apply_affine(img, p, transform_matrix[0]) - img, C = random_apply_color(img, p, transform_matrix[1]) - - return img, (G, C) diff --git a/spaces/Pfs2021Funny/Text-to-Music-ExtendedVersion/README.md b/spaces/Pfs2021Funny/Text-to-Music-ExtendedVersion/README.md deleted file mode 100644 index a4e4d994277b0ddf86f6bf76c9149a2632024d8b..0000000000000000000000000000000000000000 --- a/spaces/Pfs2021Funny/Text-to-Music-ExtendedVersion/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Text To Music -emoji: ⚡ -colorFrom: red -colorTo: green -sdk: gradio -sdk_version: 3.6 -app_file: app.py -pinned: false -license: unknown -duplicated_from: Mubert/Text-to-Music ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Pie31415/control-animation/annotator/uniformer/mmseg/models/backbones/hrnet.py b/spaces/Pie31415/control-animation/annotator/uniformer/mmseg/models/backbones/hrnet.py deleted file mode 100644 index 331ebf3ccb8597b3f507670753789073fc3c946d..0000000000000000000000000000000000000000 --- a/spaces/Pie31415/control-animation/annotator/uniformer/mmseg/models/backbones/hrnet.py +++ /dev/null @@ -1,555 +0,0 @@ -import torch.nn as nn -from annotator.uniformer.mmcv.cnn import (build_conv_layer, build_norm_layer, constant_init, - kaiming_init) -from annotator.uniformer.mmcv.runner import load_checkpoint -from annotator.uniformer.mmcv.utils.parrots_wrapper import _BatchNorm - -from annotator.uniformer.mmseg.ops import Upsample, resize -from annotator.uniformer.mmseg.utils import get_root_logger -from ..builder import BACKBONES -from .resnet import BasicBlock, Bottleneck - - -class HRModule(nn.Module): - """High-Resolution Module for HRNet. - - In this module, every branch has 4 BasicBlocks/Bottlenecks. Fusion/Exchange - is in this module. - """ - - def __init__(self, - num_branches, - blocks, - num_blocks, - in_channels, - num_channels, - multiscale_output=True, - with_cp=False, - conv_cfg=None, - norm_cfg=dict(type='BN', requires_grad=True)): - super(HRModule, self).__init__() - self._check_branches(num_branches, num_blocks, in_channels, - num_channels) - - self.in_channels = in_channels - self.num_branches = num_branches - - self.multiscale_output = multiscale_output - self.norm_cfg = norm_cfg - self.conv_cfg = conv_cfg - self.with_cp = with_cp - self.branches = self._make_branches(num_branches, blocks, num_blocks, - num_channels) - self.fuse_layers = self._make_fuse_layers() - self.relu = nn.ReLU(inplace=False) - - def _check_branches(self, num_branches, num_blocks, in_channels, - num_channels): - """Check branches configuration.""" - if num_branches != len(num_blocks): - error_msg = f'NUM_BRANCHES({num_branches}) <> NUM_BLOCKS(' \ - f'{len(num_blocks)})' - raise ValueError(error_msg) - - if num_branches != len(num_channels): - error_msg = f'NUM_BRANCHES({num_branches}) <> NUM_CHANNELS(' \ - f'{len(num_channels)})' - raise ValueError(error_msg) - - if num_branches != len(in_channels): - error_msg = f'NUM_BRANCHES({num_branches}) <> NUM_INCHANNELS(' \ - f'{len(in_channels)})' - raise ValueError(error_msg) - - def _make_one_branch(self, - branch_index, - block, - num_blocks, - num_channels, - stride=1): - """Build one branch.""" - downsample = None - if stride != 1 or \ - self.in_channels[branch_index] != \ - num_channels[branch_index] * block.expansion: - downsample = nn.Sequential( - build_conv_layer( - self.conv_cfg, - self.in_channels[branch_index], - num_channels[branch_index] * block.expansion, - kernel_size=1, - stride=stride, - bias=False), - build_norm_layer(self.norm_cfg, num_channels[branch_index] * - block.expansion)[1]) - - layers = [] - layers.append( - block( - self.in_channels[branch_index], - num_channels[branch_index], - stride, - downsample=downsample, - with_cp=self.with_cp, - norm_cfg=self.norm_cfg, - conv_cfg=self.conv_cfg)) - self.in_channels[branch_index] = \ - num_channels[branch_index] * block.expansion - for i in range(1, num_blocks[branch_index]): - layers.append( - block( - self.in_channels[branch_index], - num_channels[branch_index], - with_cp=self.with_cp, - norm_cfg=self.norm_cfg, - conv_cfg=self.conv_cfg)) - - return nn.Sequential(*layers) - - def _make_branches(self, num_branches, block, num_blocks, num_channels): - """Build multiple branch.""" - branches = [] - - for i in range(num_branches): - branches.append( - self._make_one_branch(i, block, num_blocks, num_channels)) - - return nn.ModuleList(branches) - - def _make_fuse_layers(self): - """Build fuse layer.""" - if self.num_branches == 1: - return None - - num_branches = self.num_branches - in_channels = self.in_channels - fuse_layers = [] - num_out_branches = num_branches if self.multiscale_output else 1 - for i in range(num_out_branches): - fuse_layer = [] - for j in range(num_branches): - if j > i: - fuse_layer.append( - nn.Sequential( - build_conv_layer( - self.conv_cfg, - in_channels[j], - in_channels[i], - kernel_size=1, - stride=1, - padding=0, - bias=False), - build_norm_layer(self.norm_cfg, in_channels[i])[1], - # we set align_corners=False for HRNet - Upsample( - scale_factor=2**(j - i), - mode='bilinear', - align_corners=False))) - elif j == i: - fuse_layer.append(None) - else: - conv_downsamples = [] - for k in range(i - j): - if k == i - j - 1: - conv_downsamples.append( - nn.Sequential( - build_conv_layer( - self.conv_cfg, - in_channels[j], - in_channels[i], - kernel_size=3, - stride=2, - padding=1, - bias=False), - build_norm_layer(self.norm_cfg, - in_channels[i])[1])) - else: - conv_downsamples.append( - nn.Sequential( - build_conv_layer( - self.conv_cfg, - in_channels[j], - in_channels[j], - kernel_size=3, - stride=2, - padding=1, - bias=False), - build_norm_layer(self.norm_cfg, - in_channels[j])[1], - nn.ReLU(inplace=False))) - fuse_layer.append(nn.Sequential(*conv_downsamples)) - fuse_layers.append(nn.ModuleList(fuse_layer)) - - return nn.ModuleList(fuse_layers) - - def forward(self, x): - """Forward function.""" - if self.num_branches == 1: - return [self.branches[0](x[0])] - - for i in range(self.num_branches): - x[i] = self.branches[i](x[i]) - - x_fuse = [] - for i in range(len(self.fuse_layers)): - y = 0 - for j in range(self.num_branches): - if i == j: - y += x[j] - elif j > i: - y = y + resize( - self.fuse_layers[i][j](x[j]), - size=x[i].shape[2:], - mode='bilinear', - align_corners=False) - else: - y += self.fuse_layers[i][j](x[j]) - x_fuse.append(self.relu(y)) - return x_fuse - - -@BACKBONES.register_module() -class HRNet(nn.Module): - """HRNet backbone. - - High-Resolution Representations for Labeling Pixels and Regions - arXiv: https://arxiv.org/abs/1904.04514 - - Args: - extra (dict): detailed configuration for each stage of HRNet. - in_channels (int): Number of input image channels. Normally 3. - conv_cfg (dict): dictionary to construct and config conv layer. - norm_cfg (dict): dictionary to construct and config norm layer. - norm_eval (bool): Whether to set norm layers to eval mode, namely, - freeze running stats (mean and var). Note: Effect on Batch Norm - and its variants only. - with_cp (bool): Use checkpoint or not. Using checkpoint will save some - memory while slowing down the training speed. - zero_init_residual (bool): whether to use zero init for last norm layer - in resblocks to let them behave as identity. - - Example: - >>> from annotator.uniformer.mmseg.models import HRNet - >>> import torch - >>> extra = dict( - >>> stage1=dict( - >>> num_modules=1, - >>> num_branches=1, - >>> block='BOTTLENECK', - >>> num_blocks=(4, ), - >>> num_channels=(64, )), - >>> stage2=dict( - >>> num_modules=1, - >>> num_branches=2, - >>> block='BASIC', - >>> num_blocks=(4, 4), - >>> num_channels=(32, 64)), - >>> stage3=dict( - >>> num_modules=4, - >>> num_branches=3, - >>> block='BASIC', - >>> num_blocks=(4, 4, 4), - >>> num_channels=(32, 64, 128)), - >>> stage4=dict( - >>> num_modules=3, - >>> num_branches=4, - >>> block='BASIC', - >>> num_blocks=(4, 4, 4, 4), - >>> num_channels=(32, 64, 128, 256))) - >>> self = HRNet(extra, in_channels=1) - >>> self.eval() - >>> inputs = torch.rand(1, 1, 32, 32) - >>> level_outputs = self.forward(inputs) - >>> for level_out in level_outputs: - ... print(tuple(level_out.shape)) - (1, 32, 8, 8) - (1, 64, 4, 4) - (1, 128, 2, 2) - (1, 256, 1, 1) - """ - - blocks_dict = {'BASIC': BasicBlock, 'BOTTLENECK': Bottleneck} - - def __init__(self, - extra, - in_channels=3, - conv_cfg=None, - norm_cfg=dict(type='BN', requires_grad=True), - norm_eval=False, - with_cp=False, - zero_init_residual=False): - super(HRNet, self).__init__() - self.extra = extra - self.conv_cfg = conv_cfg - self.norm_cfg = norm_cfg - self.norm_eval = norm_eval - self.with_cp = with_cp - self.zero_init_residual = zero_init_residual - - # stem net - self.norm1_name, norm1 = build_norm_layer(self.norm_cfg, 64, postfix=1) - self.norm2_name, norm2 = build_norm_layer(self.norm_cfg, 64, postfix=2) - - self.conv1 = build_conv_layer( - self.conv_cfg, - in_channels, - 64, - kernel_size=3, - stride=2, - padding=1, - bias=False) - - self.add_module(self.norm1_name, norm1) - self.conv2 = build_conv_layer( - self.conv_cfg, - 64, - 64, - kernel_size=3, - stride=2, - padding=1, - bias=False) - - self.add_module(self.norm2_name, norm2) - self.relu = nn.ReLU(inplace=True) - - # stage 1 - self.stage1_cfg = self.extra['stage1'] - num_channels = self.stage1_cfg['num_channels'][0] - block_type = self.stage1_cfg['block'] - num_blocks = self.stage1_cfg['num_blocks'][0] - - block = self.blocks_dict[block_type] - stage1_out_channels = num_channels * block.expansion - self.layer1 = self._make_layer(block, 64, num_channels, num_blocks) - - # stage 2 - self.stage2_cfg = self.extra['stage2'] - num_channels = self.stage2_cfg['num_channels'] - block_type = self.stage2_cfg['block'] - - block = self.blocks_dict[block_type] - num_channels = [channel * block.expansion for channel in num_channels] - self.transition1 = self._make_transition_layer([stage1_out_channels], - num_channels) - self.stage2, pre_stage_channels = self._make_stage( - self.stage2_cfg, num_channels) - - # stage 3 - self.stage3_cfg = self.extra['stage3'] - num_channels = self.stage3_cfg['num_channels'] - block_type = self.stage3_cfg['block'] - - block = self.blocks_dict[block_type] - num_channels = [channel * block.expansion for channel in num_channels] - self.transition2 = self._make_transition_layer(pre_stage_channels, - num_channels) - self.stage3, pre_stage_channels = self._make_stage( - self.stage3_cfg, num_channels) - - # stage 4 - self.stage4_cfg = self.extra['stage4'] - num_channels = self.stage4_cfg['num_channels'] - block_type = self.stage4_cfg['block'] - - block = self.blocks_dict[block_type] - num_channels = [channel * block.expansion for channel in num_channels] - self.transition3 = self._make_transition_layer(pre_stage_channels, - num_channels) - self.stage4, pre_stage_channels = self._make_stage( - self.stage4_cfg, num_channels) - - @property - def norm1(self): - """nn.Module: the normalization layer named "norm1" """ - return getattr(self, self.norm1_name) - - @property - def norm2(self): - """nn.Module: the normalization layer named "norm2" """ - return getattr(self, self.norm2_name) - - def _make_transition_layer(self, num_channels_pre_layer, - num_channels_cur_layer): - """Make transition layer.""" - num_branches_cur = len(num_channels_cur_layer) - num_branches_pre = len(num_channels_pre_layer) - - transition_layers = [] - for i in range(num_branches_cur): - if i < num_branches_pre: - if num_channels_cur_layer[i] != num_channels_pre_layer[i]: - transition_layers.append( - nn.Sequential( - build_conv_layer( - self.conv_cfg, - num_channels_pre_layer[i], - num_channels_cur_layer[i], - kernel_size=3, - stride=1, - padding=1, - bias=False), - build_norm_layer(self.norm_cfg, - num_channels_cur_layer[i])[1], - nn.ReLU(inplace=True))) - else: - transition_layers.append(None) - else: - conv_downsamples = [] - for j in range(i + 1 - num_branches_pre): - in_channels = num_channels_pre_layer[-1] - out_channels = num_channels_cur_layer[i] \ - if j == i - num_branches_pre else in_channels - conv_downsamples.append( - nn.Sequential( - build_conv_layer( - self.conv_cfg, - in_channels, - out_channels, - kernel_size=3, - stride=2, - padding=1, - bias=False), - build_norm_layer(self.norm_cfg, out_channels)[1], - nn.ReLU(inplace=True))) - transition_layers.append(nn.Sequential(*conv_downsamples)) - - return nn.ModuleList(transition_layers) - - def _make_layer(self, block, inplanes, planes, blocks, stride=1): - """Make each layer.""" - downsample = None - if stride != 1 or inplanes != planes * block.expansion: - downsample = nn.Sequential( - build_conv_layer( - self.conv_cfg, - inplanes, - planes * block.expansion, - kernel_size=1, - stride=stride, - bias=False), - build_norm_layer(self.norm_cfg, planes * block.expansion)[1]) - - layers = [] - layers.append( - block( - inplanes, - planes, - stride, - downsample=downsample, - with_cp=self.with_cp, - norm_cfg=self.norm_cfg, - conv_cfg=self.conv_cfg)) - inplanes = planes * block.expansion - for i in range(1, blocks): - layers.append( - block( - inplanes, - planes, - with_cp=self.with_cp, - norm_cfg=self.norm_cfg, - conv_cfg=self.conv_cfg)) - - return nn.Sequential(*layers) - - def _make_stage(self, layer_config, in_channels, multiscale_output=True): - """Make each stage.""" - num_modules = layer_config['num_modules'] - num_branches = layer_config['num_branches'] - num_blocks = layer_config['num_blocks'] - num_channels = layer_config['num_channels'] - block = self.blocks_dict[layer_config['block']] - - hr_modules = [] - for i in range(num_modules): - # multi_scale_output is only used for the last module - if not multiscale_output and i == num_modules - 1: - reset_multiscale_output = False - else: - reset_multiscale_output = True - - hr_modules.append( - HRModule( - num_branches, - block, - num_blocks, - in_channels, - num_channels, - reset_multiscale_output, - with_cp=self.with_cp, - norm_cfg=self.norm_cfg, - conv_cfg=self.conv_cfg)) - - return nn.Sequential(*hr_modules), in_channels - - def init_weights(self, pretrained=None): - """Initialize the weights in backbone. - - Args: - pretrained (str, optional): Path to pre-trained weights. - Defaults to None. - """ - if isinstance(pretrained, str): - logger = get_root_logger() - load_checkpoint(self, pretrained, strict=False, logger=logger) - elif pretrained is None: - for m in self.modules(): - if isinstance(m, nn.Conv2d): - kaiming_init(m) - elif isinstance(m, (_BatchNorm, nn.GroupNorm)): - constant_init(m, 1) - - if self.zero_init_residual: - for m in self.modules(): - if isinstance(m, Bottleneck): - constant_init(m.norm3, 0) - elif isinstance(m, BasicBlock): - constant_init(m.norm2, 0) - else: - raise TypeError('pretrained must be a str or None') - - def forward(self, x): - """Forward function.""" - - x = self.conv1(x) - x = self.norm1(x) - x = self.relu(x) - x = self.conv2(x) - x = self.norm2(x) - x = self.relu(x) - x = self.layer1(x) - - x_list = [] - for i in range(self.stage2_cfg['num_branches']): - if self.transition1[i] is not None: - x_list.append(self.transition1[i](x)) - else: - x_list.append(x) - y_list = self.stage2(x_list) - - x_list = [] - for i in range(self.stage3_cfg['num_branches']): - if self.transition2[i] is not None: - x_list.append(self.transition2[i](y_list[-1])) - else: - x_list.append(y_list[i]) - y_list = self.stage3(x_list) - - x_list = [] - for i in range(self.stage4_cfg['num_branches']): - if self.transition3[i] is not None: - x_list.append(self.transition3[i](y_list[-1])) - else: - x_list.append(y_list[i]) - y_list = self.stage4(x_list) - - return y_list - - def train(self, mode=True): - """Convert the model into training mode will keeping the normalization - layer freezed.""" - super(HRNet, self).train(mode) - if mode and self.norm_eval: - for m in self.modules(): - # trick: eval have effect on BatchNorm only - if isinstance(m, _BatchNorm): - m.eval() diff --git a/spaces/RGBD-SOD/bbsnet/prepare_samples.py b/spaces/RGBD-SOD/bbsnet/prepare_samples.py deleted file mode 100644 index 1f0d646a87572ed338b5304aa9565c36f0eece2e..0000000000000000000000000000000000000000 --- a/spaces/RGBD-SOD/bbsnet/prepare_samples.py +++ /dev/null @@ -1,31 +0,0 @@ -import os -import shutil -from typing import List, Tuple - -from PIL import Image -from datasets import load_dataset - - -dataset = load_dataset("RGBD-SOD/test", "v1", split="train", cache_dir="data") -SAMPLES_DIR = "samples" - - -def prepare_samples(): - samples: List[Tuple[str, str, str]] = [] - for sample in dataset: - rgb: Image.Image = sample["rgb"] - depth: Image.Image = sample["depth"] - gt: Image.Image = sample["gt"] - name: str = sample["name"] - dir_path = os.path.join(SAMPLES_DIR, name) - shutil.rmtree(dir_path, ignore_errors=True) - os.makedirs(dir_path, exist_ok=True) - rgb_path = os.path.join(dir_path, f"rgb.jpg") - rgb.save(rgb_path) - depth_path = os.path.join(dir_path, f"depth.jpg") - depth.save(depth_path) - gt_path = os.path.join(dir_path, f"gt.png") - gt.save(gt_path) - - samples.append([rgb_path, depth_path, gt_path]) - return samples diff --git a/spaces/RMXK/RVC_HFF/infer/modules/train/train.py b/spaces/RMXK/RVC_HFF/infer/modules/train/train.py deleted file mode 100644 index 550bef391444c9b6c0d8c44ae3a3809b3ade4218..0000000000000000000000000000000000000000 --- a/spaces/RMXK/RVC_HFF/infer/modules/train/train.py +++ /dev/null @@ -1,723 +0,0 @@ -import os -import sys -import logging - -logger = logging.getLogger(__name__) - -now_dir = os.getcwd() -sys.path.append(os.path.join(now_dir)) - -import datetime - -from infer.lib.train import utils - -hps = utils.get_hparams() -os.environ["CUDA_VISIBLE_DEVICES"] = hps.gpus.replace("-", ",") -n_gpus = len(hps.gpus.split("-")) -from random import randint, shuffle - -import torch -try: - import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import - if torch.xpu.is_available(): - from infer.modules.ipex import ipex_init - from infer.modules.ipex.gradscaler import gradscaler_init - from torch.xpu.amp import autocast - GradScaler = gradscaler_init() - ipex_init() - else: - from torch.cuda.amp import GradScaler, autocast -except Exception: - from torch.cuda.amp import GradScaler, autocast - -torch.backends.cudnn.deterministic = False -torch.backends.cudnn.benchmark = False -from time import sleep -from time import time as ttime - -import torch.distributed as dist -import torch.multiprocessing as mp - -from torch.nn import functional as F -from torch.nn.parallel import DistributedDataParallel as DDP -from torch.utils.data import DataLoader -from torch.utils.tensorboard import SummaryWriter - -from infer.lib.infer_pack import commons -from infer.lib.train.data_utils import ( - DistributedBucketSampler, - TextAudioCollate, - TextAudioCollateMultiNSFsid, - TextAudioLoader, - TextAudioLoaderMultiNSFsid, -) - -if hps.version == "v1": - from infer.lib.infer_pack.models import MultiPeriodDiscriminator - from infer.lib.infer_pack.models import SynthesizerTrnMs256NSFsid as RVC_Model_f0 - from infer.lib.infer_pack.models import ( - SynthesizerTrnMs256NSFsid_nono as RVC_Model_nof0, - ) -else: - from infer.lib.infer_pack.models import ( - SynthesizerTrnMs768NSFsid as RVC_Model_f0, - SynthesizerTrnMs768NSFsid_nono as RVC_Model_nof0, - MultiPeriodDiscriminatorV2 as MultiPeriodDiscriminator, - ) - -from infer.lib.train.losses import ( - discriminator_loss, - feature_loss, - generator_loss, - kl_loss, -) -from infer.lib.train.mel_processing import mel_spectrogram_torch, spec_to_mel_torch -from infer.lib.train.process_ckpt import savee - -global_step = 0 -import csv - -class EpochRecorder: - def __init__(self): - self.last_time = ttime() - - def record(self): - now_time = ttime() - elapsed_time = now_time - self.last_time - self.last_time = now_time - elapsed_time_str = str(datetime.timedelta(seconds=elapsed_time)) - current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") - return f"[{current_time}] | ({elapsed_time_str})" - -def reset_stop_flag(): - with open("csvdb/stop.csv", "w+", newline="") as STOPCSVwrite: - csv_writer = csv.writer(STOPCSVwrite, delimiter=",") - csv_writer.writerow(["False"]) - -def create_model(hps, model_f0, model_nof0): - filter_length_adjusted = hps.data.filter_length // 2 + 1 - segment_size_adjusted = hps.train.segment_size // hps.data.hop_length - is_half = hps.train.fp16_run - sr = hps.sample_rate - - model = model_f0 if hps.if_f0 == 1 else model_nof0 - - return model( - filter_length_adjusted, - segment_size_adjusted, - **hps.model, - is_half=is_half, - sr=sr - ) - -def move_model_to_cuda_if_available(model, rank): - if torch.cuda.is_available(): - return model.cuda(rank) - else: - return model - -def create_optimizer(model, hps): - return torch.optim.AdamW( - model.parameters(), - hps.train.learning_rate, - betas=hps.train.betas, - eps=hps.train.eps, - ) - -def create_ddp_model(model, rank): - if torch.cuda.is_available(): - return DDP(model, device_ids=[rank]) - else: - return DDP(model) - -def create_dataset(hps, if_f0=True): - return TextAudioLoaderMultiNSFsid(hps.data.training_files, hps.data) if if_f0 else TextAudioLoader(hps.data.training_files, hps.data) - -def create_sampler(dataset, batch_size, n_gpus, rank): - return DistributedBucketSampler( - dataset, - batch_size * n_gpus, - # [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1200,1400], # 16s - [100, 200, 300, 400, 500, 600, 700, 800, 900], # 16s - num_replicas=n_gpus, - rank=rank, - shuffle=True, - ) - -def set_collate_fn(if_f0=True): - return TextAudioCollateMultiNSFsid() if if_f0 else TextAudioCollate() - - -def main(): - n_gpus = torch.cuda.device_count() - - if torch.cuda.is_available() == False and torch.backends.mps.is_available() == True: - n_gpus = 1 - if n_gpus < 1: - # patch to unblock people without gpus. there is probably a better way. - logger.warn("NO GPU DETECTED: falling back to CPU - this may take a while") - n_gpus = 1 - os.environ["MASTER_ADDR"] = "localhost" - os.environ["MASTER_PORT"] = str(randint(20000, 55555)) - children = [] - for i in range(n_gpus): - subproc = mp.Process( - target=run, - args=( - i, - n_gpus, - hps, - ), - ) - children.append(subproc) - subproc.start() - - for i in range(n_gpus): - children[i].join() - - -def run(rank, n_gpus, hps): - global global_step - if rank == 0: - logger = utils.get_logger(hps.model_dir) - logger.info(hps) - # utils.check_git_hash(hps.model_dir) - writer = SummaryWriter(log_dir=hps.model_dir) - writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval")) - - dist.init_process_group( - backend="gloo", init_method="env://", world_size=n_gpus, rank=rank - ) - torch.manual_seed(hps.train.seed) - if torch.cuda.is_available(): - torch.cuda.set_device(rank) - - if hps.if_f0 == 1: - train_dataset = TextAudioLoaderMultiNSFsid(hps.data.training_files, hps.data) - else: - train_dataset = TextAudioLoader(hps.data.training_files, hps.data) - train_sampler = DistributedBucketSampler( - train_dataset, - hps.train.batch_size * n_gpus, - # [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1200,1400], # 16s - [100, 200, 300, 400, 500, 600, 700, 800, 900], # 16s - num_replicas=n_gpus, - rank=rank, - shuffle=True, - ) - # It is possible that dataloader's workers are out of shared memory. Please try to raise your shared memory limit. - # num_workers=8 -> num_workers=4 - if hps.if_f0 == 1: - collate_fn = TextAudioCollateMultiNSFsid() - else: - collate_fn = TextAudioCollate() - train_loader = DataLoader( - train_dataset, - num_workers=4, - shuffle=False, - pin_memory=True, - collate_fn=collate_fn, - batch_sampler=train_sampler, - persistent_workers=True, - prefetch_factor=8, - ) - if hps.if_f0 == 1: - net_g = RVC_Model_f0( - hps.data.filter_length // 2 + 1, - hps.train.segment_size // hps.data.hop_length, - **hps.model, - is_half=hps.train.fp16_run, - sr=hps.sample_rate, - ) - else: - net_g = RVC_Model_nof0( - hps.data.filter_length // 2 + 1, - hps.train.segment_size // hps.data.hop_length, - **hps.model, - is_half=hps.train.fp16_run, - ) - if torch.cuda.is_available(): - net_g = net_g.cuda(rank) - net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm) - if torch.cuda.is_available(): - net_d = net_d.cuda(rank) - optim_g = torch.optim.AdamW( - net_g.parameters(), - hps.train.learning_rate, - betas=hps.train.betas, - eps=hps.train.eps, - ) - optim_d = torch.optim.AdamW( - net_d.parameters(), - hps.train.learning_rate, - betas=hps.train.betas, - eps=hps.train.eps, - ) - # net_g = DDP(net_g, device_ids=[rank], find_unused_parameters=True) - # net_d = DDP(net_d, device_ids=[rank], find_unused_parameters=True) - if hasattr(torch, "xpu") and torch.xpu.is_available(): - pass - elif torch.cuda.is_available(): - net_g = DDP(net_g, device_ids=[rank]) - net_d = DDP(net_d, device_ids=[rank]) - else: - net_g = DDP(net_g) - net_d = DDP(net_d) - - try: # 如果能加载自动resume - _, _, _, epoch_str = utils.load_checkpoint( - utils.latest_checkpoint_path(hps.model_dir, "D_*.pth"), net_d, optim_d - ) # D多半加载没事 - if rank == 0: - logger.info("loaded D") - # _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), net_g, optim_g,load_opt=0) - _, _, _, epoch_str = utils.load_checkpoint( - utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), net_g, optim_g - ) - global_step = (epoch_str - 1) * len(train_loader) - # epoch_str = 1 - # global_step = 0 - except: # 如果首次不能加载,加载pretrain - # traceback.print_exc() - epoch_str = 1 - global_step = 0 - if hps.pretrainG != "": - if rank == 0: - logger.info("loaded pretrained %s" % (hps.pretrainG)) - if hasattr(net_g, "module"): - logger.info( - net_g.module.load_state_dict( - torch.load(hps.pretrainG, map_location="cpu")["model"] - ) - ) ##测试不加载优化器 - else: - logger.info( - net_g.load_state_dict( - torch.load(hps.pretrainG, map_location="cpu")["model"] - ) - ) ##测试不加载优化器 - if hps.pretrainD != "": - if rank == 0: - logger.info("loaded pretrained %s" % (hps.pretrainD)) - if hasattr(net_d, "module"): - logger.info( - net_d.module.load_state_dict( - torch.load(hps.pretrainD, map_location="cpu")["model"] - ) - ) - else: - logger.info( - net_d.load_state_dict( - torch.load(hps.pretrainD, map_location="cpu")["model"] - ) - ) - - scheduler_g = torch.optim.lr_scheduler.ExponentialLR( - optim_g, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2 - ) - scheduler_d = torch.optim.lr_scheduler.ExponentialLR( - optim_d, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2 - ) - - scaler = GradScaler(enabled=hps.train.fp16_run) - - cache = [] - for epoch in range(epoch_str, hps.train.epochs + 1): - if rank == 0: - train_and_evaluate( - rank, - epoch, - hps, - [net_g, net_d], - [optim_g, optim_d], - [scheduler_g, scheduler_d], - scaler, - [train_loader, None], - logger, - [writer, writer_eval], - cache, - ) - else: - train_and_evaluate( - rank, - epoch, - hps, - [net_g, net_d], - [optim_g, optim_d], - [scheduler_g, scheduler_d], - scaler, - [train_loader, None], - None, - None, - cache, - ) - scheduler_g.step() - scheduler_d.step() - - -def train_and_evaluate( - rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers, cache -): - net_g, net_d = nets - optim_g, optim_d = optims - train_loader, eval_loader = loaders - if writers is not None: - writer, writer_eval = writers - - train_loader.batch_sampler.set_epoch(epoch) - global global_step - - net_g.train() - net_d.train() - - # Prepare data iterator - if hps.if_cache_data_in_gpu == True: - # Use Cache - data_iterator = cache - if cache == []: - # Make new cache - for batch_idx, info in enumerate(train_loader): - # Unpack - if hps.if_f0 == 1: - ( - phone, - phone_lengths, - pitch, - pitchf, - spec, - spec_lengths, - wave, - wave_lengths, - sid, - ) = info - else: - ( - phone, - phone_lengths, - spec, - spec_lengths, - wave, - wave_lengths, - sid, - ) = info - # Load on CUDA - if torch.cuda.is_available(): - phone = phone.cuda(rank, non_blocking=True) - phone_lengths = phone_lengths.cuda(rank, non_blocking=True) - if hps.if_f0 == 1: - pitch = pitch.cuda(rank, non_blocking=True) - pitchf = pitchf.cuda(rank, non_blocking=True) - sid = sid.cuda(rank, non_blocking=True) - spec = spec.cuda(rank, non_blocking=True) - spec_lengths = spec_lengths.cuda(rank, non_blocking=True) - wave = wave.cuda(rank, non_blocking=True) - wave_lengths = wave_lengths.cuda(rank, non_blocking=True) - # Cache on list - if hps.if_f0 == 1: - cache.append( - ( - batch_idx, - ( - phone, - phone_lengths, - pitch, - pitchf, - spec, - spec_lengths, - wave, - wave_lengths, - sid, - ), - ) - ) - else: - cache.append( - ( - batch_idx, - ( - phone, - phone_lengths, - spec, - spec_lengths, - wave, - wave_lengths, - sid, - ), - ) - ) - else: - # Load shuffled cache - shuffle(cache) - else: - # Loader - data_iterator = enumerate(train_loader) - - # Run steps - epoch_recorder = EpochRecorder() - for batch_idx, info in data_iterator: - # Data - ## Unpack - if hps.if_f0 == 1: - ( - phone, - phone_lengths, - pitch, - pitchf, - spec, - spec_lengths, - wave, - wave_lengths, - sid, - ) = info - else: - phone, phone_lengths, spec, spec_lengths, wave, wave_lengths, sid = info - ## Load on CUDA - if (hps.if_cache_data_in_gpu == False) and torch.cuda.is_available(): - phone = phone.cuda(rank, non_blocking=True) - phone_lengths = phone_lengths.cuda(rank, non_blocking=True) - if hps.if_f0 == 1: - pitch = pitch.cuda(rank, non_blocking=True) - pitchf = pitchf.cuda(rank, non_blocking=True) - sid = sid.cuda(rank, non_blocking=True) - spec = spec.cuda(rank, non_blocking=True) - spec_lengths = spec_lengths.cuda(rank, non_blocking=True) - wave = wave.cuda(rank, non_blocking=True) - # wave_lengths = wave_lengths.cuda(rank, non_blocking=True) - - # Calculate - with autocast(enabled=hps.train.fp16_run): - if hps.if_f0 == 1: - ( - y_hat, - ids_slice, - x_mask, - z_mask, - (z, z_p, m_p, logs_p, m_q, logs_q), - ) = net_g(phone, phone_lengths, pitch, pitchf, spec, spec_lengths, sid) - else: - ( - y_hat, - ids_slice, - x_mask, - z_mask, - (z, z_p, m_p, logs_p, m_q, logs_q), - ) = net_g(phone, phone_lengths, spec, spec_lengths, sid) - mel = spec_to_mel_torch( - spec, - hps.data.filter_length, - hps.data.n_mel_channels, - hps.data.sampling_rate, - hps.data.mel_fmin, - hps.data.mel_fmax, - ) - y_mel = commons.slice_segments( - mel, ids_slice, hps.train.segment_size // hps.data.hop_length - ) - with autocast(enabled=False): - y_hat_mel = mel_spectrogram_torch( - y_hat.float().squeeze(1), - hps.data.filter_length, - hps.data.n_mel_channels, - hps.data.sampling_rate, - hps.data.hop_length, - hps.data.win_length, - hps.data.mel_fmin, - hps.data.mel_fmax, - ) - if hps.train.fp16_run == True: - y_hat_mel = y_hat_mel.half() - wave = commons.slice_segments( - wave, ids_slice * hps.data.hop_length, hps.train.segment_size - ) # slice - - # Discriminator - y_d_hat_r, y_d_hat_g, _, _ = net_d(wave, y_hat.detach()) - with autocast(enabled=False): - loss_disc, losses_disc_r, losses_disc_g = discriminator_loss( - y_d_hat_r, y_d_hat_g - ) - optim_d.zero_grad() - scaler.scale(loss_disc).backward() - scaler.unscale_(optim_d) - grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None) - scaler.step(optim_d) - - with autocast(enabled=hps.train.fp16_run): - # Generator - y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(wave, y_hat) - with autocast(enabled=False): - loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel - loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl - loss_fm = feature_loss(fmap_r, fmap_g) - loss_gen, losses_gen = generator_loss(y_d_hat_g) - loss_gen_all = loss_gen + loss_fm + loss_mel + loss_kl - optim_g.zero_grad() - scaler.scale(loss_gen_all).backward() - scaler.unscale_(optim_g) - grad_norm_g = commons.clip_grad_value_(net_g.parameters(), None) - scaler.step(optim_g) - scaler.update() - - if rank == 0: - if global_step % hps.train.log_interval == 0: - lr = optim_g.param_groups[0]["lr"] - logger.info( - "Train Epoch: {} [{:.0f}%]".format( - epoch, 100.0 * batch_idx / len(train_loader) - ) - ) - # Amor For Tensorboard display - if loss_mel > 75: - loss_mel = 75 - if loss_kl > 9: - loss_kl = 9 - - logger.info([global_step, lr]) - logger.info( - f"loss_disc={loss_disc:.3f}, loss_gen={loss_gen:.3f}, loss_fm={loss_fm:.3f},loss_mel={loss_mel:.3f}, loss_kl={loss_kl:.3f}" - ) - scalar_dict = { - "loss/g/total": loss_gen_all, - "loss/d/total": loss_disc, - "learning_rate": lr, - "grad_norm_d": grad_norm_d, - "grad_norm_g": grad_norm_g, - } - scalar_dict.update( - { - "loss/g/fm": loss_fm, - "loss/g/mel": loss_mel, - "loss/g/kl": loss_kl, - } - ) - - scalar_dict.update( - {"loss/g/{}".format(i): v for i, v in enumerate(losses_gen)} - ) - scalar_dict.update( - {"loss/d_r/{}".format(i): v for i, v in enumerate(losses_disc_r)} - ) - scalar_dict.update( - {"loss/d_g/{}".format(i): v for i, v in enumerate(losses_disc_g)} - ) - image_dict = { - "slice/mel_org": utils.plot_spectrogram_to_numpy( - y_mel[0].data.cpu().numpy() - ), - "slice/mel_gen": utils.plot_spectrogram_to_numpy( - y_hat_mel[0].data.cpu().numpy() - ), - "all/mel": utils.plot_spectrogram_to_numpy( - mel[0].data.cpu().numpy() - ), - } - utils.summarize( - writer=writer, - global_step=global_step, - images=image_dict, - scalars=scalar_dict, - ) - global_step += 1 - # /Run steps - - if epoch % hps.save_every_epoch == 0 and rank == 0: - if hps.if_latest == 0: - utils.save_checkpoint( - net_g, - optim_g, - hps.train.learning_rate, - epoch, - os.path.join(hps.model_dir, "G_{}.pth".format(global_step)), - ) - utils.save_checkpoint( - net_d, - optim_d, - hps.train.learning_rate, - epoch, - os.path.join(hps.model_dir, "D_{}.pth".format(global_step)), - ) - else: - utils.save_checkpoint( - net_g, - optim_g, - hps.train.learning_rate, - epoch, - os.path.join(hps.model_dir, "G_{}.pth".format(2333333)), - ) - utils.save_checkpoint( - net_d, - optim_d, - hps.train.learning_rate, - epoch, - os.path.join(hps.model_dir, "D_{}.pth".format(2333333)), - ) - if rank == 0 and hps.save_every_weights == "1": - if hasattr(net_g, "module"): - ckpt = net_g.module.state_dict() - else: - ckpt = net_g.state_dict() - logger.info( - "saving ckpt %s_e%s:%s" - % ( - hps.name, - epoch, - savee( - ckpt, - hps.sample_rate, - hps.if_f0, - hps.name + "_e%s_s%s" % (epoch, global_step), - epoch, - hps.version, - hps, - ), - ) - ) - - stopbtn = False - try: - with open("csvdb/stop.csv", 'r') as csv_file: - stopbtn_str = next(csv.reader(csv_file), [None])[0] - if stopbtn_str is not None: stopbtn = stopbtn_str.lower() == 'true' - except (ValueError, TypeError, FileNotFoundError, IndexError) as e: - print(f"Handling exception: {e}") - stopbtn = False - - if stopbtn: - logger.info("Stop Button was pressed. The program is closed.") - ckpt = net_g.module.state_dict() if hasattr(net_g, "module") else net_g.state_dict() - logger.info( - "saving final ckpt:%s" - % ( - savee( - ckpt, hps.sample_rate, hps.if_f0, hps.name, epoch, hps.version, hps - ) - ) - ) - sleep(1) - reset_stop_flag() - os._exit(2333333) - - if rank == 0: - logger.info("====> Epoch: {} {}".format(epoch, epoch_recorder.record())) - if epoch >= hps.total_epoch and rank == 0: - logger.info("Training is done. The program is closed.") - - if hasattr(net_g, "module"): - ckpt = net_g.module.state_dict() - else: - ckpt = net_g.state_dict() - logger.info( - "saving final ckpt:%s" - % ( - savee( - ckpt, hps.sample_rate, hps.if_f0, hps.name, epoch, hps.version, hps - ) - ) - ) - sleep(1) - os._exit(2333333) - - -if __name__ == "__main__": - torch.multiprocessing.set_start_method("spawn") - main() diff --git a/spaces/RMXK/RVC_HFF/lib/uvr5_pack/utils.py b/spaces/RMXK/RVC_HFF/lib/uvr5_pack/utils.py deleted file mode 100644 index 0fafe8793b0d539fa58dd024342250b24b6187a9..0000000000000000000000000000000000000000 --- a/spaces/RMXK/RVC_HFF/lib/uvr5_pack/utils.py +++ /dev/null @@ -1,120 +0,0 @@ -import torch -import numpy as np -from tqdm import tqdm -import json - - -def load_data(file_name: str = "./lib/uvr5_pack/name_params.json") -> dict: - with open(file_name, "r") as f: - data = json.load(f) - - return data - - -def make_padding(width, cropsize, offset): - left = offset - roi_size = cropsize - left * 2 - if roi_size == 0: - roi_size = cropsize - right = roi_size - (width % roi_size) + left - - return left, right, roi_size - - -def inference(X_spec, device, model, aggressiveness, data): - """ - data : dic configs - """ - - def _execute( - X_mag_pad, roi_size, n_window, device, model, aggressiveness, is_half=True - ): - model.eval() - with torch.no_grad(): - preds = [] - - iterations = [n_window] - - total_iterations = sum(iterations) - for i in tqdm(range(n_window)): - start = i * roi_size - X_mag_window = X_mag_pad[ - None, :, :, start : start + data["window_size"] - ] - X_mag_window = torch.from_numpy(X_mag_window) - if is_half: - X_mag_window = X_mag_window.half() - X_mag_window = X_mag_window.to(device) - - pred = model.predict(X_mag_window, aggressiveness) - - pred = pred.detach().cpu().numpy() - preds.append(pred[0]) - - pred = np.concatenate(preds, axis=2) - return pred - - def preprocess(X_spec): - X_mag = np.abs(X_spec) - X_phase = np.angle(X_spec) - - return X_mag, X_phase - - X_mag, X_phase = preprocess(X_spec) - - coef = X_mag.max() - X_mag_pre = X_mag / coef - - n_frame = X_mag_pre.shape[2] - pad_l, pad_r, roi_size = make_padding(n_frame, data["window_size"], model.offset) - n_window = int(np.ceil(n_frame / roi_size)) - - X_mag_pad = np.pad(X_mag_pre, ((0, 0), (0, 0), (pad_l, pad_r)), mode="constant") - - if list(model.state_dict().values())[0].dtype == torch.float16: - is_half = True - else: - is_half = False - pred = _execute( - X_mag_pad, roi_size, n_window, device, model, aggressiveness, is_half - ) - pred = pred[:, :, :n_frame] - - if data["tta"]: - pad_l += roi_size // 2 - pad_r += roi_size // 2 - n_window += 1 - - X_mag_pad = np.pad(X_mag_pre, ((0, 0), (0, 0), (pad_l, pad_r)), mode="constant") - - pred_tta = _execute( - X_mag_pad, roi_size, n_window, device, model, aggressiveness, is_half - ) - pred_tta = pred_tta[:, :, roi_size // 2 :] - pred_tta = pred_tta[:, :, :n_frame] - - return (pred + pred_tta) * 0.5 * coef, X_mag, np.exp(1.0j * X_phase) - else: - return pred * coef, X_mag, np.exp(1.0j * X_phase) - - -def _get_name_params(model_path, model_hash): - data = load_data() - flag = False - ModelName = model_path - for type in list(data): - for model in list(data[type][0]): - for i in range(len(data[type][0][model])): - if str(data[type][0][model][i]["hash_name"]) == model_hash: - flag = True - elif str(data[type][0][model][i]["hash_name"]) in ModelName: - flag = True - - if flag: - model_params_auto = data[type][0][model][i]["model_params"] - param_name_auto = data[type][0][model][i]["param_name"] - if type == "equivalent": - return param_name_auto, model_params_auto - else: - flag = False - return param_name_auto, model_params_auto diff --git a/spaces/RMXK/RVC_HFF/train/utils.py b/spaces/RMXK/RVC_HFF/train/utils.py deleted file mode 100644 index aae833b08acc24b848aa70114fd9b7aad8b1a6ad..0000000000000000000000000000000000000000 --- a/spaces/RMXK/RVC_HFF/train/utils.py +++ /dev/null @@ -1,500 +0,0 @@ -import os, traceback -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_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: - print( - "shape-%s-mismatch|need-%s|get-%s" - % (k, state_dict[k].shape, saved_state_dict[k].shape) - ) # - raise KeyError - except: - # logger.info(traceback.format_exc()) - 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) - - go(combd, "combd") - 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: - print( - "shape-%s-mismatch|need-%s|get-%s" - % (k, state_dict[k].shape, saved_state_dict[k].shape) - ) # - raise KeyError - except: - # logger.info(traceback.format_exc()) - 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] - 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] - filepaths_and_text = [item for item in filepaths_and_text if len(item) == 5] # ensure there are 5 items. - 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('-c', '--config', type=str, default="configs/40k.json",help='JSON file for configuration') - 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", - ) - parser.add_argument( - "-li", "--log_interval", type=int, required=True, help="log interval" - ) - - args = parser.parse_args() - name = args.experiment_dir - experiment_dir = os.path.join("./logs", args.experiment_dir) - - if not os.path.exists(experiment_dir): - os.makedirs(experiment_dir) - - if args.version == "v1" or args.sample_rate == "40k": - config_path = "configs/%s.json" % args.sample_rate - else: - config_path = "configs/%s_v2.json" % args.sample_rate - config_save_path = os.path.join(experiment_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 = 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 - - hparams.train.log_interval = args.log_interval - - # Update log_interval in the 'train' section of the config dictionary - config["train"]["log_interval"] = args.log_interval - - # Save the updated config back to the config_save_path - with open(config_save_path, "w") as f: - json.dump(config, f, indent=4) - - 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/Rebskii/rvc-models-test/vc_infer_pipeline.py b/spaces/Rebskii/rvc-models-test/vc_infer_pipeline.py deleted file mode 100644 index c26d45068f9b6bf2b194b13c3c89f8a06347c124..0000000000000000000000000000000000000000 --- a/spaces/Rebskii/rvc-models-test/vc_infer_pipeline.py +++ /dev/null @@ -1,306 +0,0 @@ -import numpy as np, parselmouth, torch, pdb -from time import time as ttime -import torch.nn.functional as F -from config import x_pad, x_query, x_center, x_max -import scipy.signal as signal -import pyworld, os, traceback, faiss -from scipy import signal - -bh, ah = signal.butter(N=5, Wn=48, btype="high", fs=16000) - - -class VC(object): - def __init__(self, tgt_sr, device, is_half): - self.sr = 16000 # hubert输入采样率 - self.window = 160 # 每帧点数 - self.t_pad = self.sr * x_pad # 每条前后pad时间 - self.t_pad_tgt = tgt_sr * x_pad - self.t_pad2 = self.t_pad * 2 - self.t_query = self.sr * x_query # 查询切点前后查询时间 - self.t_center = self.sr * x_center # 查询切点位置 - self.t_max = self.sr * x_max # 免查询时长阈值 - self.device = device - self.is_half = is_half - - def get_f0(self, x, p_len, f0_up_key, f0_method, inp_f0=None): - time_step = self.window / self.sr * 1000 - f0_min = 50 - f0_max = 1100 - f0_mel_min = 1127 * np.log(1 + f0_min / 700) - f0_mel_max = 1127 * np.log(1 + f0_max / 700) - if f0_method == "pm": - f0 = ( - parselmouth.Sound(x, self.sr) - .to_pitch_ac( - time_step=time_step / 1000, - voicing_threshold=0.6, - pitch_floor=f0_min, - pitch_ceiling=f0_max, - ) - .selected_array["frequency"] - ) - pad_size = (p_len - len(f0) + 1) // 2 - if pad_size > 0 or p_len - len(f0) - pad_size > 0: - f0 = np.pad( - f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant" - ) - elif f0_method == "harvest": - f0, t = pyworld.harvest( - x.astype(np.double), - fs=self.sr, - f0_ceil=f0_max, - f0_floor=f0_min, - frame_period=10, - ) - f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr) - f0 = signal.medfilt(f0, 3) - f0 *= pow(2, f0_up_key / 12) - # with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()])) - tf0 = self.sr // self.window # 每秒f0点数 - if inp_f0 is not None: - delta_t = np.round( - (inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1 - ).astype("int16") - replace_f0 = np.interp( - list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1] - ) - shape = f0[x_pad * tf0 : x_pad * tf0 + len(replace_f0)].shape[0] - f0[x_pad * tf0 : x_pad * tf0 + len(replace_f0)] = replace_f0[:shape] - # with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()])) - f0bak = f0.copy() - f0_mel = 1127 * np.log(1 + f0 / 700) - f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / ( - f0_mel_max - f0_mel_min - ) + 1 - f0_mel[f0_mel <= 1] = 1 - f0_mel[f0_mel > 255] = 255 - f0_coarse = np.rint(f0_mel).astype(np.int) - return f0_coarse, f0bak # 1-0 - - def vc( - self, - model, - net_g, - sid, - audio0, - pitch, - pitchf, - times, - index, - big_npy, - index_rate, - ): # ,file_index,file_big_npy - feats = torch.from_numpy(audio0) - if self.is_half: - feats = feats.half() - else: - feats = feats.float() - if feats.dim() == 2: # double channels - feats = feats.mean(-1) - assert feats.dim() == 1, feats.dim() - feats = feats.view(1, -1) - padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False) - - inputs = { - "source": feats.to(self.device), - "padding_mask": padding_mask, - "output_layer": 9, # layer 9 - } - t0 = ttime() - with torch.no_grad(): - logits = model.extract_features(**inputs) - feats = model.final_proj(logits[0]) - - if ( - isinstance(index, type(None)) == False - and isinstance(big_npy, type(None)) == False - and index_rate != 0 - ): - npy = feats[0].cpu().numpy() - if self.is_half: - npy = npy.astype("float32") - _, I = index.search(npy, 1) - npy = big_npy[I.squeeze()] - if self.is_half: - npy = npy.astype("float16") - feats = ( - torch.from_numpy(npy).unsqueeze(0).to(self.device) * index_rate - + (1 - index_rate) * feats - ) - - feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1) - t1 = ttime() - p_len = audio0.shape[0] // self.window - if feats.shape[1] < p_len: - p_len = feats.shape[1] - if pitch != None and pitchf != None: - pitch = pitch[:, :p_len] - pitchf = pitchf[:, :p_len] - p_len = torch.tensor([p_len], device=self.device).long() - with torch.no_grad(): - if pitch != None and pitchf != None: - audio1 = ( - (net_g.infer(feats, p_len, pitch, pitchf, sid)[0][0, 0] * 32768) - .data.cpu() - .float() - .numpy() - .astype(np.int16) - ) - else: - audio1 = ( - (net_g.infer(feats, p_len, sid)[0][0, 0] * 32768) - .data.cpu() - .float() - .numpy() - .astype(np.int16) - ) - del feats, p_len, padding_mask - if torch.cuda.is_available(): - torch.cuda.empty_cache() - t2 = ttime() - times[0] += t1 - t0 - times[2] += t2 - t1 - return audio1 - - def pipeline( - self, - model, - net_g, - sid, - audio, - times, - f0_up_key, - f0_method, - file_index, - file_big_npy, - index_rate, - if_f0, - f0_file=None, - ): - if ( - file_big_npy != "" - and file_index != "" - and os.path.exists(file_big_npy) == True - and os.path.exists(file_index) == True - and index_rate != 0 - ): - try: - index = faiss.read_index(file_index) - big_npy = np.load(file_big_npy) - except: - traceback.print_exc() - index = big_npy = None - else: - index = big_npy = None - print("Feature retrieval library doesn't exist or ratio is 0") - audio = signal.filtfilt(bh, ah, audio) - audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect") - opt_ts = [] - if audio_pad.shape[0] > self.t_max: - audio_sum = np.zeros_like(audio) - for i in range(self.window): - audio_sum += audio_pad[i : i - self.window] - for t in range(self.t_center, audio.shape[0], self.t_center): - opt_ts.append( - t - - self.t_query - + np.where( - np.abs(audio_sum[t - self.t_query : t + self.t_query]) - == np.abs(audio_sum[t - self.t_query : t + self.t_query]).min() - )[0][0] - ) - s = 0 - audio_opt = [] - t = None - t1 = ttime() - audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect") - p_len = audio_pad.shape[0] // self.window - inp_f0 = None - if hasattr(f0_file, "name") == True: - try: - with open(f0_file.name, "r") as f: - lines = f.read().strip("\n").split("\n") - inp_f0 = [] - for line in lines: - inp_f0.append([float(i) for i in line.split(",")]) - inp_f0 = np.array(inp_f0, dtype="float32") - except: - traceback.print_exc() - sid = torch.tensor(sid, device=self.device).unsqueeze(0).long() - pitch, pitchf = None, None - if if_f0 == 1: - pitch, pitchf = self.get_f0(audio_pad, p_len, f0_up_key, f0_method, inp_f0) - pitch = pitch[:p_len] - pitchf = pitchf[:p_len] - pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long() - pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float() - t2 = ttime() - times[1] += t2 - t1 - for t in opt_ts: - t = t // self.window * self.window - if if_f0 == 1: - audio_opt.append( - self.vc( - model, - net_g, - sid, - audio_pad[s : t + self.t_pad2 + self.window], - pitch[:, s // self.window : (t + self.t_pad2) // self.window], - pitchf[:, s // self.window : (t + self.t_pad2) // self.window], - times, - index, - big_npy, - index_rate, - )[self.t_pad_tgt : -self.t_pad_tgt] - ) - else: - audio_opt.append( - self.vc( - model, - net_g, - sid, - audio_pad[s : t + self.t_pad2 + self.window], - None, - None, - times, - index, - big_npy, - index_rate, - )[self.t_pad_tgt : -self.t_pad_tgt] - ) - s = t - if if_f0 == 1: - audio_opt.append( - self.vc( - model, - net_g, - sid, - audio_pad[t:], - pitch[:, t // self.window :] if t is not None else pitch, - pitchf[:, t // self.window :] if t is not None else pitchf, - times, - index, - big_npy, - index_rate, - )[self.t_pad_tgt : -self.t_pad_tgt] - ) - else: - audio_opt.append( - self.vc( - model, - net_g, - sid, - audio_pad[t:], - None, - None, - times, - index, - big_npy, - index_rate, - )[self.t_pad_tgt : -self.t_pad_tgt] - ) - audio_opt = np.concatenate(audio_opt) - del pitch, pitchf, sid - if torch.cuda.is_available(): - torch.cuda.empty_cache() - return audio_opt diff --git a/spaces/Ricecake123/RVC-demo/lib/infer_pack/modules/F0Predictor/PMF0Predictor.py b/spaces/Ricecake123/RVC-demo/lib/infer_pack/modules/F0Predictor/PMF0Predictor.py deleted file mode 100644 index b2c592527a5966e6f8e79e8c52dc5b414246dcc6..0000000000000000000000000000000000000000 --- a/spaces/Ricecake123/RVC-demo/lib/infer_pack/modules/F0Predictor/PMF0Predictor.py +++ /dev/null @@ -1,97 +0,0 @@ -from lib.infer_pack.modules.F0Predictor.F0Predictor import F0Predictor -import parselmouth -import numpy as np - - -class PMF0Predictor(F0Predictor): - def __init__(self, hop_length=512, f0_min=50, f0_max=1100, sampling_rate=44100): - self.hop_length = hop_length - self.f0_min = f0_min - self.f0_max = f0_max - self.sampling_rate = sampling_rate - - def interpolate_f0(self, f0): - """ - 对F0进行插值处理 - """ - - data = np.reshape(f0, (f0.size, 1)) - - vuv_vector = np.zeros((data.size, 1), dtype=np.float32) - vuv_vector[data > 0.0] = 1.0 - vuv_vector[data <= 0.0] = 0.0 - - ip_data = data - - frame_number = data.size - last_value = 0.0 - for i in range(frame_number): - if data[i] <= 0.0: - j = i + 1 - for j in range(i + 1, frame_number): - if data[j] > 0.0: - break - if j < frame_number - 1: - if last_value > 0.0: - step = (data[j] - data[i - 1]) / float(j - i) - for k in range(i, j): - ip_data[k] = data[i - 1] + step * (k - i + 1) - else: - for k in range(i, j): - ip_data[k] = data[j] - else: - for k in range(i, frame_number): - ip_data[k] = last_value - else: - ip_data[i] = data[i] # 这里可能存在一个没有必要的拷贝 - last_value = data[i] - - return ip_data[:, 0], vuv_vector[:, 0] - - def compute_f0(self, wav, p_len=None): - x = wav - if p_len is None: - p_len = x.shape[0] // self.hop_length - else: - assert abs(p_len - x.shape[0] // self.hop_length) < 4, "pad length error" - time_step = self.hop_length / self.sampling_rate * 1000 - f0 = ( - parselmouth.Sound(x, self.sampling_rate) - .to_pitch_ac( - time_step=time_step / 1000, - voicing_threshold=0.6, - pitch_floor=self.f0_min, - pitch_ceiling=self.f0_max, - ) - .selected_array["frequency"] - ) - - pad_size = (p_len - len(f0) + 1) // 2 - if pad_size > 0 or p_len - len(f0) - pad_size > 0: - f0 = np.pad(f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant") - f0, uv = self.interpolate_f0(f0) - return f0 - - def compute_f0_uv(self, wav, p_len=None): - x = wav - if p_len is None: - p_len = x.shape[0] // self.hop_length - else: - assert abs(p_len - x.shape[0] // self.hop_length) < 4, "pad length error" - time_step = self.hop_length / self.sampling_rate * 1000 - f0 = ( - parselmouth.Sound(x, self.sampling_rate) - .to_pitch_ac( - time_step=time_step / 1000, - voicing_threshold=0.6, - pitch_floor=self.f0_min, - pitch_ceiling=self.f0_max, - ) - .selected_array["frequency"] - ) - - pad_size = (p_len - len(f0) + 1) // 2 - if pad_size > 0 or p_len - len(f0) - pad_size > 0: - f0 = np.pad(f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant") - f0, uv = self.interpolate_f0(f0) - return f0, uv diff --git a/spaces/Ricecake123/RVC-demo/lib/uvr5_pack/lib_v5/nets_new.py b/spaces/Ricecake123/RVC-demo/lib/uvr5_pack/lib_v5/nets_new.py deleted file mode 100644 index bfaf72e48b31cc1130f2892b0973c9aa06f195a3..0000000000000000000000000000000000000000 --- a/spaces/Ricecake123/RVC-demo/lib/uvr5_pack/lib_v5/nets_new.py +++ /dev/null @@ -1,132 +0,0 @@ -import torch -from torch import nn -import torch.nn.functional as F -from . import layers_new - - -class BaseNet(nn.Module): - def __init__( - self, nin, nout, nin_lstm, nout_lstm, dilations=((4, 2), (8, 4), (12, 6)) - ): - super(BaseNet, self).__init__() - self.enc1 = layers_new.Conv2DBNActiv(nin, nout, 3, 1, 1) - self.enc2 = layers_new.Encoder(nout, nout * 2, 3, 2, 1) - self.enc3 = layers_new.Encoder(nout * 2, nout * 4, 3, 2, 1) - self.enc4 = layers_new.Encoder(nout * 4, nout * 6, 3, 2, 1) - self.enc5 = layers_new.Encoder(nout * 6, nout * 8, 3, 2, 1) - - self.aspp = layers_new.ASPPModule(nout * 8, nout * 8, dilations, dropout=True) - - self.dec4 = layers_new.Decoder(nout * (6 + 8), nout * 6, 3, 1, 1) - self.dec3 = layers_new.Decoder(nout * (4 + 6), nout * 4, 3, 1, 1) - self.dec2 = layers_new.Decoder(nout * (2 + 4), nout * 2, 3, 1, 1) - self.lstm_dec2 = layers_new.LSTMModule(nout * 2, nin_lstm, nout_lstm) - self.dec1 = layers_new.Decoder(nout * (1 + 2) + 1, nout * 1, 3, 1, 1) - - def __call__(self, x): - e1 = self.enc1(x) - e2 = self.enc2(e1) - e3 = self.enc3(e2) - e4 = self.enc4(e3) - e5 = self.enc5(e4) - - h = self.aspp(e5) - - h = self.dec4(h, e4) - h = self.dec3(h, e3) - h = self.dec2(h, e2) - h = torch.cat([h, self.lstm_dec2(h)], dim=1) - h = self.dec1(h, e1) - - return h - - -class CascadedNet(nn.Module): - def __init__(self, n_fft, nout=32, nout_lstm=128): - super(CascadedNet, self).__init__() - - self.max_bin = n_fft // 2 - self.output_bin = n_fft // 2 + 1 - self.nin_lstm = self.max_bin // 2 - self.offset = 64 - - self.stg1_low_band_net = nn.Sequential( - BaseNet(2, nout // 2, self.nin_lstm // 2, nout_lstm), - layers_new.Conv2DBNActiv(nout // 2, nout // 4, 1, 1, 0), - ) - - self.stg1_high_band_net = BaseNet( - 2, nout // 4, self.nin_lstm // 2, nout_lstm // 2 - ) - - self.stg2_low_band_net = nn.Sequential( - BaseNet(nout // 4 + 2, nout, self.nin_lstm // 2, nout_lstm), - layers_new.Conv2DBNActiv(nout, nout // 2, 1, 1, 0), - ) - self.stg2_high_band_net = BaseNet( - nout // 4 + 2, nout // 2, self.nin_lstm // 2, nout_lstm // 2 - ) - - self.stg3_full_band_net = BaseNet( - 3 * nout // 4 + 2, nout, self.nin_lstm, nout_lstm - ) - - self.out = nn.Conv2d(nout, 2, 1, bias=False) - self.aux_out = nn.Conv2d(3 * nout // 4, 2, 1, bias=False) - - def forward(self, x): - x = x[:, :, : self.max_bin] - - bandw = x.size()[2] // 2 - l1_in = x[:, :, :bandw] - h1_in = x[:, :, bandw:] - l1 = self.stg1_low_band_net(l1_in) - h1 = self.stg1_high_band_net(h1_in) - aux1 = torch.cat([l1, h1], dim=2) - - l2_in = torch.cat([l1_in, l1], dim=1) - h2_in = torch.cat([h1_in, h1], dim=1) - l2 = self.stg2_low_band_net(l2_in) - h2 = self.stg2_high_band_net(h2_in) - aux2 = torch.cat([l2, h2], dim=2) - - f3_in = torch.cat([x, aux1, aux2], dim=1) - f3 = self.stg3_full_band_net(f3_in) - - mask = torch.sigmoid(self.out(f3)) - mask = F.pad( - input=mask, - pad=(0, 0, 0, self.output_bin - mask.size()[2]), - mode="replicate", - ) - - if self.training: - aux = torch.cat([aux1, aux2], dim=1) - aux = torch.sigmoid(self.aux_out(aux)) - aux = F.pad( - input=aux, - pad=(0, 0, 0, self.output_bin - aux.size()[2]), - mode="replicate", - ) - return mask, aux - else: - return mask - - def predict_mask(self, x): - mask = self.forward(x) - - if self.offset > 0: - mask = mask[:, :, :, self.offset : -self.offset] - assert mask.size()[3] > 0 - - return mask - - def predict(self, x, aggressiveness=None): - mask = self.forward(x) - pred_mag = x * mask - - if self.offset > 0: - pred_mag = pred_mag[:, :, :, self.offset : -self.offset] - assert pred_mag.size()[3] > 0 - - return pred_mag diff --git a/spaces/Ritori/TTS_Yui/logger.py b/spaces/Ritori/TTS_Yui/logger.py deleted file mode 100644 index ad327383a24484476801ea7f6d840b9fdb49786b..0000000000000000000000000000000000000000 --- a/spaces/Ritori/TTS_Yui/logger.py +++ /dev/null @@ -1,48 +0,0 @@ -import random -import torch -from torch.utils.tensorboard import SummaryWriter -from plotting_utils import plot_alignment_to_numpy, plot_spectrogram_to_numpy -from plotting_utils import plot_gate_outputs_to_numpy - - -class Tacotron2Logger(SummaryWriter): - def __init__(self, logdir): - super(Tacotron2Logger, self).__init__(logdir) - - def log_training(self, reduced_loss, grad_norm, learning_rate, duration, - iteration): - self.add_scalar("training.loss", reduced_loss, iteration) - self.add_scalar("grad.norm", grad_norm, iteration) - self.add_scalar("learning.rate", learning_rate, iteration) - self.add_scalar("duration", duration, iteration) - - def log_validation(self, reduced_loss, model, y, y_pred, iteration): - self.add_scalar("validation.loss", reduced_loss, iteration) - _, mel_outputs, gate_outputs, alignments = y_pred - mel_targets, gate_targets = y - - # plot distribution of parameters - for tag, value in model.named_parameters(): - tag = tag.replace('.', '/') - self.add_histogram(tag, value.data.cpu().numpy(), iteration) - - # plot alignment, mel target and predicted, gate target and predicted - idx = random.randint(0, alignments.size(0) - 1) - self.add_image( - "alignment", - plot_alignment_to_numpy(alignments[idx].data.cpu().numpy().T), - iteration, dataformats='HWC') - self.add_image( - "mel_target", - plot_spectrogram_to_numpy(mel_targets[idx].data.cpu().numpy()), - iteration, dataformats='HWC') - self.add_image( - "mel_predicted", - plot_spectrogram_to_numpy(mel_outputs[idx].data.cpu().numpy()), - iteration, dataformats='HWC') - self.add_image( - "gate", - plot_gate_outputs_to_numpy( - gate_targets[idx].data.cpu().numpy(), - torch.sigmoid(gate_outputs[idx]).data.cpu().numpy()), - iteration, dataformats='HWC') diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmcv/ops/roi_align_rotated.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmcv/ops/roi_align_rotated.py deleted file mode 100644 index 0ce4961a3555d4da8bc3e32f1f7d5ad50036587d..0000000000000000000000000000000000000000 --- a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmcv/ops/roi_align_rotated.py +++ /dev/null @@ -1,177 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import torch.nn as nn -from torch.autograd import Function - -from ..utils import ext_loader - -ext_module = ext_loader.load_ext( - '_ext', ['roi_align_rotated_forward', 'roi_align_rotated_backward']) - - -class RoIAlignRotatedFunction(Function): - - @staticmethod - def symbolic(g, features, rois, out_size, spatial_scale, sample_num, - aligned, clockwise): - if isinstance(out_size, int): - out_h = out_size - out_w = out_size - elif isinstance(out_size, tuple): - assert len(out_size) == 2 - assert isinstance(out_size[0], int) - assert isinstance(out_size[1], int) - out_h, out_w = out_size - else: - raise TypeError( - '"out_size" must be an integer or tuple of integers') - return g.op( - 'mmcv::MMCVRoIAlignRotated', - features, - rois, - output_height_i=out_h, - output_width_i=out_h, - spatial_scale_f=spatial_scale, - sampling_ratio_i=sample_num, - aligned_i=aligned, - clockwise_i=clockwise) - - @staticmethod - def forward(ctx, - features, - rois, - out_size, - spatial_scale, - sample_num=0, - aligned=True, - clockwise=False): - if isinstance(out_size, int): - out_h = out_size - out_w = out_size - elif isinstance(out_size, tuple): - assert len(out_size) == 2 - assert isinstance(out_size[0], int) - assert isinstance(out_size[1], int) - out_h, out_w = out_size - else: - raise TypeError( - '"out_size" must be an integer or tuple of integers') - ctx.spatial_scale = spatial_scale - ctx.sample_num = sample_num - ctx.aligned = aligned - ctx.clockwise = clockwise - ctx.save_for_backward(rois) - ctx.feature_size = features.size() - - batch_size, num_channels, data_height, data_width = features.size() - num_rois = rois.size(0) - - output = features.new_zeros(num_rois, num_channels, out_h, out_w) - ext_module.roi_align_rotated_forward( - features, - rois, - output, - pooled_height=out_h, - pooled_width=out_w, - spatial_scale=spatial_scale, - sample_num=sample_num, - aligned=aligned, - clockwise=clockwise) - return output - - @staticmethod - def backward(ctx, grad_output): - feature_size = ctx.feature_size - spatial_scale = ctx.spatial_scale - aligned = ctx.aligned - clockwise = ctx.clockwise - sample_num = ctx.sample_num - rois = ctx.saved_tensors[0] - assert feature_size is not None - batch_size, num_channels, data_height, data_width = feature_size - - out_w = grad_output.size(3) - out_h = grad_output.size(2) - - grad_input = grad_rois = None - - if ctx.needs_input_grad[0]: - grad_input = rois.new_zeros(batch_size, num_channels, data_height, - data_width) - ext_module.roi_align_rotated_backward( - grad_output.contiguous(), - rois, - grad_input, - pooled_height=out_h, - pooled_width=out_w, - spatial_scale=spatial_scale, - sample_num=sample_num, - aligned=aligned, - clockwise=clockwise) - return grad_input, grad_rois, None, None, None, None, None - - -roi_align_rotated = RoIAlignRotatedFunction.apply - - -class RoIAlignRotated(nn.Module): - """RoI align pooling layer for rotated proposals. - - It accepts a feature map of shape (N, C, H, W) and rois with shape - (n, 6) with each roi decoded as (batch_index, center_x, center_y, - w, h, angle). The angle is in radian. - - Args: - out_size (tuple): h, w - spatial_scale (float): scale the input boxes by this number - sample_num (int): number of inputs samples to take for each - output sample. 0 to take samples densely for current models. - aligned (bool): if False, use the legacy implementation in - MMDetection. If True, align the results more perfectly. - Default: True. - clockwise (bool): If True, the angle in each proposal follows a - clockwise fashion in image space, otherwise, the angle is - counterclockwise. Default: False. - - Note: - The implementation of RoIAlign when aligned=True is modified from - https://github.com/facebookresearch/detectron2/ - - The meaning of aligned=True: - - Given a continuous coordinate c, its two neighboring pixel - indices (in our pixel model) are computed by floor(c - 0.5) and - ceil(c - 0.5). For example, c=1.3 has pixel neighbors with discrete - indices [0] and [1] (which are sampled from the underlying signal - at continuous coordinates 0.5 and 1.5). But the original roi_align - (aligned=False) does not subtract the 0.5 when computing - neighboring pixel indices and therefore it uses pixels with a - slightly incorrect alignment (relative to our pixel model) when - performing bilinear interpolation. - - With `aligned=True`, - we first appropriately scale the ROI and then shift it by -0.5 - prior to calling roi_align. This produces the correct neighbors; - - The difference does not make a difference to the model's - performance if ROIAlign is used together with conv layers. - """ - - def __init__(self, - out_size, - spatial_scale, - sample_num=0, - aligned=True, - clockwise=False): - super(RoIAlignRotated, self).__init__() - - self.out_size = out_size - self.spatial_scale = float(spatial_scale) - self.sample_num = int(sample_num) - self.aligned = aligned - self.clockwise = clockwise - - def forward(self, features, rois): - return RoIAlignRotatedFunction.apply(features, rois, self.out_size, - self.spatial_scale, - self.sample_num, self.aligned, - self.clockwise) diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmcv/runner/hooks/closure.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmcv/runner/hooks/closure.py deleted file mode 100644 index b955f81f425be4ac3e6bb3f4aac653887989e872..0000000000000000000000000000000000000000 --- a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmcv/runner/hooks/closure.py +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from .hook import HOOKS, Hook - - -@HOOKS.register_module() -class ClosureHook(Hook): - - def __init__(self, fn_name, fn): - assert hasattr(self, fn_name) - assert callable(fn) - setattr(self, fn_name, fn) diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet/models/dense_heads/rpn_head.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet/models/dense_heads/rpn_head.py deleted file mode 100644 index a888cb8c188ca6fe63045b6230266553fbe8c996..0000000000000000000000000000000000000000 --- a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet/models/dense_heads/rpn_head.py +++ /dev/null @@ -1,236 +0,0 @@ -import copy -import warnings - -import torch -import torch.nn as nn -import torch.nn.functional as F -from mmcv import ConfigDict -from mmcv.cnn import normal_init -from mmcv.ops import batched_nms - -from ..builder import HEADS -from .anchor_head import AnchorHead -from .rpn_test_mixin import RPNTestMixin - - -@HEADS.register_module() -class RPNHead(RPNTestMixin, AnchorHead): - """RPN head. - - Args: - in_channels (int): Number of channels in the input feature map. - """ # noqa: W605 - - def __init__(self, in_channels, **kwargs): - super(RPNHead, self).__init__(1, in_channels, **kwargs) - - def _init_layers(self): - """Initialize layers of the head.""" - self.rpn_conv = nn.Conv2d( - self.in_channels, self.feat_channels, 3, padding=1) - self.rpn_cls = nn.Conv2d(self.feat_channels, - self.num_anchors * self.cls_out_channels, 1) - self.rpn_reg = nn.Conv2d(self.feat_channels, self.num_anchors * 4, 1) - - def init_weights(self): - """Initialize weights of the head.""" - normal_init(self.rpn_conv, std=0.01) - normal_init(self.rpn_cls, std=0.01) - normal_init(self.rpn_reg, std=0.01) - - def forward_single(self, x): - """Forward feature map of a single scale level.""" - x = self.rpn_conv(x) - x = F.relu(x, inplace=True) - rpn_cls_score = self.rpn_cls(x) - rpn_bbox_pred = self.rpn_reg(x) - return rpn_cls_score, rpn_bbox_pred - - def loss(self, - cls_scores, - bbox_preds, - gt_bboxes, - 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]): Ground truth bboxes for each image with - shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format. - 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. - """ - losses = super(RPNHead, self).loss( - cls_scores, - bbox_preds, - gt_bboxes, - None, - img_metas, - gt_bboxes_ignore=gt_bboxes_ignore) - return dict( - loss_rpn_cls=losses['loss_cls'], loss_rpn_bbox=losses['loss_bbox']) - - def _get_bboxes(self, - cls_scores, - bbox_preds, - mlvl_anchors, - img_shapes, - scale_factors, - cfg, - rescale=False): - """Transform outputs for a single batch item into bbox predictions. - - 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). - mlvl_anchors (list[Tensor]): Box reference for each scale level - with shape (num_total_anchors, 4). - img_shapes (list[tuple[int]]): Shape of the input image, - (height, width, 3). - scale_factors (list[ndarray]): Scale factor of the image arange as - (w_scale, h_scale, w_scale, h_scale). - cfg (mmcv.Config): Test / postprocessing configuration, - if None, test_cfg would be used. - rescale (bool): If True, return boxes in original image space. - - Returns: - list[tuple[Tensor, Tensor]]: Each item in result_list is 2-tuple. - The first item is an (n, 5) tensor, where the first 4 columns - are bounding box positions (tl_x, tl_y, br_x, br_y) and the - 5-th column is a score between 0 and 1. The second item is a - (n,) tensor where each item is the predicted class labelof the - corresponding box. - """ - cfg = self.test_cfg if cfg is None else cfg - cfg = copy.deepcopy(cfg) - # bboxes from different level should be independent during NMS, - # level_ids are used as labels for batched NMS to separate them - level_ids = [] - mlvl_scores = [] - mlvl_bbox_preds = [] - mlvl_valid_anchors = [] - batch_size = cls_scores[0].shape[0] - nms_pre_tensor = torch.tensor( - cfg.nms_pre, device=cls_scores[0].device, dtype=torch.long) - for idx in range(len(cls_scores)): - rpn_cls_score = cls_scores[idx] - rpn_bbox_pred = bbox_preds[idx] - assert rpn_cls_score.size()[-2:] == rpn_bbox_pred.size()[-2:] - rpn_cls_score = rpn_cls_score.permute(0, 2, 3, 1) - if self.use_sigmoid_cls: - rpn_cls_score = rpn_cls_score.reshape(batch_size, -1) - scores = rpn_cls_score.sigmoid() - else: - rpn_cls_score = rpn_cls_score.reshape(batch_size, -1, 2) - # We set FG labels to [0, num_class-1] and BG label to - # num_class in RPN head since mmdet v2.5, which is unified to - # be consistent with other head since mmdet v2.0. In mmdet v2.0 - # to v2.4 we keep BG label as 0 and FG label as 1 in rpn head. - scores = rpn_cls_score.softmax(-1)[..., 0] - rpn_bbox_pred = rpn_bbox_pred.permute(0, 2, 3, 1).reshape( - batch_size, -1, 4) - anchors = mlvl_anchors[idx] - anchors = anchors.expand_as(rpn_bbox_pred) - if nms_pre_tensor > 0: - # sort is faster than topk - # _, topk_inds = scores.topk(cfg.nms_pre) - # keep topk op for dynamic k in onnx model - if torch.onnx.is_in_onnx_export(): - # sort op will be converted to TopK in onnx - # and k<=3480 in TensorRT - scores_shape = torch._shape_as_tensor(scores) - nms_pre = torch.where(scores_shape[1] < nms_pre_tensor, - scores_shape[1], nms_pre_tensor) - _, topk_inds = scores.topk(nms_pre) - batch_inds = torch.arange(batch_size).view( - -1, 1).expand_as(topk_inds) - scores = scores[batch_inds, topk_inds] - rpn_bbox_pred = rpn_bbox_pred[batch_inds, topk_inds, :] - anchors = anchors[batch_inds, topk_inds, :] - - elif scores.shape[-1] > cfg.nms_pre: - ranked_scores, rank_inds = scores.sort(descending=True) - topk_inds = rank_inds[:, :cfg.nms_pre] - scores = ranked_scores[:, :cfg.nms_pre] - batch_inds = torch.arange(batch_size).view( - -1, 1).expand_as(topk_inds) - rpn_bbox_pred = rpn_bbox_pred[batch_inds, topk_inds, :] - anchors = anchors[batch_inds, topk_inds, :] - - mlvl_scores.append(scores) - mlvl_bbox_preds.append(rpn_bbox_pred) - mlvl_valid_anchors.append(anchors) - level_ids.append( - scores.new_full(( - batch_size, - scores.size(1), - ), - idx, - dtype=torch.long)) - - batch_mlvl_scores = torch.cat(mlvl_scores, dim=1) - batch_mlvl_anchors = torch.cat(mlvl_valid_anchors, dim=1) - batch_mlvl_rpn_bbox_pred = torch.cat(mlvl_bbox_preds, dim=1) - batch_mlvl_proposals = self.bbox_coder.decode( - batch_mlvl_anchors, batch_mlvl_rpn_bbox_pred, max_shape=img_shapes) - batch_mlvl_ids = torch.cat(level_ids, dim=1) - - # deprecate arguments warning - if 'nms' not in cfg or 'max_num' in cfg or 'nms_thr' in cfg: - warnings.warn( - 'In rpn_proposal or test_cfg, ' - 'nms_thr has been moved to a dict named nms as ' - 'iou_threshold, max_num has been renamed as max_per_img, ' - 'name of original arguments and the way to specify ' - 'iou_threshold of NMS will be deprecated.') - if 'nms' not in cfg: - cfg.nms = ConfigDict(dict(type='nms', iou_threshold=cfg.nms_thr)) - if 'max_num' in cfg: - if 'max_per_img' in cfg: - assert cfg.max_num == cfg.max_per_img, f'You ' \ - f'set max_num and ' \ - f'max_per_img at the same time, but get {cfg.max_num} ' \ - f'and {cfg.max_per_img} respectively' \ - 'Please delete max_num which will be deprecated.' - else: - cfg.max_per_img = cfg.max_num - if 'nms_thr' in cfg: - assert cfg.nms.iou_threshold == cfg.nms_thr, f'You set' \ - f' iou_threshold in nms and ' \ - f'nms_thr at the same time, but get' \ - f' {cfg.nms.iou_threshold} and {cfg.nms_thr}' \ - f' respectively. Please delete the nms_thr ' \ - f'which will be deprecated.' - - result_list = [] - for (mlvl_proposals, mlvl_scores, - mlvl_ids) in zip(batch_mlvl_proposals, batch_mlvl_scores, - batch_mlvl_ids): - # Skip nonzero op while exporting to ONNX - if cfg.min_bbox_size > 0 and (not torch.onnx.is_in_onnx_export()): - w = mlvl_proposals[:, 2] - mlvl_proposals[:, 0] - h = mlvl_proposals[:, 3] - mlvl_proposals[:, 1] - valid_ind = torch.nonzero( - (w >= cfg.min_bbox_size) - & (h >= cfg.min_bbox_size), - as_tuple=False).squeeze() - if valid_ind.sum().item() != len(mlvl_proposals): - mlvl_proposals = mlvl_proposals[valid_ind, :] - mlvl_scores = mlvl_scores[valid_ind] - mlvl_ids = mlvl_ids[valid_ind] - - dets, keep = batched_nms(mlvl_proposals, mlvl_scores, mlvl_ids, - cfg.nms) - result_list.append(dets[:cfg.max_per_img]) - return result_list diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer_base/mmcv/cnn/utils/__init__.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer_base/mmcv/cnn/utils/__init__.py deleted file mode 100644 index a263e31c1e3977712827ca229bbc04910b4e928e..0000000000000000000000000000000000000000 --- a/spaces/Robert001/UniControl-Demo/annotator/uniformer_base/mmcv/cnn/utils/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from .flops_counter import get_model_complexity_info -from .fuse_conv_bn import fuse_conv_bn -from .sync_bn import revert_sync_batchnorm -from .weight_init import (INITIALIZERS, Caffe2XavierInit, ConstantInit, - KaimingInit, NormalInit, PretrainedInit, - TruncNormalInit, UniformInit, XavierInit, - bias_init_with_prob, caffe2_xavier_init, - constant_init, initialize, kaiming_init, normal_init, - trunc_normal_init, uniform_init, xavier_init) - -__all__ = [ - 'get_model_complexity_info', 'bias_init_with_prob', 'caffe2_xavier_init', - 'constant_init', 'kaiming_init', 'normal_init', 'trunc_normal_init', - 'uniform_init', 'xavier_init', 'fuse_conv_bn', 'initialize', - 'INITIALIZERS', 'ConstantInit', 'XavierInit', 'NormalInit', - 'TruncNormalInit', 'UniformInit', 'KaimingInit', 'PretrainedInit', - 'Caffe2XavierInit', 'revert_sync_batchnorm' -] diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer_base/mmcv/runner/hooks/ema.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer_base/mmcv/runner/hooks/ema.py deleted file mode 100644 index 15c7e68088f019802a59e7ae41cc1fe0c7f28f96..0000000000000000000000000000000000000000 --- a/spaces/Robert001/UniControl-Demo/annotator/uniformer_base/mmcv/runner/hooks/ema.py +++ /dev/null @@ -1,89 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from ...parallel import is_module_wrapper -from ..hooks.hook import HOOKS, Hook - - -@HOOKS.register_module() -class EMAHook(Hook): - r"""Exponential Moving Average Hook. - - Use Exponential Moving Average on all parameters of model in training - process. All parameters have a ema backup, which update by the formula - as below. EMAHook takes priority over EvalHook and CheckpointSaverHook. - - .. math:: - - \text{Xema\_{t+1}} = (1 - \text{momentum}) \times - \text{Xema\_{t}} + \text{momentum} \times X_t - - Args: - momentum (float): The momentum used for updating ema parameter. - Defaults to 0.0002. - interval (int): Update ema parameter every interval iteration. - Defaults to 1. - warm_up (int): During first warm_up steps, we may use smaller momentum - to update ema parameters more slowly. Defaults to 100. - resume_from (str): The checkpoint path. Defaults to None. - """ - - def __init__(self, - momentum=0.0002, - interval=1, - warm_up=100, - resume_from=None): - assert isinstance(interval, int) and interval > 0 - self.warm_up = warm_up - self.interval = interval - assert momentum > 0 and momentum < 1 - self.momentum = momentum**interval - self.checkpoint = resume_from - - def before_run(self, runner): - """To resume model with it's ema parameters more friendly. - - Register ema parameter as ``named_buffer`` to model - """ - model = runner.model - if is_module_wrapper(model): - model = model.module - self.param_ema_buffer = {} - self.model_parameters = dict(model.named_parameters(recurse=True)) - for name, value in self.model_parameters.items(): - # "." is not allowed in module's buffer name - buffer_name = f"ema_{name.replace('.', '_')}" - self.param_ema_buffer[name] = buffer_name - model.register_buffer(buffer_name, value.data.clone()) - self.model_buffers = dict(model.named_buffers(recurse=True)) - if self.checkpoint is not None: - runner.resume(self.checkpoint) - - def after_train_iter(self, runner): - """Update ema parameter every self.interval iterations.""" - curr_step = runner.iter - # We warm up the momentum considering the instability at beginning - momentum = min(self.momentum, - (1 + curr_step) / (self.warm_up + curr_step)) - if curr_step % self.interval != 0: - return - for name, parameter in self.model_parameters.items(): - buffer_name = self.param_ema_buffer[name] - buffer_parameter = self.model_buffers[buffer_name] - buffer_parameter.mul_(1 - momentum).add_(momentum, parameter.data) - - def after_train_epoch(self, runner): - """We load parameter values from ema backup to model before the - EvalHook.""" - self._swap_ema_parameters() - - def before_train_epoch(self, runner): - """We recover model's parameter from ema backup after last epoch's - EvalHook.""" - self._swap_ema_parameters() - - def _swap_ema_parameters(self): - """Swap the parameter of model with parameter in ema_buffer.""" - for name, value in self.model_parameters.items(): - temp = value.data.clone() - ema_buffer = self.model_buffers[self.param_ema_buffer[name]] - value.data.copy_(ema_buffer.data) - ema_buffer.data.copy_(temp) diff --git a/spaces/Rongjiehuang/ProDiff/modules/FastDiff/module/modules.py b/spaces/Rongjiehuang/ProDiff/modules/FastDiff/module/modules.py deleted file mode 100644 index 29b0f42123b10a0518093c23592277b9622b5266..0000000000000000000000000000000000000000 --- a/spaces/Rongjiehuang/ProDiff/modules/FastDiff/module/modules.py +++ /dev/null @@ -1,343 +0,0 @@ -import math -import torch -import numpy as np -import torch.nn as nn -import torch.nn.functional as F - -from torch.nn import Conv1d - -LRELU_SLOPE = 0.1 - - - -def get_sinusoid_encoding_table(n_position, d_hid, padding_idx=None): - ''' Sinusoid position encoding table ''' - - def cal_angle(position, hid_idx): - return position / np.power(10000, 2 * (hid_idx // 2) / d_hid) - - def get_posi_angle_vec(position): - return [cal_angle(position, hid_j) for hid_j in range(d_hid)] - - sinusoid_table = np.array([get_posi_angle_vec(pos_i) - for pos_i in range(n_position)]) - - sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i - sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1 - - if padding_idx is not None: - # zero vector for padding dimension - sinusoid_table[padding_idx] = 0. - - return torch.FloatTensor(sinusoid_table) - - -def overlap_and_add(signal, frame_step): - """Reconstructs a signal from a framed representation. - - Adds potentially overlapping frames of a signal with shape - `[..., frames, frame_length]`, offsetting subsequent frames by `frame_step`. - The resulting tensor has shape `[..., output_size]` where - - output_size = (frames - 1) * frame_step + frame_length - - Args: - signal: A [..., frames, frame_length] Tensor. All dimensions may be unknown, and rank must be at least 2. - frame_step: An integer denoting overlap offsets. Must be less than or equal to frame_length. - - Returns: - A Tensor with shape [..., output_size] containing the overlap-added frames of signal's inner-most two dimensions. - output_size = (frames - 1) * frame_step + frame_length - - Based on https://github.com/tensorflow/tensorflow/blob/r1.12/tensorflow/contrib/signal/python/ops/reconstruction_ops.py - """ - outer_dimensions = signal.size()[:-2] - frames, frame_length = signal.size()[-2:] - - # gcd=Greatest Common Divisor - subframe_length = math.gcd(frame_length, frame_step) - subframe_step = frame_step // subframe_length - subframes_per_frame = frame_length // subframe_length - output_size = frame_step * (frames - 1) + frame_length - output_subframes = output_size // subframe_length - - subframe_signal = signal.view(*outer_dimensions, -1, subframe_length) - - frame = torch.arange(0, output_subframes).unfold(0, subframes_per_frame, subframe_step) - frame = signal.new_tensor(frame).long() # signal may in GPU or CPU - frame = frame.contiguous().view(-1) - - result = signal.new_zeros(*outer_dimensions, output_subframes, subframe_length) - device_of_result = result.device - result.index_add_(-2, frame.to(device_of_result), subframe_signal) - result = result.view(*outer_dimensions, -1) - return result - - -class LastLayer(nn.Module): - def __init__(self, in_channels, out_channels, - nonlinear_activation, nonlinear_activation_params, - pad, kernel_size, pad_params, bias): - super(LastLayer, self).__init__() - self.activation = getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params) - self.pad = getattr(torch.nn, pad)((kernel_size - 1) // 2, **pad_params) - self.conv = torch.nn.Conv1d(in_channels, out_channels, kernel_size, bias=bias) - - def forward(self, x): - x = self.activation(x) - x = self.pad(x) - x = self.conv(x) - return x - - -class WeightConv1d(Conv1d): - """Conv1d module with customized initialization.""" - - def __init__(self, *args, **kwargs): - """Initialize Conv1d module.""" - super(Conv1d, self).__init__(*args, **kwargs) - - def reset_parameters(self): - """Reset parameters.""" - torch.nn.init.kaiming_normal_(self.weight, nonlinearity="relu") - if self.bias is not None: - torch.nn.init.constant_(self.bias, 0.0) - - -class Conv1d1x1(Conv1d): - """1x1 Conv1d with customized initialization.""" - - def __init__(self, in_channels, out_channels, bias): - """Initialize 1x1 Conv1d module.""" - super(Conv1d1x1, self).__init__(in_channels, out_channels, - kernel_size=1, padding=0, - dilation=1, bias=bias) - -class DiffusionDBlock(nn.Module): - def __init__(self, input_size, hidden_size, factor): - super().__init__() - self.factor = factor - self.residual_dense = Conv1d(input_size, hidden_size, 1) - self.conv = nn.ModuleList([ - Conv1d(input_size, hidden_size, 3, dilation=1, padding=1), - Conv1d(hidden_size, hidden_size, 3, dilation=2, padding=2), - Conv1d(hidden_size, hidden_size, 3, dilation=4, padding=4), - ]) - - def forward(self, x): - size = x.shape[-1] // self.factor - - residual = self.residual_dense(x) - residual = F.interpolate(residual, size=size) - - x = F.interpolate(x, size=size) - for layer in self.conv: - x = F.leaky_relu(x, 0.2) - x = layer(x) - - return x + residual - - -class TimeAware_LVCBlock(torch.nn.Module): - ''' time-aware location-variable convolutions - ''' - def __init__(self, - in_channels, - cond_channels, - upsample_ratio, - conv_layers=4, - conv_kernel_size=3, - cond_hop_length=256, - kpnet_hidden_channels=64, - kpnet_conv_size=3, - kpnet_dropout=0.0, - noise_scale_embed_dim_out=512 - ): - super().__init__() - - self.cond_hop_length = cond_hop_length - self.conv_layers = conv_layers - self.conv_kernel_size = conv_kernel_size - self.convs = torch.nn.ModuleList() - - self.upsample = torch.nn.ConvTranspose1d(in_channels, in_channels, - kernel_size=upsample_ratio*2, stride=upsample_ratio, - padding=upsample_ratio // 2 + upsample_ratio % 2, - output_padding=upsample_ratio % 2) - - - self.kernel_predictor = KernelPredictor( - cond_channels=cond_channels, - conv_in_channels=in_channels, - conv_out_channels=2 * in_channels, - conv_layers=conv_layers, - conv_kernel_size=conv_kernel_size, - kpnet_hidden_channels=kpnet_hidden_channels, - kpnet_conv_size=kpnet_conv_size, - kpnet_dropout=kpnet_dropout - ) - - # the layer-specific fc for noise scale embedding - self.fc_t = torch.nn.Linear(noise_scale_embed_dim_out, cond_channels) - - for i in range(conv_layers): - padding = (3 ** i) * int((conv_kernel_size - 1) / 2) - conv = torch.nn.Conv1d(in_channels, in_channels, kernel_size=conv_kernel_size, padding=padding, dilation=3 ** i) - - self.convs.append(conv) - - - def forward(self, data): - ''' forward propagation of the time-aware location-variable convolutions. - Args: - x (Tensor): the input sequence (batch, in_channels, in_length) - c (Tensor): the conditioning sequence (batch, cond_channels, cond_length) - - Returns: - Tensor: the output sequence (batch, in_channels, in_length) - ''' - x, audio_down, c, noise_embedding = data - batch, in_channels, in_length = x.shape - - noise = (self.fc_t(noise_embedding)).unsqueeze(-1) # (B, 80) - condition = c + noise # (B, 80, T) - kernels, bias = self.kernel_predictor(condition) - x = F.leaky_relu(x, 0.2) - x = self.upsample(x) - - for i in range(self.conv_layers): - x += audio_down - y = F.leaky_relu(x, 0.2) - y = self.convs[i](y) - y = F.leaky_relu(y, 0.2) - - k = kernels[:, i, :, :, :, :] - b = bias[:, i, :, :] - y = self.location_variable_convolution(y, k, b, 1, self.cond_hop_length) - x = x + torch.sigmoid(y[:, :in_channels, :]) * torch.tanh(y[:, in_channels:, :]) - return x - - def location_variable_convolution(self, x, kernel, bias, dilation, hop_size): - ''' perform location-variable convolution operation on the input sequence (x) using the local convolution kernl. - Time: 414 μs ± 309 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each), test on NVIDIA V100. - Args: - x (Tensor): the input sequence (batch, in_channels, in_length). - kernel (Tensor): the local convolution kernel (batch, in_channel, out_channels, kernel_size, kernel_length) - bias (Tensor): the bias for the local convolution (batch, out_channels, kernel_length) - dilation (int): the dilation of convolution. - hop_size (int): the hop_size of the conditioning sequence. - Returns: - (Tensor): the output sequence after performing local convolution. (batch, out_channels, in_length). - ''' - batch, in_channels, in_length = x.shape - batch, in_channels, out_channels, kernel_size, kernel_length = kernel.shape - - - assert in_length == (kernel_length * hop_size), "length of (x, kernel) is not matched" - - padding = dilation * int((kernel_size - 1) / 2) - x = F.pad(x, (padding, padding), 'constant', 0) # (batch, in_channels, in_length + 2*padding) - x = x.unfold(2, hop_size + 2 * padding, hop_size) # (batch, in_channels, kernel_length, hop_size + 2*padding) - - if hop_size < dilation: - x = F.pad(x, (0, dilation), 'constant', 0) - x = x.unfold(3, dilation, - dilation) # (batch, in_channels, kernel_length, (hop_size + 2*padding)/dilation, dilation) - x = x[:, :, :, :, :hop_size] - x = x.transpose(3, 4) # (batch, in_channels, kernel_length, dilation, (hop_size + 2*padding)/dilation) - x = x.unfold(4, kernel_size, 1) # (batch, in_channels, kernel_length, dilation, _, kernel_size) - - o = torch.einsum('bildsk,biokl->bolsd', x, kernel) - o = o + bias.unsqueeze(-1).unsqueeze(-1) - o = o.contiguous().view(batch, out_channels, -1) - return o - - - -class KernelPredictor(torch.nn.Module): - ''' Kernel predictor for the time-aware location-variable convolutions - ''' - - def __init__(self, - cond_channels, - conv_in_channels, - conv_out_channels, - conv_layers, - conv_kernel_size=3, - kpnet_hidden_channels=64, - kpnet_conv_size=3, - kpnet_dropout=0.0, - kpnet_nonlinear_activation="LeakyReLU", - kpnet_nonlinear_activation_params={"negative_slope": 0.1} - ): - ''' - Args: - cond_channels (int): number of channel for the conditioning sequence, - conv_in_channels (int): number of channel for the input sequence, - conv_out_channels (int): number of channel for the output sequence, - conv_layers (int): - kpnet_ - ''' - super().__init__() - - self.conv_in_channels = conv_in_channels - self.conv_out_channels = conv_out_channels - self.conv_kernel_size = conv_kernel_size - self.conv_layers = conv_layers - - l_w = conv_in_channels * conv_out_channels * conv_kernel_size * conv_layers - l_b = conv_out_channels * conv_layers - - padding = (kpnet_conv_size - 1) // 2 - self.input_conv = torch.nn.Sequential( - torch.nn.Conv1d(cond_channels, kpnet_hidden_channels, 5, padding=(5 - 1) // 2, bias=True), - getattr(torch.nn, kpnet_nonlinear_activation)(**kpnet_nonlinear_activation_params), - ) - - self.residual_conv = torch.nn.Sequential( - torch.nn.Dropout(kpnet_dropout), - torch.nn.Conv1d(kpnet_hidden_channels, kpnet_hidden_channels, kpnet_conv_size, padding=padding, bias=True), - getattr(torch.nn, kpnet_nonlinear_activation)(**kpnet_nonlinear_activation_params), - torch.nn.Conv1d(kpnet_hidden_channels, kpnet_hidden_channels, kpnet_conv_size, padding=padding, bias=True), - getattr(torch.nn, kpnet_nonlinear_activation)(**kpnet_nonlinear_activation_params), - torch.nn.Dropout(kpnet_dropout), - torch.nn.Conv1d(kpnet_hidden_channels, kpnet_hidden_channels, kpnet_conv_size, padding=padding, bias=True), - getattr(torch.nn, kpnet_nonlinear_activation)(**kpnet_nonlinear_activation_params), - torch.nn.Conv1d(kpnet_hidden_channels, kpnet_hidden_channels, kpnet_conv_size, padding=padding, bias=True), - getattr(torch.nn, kpnet_nonlinear_activation)(**kpnet_nonlinear_activation_params), - torch.nn.Dropout(kpnet_dropout), - torch.nn.Conv1d(kpnet_hidden_channels, kpnet_hidden_channels, kpnet_conv_size, padding=padding, bias=True), - getattr(torch.nn, kpnet_nonlinear_activation)(**kpnet_nonlinear_activation_params), - torch.nn.Conv1d(kpnet_hidden_channels, kpnet_hidden_channels, kpnet_conv_size, padding=padding, bias=True), - getattr(torch.nn, kpnet_nonlinear_activation)(**kpnet_nonlinear_activation_params), - ) - - self.kernel_conv = torch.nn.Conv1d(kpnet_hidden_channels, l_w, kpnet_conv_size, - padding=padding, bias=True) - self.bias_conv = torch.nn.Conv1d(kpnet_hidden_channels, l_b, kpnet_conv_size, padding=padding, - bias=True) - - def forward(self, c): - ''' - Args: - c (Tensor): the conditioning sequence (batch, cond_channels, cond_length) - Returns: - ''' - batch, cond_channels, cond_length = c.shape - - c = self.input_conv(c) - c = c + self.residual_conv(c) - k = self.kernel_conv(c) - b = self.bias_conv(c) - - kernels = k.contiguous().view(batch, - self.conv_layers, - self.conv_in_channels, - self.conv_out_channels, - self.conv_kernel_size, - cond_length) - bias = b.contiguous().view(batch, - self.conv_layers, - self.conv_out_channels, - cond_length) - return kernels, bias diff --git a/spaces/SIGGRAPH2022/DCT-Net/README.md b/spaces/SIGGRAPH2022/DCT-Net/README.md deleted file mode 100644 index ef6ddbc185afe0b8238589d308a929dbd9d71e04..0000000000000000000000000000000000000000 --- a/spaces/SIGGRAPH2022/DCT-Net/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: DCT Net -emoji: 📉 -colorFrom: red -colorTo: purple -sdk: gradio -sdk_version: 3.1.4 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Salesforce/EDICT/my_diffusers/utils/dummy_transformers_objects.py b/spaces/Salesforce/EDICT/my_diffusers/utils/dummy_transformers_objects.py deleted file mode 100644 index e05eb814d17b3a49eb550a89dfd13ee24fdda134..0000000000000000000000000000000000000000 --- a/spaces/Salesforce/EDICT/my_diffusers/utils/dummy_transformers_objects.py +++ /dev/null @@ -1,32 +0,0 @@ -# This file is autogenerated by the command `make fix-copies`, do not edit. -# flake8: noqa - -from ..utils import DummyObject, requires_backends - - -class LDMTextToImagePipeline(metaclass=DummyObject): - _backends = ["transformers"] - - def __init__(self, *args, **kwargs): - requires_backends(self, ["transformers"]) - - -class StableDiffusionImg2ImgPipeline(metaclass=DummyObject): - _backends = ["transformers"] - - def __init__(self, *args, **kwargs): - requires_backends(self, ["transformers"]) - - -class StableDiffusionInpaintPipeline(metaclass=DummyObject): - _backends = ["transformers"] - - def __init__(self, *args, **kwargs): - requires_backends(self, ["transformers"]) - - -class StableDiffusionPipeline(metaclass=DummyObject): - _backends = ["transformers"] - - def __init__(self, *args, **kwargs): - requires_backends(self, ["transformers"]) diff --git a/spaces/SankarSrin/image-matting-app/ppmatting/utils/__init__.py b/spaces/SankarSrin/image-matting-app/ppmatting/utils/__init__.py deleted file mode 100644 index 79717c71036b5b730cce8548bc27f6fef7222c21..0000000000000000000000000000000000000000 --- a/spaces/SankarSrin/image-matting-app/ppmatting/utils/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from .estimate_foreground_ml import estimate_foreground_ml -from .utils import get_files, get_image_list, mkdir diff --git a/spaces/Shad0ws/Voice_Cloning/app.py b/spaces/Shad0ws/Voice_Cloning/app.py deleted file mode 100644 index 18e84fe677fd23a472fd4ef71be564a5cbc94929..0000000000000000000000000000000000000000 --- a/spaces/Shad0ws/Voice_Cloning/app.py +++ /dev/null @@ -1,165 +0,0 @@ -from turtle import title -import gradio as gr - -import git -import os -os.system('git clone https://github.com/Edresson/Coqui-TTS -b multilingual-torchaudio-SE TTS') -os.system('pip install -q -e TTS/') -os.system('pip install -q torchaudio==0.9.0') - -import sys -TTS_PATH = "TTS/" - -# add libraries into environment -sys.path.append(TTS_PATH) # set this if TTS is not installed globally - -import os -import string -import time -import argparse -import json - -import numpy as np -import IPython -from IPython.display import Audio - - -import torch - -from TTS.tts.utils.synthesis import synthesis -from TTS.tts.utils.text.symbols import make_symbols, phonemes, symbols -try: - from TTS.utils.audio import AudioProcessor -except: - from TTS.utils.audio import AudioProcessor - - -from TTS.tts.models import setup_model -from TTS.config import load_config -from TTS.tts.models.vits import * - -OUT_PATH = 'out/' - -# create output path -os.makedirs(OUT_PATH, exist_ok=True) - -# model vars -MODEL_PATH = '/home/user/app/best_model_latest.pth.tar' -CONFIG_PATH = '/home/user/app/config.json' -TTS_LANGUAGES = "/home/user/app/language_ids.json" -TTS_SPEAKERS = "/home/user/app/speakers.json" -USE_CUDA = torch.cuda.is_available() - -# load the config -C = load_config(CONFIG_PATH) - - -# load the audio processor -ap = AudioProcessor(**C.audio) - -speaker_embedding = None - -C.model_args['d_vector_file'] = TTS_SPEAKERS -C.model_args['use_speaker_encoder_as_loss'] = False - -model = setup_model(C) -model.language_manager.set_language_ids_from_file(TTS_LANGUAGES) -# print(model.language_manager.num_languages, model.embedded_language_dim) -# print(model.emb_l) -cp = torch.load(MODEL_PATH, map_location=torch.device('cpu')) -# remove speaker encoder -model_weights = cp['model'].copy() -for key in list(model_weights.keys()): - if "speaker_encoder" in key: - del model_weights[key] - -model.load_state_dict(model_weights) - - -model.eval() - -if USE_CUDA: - model = model.cuda() - -# synthesize voice -use_griffin_lim = False - -os.system('pip install -q pydub ffmpeg-normalize') - -CONFIG_SE_PATH = "config_se.json" -CHECKPOINT_SE_PATH = "SE_checkpoint.pth.tar" - -from TTS.tts.utils.speakers import SpeakerManager -from pydub import AudioSegment -import librosa - -SE_speaker_manager = SpeakerManager(encoder_model_path=CHECKPOINT_SE_PATH, encoder_config_path=CONFIG_SE_PATH, use_cuda=USE_CUDA) - -def compute_spec(ref_file): - y, sr = librosa.load(ref_file, sr=ap.sample_rate) - spec = ap.spectrogram(y) - spec = torch.FloatTensor(spec).unsqueeze(0) - return spec - - - -def greet(Text,Voicetoclone,VoiceMicrophone): - text= "%s" % (Text) - if Voicetoclone is not None: - reference_files= "%s" % (Voicetoclone) - print("path url") - print(Voicetoclone) - sample= str(Voicetoclone) - else: - reference_files= "%s" % (VoiceMicrophone) - print("path url") - print(VoiceMicrophone) - sample= str(VoiceMicrophone) - size= len(reference_files)*sys.getsizeof(reference_files) - size2= size / 1000000 - if (size2 > 0.012) or len(text)>2000: - message="File is greater than 30mb or Text inserted is longer than 2000 characters. Please re-try with smaller sizes." - print(message) - raise SystemExit("File is greater than 30mb. Please re-try or Text inserted is longer than 2000 characters. Please re-try with smaller sizes.") - else: - os.system('ffmpeg-normalize $sample -nt rms -t=-27 -o $sample -ar 16000 -f') - reference_emb = SE_speaker_manager.compute_d_vector_from_clip(reference_files) - model.length_scale = 1 # scaler for the duration predictor. The larger it is, the slower the speech. - model.inference_noise_scale = 0.3 # defines the noise variance applied to the random z vector at inference. - model.inference_noise_scale_dp = 0.3 # defines the noise variance applied to the duration predictor z vector at inference. - text = text - model.language_manager.language_id_mapping - language_id = 0 - - print(" > text: {}".format(text)) - wav, alignment, _, _ = synthesis( - model, - text, - C, - "cuda" in str(next(model.parameters()).device), - ap, - speaker_id=None, - d_vector=reference_emb, - style_wav=None, - language_id=language_id, - enable_eos_bos_chars=C.enable_eos_bos_chars, - use_griffin_lim=True, - do_trim_silence=False, - ).values() - print("Generated Audio") - IPython.display.display(Audio(wav, rate=ap.sample_rate)) - #file_name = text.replace(" ", "_") - #file_name = file_name.translate(str.maketrans('', '', string.punctuation.replace('_', ''))) + '.wav' - file_name="Audio.wav" - out_path = os.path.join(OUT_PATH, file_name) - print(" > Saving output to {}".format(out_path)) - ap.save_wav(wav, out_path) - return out_path - -demo = gr.Interface( - fn=greet, - inputs=[gr.inputs.Textbox(label='What would you like the voice to say? (max. 2000 characters per request)'),gr.Audio(type="filepath",source="upload",label='Please upload a voice to clone (max. 30mb)'),gr.Audio(source="microphone", type="filepath", streaming=True)], - outputs="audio", - title="Cloning Interface" - ) -demo.launch() \ No newline at end of file diff --git a/spaces/Smotto/Vocal-Isolator/src/models/MDX_net/mdx_net.py b/spaces/Smotto/Vocal-Isolator/src/models/MDX_net/mdx_net.py deleted file mode 100644 index 793b9e58ef474c10c9fd9e3034063d970d4900a7..0000000000000000000000000000000000000000 --- a/spaces/Smotto/Vocal-Isolator/src/models/MDX_net/mdx_net.py +++ /dev/null @@ -1,275 +0,0 @@ -# Third-party -import torch -import torch.nn as nn - -# Local -from src.Sound_Feature_Extraction.short_time_fourier_transform import STFT - -COMPUTATION_DEVICE = "cuda" if torch.cuda.is_available() else "cpu" - - -class Conv_TDF(nn.Module): - """ - Convolutional Time-Domain Filter (TDF) Module. - - Args: - c (int): The number of input and output channels for the convolutional layers. - l (int): The number of convolutional layers within the module. - f (int): The number of features (or units) in the time-domain filter. - k (int): The size of the convolutional kernels (filters). - bn (int or None): Batch normalization factor (controls TDF behavior). If None, TDF is not used. - bias (bool): A boolean flag indicating whether bias terms are included in the linear layers. - - Attributes: - use_tdf (bool): Flag indicating whether TDF is used. - - Methods: - forward(x): Forward pass through the TDF module. - """ - - def __init__(self, c, l, f, k, bn, bias=True): - super(Conv_TDF, self).__init__() - - # Determine whether to use TDF (Time-Domain Filter) - self.use_tdf = bn is not None - - # Define a list of convolutional layers within the module - self.H = nn.ModuleList() - for i in range(l): - self.H.append( - nn.Sequential( - nn.Conv2d( - in_channels=c, - out_channels=c, - kernel_size=k, - stride=1, - padding=k // 2, - ), - nn.GroupNorm(2, c), - nn.ReLU(), - ) - ) - - # Define the Time-Domain Filter (TDF) layers if enabled - if self.use_tdf: - if bn == 0: - self.tdf = nn.Sequential( - nn.Linear(f, f, bias=bias), nn.GroupNorm(2, c), nn.ReLU() - ) - else: - self.tdf = nn.Sequential( - nn.Linear(f, f // bn, bias=bias), - nn.GroupNorm(2, c), - nn.ReLU(), - nn.Linear(f // bn, f, bias=bias), - nn.GroupNorm(2, c), - nn.ReLU(), - ) - - def forward(self, x): - # Apply the convolutional layers sequentially - for h in self.H: - x = h(x) - - # Apply the Time-Domain Filter (TDF) if enabled, and add the result to the orignal input - return x + self.tdf(x) if self.use_tdf else x - - -class Conv_TDF_net_trimm(nn.Module): - """ - Convolutional Time-Domain Filter (TDF) Network with Trimming. - - Args: - L (int): This parameter controls the number of down-sampling (DS) blocks in the network. - It's divided by 2 to determine how many DS blocks should be created. - l (int): This parameter represents the number of convolutional layers (or filters) within each dense (fully connected) block. - g (int): This parameter specifies the number of output channels for the first convolutional layer and is also used to determine the number of channels for subsequent layers in the network. - dim_f (int): This parameter represents the number of frequency bins (spectrogram columns) in the input audio data. - dim_t (int): This parameter represents the number of time frames (spectrogram rows) in the input audio data. - k (int): This parameter specifies the size of convolutional kernels (filters) used in the network's convolutional layers. - bn (int or None): This parameter controls whether batch normalization is used in the network. - If it's None, batch normalization may or may not be used based on other conditions in the code. - bias (bool): This parameter is a boolean flag that controls whether bias terms are included in the convolutional layers. - overlap (int): This parameter specifies the amount of overlap between consecutive chunks of audio data during processing. - - Attributes: - n (int): The calculated number of down-sampling (DS) blocks. - dim_f (int): The number of frequency bins (spectrogram columns) in the input audio data. - dim_t (int): The number of time frames (spectrogram rows) in the input audio data. - n_fft (int): The size of the Fast Fourier Transform (FFT) window. - hop (int): The hop size used in the STFT calculations. - n_bins (int): The number of bins in the frequency domain. - chunk_size (int): The size of each chunk of audio data. - target_name (str): The name of the target instrument being separated. - overlap (int): The amount of overlap between consecutive chunks of audio data during processing. - - Methods: - forward(x): Forward pass through the Conv_TDF_net_trimm network. - """ - - def __init__( - self, - model_path, - use_onnx, - target_name, - L, - l, - g, - dim_f, - dim_t, - k=3, - hop=1024, - bn=None, - bias=True, - overlap=1500, - ): - super(Conv_TDF_net_trimm, self).__init__() - # Dictionary specifying the scale for the number of FFT bins for different target names - n_fft_scale = {"vocals": 3, "*": 2} - - # Number of input and output channels for the initial and final convolutional layers - out_c = in_c = 4 - - # Number of down-sampling (DS) blocks - self.n = L // 2 - - # Dimensions of the frequency and time axes of the input data - self.dim_f = 3072 - self.dim_t = 256 - - # Number of FFT bins (frequencies) and hop size for the Short-Time Fourier Transform (STFT) - self.n_fft = 7680 - self.hop = hop - self.n_bins = self.n_fft // 2 + 1 - - # Chunk size used for processing - self.chunk_size = hop * (self.dim_t - 1) - - # Target name for the model - self.target_name = target_name - - # Overlap between consecutive chunks of audio data during processing - self.overlap = overlap - - # STFT module for audio processing - self.stft = STFT(self.n_fft, self.hop, self.dim_f) - - # Check if ONNX representation of the model should be used - if not use_onnx: - # First convolutional layer - self.first_conv = nn.Sequential( - nn.Conv2d(in_channels=in_c, out_channels=g, kernel_size=1, stride=1), - nn.BatchNorm2d(g), - nn.ReLU(), - ) - - # Initialize variables for dense (fully connected) blocks and downsampling (DS) blocks - f = self.dim_f - c = g - self.ds_dense = nn.ModuleList() - self.ds = nn.ModuleList() - - # Loop through down-sampling (DS) blocks - for i in range(self.n): - # Create dense (fully connected) block for down-sampling - self.ds_dense.append(Conv_TDF(c, l, f, k, bn, bias=bias)) - - # Create down-sampling (DS) block - scale = (2, 2) - self.ds.append( - nn.Sequential( - nn.Conv2d( - in_channels=c, - out_channels=c + g, - kernel_size=scale, - stride=scale, - ), - nn.BatchNorm2d(c + g), - nn.ReLU(), - ) - ) - f = f // 2 - c += g - - # Middle dense (fully connected block) - self.mid_dense = Conv_TDF(c, l, f, k, bn, bias=bias) - - # If batch normalization is not specified and mid_tdf is True, use Conv_TDF with bn=0 and bias=False - if bn is None and mid_tdf: - self.mid_dense = Conv_TDF(c, l, f, k, bn=0, bias=False) - - # Initialize variables for up-sampling (US) blocks - self.us_dense = nn.ModuleList() - self.us = nn.ModuleList() - - # Loop through up-sampling (US) blocks - for i in range(self.n): - scale = (2, 2) - # Create up-sampling (US) block - self.us.append( - nn.Sequential( - nn.ConvTranspose2d( - in_channels=c, - out_channels=c - g, - kernel_size=scale, - stride=scale, - ), - nn.BatchNorm2d(c - g), - nn.ReLU(), - ) - ) - f = f * 2 - c -= g - - # Create dense (fully connected) block for up-sampling - self.us_dense.append(Conv_TDF(c, l, f, k, bn, bias=bias)) - - # Final convolutional layer - self.final_conv = nn.Sequential( - nn.Conv2d(in_channels=c, out_channels=out_c, kernel_size=1, stride=1), - ) - - try: - # Load model state from a file - self.load_state_dict( - torch.load( - f"{model_path}/{target_name}.pt", - map_location=COMPUTATION_DEVICE, - ) - ) - print(f"Loading model ({target_name})") - except FileNotFoundError: - print(f"Random init ({target_name})") - - def forward(self, x): - """ - Forward pass through the Conv_TDF_net_trimm network. - - Args: - x (torch.Tensor): Input tensor. - - Returns: - torch.Tensor: Output tensor after passing through the network. - """ - x = self.first_conv(x) - - x = x.transpose(-1, -2) - - ds_outputs = [] - for i in range(self.n): - x = self.ds_dense[i](x) - ds_outputs.append(x) - x = self.ds[i](x) - - x = self.mid_dense(x) - - for i in range(self.n): - x = self.us[i](x) - x *= ds_outputs[-i - 1] - x = self.us_dense[i](x) - - x = x.transpose(-1, -2) - - x = self.final_conv(x) - - return x diff --git a/spaces/Sumit7864/Image-Enhancer/docs/anime_video_model.md b/spaces/Sumit7864/Image-Enhancer/docs/anime_video_model.md deleted file mode 100644 index 0ad5c85804c1f8636c3720a652b40bbd9df0fe2e..0000000000000000000000000000000000000000 --- a/spaces/Sumit7864/Image-Enhancer/docs/anime_video_model.md +++ /dev/null @@ -1,136 +0,0 @@ -# Anime Video Models - -:white_check_mark: We add small models that are optimized for anime videos :-)
-More comparisons can be found in [anime_comparisons.md](anime_comparisons.md) - -- [How to Use](#how-to-use) -- [PyTorch Inference](#pytorch-inference) -- [ncnn Executable File](#ncnn-executable-file) - - [Step 1: Use ffmpeg to extract frames from video](#step-1-use-ffmpeg-to-extract-frames-from-video) - - [Step 2: Inference with Real-ESRGAN executable file](#step-2-inference-with-real-esrgan-executable-file) - - [Step 3: Merge the enhanced frames back into a video](#step-3-merge-the-enhanced-frames-back-into-a-video) -- [More Demos](#more-demos) - -| Models | Scale | Description | -| ---------------------------------------------------------------------------------------------------------------------------------- | :---- | :----------------------------- | -| [realesr-animevideov3](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth) | X4 1 | Anime video model with XS size | - -Note:
-1 This model can also be used for X1, X2, X3. - ---- - -The following are some demos (best view in the full screen mode). - - - - - - - -## How to Use - -### PyTorch Inference - -```bash -# download model -wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth -P weights -# single gpu and single process inference -CUDA_VISIBLE_DEVICES=0 python inference_realesrgan_video.py -i inputs/video/onepiece_demo.mp4 -n realesr-animevideov3 -s 2 --suffix outx2 -# single gpu and multi process inference (you can use multi-processing to improve GPU utilization) -CUDA_VISIBLE_DEVICES=0 python inference_realesrgan_video.py -i inputs/video/onepiece_demo.mp4 -n realesr-animevideov3 -s 2 --suffix outx2 --num_process_per_gpu 2 -# multi gpu and multi process inference -CUDA_VISIBLE_DEVICES=0,1,2,3 python inference_realesrgan_video.py -i inputs/video/onepiece_demo.mp4 -n realesr-animevideov3 -s 2 --suffix outx2 --num_process_per_gpu 2 -``` - -```console -Usage: ---num_process_per_gpu The total number of process is num_gpu * num_process_per_gpu. The bottleneck of - the program lies on the IO, so the GPUs are usually not fully utilized. To alleviate - this issue, you can use multi-processing by setting this parameter. As long as it - does not exceed the CUDA memory ---extract_frame_first If you encounter ffmpeg error when using multi-processing, you can turn this option on. -``` - -### NCNN Executable File - -#### Step 1: Use ffmpeg to extract frames from video - -```bash -ffmpeg -i onepiece_demo.mp4 -qscale:v 1 -qmin 1 -qmax 1 -vsync 0 tmp_frames/frame%08d.png -``` - -- Remember to create the folder `tmp_frames` ahead - -#### Step 2: Inference with Real-ESRGAN executable file - -1. Download the latest portable [Windows](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-windows.zip) / [Linux](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-ubuntu.zip) / [MacOS](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-macos.zip) **executable files for Intel/AMD/Nvidia GPU** - -1. Taking the Windows as example, run: - - ```bash - ./realesrgan-ncnn-vulkan.exe -i tmp_frames -o out_frames -n realesr-animevideov3 -s 2 -f jpg - ``` - - - Remember to create the folder `out_frames` ahead - -#### Step 3: Merge the enhanced frames back into a video - -1. First obtain fps from input videos by - - ```bash - ffmpeg -i onepiece_demo.mp4 - ``` - - ```console - Usage: - -i input video path - ``` - - You will get the output similar to the following screenshot. - -

- -

- -2. Merge frames - - ```bash - ffmpeg -r 23.98 -i out_frames/frame%08d.jpg -c:v libx264 -r 23.98 -pix_fmt yuv420p output.mp4 - ``` - - ```console - Usage: - -i input video path - -c:v video encoder (usually we use libx264) - -r fps, remember to modify it to meet your needs - -pix_fmt pixel format in video - ``` - - If you also want to copy audio from the input videos, run: - - ```bash - ffmpeg -r 23.98 -i out_frames/frame%08d.jpg -i onepiece_demo.mp4 -map 0:v:0 -map 1:a:0 -c:a copy -c:v libx264 -r 23.98 -pix_fmt yuv420p output_w_audio.mp4 - ``` - - ```console - Usage: - -i input video path, here we use two input streams - -c:v video encoder (usually we use libx264) - -r fps, remember to modify it to meet your needs - -pix_fmt pixel format in video - ``` - -## More Demos - -- Input video for One Piece: - - - -- Out video for One Piece - - - -**More comparisons** - - diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/core/magics/config.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/core/magics/config.py deleted file mode 100644 index 9e1cb38c254f412cae88890bdd2da92da5232908..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/core/magics/config.py +++ /dev/null @@ -1,140 +0,0 @@ -"""Implementation of configuration-related magic functions. -""" -#----------------------------------------------------------------------------- -# Copyright (c) 2012 The IPython Development Team. -# -# Distributed under the terms of the Modified BSD License. -# -# The full license is in the file COPYING.txt, distributed with this software. -#----------------------------------------------------------------------------- - -#----------------------------------------------------------------------------- -# Imports -#----------------------------------------------------------------------------- - -# Stdlib -import re - -# Our own packages -from IPython.core.error import UsageError -from IPython.core.magic import Magics, magics_class, line_magic -from logging import error - -#----------------------------------------------------------------------------- -# Magic implementation classes -#----------------------------------------------------------------------------- - -reg = re.compile(r'^\w+\.\w+$') -@magics_class -class ConfigMagics(Magics): - - def __init__(self, shell): - super(ConfigMagics, self).__init__(shell) - self.configurables = [] - - @line_magic - def config(self, s): - """configure IPython - - %config Class[.trait=value] - - This magic exposes most of the IPython config system. Any - Configurable class should be able to be configured with the simple - line:: - - %config Class.trait=value - - Where `value` will be resolved in the user's namespace, if it is an - expression or variable name. - - Examples - -------- - - To see what classes are available for config, pass no arguments:: - - In [1]: %config - Available objects for config: - AliasManager - DisplayFormatter - HistoryManager - IPCompleter - LoggingMagics - MagicsManager - OSMagics - PrefilterManager - ScriptMagics - TerminalInteractiveShell - - To view what is configurable on a given class, just pass the class - name:: - - In [2]: %config LoggingMagics - LoggingMagics(Magics) options - --------------------------- - LoggingMagics.quiet= - Suppress output of log state when logging is enabled - Current: False - - but the real use is in setting values:: - - In [3]: %config LoggingMagics.quiet = True - - and these values are read from the user_ns if they are variables:: - - In [4]: feeling_quiet=False - - In [5]: %config LoggingMagics.quiet = feeling_quiet - - """ - from traitlets.config.loader import Config - # some IPython objects are Configurable, but do not yet have - # any configurable traits. Exclude them from the effects of - # this magic, as their presence is just noise: - configurables = sorted(set([ c for c in self.shell.configurables - if c.__class__.class_traits(config=True) - ]), key=lambda x: x.__class__.__name__) - classnames = [ c.__class__.__name__ for c in configurables ] - - line = s.strip() - if not line: - # print available configurable names - print("Available objects for config:") - for name in classnames: - print(" ", name) - return - elif line in classnames: - # `%config TerminalInteractiveShell` will print trait info for - # TerminalInteractiveShell - c = configurables[classnames.index(line)] - cls = c.__class__ - help = cls.class_get_help(c) - # strip leading '--' from cl-args: - help = re.sub(re.compile(r'^--', re.MULTILINE), '', help) - print(help) - return - elif reg.match(line): - cls, attr = line.split('.') - return getattr(configurables[classnames.index(cls)],attr) - elif '=' not in line: - msg = "Invalid config statement: %r, "\ - "should be `Class.trait = value`." - - ll = line.lower() - for classname in classnames: - if ll == classname.lower(): - msg = msg + '\nDid you mean %s (note the case)?' % classname - break - - raise UsageError( msg % line) - - # otherwise, assume we are setting configurables. - # leave quotes on args when splitting, because we want - # unquoted args to eval in user_ns - cfg = Config() - exec("cfg."+line, self.shell.user_ns, locals()) - - for configurable in configurables: - try: - configurable.update_config(cfg) - except Exception as e: - error(e) diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/core/tests/test_autocall.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/core/tests/test_autocall.py deleted file mode 100644 index 925a1ccae3758683dcee9e8235ae8b9d8969057d..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/core/tests/test_autocall.py +++ /dev/null @@ -1,67 +0,0 @@ -"""These kinds of tests are less than ideal, but at least they run. - -This was an old test that was being run interactively in the top-level tests/ -directory, which we are removing. For now putting this here ensures at least -we do run the test, though ultimately this functionality should all be tested -with better-isolated tests that don't rely on the global instance in iptest. -""" -from IPython.core.splitinput import LineInfo -from IPython.core.prefilter import AutocallChecker - - -def doctest_autocall(): - """ - In [1]: def f1(a,b,c): - ...: return a+b+c - ...: - - In [2]: def f2(a): - ...: return a + a - ...: - - In [3]: def r(x): - ...: return True - ...: - - In [4]: ;f2 a b c - Out[4]: 'a b ca b c' - - In [5]: assert _ == "a b ca b c" - - In [6]: ,f1 a b c - Out[6]: 'abc' - - In [7]: assert _ == 'abc' - - In [8]: print(_) - abc - - In [9]: /f1 1,2,3 - Out[9]: 6 - - In [10]: assert _ == 6 - - In [11]: /f2 4 - Out[11]: 8 - - In [12]: assert _ == 8 - - In [12]: del f1, f2 - - In [13]: ,r a - Out[13]: True - - In [14]: assert _ == True - - In [15]: r'a' - Out[15]: 'a' - - In [16]: assert _ == 'a' - """ - - -def test_autocall_should_ignore_raw_strings(): - line_info = LineInfo("r'a'") - pm = ip.prefilter_manager - ac = AutocallChecker(shell=pm.shell, prefilter_manager=pm, config=pm.config) - assert ac.check(line_info) is None diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/altair/vegalite/v5/theme.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/altair/vegalite/v5/theme.py deleted file mode 100644 index b536a1ddebe6c311672e6ce2757853ecffa6fb1e..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/altair/vegalite/v5/theme.py +++ /dev/null @@ -1,59 +0,0 @@ -"""Tools for enabling and registering chart themes""" - -from ...utils.theme import ThemeRegistry - -VEGA_THEMES = [ - "ggplot2", - "quartz", - "vox", - "fivethirtyeight", - "dark", - "latimes", - "urbaninstitute", - "excel", - "googlecharts", - "powerbi", -] - - -class VegaTheme: - """Implementation of a builtin vega theme.""" - - def __init__(self, theme): - self.theme = theme - - def __call__(self): - return { - "usermeta": {"embedOptions": {"theme": self.theme}}, - "config": {"view": {"continuousWidth": 300, "continuousHeight": 300}}, - } - - def __repr__(self): - return "VegaTheme({!r})".format(self.theme) - - -# The entry point group that can be used by other packages to declare other -# renderers that will be auto-detected. Explicit registration is also -# allowed by the PluginRegistery API. -ENTRY_POINT_GROUP = "altair.vegalite.v5.theme" # type: str -themes = ThemeRegistry(entry_point_group=ENTRY_POINT_GROUP) - -themes.register( - "default", - lambda: {"config": {"view": {"continuousWidth": 300, "continuousHeight": 300}}}, -) -themes.register( - "opaque", - lambda: { - "config": { - "background": "white", - "view": {"continuousWidth": 300, "continuousHeight": 300}, - } - }, -) -themes.register("none", lambda: {}) - -for theme in VEGA_THEMES: - themes.register(theme, VegaTheme(theme)) - -themes.enable("default") diff --git a/spaces/Suniilkumaar/MusicGen-updated/CHANGELOG.md b/spaces/Suniilkumaar/MusicGen-updated/CHANGELOG.md deleted file mode 100644 index 24fc214df236b40efead4b1585b01632d9658e9b..0000000000000000000000000000000000000000 --- a/spaces/Suniilkumaar/MusicGen-updated/CHANGELOG.md +++ /dev/null @@ -1,23 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - -## [0.0.2a] - TBD - -Improved demo, fixed top p (thanks @jnordberg). - -Compressor tanh on output to avoid clipping with some style (especially piano). -Now repeating the conditioning periodically if it is too short. - -More options when launching Gradio app locally (thanks @ashleykleynhans). - -Testing out PyTorch 2.0 memory efficient attention. - -Added extended generation (infinite length) by slowly moving the windows. -Note that other implementations exist: https://github.com/camenduru/MusicGen-colab. - -## [0.0.1] - 2023-06-09 - -Initial release, with model evaluation only. diff --git a/spaces/Superlang/ImageProcessor/annotator/uniformer/mmcv/utils/env.py b/spaces/Superlang/ImageProcessor/annotator/uniformer/mmcv/utils/env.py deleted file mode 100644 index e3f0d92529e193e6d8339419bcd9bed7901a7769..0000000000000000000000000000000000000000 --- a/spaces/Superlang/ImageProcessor/annotator/uniformer/mmcv/utils/env.py +++ /dev/null @@ -1,95 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -"""This file holding some environment constant for sharing by other files.""" - -import os.path as osp -import subprocess -import sys -from collections import defaultdict - -import cv2 -import torch - -import annotator.uniformer.mmcv as mmcv -from .parrots_wrapper import get_build_config - - -def collect_env(): - """Collect the information of the running environments. - - Returns: - dict: The environment information. The following fields are contained. - - - sys.platform: The variable of ``sys.platform``. - - Python: Python version. - - CUDA available: Bool, indicating if CUDA is available. - - GPU devices: Device type of each GPU. - - CUDA_HOME (optional): The env var ``CUDA_HOME``. - - NVCC (optional): NVCC version. - - GCC: GCC version, "n/a" if GCC is not installed. - - PyTorch: PyTorch version. - - PyTorch compiling details: The output of \ - ``torch.__config__.show()``. - - TorchVision (optional): TorchVision version. - - OpenCV: OpenCV version. - - MMCV: MMCV version. - - MMCV Compiler: The GCC version for compiling MMCV ops. - - MMCV CUDA Compiler: The CUDA version for compiling MMCV ops. - """ - env_info = {} - env_info['sys.platform'] = sys.platform - env_info['Python'] = sys.version.replace('\n', '') - - cuda_available = torch.cuda.is_available() - env_info['CUDA available'] = cuda_available - - if cuda_available: - devices = defaultdict(list) - for k in range(torch.cuda.device_count()): - devices[torch.cuda.get_device_name(k)].append(str(k)) - for name, device_ids in devices.items(): - env_info['GPU ' + ','.join(device_ids)] = name - - from annotator.uniformer.mmcv.utils.parrots_wrapper import _get_cuda_home - CUDA_HOME = _get_cuda_home() - env_info['CUDA_HOME'] = CUDA_HOME - - if CUDA_HOME is not None and osp.isdir(CUDA_HOME): - try: - nvcc = osp.join(CUDA_HOME, 'bin/nvcc') - nvcc = subprocess.check_output( - f'"{nvcc}" -V | tail -n1', shell=True) - nvcc = nvcc.decode('utf-8').strip() - except subprocess.SubprocessError: - nvcc = 'Not Available' - env_info['NVCC'] = nvcc - - try: - gcc = subprocess.check_output('gcc --version | head -n1', shell=True) - gcc = gcc.decode('utf-8').strip() - env_info['GCC'] = gcc - except subprocess.CalledProcessError: # gcc is unavailable - env_info['GCC'] = 'n/a' - - env_info['PyTorch'] = torch.__version__ - env_info['PyTorch compiling details'] = get_build_config() - - try: - import torchvision - env_info['TorchVision'] = torchvision.__version__ - except ModuleNotFoundError: - pass - - env_info['OpenCV'] = cv2.__version__ - - env_info['MMCV'] = mmcv.__version__ - - try: - from annotator.uniformer.mmcv.ops import get_compiler_version, get_compiling_cuda_version - except ModuleNotFoundError: - env_info['MMCV Compiler'] = 'n/a' - env_info['MMCV CUDA Compiler'] = 'n/a' - else: - env_info['MMCV Compiler'] = get_compiler_version() - env_info['MMCV CUDA Compiler'] = get_compiling_cuda_version() - - return env_info diff --git a/spaces/TH5314/newbing/src/app/layout.tsx b/spaces/TH5314/newbing/src/app/layout.tsx deleted file mode 100644 index 8b5122759987177b8dc4e4356d1d06cea25c15ea..0000000000000000000000000000000000000000 --- a/spaces/TH5314/newbing/src/app/layout.tsx +++ /dev/null @@ -1,47 +0,0 @@ -import { Metadata } from 'next' -import { Toaster } from 'react-hot-toast' -import { TailwindIndicator } from '@/components/tailwind-indicator' -import { Providers } from '@/components/providers' -import { Header } from '@/components/header' - -import '@/app/globals.scss' - - -export const metadata: Metadata = { - title: { - default: 'Bing AI Chatbot', - template: `%s - Bing AI Chatbot` - }, - description: 'Bing AI Chatbot Web App.', - themeColor: [ - { media: '(prefers-color-scheme: light)', color: 'white' }, - { media: '(prefers-color-scheme: dark)', color: 'dark' } - ], - icons: { - icon: '/favicon.ico', - shortcut: '../assets/images/logo.svg', - apple: '../assets/images/logo.svg' - } -} - -interface RootLayoutProps { - children: React.ReactNode -} - -export default function RootLayout({ children }: RootLayoutProps) { - return ( - - - - -
- {/* @ts-ignore */} -
-
{children}
-
- -
- - - ) -} diff --git a/spaces/TRI-ML/risk_biased_prediction/tests/risk_biased/models/test_nn_interaction.py b/spaces/TRI-ML/risk_biased_prediction/tests/risk_biased/models/test_nn_interaction.py deleted file mode 100644 index a8ee8792846ba367e76e6606a44c2512fd1f4bba..0000000000000000000000000000000000000000 --- a/spaces/TRI-ML/risk_biased_prediction/tests/risk_biased/models/test_nn_interaction.py +++ /dev/null @@ -1,113 +0,0 @@ -from cmath import isnan -import pytest - -import torch -from mmcv import Config - -from risk_biased.models.nn_blocks import ( - SequenceDecoderLSTM, - SequenceDecoderMLP, - SequenceEncoderMaskedLSTM, - SequenceEncoderMLP, - AttentionBlock, -) - - -@pytest.fixture(scope="module") -def params(): - torch.manual_seed(0) - cfg = Config() - cfg.batch_size = 4 - cfg.input_dim = 10 - cfg.output_dim = 15 - cfg.latent_dim = 3 - cfg.h_dim = 32 - cfg.num_attention_heads = 4 - cfg.num_h_layers = 2 - cfg.device = "cpu" - return cfg - - -def test_AttentionBlock(params): - attention = AttentionBlock(params.h_dim, params.num_attention_heads) - num_agents = 4 - num_map_objects = 8 - encoded_agents = torch.rand(params.batch_size, num_agents, params.h_dim) - mask_agents = torch.rand(params.batch_size, num_agents) > 0.1 - encoded_absolute_agents = torch.rand(params.batch_size, num_agents, params.h_dim) - encoded_map = torch.rand(params.batch_size, num_map_objects, params.h_dim) - mask_map = torch.rand(params.batch_size, num_map_objects) > 0.1 - output = attention( - encoded_agents, mask_agents, encoded_absolute_agents, encoded_map, mask_map - ) - # check shape - assert output.shape == (params.batch_size, num_agents, params.h_dim) - assert not torch.isnan(output).any() - - -def test_SequenceDecoder(params): - decoder = SequenceDecoderLSTM(params.h_dim) - num_agents = 8 - sequence_length = 16 - - input = torch.rand(params.batch_size, num_agents, params.h_dim) - - output = decoder(input, sequence_length) - - assert output.shape == ( - params.batch_size, - num_agents, - sequence_length, - params.h_dim, - ) - assert not torch.isnan(output).any() - - -def test_SequenceDecoderMLP(params): - sequence_length = 16 - decoder = SequenceDecoderMLP( - params.h_dim, params.num_h_layers, sequence_length, True - ) - num_agents = 8 - - input = torch.rand(params.batch_size, num_agents, params.h_dim) - - output = decoder(input, sequence_length) - - assert output.shape == ( - params.batch_size, - num_agents, - sequence_length, - params.h_dim, - ) - assert not torch.isnan(output).any() - - -def test_SequenceEncoder(params): - encoder = SequenceEncoderMaskedLSTM(params.input_dim, params.h_dim) - num_agents = 8 - sequence_length = 16 - - input = torch.rand(params.batch_size, num_agents, sequence_length, params.input_dim) - mask_input = torch.rand(params.batch_size, num_agents, sequence_length) > 0.1 - - output = encoder(input, mask_input) - - assert output.shape == (params.batch_size, num_agents, params.h_dim) - assert not torch.isnan(output).any() - - -def test_SequenceEncoderMLP(params): - sequence_length = 16 - num_agents = 8 - encoder = SequenceEncoderMLP( - params.input_dim, params.h_dim, params.num_h_layers, sequence_length, True - ) - - input = torch.rand(params.batch_size, num_agents, sequence_length, params.input_dim) - mask_input = torch.rand(params.batch_size, num_agents, sequence_length) > 0.1 - - output = encoder(input, mask_input) - - assert output.shape == (params.batch_size, num_agents, params.h_dim) - assert not torch.isnan(output).any() diff --git a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/pygments/styles/__init__.py b/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/pygments/styles/__init__.py deleted file mode 100644 index 7401cf5d3a372da67d241dafe83ba756e015eafa..0000000000000000000000000000000000000000 --- a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/pygments/styles/__init__.py +++ /dev/null @@ -1,103 +0,0 @@ -""" - pygments.styles - ~~~~~~~~~~~~~~~ - - Contains built-in styles. - - :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -from pip._vendor.pygments.plugin import find_plugin_styles -from pip._vendor.pygments.util import ClassNotFound - -#: A dictionary of built-in styles, mapping style names to -#: ``'submodule::classname'`` strings. -STYLE_MAP = { - 'default': 'default::DefaultStyle', - 'emacs': 'emacs::EmacsStyle', - 'friendly': 'friendly::FriendlyStyle', - 'friendly_grayscale': 'friendly_grayscale::FriendlyGrayscaleStyle', - 'colorful': 'colorful::ColorfulStyle', - 'autumn': 'autumn::AutumnStyle', - 'murphy': 'murphy::MurphyStyle', - 'manni': 'manni::ManniStyle', - 'material': 'material::MaterialStyle', - 'monokai': 'monokai::MonokaiStyle', - 'perldoc': 'perldoc::PerldocStyle', - 'pastie': 'pastie::PastieStyle', - 'borland': 'borland::BorlandStyle', - 'trac': 'trac::TracStyle', - 'native': 'native::NativeStyle', - 'fruity': 'fruity::FruityStyle', - 'bw': 'bw::BlackWhiteStyle', - 'vim': 'vim::VimStyle', - 'vs': 'vs::VisualStudioStyle', - 'tango': 'tango::TangoStyle', - 'rrt': 'rrt::RrtStyle', - 'xcode': 'xcode::XcodeStyle', - 'igor': 'igor::IgorStyle', - 'paraiso-light': 'paraiso_light::ParaisoLightStyle', - 'paraiso-dark': 'paraiso_dark::ParaisoDarkStyle', - 'lovelace': 'lovelace::LovelaceStyle', - 'algol': 'algol::AlgolStyle', - 'algol_nu': 'algol_nu::Algol_NuStyle', - 'arduino': 'arduino::ArduinoStyle', - 'rainbow_dash': 'rainbow_dash::RainbowDashStyle', - 'abap': 'abap::AbapStyle', - 'solarized-dark': 'solarized::SolarizedDarkStyle', - 'solarized-light': 'solarized::SolarizedLightStyle', - 'sas': 'sas::SasStyle', - 'staroffice' : 'staroffice::StarofficeStyle', - 'stata': 'stata_light::StataLightStyle', - 'stata-light': 'stata_light::StataLightStyle', - 'stata-dark': 'stata_dark::StataDarkStyle', - 'inkpot': 'inkpot::InkPotStyle', - 'zenburn': 'zenburn::ZenburnStyle', - 'gruvbox-dark': 'gruvbox::GruvboxDarkStyle', - 'gruvbox-light': 'gruvbox::GruvboxLightStyle', - 'dracula': 'dracula::DraculaStyle', - 'one-dark': 'onedark::OneDarkStyle', - 'lilypond' : 'lilypond::LilyPondStyle', - 'nord': 'nord::NordStyle', - 'nord-darker': 'nord::NordDarkerStyle', - 'github-dark': 'gh_dark::GhDarkStyle' -} - - -def get_style_by_name(name): - """ - Return a style class by its short name. The names of the builtin styles - are listed in :data:`pygments.styles.STYLE_MAP`. - - Will raise :exc:`pygments.util.ClassNotFound` if no style of that name is - found. - """ - if name in STYLE_MAP: - mod, cls = STYLE_MAP[name].split('::') - builtin = "yes" - else: - for found_name, style in find_plugin_styles(): - if name == found_name: - return style - # perhaps it got dropped into our styles package - builtin = "" - mod = name - cls = name.title() + "Style" - - try: - mod = __import__('pygments.styles.' + mod, None, None, [cls]) - except ImportError: - raise ClassNotFound("Could not find style module %r" % mod + - (builtin and ", though it should be builtin") + ".") - try: - return getattr(mod, cls) - except AttributeError: - raise ClassNotFound("Could not find style class %r in style module." % cls) - - -def get_all_styles(): - """Return a generator for all styles by name, both builtin and plugin.""" - yield from STYLE_MAP - for name, _ in find_plugin_styles(): - yield name diff --git a/spaces/ThirdEyeData/TagDiciphering/static_shape.py b/spaces/ThirdEyeData/TagDiciphering/static_shape.py deleted file mode 100644 index 4f91608328db22a63523db58dc6531b388c3c309..0000000000000000000000000000000000000000 --- a/spaces/ThirdEyeData/TagDiciphering/static_shape.py +++ /dev/null @@ -1,90 +0,0 @@ -# Copyright 2017 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. -# ============================================================================== - -"""Helper functions to access TensorShape values. - -The rank 4 tensor_shape must be of the form [batch_size, height, width, depth]. -""" - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - - -def get_dim_as_int(dim): - """Utility to get v1 or v2 TensorShape dim as an int. - - Args: - dim: The TensorShape dimension to get as an int - - Returns: - None or an int. - """ - try: - return dim.value - except AttributeError: - return dim - - -def get_batch_size(tensor_shape): - """Returns batch size from the tensor shape. - - Args: - tensor_shape: A rank 4 TensorShape. - - Returns: - An integer representing the batch size of the tensor. - """ - tensor_shape.assert_has_rank(rank=4) - return get_dim_as_int(tensor_shape[0]) - - -def get_height(tensor_shape): - """Returns height from the tensor shape. - - Args: - tensor_shape: A rank 4 TensorShape. - - Returns: - An integer representing the height of the tensor. - """ - tensor_shape.assert_has_rank(rank=4) - return get_dim_as_int(tensor_shape[1]) - - -def get_width(tensor_shape): - """Returns width from the tensor shape. - - Args: - tensor_shape: A rank 4 TensorShape. - - Returns: - An integer representing the width of the tensor. - """ - tensor_shape.assert_has_rank(rank=4) - return get_dim_as_int(tensor_shape[2]) - - -def get_depth(tensor_shape): - """Returns depth from the tensor shape. - - Args: - tensor_shape: A rank 4 TensorShape. - - Returns: - An integer representing the depth of the tensor. - """ - tensor_shape.assert_has_rank(rank=4) - return get_dim_as_int(tensor_shape[3]) diff --git a/spaces/TwoCH4/White-box-Cartoonization/wbc/network.py b/spaces/TwoCH4/White-box-Cartoonization/wbc/network.py deleted file mode 100644 index 6f16cee1aa1994d0a78c524f459764de5164e637..0000000000000000000000000000000000000000 --- a/spaces/TwoCH4/White-box-Cartoonization/wbc/network.py +++ /dev/null @@ -1,62 +0,0 @@ -import tensorflow as tf -import numpy as np -import tensorflow.contrib.slim as slim - - - -def resblock(inputs, out_channel=32, name='resblock'): - - with tf.variable_scope(name): - - x = slim.convolution2d(inputs, out_channel, [3, 3], - activation_fn=None, scope='conv1') - x = tf.nn.leaky_relu(x) - x = slim.convolution2d(x, out_channel, [3, 3], - activation_fn=None, scope='conv2') - - return x + inputs - - - - -def unet_generator(inputs, channel=32, num_blocks=4, name='generator', reuse=False): - with tf.variable_scope(name, reuse=reuse): - - x0 = slim.convolution2d(inputs, channel, [7, 7], activation_fn=None) - x0 = tf.nn.leaky_relu(x0) - - x1 = slim.convolution2d(x0, channel, [3, 3], stride=2, activation_fn=None) - x1 = tf.nn.leaky_relu(x1) - x1 = slim.convolution2d(x1, channel*2, [3, 3], activation_fn=None) - x1 = tf.nn.leaky_relu(x1) - - x2 = slim.convolution2d(x1, channel*2, [3, 3], stride=2, activation_fn=None) - x2 = tf.nn.leaky_relu(x2) - x2 = slim.convolution2d(x2, channel*4, [3, 3], activation_fn=None) - x2 = tf.nn.leaky_relu(x2) - - for idx in range(num_blocks): - x2 = resblock(x2, out_channel=channel*4, name='block_{}'.format(idx)) - - x2 = slim.convolution2d(x2, channel*2, [3, 3], activation_fn=None) - x2 = tf.nn.leaky_relu(x2) - - h1, w1 = tf.shape(x2)[1], tf.shape(x2)[2] - x3 = tf.image.resize_bilinear(x2, (h1*2, w1*2)) - x3 = slim.convolution2d(x3+x1, channel*2, [3, 3], activation_fn=None) - x3 = tf.nn.leaky_relu(x3) - x3 = slim.convolution2d(x3, channel, [3, 3], activation_fn=None) - x3 = tf.nn.leaky_relu(x3) - - h2, w2 = tf.shape(x3)[1], tf.shape(x3)[2] - x4 = tf.image.resize_bilinear(x3, (h2*2, w2*2)) - x4 = slim.convolution2d(x4+x0, channel, [3, 3], activation_fn=None) - x4 = tf.nn.leaky_relu(x4) - x4 = slim.convolution2d(x4, 3, [7, 7], activation_fn=None) - - return x4 - -if __name__ == '__main__': - - - pass \ No newline at end of file diff --git a/spaces/User1342/WatchTower/Pinpoint/Sanitizer.py b/spaces/User1342/WatchTower/Pinpoint/Sanitizer.py deleted file mode 100644 index f025934fb42a20c8fcfb9d640f9077264c7f8190..0000000000000000000000000000000000000000 --- a/spaces/User1342/WatchTower/Pinpoint/Sanitizer.py +++ /dev/null @@ -1,131 +0,0 @@ -import os.path - -from nltk import * -from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS - -from Pinpoint.Logger import * - -# If NLTK data doesn't exist, downloads it -try: - tagged = pos_tag(["test"]) -except LookupError: - download() - - -# nltk.download() #todo how to get this to run once? - -class sanitization(): - """ - This class is used to sanitize a given corpus of data. In turn removing stop words, stemming words, removing small - words, removing no alphabet words, and setting words to lower case. To save on repeat runs a local copy of the - serialised corpus is saved that is used unless this feature is overwritten. - """ - - def sanitize(self, text, output_folder, force_new_data_and_dont_persisit=False): - """ - Entry function for sanitizing text - :param text: - :param force_new_data_and_dont_persisit: - :return: sanitized text - """ - sanitize_file_name = os.path.join(output_folder, "{}-sanitized_text.txt".format(uuid.uuid4())) - final_text = "" - - # If a file exists don't sanitize given text - if os.path.isfile(sanitize_file_name) and not force_new_data_and_dont_persisit: - logger.print_message("Sanitized file exists. Using data") - - with open(sanitize_file_name, 'r', encoding="utf8") as file_to_write: - final_text = file_to_write.read() - - else: - total_words = len(text.split(" ")) - number = 0 - logger.print_message("Starting sanitization... {} words to go".format(total_words)) - for word in text.split(" "): - number = number + 1 - word = self.remove_non_alpha(word) - word = self.lower(word) - word = self.stemmer(word) - word = self.remove_stop_words(word) - word = self.remove_small_words(word) - - if word is None: - continue - - final_text = final_text + word + " " - logger.print_message("Completed {} of {} sanitized words".format(number, total_words)) - - final_text = final_text.replace(" ", " ") - - if not force_new_data_and_dont_persisit: - with open(sanitize_file_name, 'w', encoding="utf8") as file_to_write: - file_to_write.write(final_text) - - final_text = final_text.strip() - return final_text - - def stemmer(self, word): - """ - Get stemms of words - :param word: - :return: the stemmed word using port stemmer - """ - - porter = PorterStemmer() - - # todo anouther stemmer be assessed? - # lancaster = LancasterStemmer() - # stemmed_word = lancaster.stem(word) - stemmed_word = porter.stem(word) - - return stemmed_word - - def lower(self, word): - """ - get the lower case representation of words - :param word: - :return: the lowercase representation of the word - """ - return word.lower() - - def remove_stop_words(self, text): - """ - Remove stop words - :param text: - :return: the word without stop words - """ - - text_without_stopwords = [word for word in text.split() if word not in ENGLISH_STOP_WORDS] - - final_string = "" - - for word in text_without_stopwords: - final_string = final_string + word + " " - - return final_string - - def remove_non_alpha(self, word): - """ - Removes non alphabet characters (Excluding spaces) - :param word: - :return: the word with non-alpha characters removed - """ - word = word.replace("\n", " ").replace("\t", " ").replace(" ", " ") - regex = re.compile('[^a-zA-Z ]') - - return regex.sub('', word) - - def remove_small_words(self, word, length_to_remove_if_not_equal=4): - """ - Removes words that are too small, defaults to words words length 3 characters or below which are removed. - :param word: - :param length_to_remove_if_not_equal: - :return: "" if word below 3 characters or the word if above - """ - - new_word = "" - if len(word) >= length_to_remove_if_not_equal: - new_word = word - - return new_word diff --git a/spaces/VinayDBhagat/GenerateCustomerInsights/README.md b/spaces/VinayDBhagat/GenerateCustomerInsights/README.md deleted file mode 100644 index b50081365d75e2a4f8ef55a6815a1730e1881da0..0000000000000000000000000000000000000000 --- a/spaces/VinayDBhagat/GenerateCustomerInsights/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: GenerateCustomerInsights -emoji: 💻 -colorFrom: purple -colorTo: indigo -sdk: streamlit -sdk_version: 1.19.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/Violetmae14/images-to-audio/index.html b/spaces/Violetmae14/images-to-audio/index.html deleted file mode 100644 index 58275de3b1c343a98420342baa076b9baaafa157..0000000000000000000000000000000000000000 --- a/spaces/Violetmae14/images-to-audio/index.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - My static Space - - - -
-

Welcome to your static Space!

-

You can modify this app directly by editing index.html in the Files and versions tab.

-

- Also don't forget to check the - Spaces documentation. -

-
- - diff --git a/spaces/VoiceHero69/changer/setup_tools/__init__.py b/spaces/VoiceHero69/changer/setup_tools/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/Wrathless/Dkrotzer-MusicalMagic/tests/__init__.py b/spaces/Wrathless/Dkrotzer-MusicalMagic/tests/__init__.py deleted file mode 100644 index 0952fcc3f57e34b3747962e9ebd6fc57aeea63fa..0000000000000000000000000000000000000000 --- a/spaces/Wrathless/Dkrotzer-MusicalMagic/tests/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. diff --git a/spaces/YONG627/456123/yolov5-code-main/utils/loggers/wandb/__init__.py b/spaces/YONG627/456123/yolov5-code-main/utils/loggers/wandb/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/Yiqin/ChatVID/model/vision/grit_src/grit/modeling/backbone/utils.py b/spaces/Yiqin/ChatVID/model/vision/grit_src/grit/modeling/backbone/utils.py deleted file mode 100644 index e71db21f1223c87cceeb422a70888f7bac42bb18..0000000000000000000000000000000000000000 --- a/spaces/Yiqin/ChatVID/model/vision/grit_src/grit/modeling/backbone/utils.py +++ /dev/null @@ -1,186 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved -# This code is from https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/utils.py -import math -import torch -import torch.nn as nn -import torch.nn.functional as F - -__all__ = [ - "window_partition", - "window_unpartition", - "add_decomposed_rel_pos", - "get_abs_pos", - "PatchEmbed", -] - -def window_partition(x, window_size): - """ - Partition into non-overlapping windows with padding if needed. - Args: - x (tensor): input tokens with [B, H, W, C]. - window_size (int): window size. - - Returns: - windows: windows after partition with [B * num_windows, window_size, window_size, C]. - (Hp, Wp): padded height and width before partition - """ - B, H, W, C = x.shape - - pad_h = (window_size - H % window_size) % window_size - pad_w = (window_size - W % window_size) % window_size - if pad_h > 0 or pad_w > 0: - x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h)) - Hp, Wp = H + pad_h, W + pad_w - - x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C) - windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) - return windows, (Hp, Wp) - - -def window_unpartition(windows, window_size, pad_hw, hw): - """ - Window unpartition into original sequences and removing padding. - Args: - x (tensor): input tokens with [B * num_windows, window_size, window_size, C]. - window_size (int): window size. - pad_hw (Tuple): padded height and width (Hp, Wp). - hw (Tuple): original height and width (H, W) before padding. - - Returns: - x: unpartitioned sequences with [B, H, W, C]. - """ - Hp, Wp = pad_hw - H, W = hw - B = windows.shape[0] // (Hp * Wp // window_size // window_size) - x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1) - x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1) - - if Hp > H or Wp > W: - x = x[:, :H, :W, :].contiguous() - return x - - -def get_rel_pos(q_size, k_size, rel_pos): - """ - Get relative positional embeddings according to the relative positions of - query and key sizes. - Args: - q_size (int): size of query q. - k_size (int): size of key k. - rel_pos (Tensor): relative position embeddings (L, C). - - Returns: - Extracted positional embeddings according to relative positions. - """ - max_rel_dist = int(2 * max(q_size, k_size) - 1) - # Interpolate rel pos if needed. - if rel_pos.shape[0] != max_rel_dist: - # Interpolate rel pos. - rel_pos_resized = F.interpolate( - rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), - size=max_rel_dist, - mode="linear", - ) - rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0) - else: - rel_pos_resized = rel_pos - - # Scale the coords with short length if shapes for q and k are different. - q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0) - k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0) - relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0) - - return rel_pos_resized[relative_coords.long()] - - -def add_decomposed_rel_pos(attn, q, rel_pos_h, rel_pos_w, q_size, k_size): - """ - Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. - https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950 - Args: - attn (Tensor): attention map. - q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C). - rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis. - rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis. - q_size (Tuple): spatial sequence size of query q with (q_h, q_w). - k_size (Tuple): spatial sequence size of key k with (k_h, k_w). - - Returns: - attn (Tensor): attention map with added relative positional embeddings. - """ - q_h, q_w = q_size - k_h, k_w = k_size - Rh = get_rel_pos(q_h, k_h, rel_pos_h) - Rw = get_rel_pos(q_w, k_w, rel_pos_w) - - B, _, dim = q.shape - r_q = q.reshape(B, q_h, q_w, dim) - rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh) - rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw) - - attn = ( - attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :] - ).view(B, q_h * q_w, k_h * k_w) - - return attn - - -def get_abs_pos(abs_pos, has_cls_token, hw): - """ - Calculate absolute positional embeddings. If needed, resize embeddings and remove cls_token - dimension for the original embeddings. - Args: - abs_pos (Tensor): absolute positional embeddings with (1, num_position, C). - has_cls_token (bool): If true, has 1 embedding in abs_pos for cls token. - hw (Tuple): size of input image tokens. - - Returns: - Absolute positional embeddings after processing with shape (1, H, W, C) - """ - h, w = hw - if has_cls_token: - abs_pos = abs_pos[:, 1:] - xy_num = abs_pos.shape[1] - size = int(math.sqrt(xy_num)) - assert size * size == xy_num - - if size != h or size != w: - new_abs_pos = F.interpolate( - abs_pos.reshape(1, size, size, -1).permute(0, 3, 1, 2), - size=(h, w), - mode="bicubic", - align_corners=False, - ) - - return new_abs_pos.permute(0, 2, 3, 1) - else: - return abs_pos.reshape(1, h, w, -1) - - -class PatchEmbed(nn.Module): - """ - Image to Patch Embedding. - """ - - def __init__( - self, kernel_size=(16, 16), stride=(16, 16), padding=(0, 0), in_chans=3, embed_dim=768 - ): - """ - Args: - kernel_size (Tuple): kernel size of the projection layer. - stride (Tuple): stride of the projection layer. - padding (Tuple): padding size of the projection layer. - in_chans (int): Number of input image channels. - embed_dim (int): embed_dim (int): Patch embedding dimension. - """ - super().__init__() - - self.proj = nn.Conv2d( - in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding - ) - - def forward(self, x): - x = self.proj(x) - # B C H W -> B H W C - x = x.permute(0, 2, 3, 1) - return x diff --git a/spaces/Yudha515/Rvc-Models/audiocraft/modules/activations.py b/spaces/Yudha515/Rvc-Models/audiocraft/modules/activations.py deleted file mode 100644 index 8bd6f2917a56d72db56555d0ff54b2311bc21778..0000000000000000000000000000000000000000 --- a/spaces/Yudha515/Rvc-Models/audiocraft/modules/activations.py +++ /dev/null @@ -1,96 +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 -import torch.nn as nn -from torch import Tensor -from typing import Union, Callable - - -class CustomGLU(nn.Module): - """Custom Gated Linear Unit activation. - Applies a modified gated linear unit :math:`a * f(b)` where :math:`a` is the first half - of the input matrices, :math:`b` is the second half, and :math:`f` is a provided activation - function (i.e. sigmoid, swish, etc.). - - Args: - activation (nn.Module): The custom activation to apply in the Gated Linear Unit - dim (int): the dimension on which to split the input. Default: -1 - - Shape: - - Input: :math:`(\ast_1, N, \ast_2)` where `*` means, any number of additional - dimensions - - Output: :math:`(\ast_1, M, \ast_2)` where :math:`M=N/2` - - Examples:: - >>> m = CustomGLU(nn.Sigmoid()) - >>> input = torch.randn(4, 2) - >>> output = m(input) - """ - def __init__(self, activation: nn.Module, dim: int = -1): - super(CustomGLU, self).__init__() - self.dim = dim - self.activation = activation - - def forward(self, x: Tensor): - assert x.shape[self.dim] % 2 == 0 # M = N / 2 - a, b = torch.chunk(x, 2, dim=self.dim) - return a * self.activation(b) - - -class SwiGLU(CustomGLU): - """SiLU Gated Linear Unit activation. - Applies SiLU Gated Linear Unit :math:`a * SiLU(b)` where :math:`a` is - the first half of the input matrices, :math:`b` is the second half. - - Args: - dim (int): the dimension on which to split the input. Default: -1 - """ - def __init__(self, dim: int = -1): - super(SwiGLU, self).__init__(nn.SiLU(), dim) - - -class GeGLU(CustomGLU): - """GeLU Gated Linear Unit activation. - Applies GeLU Gated Linear Unit :math:`a * GELU(b)` where :math:`a` is - the first half of the input matrices, :math:`b` is the second half. - - Args: - dim (int): the dimension on which to split the input. Default: -1 - """ - def __init__(self, dim: int = -1): - super(GeGLU, self).__init__(nn.GELU(), dim) - - -class ReGLU(CustomGLU): - """ReLU Gated Linear Unit activation. - Applies ReLU Gated Linear Unit :math:`a * ReLU(b)` where :math:`a` is - the first half of the input matrices, :math:`b` is the second half. - - Args: - dim (int): the dimension on which to split the input. Default: -1 - """ - def __init__(self, dim: int = -1): - super(ReGLU, self).__init__(nn.ReLU(), dim) - - -def get_activation_fn( - activation: Union[str, Callable[[Tensor], Tensor]] -) -> Union[str, Callable[[Tensor], Tensor]]: - """Helper function to map an activation string to the activation class. - If the supplied activation is not a string that is recognized, the activation is passed back. - - Args: - activation (Union[str, Callable[[Tensor], Tensor]]): Activation to check - """ - if isinstance(activation, str): - if activation == "reglu": - return ReGLU() - elif activation == "geglu": - return GeGLU() - elif activation == "swiglu": - return SwiGLU() - return activation diff --git a/spaces/Ziqi/ReVersion/style.css b/spaces/Ziqi/ReVersion/style.css deleted file mode 100644 index af4e23927a03e13fd16ebc7b4eb6eb434c42f65b..0000000000000000000000000000000000000000 --- a/spaces/Ziqi/ReVersion/style.css +++ /dev/null @@ -1,3 +0,0 @@ -h1 { - text-align: center; -} \ No newline at end of file diff --git a/spaces/Zwicky18/vits-models/transforms.py b/spaces/Zwicky18/vits-models/transforms.py deleted file mode 100644 index 4793d67ca5a5630e0ffe0f9fb29445c949e64dae..0000000000000000000000000000000000000000 --- a/spaces/Zwicky18/vits-models/transforms.py +++ /dev/null @@ -1,193 +0,0 @@ -import torch -from torch.nn import functional as F - -import numpy as np - - -DEFAULT_MIN_BIN_WIDTH = 1e-3 -DEFAULT_MIN_BIN_HEIGHT = 1e-3 -DEFAULT_MIN_DERIVATIVE = 1e-3 - - -def piecewise_rational_quadratic_transform(inputs, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=False, - tails=None, - tail_bound=1., - min_bin_width=DEFAULT_MIN_BIN_WIDTH, - min_bin_height=DEFAULT_MIN_BIN_HEIGHT, - min_derivative=DEFAULT_MIN_DERIVATIVE): - - if tails is None: - spline_fn = rational_quadratic_spline - spline_kwargs = {} - else: - spline_fn = unconstrained_rational_quadratic_spline - spline_kwargs = { - 'tails': tails, - 'tail_bound': tail_bound - } - - outputs, logabsdet = spline_fn( - inputs=inputs, - unnormalized_widths=unnormalized_widths, - unnormalized_heights=unnormalized_heights, - unnormalized_derivatives=unnormalized_derivatives, - inverse=inverse, - min_bin_width=min_bin_width, - min_bin_height=min_bin_height, - min_derivative=min_derivative, - **spline_kwargs - ) - return outputs, logabsdet - - -def searchsorted(bin_locations, inputs, eps=1e-6): - bin_locations[..., -1] += eps - return torch.sum( - inputs[..., None] >= bin_locations, - dim=-1 - ) - 1 - - -def unconstrained_rational_quadratic_spline(inputs, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=False, - tails='linear', - tail_bound=1., - min_bin_width=DEFAULT_MIN_BIN_WIDTH, - min_bin_height=DEFAULT_MIN_BIN_HEIGHT, - min_derivative=DEFAULT_MIN_DERIVATIVE): - inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound) - outside_interval_mask = ~inside_interval_mask - - outputs = torch.zeros_like(inputs) - logabsdet = torch.zeros_like(inputs) - - if tails == 'linear': - unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1)) - constant = np.log(np.exp(1 - min_derivative) - 1) - unnormalized_derivatives[..., 0] = constant - unnormalized_derivatives[..., -1] = constant - - outputs[outside_interval_mask] = inputs[outside_interval_mask] - logabsdet[outside_interval_mask] = 0 - else: - raise RuntimeError('{} tails are not implemented.'.format(tails)) - - outputs[inside_interval_mask], logabsdet[inside_interval_mask] = rational_quadratic_spline( - inputs=inputs[inside_interval_mask], - unnormalized_widths=unnormalized_widths[inside_interval_mask, :], - unnormalized_heights=unnormalized_heights[inside_interval_mask, :], - unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :], - inverse=inverse, - left=-tail_bound, right=tail_bound, bottom=-tail_bound, top=tail_bound, - min_bin_width=min_bin_width, - min_bin_height=min_bin_height, - min_derivative=min_derivative - ) - - return outputs, logabsdet - -def rational_quadratic_spline(inputs, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=False, - left=0., right=1., bottom=0., top=1., - min_bin_width=DEFAULT_MIN_BIN_WIDTH, - min_bin_height=DEFAULT_MIN_BIN_HEIGHT, - min_derivative=DEFAULT_MIN_DERIVATIVE): - if torch.min(inputs) < left or torch.max(inputs) > right: - raise ValueError('Input to a transform is not within its domain') - - num_bins = unnormalized_widths.shape[-1] - - if min_bin_width * num_bins > 1.0: - raise ValueError('Minimal bin width too large for the number of bins') - if min_bin_height * num_bins > 1.0: - raise ValueError('Minimal bin height too large for the number of bins') - - widths = F.softmax(unnormalized_widths, dim=-1) - widths = min_bin_width + (1 - min_bin_width * num_bins) * widths - cumwidths = torch.cumsum(widths, dim=-1) - cumwidths = F.pad(cumwidths, pad=(1, 0), mode='constant', value=0.0) - cumwidths = (right - left) * cumwidths + left - cumwidths[..., 0] = left - cumwidths[..., -1] = right - widths = cumwidths[..., 1:] - cumwidths[..., :-1] - - derivatives = min_derivative + F.softplus(unnormalized_derivatives) - - heights = F.softmax(unnormalized_heights, dim=-1) - heights = min_bin_height + (1 - min_bin_height * num_bins) * heights - cumheights = torch.cumsum(heights, dim=-1) - cumheights = F.pad(cumheights, pad=(1, 0), mode='constant', value=0.0) - cumheights = (top - bottom) * cumheights + bottom - cumheights[..., 0] = bottom - cumheights[..., -1] = top - heights = cumheights[..., 1:] - cumheights[..., :-1] - - if inverse: - bin_idx = searchsorted(cumheights, inputs)[..., None] - else: - bin_idx = searchsorted(cumwidths, inputs)[..., None] - - input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0] - input_bin_widths = widths.gather(-1, bin_idx)[..., 0] - - input_cumheights = cumheights.gather(-1, bin_idx)[..., 0] - delta = heights / widths - input_delta = delta.gather(-1, bin_idx)[..., 0] - - input_derivatives = derivatives.gather(-1, bin_idx)[..., 0] - input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0] - - input_heights = heights.gather(-1, bin_idx)[..., 0] - - if inverse: - a = (((inputs - input_cumheights) * (input_derivatives - + input_derivatives_plus_one - - 2 * input_delta) - + input_heights * (input_delta - input_derivatives))) - b = (input_heights * input_derivatives - - (inputs - input_cumheights) * (input_derivatives - + input_derivatives_plus_one - - 2 * input_delta)) - c = - input_delta * (inputs - input_cumheights) - - discriminant = b.pow(2) - 4 * a * c - assert (discriminant >= 0).all() - - root = (2 * c) / (-b - torch.sqrt(discriminant)) - outputs = root * input_bin_widths + input_cumwidths - - theta_one_minus_theta = root * (1 - root) - denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta) - * theta_one_minus_theta) - derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * root.pow(2) - + 2 * input_delta * theta_one_minus_theta - + input_derivatives * (1 - root).pow(2)) - logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator) - - return outputs, -logabsdet - else: - theta = (inputs - input_cumwidths) / input_bin_widths - theta_one_minus_theta = theta * (1 - theta) - - numerator = input_heights * (input_delta * theta.pow(2) - + input_derivatives * theta_one_minus_theta) - denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta) - * theta_one_minus_theta) - outputs = input_cumheights + numerator / denominator - - derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * theta.pow(2) - + 2 * input_delta * theta_one_minus_theta - + input_derivatives * (1 - theta).pow(2)) - logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator) - - return outputs, logabsdet diff --git a/spaces/aadnk/faster-whisper-webui/src/hooks/subTaskProgressListener.py b/spaces/aadnk/faster-whisper-webui/src/hooks/subTaskProgressListener.py deleted file mode 100644 index 9a8eaa876fcd18032875d67535e0558494842c60..0000000000000000000000000000000000000000 --- a/spaces/aadnk/faster-whisper-webui/src/hooks/subTaskProgressListener.py +++ /dev/null @@ -1,37 +0,0 @@ -from src.hooks.progressListener import ProgressListener - -from typing import Union - -class SubTaskProgressListener(ProgressListener): - """ - A sub task listener that reports the progress of a sub task to a base task listener - Parameters - ---------- - base_task_listener : ProgressListener - The base progress listener to accumulate overall progress in. - base_task_total : float - The maximum total progress that will be reported to the base progress listener. - sub_task_start : float - The starting progress of a sub task, in respect to the base progress listener. - sub_task_total : float - The total amount of progress a sub task will report to the base progress listener. - """ - def __init__( - self, - base_task_listener: ProgressListener, - base_task_total: float, - sub_task_start: float, - sub_task_total: float, - ): - self.base_task_listener = base_task_listener - self.base_task_total = base_task_total - self.sub_task_start = sub_task_start - self.sub_task_total = sub_task_total - - def on_progress(self, current: Union[int, float], total: Union[int, float]): - sub_task_progress_frac = current / total - sub_task_progress = self.sub_task_start + self.sub_task_total * sub_task_progress_frac - self.base_task_listener.on_progress(sub_task_progress, self.base_task_total) - - def on_finished(self): - self.base_task_listener.on_progress(self.sub_task_start + self.sub_task_total, self.base_task_total) \ No newline at end of file diff --git a/spaces/aaronb/Anything2Image/README.md b/spaces/aaronb/Anything2Image/README.md deleted file mode 100644 index f4c1e88e38f9653d29e6dd512a751a09111eff80..0000000000000000000000000000000000000000 --- a/spaces/aaronb/Anything2Image/README.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: Anything2Image -emoji: 🏃 -colorFrom: gray -colorTo: blue -sdk: gradio -sdk_version: 3.29.0 -app_file: app.py -pinned: false ---- - -# Anything To Image - -Generate image from anything with [ImageBind](https://github.com/facebookresearch/ImageBind)'s unified latent space and [stable-diffusion-2-1-unclip](https://huggingface.co/stabilityai/stable-diffusion-2-1-unclip). - -- No training is need. -- Integration with 🤗 [Diffusers](https://github.com/huggingface/diffusers). -- `imagebind` is directly copy from [official repo](https://github.com/facebookresearch/ImageBind) with modification. -- Gradio Demo. - -## Audio to Image - -| `assets/wav/bird_audio.wav` | `assets/wav/dog_audio.wav` | `assets/wav/cattle.wav` -| --- | --- | --- | -| ![](assets/generated/bird_audio.png) | ![](assets/generated/dog_audio.png) |![](assets/generated/cattle.png) | - -```python -import imagebind -import torch -from diffusers import StableUnCLIPImg2ImgPipeline - -# construct models -device = "cuda:0" if torch.cuda.is_available() else "cpu" -pipe = StableUnCLIPImg2ImgPipeline.from_pretrained( - "stabilityai/stable-diffusion-2-1-unclip", torch_dtype=torch.float16, variation="fp16" -) -pipe = pipe.to(device) - -model = imagebind.imagebind_huge(pretrained=True) -model.eval() -model.to(device) - -# generate image -with torch.no_grad(): - audio_paths=["assets/wav/bird_audio.wav"] - embeddings = model.forward({ - imagebind.ModalityType.AUDIO: imagebind.load_and_transform_audio_data(audio_paths, device), - }) - embeddings = embeddings[imagebind.ModalityType.AUDIO] - images = pipe(image_embeds=embeddings.half()).images - images[0].save("bird_audio.png") -``` - -## More - -Under construction - - -## Citation - -Latent Diffusion - -```bibtex -@InProceedings{Rombach_2022_CVPR, - author = {Rombach, Robin and Blattmann, Andreas and Lorenz, Dominik and Esser, Patrick and Ommer, Bj\"orn}, - title = {High-Resolution Image Synthesis With Latent Diffusion Models}, - booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, - month = {June}, - year = {2022}, - pages = {10684-10695} -} -``` - -ImageBind -```bibtex -@inproceedings{girdhar2023imagebind, - title={ImageBind: One Embedding Space To Bind Them All}, - author={Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang -and Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan}, - booktitle={CVPR}, - year={2023} -} -``` \ No newline at end of file diff --git a/spaces/aarontanzb/Langchain_query_app/README.md b/spaces/aarontanzb/Langchain_query_app/README.md deleted file mode 100644 index 7c1459a6ba21ffee2031c3a3c19413c11139a61c..0000000000000000000000000000000000000000 --- a/spaces/aarontanzb/Langchain_query_app/README.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Langchain Query App -emoji: 😻 -colorFrom: gray -colorTo: pink -sdk: docker -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmcv/runner/hooks/memory.py b/spaces/abhishek/sketch-to-image/annotator/uniformer/mmcv/runner/hooks/memory.py deleted file mode 100644 index 70cf9a838fb314e3bd3c07aadbc00921a81e83ed..0000000000000000000000000000000000000000 --- a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmcv/runner/hooks/memory.py +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import torch - -from .hook import HOOKS, Hook - - -@HOOKS.register_module() -class EmptyCacheHook(Hook): - - def __init__(self, before_epoch=False, after_epoch=True, after_iter=False): - self._before_epoch = before_epoch - self._after_epoch = after_epoch - self._after_iter = after_iter - - def after_iter(self, runner): - if self._after_iter: - torch.cuda.empty_cache() - - def before_epoch(self, runner): - if self._before_epoch: - torch.cuda.empty_cache() - - def after_epoch(self, runner): - if self._after_epoch: - torch.cuda.empty_cache() diff --git a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet_null/core/bbox/match_costs/builder.py b/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet_null/core/bbox/match_costs/builder.py deleted file mode 100644 index 92f0869ed4993167c504175d14315f7e9e8411f1..0000000000000000000000000000000000000000 --- a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet_null/core/bbox/match_costs/builder.py +++ /dev/null @@ -1,8 +0,0 @@ -from annotator.uniformer.mmcv.utils import Registry, build_from_cfg - -MATCH_COST = Registry('Match Cost') - - -def build_match_cost(cfg, default_args=None): - """Builder of IoU calculator.""" - return build_from_cfg(cfg, MATCH_COST, default_args) diff --git a/spaces/abidlabs/cinemascope/app.py b/spaces/abidlabs/cinemascope/app.py deleted file mode 100644 index 5a671a58c75488031a715dab61df366131636353..0000000000000000000000000000000000000000 --- a/spaces/abidlabs/cinemascope/app.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/env python - -from __future__ import annotations - -import os -import random -import tempfile - -import gradio as gr -import imageio -import numpy as np -import torch -from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler - -DESCRIPTION = '# [ModelScope Text to Video Synthesis](https://modelscope.cn/models/damo/text-to-video-synthesis/summary)' -DESCRIPTION += '\n

For Colab usage, you can view this webpage.(the latest update on 2023.03.21)

' -DESCRIPTION += '\n

This model can only be used for non-commercial purposes. To learn more about the model, take a look at the model card.

' -if (SPACE_ID := os.getenv('SPACE_ID')) is not None: - DESCRIPTION += f'\n

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

' - -MAX_NUM_FRAMES = int(os.getenv('MAX_NUM_FRAMES', '200')) -DEFAULT_NUM_FRAMES = min(MAX_NUM_FRAMES, - int(os.getenv('DEFAULT_NUM_FRAMES', '16'))) - -pipe = DiffusionPipeline.from_pretrained('damo-vilab/text-to-video-ms-1.7b', - torch_dtype=torch.float16, - variant='fp16') -pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) -pipe.enable_model_cpu_offload() -pipe.enable_vae_slicing() - - -def to_video(frames: list[np.ndarray], fps: int) -> str: - out_file = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) - writer = imageio.get_writer(out_file.name, format='FFMPEG', fps=fps) - for frame in frames: - writer.append_data(frame) - writer.close() - return out_file.name - - -def generate(prompt: str) -> str: - seed = int(0) - num_frames = int(16) - num_inference_steps = int(25) - if seed == -1: - seed = random.randint(0, 1000000) - generator = torch.Generator().manual_seed(seed) - frames = pipe(prompt, - num_inference_steps=num_inference_steps, - num_frames=num_frames, - generator=generator).frames - return to_video(frames, 8) - - - -with gr.Blocks(css='style.css') as demo: - gr.Markdown(DESCRIPTION) - with gr.Group(): - with gr.Box(): - with gr.Row(elem_id='prompt-container').style(equal_height=True): - prompt = gr.Text( - label='Prompt', - show_label=False, - max_lines=1, - placeholder='Enter your prompt', - elem_id='prompt-text-input').style(container=False) - run_button = gr.Button('Generate video').style( - full_width=False) - result = gr.Video(label='Result', show_label=False, elem_id='gallery') - with gr.Accordion('Advanced options', open=False): - seed = gr.Slider( - label='Seed', - minimum=-1, - maximum=1000000, - step=1, - value=-1, - info='If set to -1, a different seed will be used each time.') - num_frames = gr.Slider( - label='Number of frames', - minimum=16, - maximum=MAX_NUM_FRAMES, - step=1, - value=16, - info= - 'Note that the content of the video also changes when you change the number of frames.' - ) - num_inference_steps = gr.Slider(label='Number of inference steps', - minimum=10, - maximum=50, - step=1, - value=25) - - inputs = [ - prompt, - ] - prompt.submit(fn=generate, inputs=inputs, outputs=result, api_name="predict") - run_button.click(fn=generate, inputs=inputs, outputs=result) - - - with gr.Accordion(label='Biases and content acknowledgment', open=False): - gr.HTML("""
-

Biases and content acknowledgment

-

- Despite how impressive being able to turn text into video is, beware to the fact that this model may output content that reinforces or exacerbates societal biases. The training data includes LAION5B, ImageNet, Webvid and other public datasets. The model was not trained to realistically represent people or events, so using it to generate such content is beyond the model's capabilities. -

-

- It is not intended to generate content that is demeaning or harmful to people or their environment, culture, religion, etc. Similarly, it is not allowed to generate pornographic, violent and bloody content generation. The model is meant for research purposes. -

-

- To learn more about the model, head to its model card. -

-
- """) - -demo.queue(max_size=15).launch() diff --git a/spaces/abrar-lohia/text-2-character-anim/pyrender/.eggs/pyglet-2.0.5-py3.10.egg/pyglet/libs/win32/constants.py b/spaces/abrar-lohia/text-2-character-anim/pyrender/.eggs/pyglet-2.0.5-py3.10.egg/pyglet/libs/win32/constants.py deleted file mode 100644 index 5525dc766ae2cc4436ca4eeb49031c9c70123824..0000000000000000000000000000000000000000 --- a/spaces/abrar-lohia/text-2-character-anim/pyrender/.eggs/pyglet-2.0.5-py3.10.egg/pyglet/libs/win32/constants.py +++ /dev/null @@ -1,5080 +0,0 @@ -import sys - -# Most of this file is win32con.py from Python for Windows Extensions: -# http://www.python.net/crew/mhammond/win32/ - -# From Windows 2000 API SuperBible: - -VK_OEM_1 = 0xba -VK_OEM_PLUS = 0xbb -VK_OEM_COMMA = 0xbc -VK_OEM_MINUS = 0xbd -VK_OEM_PERIOD = 0xbe -VK_OEM_2 = 0xbf -VK_OEM_3 = 0xc0 -VK_OEM_4 = 0xdb -VK_OEM_5 = 0xdc -VK_OEM_6 = 0xdd -VK_OEM_7 = 0xde -VK_OEM_8 = 0xdf -VK_OEM_102 = 0xe2 - -# Copyright (c) 1994-2001, Mark Hammond -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in -# the documentation and/or other materials provided with the distribution. -# -# Neither name of Mark Hammond nor the name of contributors may be used -# to endorse or promote products derived from this software without -# specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS -# IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. P - -# From WinGDI.h -PFD_TYPE_RGBA = 0 -PFD_TYPE_COLORINDEX = 1 -PFD_MAIN_PLANE = 0 -PFD_OVERLAY_PLANE = 1 -PFD_UNDERLAY_PLANE = (-1) -PFD_DOUBLEBUFFER = 0x00000001 -PFD_STEREO = 0x00000002 -PFD_DRAW_TO_WINDOW = 0x00000004 -PFD_DRAW_TO_BITMAP = 0x00000008 -PFD_SUPPORT_GDI = 0x00000010 -PFD_SUPPORT_OPENGL = 0x00000020 -PFD_GENERIC_FORMAT = 0x00000040 -PFD_NEED_PALETTE = 0x00000080 -PFD_NEED_SYSTEM_PALETTE = 0x00000100 -PFD_SWAP_EXCHANGE = 0x00000200 -PFD_SWAP_COPY = 0x00000400 -PFD_SWAP_LAYER_BUFFERS = 0x00000800 -PFD_GENERIC_ACCELERATED = 0x00001000 -PFD_SUPPORT_DIRECTDRAW = 0x00002000 -PFD_DEPTH_DONTCARE = 0x20000000 -PFD_DOUBLEBUFFER_DONTCARE = 0x40000000 -PFD_STEREO_DONTCARE = 0x80000000 - -# Generated by h2py from commdlg.h (plus modifications 4jan98) -WINVER = 1280 -WM_USER = 1024 -PY_0U = 0 -OFN_READONLY = 1 -OFN_OVERWRITEPROMPT = 2 -OFN_HIDEREADONLY = 4 -OFN_NOCHANGEDIR = 8 -OFN_SHOWHELP = 16 -OFN_ENABLEHOOK = 32 -OFN_ENABLETEMPLATE = 64 -OFN_ENABLETEMPLATEHANDLE = 128 -OFN_NOVALIDATE = 256 -OFN_ALLOWMULTISELECT = 512 -OFN_EXTENSIONDIFFERENT = 1024 -OFN_PATHMUSTEXIST = 2048 -OFN_FILEMUSTEXIST = 4096 -OFN_CREATEPROMPT = 8192 -OFN_SHAREAWARE = 16384 -OFN_NOREADONLYRETURN = 32768 -OFN_NOTESTFILECREATE = 65536 -OFN_NONETWORKBUTTON = 131072 -OFN_NOLONGNAMES = 262144 -OFN_EXPLORER = 524288 # new look commdlg -OFN_NODEREFERENCELINKS = 1048576 -OFN_LONGNAMES = 2097152 # force long names for 3.x modules -OFN_ENABLEINCLUDENOTIFY = 4194304 # send include message to callback -OFN_ENABLESIZING = 8388608 -OFN_DONTADDTORECENT = 33554432 -OFN_FORCESHOWHIDDEN = 268435456 # Show All files including System and hidden files -OFN_EX_NOPLACESBAR = 1 -OFN_SHAREFALLTHROUGH = 2 -OFN_SHARENOWARN = 1 -OFN_SHAREWARN = 0 -CDN_FIRST = (PY_0U-601) -CDN_LAST = (PY_0U-699) -CDN_INITDONE = (CDN_FIRST - 0) -CDN_SELCHANGE = (CDN_FIRST - 1) -CDN_FOLDERCHANGE = (CDN_FIRST - 2) -CDN_SHAREVIOLATION = (CDN_FIRST - 3) -CDN_HELP = (CDN_FIRST - 4) -CDN_FILEOK = (CDN_FIRST - 5) -CDN_TYPECHANGE = (CDN_FIRST - 6) -CDN_INCLUDEITEM = (CDN_FIRST - 7) -CDM_FIRST = (WM_USER + 100) -CDM_LAST = (WM_USER + 200) -CDM_GETSPEC = (CDM_FIRST + 0) -CDM_GETFILEPATH = (CDM_FIRST + 1) -CDM_GETFOLDERPATH = (CDM_FIRST + 2) -CDM_GETFOLDERIDLIST = (CDM_FIRST + 3) -CDM_SETCONTROLTEXT = (CDM_FIRST + 4) -CDM_HIDECONTROL = (CDM_FIRST + 5) -CDM_SETDEFEXT = (CDM_FIRST + 6) -CC_RGBINIT = 1 -CC_FULLOPEN = 2 -CC_PREVENTFULLOPEN = 4 -CC_SHOWHELP = 8 -CC_ENABLEHOOK = 16 -CC_ENABLETEMPLATE = 32 -CC_ENABLETEMPLATEHANDLE = 64 -CC_SOLIDCOLOR = 128 -CC_ANYCOLOR = 256 -FR_DOWN = 1 -FR_WHOLEWORD = 2 -FR_MATCHCASE = 4 -FR_FINDNEXT = 8 -FR_REPLACE = 16 -FR_REPLACEALL = 32 -FR_DIALOGTERM = 64 -FR_SHOWHELP = 128 -FR_ENABLEHOOK = 256 -FR_ENABLETEMPLATE = 512 -FR_NOUPDOWN = 1024 -FR_NOMATCHCASE = 2048 -FR_NOWHOLEWORD = 4096 -FR_ENABLETEMPLATEHANDLE = 8192 -FR_HIDEUPDOWN = 16384 -FR_HIDEMATCHCASE = 32768 -FR_HIDEWHOLEWORD = 65536 -CF_SCREENFONTS = 1 -CF_PRINTERFONTS = 2 -CF_BOTH = (CF_SCREENFONTS | CF_PRINTERFONTS) -CF_SHOWHELP = 4 -CF_ENABLEHOOK = 8 -CF_ENABLETEMPLATE = 16 -CF_ENABLETEMPLATEHANDLE = 32 -CF_INITTOLOGFONTSTRUCT = 64 -CF_USESTYLE = 128 -CF_EFFECTS = 256 -CF_APPLY = 512 -CF_ANSIONLY = 1024 -CF_SCRIPTSONLY = CF_ANSIONLY -CF_NOVECTORFONTS = 2048 -CF_NOOEMFONTS = CF_NOVECTORFONTS -CF_NOSIMULATIONS = 4096 -CF_LIMITSIZE = 8192 -CF_FIXEDPITCHONLY = 16384 -CF_WYSIWYG = 32768 # must also have CF_SCREENFONTS & CF_PRINTERFONTS -CF_FORCEFONTEXIST = 65536 -CF_SCALABLEONLY = 131072 -CF_TTONLY = 262144 -CF_NOFACESEL = 524288 -CF_NOSTYLESEL = 1048576 -CF_NOSIZESEL = 2097152 -CF_SELECTSCRIPT = 4194304 -CF_NOSCRIPTSEL = 8388608 -CF_NOVERTFONTS = 16777216 -SIMULATED_FONTTYPE = 32768 -PRINTER_FONTTYPE = 16384 -SCREEN_FONTTYPE = 8192 -BOLD_FONTTYPE = 256 -ITALIC_FONTTYPE = 512 -REGULAR_FONTTYPE = 1024 -OPENTYPE_FONTTYPE = 65536 -TYPE1_FONTTYPE = 131072 -DSIG_FONTTYPE = 262144 -WM_CHOOSEFONT_GETLOGFONT = (WM_USER + 1) -WM_CHOOSEFONT_SETLOGFONT = (WM_USER + 101) -WM_CHOOSEFONT_SETFLAGS = (WM_USER + 102) -LBSELCHSTRINGA = "commdlg_LBSelChangedNotify" -SHAREVISTRINGA = "commdlg_ShareViolation" -FILEOKSTRINGA = "commdlg_FileNameOK" -COLOROKSTRINGA = "commdlg_ColorOK" -SETRGBSTRINGA = "commdlg_SetRGBColor" -HELPMSGSTRINGA = "commdlg_help" -FINDMSGSTRINGA = "commdlg_FindReplace" -LBSELCHSTRING = LBSELCHSTRINGA -SHAREVISTRING = SHAREVISTRINGA -FILEOKSTRING = FILEOKSTRINGA -COLOROKSTRING = COLOROKSTRINGA -SETRGBSTRING = SETRGBSTRINGA -HELPMSGSTRING = HELPMSGSTRINGA -FINDMSGSTRING = FINDMSGSTRINGA -CD_LBSELNOITEMS = -1 -CD_LBSELCHANGE = 0 -CD_LBSELSUB = 1 -CD_LBSELADD = 2 -PD_ALLPAGES = 0 -PD_SELECTION = 1 -PD_PAGENUMS = 2 -PD_NOSELECTION = 4 -PD_NOPAGENUMS = 8 -PD_COLLATE = 16 -PD_PRINTTOFILE = 32 -PD_PRINTSETUP = 64 -PD_NOWARNING = 128 -PD_RETURNDC = 256 -PD_RETURNIC = 512 -PD_RETURNDEFAULT = 1024 -PD_SHOWHELP = 2048 -PD_ENABLEPRINTHOOK = 4096 -PD_ENABLESETUPHOOK = 8192 -PD_ENABLEPRINTTEMPLATE = 16384 -PD_ENABLESETUPTEMPLATE = 32768 -PD_ENABLEPRINTTEMPLATEHANDLE = 65536 -PD_ENABLESETUPTEMPLATEHANDLE = 131072 -PD_USEDEVMODECOPIES = 262144 -PD_DISABLEPRINTTOFILE = 524288 -PD_HIDEPRINTTOFILE = 1048576 -PD_NONETWORKBUTTON = 2097152 -DN_DEFAULTPRN = 1 -WM_PSD_PAGESETUPDLG = (WM_USER ) -WM_PSD_FULLPAGERECT = (WM_USER+1) -WM_PSD_MINMARGINRECT = (WM_USER+2) -WM_PSD_MARGINRECT = (WM_USER+3) -WM_PSD_GREEKTEXTRECT = (WM_USER+4) -WM_PSD_ENVSTAMPRECT = (WM_USER+5) -WM_PSD_YAFULLPAGERECT = (WM_USER+6) -PSD_DEFAULTMINMARGINS = 0 # default (printer's) -PSD_INWININIINTLMEASURE = 0 # 1st of 4 possible -PSD_MINMARGINS = 1 # use caller's -PSD_MARGINS = 2 # use caller's -PSD_INTHOUSANDTHSOFINCHES = 4 # 2nd of 4 possible -PSD_INHUNDREDTHSOFMILLIMETERS = 8 # 3rd of 4 possible -PSD_DISABLEMARGINS = 16 -PSD_DISABLEPRINTER = 32 -PSD_NOWARNING = 128 # must be same as PD_* -PSD_DISABLEORIENTATION = 256 -PSD_RETURNDEFAULT = 1024 # must be same as PD_* -PSD_DISABLEPAPER = 512 -PSD_SHOWHELP = 2048 # must be same as PD_* -PSD_ENABLEPAGESETUPHOOK = 8192 # must be same as PD_* -PSD_ENABLEPAGESETUPTEMPLATE = 32768 # must be same as PD_* -PSD_ENABLEPAGESETUPTEMPLATEHANDLE = 131072 # must be same as PD_* -PSD_ENABLEPAGEPAINTHOOK = 262144 -PSD_DISABLEPAGEPAINTING = 524288 -PSD_NONETWORKBUTTON = 2097152 # must be same as PD_* - -# Generated by h2py from winreg.h -HKEY_CLASSES_ROOT = -2147483648 -HKEY_CURRENT_USER = -2147483647 -HKEY_LOCAL_MACHINE = -2147483646 -HKEY_USERS = -2147483645 -HKEY_PERFORMANCE_DATA = -2147483644 -HKEY_CURRENT_CONFIG = -2147483643 -HKEY_DYN_DATA = -2147483642 -HKEY_PERFORMANCE_TEXT = -2147483568 # ?? 4Jan98 -HKEY_PERFORMANCE_NLSTEXT = -2147483552 # ?? 4Jan98 - -# Generated by h2py from winuser.h -HWND_BROADCAST = 65535 -HWND_DESKTOP = 0 -HWND_TOP = 0 -HWND_BOTTOM = 1 -HWND_TOPMOST = -1 -HWND_NOTOPMOST = -2 -HWND_MESSAGE = -3 - -# winuser.h line 4601 -SM_CXSCREEN = 0 -SM_CYSCREEN = 1 -SM_CXVSCROLL = 2 -SM_CYHSCROLL = 3 -SM_CYCAPTION = 4 -SM_CXBORDER = 5 -SM_CYBORDER = 6 -SM_CXDLGFRAME = 7 -SM_CYDLGFRAME = 8 -SM_CYVTHUMB = 9 -SM_CXHTHUMB = 10 -SM_CXICON = 11 -SM_CYICON = 12 -SM_CXCURSOR = 13 -SM_CYCURSOR = 14 -SM_CYMENU = 15 -SM_CXFULLSCREEN = 16 -SM_CYFULLSCREEN = 17 -SM_CYKANJIWINDOW = 18 -SM_MOUSEPRESENT = 19 -SM_CYVSCROLL = 20 -SM_CXHSCROLL = 21 -SM_DEBUG = 22 -SM_SWAPBUTTON = 23 -SM_RESERVED1 = 24 -SM_RESERVED2 = 25 -SM_RESERVED3 = 26 -SM_RESERVED4 = 27 -SM_CXMIN = 28 -SM_CYMIN = 29 -SM_CXSIZE = 30 -SM_CYSIZE = 31 -SM_CXFRAME = 32 -SM_CYFRAME = 33 -SM_CXMINTRACK = 34 -SM_CYMINTRACK = 35 -SM_CXDOUBLECLK = 36 -SM_CYDOUBLECLK = 37 -SM_CXICONSPACING = 38 -SM_CYICONSPACING = 39 -SM_MENUDROPALIGNMENT = 40 -SM_PENWINDOWS = 41 -SM_DBCSENABLED = 42 -SM_CMOUSEBUTTONS = 43 -SM_CXFIXEDFRAME = SM_CXDLGFRAME -SM_CYFIXEDFRAME = SM_CYDLGFRAME -SM_CXSIZEFRAME = SM_CXFRAME -SM_CYSIZEFRAME = SM_CYFRAME -SM_SECURE = 44 -SM_CXEDGE = 45 -SM_CYEDGE = 46 -SM_CXMINSPACING = 47 -SM_CYMINSPACING = 48 -SM_CXSMICON = 49 -SM_CYSMICON = 50 -SM_CYSMCAPTION = 51 -SM_CXSMSIZE = 52 -SM_CYSMSIZE = 53 -SM_CXMENUSIZE = 54 -SM_CYMENUSIZE = 55 -SM_ARRANGE = 56 -SM_CXMINIMIZED = 57 -SM_CYMINIMIZED = 58 -SM_CXMAXTRACK = 59 -SM_CYMAXTRACK = 60 -SM_CXMAXIMIZED = 61 -SM_CYMAXIMIZED = 62 -SM_NETWORK = 63 -SM_CLEANBOOT = 67 -SM_CXDRAG = 68 -SM_CYDRAG = 69 -SM_SHOWSOUNDS = 70 -SM_CXMENUCHECK = 71 -SM_CYMENUCHECK = 72 -SM_SLOWMACHINE = 73 -SM_MIDEASTENABLED = 74 -SM_MOUSEWHEELPRESENT = 75 -SM_XVIRTUALSCREEN = 76 -SM_YVIRTUALSCREEN = 77 -SM_CXVIRTUALSCREEN = 78 -SM_CYVIRTUALSCREEN = 79 -SM_CMONITORS = 80 -SM_SAMEDISPLAYFORMAT = 81 -SM_CMETRICS = 83 -MNC_IGNORE = 0 -MNC_CLOSE = 1 -MNC_EXECUTE = 2 -MNC_SELECT = 3 -MNS_NOCHECK = -2147483648 -MNS_MODELESS = 1073741824 -MNS_DRAGDROP = 536870912 -MNS_AUTODISMISS = 268435456 -MNS_NOTIFYBYPOS = 134217728 -MNS_CHECKORBMP = 67108864 -MIM_MAXHEIGHT = 1 -MIM_BACKGROUND = 2 -MIM_HELPID = 4 -MIM_MENUDATA = 8 -MIM_STYLE = 16 -MIM_APPLYTOSUBMENUS = -2147483648 -MND_CONTINUE = 0 -MND_ENDMENU = 1 -MNGOF_GAP = 3 -MNGO_NOINTERFACE = 0 -MNGO_NOERROR = 1 -MIIM_STATE = 1 -MIIM_ID = 2 -MIIM_SUBMENU = 4 -MIIM_CHECKMARKS = 8 -MIIM_TYPE = 16 -MIIM_DATA = 32 -MIIM_STRING = 64 -MIIM_BITMAP = 128 -MIIM_FTYPE = 256 -HBMMENU_CALLBACK = -1 -HBMMENU_SYSTEM = 1 -HBMMENU_MBAR_RESTORE = 2 -HBMMENU_MBAR_MINIMIZE = 3 -HBMMENU_MBAR_CLOSE = 5 -HBMMENU_MBAR_CLOSE_D = 6 -HBMMENU_MBAR_MINIMIZE_D = 7 -HBMMENU_POPUP_CLOSE = 8 -HBMMENU_POPUP_RESTORE = 9 -HBMMENU_POPUP_MAXIMIZE = 10 -HBMMENU_POPUP_MINIMIZE = 11 -GMDI_USEDISABLED = 1 -GMDI_GOINTOPOPUPS = 2 -TPM_LEFTBUTTON = 0 -TPM_RIGHTBUTTON = 2 -TPM_LEFTALIGN = 0 -TPM_CENTERALIGN = 4 -TPM_RIGHTALIGN = 8 -TPM_TOPALIGN = 0 -TPM_VCENTERALIGN = 16 -TPM_BOTTOMALIGN = 32 -TPM_HORIZONTAL = 0 -TPM_VERTICAL = 64 -TPM_NONOTIFY = 128 -TPM_RETURNCMD = 256 -TPM_RECURSE = 1 -DOF_EXECUTABLE = 32769 -DOF_DOCUMENT = 32770 -DOF_DIRECTORY = 32771 -DOF_MULTIPLE = 32772 -DOF_PROGMAN = 1 -DOF_SHELLDATA = 2 -DO_DROPFILE = 1162627398 -DO_PRINTFILE = 1414419024 -DT_TOP = 0 -DT_LEFT = 0 -DT_CENTER = 1 -DT_RIGHT = 2 -DT_VCENTER = 4 -DT_BOTTOM = 8 -DT_WORDBREAK = 16 -DT_SINGLELINE = 32 -DT_EXPANDTABS = 64 -DT_TABSTOP = 128 -DT_NOCLIP = 256 -DT_EXTERNALLEADING = 512 -DT_CALCRECT = 1024 -DT_NOPREFIX = 2048 -DT_INTERNAL = 4096 -DT_EDITCONTROL = 8192 -DT_PATH_ELLIPSIS = 16384 -DT_END_ELLIPSIS = 32768 -DT_MODIFYSTRING = 65536 -DT_RTLREADING = 131072 -DT_WORD_ELLIPSIS = 262144 -DST_COMPLEX = 0 -DST_TEXT = 1 -DST_PREFIXTEXT = 2 -DST_ICON = 3 -DST_BITMAP = 4 -DSS_NORMAL = 0 -DSS_UNION = 16 -DSS_DISABLED = 32 -DSS_MONO = 128 -DSS_RIGHT = 32768 -DCX_WINDOW = 1 -DCX_CACHE = 2 -DCX_NORESETATTRS = 4 -DCX_CLIPCHILDREN = 8 -DCX_CLIPSIBLINGS = 16 -DCX_PARENTCLIP = 32 -DCX_EXCLUDERGN = 64 -DCX_INTERSECTRGN = 128 -DCX_EXCLUDEUPDATE = 256 -DCX_INTERSECTUPDATE = 512 -DCX_LOCKWINDOWUPDATE = 1024 -DCX_VALIDATE = 2097152 -CUDR_NORMAL = 0 -CUDR_NOSNAPTOGRID = 1 -CUDR_NORESOLVEPOSITIONS = 2 -CUDR_NOCLOSEGAPS = 4 -CUDR_NEGATIVECOORDS = 8 -CUDR_NOPRIMARY = 16 -RDW_INVALIDATE = 1 -RDW_INTERNALPAINT = 2 -RDW_ERASE = 4 -RDW_VALIDATE = 8 -RDW_NOINTERNALPAINT = 16 -RDW_NOERASE = 32 -RDW_NOCHILDREN = 64 -RDW_ALLCHILDREN = 128 -RDW_UPDATENOW = 256 -RDW_ERASENOW = 512 -RDW_FRAME = 1024 -RDW_NOFRAME = 2048 -SW_SCROLLCHILDREN = 1 -SW_INVALIDATE = 2 -SW_ERASE = 4 -SW_SMOOTHSCROLL = 16 # Use smooth scrolling -ESB_ENABLE_BOTH = 0 -ESB_DISABLE_BOTH = 3 -ESB_DISABLE_LEFT = 1 -ESB_DISABLE_RIGHT = 2 -ESB_DISABLE_UP = 1 -ESB_DISABLE_DOWN = 2 -ESB_DISABLE_LTUP = ESB_DISABLE_LEFT -ESB_DISABLE_RTDN = ESB_DISABLE_RIGHT -HELPINFO_WINDOW = 1 -HELPINFO_MENUITEM = 2 -MB_OK = 0 -MB_OKCANCEL = 1 -MB_ABORTRETRYIGNORE = 2 -MB_YESNOCANCEL = 3 -MB_YESNO = 4 -MB_RETRYCANCEL = 5 -MB_ICONHAND = 16 -MB_ICONQUESTION = 32 -MB_ICONEXCLAMATION = 48 -MB_ICONASTERISK = 64 -MB_ICONWARNING = MB_ICONEXCLAMATION -MB_ICONERROR = MB_ICONHAND -MB_ICONINFORMATION = MB_ICONASTERISK -MB_ICONSTOP = MB_ICONHAND -MB_DEFBUTTON1 = 0 -MB_DEFBUTTON2 = 256 -MB_DEFBUTTON3 = 512 -MB_DEFBUTTON4 = 768 -MB_APPLMODAL = 0 -MB_SYSTEMMODAL = 4096 -MB_TASKMODAL = 8192 -MB_HELP = 16384 -MB_NOFOCUS = 32768 -MB_SETFOREGROUND = 65536 -MB_DEFAULT_DESKTOP_ONLY = 131072 -MB_TOPMOST = 262144 -MB_RIGHT = 524288 -MB_RTLREADING = 1048576 -MB_SERVICE_NOTIFICATION = 2097152 -MB_TYPEMASK = 15 -MB_USERICON = 128 -MB_ICONMASK = 240 -MB_DEFMASK = 3840 -MB_MODEMASK = 12288 -MB_MISCMASK = 49152 -# winuser.h line 6373 -CWP_ALL = 0 -CWP_SKIPINVISIBLE = 1 -CWP_SKIPDISABLED = 2 -CWP_SKIPTRANSPARENT = 4 -CTLCOLOR_MSGBOX = 0 -CTLCOLOR_EDIT = 1 -CTLCOLOR_LISTBOX = 2 -CTLCOLOR_BTN = 3 -CTLCOLOR_DLG = 4 -CTLCOLOR_SCROLLBAR = 5 -CTLCOLOR_STATIC = 6 -CTLCOLOR_MAX = 7 -COLOR_SCROLLBAR = 0 -COLOR_BACKGROUND = 1 -COLOR_ACTIVECAPTION = 2 -COLOR_INACTIVECAPTION = 3 -COLOR_MENU = 4 -COLOR_WINDOW = 5 -COLOR_WINDOWFRAME = 6 -COLOR_MENUTEXT = 7 -COLOR_WINDOWTEXT = 8 -COLOR_CAPTIONTEXT = 9 -COLOR_ACTIVEBORDER = 10 -COLOR_INACTIVEBORDER = 11 -COLOR_APPWORKSPACE = 12 -COLOR_HIGHLIGHT = 13 -COLOR_HIGHLIGHTTEXT = 14 -COLOR_BTNFACE = 15 -COLOR_BTNSHADOW = 16 -COLOR_GRAYTEXT = 17 -COLOR_BTNTEXT = 18 -COLOR_INACTIVECAPTIONTEXT = 19 -COLOR_BTNHIGHLIGHT = 20 -COLOR_3DDKSHADOW = 21 -COLOR_3DLIGHT = 22 -COLOR_INFOTEXT = 23 -COLOR_INFOBK = 24 -COLOR_HOTLIGHT = 26 -COLOR_GRADIENTACTIVECAPTION = 27 -COLOR_GRADIENTINACTIVECAPTION = 28 -COLOR_DESKTOP = COLOR_BACKGROUND -COLOR_3DFACE = COLOR_BTNFACE -COLOR_3DSHADOW = COLOR_BTNSHADOW -COLOR_3DHIGHLIGHT = COLOR_BTNHIGHLIGHT -COLOR_3DHILIGHT = COLOR_BTNHIGHLIGHT -COLOR_BTNHILIGHT = COLOR_BTNHIGHLIGHT -GW_HWNDFIRST = 0 -GW_HWNDLAST = 1 -GW_HWNDNEXT = 2 -GW_HWNDPREV = 3 -GW_OWNER = 4 -GW_CHILD = 5 -GW_ENABLEDPOPUP = 6 -GW_MAX = 6 -MF_INSERT = 0 -MF_CHANGE = 128 -MF_APPEND = 256 -MF_DELETE = 512 -MF_REMOVE = 4096 -MF_BYCOMMAND = 0 -MF_BYPOSITION = 1024 -MF_SEPARATOR = 2048 -MF_ENABLED = 0 -MF_GRAYED = 1 -MF_DISABLED = 2 -MF_UNCHECKED = 0 -MF_CHECKED = 8 -MF_USECHECKBITMAPS = 512 -MF_STRING = 0 -MF_BITMAP = 4 -MF_OWNERDRAW = 256 -MF_POPUP = 16 -MF_MENUBARBREAK = 32 -MF_MENUBREAK = 64 -MF_UNHILITE = 0 -MF_HILITE = 128 -MF_DEFAULT = 4096 -MF_SYSMENU = 8192 -MF_HELP = 16384 -MF_RIGHTJUSTIFY = 16384 -MF_MOUSESELECT = 32768 -MF_END = 128 -MFT_STRING = MF_STRING -MFT_BITMAP = MF_BITMAP -MFT_MENUBARBREAK = MF_MENUBARBREAK -MFT_MENUBREAK = MF_MENUBREAK -MFT_OWNERDRAW = MF_OWNERDRAW -MFT_RADIOCHECK = 512 -MFT_SEPARATOR = MF_SEPARATOR -MFT_RIGHTORDER = 8192 -MFT_RIGHTJUSTIFY = MF_RIGHTJUSTIFY -MFS_GRAYED = 3 -MFS_DISABLED = MFS_GRAYED -MFS_CHECKED = MF_CHECKED -MFS_HILITE = MF_HILITE -MFS_ENABLED = MF_ENABLED -MFS_UNCHECKED = MF_UNCHECKED -MFS_UNHILITE = MF_UNHILITE -MFS_DEFAULT = MF_DEFAULT -MFS_MASK = 4235 -MFS_HOTTRACKDRAWN = 268435456 -MFS_CACHEDBMP = 536870912 -MFS_BOTTOMGAPDROP = 1073741824 -MFS_TOPGAPDROP = -2147483648 -MFS_GAPDROP = -1073741824 -SC_SIZE = 61440 -SC_MOVE = 61456 -SC_MINIMIZE = 61472 -SC_MAXIMIZE = 61488 -SC_NEXTWINDOW = 61504 -SC_PREVWINDOW = 61520 -SC_CLOSE = 61536 -SC_VSCROLL = 61552 -SC_HSCROLL = 61568 -SC_MOUSEMENU = 61584 -SC_KEYMENU = 61696 -SC_ARRANGE = 61712 -SC_RESTORE = 61728 -SC_TASKLIST = 61744 -SC_SCREENSAVE = 61760 -SC_HOTKEY = 61776 -SC_DEFAULT = 61792 -SC_MONITORPOWER = 61808 -SC_CONTEXTHELP = 61824 -SC_SEPARATOR = 61455 -SC_ICON = SC_MINIMIZE -SC_ZOOM = SC_MAXIMIZE -IDC_ARROW = 32512 -IDC_IBEAM = 32513 -IDC_WAIT = 32514 -IDC_CROSS = 32515 -IDC_UPARROW = 32516 -IDC_SIZE = 32640 # OBSOLETE: use IDC_SIZEALL -IDC_ICON = 32641 # OBSOLETE: use IDC_ARROW -IDC_SIZENWSE = 32642 -IDC_SIZENESW = 32643 -IDC_SIZEWE = 32644 -IDC_SIZENS = 32645 -IDC_SIZEALL = 32646 -IDC_NO = 32648 -IDC_HAND = 32649 -IDC_APPSTARTING = 32650 -IDC_HELP = 32651 -IMAGE_BITMAP = 0 -IMAGE_ICON = 1 -IMAGE_CURSOR = 2 -IMAGE_ENHMETAFILE = 3 -LR_DEFAULTCOLOR = 0 -LR_MONOCHROME = 1 -LR_COLOR = 2 -LR_COPYRETURNORG = 4 -LR_COPYDELETEORG = 8 -LR_LOADFROMFILE = 16 -LR_LOADTRANSPARENT = 32 -LR_DEFAULTSIZE = 64 -LR_LOADREALSIZE = 128 -LR_LOADMAP3DCOLORS = 4096 -LR_CREATEDIBSECTION = 8192 -LR_COPYFROMRESOURCE = 16384 -LR_SHARED = 32768 -DI_MASK = 1 -DI_IMAGE = 2 -DI_NORMAL = 3 -DI_COMPAT = 4 -DI_DEFAULTSIZE = 8 -RES_ICON = 1 -RES_CURSOR = 2 -OBM_CLOSE = 32754 -OBM_UPARROW = 32753 -OBM_DNARROW = 32752 -OBM_RGARROW = 32751 -OBM_LFARROW = 32750 -OBM_REDUCE = 32749 -OBM_ZOOM = 32748 -OBM_RESTORE = 32747 -OBM_REDUCED = 32746 -OBM_ZOOMD = 32745 -OBM_RESTORED = 32744 -OBM_UPARROWD = 32743 -OBM_DNARROWD = 32742 -OBM_RGARROWD = 32741 -OBM_LFARROWD = 32740 -OBM_MNARROW = 32739 -OBM_COMBO = 32738 -OBM_UPARROWI = 32737 -OBM_DNARROWI = 32736 -OBM_RGARROWI = 32735 -OBM_LFARROWI = 32734 -OBM_OLD_CLOSE = 32767 -OBM_SIZE = 32766 -OBM_OLD_UPARROW = 32765 -OBM_OLD_DNARROW = 32764 -OBM_OLD_RGARROW = 32763 -OBM_OLD_LFARROW = 32762 -OBM_BTSIZE = 32761 -OBM_CHECK = 32760 -OBM_CHECKBOXES = 32759 -OBM_BTNCORNERS = 32758 -OBM_OLD_REDUCE = 32757 -OBM_OLD_ZOOM = 32756 -OBM_OLD_RESTORE = 32755 -OCR_NORMAL = 32512 -OCR_IBEAM = 32513 -OCR_WAIT = 32514 -OCR_CROSS = 32515 -OCR_UP = 32516 -OCR_SIZE = 32640 -OCR_ICON = 32641 -OCR_SIZENWSE = 32642 -OCR_SIZENESW = 32643 -OCR_SIZEWE = 32644 -OCR_SIZENS = 32645 -OCR_SIZEALL = 32646 -OCR_ICOCUR = 32647 -OCR_NO = 32648 -OCR_HAND = 32649 -OCR_APPSTARTING = 32650 -# winuser.h line 7455 -OIC_SAMPLE = 32512 -OIC_HAND = 32513 -OIC_QUES = 32514 -OIC_BANG = 32515 -OIC_NOTE = 32516 -OIC_WINLOGO = 32517 -OIC_WARNING = OIC_BANG -OIC_ERROR = OIC_HAND -OIC_INFORMATION = OIC_NOTE -ORD_LANGDRIVER = 1 -IDI_APPLICATION = 32512 -IDI_HAND = 32513 -IDI_QUESTION = 32514 -IDI_EXCLAMATION = 32515 -IDI_ASTERISK = 32516 -IDI_WINLOGO = 32517 -IDI_WARNING = IDI_EXCLAMATION -IDI_ERROR = IDI_HAND -IDI_INFORMATION = IDI_ASTERISK -IDOK = 1 -IDCANCEL = 2 -IDABORT = 3 -IDRETRY = 4 -IDIGNORE = 5 -IDYES = 6 -IDNO = 7 -IDCLOSE = 8 -IDHELP = 9 -ES_LEFT = 0 -ES_CENTER = 1 -ES_RIGHT = 2 -ES_MULTILINE = 4 -ES_UPPERCASE = 8 -ES_LOWERCASE = 16 -ES_PASSWORD = 32 -ES_AUTOVSCROLL = 64 -ES_AUTOHSCROLL = 128 -ES_NOHIDESEL = 256 -ES_OEMCONVERT = 1024 -ES_READONLY = 2048 -ES_WANTRETURN = 4096 -ES_NUMBER = 8192 -EN_SETFOCUS = 256 -EN_KILLFOCUS = 512 -EN_CHANGE = 768 -EN_UPDATE = 1024 -EN_ERRSPACE = 1280 -EN_MAXTEXT = 1281 -EN_HSCROLL = 1537 -EN_VSCROLL = 1538 -EC_LEFTMARGIN = 1 -EC_RIGHTMARGIN = 2 -EC_USEFONTINFO = 65535 -EMSIS_COMPOSITIONSTRING = 1 -EIMES_GETCOMPSTRATONCE = 1 -EIMES_CANCELCOMPSTRINFOCUS = 2 -EIMES_COMPLETECOMPSTRKILLFOCUS = 4 -EM_GETSEL = 176 -EM_SETSEL = 177 -EM_GETRECT = 178 -EM_SETRECT = 179 -EM_SETRECTNP = 180 -EM_SCROLL = 181 -EM_LINESCROLL = 182 -EM_SCROLLCARET = 183 -EM_GETMODIFY = 184 -EM_SETMODIFY = 185 -EM_GETLINECOUNT = 186 -EM_LINEINDEX = 187 -EM_SETHANDLE = 188 -EM_GETHANDLE = 189 -EM_GETTHUMB = 190 -EM_LINELENGTH = 193 -EM_REPLACESEL = 194 -EM_GETLINE = 196 -EM_LIMITTEXT = 197 -EM_CANUNDO = 198 -EM_UNDO = 199 -EM_FMTLINES = 200 -EM_LINEFROMCHAR = 201 -EM_SETTABSTOPS = 203 -EM_SETPASSWORDCHAR = 204 -EM_EMPTYUNDOBUFFER = 205 -EM_GETFIRSTVISIBLELINE = 206 -EM_SETREADONLY = 207 -EM_SETWORDBREAKPROC = 208 -EM_GETWORDBREAKPROC = 209 -EM_GETPASSWORDCHAR = 210 -EM_SETMARGINS = 211 -EM_GETMARGINS = 212 -EM_SETLIMITTEXT = EM_LIMITTEXT -EM_GETLIMITTEXT = 213 -EM_POSFROMCHAR = 214 -EM_CHARFROMPOS = 215 -EM_SETIMESTATUS = 216 -EM_GETIMESTATUS = 217 -WB_LEFT = 0 -WB_RIGHT = 1 -WB_ISDELIMITER = 2 -BS_PUSHBUTTON = 0 -BS_DEFPUSHBUTTON = 1 -BS_CHECKBOX = 2 -BS_AUTOCHECKBOX = 3 -BS_RADIOBUTTON = 4 -BS_3STATE = 5 -BS_AUTO3STATE = 6 -BS_GROUPBOX = 7 -BS_USERBUTTON = 8 -BS_AUTORADIOBUTTON = 9 -BS_OWNERDRAW = 11 -BS_LEFTTEXT = 32 -BS_TEXT = 0 -BS_ICON = 64 -BS_BITMAP = 128 -BS_LEFT = 256 -BS_RIGHT = 512 -BS_CENTER = 768 -BS_TOP = 1024 -BS_BOTTOM = 2048 -BS_VCENTER = 3072 -BS_PUSHLIKE = 4096 -BS_MULTILINE = 8192 -BS_NOTIFY = 16384 -BS_FLAT = 32768 -BS_RIGHTBUTTON = BS_LEFTTEXT -BN_CLICKED = 0 -BN_PAINT = 1 -BN_HILITE = 2 -BN_UNHILITE = 3 -BN_DISABLE = 4 -BN_DOUBLECLICKED = 5 -BN_PUSHED = BN_HILITE -BN_UNPUSHED = BN_UNHILITE -BN_DBLCLK = BN_DOUBLECLICKED -BN_SETFOCUS = 6 -BN_KILLFOCUS = 7 -BM_GETCHECK = 240 -BM_SETCHECK = 241 -BM_GETSTATE = 242 -BM_SETSTATE = 243 -BM_SETSTYLE = 244 -BM_CLICK = 245 -BM_GETIMAGE = 246 -BM_SETIMAGE = 247 -BST_UNCHECKED = 0 -BST_CHECKED = 1 -BST_INDETERMINATE = 2 -BST_PUSHED = 4 -BST_FOCUS = 8 -SS_LEFT = 0 -SS_CENTER = 1 -SS_RIGHT = 2 -SS_ICON = 3 -SS_BLACKRECT = 4 -SS_GRAYRECT = 5 -SS_WHITERECT = 6 -SS_BLACKFRAME = 7 -SS_GRAYFRAME = 8 -SS_WHITEFRAME = 9 -SS_USERITEM = 10 -SS_SIMPLE = 11 -SS_LEFTNOWORDWRAP = 12 -SS_BITMAP = 14 -SS_OWNERDRAW = 13 -SS_ENHMETAFILE = 15 -SS_ETCHEDHORZ = 16 -SS_ETCHEDVERT = 17 -SS_ETCHEDFRAME = 18 -SS_TYPEMASK = 31 -SS_NOPREFIX = 128 -SS_NOTIFY = 256 -SS_CENTERIMAGE = 512 -SS_RIGHTJUST = 1024 -SS_REALSIZEIMAGE = 2048 -SS_SUNKEN = 4096 -SS_ENDELLIPSIS = 16384 -SS_PATHELLIPSIS = 32768 -SS_WORDELLIPSIS = 49152 -SS_ELLIPSISMASK = 49152 -STM_SETICON = 368 -STM_GETICON = 369 -STM_SETIMAGE = 370 -STM_GETIMAGE = 371 -STN_CLICKED = 0 -STN_DBLCLK = 1 -STN_ENABLE = 2 -STN_DISABLE = 3 -STM_MSGMAX = 372 -DWL_MSGRESULT = 0 -DWL_DLGPROC = 4 -DWL_USER = 8 -DDL_READWRITE = 0 -DDL_READONLY = 1 -DDL_HIDDEN = 2 -DDL_SYSTEM = 4 -DDL_DIRECTORY = 16 -DDL_ARCHIVE = 32 -DDL_POSTMSGS = 8192 -DDL_DRIVES = 16384 -DDL_EXCLUSIVE = 32768 - -#from winuser.h line 153 -RT_CURSOR = 1 -RT_BITMAP = 2 -RT_ICON = 3 -RT_MENU = 4 -RT_DIALOG = 5 -RT_STRING = 6 -RT_FONTDIR = 7 -RT_FONT = 8 -RT_ACCELERATOR = 9 -RT_RCDATA = 10 -RT_MESSAGETABLE = 11 -DIFFERENCE = 11 -RT_GROUP_CURSOR = (RT_CURSOR + DIFFERENCE) -RT_GROUP_ICON = (RT_ICON + DIFFERENCE) -RT_VERSION = 16 -RT_DLGINCLUDE = 17 -RT_PLUGPLAY = 19 -RT_VXD = 20 -RT_ANICURSOR = 21 -RT_ANIICON = 22 -RT_HTML = 23 -# from winuser.h line 218 -SB_HORZ = 0 -SB_VERT = 1 -SB_CTL = 2 -SB_BOTH = 3 -SB_LINEUP = 0 -SB_LINELEFT = 0 -SB_LINEDOWN = 1 -SB_LINERIGHT = 1 -SB_PAGEUP = 2 -SB_PAGELEFT = 2 -SB_PAGEDOWN = 3 -SB_PAGERIGHT = 3 -SB_THUMBPOSITION = 4 -SB_THUMBTRACK = 5 -SB_TOP = 6 -SB_LEFT = 6 -SB_BOTTOM = 7 -SB_RIGHT = 7 -SB_ENDSCROLL = 8 -SW_HIDE = 0 -SW_SHOWNORMAL = 1 -SW_NORMAL = 1 -SW_SHOWMINIMIZED = 2 -SW_SHOWMAXIMIZED = 3 -SW_MAXIMIZE = 3 -SW_SHOWNOACTIVATE = 4 -SW_SHOW = 5 -SW_MINIMIZE = 6 -SW_SHOWMINNOACTIVE = 7 -SW_SHOWNA = 8 -SW_RESTORE = 9 -SW_SHOWDEFAULT = 10 -SW_FORCEMINIMIZE = 11 -SW_MAX = 11 -HIDE_WINDOW = 0 -SHOW_OPENWINDOW = 1 -SHOW_ICONWINDOW = 2 -SHOW_FULLSCREEN = 3 -SHOW_OPENNOACTIVATE = 4 -SW_PARENTCLOSING = 1 -SW_OTHERZOOM = 2 -SW_PARENTOPENING = 3 -SW_OTHERUNZOOM = 4 -AW_HOR_POSITIVE = 1 -AW_HOR_NEGATIVE = 2 -AW_VER_POSITIVE = 4 -AW_VER_NEGATIVE = 8 -AW_CENTER = 16 -AW_HIDE = 65536 -AW_ACTIVATE = 131072 -AW_SLIDE = 262144 -AW_BLEND = 524288 -KF_EXTENDED = 256 -KF_DLGMODE = 2048 -KF_MENUMODE = 4096 -KF_ALTDOWN = 8192 -KF_REPEAT = 16384 -KF_UP = 32768 -VK_LBUTTON = 1 -VK_RBUTTON = 2 -VK_CANCEL = 3 -VK_MBUTTON = 4 -VK_BACK = 8 -VK_TAB = 9 -VK_CLEAR = 12 -VK_RETURN = 13 -VK_SHIFT = 16 -VK_CONTROL = 17 -VK_MENU = 18 -VK_PAUSE = 19 -VK_CAPITAL = 20 -VK_KANA = 21 -VK_HANGEUL = 21 # old name - should be here for compatibility -VK_HANGUL = 21 -VK_JUNJA = 23 -VK_FINAL = 24 -VK_HANJA = 25 -VK_KANJI = 25 -VK_ESCAPE = 27 -VK_CONVERT = 28 -VK_NONCONVERT = 29 -VK_ACCEPT = 30 -VK_MODECHANGE = 31 -VK_SPACE = 32 -VK_PRIOR = 33 -VK_NEXT = 34 -VK_END = 35 -VK_HOME = 36 -VK_LEFT = 37 -VK_UP = 38 -VK_RIGHT = 39 -VK_DOWN = 40 -VK_SELECT = 41 -VK_PRINT = 42 -VK_EXECUTE = 43 -VK_SNAPSHOT = 44 -VK_INSERT = 45 -VK_DELETE = 46 -VK_HELP = 47 -VK_LWIN = 91 -VK_RWIN = 92 -VK_APPS = 93 -VK_NUMPAD0 = 96 -VK_NUMPAD1 = 97 -VK_NUMPAD2 = 98 -VK_NUMPAD3 = 99 -VK_NUMPAD4 = 100 -VK_NUMPAD5 = 101 -VK_NUMPAD6 = 102 -VK_NUMPAD7 = 103 -VK_NUMPAD8 = 104 -VK_NUMPAD9 = 105 -VK_MULTIPLY = 106 -VK_ADD = 107 -VK_SEPARATOR = 108 -VK_SUBTRACT = 109 -VK_DECIMAL = 110 -VK_DIVIDE = 111 -VK_F1 = 112 -VK_F2 = 113 -VK_F3 = 114 -VK_F4 = 115 -VK_F5 = 116 -VK_F6 = 117 -VK_F7 = 118 -VK_F8 = 119 -VK_F9 = 120 -VK_F10 = 121 -VK_F11 = 122 -VK_F12 = 123 -VK_F13 = 124 -VK_F14 = 125 -VK_F15 = 126 -VK_F16 = 127 -VK_F17 = 128 -VK_F18 = 129 -VK_F19 = 130 -VK_F20 = 131 -VK_F21 = 132 -VK_F22 = 133 -VK_F23 = 134 -VK_F24 = 135 -VK_NUMLOCK = 144 -VK_SCROLL = 145 -VK_LSHIFT = 160 -VK_RSHIFT = 161 -VK_LCONTROL = 162 -VK_RCONTROL = 163 -VK_LMENU = 164 -VK_RMENU = 165 -VK_PROCESSKEY = 229 -VK_ATTN = 246 -VK_CRSEL = 247 -VK_EXSEL = 248 -VK_EREOF = 249 -VK_PLAY = 250 -VK_ZOOM = 251 -VK_NONAME = 252 -VK_PA1 = 253 -VK_OEM_CLEAR = 254 -# multi-media related "keys" -MOUSEEVENTF_XDOWN = 0x0080 -MOUSEEVENTF_XUP = 0x0100 -MOUSEEVENTF_WHEEL = 0x0800 -VK_XBUTTON1 = 0x05 -VK_XBUTTON2 = 0x06 -VK_VOLUME_MUTE = 0xAD -VK_VOLUME_DOWN = 0xAE -VK_VOLUME_UP = 0xAF -VK_MEDIA_NEXT_TRACK = 0xB0 -VK_MEDIA_PREV_TRACK = 0xB1 -VK_MEDIA_PLAY_PAUSE = 0xB3 -VK_LAUNCH_MAIL = 0xB4 -VK_LAUNCH_MEDIA_SELECT = 0xB5 -VK_LAUNCH_APP1 = 0xB6 -VK_LAUNCH_APP2 = 0xB -VK_BROWSER_BACK = 0xA6 -VK_BROWSER_FORWARD = 0xA7 -VK_BROWSER_REFRESH = 0xA8 -VK_BROWSER_STOP = 0xA9 -VK_BROWSER_SEARCH = 0xAA -VK_BROWSER_FAVORITES = 0xAB -VK_BROWSER_HOME = 0xAC -WH_MIN = (-1) -WH_MSGFILTER = (-1) -WH_JOURNALRECORD = 0 -WH_JOURNALPLAYBACK = 1 -WH_KEYBOARD = 2 -WH_GETMESSAGE = 3 -WH_CALLWNDPROC = 4 -WH_CBT = 5 -WH_SYSMSGFILTER = 6 -WH_MOUSE = 7 -WH_HARDWARE = 8 -WH_DEBUG = 9 -WH_SHELL = 10 -WH_FOREGROUNDIDLE = 11 -WH_CALLWNDPROCRET = 12 -WH_KEYBOARD_LL = 13 -WH_MOUSE_LL = 14 -WH_MAX = 14 -WH_MINHOOK = WH_MIN -WH_MAXHOOK = WH_MAX -HC_ACTION = 0 -HC_GETNEXT = 1 -HC_SKIP = 2 -HC_NOREMOVE = 3 -HC_NOREM = HC_NOREMOVE -HC_SYSMODALON = 4 -HC_SYSMODALOFF = 5 -HCBT_MOVESIZE = 0 -HCBT_MINMAX = 1 -HCBT_QS = 2 -HCBT_CREATEWND = 3 -HCBT_DESTROYWND = 4 -HCBT_ACTIVATE = 5 -HCBT_CLICKSKIPPED = 6 -HCBT_KEYSKIPPED = 7 -HCBT_SYSCOMMAND = 8 -HCBT_SETFOCUS = 9 -MSGF_DIALOGBOX = 0 -MSGF_MESSAGEBOX = 1 -MSGF_MENU = 2 -#MSGF_MOVE = 3 -#MSGF_SIZE = 4 -MSGF_SCROLLBAR = 5 -MSGF_NEXTWINDOW = 6 -#MSGF_MAINLOOP = 8 -MSGF_MAX = 8 -MSGF_USER = 4096 -HSHELL_WINDOWCREATED = 1 -HSHELL_WINDOWDESTROYED = 2 -HSHELL_ACTIVATESHELLWINDOW = 3 -HSHELL_WINDOWACTIVATED = 4 -HSHELL_GETMINRECT = 5 -HSHELL_REDRAW = 6 -HSHELL_TASKMAN = 7 -HSHELL_LANGUAGE = 8 -HSHELL_ACCESSIBILITYSTATE = 11 -ACCESS_STICKYKEYS = 1 -ACCESS_FILTERKEYS = 2 -ACCESS_MOUSEKEYS = 3 -# winuser.h line 624 -LLKHF_EXTENDED = 1 -LLKHF_INJECTED = 16 -LLKHF_ALTDOWN = 32 -LLKHF_UP = 128 -LLMHF_INJECTED = 1 -# line 692 -HKL_PREV = 0 -HKL_NEXT = 1 -KLF_ACTIVATE = 1 -KLF_SUBSTITUTE_OK = 2 -KLF_UNLOADPREVIOUS = 4 -KLF_REORDER = 8 -KLF_REPLACELANG = 16 -KLF_NOTELLSHELL = 128 -KLF_SETFORPROCESS = 256 -KL_NAMELENGTH = 9 -DESKTOP_READOBJECTS = 1 -DESKTOP_CREATEWINDOW = 2 -DESKTOP_CREATEMENU = 4 -DESKTOP_HOOKCONTROL = 8 -DESKTOP_JOURNALRECORD = 16 -DESKTOP_JOURNALPLAYBACK = 32 -DESKTOP_ENUMERATE = 64 -DESKTOP_WRITEOBJECTS = 128 -DESKTOP_SWITCHDESKTOP = 256 -DF_ALLOWOTHERACCOUNTHOOK = 1 -WINSTA_ENUMDESKTOPS = 1 -WINSTA_READATTRIBUTES = 2 -WINSTA_ACCESSCLIPBOARD = 4 -WINSTA_CREATEDESKTOP = 8 -WINSTA_WRITEATTRIBUTES = 16 -WINSTA_ACCESSGLOBALATOMS = 32 -WINSTA_EXITWINDOWS = 64 -WINSTA_ENUMERATE = 256 -WINSTA_READSCREEN = 512 -WSF_VISIBLE = 1 -UOI_FLAGS = 1 -UOI_NAME = 2 -UOI_TYPE = 3 -UOI_USER_SID = 4 -GWL_WNDPROC = (-4) -GWL_HINSTANCE = (-6) -GWL_HWNDPARENT = (-8) -GWL_STYLE = (-16) -GWL_EXSTYLE = (-20) -GWL_USERDATA = (-21) -GWL_ID = (-12) -GCL_MENUNAME = (-8) -GCL_HBRBACKGROUND = (-10) -GCL_HCURSOR = (-12) -GCL_HICON = (-14) -GCL_HMODULE = (-16) -GCL_CBWNDEXTRA = (-18) -GCL_CBCLSEXTRA = (-20) -GCL_WNDPROC = (-24) -GCL_STYLE = (-26) -GCW_ATOM = (-32) -GCL_HICONSM = (-34) -# line 1291 -WM_NULL = 0 -WM_CREATE = 1 -WM_DESTROY = 2 -WM_MOVE = 3 -WM_SIZE = 5 -WM_ACTIVATE = 6 -WA_INACTIVE = 0 -WA_ACTIVE = 1 -WA_CLICKACTIVE = 2 -WM_SETFOCUS = 7 -WM_KILLFOCUS = 8 -WM_ENABLE = 10 -WM_SETREDRAW = 11 -WM_SETTEXT = 12 -WM_GETTEXT = 13 -WM_GETTEXTLENGTH = 14 -WM_PAINT = 15 -WM_CLOSE = 16 -WM_QUERYENDSESSION = 17 -WM_QUIT = 18 -WM_QUERYOPEN = 19 -WM_ERASEBKGND = 20 -WM_SYSCOLORCHANGE = 21 -WM_ENDSESSION = 22 -WM_SHOWWINDOW = 24 -WM_WININICHANGE = 26 -WM_SETTINGCHANGE = WM_WININICHANGE -WM_DEVMODECHANGE = 27 -WM_ACTIVATEAPP = 28 -WM_FONTCHANGE = 29 -WM_TIMECHANGE = 30 -WM_CANCELMODE = 31 -WM_SETCURSOR = 32 -WM_MOUSEACTIVATE = 33 -WM_CHILDACTIVATE = 34 -WM_QUEUESYNC = 35 -WM_GETMINMAXINFO = 36 -WM_PAINTICON = 38 -WM_ICONERASEBKGND = 39 -WM_NEXTDLGCTL = 40 -WM_SPOOLERSTATUS = 42 -WM_DRAWITEM = 43 -WM_MEASUREITEM = 44 -WM_DELETEITEM = 45 -WM_VKEYTOITEM = 46 -WM_CHARTOITEM = 47 -WM_SETFONT = 48 -WM_GETFONT = 49 -WM_SETHOTKEY = 50 -WM_GETHOTKEY = 51 -WM_QUERYDRAGICON = 55 -WM_COMPAREITEM = 57 -WM_GETOBJECT = 61 -WM_COMPACTING = 65 -WM_COMMNOTIFY = 68 -WM_WINDOWPOSCHANGING = 70 -WM_WINDOWPOSCHANGED = 71 -WM_POWER = 72 -WM_COPYGLOBALDATA = 73 -PWR_OK = 1 -PWR_FAIL = (-1) -PWR_SUSPENDREQUEST = 1 -PWR_SUSPENDRESUME = 2 -PWR_CRITICALRESUME = 3 -WM_COPYDATA = 74 -WM_CANCELJOURNAL = 75 -WM_NOTIFY = 78 -WM_INPUTLANGCHANGEREQUEST = 80 -WM_INPUTLANGCHANGE = 81 -WM_TCARD = 82 -WM_HELP = 83 -WM_USERCHANGED = 84 -WM_NOTIFYFORMAT = 85 -NFR_ANSI = 1 -NFR_UNICODE = 2 -NF_QUERY = 3 -NF_REQUERY = 4 -WM_CONTEXTMENU = 123 -WM_STYLECHANGING = 124 -WM_STYLECHANGED = 125 -WM_DISPLAYCHANGE = 126 -WM_GETICON = 127 -WM_SETICON = 128 -WM_NCCREATE = 129 -WM_NCDESTROY = 130 -WM_NCCALCSIZE = 131 -WM_NCHITTEST = 132 -WM_NCPAINT = 133 -WM_NCACTIVATE = 134 -WM_GETDLGCODE = 135 -WM_SYNCPAINT = 136 -WM_NCMOUSEMOVE = 160 -WM_NCLBUTTONDOWN = 161 -WM_NCLBUTTONUP = 162 -WM_NCLBUTTONDBLCLK = 163 -WM_NCRBUTTONDOWN = 164 -WM_NCRBUTTONUP = 165 -WM_NCRBUTTONDBLCLK = 166 -WM_NCMBUTTONDOWN = 167 -WM_NCMBUTTONUP = 168 -WM_NCMBUTTONDBLCLK = 169 -WM_KEYFIRST = 256 -WM_KEYDOWN = 256 -WM_KEYUP = 257 -WM_CHAR = 258 -WM_DEADCHAR = 259 -WM_SYSKEYDOWN = 260 -WM_SYSKEYUP = 261 -WM_SYSCHAR = 262 -WM_SYSDEADCHAR = 263 -WM_KEYLAST = 264 -WM_IME_STARTCOMPOSITION = 269 -WM_IME_ENDCOMPOSITION = 270 -WM_IME_COMPOSITION = 271 -WM_IME_KEYLAST = 271 -WM_INITDIALOG = 272 -WM_COMMAND = 273 -WM_SYSCOMMAND = 274 -WM_TIMER = 275 -WM_HSCROLL = 276 -WM_VSCROLL = 277 -WM_INITMENU = 278 -WM_INITMENUPOPUP = 279 -WM_MENUSELECT = 287 -WM_MENUCHAR = 288 -WM_ENTERIDLE = 289 -WM_MENURBUTTONUP = 290 -WM_MENUDRAG = 291 -WM_MENUGETOBJECT = 292 -WM_UNINITMENUPOPUP = 293 -WM_MENUCOMMAND = 294 -WM_CTLCOLORMSGBOX = 306 -WM_CTLCOLOREDIT = 307 -WM_CTLCOLORLISTBOX = 308 -WM_CTLCOLORBTN = 309 -WM_CTLCOLORDLG = 310 -WM_CTLCOLORSCROLLBAR = 311 -WM_CTLCOLORSTATIC = 312 -WM_MOUSEFIRST = 512 -WM_MOUSEMOVE = 512 -WM_LBUTTONDOWN = 513 -WM_LBUTTONUP = 514 -WM_LBUTTONDBLCLK = 515 -WM_RBUTTONDOWN = 516 -WM_RBUTTONUP = 517 -WM_RBUTTONDBLCLK = 518 -WM_MBUTTONDOWN = 519 -WM_MBUTTONUP = 520 -WM_MBUTTONDBLCLK = 521 -WM_XBUTTONDOWN = 523 -WM_XBUTTONUP = 524 -WM_XBUTTONBDLCLK = 525 -WM_MOUSEWHEEL = 522 -WM_MOUSELAST = 522 -WHEEL_DELTA = 120 # Value for rolling one detent -WHEEL_PAGESCROLL = -1 # Scroll one page -WM_PARENTNOTIFY = 528 -MENULOOP_WINDOW = 0 -MENULOOP_POPUP = 1 -WM_ENTERMENULOOP = 529 -WM_EXITMENULOOP = 530 -WM_NEXTMENU = 531 -WM_SIZING = 532 -WM_CAPTURECHANGED = 533 -WM_MOVING = 534 -WM_POWERBROADCAST = 536 -PBT_APMQUERYSUSPEND = 0 -PBT_APMQUERYSTANDBY = 1 -PBT_APMQUERYSUSPENDFAILED = 2 -PBT_APMQUERYSTANDBYFAILED = 3 -PBT_APMSUSPEND = 4 -PBT_APMSTANDBY = 5 -PBT_APMRESUMECRITICAL = 6 -PBT_APMRESUMESUSPEND = 7 -PBT_APMRESUMESTANDBY = 8 -PBTF_APMRESUMEFROMFAILURE = 1 -PBT_APMBATTERYLOW = 9 -PBT_APMPOWERSTATUSCHANGE = 10 -PBT_APMOEMEVENT = 11 -PBT_APMRESUMEAUTOMATIC = 18 -WM_DEVICECHANGE = 537 -WM_MDICREATE = 544 -WM_MDIDESTROY = 545 -WM_MDIACTIVATE = 546 -WM_MDIRESTORE = 547 -WM_MDINEXT = 548 -WM_MDIMAXIMIZE = 549 -WM_MDITILE = 550 -WM_MDICASCADE = 551 -WM_MDIICONARRANGE = 552 -WM_MDIGETACTIVE = 553 -WM_MDISETMENU = 560 -WM_ENTERSIZEMOVE = 561 -WM_EXITSIZEMOVE = 562 -WM_DROPFILES = 563 -WM_MDIREFRESHMENU = 564 -WM_IME_SETCONTEXT = 641 -WM_IME_NOTIFY = 642 -WM_IME_CONTROL = 643 -WM_IME_COMPOSITIONFULL = 644 -WM_IME_SELECT = 645 -WM_IME_CHAR = 646 -WM_IME_REQUEST = 648 -WM_IME_KEYDOWN = 656 -WM_IME_KEYUP = 657 -WM_MOUSEHOVER = 673 -WM_MOUSELEAVE = 675 -WM_CUT = 768 -WM_COPY = 769 -WM_PASTE = 770 -WM_CLEAR = 771 -WM_UNDO = 772 -WM_RENDERFORMAT = 773 -WM_RENDERALLFORMATS = 774 -WM_DESTROYCLIPBOARD = 775 -WM_DRAWCLIPBOARD = 776 -WM_PAINTCLIPBOARD = 777 -WM_VSCROLLCLIPBOARD = 778 -WM_SIZECLIPBOARD = 779 -WM_ASKCBFORMATNAME = 780 -WM_CHANGECBCHAIN = 781 -WM_HSCROLLCLIPBOARD = 782 -WM_QUERYNEWPALETTE = 783 -WM_PALETTEISCHANGING = 784 -WM_PALETTECHANGED = 785 -WM_HOTKEY = 786 -WM_PRINT = 791 -WM_PRINTCLIENT = 792 -WM_HANDHELDFIRST = 856 -WM_HANDHELDLAST = 863 -WM_AFXFIRST = 864 -WM_AFXLAST = 895 -WM_PENWINFIRST = 896 -WM_PENWINLAST = 911 -WM_APP = 32768 -WM_INPUT = 0x00FF -WMSZ_LEFT = 1 -WMSZ_RIGHT = 2 -WMSZ_TOP = 3 -WMSZ_TOPLEFT = 4 -WMSZ_TOPRIGHT = 5 -WMSZ_BOTTOM = 6 -WMSZ_BOTTOMLEFT = 7 -WMSZ_BOTTOMRIGHT = 8 -#ST_BEGINSWP = 0 -#ST_ENDSWP = 1 -HTERROR = (-2) -HTTRANSPARENT = (-1) -HTNOWHERE = 0 -HTCLIENT = 1 -HTCAPTION = 2 -HTSYSMENU = 3 -HTGROWBOX = 4 -HTSIZE = HTGROWBOX -HTMENU = 5 -HTHSCROLL = 6 -HTVSCROLL = 7 -HTMINBUTTON = 8 -HTMAXBUTTON = 9 -HTLEFT = 10 -HTRIGHT = 11 -HTTOP = 12 -HTTOPLEFT = 13 -HTTOPRIGHT = 14 -HTBOTTOM = 15 -HTBOTTOMLEFT = 16 -HTBOTTOMRIGHT = 17 -HTBORDER = 18 -HTREDUCE = HTMINBUTTON -HTZOOM = HTMAXBUTTON -HTSIZEFIRST = HTLEFT -HTSIZELAST = HTBOTTOMRIGHT -HTOBJECT = 19 -HTCLOSE = 20 -HTHELP = 21 -SMTO_NORMAL = 0 -SMTO_BLOCK = 1 -SMTO_ABORTIFHUNG = 2 -SMTO_NOTIMEOUTIFNOTHUNG = 8 -MA_ACTIVATE = 1 -MA_ACTIVATEANDEAT = 2 -MA_NOACTIVATE = 3 -MA_NOACTIVATEANDEAT = 4 -ICON_SMALL = 0 -ICON_BIG = 1 -SIZE_RESTORED = 0 -SIZE_MINIMIZED = 1 -SIZE_MAXIMIZED = 2 -SIZE_MAXSHOW = 3 -SIZE_MAXHIDE = 4 -SIZENORMAL = SIZE_RESTORED -SIZEICONIC = SIZE_MINIMIZED -SIZEFULLSCREEN = SIZE_MAXIMIZED -SIZEZOOMSHOW = SIZE_MAXSHOW -SIZEZOOMHIDE = SIZE_MAXHIDE -WVR_ALIGNTOP = 16 -WVR_ALIGNLEFT = 32 -WVR_ALIGNBOTTOM = 64 -WVR_ALIGNRIGHT = 128 -WVR_HREDRAW = 256 -WVR_VREDRAW = 512 -WVR_REDRAW = (WVR_HREDRAW | WVR_VREDRAW) -WVR_VALIDRECTS = 1024 -MK_LBUTTON = 1 -MK_RBUTTON = 2 -MK_SHIFT = 4 -MK_CONTROL = 8 -MK_MBUTTON = 16 -MK_XBUTTON1 = 32 -MK_XBUTTON2 = 64 -TME_HOVER = 1 -TME_LEAVE = 2 -TME_QUERY = 1073741824 -TME_CANCEL = -2147483648 -HOVER_DEFAULT = -1 -WS_OVERLAPPED = 0 -WS_POPUP = -2147483648 -WS_CHILD = 1073741824 -WS_MINIMIZE = 536870912 -WS_VISIBLE = 268435456 -WS_DISABLED = 134217728 -WS_CLIPSIBLINGS = 67108864 -WS_CLIPCHILDREN = 33554432 -WS_MAXIMIZE = 16777216 -WS_CAPTION = 12582912 -WS_BORDER = 8388608 -WS_DLGFRAME = 4194304 -WS_VSCROLL = 2097152 -WS_HSCROLL = 1048576 -WS_SYSMENU = 524288 -WS_THICKFRAME = 262144 -WS_GROUP = 131072 -WS_TABSTOP = 65536 -WS_MINIMIZEBOX = 131072 -WS_MAXIMIZEBOX = 65536 -WS_TILED = WS_OVERLAPPED -WS_ICONIC = WS_MINIMIZE -WS_SIZEBOX = WS_THICKFRAME -WS_OVERLAPPEDWINDOW = (WS_OVERLAPPED | \ - WS_CAPTION | \ - WS_SYSMENU | \ - WS_THICKFRAME | \ - WS_MINIMIZEBOX | \ - WS_MAXIMIZEBOX) -WS_POPUPWINDOW = (WS_POPUP | \ - WS_BORDER | \ - WS_SYSMENU) -WS_CHILDWINDOW = (WS_CHILD) -WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW -WS_EX_DLGMODALFRAME = 1 -WS_EX_NOPARENTNOTIFY = 4 -WS_EX_TOPMOST = 8 -WS_EX_ACCEPTFILES = 16 -WS_EX_TRANSPARENT = 32 -WS_EX_MDICHILD = 64 -WS_EX_TOOLWINDOW = 128 -WS_EX_WINDOWEDGE = 256 -WS_EX_CLIENTEDGE = 512 -WS_EX_CONTEXTHELP = 1024 -WS_EX_RIGHT = 4096 -WS_EX_LEFT = 0 -WS_EX_RTLREADING = 8192 -WS_EX_LTRREADING = 0 -WS_EX_LEFTSCROLLBAR = 16384 -WS_EX_RIGHTSCROLLBAR = 0 -WS_EX_CONTROLPARENT = 65536 -WS_EX_STATICEDGE = 131072 -WS_EX_APPWINDOW = 262144 -WS_EX_OVERLAPPEDWINDOW = (WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE) -WS_EX_PALETTEWINDOW = (WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST) -WS_EX_LAYERED = 0x00080000 -WS_EX_NOINHERITLAYOUT = 0x00100000 -WS_EX_LAYOUTRTL = 0x00400000 -WS_EX_COMPOSITED = 0x02000000 -WS_EX_NOACTIVATE = 0x08000000 - -CS_VREDRAW = 1 -CS_HREDRAW = 2 -#CS_KEYCVTWINDOW = 0x0004 -CS_DBLCLKS = 8 -CS_OWNDC = 32 -CS_CLASSDC = 64 -CS_PARENTDC = 128 -#CS_NOKEYCVT = 0x0100 -CS_NOCLOSE = 512 -CS_SAVEBITS = 2048 -CS_BYTEALIGNCLIENT = 4096 -CS_BYTEALIGNWINDOW = 8192 -CS_GLOBALCLASS = 16384 -CS_IME = 65536 -PRF_CHECKVISIBLE = 1 -PRF_NONCLIENT = 2 -PRF_CLIENT = 4 -PRF_ERASEBKGND = 8 -PRF_CHILDREN = 16 -PRF_OWNED = 32 -BDR_RAISEDOUTER = 1 -BDR_SUNKENOUTER = 2 -BDR_RAISEDINNER = 4 -BDR_SUNKENINNER = 8 -BDR_OUTER = 3 -BDR_INNER = 12 -#BDR_RAISED = 0x0005 -#BDR_SUNKEN = 0x000a -EDGE_RAISED = (BDR_RAISEDOUTER | BDR_RAISEDINNER) -EDGE_SUNKEN = (BDR_SUNKENOUTER | BDR_SUNKENINNER) -EDGE_ETCHED = (BDR_SUNKENOUTER | BDR_RAISEDINNER) -EDGE_BUMP = (BDR_RAISEDOUTER | BDR_SUNKENINNER) - -# winuser.h line 2879 -ISMEX_NOSEND = 0 -ISMEX_SEND = 1 -ISMEX_NOTIFY = 2 -ISMEX_CALLBACK = 4 -ISMEX_REPLIED = 8 -CW_USEDEFAULT = -2147483648 -FLASHW_STOP = 0 -FLASHW_CAPTION = 1 -FLASHW_TRAY = 2 -FLASHW_ALL = (FLASHW_CAPTION | FLASHW_TRAY) -FLASHW_TIMER = 4 -FLASHW_TIMERNOFG = 12 - -# winuser.h line 7963 -DS_ABSALIGN = 1 -DS_SYSMODAL = 2 -DS_LOCALEDIT = 32 -DS_SETFONT = 64 -DS_MODALFRAME = 128 -DS_NOIDLEMSG = 256 -DS_SETFOREGROUND = 512 -DS_3DLOOK = 4 -DS_FIXEDSYS = 8 -DS_NOFAILCREATE = 16 -DS_CONTROL = 1024 -DS_CENTER = 2048 -DS_CENTERMOUSE = 4096 -DS_CONTEXTHELP = 8192 -DM_GETDEFID = (WM_USER+0) -DM_SETDEFID = (WM_USER+1) -DM_REPOSITION = (WM_USER+2) -#PSM_PAGEINFO = (WM_USER+100) -#PSM_SHEETINFO = (WM_USER+101) -#PSI_SETACTIVE = 0x0001 -#PSI_KILLACTIVE = 0x0002 -#PSI_APPLY = 0x0003 -#PSI_RESET = 0x0004 -#PSI_HASHELP = 0x0005 -#PSI_HELP = 0x0006 -#PSI_CHANGED = 0x0001 -#PSI_GUISTART = 0x0002 -#PSI_REBOOT = 0x0003 -#PSI_GETSIBLINGS = 0x0004 -DC_HASDEFID = 21323 -DLGC_WANTARROWS = 1 -DLGC_WANTTAB = 2 -DLGC_WANTALLKEYS = 4 -DLGC_WANTMESSAGE = 4 -DLGC_HASSETSEL = 8 -DLGC_DEFPUSHBUTTON = 16 -DLGC_UNDEFPUSHBUTTON = 32 -DLGC_RADIOBUTTON = 64 -DLGC_WANTCHARS = 128 -DLGC_STATIC = 256 -DLGC_BUTTON = 8192 -LB_CTLCODE = 0 -LB_OKAY = 0 -LB_ERR = (-1) -LB_ERRSPACE = (-2) -LBN_ERRSPACE = (-2) -LBN_SELCHANGE = 1 -LBN_DBLCLK = 2 -LBN_SELCANCEL = 3 -LBN_SETFOCUS = 4 -LBN_KILLFOCUS = 5 -LB_ADDSTRING = 384 -LB_INSERTSTRING = 385 -LB_DELETESTRING = 386 -LB_SELITEMRANGEEX = 387 -LB_RESETCONTENT = 388 -LB_SETSEL = 389 -LB_SETCURSEL = 390 -LB_GETSEL = 391 -LB_GETCURSEL = 392 -LB_GETTEXT = 393 -LB_GETTEXTLEN = 394 -LB_GETCOUNT = 395 -LB_SELECTSTRING = 396 -LB_DIR = 397 -LB_GETTOPINDEX = 398 -LB_FINDSTRING = 399 -LB_GETSELCOUNT = 400 -LB_GETSELITEMS = 401 -LB_SETTABSTOPS = 402 -LB_GETHORIZONTALEXTENT = 403 -LB_SETHORIZONTALEXTENT = 404 -LB_SETCOLUMNWIDTH = 405 -LB_ADDFILE = 406 -LB_SETTOPINDEX = 407 -LB_GETITEMRECT = 408 -LB_GETITEMDATA = 409 -LB_SETITEMDATA = 410 -LB_SELITEMRANGE = 411 -LB_SETANCHORINDEX = 412 -LB_GETANCHORINDEX = 413 -LB_SETCARETINDEX = 414 -LB_GETCARETINDEX = 415 -LB_SETITEMHEIGHT = 416 -LB_GETITEMHEIGHT = 417 -LB_FINDSTRINGEXACT = 418 -LB_SETLOCALE = 421 -LB_GETLOCALE = 422 -LB_SETCOUNT = 423 -LB_INITSTORAGE = 424 -LB_ITEMFROMPOINT = 425 -LB_MSGMAX = 432 -LBS_NOTIFY = 1 -LBS_SORT = 2 -LBS_NOREDRAW = 4 -LBS_MULTIPLESEL = 8 -LBS_OWNERDRAWFIXED = 16 -LBS_OWNERDRAWVARIABLE = 32 -LBS_HASSTRINGS = 64 -LBS_USETABSTOPS = 128 -LBS_NOINTEGRALHEIGHT = 256 -LBS_MULTICOLUMN = 512 -LBS_WANTKEYBOARDINPUT = 1024 -LBS_EXTENDEDSEL = 2048 -LBS_DISABLENOSCROLL = 4096 -LBS_NODATA = 8192 -LBS_NOSEL = 16384 -LBS_STANDARD = (LBS_NOTIFY | LBS_SORT | WS_VSCROLL | WS_BORDER) -CB_OKAY = 0 -CB_ERR = (-1) -CB_ERRSPACE = (-2) -CBN_ERRSPACE = (-1) -CBN_SELCHANGE = 1 -CBN_DBLCLK = 2 -CBN_SETFOCUS = 3 -CBN_KILLFOCUS = 4 -CBN_EDITCHANGE = 5 -CBN_EDITUPDATE = 6 -CBN_DROPDOWN = 7 -CBN_CLOSEUP = 8 -CBN_SELENDOK = 9 -CBN_SELENDCANCEL = 10 -CBS_SIMPLE = 1 -CBS_DROPDOWN = 2 -CBS_DROPDOWNLIST = 3 -CBS_OWNERDRAWFIXED = 16 -CBS_OWNERDRAWVARIABLE = 32 -CBS_AUTOHSCROLL = 64 -CBS_OEMCONVERT = 128 -CBS_SORT = 256 -CBS_HASSTRINGS = 512 -CBS_NOINTEGRALHEIGHT = 1024 -CBS_DISABLENOSCROLL = 2048 -CBS_UPPERCASE = 8192 -CBS_LOWERCASE = 16384 -CB_GETEDITSEL = 320 -CB_LIMITTEXT = 321 -CB_SETEDITSEL = 322 -CB_ADDSTRING = 323 -CB_DELETESTRING = 324 -CB_DIR = 325 -CB_GETCOUNT = 326 -CB_GETCURSEL = 327 -CB_GETLBTEXT = 328 -CB_GETLBTEXTLEN = 329 -CB_INSERTSTRING = 330 -CB_RESETCONTENT = 331 -CB_FINDSTRING = 332 -CB_SELECTSTRING = 333 -CB_SETCURSEL = 334 -CB_SHOWDROPDOWN = 335 -CB_GETITEMDATA = 336 -CB_SETITEMDATA = 337 -CB_GETDROPPEDCONTROLRECT = 338 -CB_SETITEMHEIGHT = 339 -CB_GETITEMHEIGHT = 340 -CB_SETEXTENDEDUI = 341 -CB_GETEXTENDEDUI = 342 -CB_GETDROPPEDSTATE = 343 -CB_FINDSTRINGEXACT = 344 -CB_SETLOCALE = 345 -CB_GETLOCALE = 346 -CB_GETTOPINDEX = 347 -CB_SETTOPINDEX = 348 -CB_GETHORIZONTALEXTENT = 349 -CB_SETHORIZONTALEXTENT = 350 -CB_GETDROPPEDWIDTH = 351 -CB_SETDROPPEDWIDTH = 352 -CB_INITSTORAGE = 353 -CB_MSGMAX = 354 -SBS_HORZ = 0 -SBS_VERT = 1 -SBS_TOPALIGN = 2 -SBS_LEFTALIGN = 2 -SBS_BOTTOMALIGN = 4 -SBS_RIGHTALIGN = 4 -SBS_SIZEBOXTOPLEFTALIGN = 2 -SBS_SIZEBOXBOTTOMRIGHTALIGN = 4 -SBS_SIZEBOX = 8 -SBS_SIZEGRIP = 16 -SBM_SETPOS = 224 -SBM_GETPOS = 225 -SBM_SETRANGE = 226 -SBM_SETRANGEREDRAW = 230 -SBM_GETRANGE = 227 -SBM_ENABLE_ARROWS = 228 -SBM_SETSCROLLINFO = 233 -SBM_GETSCROLLINFO = 234 -SIF_RANGE = 1 -SIF_PAGE = 2 -SIF_POS = 4 -SIF_DISABLENOSCROLL = 8 -SIF_TRACKPOS = 16 -SIF_ALL = (SIF_RANGE | SIF_PAGE | SIF_POS | SIF_TRACKPOS) -MDIS_ALLCHILDSTYLES = 1 -MDITILE_VERTICAL = 0 -MDITILE_HORIZONTAL = 1 -MDITILE_SKIPDISABLED = 2 - -IMC_GETCANDIDATEPOS = 7 -IMC_SETCANDIDATEPOS = 8 -IMC_GETCOMPOSITIONFONT = 9 -IMC_SETCOMPOSITIONFONT = 10 -IMC_GETCOMPOSITIONWINDOW = 11 -IMC_SETCOMPOSITIONWINDOW = 12 -IMC_GETSTATUSWINDOWPOS = 15 -IMC_SETSTATUSWINDOWPOS = 16 -IMC_CLOSESTATUSWINDOW = 33 -IMC_OPENSTATUSWINDOW = 34 -# Generated by h2py from \msvc20\include\winnt.h -# hacked and split by mhammond. -DELETE = (65536) -READ_CONTROL = (131072) -WRITE_DAC = (262144) -WRITE_OWNER = (524288) -SYNCHRONIZE = (1048576) -STANDARD_RIGHTS_REQUIRED = (983040) -STANDARD_RIGHTS_READ = (READ_CONTROL) -STANDARD_RIGHTS_WRITE = (READ_CONTROL) -STANDARD_RIGHTS_EXECUTE = (READ_CONTROL) -STANDARD_RIGHTS_ALL = (2031616) -SPECIFIC_RIGHTS_ALL = (65535) -ACCESS_SYSTEM_SECURITY = (16777216) -MAXIMUM_ALLOWED = (33554432) -GENERIC_READ = (-2147483648) -GENERIC_WRITE = (1073741824) -GENERIC_EXECUTE = (536870912) -GENERIC_ALL = (268435456) - -SERVICE_KERNEL_DRIVER = 1 -SERVICE_FILE_SYSTEM_DRIVER = 2 -SERVICE_ADAPTER = 4 -SERVICE_RECOGNIZER_DRIVER = 8 -SERVICE_DRIVER = (SERVICE_KERNEL_DRIVER | \ - SERVICE_FILE_SYSTEM_DRIVER | \ - SERVICE_RECOGNIZER_DRIVER) -SERVICE_WIN32_OWN_PROCESS = 16 -SERVICE_WIN32_SHARE_PROCESS = 32 -SERVICE_WIN32 = (SERVICE_WIN32_OWN_PROCESS | \ - SERVICE_WIN32_SHARE_PROCESS) -SERVICE_INTERACTIVE_PROCESS = 256 -SERVICE_TYPE_ALL = (SERVICE_WIN32 | \ - SERVICE_ADAPTER | \ - SERVICE_DRIVER | \ - SERVICE_INTERACTIVE_PROCESS) -SERVICE_BOOT_START = 0 -SERVICE_SYSTEM_START = 1 -SERVICE_AUTO_START = 2 -SERVICE_DEMAND_START = 3 -SERVICE_DISABLED = 4 -SERVICE_ERROR_IGNORE = 0 -SERVICE_ERROR_NORMAL = 1 -SERVICE_ERROR_SEVERE = 2 -SERVICE_ERROR_CRITICAL = 3 -TAPE_ERASE_SHORT = 0 -TAPE_ERASE_LONG = 1 -TAPE_LOAD = 0 -TAPE_UNLOAD = 1 -TAPE_TENSION = 2 -TAPE_LOCK = 3 -TAPE_UNLOCK = 4 -TAPE_FORMAT = 5 -TAPE_SETMARKS = 0 -TAPE_FILEMARKS = 1 -TAPE_SHORT_FILEMARKS = 2 -TAPE_LONG_FILEMARKS = 3 -TAPE_ABSOLUTE_POSITION = 0 -TAPE_LOGICAL_POSITION = 1 -TAPE_PSEUDO_LOGICAL_POSITION = 2 -TAPE_REWIND = 0 -TAPE_ABSOLUTE_BLOCK = 1 -TAPE_LOGICAL_BLOCK = 2 -TAPE_PSEUDO_LOGICAL_BLOCK = 3 -TAPE_SPACE_END_OF_DATA = 4 -TAPE_SPACE_RELATIVE_BLOCKS = 5 -TAPE_SPACE_FILEMARKS = 6 -TAPE_SPACE_SEQUENTIAL_FMKS = 7 -TAPE_SPACE_SETMARKS = 8 -TAPE_SPACE_SEQUENTIAL_SMKS = 9 -TAPE_DRIVE_FIXED = 1 -TAPE_DRIVE_SELECT = 2 -TAPE_DRIVE_INITIATOR = 4 -TAPE_DRIVE_ERASE_SHORT = 16 -TAPE_DRIVE_ERASE_LONG = 32 -TAPE_DRIVE_ERASE_BOP_ONLY = 64 -TAPE_DRIVE_ERASE_IMMEDIATE = 128 -TAPE_DRIVE_TAPE_CAPACITY = 256 -TAPE_DRIVE_TAPE_REMAINING = 512 -TAPE_DRIVE_FIXED_BLOCK = 1024 -TAPE_DRIVE_VARIABLE_BLOCK = 2048 -TAPE_DRIVE_WRITE_PROTECT = 4096 -TAPE_DRIVE_EOT_WZ_SIZE = 8192 -TAPE_DRIVE_ECC = 65536 -TAPE_DRIVE_COMPRESSION = 131072 -TAPE_DRIVE_PADDING = 262144 -TAPE_DRIVE_REPORT_SMKS = 524288 -TAPE_DRIVE_GET_ABSOLUTE_BLK = 1048576 -TAPE_DRIVE_GET_LOGICAL_BLK = 2097152 -TAPE_DRIVE_SET_EOT_WZ_SIZE = 4194304 -TAPE_DRIVE_LOAD_UNLOAD = -2147483647 -TAPE_DRIVE_TENSION = -2147483646 -TAPE_DRIVE_LOCK_UNLOCK = -2147483644 -TAPE_DRIVE_REWIND_IMMEDIATE = -2147483640 -TAPE_DRIVE_SET_BLOCK_SIZE = -2147483632 -TAPE_DRIVE_LOAD_UNLD_IMMED = -2147483616 -TAPE_DRIVE_TENSION_IMMED = -2147483584 -TAPE_DRIVE_LOCK_UNLK_IMMED = -2147483520 -TAPE_DRIVE_SET_ECC = -2147483392 -TAPE_DRIVE_SET_COMPRESSION = -2147483136 -TAPE_DRIVE_SET_PADDING = -2147482624 -TAPE_DRIVE_SET_REPORT_SMKS = -2147481600 -TAPE_DRIVE_ABSOLUTE_BLK = -2147479552 -TAPE_DRIVE_ABS_BLK_IMMED = -2147475456 -TAPE_DRIVE_LOGICAL_BLK = -2147467264 -TAPE_DRIVE_LOG_BLK_IMMED = -2147450880 -TAPE_DRIVE_END_OF_DATA = -2147418112 -TAPE_DRIVE_RELATIVE_BLKS = -2147352576 -TAPE_DRIVE_FILEMARKS = -2147221504 -TAPE_DRIVE_SEQUENTIAL_FMKS = -2146959360 -TAPE_DRIVE_SETMARKS = -2146435072 -TAPE_DRIVE_SEQUENTIAL_SMKS = -2145386496 -TAPE_DRIVE_REVERSE_POSITION = -2143289344 -TAPE_DRIVE_SPACE_IMMEDIATE = -2139095040 -TAPE_DRIVE_WRITE_SETMARKS = -2130706432 -TAPE_DRIVE_WRITE_FILEMARKS = -2113929216 -TAPE_DRIVE_WRITE_SHORT_FMKS = -2080374784 -TAPE_DRIVE_WRITE_LONG_FMKS = -2013265920 -TAPE_DRIVE_WRITE_MARK_IMMED = -1879048192 -TAPE_DRIVE_FORMAT = -1610612736 -TAPE_DRIVE_FORMAT_IMMEDIATE = -1073741824 -TAPE_FIXED_PARTITIONS = 0 -TAPE_SELECT_PARTITIONS = 1 -TAPE_INITIATOR_PARTITIONS = 2 -# Generated by h2py from \msvc20\include\winnt.h -# hacked and split by mhammond. - -APPLICATION_ERROR_MASK = 536870912 -ERROR_SEVERITY_SUCCESS = 0 -ERROR_SEVERITY_INFORMATIONAL = 1073741824 -ERROR_SEVERITY_WARNING = -2147483648 -ERROR_SEVERITY_ERROR = -1073741824 -MINCHAR = 128 -MAXCHAR = 127 -MINSHORT = 32768 -MAXSHORT = 32767 -MINLONG = -2147483648 -MAXLONG = 2147483647 -MAXBYTE = 255 -MAXWORD = 65535 -MAXDWORD = -1 -LANG_NEUTRAL = 0 -LANG_BULGARIAN = 2 -LANG_CHINESE = 4 -LANG_CROATIAN = 26 -LANG_CZECH = 5 -LANG_DANISH = 6 -LANG_DUTCH = 19 -LANG_ENGLISH = 9 -LANG_FINNISH = 11 -LANG_FRENCH = 12 -LANG_GERMAN = 7 -LANG_GREEK = 8 -LANG_HUNGARIAN = 14 -LANG_ICELANDIC = 15 -LANG_ITALIAN = 16 -LANG_JAPANESE = 17 -LANG_KOREAN = 18 -LANG_NORWEGIAN = 20 -LANG_POLISH = 21 -LANG_PORTUGUESE = 22 -LANG_ROMANIAN = 24 -LANG_RUSSIAN = 25 -LANG_SLOVAK = 27 -LANG_SLOVENIAN = 36 -LANG_SPANISH = 10 -LANG_SWEDISH = 29 -LANG_TURKISH = 31 -SUBLANG_NEUTRAL = 0 -SUBLANG_DEFAULT = 1 -SUBLANG_SYS_DEFAULT = 2 -SUBLANG_CHINESE_TRADITIONAL = 1 -SUBLANG_CHINESE_SIMPLIFIED = 2 -SUBLANG_CHINESE_HONGKONG = 3 -SUBLANG_CHINESE_SINGAPORE = 4 -SUBLANG_DUTCH = 1 -SUBLANG_DUTCH_BELGIAN = 2 -SUBLANG_ENGLISH_US = 1 -SUBLANG_ENGLISH_UK = 2 -SUBLANG_ENGLISH_AUS = 3 -SUBLANG_ENGLISH_CAN = 4 -SUBLANG_ENGLISH_NZ = 5 -SUBLANG_ENGLISH_EIRE = 6 -SUBLANG_FRENCH = 1 -SUBLANG_FRENCH_BELGIAN = 2 -SUBLANG_FRENCH_CANADIAN = 3 -SUBLANG_FRENCH_SWISS = 4 -SUBLANG_GERMAN = 1 -SUBLANG_GERMAN_SWISS = 2 -SUBLANG_GERMAN_AUSTRIAN = 3 -SUBLANG_ITALIAN = 1 -SUBLANG_ITALIAN_SWISS = 2 -SUBLANG_NORWEGIAN_BOKMAL = 1 -SUBLANG_NORWEGIAN_NYNORSK = 2 -SUBLANG_PORTUGUESE = 2 -SUBLANG_PORTUGUESE_BRAZILIAN = 1 -SUBLANG_SPANISH = 1 -SUBLANG_SPANISH_MEXICAN = 2 -SUBLANG_SPANISH_MODERN = 3 -SORT_DEFAULT = 0 -SORT_JAPANESE_XJIS = 0 -SORT_JAPANESE_UNICODE = 1 -SORT_CHINESE_BIG5 = 0 -SORT_CHINESE_UNICODE = 1 -SORT_KOREAN_KSC = 0 -SORT_KOREAN_UNICODE = 1 -def PRIMARYLANGID(lgid): return ((lgid) & 1023) - -def SUBLANGID(lgid): return ((lgid) >> 10) - -NLS_VALID_LOCALE_MASK = 1048575 -CONTEXT_PORTABLE_32BIT = 1048576 -CONTEXT_ALPHA = 131072 -CONTEXT_CONTROL = (CONTEXT_ALPHA | 1) -CONTEXT_FLOATING_POINT = (CONTEXT_ALPHA | 2) -CONTEXT_INTEGER = (CONTEXT_ALPHA | 4) -CONTEXT_FULL = (CONTEXT_CONTROL | CONTEXT_FLOATING_POINT | CONTEXT_INTEGER) -SIZE_OF_80387_REGISTERS = 80 -CONTEXT_FULL = (CONTEXT_CONTROL | CONTEXT_FLOATING_POINT | CONTEXT_INTEGER) -CONTEXT_CONTROL = 1 -CONTEXT_FLOATING_POINT = 2 -CONTEXT_INTEGER = 4 -CONTEXT_FULL = (CONTEXT_CONTROL | CONTEXT_FLOATING_POINT | CONTEXT_INTEGER) -PROCESS_TERMINATE = (1) -PROCESS_CREATE_THREAD = (2) -PROCESS_VM_OPERATION = (8) -PROCESS_VM_READ = (16) -PROCESS_VM_WRITE = (32) -PROCESS_DUP_HANDLE = (64) -PROCESS_CREATE_PROCESS = (128) -PROCESS_SET_QUOTA = (256) -PROCESS_SET_INFORMATION = (512) -PROCESS_QUERY_INFORMATION = (1024) -PROCESS_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 4095) -THREAD_TERMINATE = (1) -THREAD_SUSPEND_RESUME = (2) -THREAD_GET_CONTEXT = (8) -THREAD_SET_CONTEXT = (16) -THREAD_SET_INFORMATION = (32) -THREAD_QUERY_INFORMATION = (64) -THREAD_SET_THREAD_TOKEN = (128) -THREAD_IMPERSONATE = (256) -THREAD_DIRECT_IMPERSONATION = (512) -TLS_MINIMUM_AVAILABLE = 64 -EVENT_MODIFY_STATE = 2 -MUTANT_QUERY_STATE = 1 -SEMAPHORE_MODIFY_STATE = 2 -TIME_ZONE_ID_UNKNOWN = 0 -TIME_ZONE_ID_STANDARD = 1 -TIME_ZONE_ID_DAYLIGHT = 2 -PROCESSOR_INTEL_386 = 386 -PROCESSOR_INTEL_486 = 486 -PROCESSOR_INTEL_PENTIUM = 586 -PROCESSOR_INTEL_860 = 860 -PROCESSOR_MIPS_R2000 = 2000 -PROCESSOR_MIPS_R3000 = 3000 -PROCESSOR_MIPS_R4000 = 4000 -PROCESSOR_ALPHA_21064 = 21064 -PROCESSOR_PPC_601 = 601 -PROCESSOR_PPC_603 = 603 -PROCESSOR_PPC_604 = 604 -PROCESSOR_PPC_620 = 620 -SECTION_QUERY = 1 -SECTION_MAP_WRITE = 2 -SECTION_MAP_READ = 4 -SECTION_MAP_EXECUTE = 8 -SECTION_EXTEND_SIZE = 16 -PAGE_NOACCESS = 1 -PAGE_READONLY = 2 -PAGE_READWRITE = 4 -PAGE_WRITECOPY = 8 -PAGE_EXECUTE = 16 -PAGE_EXECUTE_READ = 32 -PAGE_EXECUTE_READWRITE = 64 -PAGE_EXECUTE_WRITECOPY = 128 -PAGE_GUARD = 256 -PAGE_NOCACHE = 512 -MEM_COMMIT = 4096 -MEM_RESERVE = 8192 -MEM_DECOMMIT = 16384 -MEM_RELEASE = 32768 -MEM_FREE = 65536 -MEM_PRIVATE = 131072 -MEM_MAPPED = 262144 -MEM_TOP_DOWN = 1048576 - -# Generated by h2py from \msvc20\include\winnt.h -# hacked and split by mhammond. -SEC_FILE = 8388608 -SEC_IMAGE = 16777216 -SEC_RESERVE = 67108864 -SEC_COMMIT = 134217728 -SEC_NOCACHE = 268435456 -MEM_IMAGE = SEC_IMAGE -FILE_SHARE_READ = 1 -FILE_SHARE_WRITE = 2 -FILE_SHARE_DELETE = 4 -FILE_ATTRIBUTE_READONLY = 1 -FILE_ATTRIBUTE_HIDDEN = 2 -FILE_ATTRIBUTE_SYSTEM = 4 -FILE_ATTRIBUTE_DIRECTORY = 16 -FILE_ATTRIBUTE_ARCHIVE = 32 -FILE_ATTRIBUTE_NORMAL = 128 -FILE_ATTRIBUTE_TEMPORARY = 256 -FILE_ATTRIBUTE_ATOMIC_WRITE = 512 -FILE_ATTRIBUTE_XACTION_WRITE = 1024 -FILE_ATTRIBUTE_COMPRESSED = 2048 -FILE_NOTIFY_CHANGE_FILE_NAME = 1 -FILE_NOTIFY_CHANGE_DIR_NAME = 2 -FILE_NOTIFY_CHANGE_ATTRIBUTES = 4 -FILE_NOTIFY_CHANGE_SIZE = 8 -FILE_NOTIFY_CHANGE_LAST_WRITE = 16 -FILE_NOTIFY_CHANGE_SECURITY = 256 -FILE_CASE_SENSITIVE_SEARCH = 1 -FILE_CASE_PRESERVED_NAMES = 2 -FILE_UNICODE_ON_DISK = 4 -FILE_PERSISTENT_ACLS = 8 -FILE_FILE_COMPRESSION = 16 -FILE_VOLUME_IS_COMPRESSED = 32768 -IO_COMPLETION_MODIFY_STATE = 2 -DUPLICATE_CLOSE_SOURCE = 1 -DUPLICATE_SAME_ACCESS = 2 -SID_MAX_SUB_AUTHORITIES = (15) -SECURITY_NULL_RID = (0) -SECURITY_WORLD_RID = (0) -SECURITY_LOCAL_RID = (0X00000000) -SECURITY_CREATOR_OWNER_RID = (0) -SECURITY_CREATOR_GROUP_RID = (1) -SECURITY_DIALUP_RID = (1) -SECURITY_NETWORK_RID = (2) -SECURITY_BATCH_RID = (3) -SECURITY_INTERACTIVE_RID = (4) -SECURITY_SERVICE_RID = (6) -SECURITY_ANONYMOUS_LOGON_RID = (7) -SECURITY_LOGON_IDS_RID = (5) -SECURITY_LOGON_IDS_RID_COUNT = (3) -SECURITY_LOCAL_SYSTEM_RID = (18) -SECURITY_NT_NON_UNIQUE = (21) -SECURITY_BUILTIN_DOMAIN_RID = (32) -DOMAIN_USER_RID_ADMIN = (500) -DOMAIN_USER_RID_GUEST = (501) -DOMAIN_GROUP_RID_ADMINS = (512) -DOMAIN_GROUP_RID_USERS = (513) -DOMAIN_GROUP_RID_GUESTS = (514) -DOMAIN_ALIAS_RID_ADMINS = (544) -DOMAIN_ALIAS_RID_USERS = (545) -DOMAIN_ALIAS_RID_GUESTS = (546) -DOMAIN_ALIAS_RID_POWER_USERS = (547) -DOMAIN_ALIAS_RID_ACCOUNT_OPS = (548) -DOMAIN_ALIAS_RID_SYSTEM_OPS = (549) -DOMAIN_ALIAS_RID_PRINT_OPS = (550) -DOMAIN_ALIAS_RID_BACKUP_OPS = (551) -DOMAIN_ALIAS_RID_REPLICATOR = (552) -SE_GROUP_MANDATORY = (1) -SE_GROUP_ENABLED_BY_DEFAULT = (2) -SE_GROUP_ENABLED = (4) -SE_GROUP_OWNER = (8) -SE_GROUP_LOGON_ID = (-1073741824) -ACL_REVISION = (2) -ACL_REVISION1 = (1) -ACL_REVISION2 = (2) -ACCESS_ALLOWED_ACE_TYPE = (0) -ACCESS_DENIED_ACE_TYPE = (1) -SYSTEM_AUDIT_ACE_TYPE = (2) -SYSTEM_ALARM_ACE_TYPE = (3) -OBJECT_INHERIT_ACE = (1) -CONTAINER_INHERIT_ACE = (2) -NO_PROPAGATE_INHERIT_ACE = (4) -INHERIT_ONLY_ACE = (8) -VALID_INHERIT_FLAGS = (15) -SUCCESSFUL_ACCESS_ACE_FLAG = (64) -FAILED_ACCESS_ACE_FLAG = (128) -SECURITY_DESCRIPTOR_REVISION = (1) -SECURITY_DESCRIPTOR_REVISION1 = (1) -SECURITY_DESCRIPTOR_MIN_LENGTH = (20) -SE_OWNER_DEFAULTED = (1) -SE_GROUP_DEFAULTED = (2) -SE_DACL_PRESENT = (4) -SE_DACL_DEFAULTED = (8) -SE_SACL_PRESENT = (16) -SE_SACL_DEFAULTED = (32) -SE_SELF_RELATIVE = (32768) -SE_PRIVILEGE_ENABLED_BY_DEFAULT = (1) -SE_PRIVILEGE_ENABLED = (2) -SE_PRIVILEGE_USED_FOR_ACCESS = (-2147483648) -PRIVILEGE_SET_ALL_NECESSARY = (1) -SE_CREATE_TOKEN_NAME = "SeCreateTokenPrivilege" -SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege" -SE_LOCK_MEMORY_NAME = "SeLockMemoryPrivilege" -SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege" -SE_UNSOLICITED_INPUT_NAME = "SeUnsolicitedInputPrivilege" -SE_MACHINE_ACCOUNT_NAME = "SeMachineAccountPrivilege" -SE_TCB_NAME = "SeTcbPrivilege" -SE_SECURITY_NAME = "SeSecurityPrivilege" -SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege" -SE_LOAD_DRIVER_NAME = "SeLoadDriverPrivilege" -SE_SYSTEM_PROFILE_NAME = "SeSystemProfilePrivilege" -SE_SYSTEMTIME_NAME = "SeSystemtimePrivilege" -SE_PROF_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege" -SE_INC_BASE_PRIORITY_NAME = "SeIncreaseBasePriorityPrivilege" -SE_CREATE_PAGEFILE_NAME = "SeCreatePagefilePrivilege" -SE_CREATE_PERMANENT_NAME = "SeCreatePermanentPrivilege" -SE_BACKUP_NAME = "SeBackupPrivilege" -SE_RESTORE_NAME = "SeRestorePrivilege" -SE_SHUTDOWN_NAME = "SeShutdownPrivilege" -SE_DEBUG_NAME = "SeDebugPrivilege" -SE_AUDIT_NAME = "SeAuditPrivilege" -SE_SYSTEM_ENVIRONMENT_NAME = "SeSystemEnvironmentPrivilege" -SE_CHANGE_NOTIFY_NAME = "SeChangeNotifyPrivilege" -SE_REMOTE_SHUTDOWN_NAME = "SeRemoteShutdownPrivilege" - -TOKEN_ASSIGN_PRIMARY = (1) -TOKEN_DUPLICATE = (2) -TOKEN_IMPERSONATE = (4) -TOKEN_QUERY = (8) -TOKEN_QUERY_SOURCE = (16) -TOKEN_ADJUST_PRIVILEGES = (32) -TOKEN_ADJUST_GROUPS = (64) -TOKEN_ADJUST_DEFAULT = (128) -TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED |\ - TOKEN_ASSIGN_PRIMARY |\ - TOKEN_DUPLICATE |\ - TOKEN_IMPERSONATE |\ - TOKEN_QUERY |\ - TOKEN_QUERY_SOURCE |\ - TOKEN_ADJUST_PRIVILEGES |\ - TOKEN_ADJUST_GROUPS |\ - TOKEN_ADJUST_DEFAULT) -TOKEN_READ = (STANDARD_RIGHTS_READ |\ - TOKEN_QUERY) -TOKEN_WRITE = (STANDARD_RIGHTS_WRITE |\ - TOKEN_ADJUST_PRIVILEGES |\ - TOKEN_ADJUST_GROUPS |\ - TOKEN_ADJUST_DEFAULT) -TOKEN_EXECUTE = (STANDARD_RIGHTS_EXECUTE) -TOKEN_SOURCE_LENGTH = 8 - -KEY_QUERY_VALUE = (1) -KEY_SET_VALUE = (2) -KEY_CREATE_SUB_KEY = (4) -KEY_ENUMERATE_SUB_KEYS = (8) -KEY_NOTIFY = (16) -KEY_CREATE_LINK = (32) -KEY_READ = ((STANDARD_RIGHTS_READ |\ - KEY_QUERY_VALUE |\ - KEY_ENUMERATE_SUB_KEYS |\ - KEY_NOTIFY) \ - & \ - (~SYNCHRONIZE)) -KEY_WRITE = ((STANDARD_RIGHTS_WRITE |\ - KEY_SET_VALUE |\ - KEY_CREATE_SUB_KEY) \ - & \ - (~SYNCHRONIZE)) -KEY_EXECUTE = ((KEY_READ) \ - & \ - (~SYNCHRONIZE)) -KEY_ALL_ACCESS = ((STANDARD_RIGHTS_ALL |\ - KEY_QUERY_VALUE |\ - KEY_SET_VALUE |\ - KEY_CREATE_SUB_KEY |\ - KEY_ENUMERATE_SUB_KEYS |\ - KEY_NOTIFY |\ - KEY_CREATE_LINK) \ - & \ - (~SYNCHRONIZE)) -REG_NOTIFY_CHANGE_ATTRIBUTES = (2) -REG_NOTIFY_CHANGE_SECURITY = (8) -REG_RESOURCE_REQUIREMENTS_LIST = ( 10 ) -REG_NONE = ( 0 ) # No value type -REG_SZ = ( 1 ) # Unicode nul terminated string -REG_EXPAND_SZ = ( 2 ) # Unicode nul terminated string - # (with environment variable references) -REG_BINARY = ( 3 ) # Free form binary -REG_DWORD = ( 4 ) # 32-bit number -REG_DWORD_LITTLE_ENDIAN = ( 4 ) # 32-bit number (same as REG_DWORD) -REG_DWORD_BIG_ENDIAN = ( 5 ) # 32-bit number -REG_LINK = ( 6 ) # Symbolic Link (unicode) -REG_MULTI_SZ = ( 7 ) # Multiple Unicode strings -REG_RESOURCE_LIST = ( 8 ) # Resource list in the resource map -REG_FULL_RESOURCE_DESCRIPTOR =( 9 ) # Resource list in the hardware description -REG_RESOURCE_REQUIREMENTS_LIST = ( 10 ) -REG_QWORD = ( 11 ) # 64-bit number -REG_QWORD_LITTLE_ENDIAN = ( 11 ) # 64-bit number (same as REG_QWORD) - - -# Generated by h2py from \msvc20\include\winnt.h -# hacked and split by mhammond. -# Included from string.h -_NLSCMPERROR = 2147483647 -NULL = 0 -HEAP_NO_SERIALIZE = 1 -HEAP_GROWABLE = 2 -HEAP_GENERATE_EXCEPTIONS = 4 -HEAP_ZERO_MEMORY = 8 -HEAP_REALLOC_IN_PLACE_ONLY = 16 -HEAP_TAIL_CHECKING_ENABLED = 32 -HEAP_FREE_CHECKING_ENABLED = 64 -HEAP_DISABLE_COALESCE_ON_FREE = 128 -IS_TEXT_UNICODE_ASCII16 = 1 -IS_TEXT_UNICODE_REVERSE_ASCII16 = 16 -IS_TEXT_UNICODE_STATISTICS = 2 -IS_TEXT_UNICODE_REVERSE_STATISTICS = 32 -IS_TEXT_UNICODE_CONTROLS = 4 -IS_TEXT_UNICODE_REVERSE_CONTROLS = 64 -IS_TEXT_UNICODE_SIGNATURE = 8 -IS_TEXT_UNICODE_REVERSE_SIGNATURE = 128 -IS_TEXT_UNICODE_ILLEGAL_CHARS = 256 -IS_TEXT_UNICODE_ODD_LENGTH = 512 -IS_TEXT_UNICODE_DBCS_LEADBYTE = 1024 -IS_TEXT_UNICODE_NULL_BYTES = 4096 -IS_TEXT_UNICODE_UNICODE_MASK = 15 -IS_TEXT_UNICODE_REVERSE_MASK = 240 -IS_TEXT_UNICODE_NOT_UNICODE_MASK = 3840 -IS_TEXT_UNICODE_NOT_ASCII_MASK = 61440 -COMPRESSION_FORMAT_NONE = (0) -COMPRESSION_FORMAT_DEFAULT = (1) -COMPRESSION_FORMAT_LZNT1 = (2) -COMPRESSION_ENGINE_STANDARD = (0) -COMPRESSION_ENGINE_MAXIMUM = (256) -MESSAGE_RESOURCE_UNICODE = 1 -RTL_CRITSECT_TYPE = 0 -RTL_RESOURCE_TYPE = 1 -DLL_PROCESS_ATTACH = 1 -DLL_THREAD_ATTACH = 2 -DLL_THREAD_DETACH = 3 -DLL_PROCESS_DETACH = 0 -EVENTLOG_SEQUENTIAL_READ = 0X0001 -EVENTLOG_SEEK_READ = 0X0002 -EVENTLOG_FORWARDS_READ = 0X0004 -EVENTLOG_BACKWARDS_READ = 0X0008 -EVENTLOG_SUCCESS = 0X0000 -EVENTLOG_ERROR_TYPE = 1 -EVENTLOG_WARNING_TYPE = 2 -EVENTLOG_INFORMATION_TYPE = 4 -EVENTLOG_AUDIT_SUCCESS = 8 -EVENTLOG_AUDIT_FAILURE = 16 -EVENTLOG_START_PAIRED_EVENT = 1 -EVENTLOG_END_PAIRED_EVENT = 2 -EVENTLOG_END_ALL_PAIRED_EVENTS = 4 -EVENTLOG_PAIRED_EVENT_ACTIVE = 8 -EVENTLOG_PAIRED_EVENT_INACTIVE = 16 -# Generated by h2py from \msvc20\include\winnt.h -# hacked and split by mhammond. -OWNER_SECURITY_INFORMATION = (0X00000001) -GROUP_SECURITY_INFORMATION = (0X00000002) -DACL_SECURITY_INFORMATION = (0X00000004) -SACL_SECURITY_INFORMATION = (0X00000008) -IMAGE_SIZEOF_FILE_HEADER = 20 -IMAGE_FILE_MACHINE_UNKNOWN = 0 -IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16 -IMAGE_SIZEOF_ROM_OPTIONAL_HEADER = 56 -IMAGE_SIZEOF_STD_OPTIONAL_HEADER = 28 -IMAGE_SIZEOF_NT_OPTIONAL_HEADER = 224 -IMAGE_NT_OPTIONAL_HDR_MAGIC = 267 -IMAGE_ROM_OPTIONAL_HDR_MAGIC = 263 -IMAGE_SIZEOF_SHORT_NAME = 8 -IMAGE_SIZEOF_SECTION_HEADER = 40 -IMAGE_SIZEOF_SYMBOL = 18 -IMAGE_SYM_CLASS_NULL = 0 -IMAGE_SYM_CLASS_AUTOMATIC = 1 -IMAGE_SYM_CLASS_EXTERNAL = 2 -IMAGE_SYM_CLASS_STATIC = 3 -IMAGE_SYM_CLASS_REGISTER = 4 -IMAGE_SYM_CLASS_EXTERNAL_DEF = 5 -IMAGE_SYM_CLASS_LABEL = 6 -IMAGE_SYM_CLASS_UNDEFINED_LABEL = 7 -IMAGE_SYM_CLASS_MEMBER_OF_STRUCT = 8 -IMAGE_SYM_CLASS_ARGUMENT = 9 -IMAGE_SYM_CLASS_STRUCT_TAG = 10 -IMAGE_SYM_CLASS_MEMBER_OF_UNION = 11 -IMAGE_SYM_CLASS_UNION_TAG = 12 -IMAGE_SYM_CLASS_TYPE_DEFINITION = 13 -IMAGE_SYM_CLASS_UNDEFINED_STATIC = 14 -IMAGE_SYM_CLASS_ENUM_TAG = 15 -IMAGE_SYM_CLASS_MEMBER_OF_ENUM = 16 -IMAGE_SYM_CLASS_REGISTER_PARAM = 17 -IMAGE_SYM_CLASS_BIT_FIELD = 18 -IMAGE_SYM_CLASS_BLOCK = 100 -IMAGE_SYM_CLASS_FUNCTION = 101 -IMAGE_SYM_CLASS_END_OF_STRUCT = 102 -IMAGE_SYM_CLASS_FILE = 103 -IMAGE_SYM_CLASS_SECTION = 104 -IMAGE_SYM_CLASS_WEAK_EXTERNAL = 105 -N_BTMASK = 0o17 -N_TMASK = 0o60 -N_TMASK1 = 0o300 -N_TMASK2 = 0o360 -N_BTSHFT = 4 -N_TSHIFT = 2 -IMAGE_SIZEOF_AUX_SYMBOL = 18 -IMAGE_COMDAT_SELECT_NODUPLICATES = 1 -IMAGE_COMDAT_SELECT_ANY = 2 -IMAGE_COMDAT_SELECT_SAME_SIZE = 3 -IMAGE_COMDAT_SELECT_EXACT_MATCH = 4 -IMAGE_COMDAT_SELECT_ASSOCIATIVE = 5 -IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY = 1 -IMAGE_WEAK_EXTERN_SEARCH_LIBRARY = 2 -IMAGE_WEAK_EXTERN_SEARCH_ALIAS = 3 -IMAGE_SIZEOF_RELOCATION = 10 -IMAGE_REL_I386_SECTION = 0o12 -IMAGE_REL_I386_SECREL = 0o13 -IMAGE_REL_MIPS_REFHALF = 0o1 -IMAGE_REL_MIPS_REFWORD = 0o2 -IMAGE_REL_MIPS_JMPADDR = 0o3 -IMAGE_REL_MIPS_REFHI = 0o4 -IMAGE_REL_MIPS_REFLO = 0o5 -IMAGE_REL_MIPS_GPREL = 0o6 -IMAGE_REL_MIPS_LITERAL = 0o7 -IMAGE_REL_MIPS_SECTION = 0o12 -IMAGE_REL_MIPS_SECREL = 0o13 -IMAGE_REL_MIPS_REFWORDNB = 0o42 -IMAGE_REL_MIPS_PAIR = 0o45 -IMAGE_REL_ALPHA_ABSOLUTE = 0 -IMAGE_REL_ALPHA_REFLONG = 1 -IMAGE_REL_ALPHA_REFQUAD = 2 -IMAGE_REL_ALPHA_GPREL32 = 3 -IMAGE_REL_ALPHA_LITERAL = 4 -IMAGE_REL_ALPHA_LITUSE = 5 -IMAGE_REL_ALPHA_GPDISP = 6 -IMAGE_REL_ALPHA_BRADDR = 7 -IMAGE_REL_ALPHA_HINT = 8 -IMAGE_REL_ALPHA_INLINE_REFLONG = 9 -IMAGE_REL_ALPHA_REFHI = 10 -IMAGE_REL_ALPHA_REFLO = 11 -IMAGE_REL_ALPHA_PAIR = 12 -IMAGE_REL_ALPHA_MATCH = 13 -IMAGE_REL_ALPHA_SECTION = 14 -IMAGE_REL_ALPHA_SECREL = 15 -IMAGE_REL_ALPHA_REFLONGNB = 16 -IMAGE_SIZEOF_BASE_RELOCATION = 8 -IMAGE_REL_BASED_ABSOLUTE = 0 -IMAGE_REL_BASED_HIGH = 1 -IMAGE_REL_BASED_LOW = 2 -IMAGE_REL_BASED_HIGHLOW = 3 -IMAGE_REL_BASED_HIGHADJ = 4 -IMAGE_REL_BASED_MIPS_JMPADDR = 5 -IMAGE_SIZEOF_LINENUMBER = 6 -IMAGE_ARCHIVE_START_SIZE = 8 -IMAGE_ARCHIVE_START = "!\n" -IMAGE_ARCHIVE_END = "`\n" -IMAGE_ARCHIVE_PAD = "\n" -IMAGE_ARCHIVE_LINKER_MEMBER = "/ " -IMAGE_ARCHIVE_LONGNAMES_MEMBER = "// " -IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR = 60 -IMAGE_ORDINAL_FLAG = -2147483648 -def IMAGE_SNAP_BY_ORDINAL(Ordinal): return ((Ordinal & IMAGE_ORDINAL_FLAG) != 0) - -def IMAGE_ORDINAL(Ordinal): return (Ordinal & 65535) - -IMAGE_RESOURCE_NAME_IS_STRING = -2147483648 -IMAGE_RESOURCE_DATA_IS_DIRECTORY = -2147483648 -IMAGE_DEBUG_TYPE_UNKNOWN = 0 -IMAGE_DEBUG_TYPE_COFF = 1 -IMAGE_DEBUG_TYPE_CODEVIEW = 2 -IMAGE_DEBUG_TYPE_FPO = 3 -IMAGE_DEBUG_TYPE_MISC = 4 -IMAGE_DEBUG_TYPE_EXCEPTION = 5 -IMAGE_DEBUG_TYPE_FIXUP = 6 -IMAGE_DEBUG_TYPE_OMAP_TO_SRC = 7 -IMAGE_DEBUG_TYPE_OMAP_FROM_SRC = 8 -FRAME_FPO = 0 -FRAME_TRAP = 1 -FRAME_TSS = 2 -SIZEOF_RFPO_DATA = 16 -IMAGE_DEBUG_MISC_EXENAME = 1 -IMAGE_SEPARATE_DEBUG_SIGNATURE = 18756 -# Generated by h2py from \msvcnt\include\wingdi.h -# hacked and split manually by mhammond. -NEWFRAME = 1 -ABORTDOC = 2 -NEXTBAND = 3 -SETCOLORTABLE = 4 -GETCOLORTABLE = 5 -FLUSHOUTPUT = 6 -DRAFTMODE = 7 -QUERYESCSUPPORT = 8 -SETABORTPROC = 9 -STARTDOC = 10 -ENDDOC = 11 -GETPHYSPAGESIZE = 12 -GETPRINTINGOFFSET = 13 -GETSCALINGFACTOR = 14 -MFCOMMENT = 15 -GETPENWIDTH = 16 -SETCOPYCOUNT = 17 -SELECTPAPERSOURCE = 18 -DEVICEDATA = 19 -PASSTHROUGH = 19 -GETTECHNOLGY = 20 -GETTECHNOLOGY = 20 -SETLINECAP = 21 -SETLINEJOIN = 22 -SETMITERLIMIT = 23 -BANDINFO = 24 -DRAWPATTERNRECT = 25 -GETVECTORPENSIZE = 26 -GETVECTORBRUSHSIZE = 27 -ENABLEDUPLEX = 28 -GETSETPAPERBINS = 29 -GETSETPRINTORIENT = 30 -ENUMPAPERBINS = 31 -SETDIBSCALING = 32 -EPSPRINTING = 33 -ENUMPAPERMETRICS = 34 -GETSETPAPERMETRICS = 35 -POSTSCRIPT_DATA = 37 -POSTSCRIPT_IGNORE = 38 -MOUSETRAILS = 39 -GETDEVICEUNITS = 42 -GETEXTENDEDTEXTMETRICS = 256 -GETEXTENTTABLE = 257 -GETPAIRKERNTABLE = 258 -GETTRACKKERNTABLE = 259 -EXTTEXTOUT = 512 -GETFACENAME = 513 -DOWNLOADFACE = 514 -ENABLERELATIVEWIDTHS = 768 -ENABLEPAIRKERNING = 769 -SETKERNTRACK = 770 -SETALLJUSTVALUES = 771 -SETCHARSET = 772 -STRETCHBLT = 2048 -GETSETSCREENPARAMS = 3072 -BEGIN_PATH = 4096 -CLIP_TO_PATH = 4097 -END_PATH = 4098 -EXT_DEVICE_CAPS = 4099 -RESTORE_CTM = 4100 -SAVE_CTM = 4101 -SET_ARC_DIRECTION = 4102 -SET_BACKGROUND_COLOR = 4103 -SET_POLY_MODE = 4104 -SET_SCREEN_ANGLE = 4105 -SET_SPREAD = 4106 -TRANSFORM_CTM = 4107 -SET_CLIP_BOX = 4108 -SET_BOUNDS = 4109 -SET_MIRROR_MODE = 4110 -OPENCHANNEL = 4110 -DOWNLOADHEADER = 4111 -CLOSECHANNEL = 4112 -POSTSCRIPT_PASSTHROUGH = 4115 -ENCAPSULATED_POSTSCRIPT = 4116 -SP_NOTREPORTED = 16384 -SP_ERROR = (-1) -SP_APPABORT = (-2) -SP_USERABORT = (-3) -SP_OUTOFDISK = (-4) -SP_OUTOFMEMORY = (-5) -PR_JOBSTATUS = 0 -OBJ_PEN = 1 -OBJ_BRUSH = 2 -OBJ_DC = 3 -OBJ_METADC = 4 -OBJ_PAL = 5 -OBJ_FONT = 6 -OBJ_BITMAP = 7 -OBJ_REGION = 8 -OBJ_METAFILE = 9 -OBJ_MEMDC = 10 -OBJ_EXTPEN = 11 -OBJ_ENHMETADC = 12 -OBJ_ENHMETAFILE = 13 -MWT_IDENTITY = 1 -MWT_LEFTMULTIPLY = 2 -MWT_RIGHTMULTIPLY = 3 -MWT_MIN = MWT_IDENTITY -MWT_MAX = MWT_RIGHTMULTIPLY -BI_RGB = 0 -BI_RLE8 = 1 -BI_RLE4 = 2 -BI_BITFIELDS = 3 -TMPF_FIXED_PITCH = 1 -TMPF_VECTOR = 2 -TMPF_DEVICE = 8 -TMPF_TRUETYPE = 4 -NTM_REGULAR = 64 -NTM_BOLD = 32 -NTM_ITALIC = 1 -LF_FACESIZE = 32 -LF_FULLFACESIZE = 64 -OUT_DEFAULT_PRECIS = 0 -OUT_STRING_PRECIS = 1 -OUT_CHARACTER_PRECIS = 2 -OUT_STROKE_PRECIS = 3 -OUT_TT_PRECIS = 4 -OUT_DEVICE_PRECIS = 5 -OUT_RASTER_PRECIS = 6 -OUT_TT_ONLY_PRECIS = 7 -OUT_OUTLINE_PRECIS = 8 -CLIP_DEFAULT_PRECIS = 0 -CLIP_CHARACTER_PRECIS = 1 -CLIP_STROKE_PRECIS = 2 -CLIP_MASK = 15 -CLIP_LH_ANGLES = (1<<4) -CLIP_TT_ALWAYS = (2<<4) -CLIP_EMBEDDED = (8<<4) -DEFAULT_QUALITY = 0 -DRAFT_QUALITY = 1 -PROOF_QUALITY = 2 -NONANTIALIASED_QUALITY = 3 -ANTIALIASED_QUALITY = 4 -CLEARTYPE_QUALITY = 5 -CLEARTYPE_NATURAL_QUALITY = 6 -DEFAULT_PITCH = 0 -FIXED_PITCH = 1 -VARIABLE_PITCH = 2 -ANSI_CHARSET = 0 -DEFAULT_CHARSET = 1 -SYMBOL_CHARSET = 2 -SHIFTJIS_CHARSET = 128 -HANGEUL_CHARSET = 129 -CHINESEBIG5_CHARSET = 136 -OEM_CHARSET = 255 -JOHAB_CHARSET = 130 -HEBREW_CHARSET = 177 -ARABIC_CHARSET = 178 -GREEK_CHARSET = 161 -TURKISH_CHARSET = 162 -VIETNAMESE_CHARSET = 163 -THAI_CHARSET = 222 -EASTEUROPE_CHARSET = 238 -RUSSIAN_CHARSET = 204 -MAC_CHARSET = 77 -BALTIC_CHARSET = 186 -FF_DONTCARE = (0<<4) -FF_ROMAN = (1<<4) -FF_SWISS = (2<<4) -FF_MODERN = (3<<4) -FF_SCRIPT = (4<<4) -FF_DECORATIVE = (5<<4) -FW_DONTCARE = 0 -FW_THIN = 100 -FW_EXTRALIGHT = 200 -FW_LIGHT = 300 -FW_NORMAL = 400 -FW_MEDIUM = 500 -FW_SEMIBOLD = 600 -FW_BOLD = 700 -FW_EXTRABOLD = 800 -FW_HEAVY = 900 -FW_ULTRALIGHT = FW_EXTRALIGHT -FW_REGULAR = FW_NORMAL -FW_DEMIBOLD = FW_SEMIBOLD -FW_ULTRABOLD = FW_EXTRABOLD -FW_BLACK = FW_HEAVY -# Generated by h2py from \msvcnt\include\wingdi.h -# hacked and split manually by mhammond. -BS_SOLID = 0 -BS_NULL = 1 -BS_HOLLOW = BS_NULL -BS_HATCHED = 2 -BS_PATTERN = 3 -BS_INDEXED = 4 -BS_DIBPATTERN = 5 -BS_DIBPATTERNPT = 6 -BS_PATTERN8X8 = 7 -BS_DIBPATTERN8X8 = 8 -HS_HORIZONTAL = 0 -HS_VERTICAL = 1 -HS_FDIAGONAL = 2 -HS_BDIAGONAL = 3 -HS_CROSS = 4 -HS_DIAGCROSS = 5 -HS_FDIAGONAL1 = 6 -HS_BDIAGONAL1 = 7 -HS_SOLID = 8 -HS_DENSE1 = 9 -HS_DENSE2 = 10 -HS_DENSE3 = 11 -HS_DENSE4 = 12 -HS_DENSE5 = 13 -HS_DENSE6 = 14 -HS_DENSE7 = 15 -HS_DENSE8 = 16 -HS_NOSHADE = 17 -HS_HALFTONE = 18 -HS_SOLIDCLR = 19 -HS_DITHEREDCLR = 20 -HS_SOLIDTEXTCLR = 21 -HS_DITHEREDTEXTCLR = 22 -HS_SOLIDBKCLR = 23 -HS_DITHEREDBKCLR = 24 -HS_API_MAX = 25 -PS_SOLID = 0 -PS_DASH = 1 -PS_DOT = 2 -PS_DASHDOT = 3 -PS_DASHDOTDOT = 4 -PS_NULL = 5 -PS_INSIDEFRAME = 6 -PS_USERSTYLE = 7 -PS_ALTERNATE = 8 -PS_STYLE_MASK = 15 -PS_ENDCAP_ROUND = 0 -PS_ENDCAP_SQUARE = 256 -PS_ENDCAP_FLAT = 512 -PS_ENDCAP_MASK = 3840 -PS_JOIN_ROUND = 0 -PS_JOIN_BEVEL = 4096 -PS_JOIN_MITER = 8192 -PS_JOIN_MASK = 61440 -PS_COSMETIC = 0 -PS_GEOMETRIC = 65536 -PS_TYPE_MASK = 983040 -AD_COUNTERCLOCKWISE = 1 -AD_CLOCKWISE = 2 -DRIVERVERSION = 0 -TECHNOLOGY = 2 -HORZSIZE = 4 -VERTSIZE = 6 -HORZRES = 8 -VERTRES = 10 -BITSPIXEL = 12 -PLANES = 14 -NUMBRUSHES = 16 -NUMPENS = 18 -NUMMARKERS = 20 -NUMFONTS = 22 -NUMCOLORS = 24 -PDEVICESIZE = 26 -CURVECAPS = 28 -LINECAPS = 30 -POLYGONALCAPS = 32 -TEXTCAPS = 34 -CLIPCAPS = 36 -RASTERCAPS = 38 -ASPECTX = 40 -ASPECTY = 42 -ASPECTXY = 44 -LOGPIXELSX = 88 -LOGPIXELSY = 90 -SIZEPALETTE = 104 -NUMRESERVED = 106 -COLORRES = 108 -DT_PLOTTER = 0 -DT_RASDISPLAY = 1 -DT_RASPRINTER = 2 -DT_RASCAMERA = 3 -DT_CHARSTREAM = 4 -DT_METAFILE = 5 -DT_DISPFILE = 6 -CC_NONE = 0 -CC_CIRCLES = 1 -CC_PIE = 2 -CC_CHORD = 4 -CC_ELLIPSES = 8 -CC_WIDE = 16 -CC_STYLED = 32 -CC_WIDESTYLED = 64 -CC_INTERIORS = 128 -CC_ROUNDRECT = 256 -LC_NONE = 0 -LC_POLYLINE = 2 -LC_MARKER = 4 -LC_POLYMARKER = 8 -LC_WIDE = 16 -LC_STYLED = 32 -LC_WIDESTYLED = 64 -LC_INTERIORS = 128 -PC_NONE = 0 -PC_POLYGON = 1 -PC_RECTANGLE = 2 -PC_WINDPOLYGON = 4 -PC_TRAPEZOID = 4 -PC_SCANLINE = 8 -PC_WIDE = 16 -PC_STYLED = 32 -PC_WIDESTYLED = 64 -PC_INTERIORS = 128 -CP_NONE = 0 -CP_RECTANGLE = 1 -CP_REGION = 2 -TC_OP_CHARACTER = 1 -TC_OP_STROKE = 2 -TC_CP_STROKE = 4 -TC_CR_90 = 8 -TC_CR_ANY = 16 -TC_SF_X_YINDEP = 32 -TC_SA_DOUBLE = 64 -TC_SA_INTEGER = 128 -TC_SA_CONTIN = 256 -TC_EA_DOUBLE = 512 -TC_IA_ABLE = 1024 -TC_UA_ABLE = 2048 -TC_SO_ABLE = 4096 -TC_RA_ABLE = 8192 -TC_VA_ABLE = 16384 -TC_RESERVED = 32768 -TC_SCROLLBLT = 65536 -RC_BITBLT = 1 -RC_BANDING = 2 -RC_SCALING = 4 -RC_BITMAP64 = 8 -RC_GDI20_OUTPUT = 16 -RC_GDI20_STATE = 32 -RC_SAVEBITMAP = 64 -RC_DI_BITMAP = 128 -RC_PALETTE = 256 -RC_DIBTODEV = 512 -RC_BIGFONT = 1024 -RC_STRETCHBLT = 2048 -RC_FLOODFILL = 4096 -RC_STRETCHDIB = 8192 -RC_OP_DX_OUTPUT = 16384 -RC_DEVBITS = 32768 -DIB_RGB_COLORS = 0 -DIB_PAL_COLORS = 1 -DIB_PAL_INDICES = 2 -DIB_PAL_PHYSINDICES = 2 -DIB_PAL_LOGINDICES = 4 -SYSPAL_ERROR = 0 -SYSPAL_STATIC = 1 -SYSPAL_NOSTATIC = 2 -CBM_CREATEDIB = 2 -CBM_INIT = 4 -FLOODFILLBORDER = 0 -FLOODFILLSURFACE = 1 -CCHDEVICENAME = 32 -CCHFORMNAME = 32 -# Generated by h2py from \msvcnt\include\wingdi.h -# hacked and split manually by mhammond. - -# DEVMODE.dmFields -DM_SPECVERSION = 800 -DM_ORIENTATION = 1 -DM_PAPERSIZE = 2 -DM_PAPERLENGTH = 4 -DM_PAPERWIDTH = 8 -DM_SCALE = 16 -DM_POSITION = 32 -DM_NUP = 64 -DM_DISPLAYORIENTATION = 128 -DM_COPIES = 256 -DM_DEFAULTSOURCE = 512 -DM_PRINTQUALITY = 1024 -DM_COLOR = 2048 -DM_DUPLEX = 4096 -DM_YRESOLUTION = 8192 -DM_TTOPTION = 16384 -DM_COLLATE = 32768 -DM_FORMNAME = 65536 -DM_LOGPIXELS = 131072 -DM_BITSPERPEL = 262144 -DM_PELSWIDTH = 524288 -DM_PELSHEIGHT = 1048576 -DM_DISPLAYFLAGS = 2097152 -DM_DISPLAYFREQUENCY = 4194304 -DM_ICMMETHOD = 8388608 -DM_ICMINTENT = 16777216 -DM_MEDIATYPE = 33554432 -DM_DITHERTYPE = 67108864 -DM_PANNINGWIDTH = 134217728 -DM_PANNINGHEIGHT = 268435456 -DM_DISPLAYFIXEDOUTPUT = 536870912 - -# DEVMODE.dmOrientation -DMORIENT_PORTRAIT = 1 -DMORIENT_LANDSCAPE = 2 - -# DEVMODE.dmDisplayOrientation -DMDO_DEFAULT = 0 -DMDO_90 = 1 -DMDO_180 = 2 -DMDO_270 = 3 - -# DEVMODE.dmDisplayFixedOutput -DMDFO_DEFAULT = 0 -DMDFO_STRETCH = 1 -DMDFO_CENTER = 2 - -# DEVMODE.dmPaperSize -DMPAPER_LETTER = 1 -DMPAPER_LETTERSMALL = 2 -DMPAPER_TABLOID = 3 -DMPAPER_LEDGER = 4 -DMPAPER_LEGAL = 5 -DMPAPER_STATEMENT = 6 -DMPAPER_EXECUTIVE = 7 -DMPAPER_A3 = 8 -DMPAPER_A4 = 9 -DMPAPER_A4SMALL = 10 -DMPAPER_A5 = 11 -DMPAPER_B4 = 12 -DMPAPER_B5 = 13 -DMPAPER_FOLIO = 14 -DMPAPER_QUARTO = 15 -DMPAPER_10X14 = 16 -DMPAPER_11X17 = 17 -DMPAPER_NOTE = 18 -DMPAPER_ENV_9 = 19 -DMPAPER_ENV_10 = 20 -DMPAPER_ENV_11 = 21 -DMPAPER_ENV_12 = 22 -DMPAPER_ENV_14 = 23 -DMPAPER_CSHEET = 24 -DMPAPER_DSHEET = 25 -DMPAPER_ESHEET = 26 -DMPAPER_ENV_DL = 27 -DMPAPER_ENV_C5 = 28 -DMPAPER_ENV_C3 = 29 -DMPAPER_ENV_C4 = 30 -DMPAPER_ENV_C6 = 31 -DMPAPER_ENV_C65 = 32 -DMPAPER_ENV_B4 = 33 -DMPAPER_ENV_B5 = 34 -DMPAPER_ENV_B6 = 35 -DMPAPER_ENV_ITALY = 36 -DMPAPER_ENV_MONARCH = 37 -DMPAPER_ENV_PERSONAL = 38 -DMPAPER_FANFOLD_US = 39 -DMPAPER_FANFOLD_STD_GERMAN = 40 -DMPAPER_FANFOLD_LGL_GERMAN = 41 -DMPAPER_ISO_B4 = 42 -DMPAPER_JAPANESE_POSTCARD = 43 -DMPAPER_9X11 = 44 -DMPAPER_10X11 = 45 -DMPAPER_15X11 = 46 -DMPAPER_ENV_INVITE = 47 -DMPAPER_RESERVED_48 = 48 -DMPAPER_RESERVED_49 = 49 -DMPAPER_LETTER_EXTRA = 50 -DMPAPER_LEGAL_EXTRA = 51 -DMPAPER_TABLOID_EXTRA = 52 -DMPAPER_A4_EXTRA = 53 -DMPAPER_LETTER_TRANSVERSE = 54 -DMPAPER_A4_TRANSVERSE = 55 -DMPAPER_LETTER_EXTRA_TRANSVERSE = 56 -DMPAPER_A_PLUS = 57 -DMPAPER_B_PLUS = 58 -DMPAPER_LETTER_PLUS = 59 -DMPAPER_A4_PLUS = 60 -DMPAPER_A5_TRANSVERSE = 61 -DMPAPER_B5_TRANSVERSE = 62 -DMPAPER_A3_EXTRA = 63 -DMPAPER_A5_EXTRA = 64 -DMPAPER_B5_EXTRA = 65 -DMPAPER_A2 = 66 -DMPAPER_A3_TRANSVERSE = 67 -DMPAPER_A3_EXTRA_TRANSVERSE = 68 -DMPAPER_DBL_JAPANESE_POSTCARD = 69 -DMPAPER_A6 = 70 -DMPAPER_JENV_KAKU2 = 71 -DMPAPER_JENV_KAKU3 = 72 -DMPAPER_JENV_CHOU3 = 73 -DMPAPER_JENV_CHOU4 = 74 -DMPAPER_LETTER_ROTATED = 75 -DMPAPER_A3_ROTATED = 76 -DMPAPER_A4_ROTATED = 77 -DMPAPER_A5_ROTATED = 78 -DMPAPER_B4_JIS_ROTATED = 79 -DMPAPER_B5_JIS_ROTATED = 80 -DMPAPER_JAPANESE_POSTCARD_ROTATED = 81 -DMPAPER_DBL_JAPANESE_POSTCARD_ROTATED = 82 -DMPAPER_A6_ROTATED = 83 -DMPAPER_JENV_KAKU2_ROTATED = 84 -DMPAPER_JENV_KAKU3_ROTATED = 85 -DMPAPER_JENV_CHOU3_ROTATED = 86 -DMPAPER_JENV_CHOU4_ROTATED = 87 -DMPAPER_B6_JIS = 88 -DMPAPER_B6_JIS_ROTATED = 89 -DMPAPER_12X11 = 90 -DMPAPER_JENV_YOU4 = 91 -DMPAPER_JENV_YOU4_ROTATED = 92 -DMPAPER_P16K = 93 -DMPAPER_P32K = 94 -DMPAPER_P32KBIG = 95 -DMPAPER_PENV_1 = 96 -DMPAPER_PENV_2 = 97 -DMPAPER_PENV_3 = 98 -DMPAPER_PENV_4 = 99 -DMPAPER_PENV_5 = 100 -DMPAPER_PENV_6 = 101 -DMPAPER_PENV_7 = 102 -DMPAPER_PENV_8 = 103 -DMPAPER_PENV_9 = 104 -DMPAPER_PENV_10 = 105 -DMPAPER_P16K_ROTATED = 106 -DMPAPER_P32K_ROTATED = 107 -DMPAPER_P32KBIG_ROTATED = 108 -DMPAPER_PENV_1_ROTATED = 109 -DMPAPER_PENV_2_ROTATED = 110 -DMPAPER_PENV_3_ROTATED = 111 -DMPAPER_PENV_4_ROTATED = 112 -DMPAPER_PENV_5_ROTATED = 113 -DMPAPER_PENV_6_ROTATED = 114 -DMPAPER_PENV_7_ROTATED = 115 -DMPAPER_PENV_8_ROTATED = 116 -DMPAPER_PENV_9_ROTATED = 117 -DMPAPER_PENV_10_ROTATED = 118 -DMPAPER_LAST = DMPAPER_PENV_10_ROTATED -DMPAPER_USER = 256 - -# DEVMODE.dmDefaultSource -DMBIN_UPPER = 1 -DMBIN_ONLYONE = 1 -DMBIN_LOWER = 2 -DMBIN_MIDDLE = 3 -DMBIN_MANUAL = 4 -DMBIN_ENVELOPE = 5 -DMBIN_ENVMANUAL = 6 -DMBIN_AUTO = 7 -DMBIN_TRACTOR = 8 -DMBIN_SMALLFMT = 9 -DMBIN_LARGEFMT = 10 -DMBIN_LARGECAPACITY = 11 -DMBIN_CASSETTE = 14 -DMBIN_LAST = DMBIN_CASSETTE -DMBIN_USER = 256 - -# DEVMODE.dmPrintQuality -DMRES_DRAFT = (-1) -DMRES_LOW = (-2) -DMRES_MEDIUM = (-3) -DMRES_HIGH = (-4) - -# DEVMODE.dmColor -DMCOLOR_MONOCHROME = 1 -DMCOLOR_COLOR = 2 - -# DEVMODE.dmDuplex -DMDUP_SIMPLEX = 1 -DMDUP_VERTICAL = 2 -DMDUP_HORIZONTAL = 3 - -# DEVMODE.dmTTOption -DMTT_BITMAP = 1 -DMTT_DOWNLOAD = 2 -DMTT_SUBDEV = 3 -DMTT_DOWNLOAD_OUTLINE = 4 - -# DEVMODE.dmCollate -DMCOLLATE_FALSE = 0 -DMCOLLATE_TRUE = 1 - -# DEVMODE.dmDisplayFlags -DM_GRAYSCALE = 1 -DM_INTERLACED = 2 - -# DEVMODE.dmICMMethod -DMICMMETHOD_NONE = 1 -DMICMMETHOD_SYSTEM = 2 -DMICMMETHOD_DRIVER = 3 -DMICMMETHOD_DEVICE = 4 -DMICMMETHOD_USER = 256 - -# DEVMODE.dmICMIntent -DMICM_SATURATE = 1 -DMICM_CONTRAST = 2 -DMICM_COLORIMETRIC = 3 -DMICM_ABS_COLORIMETRIC = 4 -DMICM_USER = 256 - -# DEVMODE.dmMediaType -DMMEDIA_STANDARD = 1 -DMMEDIA_TRANSPARENCY = 2 -DMMEDIA_GLOSSY = 3 -DMMEDIA_USER = 256 - -# DEVMODE.dmDitherType -DMDITHER_NONE = 1 -DMDITHER_COARSE = 2 -DMDITHER_FINE = 3 -DMDITHER_LINEART = 4 -DMDITHER_ERRORDIFFUSION = 5 -DMDITHER_RESERVED6 = 6 -DMDITHER_RESERVED7 = 7 -DMDITHER_RESERVED8 = 8 -DMDITHER_RESERVED9 = 9 -DMDITHER_GRAYSCALE = 10 -DMDITHER_USER = 256 - -# DEVMODE.dmNup -DMNUP_SYSTEM = 1 -DMNUP_ONEUP = 2 - -RDH_RECTANGLES = 1 -GGO_METRICS = 0 -GGO_BITMAP = 1 -GGO_NATIVE = 2 -TT_POLYGON_TYPE = 24 -TT_PRIM_LINE = 1 -TT_PRIM_QSPLINE = 2 -TT_AVAILABLE = 1 -TT_ENABLED = 2 -DM_UPDATE = 1 -DM_COPY = 2 -DM_PROMPT = 4 -DM_MODIFY = 8 -DM_IN_BUFFER = DM_MODIFY -DM_IN_PROMPT = DM_PROMPT -DM_OUT_BUFFER = DM_COPY -DM_OUT_DEFAULT = DM_UPDATE - -# DISPLAY_DEVICE.StateFlags -DISPLAY_DEVICE_ATTACHED_TO_DESKTOP = 1 -DISPLAY_DEVICE_MULTI_DRIVER = 2 -DISPLAY_DEVICE_PRIMARY_DEVICE = 4 -DISPLAY_DEVICE_MIRRORING_DRIVER = 8 -DISPLAY_DEVICE_VGA_COMPATIBLE = 16 -DISPLAY_DEVICE_REMOVABLE = 32 -DISPLAY_DEVICE_MODESPRUNED = 134217728 -DISPLAY_DEVICE_REMOTE = 67108864 -DISPLAY_DEVICE_DISCONNECT = 33554432 - -# DeviceCapabilities types -DC_FIELDS = 1 -DC_PAPERS = 2 -DC_PAPERSIZE = 3 -DC_MINEXTENT = 4 -DC_MAXEXTENT = 5 -DC_BINS = 6 -DC_DUPLEX = 7 -DC_SIZE = 8 -DC_EXTRA = 9 -DC_VERSION = 10 -DC_DRIVER = 11 -DC_BINNAMES = 12 -DC_ENUMRESOLUTIONS = 13 -DC_FILEDEPENDENCIES = 14 -DC_TRUETYPE = 15 -DC_PAPERNAMES = 16 -DC_ORIENTATION = 17 -DC_COPIES = 18 -DC_BINADJUST = 19 -DC_EMF_COMPLIANT = 20 -DC_DATATYPE_PRODUCED = 21 -DC_COLLATE = 22 -DC_MANUFACTURER = 23 -DC_MODEL = 24 -DC_PERSONALITY = 25 -DC_PRINTRATE = 26 -DC_PRINTRATEUNIT = 27 -DC_PRINTERMEM = 28 -DC_MEDIAREADY = 29 -DC_STAPLE = 30 -DC_PRINTRATEPPM = 31 -DC_COLORDEVICE = 32 -DC_NUP = 33 -DC_MEDIATYPENAMES = 34 -DC_MEDIATYPES = 35 - -PRINTRATEUNIT_PPM = 1 -PRINTRATEUNIT_CPS = 2 -PRINTRATEUNIT_LPM = 3 -PRINTRATEUNIT_IPM = 4 - -# TrueType constants -DCTT_BITMAP = 1 -DCTT_DOWNLOAD = 2 -DCTT_SUBDEV = 4 -DCTT_DOWNLOAD_OUTLINE = 8 - -CA_NEGATIVE = 1 -CA_LOG_FILTER = 2 -ILLUMINANT_DEVICE_DEFAULT = 0 -ILLUMINANT_A = 1 -ILLUMINANT_B = 2 -ILLUMINANT_C = 3 -ILLUMINANT_D50 = 4 -ILLUMINANT_D55 = 5 -ILLUMINANT_D65 = 6 -ILLUMINANT_D75 = 7 -ILLUMINANT_F2 = 8 -ILLUMINANT_MAX_INDEX = ILLUMINANT_F2 -ILLUMINANT_TUNGSTEN = ILLUMINANT_A -ILLUMINANT_DAYLIGHT = ILLUMINANT_C -ILLUMINANT_FLUORESCENT = ILLUMINANT_F2 -ILLUMINANT_NTSC = ILLUMINANT_C - -# Generated by h2py from \msvcnt\include\wingdi.h -# hacked and split manually by mhammond. -FONTMAPPER_MAX = 10 -ENHMETA_SIGNATURE = 1179469088 -ENHMETA_STOCK_OBJECT = -2147483648 -EMR_HEADER = 1 -EMR_POLYBEZIER = 2 -EMR_POLYGON = 3 -EMR_POLYLINE = 4 -EMR_POLYBEZIERTO = 5 -EMR_POLYLINETO = 6 -EMR_POLYPOLYLINE = 7 -EMR_POLYPOLYGON = 8 -EMR_SETWINDOWEXTEX = 9 -EMR_SETWINDOWORGEX = 10 -EMR_SETVIEWPORTEXTEX = 11 -EMR_SETVIEWPORTORGEX = 12 -EMR_SETBRUSHORGEX = 13 -EMR_EOF = 14 -EMR_SETPIXELV = 15 -EMR_SETMAPPERFLAGS = 16 -EMR_SETMAPMODE = 17 -EMR_SETBKMODE = 18 -EMR_SETPOLYFILLMODE = 19 -EMR_SETROP2 = 20 -EMR_SETSTRETCHBLTMODE = 21 -EMR_SETTEXTALIGN = 22 -EMR_SETCOLORADJUSTMENT = 23 -EMR_SETTEXTCOLOR = 24 -EMR_SETBKCOLOR = 25 -EMR_OFFSETCLIPRGN = 26 -EMR_MOVETOEX = 27 -EMR_SETMETARGN = 28 -EMR_EXCLUDECLIPRECT = 29 -EMR_INTERSECTCLIPRECT = 30 -EMR_SCALEVIEWPORTEXTEX = 31 -EMR_SCALEWINDOWEXTEX = 32 -EMR_SAVEDC = 33 -EMR_RESTOREDC = 34 -EMR_SETWORLDTRANSFORM = 35 -EMR_MODIFYWORLDTRANSFORM = 36 -EMR_SELECTOBJECT = 37 -EMR_CREATEPEN = 38 -EMR_CREATEBRUSHINDIRECT = 39 -EMR_DELETEOBJECT = 40 -EMR_ANGLEARC = 41 -EMR_ELLIPSE = 42 -EMR_RECTANGLE = 43 -EMR_ROUNDRECT = 44 -EMR_ARC = 45 -EMR_CHORD = 46 -EMR_PIE = 47 -EMR_SELECTPALETTE = 48 -EMR_CREATEPALETTE = 49 -EMR_SETPALETTEENTRIES = 50 -EMR_RESIZEPALETTE = 51 -EMR_REALIZEPALETTE = 52 -EMR_EXTFLOODFILL = 53 -EMR_LINETO = 54 -EMR_ARCTO = 55 -EMR_POLYDRAW = 56 -EMR_SETARCDIRECTION = 57 -EMR_SETMITERLIMIT = 58 -EMR_BEGINPATH = 59 -EMR_ENDPATH = 60 -EMR_CLOSEFIGURE = 61 -EMR_FILLPATH = 62 -EMR_STROKEANDFILLPATH = 63 -EMR_STROKEPATH = 64 -EMR_FLATTENPATH = 65 -EMR_WIDENPATH = 66 -EMR_SELECTCLIPPATH = 67 -EMR_ABORTPATH = 68 -EMR_GDICOMMENT = 70 -EMR_FILLRGN = 71 -EMR_FRAMERGN = 72 -EMR_INVERTRGN = 73 -EMR_PAINTRGN = 74 -EMR_EXTSELECTCLIPRGN = 75 -EMR_BITBLT = 76 -EMR_STRETCHBLT = 77 -EMR_MASKBLT = 78 -EMR_PLGBLT = 79 -EMR_SETDIBITSTODEVICE = 80 -EMR_STRETCHDIBITS = 81 -EMR_EXTCREATEFONTINDIRECTW = 82 -EMR_EXTTEXTOUTA = 83 -EMR_EXTTEXTOUTW = 84 -EMR_POLYBEZIER16 = 85 -EMR_POLYGON16 = 86 -EMR_POLYLINE16 = 87 -EMR_POLYBEZIERTO16 = 88 -EMR_POLYLINETO16 = 89 -EMR_POLYPOLYLINE16 = 90 -EMR_POLYPOLYGON16 = 91 -EMR_POLYDRAW16 = 92 -EMR_CREATEMONOBRUSH = 93 -EMR_CREATEDIBPATTERNBRUSHPT = 94 -EMR_EXTCREATEPEN = 95 -EMR_POLYTEXTOUTA = 96 -EMR_POLYTEXTOUTW = 97 -EMR_MIN = 1 -EMR_MAX = 97 -# Generated by h2py from \msvcnt\include\wingdi.h -# hacked and split manually by mhammond. -PANOSE_COUNT = 10 -PAN_FAMILYTYPE_INDEX = 0 -PAN_SERIFSTYLE_INDEX = 1 -PAN_WEIGHT_INDEX = 2 -PAN_PROPORTION_INDEX = 3 -PAN_CONTRAST_INDEX = 4 -PAN_STROKEVARIATION_INDEX = 5 -PAN_ARMSTYLE_INDEX = 6 -PAN_LETTERFORM_INDEX = 7 -PAN_MIDLINE_INDEX = 8 -PAN_XHEIGHT_INDEX = 9 -PAN_CULTURE_LATIN = 0 -PAN_ANY = 0 -PAN_NO_FIT = 1 -PAN_FAMILY_TEXT_DISPLAY = 2 -PAN_FAMILY_SCRIPT = 3 -PAN_FAMILY_DECORATIVE = 4 -PAN_FAMILY_PICTORIAL = 5 -PAN_SERIF_COVE = 2 -PAN_SERIF_OBTUSE_COVE = 3 -PAN_SERIF_SQUARE_COVE = 4 -PAN_SERIF_OBTUSE_SQUARE_COVE = 5 -PAN_SERIF_SQUARE = 6 -PAN_SERIF_THIN = 7 -PAN_SERIF_BONE = 8 -PAN_SERIF_EXAGGERATED = 9 -PAN_SERIF_TRIANGLE = 10 -PAN_SERIF_NORMAL_SANS = 11 -PAN_SERIF_OBTUSE_SANS = 12 -PAN_SERIF_PERP_SANS = 13 -PAN_SERIF_FLARED = 14 -PAN_SERIF_ROUNDED = 15 -PAN_WEIGHT_VERY_LIGHT = 2 -PAN_WEIGHT_LIGHT = 3 -PAN_WEIGHT_THIN = 4 -PAN_WEIGHT_BOOK = 5 -PAN_WEIGHT_MEDIUM = 6 -PAN_WEIGHT_DEMI = 7 -PAN_WEIGHT_BOLD = 8 -PAN_WEIGHT_HEAVY = 9 -PAN_WEIGHT_BLACK = 10 -PAN_WEIGHT_NORD = 11 -PAN_PROP_OLD_STYLE = 2 -PAN_PROP_MODERN = 3 -PAN_PROP_EVEN_WIDTH = 4 -PAN_PROP_EXPANDED = 5 -PAN_PROP_CONDENSED = 6 -PAN_PROP_VERY_EXPANDED = 7 -PAN_PROP_VERY_CONDENSED = 8 -PAN_PROP_MONOSPACED = 9 -PAN_CONTRAST_NONE = 2 -PAN_CONTRAST_VERY_LOW = 3 -PAN_CONTRAST_LOW = 4 -PAN_CONTRAST_MEDIUM_LOW = 5 -PAN_CONTRAST_MEDIUM = 6 -PAN_CONTRAST_MEDIUM_HIGH = 7 -PAN_CONTRAST_HIGH = 8 -PAN_CONTRAST_VERY_HIGH = 9 -PAN_STROKE_GRADUAL_DIAG = 2 -PAN_STROKE_GRADUAL_TRAN = 3 -PAN_STROKE_GRADUAL_VERT = 4 -PAN_STROKE_GRADUAL_HORZ = 5 -PAN_STROKE_RAPID_VERT = 6 -PAN_STROKE_RAPID_HORZ = 7 -PAN_STROKE_INSTANT_VERT = 8 -PAN_STRAIGHT_ARMS_HORZ = 2 -PAN_STRAIGHT_ARMS_WEDGE = 3 -PAN_STRAIGHT_ARMS_VERT = 4 -PAN_STRAIGHT_ARMS_SINGLE_SERIF = 5 -PAN_STRAIGHT_ARMS_DOUBLE_SERIF = 6 -PAN_BENT_ARMS_HORZ = 7 -PAN_BENT_ARMS_WEDGE = 8 -PAN_BENT_ARMS_VERT = 9 -PAN_BENT_ARMS_SINGLE_SERIF = 10 -PAN_BENT_ARMS_DOUBLE_SERIF = 11 -PAN_LETT_NORMAL_CONTACT = 2 -PAN_LETT_NORMAL_WEIGHTED = 3 -PAN_LETT_NORMAL_BOXED = 4 -PAN_LETT_NORMAL_FLATTENED = 5 -PAN_LETT_NORMAL_ROUNDED = 6 -PAN_LETT_NORMAL_OFF_CENTER = 7 -PAN_LETT_NORMAL_SQUARE = 8 -PAN_LETT_OBLIQUE_CONTACT = 9 -PAN_LETT_OBLIQUE_WEIGHTED = 10 -PAN_LETT_OBLIQUE_BOXED = 11 -PAN_LETT_OBLIQUE_FLATTENED = 12 -PAN_LETT_OBLIQUE_ROUNDED = 13 -PAN_LETT_OBLIQUE_OFF_CENTER = 14 -PAN_LETT_OBLIQUE_SQUARE = 15 -PAN_MIDLINE_STANDARD_TRIMMED = 2 -PAN_MIDLINE_STANDARD_POINTED = 3 -PAN_MIDLINE_STANDARD_SERIFED = 4 -PAN_MIDLINE_HIGH_TRIMMED = 5 -PAN_MIDLINE_HIGH_POINTED = 6 -PAN_MIDLINE_HIGH_SERIFED = 7 -PAN_MIDLINE_CONSTANT_TRIMMED = 8 -PAN_MIDLINE_CONSTANT_POINTED = 9 -PAN_MIDLINE_CONSTANT_SERIFED = 10 -PAN_MIDLINE_LOW_TRIMMED = 11 -PAN_MIDLINE_LOW_POINTED = 12 -PAN_MIDLINE_LOW_SERIFED = 13 -PAN_XHEIGHT_CONSTANT_SMALL = 2 -PAN_XHEIGHT_CONSTANT_STD = 3 -PAN_XHEIGHT_CONSTANT_LARGE = 4 -PAN_XHEIGHT_DUCKING_SMALL = 5 -PAN_XHEIGHT_DUCKING_STD = 6 -PAN_XHEIGHT_DUCKING_LARGE = 7 -ELF_VENDOR_SIZE = 4 -ELF_VERSION = 0 -ELF_CULTURE_LATIN = 0 -RASTER_FONTTYPE = 1 -DEVICE_FONTTYPE = 2 -TRUETYPE_FONTTYPE = 4 -def PALETTEINDEX(i): return ((16777216 | (i))) - -PC_RESERVED = 1 -PC_EXPLICIT = 2 -PC_NOCOLLAPSE = 4 -def GetRValue(rgb): return rgb & 0xff - -def GetGValue(rgb): return (rgb >> 8) & 0xff - -def GetBValue(rgb): return (rgb >> 16) & 0xff - -TRANSPARENT = 1 -OPAQUE = 2 -BKMODE_LAST = 2 -GM_COMPATIBLE = 1 -GM_ADVANCED = 2 -GM_LAST = 2 -PT_CLOSEFIGURE = 1 -PT_LINETO = 2 -PT_BEZIERTO = 4 -PT_MOVETO = 6 -MM_TEXT = 1 -MM_LOMETRIC = 2 -MM_HIMETRIC = 3 -MM_LOENGLISH = 4 -MM_HIENGLISH = 5 -MM_TWIPS = 6 -MM_ISOTROPIC = 7 -MM_ANISOTROPIC = 8 -MM_MIN = MM_TEXT -MM_MAX = MM_ANISOTROPIC -MM_MAX_FIXEDSCALE = MM_TWIPS -ABSOLUTE = 1 -RELATIVE = 2 -WHITE_BRUSH = 0 -LTGRAY_BRUSH = 1 -GRAY_BRUSH = 2 -DKGRAY_BRUSH = 3 -BLACK_BRUSH = 4 -NULL_BRUSH = 5 -HOLLOW_BRUSH = NULL_BRUSH -WHITE_PEN = 6 -BLACK_PEN = 7 -NULL_PEN = 8 -OEM_FIXED_FONT = 10 -ANSI_FIXED_FONT = 11 -ANSI_VAR_FONT = 12 -SYSTEM_FONT = 13 -DEVICE_DEFAULT_FONT = 14 -DEFAULT_PALETTE = 15 -SYSTEM_FIXED_FONT = 16 -STOCK_LAST = 16 -CLR_INVALID = -1 - -# Exception/Status codes from winuser.h and winnt.h -STATUS_WAIT_0 = 0 -STATUS_ABANDONED_WAIT_0 = 128 -STATUS_USER_APC = 192 -STATUS_TIMEOUT = 258 -STATUS_PENDING = 259 -STATUS_SEGMENT_NOTIFICATION = 1073741829 -STATUS_GUARD_PAGE_VIOLATION = -2147483647 -STATUS_DATATYPE_MISALIGNMENT = -2147483646 -STATUS_BREAKPOINT = -2147483645 -STATUS_SINGLE_STEP = -2147483644 -STATUS_ACCESS_VIOLATION = -1073741819 -STATUS_IN_PAGE_ERROR = -1073741818 -STATUS_INVALID_HANDLE = -1073741816 -STATUS_NO_MEMORY = -1073741801 -STATUS_ILLEGAL_INSTRUCTION = -1073741795 -STATUS_NONCONTINUABLE_EXCEPTION = -1073741787 -STATUS_INVALID_DISPOSITION = -1073741786 -STATUS_ARRAY_BOUNDS_EXCEEDED = -1073741684 -STATUS_FLOAT_DENORMAL_OPERAND = -1073741683 -STATUS_FLOAT_DIVIDE_BY_ZERO = -1073741682 -STATUS_FLOAT_INEXACT_RESULT = -1073741681 -STATUS_FLOAT_INVALID_OPERATION = -1073741680 -STATUS_FLOAT_OVERFLOW = -1073741679 -STATUS_FLOAT_STACK_CHECK = -1073741678 -STATUS_FLOAT_UNDERFLOW = -1073741677 -STATUS_INTEGER_DIVIDE_BY_ZERO = -1073741676 -STATUS_INTEGER_OVERFLOW = -1073741675 -STATUS_PRIVILEGED_INSTRUCTION = -1073741674 -STATUS_STACK_OVERFLOW = -1073741571 -STATUS_CONTROL_C_EXIT = -1073741510 - - -WAIT_FAILED = -1 -WAIT_OBJECT_0 = STATUS_WAIT_0 + 0 - -WAIT_ABANDONED = STATUS_ABANDONED_WAIT_0 + 0 -WAIT_ABANDONED_0 = STATUS_ABANDONED_WAIT_0 + 0 - -WAIT_TIMEOUT = STATUS_TIMEOUT -WAIT_IO_COMPLETION = STATUS_USER_APC -STILL_ACTIVE = STATUS_PENDING -EXCEPTION_ACCESS_VIOLATION = STATUS_ACCESS_VIOLATION -EXCEPTION_DATATYPE_MISALIGNMENT = STATUS_DATATYPE_MISALIGNMENT -EXCEPTION_BREAKPOINT = STATUS_BREAKPOINT -EXCEPTION_SINGLE_STEP = STATUS_SINGLE_STEP -EXCEPTION_ARRAY_BOUNDS_EXCEEDED = STATUS_ARRAY_BOUNDS_EXCEEDED -EXCEPTION_FLT_DENORMAL_OPERAND = STATUS_FLOAT_DENORMAL_OPERAND -EXCEPTION_FLT_DIVIDE_BY_ZERO = STATUS_FLOAT_DIVIDE_BY_ZERO -EXCEPTION_FLT_INEXACT_RESULT = STATUS_FLOAT_INEXACT_RESULT -EXCEPTION_FLT_INVALID_OPERATION = STATUS_FLOAT_INVALID_OPERATION -EXCEPTION_FLT_OVERFLOW = STATUS_FLOAT_OVERFLOW -EXCEPTION_FLT_STACK_CHECK = STATUS_FLOAT_STACK_CHECK -EXCEPTION_FLT_UNDERFLOW = STATUS_FLOAT_UNDERFLOW -EXCEPTION_INT_DIVIDE_BY_ZERO = STATUS_INTEGER_DIVIDE_BY_ZERO -EXCEPTION_INT_OVERFLOW = STATUS_INTEGER_OVERFLOW -EXCEPTION_PRIV_INSTRUCTION = STATUS_PRIVILEGED_INSTRUCTION -EXCEPTION_IN_PAGE_ERROR = STATUS_IN_PAGE_ERROR -EXCEPTION_ILLEGAL_INSTRUCTION = STATUS_ILLEGAL_INSTRUCTION -EXCEPTION_NONCONTINUABLE_EXCEPTION = STATUS_NONCONTINUABLE_EXCEPTION -EXCEPTION_STACK_OVERFLOW = STATUS_STACK_OVERFLOW -EXCEPTION_INVALID_DISPOSITION = STATUS_INVALID_DISPOSITION -EXCEPTION_GUARD_PAGE = STATUS_GUARD_PAGE_VIOLATION -EXCEPTION_INVALID_HANDLE = STATUS_INVALID_HANDLE -CONTROL_C_EXIT = STATUS_CONTROL_C_EXIT - -# winuser.h line 8594 -# constants used with SystemParametersInfo -SPI_GETBEEP = 1 -SPI_SETBEEP = 2 -SPI_GETMOUSE = 3 -SPI_SETMOUSE = 4 -SPI_GETBORDER = 5 -SPI_SETBORDER = 6 -SPI_GETKEYBOARDSPEED = 10 -SPI_SETKEYBOARDSPEED = 11 -SPI_LANGDRIVER = 12 -SPI_ICONHORIZONTALSPACING = 13 -SPI_GETSCREENSAVETIMEOUT = 14 -SPI_SETSCREENSAVETIMEOUT = 15 -SPI_GETSCREENSAVEACTIVE = 16 -SPI_SETSCREENSAVEACTIVE = 17 -SPI_GETGRIDGRANULARITY = 18 -SPI_SETGRIDGRANULARITY = 19 -SPI_SETDESKWALLPAPER = 20 -SPI_SETDESKPATTERN = 21 -SPI_GETKEYBOARDDELAY = 22 -SPI_SETKEYBOARDDELAY = 23 -SPI_ICONVERTICALSPACING = 24 -SPI_GETICONTITLEWRAP = 25 -SPI_SETICONTITLEWRAP = 26 -SPI_GETMENUDROPALIGNMENT = 27 -SPI_SETMENUDROPALIGNMENT = 28 -SPI_SETDOUBLECLKWIDTH = 29 -SPI_SETDOUBLECLKHEIGHT = 30 -SPI_GETICONTITLELOGFONT = 31 -SPI_SETDOUBLECLICKTIME = 32 -SPI_SETMOUSEBUTTONSWAP = 33 -SPI_SETICONTITLELOGFONT = 34 -SPI_GETFASTTASKSWITCH = 35 -SPI_SETFASTTASKSWITCH = 36 -SPI_SETDRAGFULLWINDOWS = 37 -SPI_GETDRAGFULLWINDOWS = 38 -SPI_GETNONCLIENTMETRICS = 41 -SPI_SETNONCLIENTMETRICS = 42 -SPI_GETMINIMIZEDMETRICS = 43 -SPI_SETMINIMIZEDMETRICS = 44 -SPI_GETICONMETRICS = 45 -SPI_SETICONMETRICS = 46 -SPI_SETWORKAREA = 47 -SPI_GETWORKAREA = 48 -SPI_SETPENWINDOWS = 49 -SPI_GETFILTERKEYS = 50 -SPI_SETFILTERKEYS = 51 -SPI_GETTOGGLEKEYS = 52 -SPI_SETTOGGLEKEYS = 53 -SPI_GETMOUSEKEYS = 54 -SPI_SETMOUSEKEYS = 55 -SPI_GETSHOWSOUNDS = 56 -SPI_SETSHOWSOUNDS = 57 -SPI_GETSTICKYKEYS = 58 -SPI_SETSTICKYKEYS = 59 -SPI_GETACCESSTIMEOUT = 60 -SPI_SETACCESSTIMEOUT = 61 -SPI_GETSERIALKEYS = 62 -SPI_SETSERIALKEYS = 63 -SPI_GETSOUNDSENTRY = 64 -SPI_SETSOUNDSENTRY = 65 -SPI_GETHIGHCONTRAST = 66 -SPI_SETHIGHCONTRAST = 67 -SPI_GETKEYBOARDPREF = 68 -SPI_SETKEYBOARDPREF = 69 -SPI_GETSCREENREADER = 70 -SPI_SETSCREENREADER = 71 -SPI_GETANIMATION = 72 -SPI_SETANIMATION = 73 -SPI_GETFONTSMOOTHING = 74 -SPI_SETFONTSMOOTHING = 75 -SPI_SETDRAGWIDTH = 76 -SPI_SETDRAGHEIGHT = 77 -SPI_SETHANDHELD = 78 -SPI_GETLOWPOWERTIMEOUT = 79 -SPI_GETPOWEROFFTIMEOUT = 80 -SPI_SETLOWPOWERTIMEOUT = 81 -SPI_SETPOWEROFFTIMEOUT = 82 -SPI_GETLOWPOWERACTIVE = 83 -SPI_GETPOWEROFFACTIVE = 84 -SPI_SETLOWPOWERACTIVE = 85 -SPI_SETPOWEROFFACTIVE = 86 -SPI_SETCURSORS = 87 -SPI_SETICONS = 88 -SPI_GETDEFAULTINPUTLANG = 89 -SPI_SETDEFAULTINPUTLANG = 90 -SPI_SETLANGTOGGLE = 91 -SPI_GETWINDOWSEXTENSION = 92 -SPI_SETMOUSETRAILS = 93 -SPI_GETMOUSETRAILS = 94 -SPI_GETSNAPTODEFBUTTON = 95 -SPI_SETSNAPTODEFBUTTON = 96 -SPI_SETSCREENSAVERRUNNING = 97 -SPI_SCREENSAVERRUNNING = SPI_SETSCREENSAVERRUNNING -SPI_GETMOUSEHOVERWIDTH = 98 -SPI_SETMOUSEHOVERWIDTH = 99 -SPI_GETMOUSEHOVERHEIGHT = 100 -SPI_SETMOUSEHOVERHEIGHT = 101 -SPI_GETMOUSEHOVERTIME = 102 -SPI_SETMOUSEHOVERTIME = 103 -SPI_GETWHEELSCROLLLINES = 104 -SPI_SETWHEELSCROLLLINES = 105 -SPI_GETMENUSHOWDELAY = 106 -SPI_SETMENUSHOWDELAY = 107 - -SPI_GETSHOWIMEUI = 110 -SPI_SETSHOWIMEUI = 111 -SPI_GETMOUSESPEED = 112 -SPI_SETMOUSESPEED = 113 -SPI_GETSCREENSAVERRUNNING = 114 -SPI_GETDESKWALLPAPER = 115 - -SPI_GETACTIVEWINDOWTRACKING = 4096 -SPI_SETACTIVEWINDOWTRACKING = 4097 -SPI_GETMENUANIMATION = 4098 -SPI_SETMENUANIMATION = 4099 -SPI_GETCOMBOBOXANIMATION = 4100 -SPI_SETCOMBOBOXANIMATION = 4101 -SPI_GETLISTBOXSMOOTHSCROLLING = 4102 -SPI_SETLISTBOXSMOOTHSCROLLING = 4103 -SPI_GETGRADIENTCAPTIONS = 4104 -SPI_SETGRADIENTCAPTIONS = 4105 -SPI_GETKEYBOARDCUES = 4106 -SPI_SETKEYBOARDCUES = 4107 -SPI_GETMENUUNDERLINES = 4106 -SPI_SETMENUUNDERLINES = 4107 -SPI_GETACTIVEWNDTRKZORDER = 4108 -SPI_SETACTIVEWNDTRKZORDER = 4109 -SPI_GETHOTTRACKING = 4110 -SPI_SETHOTTRACKING = 4111 - -SPI_GETMENUFADE = 4114 -SPI_SETMENUFADE = 4115 -SPI_GETSELECTIONFADE = 4116 -SPI_SETSELECTIONFADE = 4117 -SPI_GETTOOLTIPANIMATION = 4118 -SPI_SETTOOLTIPANIMATION = 4119 -SPI_GETTOOLTIPFADE = 4120 -SPI_SETTOOLTIPFADE = 4121 -SPI_GETCURSORSHADOW = 4122 -SPI_SETCURSORSHADOW = 4123 -SPI_GETMOUSESONAR = 4124 -SPI_SETMOUSESONAR = 4125 -SPI_GETMOUSECLICKLOCK = 4126 -SPI_SETMOUSECLICKLOCK = 4127 -SPI_GETMOUSEVANISH = 4128 -SPI_SETMOUSEVANISH = 4129 -SPI_GETFLATMENU = 4130 -SPI_SETFLATMENU = 4131 -SPI_GETDROPSHADOW = 4132 -SPI_SETDROPSHADOW = 4133 -SPI_GETBLOCKSENDINPUTRESETS = 4134 -SPI_SETBLOCKSENDINPUTRESETS = 4135 -SPI_GETUIEFFECTS = 4158 -SPI_SETUIEFFECTS = 4159 - -SPI_GETFOREGROUNDLOCKTIMEOUT = 8192 -SPI_SETFOREGROUNDLOCKTIMEOUT = 8193 -SPI_GETACTIVEWNDTRKTIMEOUT = 8194 -SPI_SETACTIVEWNDTRKTIMEOUT = 8195 -SPI_GETFOREGROUNDFLASHCOUNT = 8196 -SPI_SETFOREGROUNDFLASHCOUNT = 8197 -SPI_GETCARETWIDTH = 8198 -SPI_SETCARETWIDTH = 8199 -SPI_GETMOUSECLICKLOCKTIME = 8200 -SPI_SETMOUSECLICKLOCKTIME = 8201 -SPI_GETFONTSMOOTHINGTYPE = 8202 -SPI_SETFONTSMOOTHINGTYPE = 8203 -SPI_GETFONTSMOOTHINGCONTRAST = 8204 -SPI_SETFONTSMOOTHINGCONTRAST = 8205 -SPI_GETFOCUSBORDERWIDTH = 8206 -SPI_SETFOCUSBORDERWIDTH = 8207 -SPI_GETFOCUSBORDERHEIGHT = 8208 -SPI_SETFOCUSBORDERHEIGHT = 8209 -SPI_GETFONTSMOOTHINGORIENTATION = 8210 -SPI_SETFONTSMOOTHINGORIENTATION = 8211 - -# fWinIni flags for SystemParametersInfo -SPIF_UPDATEINIFILE = 1 -SPIF_SENDWININICHANGE = 2 -SPIF_SENDCHANGE = SPIF_SENDWININICHANGE - -# used with SystemParametersInfo and SPI_GETFONTSMOOTHINGTYPE/SPI_SETFONTSMOOTHINGTYPE -FE_FONTSMOOTHINGSTANDARD = 1 -FE_FONTSMOOTHINGCLEARTYPE = 2 -FE_FONTSMOOTHINGDOCKING = 32768 - -METRICS_USEDEFAULT = -1 -ARW_BOTTOMLEFT = 0 -ARW_BOTTOMRIGHT = 1 -ARW_TOPLEFT = 2 -ARW_TOPRIGHT = 3 -ARW_STARTMASK = 3 -ARW_STARTRIGHT = 1 -ARW_STARTTOP = 2 -ARW_LEFT = 0 -ARW_RIGHT = 0 -ARW_UP = 4 -ARW_DOWN = 4 -ARW_HIDE = 8 -#ARW_VALID = 0x000F -SERKF_SERIALKEYSON = 1 -SERKF_AVAILABLE = 2 -SERKF_INDICATOR = 4 -HCF_HIGHCONTRASTON = 1 -HCF_AVAILABLE = 2 -HCF_HOTKEYACTIVE = 4 -HCF_CONFIRMHOTKEY = 8 -HCF_HOTKEYSOUND = 16 -HCF_INDICATOR = 32 -HCF_HOTKEYAVAILABLE = 64 -CDS_UPDATEREGISTRY = 1 -CDS_TEST = 2 -CDS_FULLSCREEN = 4 -CDS_GLOBAL = 8 -CDS_SET_PRIMARY = 16 -CDS_RESET = 1073741824 -CDS_SETRECT = 536870912 -CDS_NORESET = 268435456 - -# return values from ChangeDisplaySettings and ChangeDisplaySettingsEx -DISP_CHANGE_SUCCESSFUL = 0 -DISP_CHANGE_RESTART = 1 -DISP_CHANGE_FAILED = -1 -DISP_CHANGE_BADMODE = -2 -DISP_CHANGE_NOTUPDATED = -3 -DISP_CHANGE_BADFLAGS = -4 -DISP_CHANGE_BADPARAM = -5 -DISP_CHANGE_BADDUALVIEW = -6 - -ENUM_CURRENT_SETTINGS = -1 -ENUM_REGISTRY_SETTINGS = -2 -FKF_FILTERKEYSON = 1 -FKF_AVAILABLE = 2 -FKF_HOTKEYACTIVE = 4 -FKF_CONFIRMHOTKEY = 8 -FKF_HOTKEYSOUND = 16 -FKF_INDICATOR = 32 -FKF_CLICKON = 64 -SKF_STICKYKEYSON = 1 -SKF_AVAILABLE = 2 -SKF_HOTKEYACTIVE = 4 -SKF_CONFIRMHOTKEY = 8 -SKF_HOTKEYSOUND = 16 -SKF_INDICATOR = 32 -SKF_AUDIBLEFEEDBACK = 64 -SKF_TRISTATE = 128 -SKF_TWOKEYSOFF = 256 -SKF_LALTLATCHED = 268435456 -SKF_LCTLLATCHED = 67108864 -SKF_LSHIFTLATCHED = 16777216 -SKF_RALTLATCHED = 536870912 -SKF_RCTLLATCHED = 134217728 -SKF_RSHIFTLATCHED = 33554432 -SKF_LWINLATCHED = 1073741824 -SKF_RWINLATCHED = -2147483648 -SKF_LALTLOCKED = 1048576 -SKF_LCTLLOCKED = 262144 -SKF_LSHIFTLOCKED = 65536 -SKF_RALTLOCKED = 2097152 -SKF_RCTLLOCKED = 524288 -SKF_RSHIFTLOCKED = 131072 -SKF_LWINLOCKED = 4194304 -SKF_RWINLOCKED = 8388608 -MKF_MOUSEKEYSON = 1 -MKF_AVAILABLE = 2 -MKF_HOTKEYACTIVE = 4 -MKF_CONFIRMHOTKEY = 8 -MKF_HOTKEYSOUND = 16 -MKF_INDICATOR = 32 -MKF_MODIFIERS = 64 -MKF_REPLACENUMBERS = 128 -MKF_LEFTBUTTONSEL = 268435456 -MKF_RIGHTBUTTONSEL = 536870912 -MKF_LEFTBUTTONDOWN = 16777216 -MKF_RIGHTBUTTONDOWN = 33554432 -MKF_MOUSEMODE = -2147483648 -ATF_TIMEOUTON = 1 -ATF_ONOFFFEEDBACK = 2 -SSGF_NONE = 0 -SSGF_DISPLAY = 3 -SSTF_NONE = 0 -SSTF_CHARS = 1 -SSTF_BORDER = 2 -SSTF_DISPLAY = 3 -SSWF_NONE = 0 -SSWF_TITLE = 1 -SSWF_WINDOW = 2 -SSWF_DISPLAY = 3 -SSWF_CUSTOM = 4 -SSF_SOUNDSENTRYON = 1 -SSF_AVAILABLE = 2 -SSF_INDICATOR = 4 -TKF_TOGGLEKEYSON = 1 -TKF_AVAILABLE = 2 -TKF_HOTKEYACTIVE = 4 -TKF_CONFIRMHOTKEY = 8 -TKF_HOTKEYSOUND = 16 -TKF_INDICATOR = 32 -SLE_ERROR = 1 -SLE_MINORERROR = 2 -SLE_WARNING = 3 -MONITOR_DEFAULTTONULL = 0 -MONITOR_DEFAULTTOPRIMARY = 1 -MONITOR_DEFAULTTONEAREST = 2 -MONITORINFOF_PRIMARY = 1 -CCHDEVICENAME = 32 -CHILDID_SELF = 0 -INDEXID_OBJECT = 0 -INDEXID_CONTAINER = 0 -OBJID_WINDOW = 0 -OBJID_SYSMENU = -1 -OBJID_TITLEBAR = -2 -OBJID_MENU = -3 -OBJID_CLIENT = -4 -OBJID_VSCROLL = -5 -OBJID_HSCROLL = -6 -OBJID_SIZEGRIP = -7 -OBJID_CARET = -8 -OBJID_CURSOR = -9 -OBJID_ALERT = -10 -OBJID_SOUND = -11 -EVENT_MIN = 1 -EVENT_MAX = 2147483647 -EVENT_SYSTEM_SOUND = 1 -EVENT_SYSTEM_ALERT = 2 -EVENT_SYSTEM_FOREGROUND = 3 -EVENT_SYSTEM_MENUSTART = 4 -EVENT_SYSTEM_MENUEND = 5 -EVENT_SYSTEM_MENUPOPUPSTART = 6 -EVENT_SYSTEM_MENUPOPUPEND = 7 -EVENT_SYSTEM_CAPTURESTART = 8 -EVENT_SYSTEM_CAPTUREEND = 9 -EVENT_SYSTEM_MOVESIZESTART = 10 -EVENT_SYSTEM_MOVESIZEEND = 11 -EVENT_SYSTEM_CONTEXTHELPSTART = 12 -EVENT_SYSTEM_CONTEXTHELPEND = 13 -EVENT_SYSTEM_DRAGDROPSTART = 14 -EVENT_SYSTEM_DRAGDROPEND = 15 -EVENT_SYSTEM_DIALOGSTART = 16 -EVENT_SYSTEM_DIALOGEND = 17 -EVENT_SYSTEM_SCROLLINGSTART = 18 -EVENT_SYSTEM_SCROLLINGEND = 19 -EVENT_SYSTEM_SWITCHSTART = 20 -EVENT_SYSTEM_SWITCHEND = 21 -EVENT_SYSTEM_MINIMIZESTART = 22 -EVENT_SYSTEM_MINIMIZEEND = 23 -EVENT_OBJECT_CREATE = 32768 -EVENT_OBJECT_DESTROY = 32769 -EVENT_OBJECT_SHOW = 32770 -EVENT_OBJECT_HIDE = 32771 -EVENT_OBJECT_REORDER = 32772 -EVENT_OBJECT_FOCUS = 32773 -EVENT_OBJECT_SELECTION = 32774 -EVENT_OBJECT_SELECTIONADD = 32775 -EVENT_OBJECT_SELECTIONREMOVE = 32776 -EVENT_OBJECT_SELECTIONWITHIN = 32777 -EVENT_OBJECT_STATECHANGE = 32778 -EVENT_OBJECT_LOCATIONCHANGE = 32779 -EVENT_OBJECT_NAMECHANGE = 32780 -EVENT_OBJECT_DESCRIPTIONCHANGE = 32781 -EVENT_OBJECT_VALUECHANGE = 32782 -EVENT_OBJECT_PARENTCHANGE = 32783 -EVENT_OBJECT_HELPCHANGE = 32784 -EVENT_OBJECT_DEFACTIONCHANGE = 32785 -EVENT_OBJECT_ACCELERATORCHANGE = 32786 -SOUND_SYSTEM_STARTUP = 1 -SOUND_SYSTEM_SHUTDOWN = 2 -SOUND_SYSTEM_BEEP = 3 -SOUND_SYSTEM_ERROR = 4 -SOUND_SYSTEM_QUESTION = 5 -SOUND_SYSTEM_WARNING = 6 -SOUND_SYSTEM_INFORMATION = 7 -SOUND_SYSTEM_MAXIMIZE = 8 -SOUND_SYSTEM_MINIMIZE = 9 -SOUND_SYSTEM_RESTOREUP = 10 -SOUND_SYSTEM_RESTOREDOWN = 11 -SOUND_SYSTEM_APPSTART = 12 -SOUND_SYSTEM_FAULT = 13 -SOUND_SYSTEM_APPEND = 14 -SOUND_SYSTEM_MENUCOMMAND = 15 -SOUND_SYSTEM_MENUPOPUP = 16 -CSOUND_SYSTEM = 16 -ALERT_SYSTEM_INFORMATIONAL = 1 -ALERT_SYSTEM_WARNING = 2 -ALERT_SYSTEM_ERROR = 3 -ALERT_SYSTEM_QUERY = 4 -ALERT_SYSTEM_CRITICAL = 5 -CALERT_SYSTEM = 6 -WINEVENT_OUTOFCONTEXT = 0 -WINEVENT_SKIPOWNTHREAD = 1 -WINEVENT_SKIPOWNPROCESS = 2 -WINEVENT_INCONTEXT = 4 -GUI_CARETBLINKING = 1 -GUI_INMOVESIZE = 2 -GUI_INMENUMODE = 4 -GUI_SYSTEMMENUMODE = 8 -GUI_POPUPMENUMODE = 16 -STATE_SYSTEM_UNAVAILABLE = 1 -STATE_SYSTEM_SELECTED = 2 -STATE_SYSTEM_FOCUSED = 4 -STATE_SYSTEM_PRESSED = 8 -STATE_SYSTEM_CHECKED = 16 -STATE_SYSTEM_MIXED = 32 -STATE_SYSTEM_READONLY = 64 -STATE_SYSTEM_HOTTRACKED = 128 -STATE_SYSTEM_DEFAULT = 256 -STATE_SYSTEM_EXPANDED = 512 -STATE_SYSTEM_COLLAPSED = 1024 -STATE_SYSTEM_BUSY = 2048 -STATE_SYSTEM_FLOATING = 4096 -STATE_SYSTEM_MARQUEED = 8192 -STATE_SYSTEM_ANIMATED = 16384 -STATE_SYSTEM_INVISIBLE = 32768 -STATE_SYSTEM_OFFSCREEN = 65536 -STATE_SYSTEM_SIZEABLE = 131072 -STATE_SYSTEM_MOVEABLE = 262144 -STATE_SYSTEM_SELFVOICING = 524288 -STATE_SYSTEM_FOCUSABLE = 1048576 -STATE_SYSTEM_SELECTABLE = 2097152 -STATE_SYSTEM_LINKED = 4194304 -STATE_SYSTEM_TRAVERSED = 8388608 -STATE_SYSTEM_MULTISELECTABLE = 16777216 -STATE_SYSTEM_EXTSELECTABLE = 33554432 -STATE_SYSTEM_ALERT_LOW = 67108864 -STATE_SYSTEM_ALERT_MEDIUM = 134217728 -STATE_SYSTEM_ALERT_HIGH = 268435456 -STATE_SYSTEM_VALID = 536870911 -CCHILDREN_TITLEBAR = 5 -CCHILDREN_SCROLLBAR = 5 -CURSOR_SHOWING = 1 -WS_ACTIVECAPTION = 1 -GA_MIC = 1 -GA_PARENT = 1 -GA_ROOT = 2 -GA_ROOTOWNER = 3 -GA_MAC = 4 - -# winuser.h line 1979 -BF_LEFT = 1 -BF_TOP = 2 -BF_RIGHT = 4 -BF_BOTTOM = 8 -BF_TOPLEFT = (BF_TOP | BF_LEFT) -BF_TOPRIGHT = (BF_TOP | BF_RIGHT) -BF_BOTTOMLEFT = (BF_BOTTOM | BF_LEFT) -BF_BOTTOMRIGHT = (BF_BOTTOM | BF_RIGHT) -BF_RECT = (BF_LEFT | BF_TOP | BF_RIGHT | BF_BOTTOM) -BF_DIAGONAL = 16 -BF_DIAGONAL_ENDTOPRIGHT = (BF_DIAGONAL | BF_TOP | BF_RIGHT) -BF_DIAGONAL_ENDTOPLEFT = (BF_DIAGONAL | BF_TOP | BF_LEFT) -BF_DIAGONAL_ENDBOTTOMLEFT = (BF_DIAGONAL | BF_BOTTOM | BF_LEFT) -BF_DIAGONAL_ENDBOTTOMRIGHT = (BF_DIAGONAL | BF_BOTTOM | BF_RIGHT) -BF_MIDDLE = 2048 -BF_SOFT = 4096 -BF_ADJUST = 8192 -BF_FLAT = 16384 -BF_MONO = 32768 -DFC_CAPTION = 1 -DFC_MENU = 2 -DFC_SCROLL = 3 -DFC_BUTTON = 4 -DFC_POPUPMENU = 5 -DFCS_CAPTIONCLOSE = 0 -DFCS_CAPTIONMIN = 1 -DFCS_CAPTIONMAX = 2 -DFCS_CAPTIONRESTORE = 3 -DFCS_CAPTIONHELP = 4 -DFCS_MENUARROW = 0 -DFCS_MENUCHECK = 1 -DFCS_MENUBULLET = 2 -DFCS_MENUARROWRIGHT = 4 -DFCS_SCROLLUP = 0 -DFCS_SCROLLDOWN = 1 -DFCS_SCROLLLEFT = 2 -DFCS_SCROLLRIGHT = 3 -DFCS_SCROLLCOMBOBOX = 5 -DFCS_SCROLLSIZEGRIP = 8 -DFCS_SCROLLSIZEGRIPRIGHT = 16 -DFCS_BUTTONCHECK = 0 -DFCS_BUTTONRADIOIMAGE = 1 -DFCS_BUTTONRADIOMASK = 2 -DFCS_BUTTONRADIO = 4 -DFCS_BUTTON3STATE = 8 -DFCS_BUTTONPUSH = 16 -DFCS_INACTIVE = 256 -DFCS_PUSHED = 512 -DFCS_CHECKED = 1024 -DFCS_TRANSPARENT = 2048 -DFCS_HOT = 4096 -DFCS_ADJUSTRECT = 8192 -DFCS_FLAT = 16384 -DFCS_MONO = 32768 -DC_ACTIVE = 1 -DC_SMALLCAP = 2 -DC_ICON = 4 -DC_TEXT = 8 -DC_INBUTTON = 16 -DC_GRADIENT = 32 -IDANI_OPEN = 1 -IDANI_CLOSE = 2 -IDANI_CAPTION = 3 -CF_TEXT = 1 -CF_BITMAP = 2 -CF_METAFILEPICT = 3 -CF_SYLK = 4 -CF_DIF = 5 -CF_TIFF = 6 -CF_OEMTEXT = 7 -CF_DIB = 8 -CF_PALETTE = 9 -CF_PENDATA = 10 -CF_RIFF = 11 -CF_WAVE = 12 -CF_UNICODETEXT = 13 -CF_ENHMETAFILE = 14 -CF_HDROP = 15 -CF_LOCALE = 16 -CF_MAX = 17 -CF_OWNERDISPLAY = 128 -CF_DSPTEXT = 129 -CF_DSPBITMAP = 130 -CF_DSPMETAFILEPICT = 131 -CF_DSPENHMETAFILE = 142 -CF_PRIVATEFIRST = 512 -CF_PRIVATELAST = 767 -CF_GDIOBJFIRST = 768 -CF_GDIOBJLAST = 1023 -FVIRTKEY =1 -FNOINVERT = 2 -FSHIFT = 4 -FCONTROL = 8 -FALT = 16 -WPF_SETMINPOSITION = 1 -WPF_RESTORETOMAXIMIZED = 2 -ODT_MENU = 1 -ODT_LISTBOX = 2 -ODT_COMBOBOX = 3 -ODT_BUTTON = 4 -ODT_STATIC = 5 -ODA_DRAWENTIRE = 1 -ODA_SELECT = 2 -ODA_FOCUS = 4 -ODS_SELECTED = 1 -ODS_GRAYED = 2 -ODS_DISABLED = 4 -ODS_CHECKED = 8 -ODS_FOCUS = 16 -ODS_DEFAULT = 32 -ODS_COMBOBOXEDIT = 4096 -ODS_HOTLIGHT = 64 -ODS_INACTIVE = 128 -PM_NOREMOVE = 0 -PM_REMOVE = 1 -PM_NOYIELD = 2 -# Name clashes with key.MOD_ALT, key.MOD_CONTROL and key.MOD_SHIFT -WIN32_MOD_ALT = 1 -WIN32_MOD_CONTROL = 2 -WIN32_MOD_SHIFT = 4 -WIN32_MOD_WIN = 8 -IDHOT_SNAPWINDOW = (-1) -IDHOT_SNAPDESKTOP = (-2) -#EW_RESTARTWINDOWS = 0x0042 -#EW_REBOOTSYSTEM = 0x0043 -#EW_EXITANDEXECAPP = 0x0044 -ENDSESSION_LOGOFF = -2147483648 -EWX_LOGOFF = 0 -EWX_SHUTDOWN = 1 -EWX_REBOOT = 2 -EWX_FORCE = 4 -EWX_POWEROFF = 8 -EWX_FORCEIFHUNG = 16 -BSM_ALLCOMPONENTS = 0 -BSM_VXDS = 1 -BSM_NETDRIVER = 2 -BSM_INSTALLABLEDRIVERS = 4 -BSM_APPLICATIONS = 8 -BSM_ALLDESKTOPS = 16 -BSF_QUERY = 1 -BSF_IGNORECURRENTTASK = 2 -BSF_FLUSHDISK = 4 -BSF_NOHANG = 8 -BSF_POSTMESSAGE = 16 -BSF_FORCEIFHUNG = 32 -BSF_NOTIMEOUTIFNOTHUNG = 64 -BROADCAST_QUERY_DENY = 1112363332 # Return this value to deny a query. - -DBWF_LPARAMPOINTER = 32768 - -# winuser.h line 3232 -SWP_NOSIZE = 1 -SWP_NOMOVE = 2 -SWP_NOZORDER = 4 -SWP_NOREDRAW = 8 -SWP_NOACTIVATE = 16 -SWP_FRAMECHANGED = 32 -SWP_SHOWWINDOW = 64 -SWP_HIDEWINDOW = 128 -SWP_NOCOPYBITS = 256 -SWP_NOOWNERZORDER = 512 -SWP_NOSENDCHANGING = 1024 -SWP_DRAWFRAME = SWP_FRAMECHANGED -SWP_NOREPOSITION = SWP_NOOWNERZORDER -SWP_DEFERERASE = 8192 -SWP_ASYNCWINDOWPOS = 16384 - -DLGWINDOWEXTRA = 30 -# winuser.h line 4249 -KEYEVENTF_EXTENDEDKEY = 1 -KEYEVENTF_KEYUP = 2 -MOUSEEVENTF_MOVE = 1 -MOUSEEVENTF_LEFTDOWN = 2 -MOUSEEVENTF_LEFTUP = 4 -MOUSEEVENTF_RIGHTDOWN = 8 -MOUSEEVENTF_RIGHTUP = 16 -MOUSEEVENTF_MIDDLEDOWN = 32 -MOUSEEVENTF_MIDDLEUP = 64 -MOUSEEVENTF_ABSOLUTE = 32768 -INPUT_MOUSE = 0 -INPUT_KEYBOARD = 1 -INPUT_HARDWARE = 2 -MWMO_WAITALL = 1 -MWMO_ALERTABLE = 2 -MWMO_INPUTAVAILABLE = 4 -QS_KEY = 1 -QS_MOUSEMOVE = 2 -QS_MOUSEBUTTON = 4 -QS_POSTMESSAGE = 8 -QS_TIMER = 16 -QS_PAINT = 32 -QS_SENDMESSAGE = 64 -QS_HOTKEY = 128 -QS_RAWINPUT = 0x400 -QS_MOUSE = (QS_MOUSEMOVE | - QS_MOUSEBUTTON) -QS_INPUT = (QS_MOUSE | - QS_KEY | - QS_RAWINPUT) -QS_ALLEVENTS = (QS_INPUT | - QS_POSTMESSAGE | - QS_TIMER | - QS_PAINT | - QS_HOTKEY) -QS_ALLINPUT = (QS_INPUT | - QS_POSTMESSAGE | - QS_TIMER | - QS_PAINT | - QS_HOTKEY | - QS_SENDMESSAGE) - - -IMN_CLOSESTATUSWINDOW = 1 -IMN_OPENSTATUSWINDOW = 2 -IMN_CHANGECANDIDATE = 3 -IMN_CLOSECANDIDATE = 4 -IMN_OPENCANDIDATE = 5 -IMN_SETCONVERSIONMODE = 6 -IMN_SETSENTENCEMODE = 7 -IMN_SETOPENSTATUS = 8 -IMN_SETCANDIDATEPOS = 9 -IMN_SETCOMPOSITIONFONT = 10 -IMN_SETCOMPOSITIONWINDOW = 11 -IMN_SETSTATUSWINDOWPOS = 12 -IMN_GUIDELINE = 13 -IMN_PRIVATE = 14 - -# winuser.h line 8518 -HELP_CONTEXT = 1 -HELP_QUIT = 2 -HELP_INDEX = 3 -HELP_CONTENTS = 3 -HELP_HELPONHELP = 4 -HELP_SETINDEX = 5 -HELP_SETCONTENTS = 5 -HELP_CONTEXTPOPUP = 8 -HELP_FORCEFILE = 9 -HELP_KEY = 257 -HELP_COMMAND = 258 -HELP_PARTIALKEY = 261 -HELP_MULTIKEY = 513 -HELP_SETWINPOS = 515 -HELP_CONTEXTMENU = 10 -HELP_FINDER = 11 -HELP_WM_HELP = 12 -HELP_SETPOPUP_POS = 13 -HELP_TCARD = 32768 -HELP_TCARD_DATA = 16 -HELP_TCARD_OTHER_CALLER = 17 -IDH_NO_HELP = 28440 -IDH_MISSING_CONTEXT = 28441 # Control doesn't have matching help context -IDH_GENERIC_HELP_BUTTON = 28442 # Property sheet help button -IDH_OK = 28443 -IDH_CANCEL = 28444 -IDH_HELP = 28445 -GR_GDIOBJECTS = 0 # Count of GDI objects -GR_USEROBJECTS = 1 # Count of USER objects -# Generated by h2py from \msvcnt\include\wingdi.h -# manually added (missed by generation some how! -SRCCOPY = 13369376 # dest = source -SRCPAINT = 15597702 # dest = source OR dest -SRCAND = 8913094 # dest = source AND dest -SRCINVERT = 6684742 # dest = source XOR dest -SRCERASE = 4457256 # dest = source AND (NOT dest ) -NOTSRCCOPY = 3342344 # dest = (NOT source) -NOTSRCERASE = 1114278 # dest = (NOT src) AND (NOT dest) -MERGECOPY = 12583114 # dest = (source AND pattern) -MERGEPAINT = 12255782 # dest = (NOT source) OR dest -PATCOPY = 15728673 # dest = pattern -PATPAINT = 16452105 # dest = DPSnoo -PATINVERT = 5898313 # dest = pattern XOR dest -DSTINVERT = 5570569 # dest = (NOT dest) -BLACKNESS = 66 # dest = BLACK -WHITENESS = 16711778 # dest = WHITE - -# hacked and split manually by mhammond. -R2_BLACK = 1 -R2_NOTMERGEPEN = 2 -R2_MASKNOTPEN = 3 -R2_NOTCOPYPEN = 4 -R2_MASKPENNOT = 5 -R2_NOT = 6 -R2_XORPEN = 7 -R2_NOTMASKPEN = 8 -R2_MASKPEN = 9 -R2_NOTXORPEN = 10 -R2_NOP = 11 -R2_MERGENOTPEN = 12 -R2_COPYPEN = 13 -R2_MERGEPENNOT = 14 -R2_MERGEPEN = 15 -R2_WHITE = 16 -R2_LAST = 16 -GDI_ERROR = (-1) -ERROR = 0 -NULLREGION = 1 -SIMPLEREGION = 2 -COMPLEXREGION = 3 -RGN_ERROR = ERROR -RGN_AND = 1 -RGN_OR = 2 -RGN_XOR = 3 -RGN_DIFF = 4 -RGN_COPY = 5 -RGN_MIN = RGN_AND -RGN_MAX = RGN_COPY -BLACKONWHITE = 1 -WHITEONBLACK = 2 -COLORONCOLOR = 3 -HALFTONE = 4 -MAXSTRETCHBLTMODE = 4 -ALTERNATE = 1 -WINDING = 2 -POLYFILL_LAST = 2 -TA_NOUPDATECP = 0 -TA_UPDATECP = 1 -TA_LEFT = 0 -TA_RIGHT = 2 -TA_CENTER = 6 -TA_TOP = 0 -TA_BOTTOM = 8 -TA_BASELINE = 24 -TA_MASK = (TA_BASELINE+TA_CENTER+TA_UPDATECP) -VTA_BASELINE = TA_BASELINE -VTA_LEFT = TA_BOTTOM -VTA_RIGHT = TA_TOP -VTA_CENTER = TA_CENTER -VTA_BOTTOM = TA_RIGHT -VTA_TOP = TA_LEFT -ETO_GRAYED = 1 -ETO_OPAQUE = 2 -ETO_CLIPPED = 4 -ASPECT_FILTERING = 1 -DCB_RESET = 1 -DCB_ACCUMULATE = 2 -DCB_DIRTY = DCB_ACCUMULATE -DCB_SET = (DCB_RESET | DCB_ACCUMULATE) -DCB_ENABLE = 4 -DCB_DISABLE = 8 -META_SETBKCOLOR = 513 -META_SETBKMODE = 258 -META_SETMAPMODE = 259 -META_SETROP2 = 260 -META_SETRELABS = 261 -META_SETPOLYFILLMODE = 262 -META_SETSTRETCHBLTMODE = 263 -META_SETTEXTCHAREXTRA = 264 -META_SETTEXTCOLOR = 521 -META_SETTEXTJUSTIFICATION = 522 -META_SETWINDOWORG = 523 -META_SETWINDOWEXT = 524 -META_SETVIEWPORTORG = 525 -META_SETVIEWPORTEXT = 526 -META_OFFSETWINDOWORG = 527 -META_SCALEWINDOWEXT = 1040 -META_OFFSETVIEWPORTORG = 529 -META_SCALEVIEWPORTEXT = 1042 -META_LINETO = 531 -META_MOVETO = 532 -META_EXCLUDECLIPRECT = 1045 -META_INTERSECTCLIPRECT = 1046 -META_ARC = 2071 -META_ELLIPSE = 1048 -META_FLOODFILL = 1049 -META_PIE = 2074 -META_RECTANGLE = 1051 -META_ROUNDRECT = 1564 -META_PATBLT = 1565 -META_SAVEDC = 30 -META_SETPIXEL = 1055 -META_OFFSETCLIPRGN = 544 -META_TEXTOUT = 1313 -META_BITBLT = 2338 -META_STRETCHBLT = 2851 -META_POLYGON = 804 -META_POLYLINE = 805 -META_ESCAPE = 1574 -META_RESTOREDC = 295 -META_FILLREGION = 552 -META_FRAMEREGION = 1065 -META_INVERTREGION = 298 -META_PAINTREGION = 299 -META_SELECTCLIPREGION = 300 -META_SELECTOBJECT = 301 -META_SETTEXTALIGN = 302 -META_CHORD = 2096 -META_SETMAPPERFLAGS = 561 -META_EXTTEXTOUT = 2610 -META_SETDIBTODEV = 3379 -META_SELECTPALETTE = 564 -META_REALIZEPALETTE = 53 -META_ANIMATEPALETTE = 1078 -META_SETPALENTRIES = 55 -META_POLYPOLYGON = 1336 -META_RESIZEPALETTE = 313 -META_DIBBITBLT = 2368 -META_DIBSTRETCHBLT = 2881 -META_DIBCREATEPATTERNBRUSH = 322 -META_STRETCHDIB = 3907 -META_EXTFLOODFILL = 1352 -META_DELETEOBJECT = 496 -META_CREATEPALETTE = 247 -META_CREATEPATTERNBRUSH = 505 -META_CREATEPENINDIRECT = 762 -META_CREATEFONTINDIRECT = 763 -META_CREATEBRUSHINDIRECT = 764 -META_CREATEREGION = 1791 -FILE_BEGIN = 0 -FILE_CURRENT = 1 -FILE_END = 2 -FILE_FLAG_WRITE_THROUGH = -2147483648 -FILE_FLAG_OVERLAPPED = 1073741824 -FILE_FLAG_NO_BUFFERING = 536870912 -FILE_FLAG_RANDOM_ACCESS = 268435456 -FILE_FLAG_SEQUENTIAL_SCAN = 134217728 -FILE_FLAG_DELETE_ON_CLOSE = 67108864 -FILE_FLAG_BACKUP_SEMANTICS = 33554432 -FILE_FLAG_POSIX_SEMANTICS = 16777216 -CREATE_NEW = 1 -CREATE_ALWAYS = 2 -OPEN_EXISTING = 3 -OPEN_ALWAYS = 4 -TRUNCATE_EXISTING = 5 -PIPE_ACCESS_INBOUND = 1 -PIPE_ACCESS_OUTBOUND = 2 -PIPE_ACCESS_DUPLEX = 3 -PIPE_CLIENT_END = 0 -PIPE_SERVER_END = 1 -PIPE_WAIT = 0 -PIPE_NOWAIT = 1 -PIPE_READMODE_BYTE = 0 -PIPE_READMODE_MESSAGE = 2 -PIPE_TYPE_BYTE = 0 -PIPE_TYPE_MESSAGE = 4 -PIPE_UNLIMITED_INSTANCES = 255 -SECURITY_CONTEXT_TRACKING = 262144 -SECURITY_EFFECTIVE_ONLY = 524288 -SECURITY_SQOS_PRESENT = 1048576 -SECURITY_VALID_SQOS_FLAGS = 2031616 -DTR_CONTROL_DISABLE = 0 -DTR_CONTROL_ENABLE = 1 -DTR_CONTROL_HANDSHAKE = 2 -RTS_CONTROL_DISABLE = 0 -RTS_CONTROL_ENABLE = 1 -RTS_CONTROL_HANDSHAKE = 2 -RTS_CONTROL_TOGGLE = 3 -GMEM_FIXED = 0 -GMEM_MOVEABLE = 2 -GMEM_NOCOMPACT = 16 -GMEM_NODISCARD = 32 -GMEM_ZEROINIT = 64 -GMEM_MODIFY = 128 -GMEM_DISCARDABLE = 256 -GMEM_NOT_BANKED = 4096 -GMEM_SHARE = 8192 -GMEM_DDESHARE = 8192 -GMEM_NOTIFY = 16384 -GMEM_LOWER = GMEM_NOT_BANKED -GMEM_VALID_FLAGS = 32626 -GMEM_INVALID_HANDLE = 32768 -GHND = (GMEM_MOVEABLE | GMEM_ZEROINIT) -GPTR = (GMEM_FIXED | GMEM_ZEROINIT) -GMEM_DISCARDED = 16384 -GMEM_LOCKCOUNT = 255 -LMEM_FIXED = 0 -LMEM_MOVEABLE = 2 -LMEM_NOCOMPACT = 16 -LMEM_NODISCARD = 32 -LMEM_ZEROINIT = 64 -LMEM_MODIFY = 128 -LMEM_DISCARDABLE = 3840 -LMEM_VALID_FLAGS = 3954 -LMEM_INVALID_HANDLE = 32768 -LHND = (LMEM_MOVEABLE | LMEM_ZEROINIT) -LPTR = (LMEM_FIXED | LMEM_ZEROINIT) -NONZEROLHND = (LMEM_MOVEABLE) -NONZEROLPTR = (LMEM_FIXED) -LMEM_DISCARDED = 16384 -LMEM_LOCKCOUNT = 255 -DEBUG_PROCESS = 1 -DEBUG_ONLY_THIS_PROCESS = 2 -CREATE_SUSPENDED = 4 -DETACHED_PROCESS = 8 -CREATE_NEW_CONSOLE = 16 -NORMAL_PRIORITY_CLASS = 32 -IDLE_PRIORITY_CLASS = 64 -HIGH_PRIORITY_CLASS = 128 -REALTIME_PRIORITY_CLASS = 256 -CREATE_NEW_PROCESS_GROUP = 512 -CREATE_UNICODE_ENVIRONMENT = 1024 -CREATE_SEPARATE_WOW_VDM = 2048 -CREATE_SHARED_WOW_VDM = 4096 -CREATE_DEFAULT_ERROR_MODE = 67108864 -CREATE_NO_WINDOW = 134217728 -PROFILE_USER = 268435456 -PROFILE_KERNEL = 536870912 -PROFILE_SERVER = 1073741824 -THREAD_BASE_PRIORITY_LOWRT = 15 -THREAD_BASE_PRIORITY_MAX = 2 -THREAD_BASE_PRIORITY_MIN = -2 -THREAD_BASE_PRIORITY_IDLE = -15 -THREAD_PRIORITY_LOWEST = THREAD_BASE_PRIORITY_MIN -THREAD_PRIORITY_BELOW_NORMAL = THREAD_PRIORITY_LOWEST+1 -THREAD_PRIORITY_HIGHEST = THREAD_BASE_PRIORITY_MAX -THREAD_PRIORITY_ABOVE_NORMAL = THREAD_PRIORITY_HIGHEST-1 -THREAD_PRIORITY_ERROR_RETURN = MAXLONG -THREAD_PRIORITY_TIME_CRITICAL = THREAD_BASE_PRIORITY_LOWRT -THREAD_PRIORITY_IDLE = THREAD_BASE_PRIORITY_IDLE -THREAD_PRIORITY_NORMAL = 0 -EXCEPTION_DEBUG_EVENT = 1 -CREATE_THREAD_DEBUG_EVENT = 2 -CREATE_PROCESS_DEBUG_EVENT = 3 -EXIT_THREAD_DEBUG_EVENT = 4 -EXIT_PROCESS_DEBUG_EVENT = 5 -LOAD_DLL_DEBUG_EVENT = 6 -UNLOAD_DLL_DEBUG_EVENT = 7 -OUTPUT_DEBUG_STRING_EVENT = 8 -RIP_EVENT = 9 -DRIVE_UNKNOWN = 0 -DRIVE_NO_ROOT_DIR = 1 -DRIVE_REMOVABLE = 2 -DRIVE_FIXED = 3 -DRIVE_REMOTE = 4 -DRIVE_CDROM = 5 -DRIVE_RAMDISK = 6 -FILE_TYPE_UNKNOWN = 0 -FILE_TYPE_DISK = 1 -FILE_TYPE_CHAR = 2 -FILE_TYPE_PIPE = 3 -FILE_TYPE_REMOTE = 32768 -NOPARITY = 0 -ODDPARITY = 1 -EVENPARITY = 2 -MARKPARITY = 3 -SPACEPARITY = 4 -ONESTOPBIT = 0 -ONE5STOPBITS = 1 -TWOSTOPBITS = 2 -CBR_110 = 110 -CBR_300 = 300 -CBR_600 = 600 -CBR_1200 = 1200 -CBR_2400 = 2400 -CBR_4800 = 4800 -CBR_9600 = 9600 -CBR_14400 = 14400 -CBR_19200 = 19200 -CBR_38400 = 38400 -CBR_56000 = 56000 -CBR_57600 = 57600 -CBR_115200 = 115200 -CBR_128000 = 128000 -CBR_256000 = 256000 -S_QUEUEEMPTY = 0 -S_THRESHOLD = 1 -S_ALLTHRESHOLD = 2 -S_NORMAL = 0 -S_LEGATO = 1 -S_STACCATO = 2 -NMPWAIT_WAIT_FOREVER = -1 -NMPWAIT_NOWAIT = 1 -NMPWAIT_USE_DEFAULT_WAIT = 0 -OF_READ = 0 -OF_WRITE = 1 -OF_READWRITE = 2 -OF_SHARE_COMPAT = 0 -OF_SHARE_EXCLUSIVE = 16 -OF_SHARE_DENY_WRITE = 32 -OF_SHARE_DENY_READ = 48 -OF_SHARE_DENY_NONE = 64 -OF_PARSE = 256 -OF_DELETE = 512 -OF_VERIFY = 1024 -OF_CANCEL = 2048 -OF_CREATE = 4096 -OF_PROMPT = 8192 -OF_EXIST = 16384 -OF_REOPEN = 32768 -OFS_MAXPATHNAME = 128 -MAXINTATOM = 49152 - -# winbase.h -PROCESS_HEAP_REGION = 1 -PROCESS_HEAP_UNCOMMITTED_RANGE = 2 -PROCESS_HEAP_ENTRY_BUSY = 4 -PROCESS_HEAP_ENTRY_MOVEABLE = 16 -PROCESS_HEAP_ENTRY_DDESHARE = 32 -SCS_32BIT_BINARY = 0 -SCS_DOS_BINARY = 1 -SCS_WOW_BINARY = 2 -SCS_PIF_BINARY = 3 -SCS_POSIX_BINARY = 4 -SCS_OS216_BINARY = 5 -SEM_FAILCRITICALERRORS = 1 -SEM_NOGPFAULTERRORBOX = 2 -SEM_NOALIGNMENTFAULTEXCEPT = 4 -SEM_NOOPENFILEERRORBOX = 32768 -LOCKFILE_FAIL_IMMEDIATELY = 1 -LOCKFILE_EXCLUSIVE_LOCK = 2 -HANDLE_FLAG_INHERIT = 1 -HANDLE_FLAG_PROTECT_FROM_CLOSE = 2 -HINSTANCE_ERROR = 32 -GET_TAPE_MEDIA_INFORMATION = 0 -GET_TAPE_DRIVE_INFORMATION = 1 -SET_TAPE_MEDIA_INFORMATION = 0 -SET_TAPE_DRIVE_INFORMATION = 1 -FORMAT_MESSAGE_ALLOCATE_BUFFER = 256 -FORMAT_MESSAGE_IGNORE_INSERTS = 512 -FORMAT_MESSAGE_FROM_STRING = 1024 -FORMAT_MESSAGE_FROM_HMODULE = 2048 -FORMAT_MESSAGE_FROM_SYSTEM = 4096 -FORMAT_MESSAGE_ARGUMENT_ARRAY = 8192 -FORMAT_MESSAGE_MAX_WIDTH_MASK = 255 -BACKUP_INVALID = 0 -BACKUP_DATA = 1 -BACKUP_EA_DATA = 2 -BACKUP_SECURITY_DATA = 3 -BACKUP_ALTERNATE_DATA = 4 -BACKUP_LINK = 5 -BACKUP_PROPERTY_DATA = 6 -BACKUP_OBJECT_ID = 7 -BACKUP_REPARSE_DATA = 8 -BACKUP_SPARSE_BLOCK = 9 - -STREAM_NORMAL_ATTRIBUTE = 0 -STREAM_MODIFIED_WHEN_READ = 1 -STREAM_CONTAINS_SECURITY = 2 -STREAM_CONTAINS_PROPERTIES = 4 -STARTF_USESHOWWINDOW = 1 -STARTF_USESIZE = 2 -STARTF_USEPOSITION = 4 -STARTF_USECOUNTCHARS = 8 -STARTF_USEFILLATTRIBUTE = 16 -STARTF_FORCEONFEEDBACK = 64 -STARTF_FORCEOFFFEEDBACK = 128 -STARTF_USESTDHANDLES = 256 -STARTF_USEHOTKEY = 512 -SHUTDOWN_NORETRY = 1 -DONT_RESOLVE_DLL_REFERENCES = 1 -LOAD_LIBRARY_AS_DATAFILE = 2 -LOAD_WITH_ALTERED_SEARCH_PATH = 8 -DDD_RAW_TARGET_PATH = 1 -DDD_REMOVE_DEFINITION = 2 -DDD_EXACT_MATCH_ON_REMOVE = 4 -MOVEFILE_REPLACE_EXISTING = 1 -MOVEFILE_COPY_ALLOWED = 2 -MOVEFILE_DELAY_UNTIL_REBOOT = 4 -MAX_COMPUTERNAME_LENGTH = 15 -LOGON32_LOGON_INTERACTIVE = 2 -LOGON32_LOGON_BATCH = 4 -LOGON32_LOGON_SERVICE = 5 -LOGON32_PROVIDER_DEFAULT = 0 -LOGON32_PROVIDER_WINNT35 = 1 -VER_PLATFORM_WIN32s = 0 -VER_PLATFORM_WIN32_WINDOWS = 1 -VER_PLATFORM_WIN32_NT = 2 -TC_NORMAL = 0 -TC_HARDERR = 1 -TC_GP_TRAP = 2 -TC_SIGNAL = 3 -AC_LINE_OFFLINE = 0 -AC_LINE_ONLINE = 1 -AC_LINE_BACKUP_POWER = 2 -AC_LINE_UNKNOWN = 255 -BATTERY_FLAG_HIGH = 1 -BATTERY_FLAG_LOW = 2 -BATTERY_FLAG_CRITICAL = 4 -BATTERY_FLAG_CHARGING = 8 -BATTERY_FLAG_NO_BATTERY = 128 -BATTERY_FLAG_UNKNOWN = 255 -BATTERY_PERCENTAGE_UNKNOWN = 255 -BATTERY_LIFE_UNKNOWN = -1 - -# Generated by h2py from d:\msdev\include\richedit.h -cchTextLimitDefault = 32767 -WM_CONTEXTMENU = 123 -WM_PRINTCLIENT = 792 -EN_MSGFILTER = 1792 -EN_REQUESTRESIZE = 1793 -EN_SELCHANGE = 1794 -EN_DROPFILES = 1795 -EN_PROTECTED = 1796 -EN_CORRECTTEXT = 1797 -EN_STOPNOUNDO = 1798 -EN_IMECHANGE = 1799 -EN_SAVECLIPBOARD = 1800 -EN_OLEOPFAILED = 1801 -ENM_NONE = 0 -ENM_CHANGE = 1 -ENM_UPDATE = 2 -ENM_SCROLL = 4 -ENM_KEYEVENTS = 65536 -ENM_MOUSEEVENTS = 131072 -ENM_REQUESTRESIZE = 262144 -ENM_SELCHANGE = 524288 -ENM_DROPFILES = 1048576 -ENM_PROTECTED = 2097152 -ENM_CORRECTTEXT = 4194304 -ENM_IMECHANGE = 8388608 -ES_SAVESEL = 32768 -ES_SUNKEN = 16384 -ES_DISABLENOSCROLL = 8192 -ES_SELECTIONBAR = 16777216 -ES_EX_NOCALLOLEINIT = 16777216 -ES_VERTICAL = 4194304 -ES_NOIME = 524288 -ES_SELFIME = 262144 -ECO_AUTOWORDSELECTION = 1 -ECO_AUTOVSCROLL = 64 -ECO_AUTOHSCROLL = 128 -ECO_NOHIDESEL = 256 -ECO_READONLY = 2048 -ECO_WANTRETURN = 4096 -ECO_SAVESEL = 32768 -ECO_SELECTIONBAR = 16777216 -ECO_VERTICAL = 4194304 -ECOOP_SET = 1 -ECOOP_OR = 2 -ECOOP_AND = 3 -ECOOP_XOR = 4 -WB_CLASSIFY = 3 -WB_MOVEWORDLEFT = 4 -WB_MOVEWORDRIGHT = 5 -WB_LEFTBREAK = 6 -WB_RIGHTBREAK = 7 -WB_MOVEWORDPREV = 4 -WB_MOVEWORDNEXT = 5 -WB_PREVBREAK = 6 -WB_NEXTBREAK = 7 -PC_FOLLOWING = 1 -PC_LEADING = 2 -PC_OVERFLOW = 3 -PC_DELIMITER = 4 -WBF_WORDWRAP = 16 -WBF_WORDBREAK = 32 -WBF_OVERFLOW = 64 -WBF_LEVEL1 = 128 -WBF_LEVEL2 = 256 -WBF_CUSTOM = 512 -CFM_BOLD = 1 -CFM_ITALIC = 2 -CFM_UNDERLINE = 4 -CFM_STRIKEOUT = 8 -CFM_PROTECTED = 16 -CFM_SIZE = -2147483648 -CFM_COLOR = 1073741824 -CFM_FACE = 536870912 -CFM_OFFSET = 268435456 -CFM_CHARSET = 134217728 -CFE_BOLD = 1 -CFE_ITALIC = 2 -CFE_UNDERLINE = 4 -CFE_STRIKEOUT = 8 -CFE_PROTECTED = 16 -CFE_AUTOCOLOR = 1073741824 -yHeightCharPtsMost = 1638 -SCF_SELECTION = 1 -SCF_WORD = 2 -SF_TEXT = 1 -SF_RTF = 2 -SF_RTFNOOBJS = 3 -SF_TEXTIZED = 4 -SFF_SELECTION = 32768 -SFF_PLAINRTF = 16384 -MAX_TAB_STOPS = 32 -lDefaultTab = 720 -PFM_STARTINDENT = 1 -PFM_RIGHTINDENT = 2 -PFM_OFFSET = 4 -PFM_ALIGNMENT = 8 -PFM_TABSTOPS = 16 -PFM_NUMBERING = 32 -PFM_OFFSETINDENT = -2147483648 -PFN_BULLET = 1 -PFA_LEFT = 1 -PFA_RIGHT = 2 -PFA_CENTER = 3 -WM_NOTIFY = 78 -SEL_EMPTY = 0 -SEL_TEXT = 1 -SEL_OBJECT = 2 -SEL_MULTICHAR = 4 -SEL_MULTIOBJECT = 8 -OLEOP_DOVERB = 1 -CF_RTF = "Rich Text Format" -CF_RTFNOOBJS = "Rich Text Format Without Objects" -CF_RETEXTOBJ = "RichEdit Text and Objects" - -# From wincon.h -RIGHT_ALT_PRESSED = 1 # the right alt key is pressed. -LEFT_ALT_PRESSED = 2 # the left alt key is pressed. -RIGHT_CTRL_PRESSED = 4 # the right ctrl key is pressed. -LEFT_CTRL_PRESSED = 8 # the left ctrl key is pressed. -SHIFT_PRESSED = 16 # the shift key is pressed. -NUMLOCK_ON = 32 # the numlock light is on. -SCROLLLOCK_ON = 64 # the scrolllock light is on. -CAPSLOCK_ON = 128 # the capslock light is on. -ENHANCED_KEY = 256 # the key is enhanced. -NLS_DBCSCHAR = 65536 # DBCS for JPN: SBCS/DBCS mode. -NLS_ALPHANUMERIC = 0 # DBCS for JPN: Alphanumeric mode. -NLS_KATAKANA = 131072 # DBCS for JPN: Katakana mode. -NLS_HIRAGANA = 262144 # DBCS for JPN: Hiragana mode. -NLS_ROMAN = 4194304 # DBCS for JPN: Roman/Noroman mode. -NLS_IME_CONVERSION = 8388608 # DBCS for JPN: IME conversion. -NLS_IME_DISABLE = 536870912 # DBCS for JPN: IME enable/disable. - -FROM_LEFT_1ST_BUTTON_PRESSED = 1 -RIGHTMOST_BUTTON_PRESSED = 2 -FROM_LEFT_2ND_BUTTON_PRESSED = 4 -FROM_LEFT_3RD_BUTTON_PRESSED = 8 -FROM_LEFT_4TH_BUTTON_PRESSED = 16 - -CTRL_C_EVENT = 0 -CTRL_BREAK_EVENT = 1 -CTRL_CLOSE_EVENT = 2 -CTRL_LOGOFF_EVENT = 5 -CTRL_SHUTDOWN_EVENT = 6 - -MOUSE_MOVED = 1 -DOUBLE_CLICK = 2 -MOUSE_WHEELED = 4 - -#property sheet window messages from prsht.h -PSM_SETCURSEL = (WM_USER + 101) -PSM_REMOVEPAGE = (WM_USER + 102) -PSM_ADDPAGE = (WM_USER + 103) -PSM_CHANGED = (WM_USER + 104) -PSM_RESTARTWINDOWS = (WM_USER + 105) -PSM_REBOOTSYSTEM = (WM_USER + 106) -PSM_CANCELTOCLOSE = (WM_USER + 107) -PSM_QUERYSIBLINGS = (WM_USER + 108) -PSM_UNCHANGED = (WM_USER + 109) -PSM_APPLY = (WM_USER + 110) -PSM_SETTITLEA = (WM_USER + 111) -PSM_SETTITLEW = (WM_USER + 120) -PSM_SETWIZBUTTONS = (WM_USER + 112) -PSM_PRESSBUTTON = (WM_USER + 113) -PSM_SETCURSELID = (WM_USER + 114) -PSM_SETFINISHTEXTA = (WM_USER + 115) -PSM_SETFINISHTEXTW = (WM_USER + 121) -PSM_GETTABCONTROL = (WM_USER + 116) -PSM_ISDIALOGMESSAGE = (WM_USER + 117) -PSM_GETCURRENTPAGEHWND = (WM_USER + 118) -PSM_INSERTPAGE = (WM_USER + 119) -PSM_SETHEADERTITLEA = (WM_USER + 125) -PSM_SETHEADERTITLEW = (WM_USER + 126) -PSM_SETHEADERSUBTITLEA = (WM_USER + 127) -PSM_SETHEADERSUBTITLEW = (WM_USER + 128) -PSM_HWNDTOINDEX = (WM_USER + 129) -PSM_INDEXTOHWND = (WM_USER + 130) -PSM_PAGETOINDEX = (WM_USER + 131) -PSM_INDEXTOPAGE = (WM_USER + 132) -PSM_IDTOINDEX = (WM_USER + 133) -PSM_INDEXTOID = (WM_USER + 134) -PSM_GETRESULT = (WM_USER + 135) -PSM_RECALCPAGESIZES = (WM_USER + 136) - -# GetUserNameEx/GetComputerNameEx -NameUnknown = 0 -NameFullyQualifiedDN = 1 -NameSamCompatible = 2 -NameDisplay = 3 -NameUniqueId = 6 -NameCanonical = 7 -NameUserPrincipal = 8 -NameCanonicalEx = 9 -NameServicePrincipal = 10 -NameDnsDomain = 12 - -ComputerNameNetBIOS = 0 -ComputerNameDnsHostname = 1 -ComputerNameDnsDomain = 2 -ComputerNameDnsFullyQualified = 3 -ComputerNamePhysicalNetBIOS = 4 -ComputerNamePhysicalDnsHostname = 5 -ComputerNamePhysicalDnsDomain = 6 -ComputerNamePhysicalDnsFullyQualified = 7 - -LWA_COLORKEY = 0x00000001 -LWA_ALPHA = 0x00000002 -ULW_COLORKEY = 0x00000001 -ULW_ALPHA = 0x00000002 -ULW_OPAQUE = 0x00000004 - -# WinDef.h -TRUE = 1 -FALSE = 0 -MAX_PATH = 260 -# WinGDI.h -AC_SRC_OVER = 0 -AC_SRC_ALPHA = 1 -GRADIENT_FILL_RECT_H = 0 -GRADIENT_FILL_RECT_V = 1 -GRADIENT_FILL_TRIANGLE = 2 -GRADIENT_FILL_OP_FLAG = 255 - -# Bizarrely missing from any platform header. Ref: -# http://www.codeguru.com/forum/archive/index.php/t-426785.html -MAPVK_VK_TO_VSC = 0 -MAPVK_VSC_TO_VK = 1 -MAPVK_VK_TO_CHAR = 2 -MAPVK_VSC_TO_VK_EX = 3 - -USER_TIMER_MAXIMUM = 0x7fffffff - -# From WinBase.h -INFINITE = 0xffffffff - -# From Winuser.h -RIDEV_REMOVE = 0x00000001 -RIDEV_EXCLUDE = 0x00000010 -RIDEV_PAGEONLY = 0x00000020 -RIDEV_NOLEGACY = 0x00000030 -RIDEV_INPUTSINK = 0x00000100 -RIDEV_CAPTUREMOUSE = 0x00000200 -RIDEV_NOHOTKEYS = 0x00000200 -RIDEV_APPKEYS = 0x00000400 -RIDEV_EXMODEMASK = 0x000000F0 -RIDEV_EXINPUTSINK = 0x00001000 # Vista+ -RIDEV_DEVNOTIFY = 0x00002000 # Vista+ - -RI_KEY_MAKE = 0 -RI_KEY_BREAK = 1 -RI_KEY_E0 = 2 -RI_KEY_E1 = 4 -RI_KEY_TERMSRV_SET_LED = 8 -RI_KEY_TERMSRV_SHADOW = 0x10 - -RIM_TYPEMOUSE = 0 -RIM_TYPEKEYBOARD = 1 -RIM_TYPEHID = 2 - -RID_INPUT = 0x10000003 -RID_HEADER = 0x10000005 - -MOUSE_MOVE_RELATIVE = 0 -MOUSE_MOVE_ABSOLUTE = 1 -MOUSE_VIRTUAL_DESKTOP = 0x02 -MOUSE_ATTRIBUTES_CHANGED = 0x04 - -RI_MOUSE_LEFT_BUTTON_DOWN = 0x0001 -RI_MOUSE_LEFT_BUTTON_UP = 0x0002 -RI_MOUSE_RIGHT_BUTTON_DOWN = 0x0004 -RI_MOUSE_RIGHT_BUTTON_UP = 0x0008 -RI_MOUSE_MIDDLE_BUTTON_DOWN = 0x0010 -RI_MOUSE_MIDDLE_BUTTON_UP = 0x0020 - -RI_MOUSE_BUTTON_1_DOWN = RI_MOUSE_LEFT_BUTTON_DOWN -RI_MOUSE_BUTTON_1_UP = RI_MOUSE_LEFT_BUTTON_UP -RI_MOUSE_BUTTON_2_DOWN = RI_MOUSE_RIGHT_BUTTON_DOWN -RI_MOUSE_BUTTON_2_UP = RI_MOUSE_RIGHT_BUTTON_UP -RI_MOUSE_BUTTON_3_DOWN = RI_MOUSE_MIDDLE_BUTTON_DOWN -RI_MOUSE_BUTTON_3_UP = RI_MOUSE_MIDDLE_BUTTON_UP - -RI_MOUSE_BUTTON_4_DOWN = 0x0040 -RI_MOUSE_BUTTON_4_UP = 0x0080 -RI_MOUSE_BUTTON_5_DOWN = 0x0100 -RI_MOUSE_BUTTON_5_UP = 0x0200 - -RI_MOUSE_WHEEL = 0x0400 - -WINDOWS_VISTA_OR_GREATER = sys.getwindowsversion() >= (6, 0) -WINDOWS_7_OR_GREATER = sys.getwindowsversion() >= (6, 1) -WINDOWS_8_OR_GREATER = sys.getwindowsversion() >= (6, 2) -WINDOWS_8_1_OR_GREATER = sys.getwindowsversion() >= (6, 3) -WINDOWS_10_ANNIVERSARY_UPDATE_OR_GREATER = sys.getwindowsversion() >= (10, 0, 14393) # 1607 -WINDOWS_10_CREATORS_UPDATE_OR_GREATER = sys.getwindowsversion() >= (10, 0, 15063) # 1703 - -MSGFLT_ALLOW = 1 -MSGFLT_DISALLOW = 2 -MSGFLT_RESET = 0 - -COINIT_APARTMENTTHREADED = 0x2 -COINIT_MULTITHREADED = 0x0 -COINIT_DISABLE_OLE1DDE = 0x4 -COINIT_SPEED_OVER_MEMORY = 0x8 -RPC_E_CHANGED_MODE = -2147417850 - -MF_ACCESSMODE_READ = 1 -MF_ACCESSMODE_WRITE = 2 -MF_ACCESSMODE_READWRITE = 3 - -MF_OPENMODE_FAIL_IF_NOT_EXIST = 0 -MF_OPENMODE_FAIL_IF_EXIST = 1 -MF_OPENMODE_RESET_IF_EXIST = 2 -MF_OPENMODE_APPEND_IF_EXIST = 3 -MF_OPENMODE_DELETE_IF_EXIST = 4 - -MF_FILEFLAGS_NONE = 0 -MF_FILEFLAGS_NOBUFFERING = 1 - -CLSCTX_INPROC_SERVER = 0x1 - -# From Dwmapi.h -DWM_BB_ENABLE = 0x00000001 -DWM_BB_BLURREGION = 0x00000002 -DWM_BB_TRANSITIONONMAXIMIZED = 0x00000004 - -STREAM_SEEK_SET = 0 -STREAM_SEEK_CUR = 1 -STREAM_SEEK_END = 2 - -LOCALE_NAME_MAX_LENGTH = 85 - -DBT_DEVICEARRIVAL = 0x8000 -DBT_DEVICEREMOVECOMPLETE = 0x8004 - -DBT_DEVTYP_DEVICEINTERFACE = 5 - -DEVICE_NOTIFY_WINDOW_HANDLE = 0 -DEVICE_NOTIFY_SERVICE_HANDLE = 1 diff --git a/spaces/acmyu/frame_interpolation_prototype/frame_dataset.py b/spaces/acmyu/frame_interpolation_prototype/frame_dataset.py deleted file mode 100644 index 38c91acca05bb83e69357efbbe35110f131e53cc..0000000000000000000000000000000000000000 --- a/spaces/acmyu/frame_interpolation_prototype/frame_dataset.py +++ /dev/null @@ -1,67 +0,0 @@ -import os -import pandas as pd -from torchvision.io import read_image -from torch.utils.data import Dataset -import torchvision.transforms as transforms -from torchvision.transforms import functional as TF - -from enum import Enum -import numpy as np -import glob -import random as r -from PIL import Image - - -FILE_TEMPLATE = 'frame_{0:09d}.jpg' - -TRAIN_DATA_PATH = 'data/frames' - -# Custom crop image transformation -class CropTransform: - - def __init__(self, h, w, size): - self.h_coor = h; - self.w_coor = w; - self.size = size; - - def __call__(self, img): - return TF.crop(img, self.h_coor, self.w_coor, self.size, self.size); - -class FrameDataset(Dataset): - def __init__(self, imsize, path = TRAIN_DATA_PATH): - self.crop_size = imsize - self.path = path - return - - def __len__(self): - files = glob.glob(self.path + '/*.jpg') - return len(files) #- 2 - - def __getitem__(self, idx): - #print(idx) - img1 = Image.open(os.path.join(self.path, FILE_TEMPLATE.format(idx))) - #img2 = Image.open(os.path.join(self.path, FILE_TEMPLATE.format(idx+1))) - #img3 = Image.open(os.path.join(self.path, FILE_TEMPLATE.format(idx+2))) - - img_size = min(img1.size) - h = r.randint(0, max(0, img_size - self.crop_size - 1)) - w = r.randint(0, max(0, img_size - self.crop_size - 1)) - - data = [] - data.append(self._transformImageForNoNoiseGenerator(img1, h, w)); - #data.append(self._transformImageForNoNoiseGenerator(img2, h, w)); - #data.append(self._transformImageForNoNoiseGenerator(img3, h, w)); - - #image1 = read_image(img_path1) - return np.asarray(data), 0 - - def _transformImageForNoNoiseGenerator(self, img, h, w): - size = min(img.size) - transTensor = transforms.ToTensor(); - - if (self.crop_size == -1) : - return transTensor(img).numpy(); - else: - transCrop = CropTransform(h, w, min(self.crop_size, size)); - - return transTensor(transCrop(img)).numpy(); \ No newline at end of file diff --git a/spaces/aijack/jojo/op/__init__.py b/spaces/aijack/jojo/op/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/akashpadala/myGenAIAvatarSpeech/README.md b/spaces/akashpadala/myGenAIAvatarSpeech/README.md deleted file mode 100644 index ea4ba2224ec4d70a7150ca95c2314acf05f93895..0000000000000000000000000000000000000000 --- a/spaces/akashpadala/myGenAIAvatarSpeech/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: MyGenAIAvatarSpeech -emoji: 🌖 -colorFrom: green -colorTo: indigo -sdk: gradio -sdk_version: 3.39.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/akhaliq/SummerTime/model/third_party/HMNet/DataLoader/infinibatch/bin/block_randomize_and_batch.py b/spaces/akhaliq/SummerTime/model/third_party/HMNet/DataLoader/infinibatch/bin/block_randomize_and_batch.py deleted file mode 100644 index ed6cc8f0a3adcd0fa5b76fc18a5148395f869b2c..0000000000000000000000000000000000000000 --- a/spaces/akhaliq/SummerTime/model/third_party/HMNet/DataLoader/infinibatch/bin/block_randomize_and_batch.py +++ /dev/null @@ -1,36 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT license. - - -#!/usr/bin/python3.6 - -# simple command-line wrapper around BucketedReadaheadBatchIterator on a IterableChunkedDataset -# Example: -# block_randomize_and_batch my_chunked_data - -import os, sys, inspect - -sys.path.insert( - 0, - os.path.dirname( - os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) - ), -) # find our imports - -from infinibatch.datasets import chunked_dataset_iterator -from infinibatch.iterators import BucketedReadaheadBatchIterator - -sets = sys.argv[1:] - -ds = chunked_dataset_iterator(sets, shuffle=True, buffer_size=10000000, seed=1) -batch_labels = 500 -bg = BucketedReadaheadBatchIterator( - ds, - read_ahead=100, - key=lambda line: len(line), - batch_size=lambda line: batch_labels // (1 + len(line)), - seed=1, -) -for batch in bg: - print(f"\n---- size {len(batch)} ---\n") - print("\n".join(batch)) diff --git a/spaces/albertvillanova/datasets-report/app.py b/spaces/albertvillanova/datasets-report/app.py deleted file mode 100644 index 515eb0b3a667254a69af5d6367306d19cc728c96..0000000000000000000000000000000000000000 --- a/spaces/albertvillanova/datasets-report/app.py +++ /dev/null @@ -1,87 +0,0 @@ -# import datetime -import json -import os -from pathlib import Path - -import gradio as gr -import huggingface_hub as hfh -# from apscheduler.schedulers.background import BackgroundScheduler - - -DATASET_ID = "albertvillanova/datasets-report" -DATASET_PATH = "dataset" -DATA_DIR = "data" -DATA_PATH = f"{DATASET_PATH}/{DATA_DIR}" - - -def pull_dataset_repo(repo_id=DATASET_ID, repo_path=DATASET_PATH): - token = os.environ.get('HUB_TOKEN') - repo = hfh.Repository( - local_dir=repo_path, - clone_from=repo_id, - repo_type="dataset", - use_auth_token=token, - ) - repo.git_pull() - return repo - - -def load_dates(): - return [data_path.stem for data_path in sorted(Path(DATA_PATH).iterdir())] - - -repo = pull_dataset_repo() -dates = load_dates() -datasets = hfh.list_datasets() - - -def filter_datasets_by_date(date_from, date_to): - with open(f"{DATA_PATH}/{date_from}.json") as f: - ids_from = json.load(f) - with open(f"{DATA_PATH}/{date_to}.json") as f: - ids_to = json.load(f) - ids = set(ids_to) - set(ids_from) - dss = [ds for ds in datasets if ds.id in ids] - for ds in dss: - try: - _ = getattr(ds, "downloads") - except AttributeError: - setattr(ds, "downloads", 0) - dss = sorted(dss, key=lambda item: item.downloads, reverse=True) - return dss - - -def filter_dataframe(date_from, date_to): - dss = filter_datasets_by_date(date_from, date_to) - return [[ds.id, ds.downloads] for ds in dss] - - -# def update_datasets(): -# # Retrieve datasets -# datasets = hfh.list_datasets() -# # Save dataset IDs -# repo = pull_dataset_repo() -# os.makedirs(DATA_PATH, exist_ok=True) -# today = datetime.datetime.now(datetime.timezone.utc).date().isoformat() -# with repo.commit(f"Add {today} data file"): -# with open(f"data/{today}.json", "w") as f: -# json.dump([ds.id for ds in sorted(datasets, key=lambda item: item.id)], f) -# -# -# scheduler = BackgroundScheduler() -# scheduler.add_job(update_datasets, trigger="cron", hour=0, minute=1, timezone=datetime.timezone.utc) -# scheduler.start() - - -with gr.Blocks() as demo: - with gr.Row(): - date_from = gr.Dropdown(choices=dates, label="Date from") - date_to = gr.Dropdown(choices=dates, label="Date to") - submit_btn = gr.Button("Submit") - outputs = gr.Dataframe( - headers=["Dataset", "Downloads"], - datatype=["str", "number"], - label="Created datasets", - ) - submit_btn.click(fn=filter_dataframe, inputs=[date_from, date_to], outputs=outputs) -demo.launch() diff --git a/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_internal/operations/build/metadata_editable.py b/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_internal/operations/build/metadata_editable.py deleted file mode 100644 index 4c3f48b6cdfb3087a833546410fc810a343b9e13..0000000000000000000000000000000000000000 --- a/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_internal/operations/build/metadata_editable.py +++ /dev/null @@ -1,41 +0,0 @@ -"""Metadata generation logic for source distributions. -""" - -import os - -from pip._vendor.pep517.wrappers import Pep517HookCaller - -from pip._internal.build_env import BuildEnvironment -from pip._internal.exceptions import ( - InstallationSubprocessError, - MetadataGenerationFailed, -) -from pip._internal.utils.subprocess import runner_with_spinner_message -from pip._internal.utils.temp_dir import TempDirectory - - -def generate_editable_metadata( - build_env: BuildEnvironment, backend: Pep517HookCaller, details: str -) -> str: - """Generate metadata using mechanisms described in PEP 660. - - Returns the generated metadata directory. - """ - metadata_tmpdir = TempDirectory(kind="modern-metadata", globally_managed=True) - - metadata_dir = metadata_tmpdir.path - - with build_env: - # Note that Pep517HookCaller implements a fallback for - # prepare_metadata_for_build_wheel/editable, so we don't have to - # consider the possibility that this hook doesn't exist. - runner = runner_with_spinner_message( - "Preparing editable metadata (pyproject.toml)" - ) - with backend.subprocess_runner(runner): - try: - distinfo_dir = backend.prepare_metadata_for_build_editable(metadata_dir) - except InstallationSubprocessError as error: - raise MetadataGenerationFailed(package_details=details) from error - - return os.path.join(metadata_dir, distinfo_dir) diff --git a/spaces/algomuffin/jojo_fork/e4e/models/stylegan2/__init__.py b/spaces/algomuffin/jojo_fork/e4e/models/stylegan2/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/ali-ghamdan/deoldify/README.md b/spaces/ali-ghamdan/deoldify/README.md deleted file mode 100644 index 57573f735126a106e654a8e82333acff9559f48e..0000000000000000000000000000000000000000 --- a/spaces/ali-ghamdan/deoldify/README.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: deoldify -emoji: 📷 -colorFrom: pink -colorTo: purple -sdk: gradio -app_file: app.py -pinned: false ---- \ No newline at end of file diff --git a/spaces/alirezamsh/small100/app.py b/spaces/alirezamsh/small100/app.py deleted file mode 100644 index a40059edbe40dd1bc89a5fa8384c25b935d35cab..0000000000000000000000000000000000000000 --- a/spaces/alirezamsh/small100/app.py +++ /dev/null @@ -1,37 +0,0 @@ -import gradio as gr -import os - -os.system("pip install transformers sentencepiece torch") - -from transformers import M2M100ForConditionalGeneration -from tokenization_small100 import SMALL100Tokenizer - -langs = """Afrikaans (af), Amharic (am), Arabic (ar), Asturian (ast), Azerbaijani (az), Bashkir (ba), Belarusian (be), Bulgarian (bg), Bengali (bn), Breton (br), Bosnian (bs), Catalan; Valencian (ca), Cebuano (ceb), Czech (cs), Welsh (cy), Danish (da), German (de), Greeek (el), English (en), Spanish (es), Estonian (et), Persian (fa), Fulah (ff), Finnish (fi), French (fr), Western Frisian (fy), Irish (ga), Gaelic; Scottish Gaelic (gd), Galician (gl), Gujarati (gu), Hausa (ha), Hebrew (he), Hindi (hi), Croatian (hr), Haitian; Haitian Creole (ht), Hungarian (hu), Armenian (hy), Indonesian (id), Igbo (ig), Iloko (ilo), Icelandic (is), Italian (it), Japanese (ja), Javanese (jv), Georgian (ka), Kazakh (kk), Central Khmer (km), Kannada (kn), -Korean (ko), Luxembourgish; Letzeburgesch (lb), Ganda (lg), Lingala (ln), Lao (lo), Lithuanian (lt), Latvian (lv), Malagasy (mg), Macedonian (mk), Malayalam (ml), Mongolian (mn), Marathi (mr), Malay (ms), Burmese (my), Nepali (ne), Dutch; Flemish (nl), Norwegian (no), Northern Sotho (ns), Occitan (post 1500) (oc), Oriya (or), Panjabi; Punjabi (pa), Polish (pl), Pushto; Pashto (ps), Portuguese (pt), Romanian; Moldavian; Moldovan (ro), Russian (ru), Sindhi (sd), Sinhala; Sinhalese (si), Slovak (sk), -Slovenian (sl), Somali (so), Albanian (sq), Serbian (sr), Swati (ss), Sundanese (su), Swedish (sv), Swahili (sw), Tamil (ta), Thai (th), Tagalog (tl), Tswana (tn), -Turkish (tr), Ukrainian (uk), Urdu (ur), Uzbek (uz), Vietnamese (vi), Wolof (wo), Xhosa (xh), Yiddish (yi), Yoruba (yo), Chinese (zh), Zulu (zu)""" -lang_list = [lang.strip() for lang in langs.split(',')] - -model = M2M100ForConditionalGeneration.from_pretrained("alirezamsh/small100") -tokenizer = SMALL100Tokenizer.from_pretrained("alirezamsh/small100") - -description = """This is an official demo for the paper [*SMaLL-100: Introducing Shallow Multilingual Machine Translation Model for Low-Resource Languages*](https://arxiv.org/abs/2210.11621) by Alireza Mohammadshahi, Vassilina Nikoulina, Alexandre Berard, Caroline Brun, James Henderson, Laurent Besacier - -In this paper, they propose a compact and shallow massively multilingual MT model, and achieve competitive results with M2M-100, while being super smaller and faster. More details are provided [here](https://huggingface.co/alirezamsh/small100). Currently running on 2 vCPU - 16GB RAM.""" - -def small100_tr(lang, text): - - lang = lang.split(" ")[-1][1:-1] - - tokenizer.tgt_lang = lang - encoded_text = tokenizer(text, return_tensors="pt") - generated_tokens = model.generate(**encoded_text) - return tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)[0] - -examples = [["French (fr)", "Life is like a box of chocolates."]] - -output_text = gr.outputs.Textbox() -gr.Interface(small100_tr, inputs=[gr.inputs.Dropdown(lang_list, label=" Target Language"), 'text'], outputs=output_text, title="SMaLL100: Translate much faster between 100 languages", - description=description, - examples=examples - ).launch() diff --git a/spaces/allknowingroger/Image-Models-Test207/app.py b/spaces/allknowingroger/Image-Models-Test207/app.py deleted file mode 100644 index e3b99a48e4b9d7d70aad392e4869caba9c2537e2..0000000000000000000000000000000000000000 --- a/spaces/allknowingroger/Image-Models-Test207/app.py +++ /dev/null @@ -1,144 +0,0 @@ -import gradio as gr -# import os -# import sys -# from pathlib import Path -import time - -models =[ - "jordanhilado/sd-1-5-pokemon-lora", - "MaxReynolds/SouderRocketLauncherNetCombined_LORA", - "hahminlew/sdxl-kream-model-lora", - "linuxlewis/lucy-sdxl", - "dbarbedillo/tomasthecat_t2", - "lberglund/sweep_full_6_20231012154758", - "dbarbedillo/tomasthecat_t1", - "merve/emoji-dreambooth-trained-xl", - "Daniil-plotnikov/deepvision-v4-0", -] - - -model_functions = {} -model_idx = 1 -for model_path in models: - try: - model_functions[model_idx] = gr.Interface.load(f"models/{model_path}", live=False, preprocess=True, postprocess=False) - except Exception as error: - def the_fn(txt): - return None - model_functions[model_idx] = gr.Interface(fn=the_fn, inputs=["text"], outputs=["image"]) - model_idx+=1 - - -def send_it_idx(idx): - def send_it_fn(prompt): - output = (model_functions.get(str(idx)) or model_functions.get(str(1)))(prompt) - return output - return send_it_fn - -def get_prompts(prompt_text): - return prompt_text - -def clear_it(val): - if int(val) != 0: - val = 0 - else: - val = 0 - pass - return val - -def all_task_end(cnt,t_stamp): - to = t_stamp + 60 - et = time.time() - if et > to and t_stamp != 0: - d = gr.update(value=0) - tog = gr.update(value=1) - #print(f'to: {to} et: {et}') - else: - if cnt != 0: - d = gr.update(value=et) - else: - d = gr.update(value=0) - tog = gr.update(value=0) - #print (f'passing: to: {to} et: {et}') - pass - return d, tog - -def all_task_start(): - print("\n\n\n\n\n\n\n") - t = time.gmtime() - t_stamp = time.time() - current_time = time.strftime("%H:%M:%S", t) - return gr.update(value=t_stamp), gr.update(value=t_stamp), gr.update(value=0) - -def clear_fn(): - nn = len(models) - return tuple([None, *[None for _ in range(nn)]]) - - - -with gr.Blocks(title="SD Models") as my_interface: - with gr.Column(scale=12): - # with gr.Row(): - # gr.Markdown("""- Primary prompt: 你想画的内容(英文单词,如 a cat, 加英文逗号效果更好;点 Improve 按钮进行完善)\n- Real prompt: 完善后的提示词,出现后再点右边的 Run 按钮开始运行""") - with gr.Row(): - with gr.Row(scale=6): - primary_prompt=gr.Textbox(label="Prompt", value="") - # real_prompt=gr.Textbox(label="Real prompt") - with gr.Row(scale=6): - # improve_prompts_btn=gr.Button("Improve") - with gr.Row(): - run=gr.Button("Run",variant="primary") - clear_btn=gr.Button("Clear") - with gr.Row(): - sd_outputs = {} - model_idx = 1 - for model_path in models: - with gr.Column(scale=3, min_width=320): - with gr.Box(): - sd_outputs[model_idx] = gr.Image(label=model_path) - pass - model_idx += 1 - pass - pass - - with gr.Row(visible=False): - start_box=gr.Number(interactive=False) - end_box=gr.Number(interactive=False) - tog_box=gr.Textbox(value=0,interactive=False) - - start_box.change( - all_task_end, - [start_box, end_box], - [start_box, tog_box], - every=1, - show_progress=False) - - primary_prompt.submit(all_task_start, None, [start_box, end_box, tog_box]) - run.click(all_task_start, None, [start_box, end_box, tog_box]) - runs_dict = {} - model_idx = 1 - for model_path in models: - runs_dict[model_idx] = run.click(model_functions[model_idx], inputs=[primary_prompt], outputs=[sd_outputs[model_idx]]) - model_idx += 1 - pass - pass - - # improve_prompts_btn_clicked=improve_prompts_btn.click( - # get_prompts, - # inputs=[primary_prompt], - # outputs=[primary_prompt], - # cancels=list(runs_dict.values())) - clear_btn.click( - clear_fn, - None, - [primary_prompt, *list(sd_outputs.values())], - cancels=[*list(runs_dict.values())]) - tog_box.change( - clear_it, - tog_box, - tog_box, - cancels=[*list(runs_dict.values())]) - -my_interface.queue(concurrency_count=600, status_update_rate=1) -my_interface.launch(inline=True, show_api=False) - \ No newline at end of file diff --git a/spaces/allknowingroger/Image-Models-Test31/app.py b/spaces/allknowingroger/Image-Models-Test31/app.py deleted file mode 100644 index 987cc4cf3e5d462a68239ff8ec6e21cb17140808..0000000000000000000000000000000000000000 --- a/spaces/allknowingroger/Image-Models-Test31/app.py +++ /dev/null @@ -1,144 +0,0 @@ -import gradio as gr -# import os -# import sys -# from pathlib import Path -import time - -models =[ - "hangeol/test_sep", - "hangeol/42", - "udg/7bc028fc-950b-4d22-a0a0-1ef982d0934a", - "wujia/fantuan_result", - "XiaominDLUT/textual_inversion_style", - "yugkha3/avatar", - "yuanzheng/zhu-family-v1-sd15", - "yuanzheng/fangyuan", - "yuanzheng/familyportrait", -] - - -model_functions = {} -model_idx = 1 -for model_path in models: - try: - model_functions[model_idx] = gr.Interface.load(f"models/{model_path}", live=False, preprocess=True, postprocess=False) - except Exception as error: - def the_fn(txt): - return None - model_functions[model_idx] = gr.Interface(fn=the_fn, inputs=["text"], outputs=["image"]) - model_idx+=1 - - -def send_it_idx(idx): - def send_it_fn(prompt): - output = (model_functions.get(str(idx)) or model_functions.get(str(1)))(prompt) - return output - return send_it_fn - -def get_prompts(prompt_text): - return prompt_text - -def clear_it(val): - if int(val) != 0: - val = 0 - else: - val = 0 - pass - return val - -def all_task_end(cnt,t_stamp): - to = t_stamp + 60 - et = time.time() - if et > to and t_stamp != 0: - d = gr.update(value=0) - tog = gr.update(value=1) - #print(f'to: {to} et: {et}') - else: - if cnt != 0: - d = gr.update(value=et) - else: - d = gr.update(value=0) - tog = gr.update(value=0) - #print (f'passing: to: {to} et: {et}') - pass - return d, tog - -def all_task_start(): - print("\n\n\n\n\n\n\n") - t = time.gmtime() - t_stamp = time.time() - current_time = time.strftime("%H:%M:%S", t) - return gr.update(value=t_stamp), gr.update(value=t_stamp), gr.update(value=0) - -def clear_fn(): - nn = len(models) - return tuple([None, *[None for _ in range(nn)]]) - - - -with gr.Blocks(title="SD Models") as my_interface: - with gr.Column(scale=12): - # with gr.Row(): - # gr.Markdown("""- Primary prompt: 你想画的内容(英文单词,如 a cat, 加英文逗号效果更好;点 Improve 按钮进行完善)\n- Real prompt: 完善后的提示词,出现后再点右边的 Run 按钮开始运行""") - with gr.Row(): - with gr.Row(scale=6): - primary_prompt=gr.Textbox(label="Prompt", value="") - # real_prompt=gr.Textbox(label="Real prompt") - with gr.Row(scale=6): - # improve_prompts_btn=gr.Button("Improve") - with gr.Row(): - run=gr.Button("Run",variant="primary") - clear_btn=gr.Button("Clear") - with gr.Row(): - sd_outputs = {} - model_idx = 1 - for model_path in models: - with gr.Column(scale=3, min_width=320): - with gr.Box(): - sd_outputs[model_idx] = gr.Image(label=model_path) - pass - model_idx += 1 - pass - pass - - with gr.Row(visible=False): - start_box=gr.Number(interactive=False) - end_box=gr.Number(interactive=False) - tog_box=gr.Textbox(value=0,interactive=False) - - start_box.change( - all_task_end, - [start_box, end_box], - [start_box, tog_box], - every=1, - show_progress=False) - - primary_prompt.submit(all_task_start, None, [start_box, end_box, tog_box]) - run.click(all_task_start, None, [start_box, end_box, tog_box]) - runs_dict = {} - model_idx = 1 - for model_path in models: - runs_dict[model_idx] = run.click(model_functions[model_idx], inputs=[primary_prompt], outputs=[sd_outputs[model_idx]]) - model_idx += 1 - pass - pass - - # improve_prompts_btn_clicked=improve_prompts_btn.click( - # get_prompts, - # inputs=[primary_prompt], - # outputs=[primary_prompt], - # cancels=list(runs_dict.values())) - clear_btn.click( - clear_fn, - None, - [primary_prompt, *list(sd_outputs.values())], - cancels=[*list(runs_dict.values())]) - tog_box.change( - clear_it, - tog_box, - tog_box, - cancels=[*list(runs_dict.values())]) - -my_interface.queue(concurrency_count=600, status_update_rate=1) -my_interface.launch(inline=True, show_api=False) - \ No newline at end of file diff --git a/spaces/almakedon/faster-whisper-webui/src/vad.py b/spaces/almakedon/faster-whisper-webui/src/vad.py deleted file mode 100644 index e68ee7391e93f539a05d548601f2d87168bb1282..0000000000000000000000000000000000000000 --- a/spaces/almakedon/faster-whisper-webui/src/vad.py +++ /dev/null @@ -1,568 +0,0 @@ -from abc import ABC, abstractmethod -from collections import Counter, deque -import time - -from typing import Any, Deque, Iterator, List, Dict - -from pprint import pprint -from src.hooks.progressListener import ProgressListener -from src.hooks.subTaskProgressListener import SubTaskProgressListener -from src.hooks.whisperProgressHook import create_progress_listener_handle -from src.modelCache import GLOBAL_MODEL_CACHE, ModelCache - -from src.segments import merge_timestamps -from src.whisper.abstractWhisperContainer import AbstractWhisperCallback - -# Workaround for https://github.com/tensorflow/tensorflow/issues/48797 -try: - import tensorflow as tf -except ModuleNotFoundError: - # Error handling - pass - -import torch - -import ffmpeg -import numpy as np - -from src.utils import format_timestamp -from enum import Enum - -class NonSpeechStrategy(Enum): - """ - Ignore non-speech frames segments. - """ - SKIP = 1 - """ - Just treat non-speech segments as speech. - """ - CREATE_SEGMENT = 2 - """ - Expand speech segments into subsequent non-speech segments. - """ - EXPAND_SEGMENT = 3 - -# Defaults for Silero -SPEECH_TRESHOLD = 0.3 - -# Minimum size of segments to process -MIN_SEGMENT_DURATION = 1 - -# The maximum time for texts from old segments to be used in the next segment -MAX_PROMPT_WINDOW = 0 # seconds (0 = disabled) -PROMPT_NO_SPEECH_PROB = 0.1 # Do not pass the text from segments with a no speech probability higher than this - -VAD_MAX_PROCESSING_CHUNK = 60 * 60 # 60 minutes of audio - -class TranscriptionConfig(ABC): - def __init__(self, non_speech_strategy: NonSpeechStrategy = NonSpeechStrategy.SKIP, - segment_padding_left: float = None, segment_padding_right = None, max_silent_period: float = None, - max_merge_size: float = None, max_prompt_window: float = None, initial_segment_index = -1): - self.non_speech_strategy = non_speech_strategy - self.segment_padding_left = segment_padding_left - self.segment_padding_right = segment_padding_right - self.max_silent_period = max_silent_period - self.max_merge_size = max_merge_size - self.max_prompt_window = max_prompt_window - self.initial_segment_index = initial_segment_index - -class PeriodicTranscriptionConfig(TranscriptionConfig): - def __init__(self, periodic_duration: float, non_speech_strategy: NonSpeechStrategy = NonSpeechStrategy.SKIP, - segment_padding_left: float = None, segment_padding_right = None, max_silent_period: float = None, - max_merge_size: float = None, max_prompt_window: float = None, initial_segment_index = -1): - super().__init__(non_speech_strategy, segment_padding_left, segment_padding_right, max_silent_period, max_merge_size, max_prompt_window, initial_segment_index) - self.periodic_duration = periodic_duration - -class AbstractTranscription(ABC): - def __init__(self, sampling_rate: int = 16000): - self.sampling_rate = sampling_rate - - def get_audio_segment(self, str, start_time: str = None, duration: str = None): - return load_audio(str, self.sampling_rate, start_time, duration) - - def is_transcribe_timestamps_fast(self): - """ - Determine if get_transcribe_timestamps is fast enough to not need parallelization. - """ - return False - - @abstractmethod - def get_transcribe_timestamps(self, audio: str, config: TranscriptionConfig, start_time: float, end_time: float): - """ - Get the start and end timestamps of the sections that should be transcribed by this VAD method. - - Parameters - ---------- - audio: str - The audio file. - config: TranscriptionConfig - The transcription configuration. - - Returns - ------- - A list of start and end timestamps, in fractional seconds. - """ - return - - def get_merged_timestamps(self, timestamps: List[Dict[str, Any]], config: TranscriptionConfig, total_duration: float): - """ - Get the start and end timestamps of the sections that should be transcribed by this VAD method, - after merging the given segments using the specified configuration. - - Parameters - ---------- - audio: str - The audio file. - config: TranscriptionConfig - The transcription configuration. - - Returns - ------- - A list of start and end timestamps, in fractional seconds. - """ - merged = merge_timestamps(timestamps, config.max_silent_period, config.max_merge_size, - config.segment_padding_left, config.segment_padding_right) - - if config.non_speech_strategy != NonSpeechStrategy.SKIP: - # Expand segments to include the gaps between them - if (config.non_speech_strategy == NonSpeechStrategy.CREATE_SEGMENT): - # When we have a prompt window, we create speech segments betwen each segment if we exceed the merge size - merged = self.fill_gaps(merged, total_duration=total_duration, max_expand_size=config.max_merge_size) - elif config.non_speech_strategy == NonSpeechStrategy.EXPAND_SEGMENT: - # With no prompt window, it is better to just expand the segments (this effectively passes the prompt to the next segment) - merged = self.expand_gaps(merged, total_duration=total_duration) - else: - raise Exception("Unknown non-speech strategy: " + str(config.non_speech_strategy)) - - print("Transcribing non-speech:") - pprint(merged) - return merged - - def transcribe(self, audio: str, whisperCallable: AbstractWhisperCallback, config: TranscriptionConfig, - progressListener: ProgressListener = None): - """ - Transcribe the given audo file. - - Parameters - ---------- - audio: str - The audio file. - whisperCallable: WhisperCallback - A callback object to call to transcribe each segment. - - Returns - ------- - A list of start and end timestamps, in fractional seconds. - """ - - try: - max_audio_duration = self.get_audio_duration(audio, config) - timestamp_segments = self.get_transcribe_timestamps(audio, config, 0, max_audio_duration) - - # Get speech timestamps from full audio file - merged = self.get_merged_timestamps(timestamp_segments, config, max_audio_duration) - - # A deque of transcribed segments that is passed to the next segment as a prompt - prompt_window = deque() - - print("Processing timestamps:") - pprint(merged) - - result = { - 'text': "", - 'segments': [], - 'language': "" - } - languageCounter = Counter() - detected_language = None - - segment_index = config.initial_segment_index - - # Calculate progress - progress_start_offset = merged[0]['start'] if len(merged) > 0 else 0 - progress_total_duration = sum([segment['end'] - segment['start'] for segment in merged]) - - # For each time segment, run whisper - for segment in merged: - segment_index += 1 - segment_start = segment['start'] - segment_end = segment['end'] - segment_expand_amount = segment.get('expand_amount', 0) - segment_gap = segment.get('gap', False) - - segment_duration = segment_end - segment_start - - if segment_duration < MIN_SEGMENT_DURATION: - continue - - # Audio to run on Whisper - segment_audio = self.get_audio_segment(audio, start_time = str(segment_start), duration = str(segment_duration)) - # Previous segments to use as a prompt - segment_prompt = ' '.join([segment['text'] for segment in prompt_window]) if len(prompt_window) > 0 else None - - # Detected language - detected_language = languageCounter.most_common(1)[0][0] if len(languageCounter) > 0 else None - - print("Running whisper from ", format_timestamp(segment_start), " to ", format_timestamp(segment_end), ", duration: ", - segment_duration, "expanded: ", segment_expand_amount, "prompt: ", segment_prompt, "language: ", detected_language) - - perf_start_time = time.perf_counter() - - scaled_progress_listener = SubTaskProgressListener(progressListener, base_task_total=progress_total_duration, - sub_task_start=segment_start - progress_start_offset, sub_task_total=segment_duration) - segment_result = whisperCallable.invoke(segment_audio, segment_index, segment_prompt, detected_language, progress_listener=scaled_progress_listener) - - perf_end_time = time.perf_counter() - print("Whisper took {} seconds".format(perf_end_time - perf_start_time)) - - adjusted_segments = self.adjust_timestamp(segment_result["segments"], adjust_seconds=segment_start, max_source_time=segment_duration) - - # Propagate expand amount to the segments - if (segment_expand_amount > 0): - segment_without_expansion = segment_duration - segment_expand_amount - - for adjusted_segment in adjusted_segments: - adjusted_segment_end = adjusted_segment['end'] - - # Add expand amount if the segment got expanded - if (adjusted_segment_end > segment_without_expansion): - adjusted_segment["expand_amount"] = adjusted_segment_end - segment_without_expansion - - # Append to output - result['text'] += segment_result['text'] - result['segments'].extend(adjusted_segments) - - # Increment detected language - if not segment_gap: - languageCounter[segment_result['language']] += 1 - - # Update prompt window - self.__update_prompt_window(prompt_window, adjusted_segments, segment_end, segment_gap, config) - - if detected_language is not None: - result['language'] = detected_language - finally: - # Notify progress listener that we are done - if progressListener is not None: - progressListener.on_finished() - return result - - def get_audio_duration(self, audio: str, config: TranscriptionConfig): - return get_audio_duration(audio) - - def __update_prompt_window(self, prompt_window: Deque, adjusted_segments: List, segment_end: float, segment_gap: bool, config: TranscriptionConfig): - if (config.max_prompt_window is not None and config.max_prompt_window > 0): - # Add segments to the current prompt window (unless it is a speech gap) - if not segment_gap: - for segment in adjusted_segments: - if segment.get('no_speech_prob', 0) <= PROMPT_NO_SPEECH_PROB: - prompt_window.append(segment) - - while (len(prompt_window) > 0): - first_end_time = prompt_window[0].get('end', 0) - # Time expanded in the segments should be discounted from the prompt window - first_expand_time = prompt_window[0].get('expand_amount', 0) - - if (first_end_time - first_expand_time < segment_end - config.max_prompt_window): - prompt_window.popleft() - else: - break - - def include_gaps(self, segments: Iterator[dict], min_gap_length: float, total_duration: float): - result = [] - last_end_time = 0 - - for segment in segments: - segment_start = float(segment['start']) - segment_end = float(segment['end']) - - if (last_end_time != segment_start): - delta = segment_start - last_end_time - - if (min_gap_length is None or delta >= min_gap_length): - result.append( { 'start': last_end_time, 'end': segment_start, 'gap': True } ) - - last_end_time = segment_end - result.append(segment) - - # Also include total duration if specified - if (total_duration is not None and last_end_time < total_duration): - delta = total_duration - segment_start - - if (min_gap_length is None or delta >= min_gap_length): - result.append( { 'start': last_end_time, 'end': total_duration, 'gap': True } ) - - return result - - # Expand the end time of each segment to the start of the next segment - def expand_gaps(self, segments: List[Dict[str, Any]], total_duration: float): - result = [] - - if len(segments) == 0: - return result - - # Add gap at the beginning if needed - if (segments[0]['start'] > 0): - result.append({ 'start': 0, 'end': segments[0]['start'], 'gap': True } ) - - for i in range(len(segments) - 1): - current_segment = segments[i] - next_segment = segments[i + 1] - - delta = next_segment['start'] - current_segment['end'] - - # Expand if the gap actually exists - if (delta >= 0): - current_segment = current_segment.copy() - current_segment['expand_amount'] = delta - current_segment['end'] = next_segment['start'] - - result.append(current_segment) - - # Add last segment - last_segment = segments[-1] - result.append(last_segment) - - # Also include total duration if specified - if (total_duration is not None): - last_segment = result[-1] - - if (last_segment['end'] < total_duration): - last_segment = last_segment.copy() - last_segment['end'] = total_duration - result[-1] = last_segment - - return result - - def fill_gaps(self, segments: List[Dict[str, Any]], total_duration: float, max_expand_size: float = None): - result = [] - - if len(segments) == 0: - return result - - # Add gap at the beginning if needed - if (segments[0]['start'] > 0): - result.append({ 'start': 0, 'end': segments[0]['start'], 'gap': True } ) - - for i in range(len(segments) - 1): - expanded = False - current_segment = segments[i] - next_segment = segments[i + 1] - - delta = next_segment['start'] - current_segment['end'] - - if (max_expand_size is not None and delta <= max_expand_size): - # Just expand the current segment - current_segment = current_segment.copy() - current_segment['expand_amount'] = delta - current_segment['end'] = next_segment['start'] - expanded = True - - result.append(current_segment) - - # Add a gap to the next segment if needed - if (delta >= 0 and not expanded): - result.append({ 'start': current_segment['end'], 'end': next_segment['start'], 'gap': True } ) - - # Add last segment - last_segment = segments[-1] - result.append(last_segment) - - # Also include total duration if specified - if (total_duration is not None): - last_segment = result[-1] - - delta = total_duration - last_segment['end'] - - if (delta > 0): - if (max_expand_size is not None and delta <= max_expand_size): - # Expand the last segment - last_segment = last_segment.copy() - last_segment['expand_amount'] = delta - last_segment['end'] = total_duration - result[-1] = last_segment - else: - result.append({ 'start': last_segment['end'], 'end': total_duration, 'gap': True } ) - - return result - - def adjust_timestamp(self, segments: Iterator[dict], adjust_seconds: float, max_source_time: float = None): - result = [] - - for segment in segments: - segment_start = float(segment['start']) - segment_end = float(segment['end']) - - # Filter segments? - if (max_source_time is not None): - if (segment_start > max_source_time): - continue - segment_end = min(max_source_time, segment_end) - - new_segment = segment.copy() - - # Add to start and end - new_segment['start'] = segment_start + adjust_seconds - new_segment['end'] = segment_end + adjust_seconds - - # Handle words - if ('words' in new_segment): - for word in new_segment['words']: - # Adjust start and end - word['start'] = word['start'] + adjust_seconds - word['end'] = word['end'] + adjust_seconds - - result.append(new_segment) - return result - - def multiply_timestamps(self, timestamps: List[Dict[str, Any]], factor: float): - result = [] - - for entry in timestamps: - start = entry['start'] - end = entry['end'] - - result.append({ - 'start': start * factor, - 'end': end * factor - }) - return result - - -class VadSileroTranscription(AbstractTranscription): - def __init__(self, sampling_rate: int = 16000, cache: ModelCache = None): - super().__init__(sampling_rate=sampling_rate) - self.model = None - self.cache = cache - self._initialize_model() - - def _initialize_model(self): - if (self.cache is not None): - model_key = "VadSileroTranscription" - self.model, self.get_speech_timestamps = self.cache.get(model_key, self._create_model) - print("Loaded Silerio model from cache.") - else: - self.model, self.get_speech_timestamps = self._create_model() - print("Created Silerio model") - - def _create_model(self): - model, utils = torch.hub.load(repo_or_dir='snakers4/silero-vad', model='silero_vad') - - # Silero does not benefit from multi-threading - torch.set_num_threads(1) # JIT - (get_speech_timestamps, _, _, _, _) = utils - - return model, get_speech_timestamps - - def get_transcribe_timestamps(self, audio: str, config: TranscriptionConfig, start_time: float, end_time: float): - result = [] - - print("Getting timestamps from audio file: {}, start: {}, duration: {}".format(audio, start_time, end_time)) - perf_start_time = time.perf_counter() - - # Divide procesisng of audio into chunks - chunk_start = start_time - - while (chunk_start < end_time): - chunk_duration = min(end_time - chunk_start, VAD_MAX_PROCESSING_CHUNK) - - print("Processing VAD in chunk from {} to {}".format(format_timestamp(chunk_start), format_timestamp(chunk_start + chunk_duration))) - wav = self.get_audio_segment(audio, str(chunk_start), str(chunk_duration)) - - sample_timestamps = self.get_speech_timestamps(wav, self.model, sampling_rate=self.sampling_rate, threshold=SPEECH_TRESHOLD) - seconds_timestamps = self.multiply_timestamps(sample_timestamps, factor=1 / self.sampling_rate) - adjusted = self.adjust_timestamp(seconds_timestamps, adjust_seconds=chunk_start, max_source_time=chunk_start + chunk_duration) - - #pprint(adjusted) - - result.extend(adjusted) - chunk_start += chunk_duration - - perf_end_time = time.perf_counter() - print("VAD processing took {} seconds".format(perf_end_time - perf_start_time)) - - return result - - def __getstate__(self): - # We only need the sampling rate - return { 'sampling_rate': self.sampling_rate } - - def __setstate__(self, state): - self.sampling_rate = state['sampling_rate'] - self.model = None - # Use the global cache - self.cache = GLOBAL_MODEL_CACHE - self._initialize_model() - -# A very simple VAD that just marks every N seconds as speech -class VadPeriodicTranscription(AbstractTranscription): - def __init__(self, sampling_rate: int = 16000): - super().__init__(sampling_rate=sampling_rate) - - def is_transcribe_timestamps_fast(self): - # This is a very fast VAD - no need to parallelize it - return True - - def get_transcribe_timestamps(self, audio: str, config: PeriodicTranscriptionConfig, start_time: float, end_time: float): - result = [] - - # Generate a timestamp every N seconds - start_timestamp = start_time - - while (start_timestamp < end_time): - end_timestamp = min(start_timestamp + config.periodic_duration, end_time) - segment_duration = end_timestamp - start_timestamp - - # Minimum duration is 1 second - if (segment_duration >= 1): - result.append( { 'start': start_timestamp, 'end': end_timestamp } ) - - start_timestamp = end_timestamp - - return result - -def get_audio_duration(file: str): - return float(ffmpeg.probe(file)["format"]["duration"]) - -def load_audio(file: str, sample_rate: int = 16000, - start_time: str = None, duration: str = None): - """ - Open an audio file and read as mono waveform, resampling as necessary - - Parameters - ---------- - file: str - The audio file to open - - sr: int - The sample rate to resample the audio if necessary - - start_time: str - The start time, using the standard FFMPEG time duration syntax, or None to disable. - - duration: str - The duration, using the standard FFMPEG time duration syntax, or None to disable. - - Returns - ------- - A NumPy array containing the audio waveform, in float32 dtype. - """ - try: - inputArgs = {'threads': 0} - - if (start_time is not None): - inputArgs['ss'] = start_time - if (duration is not None): - inputArgs['t'] = duration - - # This launches a subprocess to decode audio while down-mixing and resampling as necessary. - # Requires the ffmpeg CLI and `ffmpeg-python` package to be installed. - out, _ = ( - ffmpeg.input(file, **inputArgs) - .output("-", format="s16le", acodec="pcm_s16le", ac=1, ar=sample_rate) - .run(cmd="ffmpeg", capture_stdout=True, capture_stderr=True) - ) - except ffmpeg.Error as e: - raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}") - - return np.frombuffer(out, np.int16).flatten().astype(np.float32) / 32768.0 \ No newline at end of file diff --git a/spaces/andryMLOPS/ASTA-GPT-3.8_web_ui/g4f/Provider/Providers/Ezcht.py b/spaces/andryMLOPS/ASTA-GPT-3.8_web_ui/g4f/Provider/Providers/Ezcht.py deleted file mode 100644 index baec214f7e0e936ea06bffa357e1bd2b77cd4089..0000000000000000000000000000000000000000 --- a/spaces/andryMLOPS/ASTA-GPT-3.8_web_ui/g4f/Provider/Providers/Ezcht.py +++ /dev/null @@ -1,35 +0,0 @@ -import requests -import os -import json -from ...typing import sha256, Dict, get_type_hints - -url = 'https://gpt4.ezchat.top' -model = ['gpt-3.5-turbo', 'gpt-3.5-turbo-16k', 'gpt-3.5-turbo-16k-0613', 'gpt-3.5-turbo-0613'] -supports_stream = True -needs_auth = False - -def _create_completion(model: str, messages: list, stream: bool, temperature: float = 0.7, **kwargs): - headers = { - 'Content-Type': 'application/json', - } - data = { - 'model': model, - 'temperature': 0.7, - 'presence_penalty': 0, - 'messages': messages, - } - response = requests.post(url + '/api/openai/v1/chat/completions', - json=data, stream=True) - - if stream: - for chunk in response.iter_content(chunk_size=None): - chunk = chunk.decode('utf-8') - if chunk.strip(): - message = json.loads(chunk)['choices'][0]['message']['content'] - yield message - else: - message = response.json()['choices'][0]['message']['content'] - yield message - -params = f'g4f.Providers.{os.path.basename(__file__)[:-3]} supports: ' + \ - '(%s)' % ', '.join([f"{name}: {get_type_hints(_create_completion)[name].__name__}" for name in _create_completion.__code__.co_varnames[:_create_completion.__code__.co_argcount]]) \ No newline at end of file diff --git a/spaces/anhnv125/FRN/README.md b/spaces/anhnv125/FRN/README.md deleted file mode 100644 index 72e06f021855083b2fe07197d45f6fd465d93342..0000000000000000000000000000000000000000 --- a/spaces/anhnv125/FRN/README.md +++ /dev/null @@ -1,196 +0,0 @@ ---- -title: FRN -emoji: 📉 -colorFrom: gray -colorTo: red -sdk: streamlit -pinned: true -app_file: app.py -sdk_version: 1.10.0 -python_version: 3.8 ---- - -# FRN - Full-band Recurrent Network Official Implementation - -**Improving performance of real-time full-band blind packet-loss concealment with predictive network - ICASSP 2023** - -[![Generic badge](https://img.shields.io/badge/arXiv-2211.04071-brightgreen.svg?style=flat-square)](https://arxiv.org/abs/2211.04071) -[![Generic badge](https://img.shields.io/github/stars/Crystalsound/FRN?color=yellow&label=FRN&logo=github&style=flat-square)](https://github.com/Crystalsound/FRN/) -[![Generic badge](https://img.shields.io/github/last-commit/Crystalsound/FRN?color=blue&label=last%20commit&style=flat-square)](https://github.com/Crystalsound/FRN/commits) - -## License and citation - -This repository is released under the CC-BY-NC 4.0. license as found in the LICENSE file. - -If you use our software, please cite as below. -For future queries, please contact [anh.nguyen@namitech.io](mailto:anh.nguyen@namitech.io). - -Copyright © 2022 NAMI TECHNOLOGY JSC, Inc. All rights reserved. - -``` -@misc{Nguyen2022ImprovingPO, - title={Improving performance of real-time full-band blind packet-loss concealment with predictive network}, - author={Viet-Anh Nguyen and Anh H. T. Nguyen and Andy W. H. Khong}, - year={2022}, - eprint={2211.04071}, - archivePrefix={arXiv}, - primaryClass={cs.LG} -} -``` - -# 1. Results - -Our model achieved a significant gain over baselines. Here, we include the predicted packet loss concealment -mean-opinion-score (PLCMOS) using Microsoft's [PLCMOS](https://github.com/microsoft/PLC-Challenge/tree/main/PLCMOS) -service. Please refer to our paper for more benchmarks. - -| Model | PLCMOS | -|---------|-----------| -| Input | 3.517 | -| tPLC | 3.463 | -| TFGAN | 3.645 | -| **FRN** | **3.655** | - -We also provide several audio samples in [https://crystalsound.github.io/FRN/](https://crystalsound.github.io/FRN/) for -comparison. - -# 2. Installation - -## Setup - -### Clone the repo - -``` -$ git clone https://github.com/Crystalsound/FRN.git -$ cd FRN -``` - -### Install dependencies - -* Our implementation requires the `libsndfile` libraries for the Python packages `soundfile`. On Ubuntu, they can be - easily installed using `apt-get`: - ``` - $ apt-get update && apt-get install libsndfile-dev - ``` -* Create a Python 3.8 environment. Conda is recommended: - ``` - $ conda create -n frn python=3.8 - $ conda activate frn - ``` - -* Install the requirements: - ``` - $ pip install -r requirements.txt - ``` - -# 3. Data preparation - -In our paper, we conduct experiments on the [VCTK](https://datashare.ed.ac.uk/handle/10283/3443) dataset. - -* Download and extract the datasets: - ``` - $ wget http://www.udialogue.org/download/VCTK-Corpus.tar.gz -O data/vctk/VCTK-Corpus.tar.gz - $ tar -zxvf data/vctk/VCTK-Corpus.tar.gz -C data/vctk/ --strip-components=1 - ``` - - After extracting the datasets, your `./data` directory should look like this: - - ``` - . - |--data - |--vctk - |--wav48 - |--p225 - |--p225_001.wav - ... - |--train.txt - |--test.txt - ``` -* In order to load the datasets, text files that contain training and testing audio paths are required. We have - prepared `train.txt` and `test.txt` files in `./data/vctk` directory. - -# 4. Run the code - -## Configuration - -`config.py` is the most important file. Here, you can find all the configurations related to experiment setups, -datasets, models, training, testing, etc. Although the config file has been explained thoroughly, we recommend reading -our paper to fully understand each parameter. - -## Training - -* Adjust training hyperparameters in `config.py`. We provide the pretrained predictor in `lightning_logs/predictor` as stated in our paper. The FRN model can be trained entirely from scratch and will work as well. In this case, initiate `PLCModel(..., pred_ckpt_path=None)`. - -* Run `main.py`: - ``` - $ python main.py --mode train - ``` -* Each run will create a version in `./lightning_logs`, where the model checkpoint and hyperparameters are saved. In - case you want to continue training from one of these versions, just set the argument `--version` of the above command - to your desired version number. For example: - ``` - # resume from version 0 - $ python main.py --mode train --version 0 - ``` -* To monitor the training curves as well as inspect model output visualization, run the tensorboard: - ``` - $ tensorboard --logdir=./lightning_logs --bind_all - ``` - ![image.png](https://images.viblo.asia/eb2246f9-2747-43b9-8f78-d6c154144716.png) - -## Evaluation - -In our paper, we evaluated with 2 masking methods: simulation using Markov Chain and employing real traces in PLC -Challenge. - -* Get the blind test set with loss traces: - ``` - $ wget http://plcchallenge2022pub.blob.core.windows.net/plcchallengearchive/blind.tar.gz - $ tar -xvf blind.tar.gz -C test_samples - ``` -* Modify `config.py` to change evaluation setup if necessary. -* Run `main.py` with a version number to be evaluated: - ``` - $ python main.py --mode eval --version 0 - ``` - During the evaluation, several output samples are saved to `CONFIG.LOG.sample_path` for sanity testing. - -## Configure a new dataset - -Our implementation currently works with the VCTK dataset but can be easily extensible to a new one. - -* Firstly, you need to prepare `train.txt` and `test.txt`. See `./data/vctk/train.txt` and `./data/vctk/test.txt` for - example. -* Secondly, add a new dictionary to `CONFIG.DATA.data_dir`: - ``` - { - 'root': 'path/to/data/directory', - 'train': 'path/to/train.txt', - 'test': 'path/to/test.txt' - } - ``` - **Important:** Make sure each line in `train.txt` and `test.txt` joining with `'root'` is a valid path to its - corresponding audio file. - -# 5. Audio generation - -* In order to generate output audios, you need to modify `CONFIG.TEST.in_dir` to your input directory. -* Run `main.py`: - ``` - python main.py --mode test --version 0 - ``` - The generated audios are saved to `CONFIG.TEST.out_dir`. - - ## ONNX inferencing - We provide ONNX inferencing scripts and the best ONNX model (converted from the best checkpoint) - at `lightning_logs/best_model.onnx`. - * Convert a checkpoint to an ONNX model: - ``` - python main.py --mode onnx --version 0 - ``` - The converted ONNX model will be saved to `lightning_logs/version_0/checkpoints`. - * Put test audios in `test_samples` and inference with the converted ONNX model (see `inference_onnx.py` for more - details): - ``` - python inference_onnx.py --onnx_path lightning_logs/version_0/frn.onnx - ``` diff --git a/spaces/ankush37/phishingDetection/README.md b/spaces/ankush37/phishingDetection/README.md deleted file mode 100644 index bd2a46fd01f11853c7cb48482698efff26c7fe7a..0000000000000000000000000000000000000000 --- a/spaces/ankush37/phishingDetection/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: PhishingDetection -emoji: 🐨 -colorFrom: gray -colorTo: red -sdk: gradio -sdk_version: 3.35.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/antonovmaxim/text-generation-webui-space/text-generation-webui-main/modules/llamacpp_model.py b/spaces/antonovmaxim/text-generation-webui-space/text-generation-webui-main/modules/llamacpp_model.py deleted file mode 100644 index d19eea27c19c37a0cbf3e85bdd63358c2bfbf640..0000000000000000000000000000000000000000 --- a/spaces/antonovmaxim/text-generation-webui-space/text-generation-webui-main/modules/llamacpp_model.py +++ /dev/null @@ -1,67 +0,0 @@ -''' -Based on -https://github.com/abetlen/llama-cpp-python - -Documentation: -https://abetlen.github.io/llama-cpp-python/ -''' - -from llama_cpp import Llama, LlamaCache - -from modules import shared -from modules.callbacks import Iteratorize - - -class LlamaCppModel: - def __init__(self): - self.initialized = False - - @classmethod - def from_pretrained(self, path): - result = self() - - params = { - 'model_path': str(path), - 'n_ctx': 2048, - 'seed': 0, - 'n_threads': shared.args.threads or None, - 'n_batch': shared.args.n_batch, - 'use_mmap': not shared.args.no_mmap, - 'use_mlock': shared.args.mlock - } - self.model = Llama(**params) - self.model.set_cache(LlamaCache) - - # This is ugly, but the model and the tokenizer are the same object in this library. - return result, result - - def encode(self, string): - if type(string) is str: - string = string.encode() - return self.model.tokenize(string) - - def generate(self, context="", token_count=20, temperature=1, top_p=1, top_k=50, repetition_penalty=1, callback=None): - if type(context) is str: - context = context.encode() - tokens = self.model.tokenize(context) - - output = b"" - count = 0 - for token in self.model.generate(tokens, top_k=top_k, top_p=top_p, temp=temperature, repeat_penalty=repetition_penalty): - text = self.model.detokenize([token]) - output += text - if callback: - callback(text.decode()) - - count += 1 - if count >= token_count or (token == self.model.token_eos()): - break - - return output.decode() - - def generate_with_streaming(self, **kwargs): - with Iteratorize(self.generate, kwargs, callback=None) as generator: - reply = '' - for token in generator: - reply += token - yield reply diff --git a/spaces/anurag629/botaniscan/Dockerfile b/spaces/anurag629/botaniscan/Dockerfile deleted file mode 100644 index a13ad4654507b9354f109c9ae22d08bbf37979c9..0000000000000000000000000000000000000000 --- a/spaces/anurag629/botaniscan/Dockerfile +++ /dev/null @@ -1,43 +0,0 @@ -# Build stage -FROM python:3.8.0 AS build - -# Install required packages as root -RUN apt-get update && apt-get install -y --no-install-recommends \ - bzip2 \ - g++ \ - git \ - graphviz \ - libgl1-mesa-glx \ - libhdf5-dev \ - openmpi-bin \ - wget \ - python3-tk \ - ffmpeg && \ - rm -rf /var/lib/apt/lists/* - -WORKDIR /code - -COPY ./requirements.txt /code/requirements.txt - -RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt - -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 - -# Minimize image size with sudo command and give permission to user -RUN (apt-get autoremove -y; \ - apt-get autoclean -y; \ - rm -rf /var/lib/apt/lists/*; \ - echo "user ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers; \ - chown -R user:user $HOME; \ - chmod -R 777 $HOME) - -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"] - - diff --git a/spaces/aodianyun/panoptic-segment-anything/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.h b/spaces/aodianyun/panoptic-segment-anything/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.h deleted file mode 100644 index b2b88e8c46f19b6db0933163e57ccdb51180f517..0000000000000000000000000000000000000000 --- a/spaces/aodianyun/panoptic-segment-anything/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.h +++ /dev/null @@ -1,35 +0,0 @@ -/*! -************************************************************************************************** -* Deformable DETR -* Copyright (c) 2020 SenseTime. All Rights Reserved. -* Licensed under the Apache License, Version 2.0 [see LICENSE for details] -************************************************************************************************** -* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0 -************************************************************************************************** -*/ - -#pragma once -#include - -namespace groundingdino { - -at::Tensor -ms_deform_attn_cpu_forward( - const at::Tensor &value, - const at::Tensor &spatial_shapes, - const at::Tensor &level_start_index, - const at::Tensor &sampling_loc, - const at::Tensor &attn_weight, - const int im2col_step); - -std::vector -ms_deform_attn_cpu_backward( - const at::Tensor &value, - const at::Tensor &spatial_shapes, - const at::Tensor &level_start_index, - const at::Tensor &sampling_loc, - const at::Tensor &attn_weight, - const at::Tensor &grad_output, - const int im2col_step); - -} // namespace groundingdino diff --git a/spaces/aodianyun/stable-diffusion-webui/modules/interrogate.py b/spaces/aodianyun/stable-diffusion-webui/modules/interrogate.py deleted file mode 100644 index 236abe516c8783824b6aecaae188a31cfa17f75c..0000000000000000000000000000000000000000 --- a/spaces/aodianyun/stable-diffusion-webui/modules/interrogate.py +++ /dev/null @@ -1,227 +0,0 @@ -import os -import sys -import traceback -from collections import namedtuple -from pathlib import Path -import re - -import torch -import torch.hub - -from torchvision import transforms -from torchvision.transforms.functional import InterpolationMode - -import modules.shared as shared -from modules import devices, paths, shared, lowvram, modelloader, errors - -blip_image_eval_size = 384 -clip_model_name = 'ViT-L/14' - -Category = namedtuple("Category", ["name", "topn", "items"]) - -re_topn = re.compile(r"\.top(\d+)\.") - -def category_types(): - return [f.stem for f in Path(shared.interrogator.content_dir).glob('*.txt')] - - -def download_default_clip_interrogate_categories(content_dir): - print("Downloading CLIP categories...") - - tmpdir = content_dir + "_tmp" - category_types = ["artists", "flavors", "mediums", "movements"] - - try: - os.makedirs(tmpdir) - for category_type in category_types: - torch.hub.download_url_to_file(f"https://raw.githubusercontent.com/pharmapsychotic/clip-interrogator/main/clip_interrogator/data/{category_type}.txt", os.path.join(tmpdir, f"{category_type}.txt")) - os.rename(tmpdir, content_dir) - - except Exception as e: - errors.display(e, "downloading default CLIP interrogate categories") - finally: - if os.path.exists(tmpdir): - os.remove(tmpdir) - - -class InterrogateModels: - blip_model = None - clip_model = None - clip_preprocess = None - dtype = None - running_on_cpu = None - - def __init__(self, content_dir): - self.loaded_categories = None - self.skip_categories = [] - self.content_dir = content_dir - self.running_on_cpu = devices.device_interrogate == torch.device("cpu") - - def categories(self): - if not os.path.exists(self.content_dir): - download_default_clip_interrogate_categories(self.content_dir) - - if self.loaded_categories is not None and self.skip_categories == shared.opts.interrogate_clip_skip_categories: - return self.loaded_categories - - self.loaded_categories = [] - - if os.path.exists(self.content_dir): - self.skip_categories = shared.opts.interrogate_clip_skip_categories - category_types = [] - for filename in Path(self.content_dir).glob('*.txt'): - category_types.append(filename.stem) - if filename.stem in self.skip_categories: - continue - m = re_topn.search(filename.stem) - topn = 1 if m is None else int(m.group(1)) - with open(filename, "r", encoding="utf8") as file: - lines = [x.strip() for x in file.readlines()] - - self.loaded_categories.append(Category(name=filename.stem, topn=topn, items=lines)) - - return self.loaded_categories - - def create_fake_fairscale(self): - class FakeFairscale: - def checkpoint_wrapper(self): - pass - - sys.modules["fairscale.nn.checkpoint.checkpoint_activations"] = FakeFairscale - - def load_blip_model(self): - self.create_fake_fairscale() - import models.blip - - files = modelloader.load_models( - model_path=os.path.join(paths.models_path, "BLIP"), - model_url='https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_caption_capfilt_large.pth', - ext_filter=[".pth"], - download_name='model_base_caption_capfilt_large.pth', - ) - - blip_model = models.blip.blip_decoder(pretrained=files[0], image_size=blip_image_eval_size, vit='base', med_config=os.path.join(paths.paths["BLIP"], "configs", "med_config.json")) - blip_model.eval() - - return blip_model - - def load_clip_model(self): - import clip - - if self.running_on_cpu: - model, preprocess = clip.load(clip_model_name, device="cpu", download_root=shared.cmd_opts.clip_models_path) - else: - model, preprocess = clip.load(clip_model_name, download_root=shared.cmd_opts.clip_models_path) - - model.eval() - model = model.to(devices.device_interrogate) - - return model, preprocess - - def load(self): - if self.blip_model is None: - self.blip_model = self.load_blip_model() - if not shared.cmd_opts.no_half and not self.running_on_cpu: - self.blip_model = self.blip_model.half() - - self.blip_model = self.blip_model.to(devices.device_interrogate) - - if self.clip_model is None: - self.clip_model, self.clip_preprocess = self.load_clip_model() - if not shared.cmd_opts.no_half and not self.running_on_cpu: - self.clip_model = self.clip_model.half() - - self.clip_model = self.clip_model.to(devices.device_interrogate) - - self.dtype = next(self.clip_model.parameters()).dtype - - def send_clip_to_ram(self): - if not shared.opts.interrogate_keep_models_in_memory: - if self.clip_model is not None: - self.clip_model = self.clip_model.to(devices.cpu) - - def send_blip_to_ram(self): - if not shared.opts.interrogate_keep_models_in_memory: - if self.blip_model is not None: - self.blip_model = self.blip_model.to(devices.cpu) - - def unload(self): - self.send_clip_to_ram() - self.send_blip_to_ram() - - devices.torch_gc() - - def rank(self, image_features, text_array, top_count=1): - import clip - - devices.torch_gc() - - if shared.opts.interrogate_clip_dict_limit != 0: - text_array = text_array[0:int(shared.opts.interrogate_clip_dict_limit)] - - top_count = min(top_count, len(text_array)) - text_tokens = clip.tokenize([text for text in text_array], truncate=True).to(devices.device_interrogate) - text_features = self.clip_model.encode_text(text_tokens).type(self.dtype) - text_features /= text_features.norm(dim=-1, keepdim=True) - - similarity = torch.zeros((1, len(text_array))).to(devices.device_interrogate) - for i in range(image_features.shape[0]): - similarity += (100.0 * image_features[i].unsqueeze(0) @ text_features.T).softmax(dim=-1) - similarity /= image_features.shape[0] - - top_probs, top_labels = similarity.cpu().topk(top_count, dim=-1) - return [(text_array[top_labels[0][i].numpy()], (top_probs[0][i].numpy()*100)) for i in range(top_count)] - - def generate_caption(self, pil_image): - gpu_image = transforms.Compose([ - transforms.Resize((blip_image_eval_size, blip_image_eval_size), interpolation=InterpolationMode.BICUBIC), - transforms.ToTensor(), - transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)) - ])(pil_image).unsqueeze(0).type(self.dtype).to(devices.device_interrogate) - - with torch.no_grad(): - caption = self.blip_model.generate(gpu_image, sample=False, num_beams=shared.opts.interrogate_clip_num_beams, min_length=shared.opts.interrogate_clip_min_length, max_length=shared.opts.interrogate_clip_max_length) - - return caption[0] - - def interrogate(self, pil_image): - res = "" - shared.state.begin() - shared.state.job = 'interrogate' - try: - if shared.cmd_opts.lowvram or shared.cmd_opts.medvram: - lowvram.send_everything_to_cpu() - devices.torch_gc() - - self.load() - - caption = self.generate_caption(pil_image) - self.send_blip_to_ram() - devices.torch_gc() - - res = caption - - clip_image = self.clip_preprocess(pil_image).unsqueeze(0).type(self.dtype).to(devices.device_interrogate) - - with torch.no_grad(), devices.autocast(): - image_features = self.clip_model.encode_image(clip_image).type(self.dtype) - - image_features /= image_features.norm(dim=-1, keepdim=True) - - for name, topn, items in self.categories(): - matches = self.rank(image_features, items, top_count=topn) - for match, score in matches: - if shared.opts.interrogate_return_ranks: - res += f", ({match}:{score/100:.3f})" - else: - res += ", " + match - - except Exception: - print("Error interrogating", file=sys.stderr) - print(traceback.format_exc(), file=sys.stderr) - res += "" - - self.unload() - shared.state.end() - - return res diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/fairseq/examples/MMPT/mmpt/utils/__init__.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/fairseq/examples/MMPT/mmpt/utils/__init__.py deleted file mode 100644 index 2429ee3757353e768f71b27d129eb3ca3bcbec73..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/fairseq/examples/MMPT/mmpt/utils/__init__.py +++ /dev/null @@ -1,68 +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 random -import numpy as np -import torch - -from .shardedtensor import * -from .load_config import * - - -def set_seed(seed=43211): - random.seed(seed) - np.random.seed(seed) - torch.manual_seed(seed) - torch.cuda.manual_seed_all(seed) - if torch.backends.cudnn.enabled: - torch.backends.cudnn.benchmark = False - torch.backends.cudnn.deterministic = True - - -def get_world_size(): - if torch.distributed.is_initialized(): - world_size = torch.distributed.get_world_size() - else: - world_size = 1 - return world_size - - -def get_local_rank(): - return torch.distributed.get_rank() \ - if torch.distributed.is_initialized() else 0 - - -def print_on_rank0(func): - local_rank = get_local_rank() - if local_rank == 0: - print("[INFO]", func) - - -class RetriMeter(object): - """ - Statistics on whether retrieval yields a better pair. - """ - def __init__(self, freq=1024): - self.freq = freq - self.total = 0 - self.replace = 0 - self.updates = 0 - - def __call__(self, data): - if isinstance(data, np.ndarray): - self.replace += data.shape[0] - int((data[:, 0] == -1).sum()) - self.total += data.shape[0] - elif torch.is_tensor(data): - self.replace += int(data.sum()) - self.total += data.size(0) - else: - raise ValueError("unsupported RetriMeter data type.", type(data)) - - self.updates += 1 - if get_local_rank() == 0 and self.updates % self.freq == 0: - print("[INFO]", self) - - def __repr__(self): - return "RetriMeter (" + str(self.replace / self.total) \ - + "/" + str(self.replace) + "/" + str(self.total) + ")" diff --git a/spaces/aswinkvj/image_captioning/vit_gpt2/configuration_vit_gpt2.py b/spaces/aswinkvj/image_captioning/vit_gpt2/configuration_vit_gpt2.py deleted file mode 100644 index e78c09e2af38130aaff70dde1817c957749283d2..0000000000000000000000000000000000000000 --- a/spaces/aswinkvj/image_captioning/vit_gpt2/configuration_vit_gpt2.py +++ /dev/null @@ -1,45 +0,0 @@ -import copy - -from transformers import GPT2Config, ViTConfig -from transformers.configuration_utils import PretrainedConfig -from transformers.utils import logging - -logger = logging.get_logger(__name__) - - -class ViTGPT2Config(PretrainedConfig): - - model_type = "vit-gpt2" - is_composition = True - - def __init__(self, **kwargs): - super().__init__(**kwargs) - - if "vit_config" not in kwargs: - raise ValueError("`vit_config` can not be `None`.") - - if "gpt2_config" not in kwargs: - raise ValueError("`gpt2_config` can not be `None`.") - - vit_config = kwargs.pop("vit_config") - gpt2_config = kwargs.pop("gpt2_config") - - self.vit_config = ViTConfig(**vit_config) - self.gpt2_config = GPT2Config(**gpt2_config) - - @classmethod - def from_vit_gpt2_configs( - cls, vit_config: PretrainedConfig, gpt2_config: PretrainedConfig, **kwargs - ): - return cls( - vit_config=vit_config.to_dict(), - gpt2_config=gpt2_config.to_dict(), - **kwargs - ) - - def to_dict(self): - output = copy.deepcopy(self.__dict__) - output["vit_config"] = self.vit_config.to_dict() - output["gpt2_config"] = self.gpt2_config.to_dict() - output["model_type"] = self.__class__.model_type - return output \ No newline at end of file diff --git a/spaces/atimughal662/InfoFusion/gen.py b/spaces/atimughal662/InfoFusion/gen.py deleted file mode 100644 index 5919c5cbf8dbec02e05487b003c736398367aad6..0000000000000000000000000000000000000000 --- a/spaces/atimughal662/InfoFusion/gen.py +++ /dev/null @@ -1,4307 +0,0 @@ -import ast -import copy -import functools -import inspect -import queue -import sys -import os -import time -import traceback -import typing -import warnings -from datetime import datetime -import requests -from requests import ConnectTimeout, JSONDecodeError -from urllib3.exceptions import ConnectTimeoutError, MaxRetryError, ConnectionError -from requests.exceptions import ConnectionError as ConnectionError2 -from requests.exceptions import ReadTimeout as ReadTimeout2 - -if os.path.dirname(os.path.abspath(__file__)) not in sys.path: - sys.path.append(os.path.dirname(os.path.abspath(__file__))) - -os.environ['HF_HUB_DISABLE_TELEMETRY'] = '1' -os.environ['BITSANDBYTES_NOWELCOME'] = '1' -warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated') - -# more is not useful typically, don't let these go beyond limits and eat up resources -max_cores = max(1, os.cpu_count() // 2) -if os.getenv('NUMEXPR_MAX_THREADS') is None: - os.environ['NUMEXPR_MAX_THREADS'] = str(min(8, max_cores)) -if os.getenv('NUMEXPR_NUM_THREADS') is None: - os.environ['NUMEXPR_NUM_THREADS'] = str(min(8, max_cores)) -if os.getenv('OMP_NUM_THREADS') is None: - os.environ['OMP_NUM_THREADS'] = str(min(8, max_cores)) -if os.getenv('OPENBLAS_NUM_THREADS') is None: - os.environ['OPENBLAS_NUM_THREADS'] = str(min(8, max_cores)) -if os.getenv('DUCKDB_NUM_THREADS') is None: - os.environ['DUCKDB_NUM_THREADS'] = str(min(4, max_cores)) -if os.getenv('RAYON_RS_NUM_CPUS') is None: - os.environ['RAYON_RS_NUM_CPUS'] = str(min(8, max_cores)) -if os.getenv('RAYON_NUM_THREADS') is None: - os.environ['RAYON_NUM_THREADS'] = str(min(8, max_cores)) - -import numpy as np -from evaluate_params import eval_func_param_names, no_default_param_names, input_args_list -from enums import DocumentSubset, LangChainMode, no_lora_str, model_token_mapping, no_model_str, \ - LangChainAction, LangChainAgent, DocumentChoice, LangChainTypes, super_source_prefix, \ - super_source_postfix, t5_type, get_langchain_prompts, gr_to_lg, invalid_key_msg, docs_joiner_default, \ - docs_ordering_types_default, docs_token_handling_default -from loaders import get_loaders -# import utils import . -from utzils import set_seed, clear_torch_cache, NullContext, wrapped_partial, EThread, get_githash, \ - import_matplotlib, get_device, makedirs, get_kwargs, start_faulthandler, get_hf_server, FakeTokenizer, \ - have_langchain, set_openai, cuda_vis_check, H2O_Fire, lg_to_gr, str_to_list, str_to_dict, get_token_count - -start_faulthandler() -import_matplotlib() - -SEED = 1236 -set_seed(SEED) - -from typing import Union - -import torch -from transformers import GenerationConfig, AutoModel, TextIteratorStreamer - -from prompter import Prompter, inv_prompt_type_to_model_lower, non_hf_types, PromptType, get_prompt, generate_prompt -from stopping import get_stopping - -langchain_actions = [x.value for x in list(LangChainAction)] - -langchain_agents_list = [x.value for x in list(LangChainAgent)] - - -def main( - load_8bit: bool = False, - load_4bit: bool = False, - low_bit_mode: int = 1, - load_half: bool = None, - load_gptq: str = '', - load_awq: str = '', - load_exllama: bool = False, - use_safetensors: bool = False, - revision: str = None, - use_gpu_id: bool = True, - base_model: str = '', - tokenizer_base_model: str = '', - lora_weights: str = "", - gpu_id: int = 0, - compile_model: bool = None, - use_cache: bool = None, - inference_server: str = "", - prompt_type: Union[int, str] = None, - prompt_dict: typing.Dict = None, - system_prompt: str = '', - - # llama and gpt4all settings - llamacpp_dict: typing.Dict = dict(n_gpu_layers=100, use_mlock=True, n_batch=1024, n_gqa=0), - model_path_llama: str = 'https://huggingface.co/TheBloke/Llama-2-7b-Chat-GGUF/resolve/main/llama-2-7b-chat.Q6_K.gguf', - model_name_gptj: str = 'ggml-gpt4all-j-v1.3-groovy.bin', - model_name_gpt4all_llama: str = 'ggml-wizardLM-7B.q4_2.bin', - model_name_exllama_if_no_config: str = 'TheBloke/Nous-Hermes-Llama2-GPTQ', - exllama_dict: typing.Dict = dict(), - gptq_dict: typing.Dict = dict(), - attention_sinks: bool = False, - sink_dict: typing.Dict = dict(), - truncation_generation: bool = False, - hf_model_dict: typing.Dict = dict(), - - model_lock: typing.List[typing.Dict[str, str]] = None, - model_lock_columns: int = None, - fail_if_cannot_connect: bool = False, - - # input to generation - temperature: float = None, - top_p: float = None, - top_k: int = None, - penalty_alpha: float = None, - num_beams: int = None, - repetition_penalty: float = None, - num_return_sequences: int = None, - do_sample: bool = None, - max_new_tokens: int = None, - min_new_tokens: int = None, - early_stopping: Union[bool, str] = None, - max_time: float = None, - - memory_restriction_level: int = None, - debug: bool = False, - save_dir: str = None, - local_files_only: bool = False, - resume_download: bool = True, - use_auth_token: Union[str, bool] = False, - trust_remote_code: Union[str, bool] = True, - rope_scaling: dict = None, - max_seq_len: int = None, - offload_folder: str = "offline_folder", - - src_lang: str = "English", - tgt_lang: str = "Russian", - - prepare_offline_level: int = 0, - cli: bool = False, - cli_loop: bool = True, - gradio: bool = True, - gradio_offline_level: int = 0, - server_name: str = "0.0.0.0", - share: bool = False, - open_browser: bool = False, - root_path: str = "", - ssl_verify: bool = True, - ssl_keyfile: str | None = None, - ssl_certfile: str | None = None, - ssl_keyfile_password: str | None = None, - - chat: bool = True, - chat_conversation: typing.List[typing.Tuple[str, str]] = None, - text_context_list: typing.List[str] = None, - stream_output: bool = True, - async_output: bool = True, - num_async: int = 3, - show_examples: bool = None, - verbose: bool = False, - h2ocolors: bool = True, - dark: bool = False, # light tends to be best - height: int = 600, - render_markdown: bool = True, - show_lora: bool = True, - show_llama: bool = True, - show_gpt4all: bool = False, - login_mode_if_model0: bool = False, - block_gradio_exit: bool = True, - concurrency_count: int = 1, - api_open: bool = False, - allow_api: bool = True, - input_lines: int = 1, - gradio_size: str = None, - show_copy_button: bool = True, - large_file_count_mode: bool = False, - pre_load_embedding_model: bool = True, - - auth: Union[typing.List[typing.Tuple[str, str]], str] = None, - auth_filename: str = None, - auth_access: str = 'open', - auth_freeze: bool = False, - auth_message: str = None, - guest_name: str = "guest", - enforce_h2ogpt_api_key: bool = None, - enforce_h2ogpt_ui_key: bool = None, - h2ogpt_api_keys: Union[list, str] = [], - h2ogpt_key: str = None, - - max_max_time=None, - max_max_new_tokens=None, - - visible_models: list = None, - visible_visible_models: bool = True, - visible_submit_buttons: bool = True, - visible_side_bar: bool = True, - visible_doc_track: bool = True, - visible_chat_tab: bool = True, - visible_doc_selection_tab: bool = True, - visible_doc_view_tab: bool = True, - visible_chat_history_tab: bool = True, - visible_expert_tab: bool = True, - visible_models_tab: bool = True, - visible_system_tab: bool = True, - visible_tos_tab: bool = False, - visible_login_tab: bool = True, - visible_hosts_tab: bool = False, - chat_tables: bool = False, - visible_h2ogpt_header: bool = True, - max_raw_chunks: int = None, - - sanitize_user_prompt: bool = False, - sanitize_bot_response: bool = False, - - extra_model_options: typing.List[str] = [], - extra_lora_options: typing.List[str] = [], - extra_server_options: typing.List[str] = [], - - score_model: str = 'auto', - - eval_filename: str = None, - eval_prompts_only_num: int = 0, - eval_prompts_only_seed: int = 1234, - eval_as_output: bool = False, - - langchain_mode: str = None, - user_path: str = None, - langchain_modes: list = [LangChainMode.USER_DATA.value, LangChainMode.MY_DATA.value, LangChainMode.LLM.value, - LangChainMode.DISABLED.value], - langchain_mode_paths: dict = {LangChainMode.USER_DATA.value: None}, - langchain_mode_types: dict = {LangChainMode.USER_DATA.value: LangChainTypes.SHARED.value}, - detect_user_path_changes_every_query: bool = False, - - langchain_action: str = LangChainAction.QUERY.value, - langchain_agents: list = [], - force_langchain_evaluate: bool = False, - - visible_langchain_actions: list = [LangChainAction.QUERY.value, LangChainAction.SUMMARIZE_MAP.value, - LangChainAction.EXTRACT.value], - visible_langchain_agents: list = langchain_agents_list.copy(), - - document_subset: str = DocumentSubset.Relevant.name, - document_choice: list = [DocumentChoice.ALL.value], - - use_llm_if_no_docs: bool = True, - load_db_if_exists: bool = True, - keep_sources_in_context: bool = False, - db_type: str = 'chroma', - use_openai_embedding: bool = False, - use_openai_model: bool = False, - hf_embedding_model: str = None, - migrate_embedding_model: str = False, - auto_migrate_db: bool = False, - cut_distance: float = 1.64, - answer_with_sources: bool = True, - append_sources_to_answer: bool = True, - show_accordions: bool = True, - top_k_docs_max_show: int = 10, - show_link_in_sources: bool = True, - pre_prompt_query: str = None, - prompt_query: str = None, - pre_prompt_summary: str = None, - prompt_summary: str = None, - add_chat_history_to_context: bool = True, - add_search_to_context: bool = False, - context: str = '', - iinput: str = '', - allow_upload_to_user_data: bool = True, - reload_langchain_state: bool = True, - allow_upload_to_my_data: bool = True, - enable_url_upload: bool = True, - enable_text_upload: bool = True, - enable_sources_list: bool = True, - chunk: bool = True, - chunk_size: int = 512, - top_k_docs: int = None, - docs_ordering_type: str = docs_ordering_types_default, - min_max_new_tokens=256, - max_input_tokens=-1, - docs_token_handling: str = docs_token_handling_default, - docs_joiner: str = docs_joiner_default, - hyde_level: int = 0, - hyde_template: str = None, - - auto_reduce_chunks: bool = True, - max_chunks: int = 100, - headsize: int = 50, - n_jobs: int = -1, - - # urls - use_unstructured=True, - use_playwright=False, - use_selenium=False, - - # pdfs - use_pymupdf='auto', - use_unstructured_pdf='auto', - use_pypdf='auto', - enable_pdf_ocr='auto', - enable_pdf_doctr='auto', - try_pdf_as_html='auto', - - # images - enable_ocr=False, - enable_doctr=True, - enable_pix2struct=False, - enable_captions=True, - - pre_load_caption_model: bool = False, - caption_gpu: bool = True, - caption_gpu_id: Union[int, str] = 'auto', - captions_model: str = "Salesforce/blip-image-captioning-base", - doctr_gpu: bool = True, - doctr_gpu_id: Union[int, str] = 'auto', - - # json - jq_schema='.[]', - - max_quality: bool = False, - - enable_heap_analytics: bool = True, - heap_app_id: str = "1680123994", -): - """ - - :param load_8bit: load model in 8-bit using bitsandbytes - :param load_4bit: load model in 4-bit using bitsandbytes - :param low_bit_mode: 0: no quantization config 1: change compute 2: nf4 3: double quant 4: 2 and 3 - See: https://huggingface.co/docs/transformers/main_classes/quantization - If using older bitsandbytes or transformers, 0 is required - :param load_half: load model in float16 (None means auto, which means True unless t5 based model) - otherwise specify bool - :param load_gptq: to load model with GPTQ, put model_basename here, e.g. gptq_model-4bit--1g - :param load_awq: load model with AWQ, often 'model' for TheBloke models - :param load_exllama: whether to use exllama (only applicable to LLaMa1/2 models with 16-bit or GPTQ - :param use_safetensors: to use safetensors version (assumes file/HF points to safe tensors version) - :param revision: Which HF revision to use - :param use_gpu_id: whether to control devices with gpu_id. If False, then spread across GPUs - :param base_model: model HF-type name. If use --base_model to preload model, cannot unload in gradio in models tab - :param tokenizer_base_model: tokenizer HF-type name. Usually not required, inferred from base_model. - :param lora_weights: LORA weights path/HF link - :param gpu_id: if use_gpu_id, then use gpu_id for cuda device ID, or auto mode if gpu_id != -1 - :param compile_model Whether to compile the model - :param use_cache: Whether to use caching in model (some models fail when multiple threads use) - :param inference_server: Consume base_model as type of model at this address - Address can be text-generation-server hosting that base_model - e.g. python generate.py --inference_server="http://192.168.1.46:6112" --base_model=h2oai/h2ogpt-oasst1-512-12b - - Or Address can be "openai_chat" or "openai" for OpenAI API - Or Address can be "openai_azure_chat" or "openai_azure" for Azure OpenAI API - e.g. python generate.py --inference_server="openai_chat" --base_model=gpt-3.5-turbo - e.g. python generate.py --inference_server="openai" --base_model=text-davinci-003 - e.g. python generate.py --inference_server="openai_azure_chat::::" --base_model=gpt-3.5-turbo - e.g. python generate.py --inference_server="openai_azure::::" --base_model=text-davinci-003 - Optionals (Replace with None or just leave empty but keep :) - of some deployment name - : e.g. ".openai.azure.com" for some without https:// - of some api, e.g. 2023-05-15 - e.g. 0613 - - Or Address can be for vLLM: - Use: "vllm:IP:port" for OpenAI-compliant vLLM endpoint - Use: "vllm_chat:IP:port" for OpenAI-Chat-compliant vLLM endpoint - - Use: "vllm:http://IP:port/v1" for OpenAI-compliant vLLM endpoint - Use: "vllm_chat:http://IP:port/v1" for OpenAI-Chat-compliant vLLM endpoint - - Use: "vllm:https://IP/v1" for OpenAI-compliant vLLM endpoint - Use: "vllm_chat:https://IP/v1" for OpenAI-Chat-compliant vLLM endpoint - - Or Address can be replicate: - Use: - --inference_server=replicate: will use a Replicate server, requiring a Replicate key. - e.g. looks like "a16z-infra/llama13b-v2-chat:df7690f1994d94e96ad9d568eac121aecf50684a0b0963b25a41cc40061269e5" - - Or Address can be for AWS SageMaker: - Use: "sagemaker_chat:" for chat models that AWS sets up as dialog - Use: "sagemaker:" for foundation models that AWS only text as inputs - - :param prompt_type: type of prompt, usually matched to fine-tuned model or plain for foundational model - :param prompt_dict: If prompt_type=custom, then expects (some) items returned by get_prompt(..., return_dict=True) - :param system_prompt: Universal system prompt to use if model supports, like LLaMa2, regardless of prompt_type definition. - Useful for langchain case to control behavior, or OpenAI and Replicate. - If None, 'None', or 'auto', then for LLaMa or other models that internally have system_prompt, will use default for each model - If '', then no system prompt (no empty template given to model either, just no system part added at all) - If some string not in ['None', 'auto'], then use that as system prompt - Default is '', no system_prompt, because often it hurts performance/accuracy - - :param llamacpp_dict: - n_gpu_layers: for llama.cpp based models, number of GPU layers to offload (default is all by using large value) - use_mlock: when using `llama.cpp` based CPU models, for computers with low system RAM or slow CPUs, recommended False - n_batch: Can make smaller to 128 for slower low-memory CPU systems - n_gqa: Required to be 8 for LLaMa 70B - ... etc. anything that could be passed to llama.cpp or GPT4All models - e.g. python generate.py --base_model='llama' --prompt_type=llama2 --score_model=None --langchain_mode='UserData' --user_path=user_path --llamacpp_dict="{'n_gpu_layers':25,'n_batch':128}" - :param model_path_llama: model path or URL (for auto-download) - :param model_name_gptj: model path or URL (for auto-download) - :param model_name_gpt4all_llama: model path or URL (for auto-download) - :param model_name_exllama_if_no_config: exllama model's full path for model, tokenizer, generator for use when no HuggingFace config - :param exllama_dict for setting various things for Exllama class - E.g. compress_pos_emb, - set_auto_map, - gpu_peer_fix, - alpha_value, - matmul_recons_thd, - fused_mlp_thd - sdp_thd - fused_attn - matmul_fused_remap - rmsnorm_no_half2 - rope_no_half2 - matmul_no_half2 - silu_no_half2 - concurrent_streams - E.g. to set memory to be split across 2 GPUs, use --exllama_dict="{'set_auto_map':20,20}" - :param gptq_dict: Choices for AutoGPTQ, e.g. one can change defaults to these non-defaults: - inject_fused_attention=False - disable_exllama=True - use_triton=True - :param attention_sinks: Whether to enable attention sinks. Requires in local repo: - git clone https://github.com/tomaarsen/attention_sinks.git - :param sink_dict: dict of options for attention sinks - :param hf_model_dict: dict of options for HF models using transformers - - :param truncation_generation: Whether (for torch) to terminate generation once reach context length of model. - For some models, perplexity becomes critically large beyond context - For other models like Mistral, one can generate beyond max_seq_len set to 4096 or 8192 without issue, since based upon 32k embeddings - codellama can also generate beyond its 16k context length - So default is off, but for simpler/older models True may be wise to avoid bad generations - - :param model_lock: Lock models to specific combinations, for ease of use and extending to many models - Only used if gradio = True - List of dicts, each dict has base_model, tokenizer_base_model, lora_weights, inference_server, prompt_type, and prompt_dict - If all models have same prompt_type, and prompt_dict, can still specify that once in CLI outside model_lock as default for dict - Can specify model_lock instead of those items on CLI - As with CLI itself, base_model can infer prompt_type and prompt_dict if in prompter.py. - Also, tokenizer_base_model and lora_weights are optional. - Also, inference_server is optional if loading model from local system. - All models provided will automatically appear in compare model mode - Model loading-unloading and related choices will be disabled. Model/lora/server adding will be disabled - :param model_lock_columns: How many columns to show if locking models (and so showing all at once) - If None, then defaults to up to 3 - if -1, then all goes into 1 row - Maximum value is 4 due to non-dynamic gradio rendering elements - :param fail_if_cannot_connect: if doing model locking (e.g. with many models), fail if True. Otherwise ignore. - Useful when many endpoints and want to just see what works, but still have to wait for timeout. - - :param temperature: generation temperature - :param top_p: generation top_p - :param top_k: generation top_k - :param penalty_alpha: penalty_alpha>0 and top_k>1 enables contrastive search (not all models support) - :param num_beams: generation number of beams - :param repetition_penalty: generation repetition penalty - :param num_return_sequences: generation number of sequences (1 forced for chat) - :param do_sample: generation sample - :param max_new_tokens: generation max new tokens - :param min_new_tokens: generation min tokens - :param early_stopping: generation early stopping - :param max_time: maximum time to allow for generation - :param memory_restriction_level: 0 = no restriction to tokens or model, 1 = some restrictions on token 2 = HF like restriction 3 = very low memory case - :param debug: enable debug mode - :param save_dir: directory chat data is saved to - :param local_files_only: whether to only use local files instead of doing to HF for models - :param resume_download: whether to resume downloads from HF for models - :param use_auth_token: whether to use HF auth token (requires CLI did huggingface-cli login before) - :param trust_remote_code: whether to use trust any code needed for HF model - :param rope_scaling: - For HF transformers model: scaling for rope-based models. - For long context models that have been tuned for a specific size, you have to only use that specific size by setting the `--rope_scaling` exactly correctly - e.g. --rope_scaling="{'type':'dynamic', 'factor':4}" - e.g. --rope_scaling="{'type':'linear', 'factor':4}" - e.g. python generate.py --rope_scaling="{'type':'linear','factor':4}" --base_model=lmsys/vicuna-13b-v1.5-16k --hf_embedding_model=sentence-transformers/all-MiniLM-L6-v2 --load_8bit=True --langchain_mode=UserData --user_path=user_path --prompt_type=vicuna11 --h2ocolors=False - For exllama model: --rope_scaling="{'alpha_value':4}" . This automatically scales max_seq_len for exllama - :param max_seq_len: Manually set maximum sequence length for the LLM - :param offload_folder: path for spilling model onto disk - :param src_lang: source languages to include if doing translation (None = all) - :param tgt_lang: target languages to include if doing translation (None = all) - - :param prepare_offline_level: - Whether to just prepare for offline use, do not go into cli, eval, or gradio run modes - 0 : no prep - 1: prepare just h2oGPT with exact same setup as passed to CLI and ensure all artifacts for h2oGPT alone added to ~/.cache/ - 2: prepare h2oGPT + all inference servers so h2oGPT+inference servers can use the ~/.cache/ - :param cli: whether to use CLI (non-gradio) interface. - :param cli_loop: whether to loop for CLI (False usually only for testing) - :param gradio: whether to enable gradio, or to enable benchmark mode - :param gradio_offline_level: > 0, then change fonts so full offline - == 1 means backend won't need internet for fonts, but front-end UI might if font not cached - == 2 means backend and frontend don't need internet to download any fonts. - Note: Some things always disabled include HF telemetry, gradio telemetry, chromadb posthog that involve uploading. - This option further disables google fonts for downloading, which is less intrusive than uploading, - but still required in air-gapped case. The fonts don't look as nice as google fonts, but ensure full offline behavior. - Also set --share=False to avoid sharing a gradio live link. - :param server_name: IP to use. In linux 0.0.0.0 is good choice so exposed to outside host, else for only local use 127.0.0.1. - For windows/MAC 0.0.0.0 or 127.0.0.1 will work, but may need to specify actual LAN IP address for other LAN clients to see. - :param share: whether to share the gradio app with sharable URL - :param open_browser: whether to automatically open browser tab with gradio UI - :param root_path: The root path (or "mount point") of the application, - if it's not served from the root ("/") of the domain. Often used when the application is behind a reverse proxy - that forwards requests to the application. For example, if the application is served at "https://example.com/myapp", - the `root_path` should be set to "/myapp". - :param ssl_verify: passed go gradio launch - :param ssl_keyfile: passed go gradio launch - :param ssl_certfile: passed go gradio launch - :param ssl_keyfile_password: passed go gradio launch - - :param chat: whether to enable chat mode with chat history - :param chat_conversation: list of tuples of (human, bot) conversation pre-appended to existing chat when using instruct/chat models - Requires also add_chat_history_to_context = True - It does *not* require chat=True, so works with nochat_api etc. - :param text_context_list: List of strings to add to context for non-database version of document Q/A for faster handling via API etc. - Forces LangChain code path and uses as many entries in list as possible given max_seq_len, with first assumed to be most relevant and to go near prompt. - :param stream_output: whether to stream output - :param async_output: Whether to do asyncio handling - For summarization - Applicable to HF TGI server - Only if stream_output=False in CLI, UI, or API - :param num_async: Number of simultaneously allowed asyncio calls to make for async_output - Too many will overload inference server, too few will be too slow - :param show_examples: whether to show clickable examples in gradio - :param verbose: whether to show verbose prints - :param h2ocolors: whether to use H2O.ai theme - :param dark: whether to use dark mode for UI by default (still controlled in UI) - :param height: height of chat window - :param render_markdown: Whether to render markdown in chatbot UI. In some cases this distorts the rendering. - https://github.com/gradio-app/gradio/issues/4344#issuecomment-1771963021 - :param show_lora: whether to show LORA options in UI (expert so can be hard to understand) - :param show_llama: whether to show LLaMa.cpp/GPT4All options in UI (only likely useful if have weak GPUs) - :param show_gpt4all: whether to show GPT4All models in UI (not often useful, llama.cpp models best) - :param login_mode_if_model0: set to True to load --base_model after client logs in, to be able to free GPU memory when model is swapped - :param block_gradio_exit: whether to block gradio exit (used for testing) - :param concurrency_count: gradio concurrency count (1 is optimal for LLMs) - :param api_open: If False, don't let API calls skip gradio queue - :param allow_api: whether to allow API calls at all to gradio server - :param input_lines: how many input lines to show for chat box (>1 forces shift-enter for submit, else enter is submit) - :param gradio_size: Overall size of text and spaces: "xsmall", "small", "medium", "large". - Small useful for many chatbots in model_lock mode - :param show_copy_button: Whether to show copy button for chatbots - :param large_file_count_mode: Whether to force manual update to UI of drop-downs, good idea if millions of chunks or documents - :param pre_load_embedding_model: Whether to preload embedding model for shared use across DBs and users (multi-thread safe only) - - :param auth: gradio auth for launcher in form [(user1, pass1), (user2, pass2), ...] - e.g. --auth=[('jon','password')] with no spaces - e.g. --auth="[('jon', 'password)())(')]" so any special characters can be used - e.g. --auth=auth.json to specify persisted state file with name auth.json (auth_filename then not required) - e.g. --auth='' will use default auth.json as file name for persisted state file (auth_filename then not required) - e.g. --auth=None will use no auth, but still keep track of auth state, just not from logins - :param auth_filename: - Set auth filename, used only if --auth= was passed list of user/passwords - :param auth_access: - 'open': Allow new users to be added - 'closed': Stick to existing users - :param auth_freeze: whether freeze authentication based upon current file, no longer update file - :param auth_message: Message to show if having users login, fixed if passed, else dynamic internally - :param guest_name: guess name if using auth and have open access. - If '', then no guest allowed even if open access, then all databases for each user always persisted - :param enforce_h2ogpt_api_key: Whether to enforce h2oGPT token usage for API - :param enforce_h2ogpt_ui_key: Whether to enforce h2oGPT token usage for UI (same keys as API assumed) - :param h2ogpt_api_keys: list of tokens allowed for API access or file accessed on demand for json of list of keys - :param h2ogpt_key: E.g. can be set when accessing gradio h2oGPT server from local gradio h2oGPT server that acts as client to that inference server - - :param max_max_time: Maximum max_time for gradio slider - :param max_max_new_tokens: Maximum max_new_tokens for gradio slider - :param min_max_new_tokens: Minimum of max_new_tokens, when auto-scaling down to handle more docs/prompt, but still let generation have some tokens - :param max_input_tokens: Max input tokens to place into model context for each LLM call - -1 means auto, fully fill context for query, and fill by original document chunk for summarization - >=0 means use that to limit context filling to that many tokens - :param docs_token_handling: 'chunk' means fill context with top_k_docs (limited by max_input_tokens or model_max_len) chunks for query - or top_k_docs original document chunks summarization - None or 'split_or_merge' means same as 'chunk' for query, while for summarization merges documents to fill up to max_input_tokens or model_max_len tokens - - :param docs_joiner: string to join lists of text when doing split_or_merge. None means '\n\n' - :param hyde_level: HYDE level for HYDE approach (https://arxiv.org/abs/2212.10496) - 0: No HYDE - 1: Use non-document-based LLM response and original query for embedding query - 2: Use document-based LLM response and original query for embedding query - 3+: Continue iterations of embedding prior answer and getting new response - :param hyde_template: - None, 'None', 'auto' uses internal value and enable - '{query}' is minimal template one can pass - :param visible_models: Which models in model_lock list to show by default - Takes integers of position in model_lock (model_states) list or strings of base_model names - Ignored if model_lock not used - For nochat API, this is single item within a list for model by name or by index in model_lock - If None, then just use first model in model_lock list - If model_lock not set, use model selected by CLI --base_model etc. - Note that unlike h2ogpt_key, this visible_models only applies to this running h2oGPT server, - and the value is not used to access the inference server. - If need a visible_models for an inference server, then use --model_lock and group together. - - :param visible_visible_models: Whether visible models drop-down is visible in UI - :param visible_submit_buttons: whether submit buttons are visible when UI first comes up - :param visible_side_bar: whether left side bar is visible when UI first comes up - :param visible_doc_track: whether left side bar's document tracking is visible when UI first comes up - :param visible_chat_tab: "" for chat tab - :param visible_doc_selection_tab: "" for doc selection tab - :param visible_doc_view_tab: "" for doc view tab - :param visible_chat_history_tab: "" for chat history tab - :param visible_expert_tab: "" for expert tab - :param visible_models_tab: "" for models tab - :param visible_system_tab: "" for system tab - :param visible_tos_tab: "" for ToS tab - :param visible_login_tab: "" for Login tab (needed for persistence or to enter key for UI access to models and ingestion) - :param visible_hosts_tab: "" for hosts tab - :param chat_tables: Just show Chat as block without tab (useful if want only chat view) - :param visible_h2ogpt_header: Whether github stars, URL, logo, and QR code are visible - :param max_raw_chunks: Maximum number of chunks to show in UI when asking for raw DB text from documents/collection - - :param sanitize_user_prompt: whether to remove profanity from user input (slows down input processing) - Requires optional packages: - pip install alt-profanity-check==1.2.2 better-profanity==0.7.0 - :param sanitize_bot_response: whether to remove profanity and repeat lines from bot output (about 2x slower generation for long streaming cases due to better_profanity being slow) - :param extra_model_options: extra models to show in list in gradio - :param extra_lora_options: extra LORA to show in list in gradio - :param extra_server_options: extra servers to show in list in gradio - :param score_model: which model to score responses - None: no response scoring - 'auto': auto mode, '' (no model) for CPU or 1 GPU, 'OpenAssistant/reward-model-deberta-v3-large-v2' for >=2 GPUs, - because on CPU takes too much compute just for scoring response - :param eval_filename: json file to use for evaluation, if None is sharegpt - :param eval_prompts_only_num: for no gradio benchmark, if using eval_filename prompts for eval instead of examples - :param eval_prompts_only_seed: for no gradio benchmark, seed for eval_filename sampling - :param eval_as_output: for no gradio benchmark, whether to test eval_filename output itself - - :param langchain_mode: Data source to include. Choose "UserData" to only consume files from make_db.py. - None: auto mode, check if langchain package exists, at least do LLM if so, else Disabled - If not passed, then chosen to be first langchain_modes, else langchain_mode->Disabled is set if no langchain_modes either - WARNING: wiki_full requires extra data processing via read_wiki_full.py and requires really good workstation to generate db, unless already present. - :param user_path: user path to glob from to generate db for vector search, for 'UserData' langchain mode. - If already have db, any new/changed files are added automatically if path set, does not have to be same path used for prior db sources - :param langchain_modes: dbs to generate at launch to be ready for LLM - Apart from additional user-defined collections, can include ['wiki', 'wiki_full', 'UserData', 'MyData', 'github h2oGPT', 'DriverlessAI docs'] - But wiki_full is expensive and requires preparation - To allow personal space only live in session, add 'MyData' to list - Default: If only want to consume local files, e.g. prepared by make_db.py, only include ['UserData'] - If have own user modes, need to add these here or add in UI. - :param langchain_mode_paths: dict of langchain_mode keys and disk path values to use for source of documents - E.g. "{'UserData2': 'userpath2'}" - A disk path be None, e.g. --langchain_mode_paths="{'UserData2': None}" even if existing DB, to avoid new documents being added from that path, source links that are on disk still work. - If `--user_path` was passed, that path is used for 'UserData' instead of the value in this dict - :param langchain_mode_types: dict of langchain_mode keys and database types - E.g. python generate.py --base_model=llama --langchain_modes=['TestData'] --langchain_mode_types="{'TestData':'shared'}" - The type is attempted to be inferred if directory already exists, then don't have to pass this - :param detect_user_path_changes_every_query: whether to detect if any files changed or added every similarity search (by file hashes). - Expensive for large number of files, so not done by default. By default only detect changes during db loading. - - :param langchain_action: Mode langchain operations in on documents. - Query: Make query of document(s) - Summarize or Summarize_map_reduce: Summarize document(s) via map_reduce - Summarize_all: Summarize document(s) using entire document at once - Summarize_refine: Summarize document(s) using entire document, and try to refine before returning summary - Extract: Extract information from document(s) via map (no reduce) - :param langchain_agents: Which agents to use - 'search': Use Web Search as context for LLM response, e.g. SERP if have SERPAPI_API_KEY in env - :param force_langchain_evaluate: Whether to force langchain LLM use even if not doing langchain, mostly for testing. - - :param visible_langchain_actions: Which actions to allow - :param visible_langchain_agents: Which agents to allow - - :param document_subset: Default document choice when taking subset of collection - :param document_choice: Chosen document(s) by internal name, 'All' means use all docs - - :param use_llm_if_no_docs: Whether to use LLM even if no documents, when langchain_mode=UserData or MyData or custom - :param load_db_if_exists: Whether to load chroma db if exists or re-generate db - :param keep_sources_in_context: Whether to keep url sources in context, not helpful usually - :param db_type: 'faiss' for in-memory - 'chroma' (for chroma >= 0.4) - 'chroma_old' (for chroma < 0.4) -- recommended for large collections - 'weaviate' for persisted on disk - :param use_openai_embedding: Whether to use OpenAI embeddings for vector db - :param use_openai_model: Whether to use OpenAI model for use with vector db - :param hf_embedding_model: Which HF embedding model to use for vector db - Default is instructor-large with 768 parameters per embedding if have GPUs, else all-MiniLM-L6-v2 if no GPUs - Can also choose simpler model with 384 parameters per embedding: "sentence-transformers/all-MiniLM-L6-v2" - Can also choose even better embedding with 1024 parameters: 'hkunlp/instructor-xl' - We support automatically changing of embeddings for chroma, with a backup of db made if this is done - :param migrate_embedding_model: whether to use hf_embedding_model embedding even if database already had an embedding set. - used to migrate all embeddings to a new one, but will take time to re-embed. - Default (False) is to use the prior embedding for existing databases, and only use hf_embedding_model for new databases - If had old database without embedding saved, then hf_embedding_model is also used. - :param auto_migrate_db: whether to automatically migrate any chroma<0.4 database from duckdb -> sqlite version - :param cut_distance: Distance to cut off references with larger distances when showing references. - 1.64 is good to avoid dropping references for all-MiniLM-L6-v2, but instructor-large will always show excessive references. - For all-MiniLM-L6-v2, a value of 1.5 can push out even more references, or a large value of 100 can avoid any loss of references. - :param answer_with_sources: Whether to determine (and return) sources - :param append_sources_to_answer: Whether to place source information in chat response (ignored by LLM). Always disabled for API. - :param show_accordions: whether to show accordion for document references in chatbot UI - :param top_k_docs_max_show: Max number of docs to show in UI for sources - If web search is enabled, then this is modified to be max(top_k_docs_max_show, number of links used in search) - :param show_link_in_sources: Whether to show URL link to source document in references - :param pre_prompt_query: prompt before documents to query, if None then use internal defaults - :param prompt_query: prompt after documents to query, if None then use internal defaults - :param pre_prompt_summary: prompt before documents to summarize/extract from, if None then use internal defaults - :param prompt_summary: prompt after documents to summarize/extract from, if None then use internal defaults - For summarize/extract, normal to have empty query (nothing added in ask anything in UI or empty string in API) - If pass query, template is "Focusing on %s, %s" % (query, prompt_summary) - If pass query and iinput, template is "Focusing on %s, %s, %s" % (query, iinput, prompt_summary) - :param add_chat_history_to_context: Include chat context when performing action - Not supported yet for openai_chat when using document collection instead of LLM - Also not supported when using CLI mode - :param add_search_to_context: Include web search in context as augmented prompt - :param context: Default context to use (for system pre-context in gradio UI) - context comes before chat_conversation and any document Q/A from text_context_list - :param iinput: Default input for instruction-based prompts - :param allow_upload_to_user_data: Whether to allow file uploads to update shared vector db (UserData or custom user dbs) - Ensure pass user_path for the files uploaded to be moved to this location for linking. - :param reload_langchain_state: Whether to reload langchain_modes.pkl file that contains any new user collections. - :param allow_upload_to_my_data: Whether to allow file uploads to update personal vector db - :param enable_url_upload: Whether to allow upload from URL - :param enable_text_upload: Whether to allow upload of text - :param enable_sources_list: Whether to allow list (or download for non-shared db) of list of sources for chosen db - :param chunk: Whether to chunk data (True unless know data is already optimally chunked) - :param chunk_size: Size of chunks, with typically top-4 passed to LLM, so needs to be in context length - :param top_k_docs: For langchain_action query: number of chunks to give LLM - -1 : auto-fills context up to max_seq_len - For langchain_action summarize/extract: number of document parts, like pages for PDF. - There's no such thing as chunks for summarization. - -1 : auto-fills context up to max_seq_len - :param docs_ordering_type: - Type of ordering of docs. - 'best_first': Order by score so score is worst match near prompt - 'best_near_prompt' or 'reverse_sort' : reverse docs order so most relevant is closest to question. - Best choice for sufficiently smart model, and truncation occurs for oldest context, so best then too. - But smaller 6_9 models fail to use newest context and can get stuck on old information. - '' or None (i.e. default) or 'reverse_ucurve_sort' : Sort so most relevant is either near start or near end - Best to avoid "lost in middle" as well as avoid hallucinating off starting content that LLM focuses on alot. - :param auto_reduce_chunks: Whether to automatically reduce top_k_docs to fit context given prompt - :param max_chunks: If top_k_docs=-1, maximum number of chunks to allow - :param headsize: Maximum number of characters for head of document document for UI to show - :param n_jobs: Number of processors to use when consuming documents (-1 = all, is default) - - :param use_unstructured: Enable unstructured URL loader - :param use_playwright: Enable PlayWright URL loader - :param use_selenium: Enable Selenium URL loader - - :param use_pymupdf: enable PyMUPDF 'auto' means use first, use others if they are 'auto' if no result - :param use_unstructured_pdf: enable Unstructured PDF loader, 'auto' means use if pymupdf fails to get doc result - :param use_pypdf: enable PyPDF loader 'auto' means use if unstructured fails to get doc result - :param enable_pdf_ocr: 'auto' means only use OCR if normal text extraction fails. Useful for pure image-based PDFs with text. - if enable_pdf_doctr == 'on' then don't do. - 'on' means always do OCR as additional parsing of same documents - 'off' means don't do OCR (e.g. because it's slow even if 'auto' only would trigger if nothing else worked) - :param enable_pdf_doctr: Whether to support doctr on pdfs, 'auto' means use do if failed to get doc result so far - :param try_pdf_as_html: Try "PDF" as if HTML file, in case web link has .pdf extension but really is just HTML - - :param enable_ocr: Whether to support OCR on images - :param enable_doctr: Whether to support doctr on images (using OCR better than enable_ocr=True) - :param enable_pix2struct: Whether to support pix2struct on images for captions - :param enable_captions: Whether to support captions using BLIP for image files as documents, - then preloads that model if pre_load_caption_model=True - - :param pre_load_caption_model: Whether to preload caption model (True), or load after forking parallel doc loader (False) - parallel loading disabled if preload and have images, to prevent deadlocking on cuda context - Recommended if using larger caption model or doing production serving with many users to avoid GPU OOM if many would use model at same time - Also applies to DocTR - :param captions_model: Which model to use for captions. - captions_model: str = "Salesforce/blip-image-captioning-base", # continue capable - captions_model: str = "Salesforce/blip2-flan-t5-xl", # question/answer capable, 16GB state - captions_model: str = "Salesforce/blip2-flan-t5-xxl", # question/answer capable, 60GB state - Note: opt-based blip2 are not permissive license due to opt and Meta license restrictions - Disabled for CPU since BLIP requires CUDA - :param caption_gpu: If support caption, then use GPU if exists - :param caption_gpu_id: Which GPU id to use, if 'auto' then select 0 - - :param doctr_gpu: If support doctr, then use GPU if exists - :param doctr_gpu_id: Which GPU id to use, if 'auto' then select 0 - - :param jq_schema: control json loader - By default '.[]' ingests everything in brute-force way, but better to match your schema - See: https://python.langchain.com/docs/modules/data_connection/document_loaders/json#using-jsonloader - - :param max_quality: Choose maximum quality ingestion with all available parsers - Pro: Catches document when some default parsers would fail - Pro: Enables DocTR that has much better OCR than Tesseract - Con: Fills DB with results from all parsers, so similarity search gives redundant results - - :param enable_heap_analytics: Toggle telemetry. - :param heap_app_id: App ID for Heap, change to your ID. - :return: - """ - if base_model is None: - base_model = '' - if tokenizer_base_model is None: - tokenizer_base_model = '' - if lora_weights is None: - lora_weights = '' - if inference_server is None: - inference_server = '' - - # listen to env if set - model_lock = os.getenv('model_lock', str(model_lock)) - model_lock = ast.literal_eval(model_lock) - - chat_conversation = str_to_list(chat_conversation) - text_context_list = str_to_list(text_context_list) - - llamacpp_dict = str_to_dict(llamacpp_dict) - # add others to single dict - llamacpp_dict['model_path_llama'] = model_path_llama - llamacpp_dict['model_name_gptj'] = model_name_gptj - llamacpp_dict['model_name_gpt4all_llama'] = model_name_gpt4all_llama - llamacpp_dict['model_name_exllama_if_no_config'] = model_name_exllama_if_no_config - # if user overrides but doesn't set these: - if 'n_batch' not in llamacpp_dict: - llamacpp_dict['n_batch'] = 128 - if 'n_gpu_layers' not in llamacpp_dict: - llamacpp_dict['n_gpu_layers'] = 100 - if 'n_gqa' not in llamacpp_dict: - llamacpp_dict['n_gqa'] = 0 - - exllama_dict = str_to_dict(exllama_dict) - gptq_dict = str_to_dict(gptq_dict) - sink_dict = str_to_dict(sink_dict) - hf_model_dict = str_to_dict(hf_model_dict) - - if os.environ.get('SERPAPI_API_KEY') is None and LangChainAgent.SEARCH.value in visible_langchain_agents: - visible_langchain_agents.remove(LangChainAgent.SEARCH.value) - - if model_lock: - assert gradio, "model_lock only supported for gradio=True" - assert not cli, "model_lock only supported for cli=False" - assert not (not cli and not gradio), "model_lock only supported for eval (cli=gradio=False)" - assert not base_model, "Don't specify model_lock and base_model" - assert not tokenizer_base_model, "Don't specify model_lock and tokenizer_base_model" - assert not lora_weights, "Don't specify model_lock and lora_weights" - assert not inference_server, "Don't specify model_lock and inference_server" - # assert not prompt_type, "Don't specify model_lock and prompt_type" - # assert not prompt_dict, "Don't specify model_lock and prompt_dict" - - n_jobs = int(os.getenv('n_jobs', str(n_jobs))) - is_hf = bool(int(os.getenv("HUGGINGFACE_SPACES", '0'))) - is_gpth2oai = bool(int(os.getenv("GPT_H2O_AI", '0'))) - is_public = is_hf or is_gpth2oai # multi-user case with fixed model and disclaimer - if enforce_h2ogpt_ui_key is None: - # nominally allow UI access public or not - enforce_h2ogpt_ui_key = False - if is_public: - visible_tos_tab = visible_hosts_tab = True - if enforce_h2ogpt_api_key is None: - enforce_h2ogpt_api_key = True - else: - if enforce_h2ogpt_api_key is None: - enforce_h2ogpt_api_key = False - if isinstance(h2ogpt_api_keys, str) and not os.path.isfile(h2ogpt_api_keys): - h2ogpt_api_keys = str_to_list(h2ogpt_api_keys) - if memory_restriction_level is None: - memory_restriction_level = 2 if is_hf else 0 # 2 assumes run on 24GB consumer GPU - else: - assert 0 <= memory_restriction_level <= 3, "Bad memory_restriction_level=%s" % memory_restriction_level - if n_jobs == -1: - # if -1, assume hypercores, don't use, force user to pass n_jobs to be specific if not standard cores - n_jobs = max(1, os.cpu_count() // 2) - if is_public and os.getenv('n_jobs') is None: - n_jobs = min(n_jobs, max(1, min(os.cpu_count() // 2, 8))) - admin_pass = os.getenv("ADMIN_PASS") - # will sometimes appear in UI or sometimes actual generation, but maybe better than empty result - # but becomes unrecoverable sometimes if raise, so just be silent for now - raise_generate_gpu_exceptions = True - - rope_scaling = str_to_dict(rope_scaling) - - if isinstance(auth, str): - if auth.strip().startswith('['): - auth = str_to_list(auth) - if isinstance(auth, str) and auth: - auth_filename = auth - if not auth_filename: - auth_filename = "auth.json" - assert isinstance(auth, (str, list, tuple, type(None))), "Unknown type %s for auth=%s" % (type(auth), auth) - - # allow set token directly - use_auth_token = os.environ.get("HUGGING_FACE_HUB_TOKEN", use_auth_token) - allow_upload_to_user_data = bool( - int(os.environ.get("allow_upload_to_user_data", str(int(allow_upload_to_user_data))))) - allow_upload_to_my_data = bool(int(os.environ.get("allow_upload_to_my_data", str(int(allow_upload_to_my_data))))) - height = int(os.environ.get("HEIGHT", height)) - h2ocolors = bool(int(os.getenv('h2ocolors', h2ocolors))) - - # allow enabling langchain via ENV - # FIRST PLACE where LangChain referenced, but no imports related to it - langchain_modes = ast.literal_eval(os.environ.get("langchain_modes", str(langchain_modes))) - if not isinstance(langchain_modes, list): - langchain_modes = [] - # always allow DISABLED - if LangChainMode.DISABLED.value not in langchain_modes: - langchain_modes.append(LangChainMode.DISABLED.value) - if not have_langchain: - # only allow disabled, not even LLM that is langchain related - langchain_mode = LangChainMode.DISABLED.value - langchain_modes = [langchain_mode] - - # update - langchain_mode_paths = str_to_dict(langchain_mode_paths) - langchain_mode_types = str_to_dict(langchain_mode_types) - for lmode in [LangChainMode.GITHUB_H2OGPT.value, - LangChainMode.H2O_DAI_DOCS.value, - LangChainMode.WIKI.value, - LangChainMode.WIKI_FULL.value, - ]: - if lmode not in langchain_mode_types: - langchain_mode_types[lmode] = 'shared' - if lmode not in langchain_mode_paths: - langchain_mode_types[lmode] = '' - if user_path: - user_path = makedirs(user_path, use_base=True) - langchain_mode_paths['UserData'] = user_path - langchain_mode_paths['UserData'] = LangChainTypes.SHARED.value - - if is_public: - allow_upload_to_user_data = False - if LangChainMode.USER_DATA.value in langchain_modes: - langchain_modes.remove(LangChainMode.USER_DATA.value) - if max_raw_chunks is None: - max_raw_chunks = 30 if is_public else 1000000 - - # in-place, for non-scratch dbs - if allow_upload_to_user_data: - # always listen to CLI-passed user_path if passed - if user_path: - langchain_mode_paths['UserData'] = user_path - - assert langchain_action in langchain_actions, "Invalid langchain_action %s not in %s" % ( - langchain_action, langchain_actions) - assert len( - set(langchain_agents).difference(langchain_agents_list)) == 0, "Invalid langchain_agents %s" % langchain_agents - - # auto-set langchain_mode - langchain_mode = os.environ.get("LANGCHAIN_MODE", langchain_mode) - if have_langchain and langchain_mode is None: - # start in chat mode, in case just want to chat and don't want to get "No documents to query" by default. - if LangChainMode.LLM.value in langchain_modes: - langchain_mode = LangChainMode.LLM.value - elif len(langchain_modes) >= 1: - # infer even if don't pass which langchain_mode, just langchain_modes. - langchain_mode = langchain_modes[0] - if allow_upload_to_user_data and not is_public and langchain_mode_paths['UserData']: - if verbose: - print("Auto set langchain_mode=%s. Could use UserData instead." % langchain_mode, flush=True) - elif allow_upload_to_my_data: - if verbose: - print("Auto set langchain_mode=%s. Could use MyData instead." - " To allow UserData to pull files from disk," - " set user_path or langchain_mode_paths, and ensure allow_upload_to_user_data=True" % langchain_mode, - flush=True) - else: - raise RuntimeError("Please pass --langchain_mode= out of %s" % langchain_modes) - if not have_langchain and langchain_mode not in [None, LangChainMode.DISABLED.value, LangChainMode.LLM.value]: - raise RuntimeError("Asked for LangChain mode but langchain python package cannot be found.") - if langchain_mode is None: - # if not set yet, disable - langchain_mode = LangChainMode.DISABLED.value - print("Auto set langchain_mode=%s Have langchain package: %s" % (langchain_mode, have_langchain), flush=True) - # go ahead and add - if langchain_mode not in langchain_modes: - langchain_modes.append(langchain_mode) - - if is_public: - allow_upload_to_user_data = False - input_lines = 1 # ensure set, for ease of use - temperature = 0.2 if temperature is None else temperature - top_p = 0.85 if top_p is None else top_p - top_k = 70 if top_k is None else top_k - penalty_alpha = 0.0 if penalty_alpha is None else penalty_alpha - if is_hf: - do_sample = True if do_sample is None else do_sample - top_k_docs = 3 if top_k_docs is None else top_k_docs - else: - # by default don't sample, too chatty - do_sample = False if do_sample is None else do_sample - top_k_docs = 4 if top_k_docs is None else top_k_docs - - if memory_restriction_level == 2: - if not base_model and not inference_server and not model_lock: - base_model = 'h2oai/h2ogpt-oasst1-512-12b' - # don't set load_8bit if passed base_model, doesn't always work so can't just override - load_8bit = True - load_4bit = False # FIXME - consider using 4-bit instead of 8-bit - elif not inference_server: - top_k_docs = 10 if top_k_docs is None else top_k_docs - if memory_restriction_level >= 2: - load_8bit = True - load_4bit = False # FIXME - consider using 4-bit instead of 8-bit - if hf_embedding_model is None: - hf_embedding_model = "sentence-transformers/all-MiniLM-L6-v2" - top_k_docs = 3 if top_k_docs is None else top_k_docs - if top_k_docs is None: - top_k_docs = 3 - if is_public: - if not max_time: - max_time = 60 * 2 - if not max_max_time: - max_max_time = max_time - if not max_new_tokens: - max_new_tokens = 256 - if not max_max_new_tokens: - max_max_new_tokens = 512 - else: - if not max_max_time: - max_max_time = 60 * 20 - if not max_max_new_tokens: - max_max_new_tokens = 1024 - if is_hf: - # must override share if in spaces - share = False - if not max_time: - max_time = 60 * 1 - if not max_max_time: - max_max_time = max_time - # HF accounted for later in get_max_max_new_tokens() - save_dir = os.getenv('SAVE_DIR', save_dir) - save_dir = makedirs(save_dir, exist_ok=True, tmp_ok=True, use_base=True) - score_model = os.getenv('SCORE_MODEL', score_model) - if str(score_model) == 'None': - score_model = '' - concurrency_count = int(os.getenv('CONCURRENCY_COUNT', concurrency_count)) - api_open = bool(int(os.getenv('API_OPEN', str(int(api_open))))) - allow_api = bool(int(os.getenv('ALLOW_API', str(int(allow_api))))) - - n_gpus = torch.cuda.device_count() if torch.cuda.is_available() else 0 - n_gpus, gpu_ids = cuda_vis_check(n_gpus) - - if load_half is None and t5_type(base_model): - load_half = False - print("load_half=%s auto-set for %s to avoid bad generation" % (load_half, base_model), flush=True) - - if n_gpus == 0 or get_device() == "mps": - # No CUDA GPUs usable - - if get_device() != "mps": - print("No GPUs detected", flush=True) - - enable_captions = False - gpu_id = None - load_8bit = False - load_4bit = False - low_bit_mode = 1 - if load_half is None: - # wouldn't work if specified True, but respect - load_half = False - load_gptq = '' - load_awq = '' - load_exllama = False - use_gpu_id = False - if get_device() == "cuda": - torch.backends.cudnn.benchmark = True - torch.backends.cudnn.enabled = False - torch.set_default_dtype(torch.float32) - if is_public and not inference_server and not model_lock: - # 12B uses ~94GB - # 6.9B uses ~47GB - base_model = 'h2oai/h2ogpt-oig-oasst1-512-6_9b' if not base_model else base_model - if hf_embedding_model is None: - # if no GPUs, use simpler embedding model to avoid cost in time - hf_embedding_model = "sentence-transformers/all-MiniLM-L6-v2" - if score_model == 'auto': - score_model = '' - else: - if load_half is None: - load_half = True - # CUDA GPUs visible - if score_model == 'auto': - if n_gpus >= 2: - # will by default place scoring model on last GPU - score_model = 'OpenAssistant/reward-model-deberta-v3-large-v2' - else: - score_model = '' - if hf_embedding_model is None: - # if still None, then set default - hf_embedding_model = 'hkunlp/instructor-large' - - # get defaults - if base_model: - model_lower = base_model.lower() - elif model_lock: - # have 0th model be thought of as normal model - assert len(model_lock) > 0 and model_lock[0]['base_model'], "model_lock: %s" % model_lock - model_lower = model_lock[0]['base_model'].lower() - else: - model_lower = '' - if not gradio: - # force, else not single response like want to look at - stream_output = False - # else prompt removal can mess up output - chat = False - # hard-coded defaults - first_para = False - text_limit = None - - if compile_model is None: - # too avoid noisy CLI - compile_model = not cli - - if offload_folder: - offload_folder = makedirs(offload_folder, exist_ok=True, tmp_ok=True, use_base=True) - - # defaults - caption_loader = None - doctr_loader = None - pix2struct_loader = None - - image_loaders_options0, image_loaders_options, \ - pdf_loaders_options0, pdf_loaders_options, \ - url_loaders_options0, url_loaders_options = lg_to_gr(**locals()) - jq_schema0 = jq_schema - # transcribe - image_loaders = image_loaders_options0 - pdf_loaders = pdf_loaders_options0 - url_loaders = url_loaders_options0 - - placeholder_instruction, placeholder_input, \ - stream_output, show_examples, \ - prompt_type, prompt_dict, \ - temperature, top_p, top_k, penalty_alpha, num_beams, \ - max_new_tokens, min_new_tokens, early_stopping, max_time, \ - repetition_penalty, num_return_sequences, \ - do_sample, \ - src_lang, tgt_lang, \ - examples, \ - task_info = \ - get_generate_params(model_lower, - chat, - stream_output, show_examples, - prompt_type, prompt_dict, - system_prompt, - pre_prompt_query, prompt_query, - pre_prompt_summary, prompt_summary, - temperature, top_p, top_k, penalty_alpha, num_beams, - max_new_tokens, min_new_tokens, early_stopping, max_time, - repetition_penalty, num_return_sequences, - do_sample, - top_k_docs, - chunk, - chunk_size, - image_loaders, - pdf_loaders, - url_loaders, - jq_schema, - docs_ordering_type, - min_max_new_tokens, - max_input_tokens, - docs_token_handling, - docs_joiner, - hyde_level, - hyde_template, - verbose, - ) - - git_hash = get_githash() if is_public or os.getenv('GET_GITHASH') else "GET_GITHASH" - locals_dict = locals() - locals_print = '\n'.join(['%s: %s' % (k, v) for k, v in locals_dict.items()]) - if verbose: - print(f"Generating model with params:\n{locals_print}", flush=True) - print("Command: %s\nHash: %s" % (str(' '.join(sys.argv)), git_hash), flush=True) - - if langchain_mode != LangChainMode.DISABLED.value: - # SECOND PLACE where LangChain referenced, but all imports are kept local so not required - from gpt_langchain import prep_langchain, get_some_dbs_from_hf, get_persist_directory - if is_hf: - get_some_dbs_from_hf() - dbs = {} - for langchain_mode1 in langchain_modes: - langchain_type = langchain_mode_types.get(langchain_mode1, LangChainTypes.EITHER.value) - if langchain_type == LangChainTypes.PERSONAL.value: - # shouldn't prepare per-user databases here - continue - persist_directory1, langchain_type = get_persist_directory(langchain_mode1, langchain_type=langchain_type) - langchain_mode_types[langchain_mode1] = langchain_type - if langchain_type == LangChainTypes.PERSONAL.value: - # shouldn't prepare per-user databases here - continue - try: - db = prep_langchain(persist_directory1, - load_db_if_exists, - db_type, use_openai_embedding, - langchain_mode1, langchain_mode_paths, langchain_mode_types, - hf_embedding_model, - migrate_embedding_model, - auto_migrate_db, - kwargs_make_db=locals(), - verbose=verbose) - finally: - # in case updated embeddings or created new embeddings - clear_torch_cache() - dbs[langchain_mode1] = db - # remove None db's so can just rely upon k in dbs for if hav db - dbs = {k: v for k, v in dbs.items() if v is not None} - else: - dbs = {} - # import control - if os.environ.get("TEST_LANGCHAIN_IMPORT"): - assert 'gpt_langchain' not in sys.modules, "Dev bug, import of langchain when should not have" - assert 'langchain' not in sys.modules, "Dev bug, import of langchain when should not have" - - if attention_sinks: - if use_cache is False: - raise ValueError("attention sinks requires use_cache=True") - else: - use_cache = True - # never truncate if using attention sinks - truncation_generation = truncation_generation and not attention_sinks - - other_model_state_defaults = dict(load_8bit=load_8bit, load_4bit=load_4bit, low_bit_mode=low_bit_mode, - load_half=load_half, - load_gptq=load_gptq, load_awq=load_awq, load_exllama=load_exllama, - use_safetensors=use_safetensors, - revision=revision, use_gpu_id=use_gpu_id, gpu_id=gpu_id, - compile_model=compile_model, - use_cache=use_cache, - llamacpp_dict=llamacpp_dict, model_path_llama=model_path_llama, - model_name_gptj=model_name_gptj, - model_name_gpt4all_llama=model_name_gpt4all_llama, - model_name_exllama_if_no_config=model_name_exllama_if_no_config, - rope_scaling=rope_scaling, - max_seq_len=max_seq_len, - exllama_dict=exllama_dict, - gptq_dict=gptq_dict, - attention_sinks=attention_sinks, - sink_dict=sink_dict, - truncation_generation=truncation_generation, - hf_model_dict=hf_model_dict, - ) - model_state_none = dict(model=None, tokenizer=None, device=None, - base_model=None, tokenizer_base_model=None, lora_weights=None, - inference_server=None, prompt_type=None, prompt_dict=None, - visible_models=None, h2ogpt_key=None, - ) - model_state_none.update(other_model_state_defaults) - my_db_state0 = {LangChainMode.MY_DATA.value: [None, None, None]} - selection_docs_state0 = dict(langchain_modes=langchain_modes, - langchain_mode_paths=langchain_mode_paths, - langchain_mode_types=langchain_mode_types) - selection_docs_state = copy.deepcopy(selection_docs_state0) - - if cli or not gradio: - # initial state for query prompt - model_name = base_model - pre_prompt_query, prompt_query, pre_prompt_summary, prompt_summary = \ - get_langchain_prompts(pre_prompt_query, prompt_query, - pre_prompt_summary, prompt_summary, - model_name, inference_server, - model_path_llama) - - if cli: - from cli import run_cli - return run_cli(**get_kwargs(run_cli, exclude_names=['model_state0'], **locals())) - elif not gradio: - from eval import run_eval - return run_eval(**get_kwargs(run_eval, exclude_names=['model_state0'], **locals())) - elif gradio or prepare_offline_level > 0: - # imported here so don't require gradio to run generate - from gradio_runner import go_gradio - - # get default model - model_states = [] - model_list = [dict(base_model=base_model, tokenizer_base_model=tokenizer_base_model, lora_weights=lora_weights, - inference_server=inference_server, prompt_type=prompt_type, prompt_dict=prompt_dict, - visible_models=None, h2ogpt_key=None)] - model_list[0].update(other_model_state_defaults) - # FIXME: hyper per model, not about model loading - # for k in gen_hyper: - # model_list[k] = locals()[k] - - model_list0 = copy.deepcopy(model_list) # just strings, safe to deepcopy - model_state0 = model_state_none.copy() - assert len(model_state_none) == len(model_state0) - if model_lock: - model_list = model_lock - # do reverse, so first is default base_model etc., so some logic works in go_gradio() more easily - for model_dict in reversed(model_list): - # handle defaults user didn't have to pass - # special defaults, ignore defaults for these if not specifically set, replace with '' - model_dict['base_model'] = model_dict.get('base_model', '') - model_dict['tokenizer_base_model'] = model_dict.get('tokenizer_base_model', '') - model_dict['lora_weights'] = model_dict.get('lora_weights', '') - model_dict['inference_server'] = model_dict.get('inference_server', '') - if prepare_offline_level >= 2: - if 'openai' not in model_dict['inference_server'] and 'replicate' not in model_dict['inference_server']: - # assume want locally, but OpenAI and replicate are never local for model part - model_dict['inference_server'] = '' - prompt_type_infer = not model_dict.get('prompt_type') - model_dict['prompt_type'] = model_dict.get('prompt_type', - model_list0[0]['prompt_type']) # don't use mutated value - # rest of generic defaults - for k in model_list0[0]: - if k not in model_dict: - model_dict[k] = model_list0[0][k] - - # begin prompt adjustments - # get query prompt for (say) last base model if using model lock - pre_prompt_query1, prompt_query1, pre_prompt_summary1, prompt_summary1 = ( - get_langchain_prompts(pre_prompt_query, prompt_query, - pre_prompt_summary, prompt_summary, - model_dict['base_model'], - model_dict['inference_server'], - model_dict['model_path_llama'])) - # if mixed setup, choose non-empty so best models best - # FIXME: Make per model dict passed through to evaluate - pre_prompt_query = pre_prompt_query or pre_prompt_query1 - prompt_query = prompt_query or prompt_query1 - pre_prompt_summary = pre_prompt_summary or pre_prompt_summary1 - prompt_summary = prompt_summary or prompt_summary1 - - # try to infer, ignore empty initial state leading to get_generate_params -> 'plain' - if prompt_type_infer: - model_lower1 = model_dict['base_model'].lower() - if model_lower1 in inv_prompt_type_to_model_lower: - model_dict['prompt_type'] = inv_prompt_type_to_model_lower[model_lower1] - model_dict['prompt_dict'], error0 = get_prompt(model_dict['prompt_type'], '', - chat=False, context='', reduced=False, - making_context=False, - return_dict=True, - system_prompt=system_prompt) - else: - model_dict['prompt_dict'] = prompt_dict - else: - model_dict['prompt_dict'] = prompt_dict - model_dict['prompt_dict'] = model_dict.get('prompt_dict', model_dict['prompt_dict']) - # end prompt adjustments - all_kwargs = locals().copy() - all_kwargs.update(model_dict) - if model_dict['base_model'] and not login_mode_if_model0: - model0, tokenizer0, device = get_model(reward_type=False, - **get_kwargs(get_model, exclude_names=['reward_type'], - **all_kwargs)) - # update model state - if hasattr(tokenizer0, 'model_max_length'): - model_dict['max_seq_len'] = tokenizer0.model_max_length - else: - # if empty model, then don't load anything, just get gradio up - model0, tokenizer0, device = None, None, None - if model0 is None: - if fail_if_cannot_connect: - raise RuntimeError("Could not connect, see logs") - # skip - if isinstance(model_lock, list): - model_lock.remove(model_dict) - continue - model_state_trial = dict(model=model0, tokenizer=tokenizer0, device=device) - model_state_trial.update(model_dict) - diff_keys = set(list(model_state_none.keys())).symmetric_difference(model_state_trial.keys()) - assert len(model_state_none) == len(model_state_trial), diff_keys - print("Model %s" % model_dict, flush=True) - if model_lock: - # last in iteration will be first - model_states.insert(0, model_state_trial) - # fill model_state0 so go_gradio() easier, manage model_states separately - model_state0 = model_state_trial.copy() - else: - model_state0 = model_state_trial.copy() - assert len(model_state_none) == len(model_state0) - - visible_models = str_to_list(visible_models, allow_none=True) # None means first model - all_models = [x.get('base_model', xi) for xi, x in enumerate(model_states)] - visible_models_state0 = [x.get('base_model', xi) for xi, x in enumerate(model_states) if - visible_models is None or - x.get('base_model', xi) in visible_models or - xi in visible_models] - - # update to be consistent with what is passed from CLI and model chose - # do after go over all models if multi-model, so don't contaminate - # This is just so UI shows reasonable correct value, not 2048 dummy value - if len(model_states) >= 1: - max_seq_len = model_states[0]['tokenizer'].model_max_length - elif model_state0 is not None and \ - 'tokenizer' in model_state0 and \ - hasattr(model_state0['tokenizer'], 'model_max_length'): - max_seq_len = model_state0['tokenizer'].model_max_length - - # get score model - all_kwargs = locals().copy() - smodel, stokenizer, sdevice = get_score_model(reward_type=True, - **get_kwargs(get_score_model, exclude_names=['reward_type'], - **all_kwargs)) - score_model_state0 = dict(model=smodel, tokenizer=stokenizer, device=sdevice, - base_model=score_model, tokenizer_base_model='', lora_weights='', - inference_server='', prompt_type='', prompt_dict='', - visible_models=None, h2ogpt_key=None) - - if enable_captions: - if pre_load_caption_model: - from image_captions import H2OImageCaptionLoader - caption_loader = H2OImageCaptionLoader(caption_gpu=caption_gpu, gpu_id=caption_gpu_id).load_model() - else: - caption_loader = 'gpu' if n_gpus > 0 and caption_gpu else 'cpu' - else: - caption_loader = False - - if pre_load_embedding_model and \ - langchain_mode != LangChainMode.DISABLED.value and \ - not use_openai_embedding: - from src.gpt_langchain import get_embedding - hf_embedding_model = dict(name=hf_embedding_model, - model=get_embedding(use_openai_embedding, hf_embedding_model=hf_embedding_model, - preload=True)) - - if enable_doctr or enable_pdf_ocr in [True, 'auto', 'on']: - if pre_load_caption_model: - from image_doctr import H2OOCRLoader - doctr_loader = H2OOCRLoader(layout_aware=True, gpu_id=doctr_gpu_id) - else: - doctr_loader = 'gpu' if n_gpus > 0 and caption_gpu else 'cpu' - else: - doctr_loader = False - - # assume gradio needs everything - go_gradio(**locals()) - - -def get_config(base_model, - use_auth_token=False, - trust_remote_code=True, - offload_folder=None, - revision=None, - rope_scaling=None, - triton_attn=False, - long_sequence=True, - return_model=False, - raise_exception=False, - max_seq_len=None, - verbose=False, - ): - from accelerate import init_empty_weights - with init_empty_weights(): - from transformers import AutoConfig - try: - if rope_scaling: - rope_kwargs = dict(rope_scaling=rope_scaling) - else: - rope_kwargs = {} - config = AutoConfig.from_pretrained(base_model, token=use_auth_token, - trust_remote_code=trust_remote_code, - offload_folder=offload_folder, - revision=revision, - **rope_kwargs) - except OSError as e: - if raise_exception: - raise - if 'not a local folder and is not a valid model identifier listed on' in str( - e) or '404 Client Error' in str(e) or "couldn't connect" in str(e): - # e.g. llama, gpjt, etc. - # e.g. HF TGI but not model on HF or private etc. - if max_seq_len is None and base_model.lower() in non_hf_types: - print("Could not determine --max_seq_len, setting to 2048. Pass if not correct", flush=True) - max_seq_len = 2048 - # HF TGI server only should really require prompt_type, not HF model state - return None, None, max_seq_len - else: - raise - if triton_attn and 'mpt-' in base_model.lower(): - config.attn_config['attn_impl'] = 'triton' - if long_sequence: - if 'mpt-7b-storywriter' in base_model.lower(): - config.update({"max_seq_len": 83968}) - if 'mosaicml/mpt-7b-chat' in base_model.lower(): - config.update({"max_seq_len": 4096}) - if 'mpt-30b' in base_model.lower(): - config.update({"max_seq_len": 2 * 8192}) - if return_model and \ - issubclass(config.__class__, tuple(AutoModel._model_mapping.keys())): - model = AutoModel.from_config( - config, - trust_remote_code=trust_remote_code, - ) - else: - # can't infer - model = None - if 'falcon' in base_model.lower(): - config.use_cache = False - - # allow override - if max_seq_len is not None: - print("Overriding max_seq_len -> %d" % max_seq_len, flush=True) - else: - if hasattr(config, 'max_seq_len'): - max_seq_len = int(config.max_seq_len) - # Note https://huggingface.co/lmsys/vicuna-13b-v1.5-16k/blob/main/config.json has below, but here just want base size before rope - # elif hasattr(config, 'max_sequence_length'): - # max_seq_len = int(config.max_sequence_length) - elif hasattr(config, 'max_position_embeddings') and isinstance(config.max_position_embeddings, int): - # help automatically limit inputs to generate - max_seq_len = config.max_position_embeddings - if verbose: - print("Used max_position_embeddings=%s as base model (pre-rope) max_seq_len." - " If not desired, pass --max_seq_len and set to some integer value." % config.max_position_embeddings, - flush=True) - elif hasattr(config, 'n_ctx'): - # e.g. gpt2 - max_seq_len = int(config.n_ctx) - else: - print("Could not determine --max_seq_len, setting to 2048. Pass if not correct", flush=True) - max_seq_len = 2048 - # FIXME: - # raise RuntimeError("Could not determine max_seq_len," - # " please pass --max_seq_len and set to some value, e.g. 2048.") - - # listen to model if sets this and user passed nothing - if not rope_scaling and hasattr(config, 'rope_scaling'): - rope_scaling = config.rope_scaling - - if rope_scaling: - if rope_scaling.get('factor'): - # HF transformers - max_seq_len *= rope_scaling.get('factor') - elif rope_scaling.get('alpha_value'): - # exllama - # Note: exllama's own tokenizer has this set correctly in loaders.py, this config will be unused - max_seq_len *= rope_scaling.get('alpha_value') - max_seq_len = int(max_seq_len) - print("Automatically setting max_seq_len=%d for RoPE scaling for %s" % (max_seq_len, base_model), - flush=True) - - return config, model, max_seq_len - - -def get_non_lora_model(base_model, model_loader, load_half, - load_gptq, - load_awq, - load_exllama, - use_safetensors, - revision, - model_kwargs, reward_type, - config, model, - gpu_id=0, - ): - """ - Ensure model gets on correct device - """ - - if model is not None: - # NOTE: Can specify max_memory={0: max_mem, 1: max_mem}, to shard model - # NOTE: Some models require avoiding sharding some layers, - # then would pass no_split_module_classes and give list of those layers. - from accelerate import infer_auto_device_map - device_map = infer_auto_device_map( - model, - dtype=torch.float16 if load_half else torch.float32, - ) - if hasattr(model, 'model'): - device_map_model = infer_auto_device_map( - model.model, - dtype=torch.float16 if load_half else torch.float32, - ) - device_map.update(device_map_model) - else: - device_map = "auto" - - n_gpus = torch.cuda.device_count() if torch.cuda.is_available() else 0 - n_gpus, gpu_ids = cuda_vis_check(n_gpus) - - if n_gpus > 0: - if gpu_id >= 0: - # FIXME: If really distributes model, tend to get things like: ValueError: gpt_neox.embed_in.weight doesn't have any device set. - # So avoid for now, just put on first GPU, unless score_model, put on last - if reward_type: - device_map = {'': n_gpus - 1} - else: - device_map = {'': min(n_gpus - 1, gpu_id)} - if gpu_id == -1: - device_map = {'': 'cuda'} - else: - device_map = {'': 'cpu'} - model_kwargs['load_in_8bit'] = False - model_kwargs['load_in_4bit'] = False - print('device_map: %s' % device_map, flush=True) - - load_in_8bit = model_kwargs.get('load_in_8bit', False) - load_in_4bit = model_kwargs.get('load_in_4bit', False) - model_kwargs['device_map'] = device_map - model_kwargs['use_safetensors'] = use_safetensors - model_kwargs['revision'] = revision - pop_unused_model_kwargs(model_kwargs) - - if load_exllama: - model = model_loader - elif load_gptq: - model_kwargs.pop('torch_dtype', None) - model_kwargs.pop('device_map') - model = model_loader( - model_name_or_path=base_model, - model_basename=load_gptq, - **model_kwargs, - ) - elif load_awq: - allowed_dict = dict(max_new_tokens=None, - trust_remote_code=True, fuse_layers=True, - batch_size=1, safetensors=False, - max_memory=None, offload_folder=None) - for k in model_kwargs.copy(): - if k not in allowed_dict: - model_kwargs.pop(k) - if load_awq.endswith('.pt'): - args = tuple([base_model, load_awq]) - else: - args = tuple([base_model]) - model = model_loader( - *args, - safetensors=use_safetensors, - **model_kwargs, - ) - elif load_in_8bit or load_in_4bit or not load_half: - model = model_loader( - base_model, - config=config, - **model_kwargs, - ) - else: - model = model_loader( - base_model, - config=config, - **model_kwargs, - ) - if not getattr(model, "is_quantized", False): - model = model.half() - return model - - -def get_client_from_inference_server(inference_server, base_model=None, raise_connection_exception=False): - inference_server, headers = get_hf_server(inference_server) - # preload client since slow for gradio case especially - from gradio_utils.grclient import GradioClient - gr_client = None - hf_client = None - if headers is None: - try: - print("GR Client Begin: %s %s" % (inference_server, base_model), flush=True) - # first do sanity check if alive, else gradio client takes too long by default - requests.get(inference_server, timeout=int(os.getenv('REQUEST_TIMEOUT', '30'))) - gr_client = GradioClient(inference_server).setup() - print("GR Client End: %s" % inference_server, flush=True) - except (OSError, ValueError) as e: - # Occurs when wrong endpoint and should have been HF client, so don't hard raise, just move to HF - gr_client = None - print("GR Client Failed %s %s: %s" % (inference_server, base_model, str(e)), flush=True) - except (ConnectTimeoutError, ConnectTimeout, MaxRetryError, ConnectionError, ConnectionError2, - JSONDecodeError, ReadTimeout2, KeyError) as e: - t, v, tb = sys.exc_info() - ex = ''.join(traceback.format_exception(t, v, tb)) - print("GR Client Failed %s %s: %s" % (inference_server, base_model, str(ex)), flush=True) - if raise_connection_exception: - raise - - if gr_client is None: - res = None - from text_generation import Client as HFClient - print("HF Client Begin: %s %s" % (inference_server, base_model)) - try: - hf_client = HFClient(inference_server, headers=headers, timeout=int(os.getenv('REQUEST_TIMEOUT', '30'))) - # quick check valid TGI endpoint - res = hf_client.generate('What?', max_new_tokens=1) - hf_client = HFClient(inference_server, headers=headers, timeout=300) - except (ConnectTimeoutError, ConnectTimeout, MaxRetryError, ConnectionError, ConnectionError2, - JSONDecodeError, ReadTimeout2, KeyError) as e: - hf_client = None - t, v, tb = sys.exc_info() - ex = ''.join(traceback.format_exception(t, v, tb)) - print("HF Client Failed %s %s: %s" % (inference_server, base_model, str(ex))) - if raise_connection_exception: - raise - print("HF Client End: %s %s : %s" % (inference_server, base_model, res)) - return inference_server, gr_client, hf_client - - -def get_model( - load_8bit: bool = False, - load_4bit: bool = False, - low_bit_mode: int = 1, - load_half: bool = True, - load_gptq: str = '', - load_awq: str = '', - load_exllama: bool = False, - use_safetensors: bool = False, - revision: str = None, - use_gpu_id: bool = True, - base_model: str = '', - inference_server: str = "", - tokenizer_base_model: str = '', - lora_weights: str = "", - gpu_id: int = 0, - n_jobs=None, - - reward_type: bool = None, - local_files_only: bool = False, - resume_download: bool = True, - use_auth_token: Union[str, bool] = False, - trust_remote_code: bool = True, - offload_folder: str = None, - rope_scaling: dict = None, - max_seq_len: int = None, - compile_model: bool = True, - llamacpp_dict=None, - exllama_dict=None, - gptq_dict=None, - attention_sinks=None, - sink_dict=None, - truncation_generation=None, - hf_model_dict={}, - - verbose: bool = False, -): - """ - - :param load_8bit: load model in 8-bit, not supported by all models - :param load_4bit: load model in 4-bit, not supported by all models - :param low_bit_mode: See gen.py - :param load_half: load model in 16-bit - :param load_gptq: GPTQ model_basename - :param load_awq: AWQ model_basename - :param load_exllama: whether to use exllama - :param use_safetensors: use safetensors file - :param revision: - :param use_gpu_id: Use torch infer of optimal placement of layers on devices (for non-lora case) - For non-LORA case, False will spread shards across multiple GPUs, but this can lead to cuda:x cuda:y mismatches - So it is not the default - :param base_model: name/path of base model - :param inference_server: whether base_model is hosted locally ('') or via http (url) - :param tokenizer_base_model: name/path of tokenizer - :param lora_weights: name/path - :param gpu_id: which GPU (0..n_gpus-1) or allow all GPUs if relevant (-1) - :param n_jobs: number of cores to use (e.g. for llama CPU model) - :param reward_type: reward type model for sequence classification - :param local_files_only: use local files instead of from HF - :param resume_download: resume downloads from HF - :param use_auth_token: assumes user did on CLI `huggingface-cli login` to access private repo - :param trust_remote_code: trust code needed by model - :param offload_folder: offload folder - :param rope_scaling: scaling for rope-based models, e.g. "{'type':'dynamic', 'factor':4}" - :param max_seq_len: override for maximum sequence length for model - :param max_seq_len: if set, use as max_seq_len for model - :param compile_model: whether to compile torch model - :param llamacpp_dict: dict of llama.cpp and GPT4All model options - :param exllama_dict: dict of exllama options - :param gptq_dict: dict of AutoGPTQ options - :param attention_sinks: whether to use attention_sinks package - :param sink_dict: dict of attention sinks options - :param truncation_generation: whether to truncate generation in torch case to max_seq_len - :param hf_model_dict - :param verbose: - :return: - """ - print("Starting get_model: %s %s" % (base_model, inference_server), flush=True) - - triton_attn = False - long_sequence = True - config_kwargs = dict(use_auth_token=use_auth_token, - trust_remote_code=trust_remote_code, - offload_folder=offload_folder, - rope_scaling=rope_scaling, - triton_attn=triton_attn, - long_sequence=long_sequence, - revision=revision, - max_seq_len=max_seq_len, - verbose=verbose) - config, _, max_seq_len = get_config(base_model, **config_kwargs, raise_exception=False) - - if base_model in non_hf_types: - assert config is None, "Expected config None for %s" % base_model - - llama_type_from_config = 'llama' in str(config).lower() - llama_type_from_name = "llama" in base_model.lower() - llama_type = llama_type_from_config or llama_type_from_name - if "xgen" in base_model.lower() or 'llama2' in base_model.lower() or 'llama-2' in base_model.lower(): - llama_type = False - if llama_type: - if verbose: - print("Detected as llama type from" - " config (%s) or name (%s)" % (llama_type_from_config, llama_type_from_name), flush=True) - - model_name_exllama_if_no_config = '' if not llamacpp_dict else llamacpp_dict.get('model_name_exllama_if_no_config', - '') - model_loader, tokenizer_loader, conditional_type = ( - get_loaders(model_name=base_model, reward_type=reward_type, llama_type=llama_type, - load_gptq=load_gptq, load_awq=load_awq, load_exllama=load_exllama, - config=config, - rope_scaling=rope_scaling, max_seq_len=max_seq_len, - model_name_exllama_if_no_config=model_name_exllama_if_no_config, - exllama_dict=exllama_dict, gptq_dict=gptq_dict, - attention_sinks=attention_sinks, sink_dict=sink_dict, - truncation_generation=truncation_generation, - hf_model_dict=hf_model_dict)) - - tokenizer_kwargs = dict(local_files_only=local_files_only, - resume_download=resume_download, - token=use_auth_token, - trust_remote_code=trust_remote_code, - offload_folder=offload_folder, - revision=revision, - padding_side='left', - config=config, - ) - if not tokenizer_base_model: - tokenizer_base_model = base_model - - if load_exllama: - tokenizer = tokenizer_loader - elif config is not None and tokenizer_loader is not None and not isinstance(tokenizer_loader, str): - if load_exllama: - tokenizer = tokenizer_loader - else: - tokenizer = tokenizer_loader.from_pretrained(tokenizer_base_model, **tokenizer_kwargs) - # sets raw (no cushion) limit - # If using RoPE with scaling, then for non-exllama models (e.g. HF models), - # then config -> tokenizer will set model_max_length correctly - set_model_max_len(max_seq_len, tokenizer, verbose=False) - # if using fake tokenizer, not really accurate when lots of numbers, give a bit of buffer, else get: - # Generation Failed: Input validation error: `inputs` must have less than 2048 tokens. Given: 2233 - tokenizer.model_max_length = int(tokenizer.model_max_length - 50) - else: - tokenizer = None - - if isinstance(inference_server, str) and inference_server.startswith("http"): - inference_server, gr_client, hf_client = get_client_from_inference_server(inference_server, - base_model=base_model) - client = gr_client or hf_client - # Don't return None, None for model, tokenizer so triggers - if tokenizer is None: - # FIXME: Could use only tokenizer from llama etc. but hard to detatch from model, just use fake for now - if os.getenv("HARD_ASSERTS") and base_model not in non_hf_types: - raise RuntimeError("Unexpected tokenizer=None") - tokenizer = FakeTokenizer() - return client, tokenizer, 'http' - if isinstance(inference_server, str) and ( - inference_server.startswith('openai') or - inference_server.startswith('vllm') or - inference_server.startswith('replicate') or - inference_server.startswith('sagemaker') - ): - if inference_server.startswith('openai'): - assert os.getenv('OPENAI_API_KEY'), "Set environment for OPENAI_API_KEY" - # Don't return None, None for model, tokenizer so triggers - # include small token cushion - max_seq_len = model_token_mapping[base_model] - if inference_server.startswith('replicate'): - assert len(inference_server.split(':')) >= 3, "Expected replicate:model string, got %s" % inference_server - assert os.getenv('REPLICATE_API_TOKEN'), "Set environment for REPLICATE_API_TOKEN" - assert max_seq_len is not None, "Please pass --max_seq_len= for replicate models." - try: - import replicate as replicate_python - except ImportError: - raise ImportError( - "Could not import replicate python package. " - "Please install it with `pip install replicate`." - ) - if inference_server.startswith('sagemaker'): - assert len( - inference_server.split( - ':')) >= 3, "Expected sagemaker_chat::, got %s" % inference_server - assert os.getenv('AWS_ACCESS_KEY_ID'), "Set environment for AWS_ACCESS_KEY_ID" - assert os.getenv('AWS_SECRET_ACCESS_KEY'), "Set environment for AWS_SECRET_ACCESS_KEY" - # Don't return None, None for model, tokenizer so triggers - # include small token cushion - if inference_server.startswith('openai') or tokenizer is None: - # don't use fake (tiktoken) tokenizer for vLLM//replicate if know actual model with actual tokenizer - assert max_seq_len is not None, "Please pass --max_seq_len= for unknown or non-HF model %s" % base_model - tokenizer = FakeTokenizer(model_max_length=max_seq_len - 50, is_openai=True) - return inference_server, tokenizer, inference_server - assert not inference_server, "Malformed inference_server=%s" % inference_server - if base_model in non_hf_types: - from gpt4all_llm import get_model_tokenizer_gpt4all - model, tokenizer, device = get_model_tokenizer_gpt4all(base_model, n_jobs=n_jobs, - max_seq_len=max_seq_len, - llamacpp_dict=llamacpp_dict) - return model, tokenizer, device - if load_exllama: - return model_loader, tokenizer, 'cuda' - - # get local torch-HF model - return get_hf_model(load_8bit=load_8bit, - load_4bit=load_4bit, - low_bit_mode=low_bit_mode, - load_half=load_half, - load_gptq=load_gptq, - load_awq=load_awq, - use_safetensors=use_safetensors, - revision=revision, - use_gpu_id=use_gpu_id, - base_model=base_model, - tokenizer_base_model=tokenizer_base_model, - lora_weights=lora_weights, - gpu_id=gpu_id, - - reward_type=reward_type, - local_files_only=local_files_only, - resume_download=resume_download, - use_auth_token=use_auth_token, - trust_remote_code=trust_remote_code, - offload_folder=offload_folder, - rope_scaling=rope_scaling, - compile_model=compile_model, - - llama_type=llama_type, - config_kwargs=config_kwargs, - tokenizer_kwargs=tokenizer_kwargs, - gptq_dict=gptq_dict, - attention_sinks=attention_sinks, - sink_dict=sink_dict, - truncation_generation=truncation_generation, - hf_model_dict=hf_model_dict, - - verbose=verbose) - - -def get_hf_model(load_8bit: bool = False, - load_4bit: bool = False, - low_bit_mode: int = 1, - load_half: bool = True, - load_gptq: str = '', - load_awq: str = '', - use_safetensors: bool = False, - revision: str = None, - use_gpu_id: bool = True, - base_model: str = '', - tokenizer_base_model: str = '', - lora_weights: str = "", - gpu_id: int = 0, - - reward_type: bool = None, - local_files_only: bool = False, - resume_download: bool = True, - use_auth_token: Union[str, bool] = False, - trust_remote_code: bool = True, - offload_folder: str = None, - rope_scaling: dict = None, - compile_model: bool = True, - - llama_type: bool = False, - config_kwargs=None, - tokenizer_kwargs=None, - gptq_dict=None, - attention_sinks=None, - sink_dict=None, - truncation_generation=None, - hf_model_dict=None, - - verbose: bool = False, - ): - assert config_kwargs is not None - assert tokenizer_kwargs is not None - - load_exllama = False # Never should be in HF code for exllama - exllama_dict = {} - - if lora_weights is not None and lora_weights.strip(): - if verbose: - print("Get %s lora weights" % lora_weights, flush=True) - device = get_device() - - if 'gpt2' in base_model.lower(): - # RuntimeError: where expected condition to be a boolean tensor, but got a tensor with dtype Half - load_8bit = False - load_4bit = False - - assert base_model.strip(), ( - "Please choose a base model with --base_model (CLI) or load one from Models Tab (gradio)" - ) - - model_loader, tokenizer_loader, conditional_type = ( - get_loaders(model_name=base_model, reward_type=reward_type, llama_type=llama_type, - load_gptq=load_gptq, load_awq=load_awq, load_exllama=load_exllama, - exllama_dict=exllama_dict, gptq_dict=gptq_dict, - attention_sinks=attention_sinks, sink_dict=sink_dict, - truncation_generation=truncation_generation, - hf_model_dict=hf_model_dict)) - - config, _, max_seq_len = get_config(base_model, return_model=False, raise_exception=True, **config_kwargs) - - if tokenizer_loader is not None and not isinstance(tokenizer_loader, str): - if load_exllama: - tokenizer = tokenizer_loader - else: - tokenizer = tokenizer_loader.from_pretrained(tokenizer_base_model, - **tokenizer_kwargs) - else: - tokenizer = tokenizer_loader - - if isinstance(tokenizer, str): - # already a pipeline, tokenizer_loader is string for task - model = model_loader(tokenizer, - model=base_model, - device=0 if device == "cuda" else -1, - torch_dtype=torch.float16 if device == 'cuda' else torch.float32) - else: - assert device in ["cuda", "cpu", "mps"], "Unsupported device %s" % device - model_kwargs = dict(local_files_only=local_files_only, - torch_dtype=torch.float16 if device == 'cuda' else torch.float32, - resume_download=resume_download, - token=use_auth_token, - trust_remote_code=trust_remote_code, - offload_folder=offload_folder, - revision=revision, - # rope_scaling=rope_scaling, # only put into config - ) - if 'mbart-' not in base_model.lower() and 'mpt-' not in base_model.lower(): - if use_gpu_id and gpu_id is not None and gpu_id >= 0 and device == 'cuda': - device_map = {"": gpu_id} - else: - device_map = "auto" - model_kwargs.update(dict(load_in_8bit=load_8bit, - load_in_4bit=load_4bit, - device_map=device_map, - )) - if 'mpt-' in base_model.lower() and gpu_id is not None and gpu_id >= 0: - # MPT doesn't support spreading over GPUs - model_kwargs.update(dict(device_map={"": gpu_id} if device == 'cuda' else "cpu")) - - if 'OpenAssistant/reward-model'.lower() in base_model.lower(): - # FIXME: could put on other GPUs - model_kwargs['device_map'] = {"": 0} if device == 'cuda' else {"": 'cpu'} - model_kwargs.pop('torch_dtype', None) - pop_unused_model_kwargs(model_kwargs) - - n_gpus = torch.cuda.device_count() if torch.cuda.is_available() else 0 - n_gpus, gpu_ids = cuda_vis_check(n_gpus) - if low_bit_mode == 1 and n_gpus != 0: - from transformers import BitsAndBytesConfig - model_kwargs['quantization_config'] = BitsAndBytesConfig(bnb_4bit_compute_dtype=torch.bfloat16, - load_in_4bit=load_4bit, - load_in_8bit=load_8bit, - ) - elif low_bit_mode == 2 and n_gpus != 0: - from transformers import BitsAndBytesConfig - model_kwargs['quantization_config'] = BitsAndBytesConfig(bnb_4bit_quant_type="nf4", - load_in_4bit=load_4bit, - load_in_8bit=load_8bit, - ) - elif low_bit_mode == 3 and n_gpus != 0: - from transformers import BitsAndBytesConfig - model_kwargs['quantization_config'] = BitsAndBytesConfig(bnb_4bit_use_double_quant=True, - load_in_4bit=load_4bit, - load_in_8bit=load_8bit, - ) - elif low_bit_mode == 4 and n_gpus != 0: - from transformers import BitsAndBytesConfig - model_kwargs['quantization_config'] = BitsAndBytesConfig(bnb_4bit_use_double_quant=True, - bnb_4bit_quant_type="nf4", - load_in_4bit=load_4bit, - load_in_8bit=load_8bit, - ) - - if not lora_weights: - # torch.device context uses twice memory for AutoGPTQ - context = NullContext if (load_gptq or load_awq) else torch.device - with context(device): - - if use_gpu_id: - config, model, max_seq_len = get_config(base_model, - return_model=True, raise_exception=True, **config_kwargs) - model = get_non_lora_model(base_model, model_loader, load_half, - load_gptq, load_awq, - load_exllama, - use_safetensors, - revision, - model_kwargs, reward_type, - config, model, - gpu_id=gpu_id, - ) - else: - model_kwargs['use_safetensors'] = use_safetensors - model_kwargs['revision'] = revision - config, _, max_seq_len = get_config(base_model, **config_kwargs) - if load_half and not (load_8bit or load_4bit or load_gptq or load_awq): - model = model_loader( - base_model, - config=config, - **model_kwargs) - if not getattr(model, "is_quantized", False): - model = model.half() - else: - if load_gptq: - model_kwargs.pop('torch_dtype', None) - model_kwargs.pop('device_map') - model = model_loader( - model_name_or_path=base_model, - model_basename=load_gptq, - **model_kwargs, - ) - elif load_awq: - allowed_dict = dict(max_new_tokens=None, - trust_remote_code=True, fuse_layers=True, - batch_size=1, safetensors=False, - max_memory=None, offload_folder=None) - for k in model_kwargs.copy(): - if k not in allowed_dict: - model_kwargs.pop(k) - if load_awq.endswith('.pt'): - args = tuple([base_model, load_awq]) - else: - args = tuple([base_model]) - model = model_loader( - *args, - safetensors=use_safetensors, - **model_kwargs, - ) - else: - model = model_loader( - base_model, - config=config, - **model_kwargs) - elif load_8bit or load_4bit: - config, _, max_seq_len = get_config(base_model, **config_kwargs) - model = model_loader( - base_model, - config=config, - **model_kwargs - ) - from peft import PeftModel # loads cuda, so avoid in global scope - model = PeftModel.from_pretrained( - model, - lora_weights, - torch_dtype=torch.float16 if device == 'cuda' else torch.float32, - local_files_only=local_files_only, - resume_download=resume_download, - token=use_auth_token, - trust_remote_code=trust_remote_code, - offload_folder=offload_folder, - rope_scaling=rope_scaling, - revision=revision, - device_map={"": 0} if device == 'cuda' else {"": 'cpu'}, # seems to be required - ) - else: - with torch.device(device): - config, _, max_seq_len = get_config(base_model, raise_exception=True, **config_kwargs) - model = model_loader( - base_model, - config=config, - **model_kwargs - ) - from peft import PeftModel # loads cuda, so avoid in global scope - model = PeftModel.from_pretrained( - model, - lora_weights, - torch_dtype=torch.float16 if device == 'cuda' else torch.float32, - local_files_only=local_files_only, - resume_download=resume_download, - token=use_auth_token, - trust_remote_code=trust_remote_code, - offload_folder=offload_folder, - rope_scaling=rope_scaling, - device_map="auto", - ) - if load_half and not (load_gptq or load_awq): - if not getattr(model, "is_quantized", False): - model = model.half() - - # unwind broken decapoda-research config - if llama_type: - model.config.pad_token_id = tokenizer.pad_token_id = 0 # unk - model.config.bos_token_id = 1 - model.config.eos_token_id = 2 - if 'gpt2' in base_model.lower(): - # add special tokens that otherwise all share the same id - tokenizer.add_special_tokens({'bos_token': '', - 'eos_token': '', - 'pad_token': ''}) - - if not isinstance(tokenizer, str): - model.eval() - if torch.__version__ >= "2" and sys.platform != "win32" and compile_model: - model = torch.compile(model) - - set_model_max_len(max_seq_len, tokenizer, verbose=False, reward_type=reward_type) - - # tell if conditional type - model.conditional_type = conditional_type - tokenizer.conditional_type = conditional_type - - return model, tokenizer, device - - -def set_model_max_len(max_seq_len, tokenizer, verbose=False, reward_type=False): - if reward_type: - # limit deberta, else uses too much memory and not worth response score - tokenizer.model_max_length = 512 - return - - tokenizer.model_max_length = int(max_seq_len) - if verbose: - print("model_max_length=%s" % tokenizer.model_max_length, flush=True) - # for bug in HF transformers - if tokenizer.model_max_length > 100000000: - tokenizer.model_max_length = 2048 - - -def pop_unused_model_kwargs(model_kwargs): - """ - in-place pop unused kwargs that are not dependency-upgrade friendly - no point passing in False, is default, and helps avoid needing to update requirements for new deps - :param model_kwargs: - :return: - """ - check_list = ['load_in_8bit', 'load_in_4bit'] - for k in check_list: - if k in model_kwargs and not model_kwargs[k]: - model_kwargs.pop(k) - - -def get_score_model(score_model: str = None, - load_8bit: bool = False, - load_4bit: bool = False, - low_bit_mode=1, - load_half: bool = True, - load_gptq: str = '', - load_awq: str = '', - load_exllama: bool = False, - use_gpu_id: bool = True, - base_model: str = '', - inference_server: str = '', - tokenizer_base_model: str = '', - lora_weights: str = "", - gpu_id: int = 0, - n_jobs=None, - - reward_type: bool = None, - local_files_only: bool = False, - resume_download: bool = True, - use_auth_token: Union[str, bool] = False, - trust_remote_code: bool = True, - offload_folder: str = None, - rope_scaling: dict = None, - compile_model: bool = True, - llamacpp_dict: typing.Dict = None, - exllama_dict: typing.Dict = None, - gptq_dict: typing.Dict = None, - attention_sinks: bool = False, - sink_dict: typing.Dict = None, - truncation_generation: bool = False, - hf_model_dict: typing.Dict = None, - - verbose: bool = False, - ): - if score_model is not None and score_model.strip(): - load_8bit = False - load_4bit = False - low_bit_mode = 1 - load_half = False - load_gptq = '' - load_awq = '' - load_exllama = False - use_safetensors = False - revision = None - base_model = score_model.strip() - tokenizer_base_model = '' - lora_weights = '' - inference_server = '' - llama_type = False - max_seq_len = None - rope_scaling = {} - compile_model = False - llamacpp_dict = {} - exllama_dict = {} - gptq_dict = {} - attention_sinks = False - sink_dict = {} - truncation_generation = False - hf_model_dict = {} - smodel, stokenizer, sdevice = get_model(reward_type=True, - **get_kwargs(get_model, exclude_names=['reward_type'], **locals())) - else: - smodel, stokenizer, sdevice = None, None, None - return smodel, stokenizer, sdevice - - -def evaluate_fake(*args, **kwargs): - yield dict(response=invalid_key_msg, sources='', save_dict=dict(), llm_answers={}) - return - - -def evaluate( - model_state, - my_db_state, - selection_docs_state, - requests_state, - # START NOTE: Examples must have same order of parameters - instruction, - iinput, - context, - stream_output, - prompt_type, - prompt_dict, - temperature, - top_p, - top_k, - penalty_alpha, - num_beams, - max_new_tokens, - min_new_tokens, - early_stopping, - max_time, - repetition_penalty, - num_return_sequences, - do_sample, - chat, - instruction_nochat, - iinput_nochat, - langchain_mode, - add_chat_history_to_context, - langchain_action, - langchain_agents, - top_k_docs, - chunk, - chunk_size, - document_subset, - document_choice, - pre_prompt_query, - prompt_query, - pre_prompt_summary, - prompt_summary, - system_prompt, - - image_loaders, - pdf_loaders, - url_loaders, - jq_schema, - visible_models, - h2ogpt_key, - add_search_to_context, - chat_conversation, - text_context_list, - docs_ordering_type, - min_max_new_tokens, - max_input_tokens, - docs_token_handling, - docs_joiner, - hyde_level, - hyde_template, - - # END NOTE: Examples must have same order of parameters - captions_model=None, - caption_loader=None, - doctr_loader=None, - pix2struct_loader=None, - async_output=None, - num_async=None, - src_lang=None, - tgt_lang=None, - debug=False, - concurrency_count=None, - save_dir=None, - sanitize_bot_response=False, - model_state0=None, - memory_restriction_level=None, - max_max_new_tokens=None, - is_public=None, - max_max_time=None, - raise_generate_gpu_exceptions=None, - lora_weights=None, - use_llm_if_no_docs=True, - load_db_if_exists=True, - dbs=None, - detect_user_path_changes_every_query=None, - use_openai_embedding=None, - use_openai_model=None, - hf_embedding_model=None, - migrate_embedding_model=None, - auto_migrate_db=None, - cut_distance=None, - db_type=None, - n_jobs=None, - first_para=None, - text_limit=None, - show_accordions=None, - top_k_docs_max_show=None, - show_link_in_sources=None, - verbose=False, - gradio=True, - cli=False, - use_cache=None, - auto_reduce_chunks=None, - max_chunks=None, - headsize=None, - model_lock=None, - force_langchain_evaluate=None, - model_state_none=None, - llamacpp_dict=None, - exllama_dict=None, - gptq_dict=None, - attention_sinks=None, - sink_dict=None, - truncation_generation=None, - hf_model_dict=None, - - load_exllama=None, - answer_with_sources=None, - append_sources_to_answer=None, - image_loaders_options0=None, - pdf_loaders_options0=None, - url_loaders_options0=None, - jq_schema0=None, - keep_sources_in_context=None, -): - # ensure passed these - assert concurrency_count is not None - assert memory_restriction_level is not None - assert raise_generate_gpu_exceptions is not None - assert use_openai_embedding is not None - assert use_openai_model is not None - assert hf_embedding_model is not None - assert migrate_embedding_model is not None - assert auto_migrate_db is not None - assert db_type is not None - assert top_k_docs is not None and isinstance(top_k_docs, int) - assert chunk is not None and isinstance(chunk, bool) - assert chunk_size is not None and isinstance(chunk_size, int) - assert n_jobs is not None - assert first_para is not None - assert isinstance(add_chat_history_to_context, bool) - assert isinstance(add_search_to_context, bool) - assert load_exllama is not None - # for lazy client (even chat client) - if image_loaders is None: - image_loaders = image_loaders_options0 - if pdf_loaders is None: - pdf_loaders = pdf_loaders_options0 - if url_loaders is None: - url_loaders = url_loaders_options0 - if jq_schema is None: - jq_schema = jq_schema0 - if isinstance(langchain_agents, str): - if langchain_agents.strip().startswith('['): - # already list, but as string - langchain_agents = str_to_list(langchain_agents) - else: - # just 1 item and make list - langchain_agents = [langchain_agents] - chat_conversation = str_to_list(chat_conversation) - text_context_list = str_to_list(text_context_list) - - langchain_modes = selection_docs_state['langchain_modes'] - langchain_mode_paths = selection_docs_state['langchain_mode_paths'] - langchain_mode_types = selection_docs_state['langchain_mode_types'] - - if debug: - locals_dict = locals().copy() - locals_dict.pop('model_state', None) - locals_dict.pop('model_state0', None) - locals_dict.pop('model_states', None) - print(locals_dict) - - no_model_msg = "Please choose a base model with --base_model (CLI) or load in Models Tab (gradio).\n" \ - "Then start New Conversation" - - if model_state is None: - model_state = model_state_none.copy() - if model_state0 is None: - # e.g. for no gradio case, set dummy value, else should be set - model_state0 = model_state_none.copy() - - # model_state['model] is only 'model' if should use model_state0 - # model could also be None - have_model_lock = model_lock is not None - have_fresh_model = model_state['model'] not in [None, 'model', no_model_str] - # for gradio UI control, expect model_state and model_state0 to match, so if have_model_lock=True, then should have_fresh_model=True - # but gradio API control will only use nochat api etc. and won't use fresh model, so can't assert in general - # if have_model_lock: - # assert have_fresh_model, "Expected model_state and model_state0 to match if have_model_lock" - have_cli_model = model_state0['model'] not in [None, 'model', no_model_str] - - if have_fresh_model: - # USE FRESH MODEL - if not have_model_lock: - # model_state0 is just one of model_state if model_lock, so don't nuke - # try to free-up original model (i.e. list was passed as reference) - if model_state0['model'] and hasattr(model_state0['model'], 'cpu'): - model_state0['model'].cpu() - model_state0['model'] = None - # try to free-up original tokenizer (i.e. list was passed as reference) - if model_state0['tokenizer']: - model_state0['tokenizer'] = None - clear_torch_cache() - chosen_model_state = model_state - elif have_cli_model: - # USE MODEL SETUP AT CLI - assert isinstance(model_state['model'], (type(None), str)) # expect no fresh model - chosen_model_state = model_state0 - else: - raise AssertionError(no_model_msg) - # get variables - model = chosen_model_state['model'] - tokenizer = chosen_model_state['tokenizer'] - device = chosen_model_state['device'] - base_model = chosen_model_state['base_model'] - tokenizer_base_model = chosen_model_state['tokenizer_base_model'] - lora_weights = chosen_model_state['lora_weights'] - inference_server = chosen_model_state['inference_server'] - visible_models = chosen_model_state['visible_models'] - # use overall key if have, so key for this gradio and any inner gradio - if chosen_model_state['h2ogpt_key'] is not None: - h2ogpt_key = chosen_model_state['h2ogpt_key'] - # prefer use input from API over model state - prompt_type = prompt_type or chosen_model_state['prompt_type'] - prompt_dict = prompt_dict or chosen_model_state['prompt_dict'] - - if base_model is None: - raise AssertionError(no_model_msg) - - assert base_model.strip(), no_model_msg - assert model, "Model is missing" - assert tokenizer, "Tokenizer is missing" - - # choose chat or non-chat mode - if not chat: - instruction = instruction_nochat - iinput = iinput_nochat - - # avoid instruction in chat_conversation itself, since always used as additional context to prompt in what follows - if isinstance(chat_conversation, list) and \ - len(chat_conversation) > 0 and \ - len(chat_conversation[-1]) == 2 and \ - chat_conversation[-1][0] == instruction and \ - chat_conversation[-1][1] in [None, '']: - chat_conversation = chat_conversation[:-1] - if not add_chat_history_to_context: - # make it easy to ignore without needing add_chat_history_to_context - # some langchain or unit test may need to then handle more general case - chat_conversation = [] - - # in some cases, like lean nochat API, don't want to force sending prompt_type, allow default choice - model_lower = base_model.lower() - if not prompt_type and model_lower in inv_prompt_type_to_model_lower and prompt_type != 'custom': - prompt_type = inv_prompt_type_to_model_lower[model_lower] - if verbose: - print("Auto-selecting prompt_type=%s for %s" % (prompt_type, model_lower), flush=True) - assert prompt_type is not None, "prompt_type was None" - - # Control generation hyperparameters - # adjust for bad inputs, e.g. in case also come from API that doesn't get constrained by gradio sliders - # below is for TGI server, not required for HF transformers - # limits are chosen similar to gradio_runner.py sliders/numbers - top_p = min(max(1e-3, top_p), 1.0 - 1e-3) - top_k = min(max(1, int(top_k)), 100) - penalty_alpha = min(2.0, max(0.0, penalty_alpha)) - temperature = min(max(0.01, temperature), 2.0) - # FIXME: https://github.com/h2oai/h2ogpt/issues/106 - num_beams = 1 if stream_output else num_beams # See max_beams in gradio_runner - if model_lower == 'distilgpt2': - # always truncate for certain models that totally fail otherwise - truncation_generation = True - max_max_new_tokens = get_max_max_new_tokens(chosen_model_state, - memory_restriction_level=memory_restriction_level, - max_new_tokens=max_new_tokens, - attention_sinks=attention_sinks, - max_max_new_tokens=max_max_new_tokens, - truncation_generation=truncation_generation) - if min_max_new_tokens is None: - # default for nochat api - min_max_new_tokens = 256 - if max_input_tokens is None: - max_input_tokens = -1 - if docs_ordering_type is None: - docs_ordering_type = docs_ordering_types_default - if docs_token_handling is None: - docs_token_handling = docs_token_handling_default - if docs_joiner is None: - docs_joiner = docs_joiner_default - model_max_length = get_model_max_length(chosen_model_state) - max_new_tokens = min(max(1, int(max_new_tokens)), max_max_new_tokens) - min_new_tokens = min(max(0, int(min_new_tokens)), max_new_tokens) - max_time = min(max(0, max_time), max_max_time) - repetition_penalty = min(max(0.01, repetition_penalty), 3.0) - num_return_sequences = 1 if chat else min(max(1, int(num_return_sequences)), 10) - min_top_k_docs, max_top_k_docs, label_top_k_docs = get_minmax_top_k_docs(is_public) - # limit total tokens processed, e.g. for summarization, if public instance - if is_public: - total_tokens_for_docs = min(2 * model_max_length, 16384) - else: - total_tokens_for_docs = None - top_k_docs = min(max(min_top_k_docs, int(top_k_docs)), max_top_k_docs) - chunk_size = min(max(128, int(chunk_size)), 2048) - if not context: - context = '' - - # NOTE!!!!!!!!!! Choice of developer. But only possible to force stream if num_beams=1 - # stream if can, so can control task iteration and time of iteration - # not required, but helpful for max_time control etc. - stream_output0 = stream_output - stream_output = gradio and num_beams == 1 - - # get prompter - prompter = Prompter(prompt_type, prompt_dict, debug=debug, chat=chat, stream_output=stream_output, - system_prompt=system_prompt) - - # THIRD PLACE where LangChain referenced, but imports only occur if enabled and have db to use - assert langchain_mode in langchain_modes, "Invalid langchain_mode %s not in %s" % (langchain_mode, langchain_modes) - assert langchain_action in langchain_actions, "Invalid langchain_action %s not in %s" % ( - langchain_action, langchain_actions) - assert len( - set(langchain_agents).difference(langchain_agents_list)) == 0, "Invalid langchain_agents %s" % langchain_agents - - # get db, but also fill db state so return already has my_db_state and dbs filled so faster next query - if langchain_mode != LangChainMode.DISABLED.value: - from src.gpt_langchain import get_any_db - db = get_any_db(my_db_state, langchain_mode, langchain_mode_paths, langchain_mode_types, - dbs=dbs, - load_db_if_exists=load_db_if_exists, - db_type=db_type, - use_openai_embedding=use_openai_embedding, - hf_embedding_model=hf_embedding_model, - migrate_embedding_model=migrate_embedding_model, - auto_migrate_db=auto_migrate_db, - for_sources_list=True, - verbose=verbose, - n_jobs=n_jobs, - ) - else: - db = None - - t_generate = time.time() - langchain_only_model = base_model in non_hf_types or \ - load_exllama or \ - inference_server.startswith('replicate') or \ - inference_server.startswith('sagemaker') or \ - inference_server.startswith('openai_azure_chat') or \ - inference_server.startswith('openai_azure') - do_langchain_path = langchain_mode not in [False, 'Disabled', 'LLM'] or \ - langchain_only_model or \ - force_langchain_evaluate or \ - len(text_context_list) > 0 - - if len(langchain_agents) > 0: - do_langchain_path = True - if add_search_to_context: - # easier to manage prompt etc. by doing full langchain path - do_langchain_path = True - - if do_langchain_path: - text = '' - sources = '' - response = '' - # use smaller cut_distance for wiki_full since so many matches could be obtained, and often irrelevant unless close - from gpt_langchain import run_qa_db - gen_hyper_langchain = dict(do_sample=do_sample, - temperature=temperature, - repetition_penalty=repetition_penalty, - top_p=top_p, - top_k=top_k, - penalty_alpha=penalty_alpha, - num_beams=num_beams, - min_new_tokens=min_new_tokens, - max_new_tokens=max_new_tokens, - early_stopping=early_stopping, - max_time=max_time, - num_return_sequences=num_return_sequences, - ) - loaders_dict, captions_model = gr_to_lg(image_loaders, - pdf_loaders, - url_loaders, - captions_model=captions_model, - ) - loaders_dict.update(dict(captions_model=captions_model, - caption_loader=caption_loader, - doctr_loader=doctr_loader, - pix2struct_loader=pix2struct_loader, - jq_schema=jq_schema, - )) - data_point = dict(context=context, instruction=instruction, input=iinput) - # no longer stuff chat history directly into context this early - prompt_basic = prompter.generate_prompt(data_point, context_from_history=False) - prompt = prompt_basic - num_prompt_tokens = 0 - llm_answers = {} - for r in run_qa_db( - inference_server=inference_server, - model_name=base_model, model=model, tokenizer=tokenizer, - langchain_only_model=langchain_only_model, - async_output=async_output, - num_async=num_async, - prompter=prompter, - use_llm_if_no_docs=use_llm_if_no_docs, - load_db_if_exists=load_db_if_exists, - db=db, - langchain_mode_paths=langchain_mode_paths, - langchain_mode_types=langchain_mode_types, - detect_user_path_changes_every_query=detect_user_path_changes_every_query, - cut_distance=1.1 if langchain_mode in ['wiki_full'] else cut_distance, - answer_with_sources=answer_with_sources, - append_sources_to_answer=append_sources_to_answer, - add_chat_history_to_context=add_chat_history_to_context, - add_search_to_context=add_search_to_context, - keep_sources_in_context=keep_sources_in_context, - memory_restriction_level=memory_restriction_level, - system_prompt=system_prompt, - use_openai_embedding=use_openai_embedding, - use_openai_model=use_openai_model, - hf_embedding_model=hf_embedding_model, - migrate_embedding_model=migrate_embedding_model, - auto_migrate_db=auto_migrate_db, - first_para=first_para, - text_limit=text_limit, - show_accordions=show_accordions, - top_k_docs_max_show=top_k_docs_max_show, - show_link_in_sources=show_link_in_sources, - - # evaluate args items - query=instruction, - iinput=iinput, - context=context, - stream_output0=stream_output0, - stream_output=stream_output, - chunk=chunk, - chunk_size=chunk_size, - - **loaders_dict, - - langchain_mode=langchain_mode, - langchain_action=langchain_action, - langchain_agents=langchain_agents, - document_subset=document_subset, - document_choice=document_choice, - top_k_docs=top_k_docs, - prompt_type=prompt_type, - prompt_dict=prompt_dict, - pre_prompt_query=pre_prompt_query, - prompt_query=prompt_query, - pre_prompt_summary=pre_prompt_summary, - prompt_summary=prompt_summary, - text_context_list=text_context_list, - chat_conversation=chat_conversation, - visible_models=visible_models, - h2ogpt_key=h2ogpt_key, - docs_ordering_type=docs_ordering_type, - min_max_new_tokens=min_max_new_tokens, - max_input_tokens=max_input_tokens, - docs_token_handling=docs_token_handling, - docs_joiner=docs_joiner, - hyde_level=hyde_level, - hyde_template=hyde_template, - - **gen_hyper_langchain, - - db_type=db_type, - n_jobs=n_jobs, - verbose=verbose, - cli=cli, - sanitize_bot_response=sanitize_bot_response, - - lora_weights=lora_weights, - llamacpp_dict=llamacpp_dict, - exllama_dict=exllama_dict, - gptq_dict=gptq_dict, - attention_sinks=attention_sinks, - sink_dict=sink_dict, - truncation_generation=truncation_generation, - hf_model_dict=hf_model_dict, - - auto_reduce_chunks=auto_reduce_chunks, - max_chunks=max_chunks, - total_tokens_for_docs=total_tokens_for_docs, - headsize=headsize, - ): - # doesn't accumulate, new answer every yield, so only save that full answer - response = r['response'] - sources = r['sources'] - prompt = r['prompt'] - num_prompt_tokens = r['num_prompt_tokens'] - llm_answers = r['llm_answers'] - yield dict(response=response, sources=sources, save_dict=dict(), llm_answers=llm_answers) - if save_dir: - # estimate using tiktoken - extra_dict = gen_hyper_langchain.copy() - extra_dict.update(prompt_type=prompt_type, - inference_server=inference_server, - langchain_mode=langchain_mode, - langchain_action=langchain_action, - langchain_agents=langchain_agents, - document_subset=document_subset, - document_choice=document_choice, - chat_conversation=chat_conversation, - add_search_to_context=add_search_to_context, - num_prompt_tokens=num_prompt_tokens, - instruction=instruction, - iinput=iinput, - context=context, - t_generate=time.time() - t_generate, - ntokens=None, - tokens_persecond=None, - ) - save_dict = dict(prompt=prompt, - output=response, base_model=base_model, save_dir=save_dir, - where_from='run_qa_db', - extra_dict=extra_dict) - yield dict(response=response, sources=sources, save_dict=save_dict, llm_answers=llm_answers) - if verbose: - print( - 'Post-Generate Langchain: %s decoded_output: %s' % - (str(datetime.now()), len(response) if response else -1), - flush=True) - if response or sources or langchain_only_model: - # if got no response (e.g. not showing sources and got no sources, - # so nothing to give to LLM), then slip through and ask LLM - # Or if llama/gptj, then just return since they had no response and can't go down below code path - # don't clear torch cache here, delays multi-generation, and bot(), all_bot(), and evaluate_nochat() do it - return - - # NOT LANGCHAIN PATH, raw LLM - # restrict instruction + , typically what has large input - from gradio_utils.grclient import GradioClient - gradio_server = inference_server.startswith('http') and isinstance(model, GradioClient) - - prompt, \ - instruction, iinput, context, \ - num_prompt_tokens, max_new_tokens, num_prompt_tokens0, num_prompt_tokens_actual, \ - chat_index, external_handle_chat_conversation, \ - top_k_docs_trial, one_doc_size, truncation_generation = \ - get_limited_prompt(instruction, - iinput, - tokenizer, - prompter=prompter, - inference_server=inference_server, - # prompt_type=prompt_type, - # prompt_dict=prompt_dict, - # chat=chat, - max_new_tokens=max_new_tokens, - # system_prompt=system_prompt, - context=context, - chat_conversation=chat_conversation, - keep_sources_in_context=keep_sources_in_context, - model_max_length=model_max_length, - memory_restriction_level=memory_restriction_level, - langchain_mode=langchain_mode, - add_chat_history_to_context=add_chat_history_to_context, - min_max_new_tokens=min_max_new_tokens, - max_input_tokens=max_input_tokens, - truncation_generation=truncation_generation, - gradio_server=gradio_server, - ) - - if inference_server.startswith('vllm') or \ - inference_server.startswith('openai') or \ - inference_server.startswith('http'): - if inference_server.startswith('vllm') or inference_server.startswith('openai'): - assert not inference_server.startswith('openai_azure_chat'), "Not fo Azure, use langchain path" - assert not inference_server.startswith('openai_azure'), "Not for Azure, use langchain path" - openai, inf_type, deployment_name, base_url, api_version, api_key = set_openai(inference_server) - where_from = inf_type - - terminate_response = prompter.terminate_response or [] - stop_sequences = list(set(terminate_response + [prompter.PreResponse])) - stop_sequences = [x for x in stop_sequences if x] - # OpenAI will complain if ask for too many new tokens, takes it as min in some sense, wrongly so. - max_new_tokens_openai = min(max_new_tokens, model_max_length - num_prompt_tokens) - gen_server_kwargs = dict(temperature=temperature if do_sample else 0, - max_tokens=max_new_tokens_openai, - top_p=top_p if do_sample else 1, - frequency_penalty=0, - n=num_return_sequences, - presence_penalty=1.07 - repetition_penalty + 0.6, # so good default - ) - if inf_type == 'vllm' or inference_server == 'openai': - responses = openai.Completion.create( - model=base_model, - prompt=prompt, - **gen_server_kwargs, - stop=stop_sequences, - stream=stream_output, - ) - text = '' - sources = '' - response = '' - if not stream_output: - text = responses['choices'][0]['text'] - response = prompter.get_response(prompt + text, prompt=prompt, - sanitize_bot_response=sanitize_bot_response) - yield dict(response=response, sources=sources, save_dict=dict(), llm_answers={}) - else: - collected_events = [] - tgen0 = time.time() - for event in responses: - collected_events.append(event) # save the event response - event_text = event['choices'][0]['text'] # extract the text - text += event_text # append the text - response = prompter.get_response(prompt + text, prompt=prompt, - sanitize_bot_response=sanitize_bot_response) - yield dict(response=response, sources=sources, save_dict=dict(), llm_answers={}) - if time.time() - tgen0 > max_time: - if verbose: - print("Took too long for OpenAI or VLLM: %s" % (time.time() - tgen0), flush=True) - break - elif inf_type == 'vllm_chat' or inference_server == 'openai_chat': - if system_prompt in [None, 'None', 'auto']: - openai_system_prompt = "You are a helpful assistant." - else: - openai_system_prompt = system_prompt - messages0 = [] - if openai_system_prompt: - messages0.append({"role": "system", "content": openai_system_prompt}) - if chat_conversation and add_chat_history_to_context: - assert external_handle_chat_conversation, "Should be handling only externally" - # chat_index handles token counting issues - for message1 in chat_conversation[chat_index:]: - if len(message1) == 2: - messages0.append( - {'role': 'user', 'content': message1[0] if message1[0] is not None else ''}) - messages0.append( - {'role': 'assistant', 'content': message1[1] if message1[1] is not None else ''}) - messages0.append({'role': 'user', 'content': prompt if prompt is not None else ''}) - responses = openai.ChatCompletion.create( - model=base_model, - messages=messages0, - stream=stream_output, - **gen_server_kwargs, - ) - text = "" - sources = '' - response = "" - if not stream_output: - text = responses["choices"][0]["message"]["content"] - response = prompter.get_response(prompt + text, prompt=prompt, - sanitize_bot_response=sanitize_bot_response) - yield dict(response=response, sources=sources, save_dict=dict(), llm_answers={}) - else: - tgen0 = time.time() - for chunk in responses: - delta = chunk["choices"][0]["delta"] - if 'content' in delta: - text += delta['content'] - response = prompter.get_response(prompt + text, prompt=prompt, - sanitize_bot_response=sanitize_bot_response) - yield dict(response=response, sources=sources, save_dict=dict(), llm_answers={}) - if time.time() - tgen0 > max_time: - if verbose: - print("Took too long for OpenAI or VLLM Chat: %s" % (time.time() - tgen0), flush=True) - break - else: - raise RuntimeError("No such OpenAI mode: %s" % inference_server) - elif inference_server.startswith('http'): - inference_server, headers = get_hf_server(inference_server) - from text_generation import Client as HFClient - if isinstance(model, GradioClient): - gr_client = model.clone() - hf_client = None - elif isinstance(model, HFClient): - gr_client = None - hf_client = model - else: - inference_server, gr_client, hf_client = get_client_from_inference_server(inference_server, - base_model=base_model) - - # quick sanity check to avoid long timeouts, just see if can reach server - requests.get(inference_server, timeout=int(os.getenv('REQUEST_TIMEOUT_FAST', '10'))) - - if gr_client is not None: - # Note: h2oGPT gradio server could handle input token size issues for prompt, - # but best to handle here so send less data to server - - chat_client = False - where_from = "gr_client" - client_langchain_mode = 'Disabled' - client_add_chat_history_to_context = True - client_add_search_to_context = False - client_langchain_action = LangChainAction.QUERY.value - client_langchain_agents = [] - gen_server_kwargs = dict(temperature=temperature, - top_p=top_p, - top_k=top_k, - penalty_alpha=penalty_alpha, - num_beams=num_beams, - max_new_tokens=max_new_tokens, - min_new_tokens=min_new_tokens, - early_stopping=early_stopping, - max_time=max_time, - repetition_penalty=repetition_penalty, - num_return_sequences=num_return_sequences, - do_sample=do_sample, - chat=chat_client, - ) - # account for gradio into gradio that handles prompting, avoid duplicating prompter prompt injection - if prompt_type in [None, '', PromptType.plain.name, PromptType.plain.value, - str(PromptType.plain.value)]: - # if our prompt is plain, assume either correct or gradio server knows different prompt type, - # so pass empty prompt_Type - gr_prompt_type = '' - gr_prompt_dict = '' - gr_prompt = prompt # already prepared prompt - gr_context = '' - gr_iinput = '' - else: - # if already have prompt_type that is not plain, None, or '', then already applied some prompting - # But assume server can handle prompting, and need to avoid double-up. - # Also assume server can do better job of using stopping.py to stop early, so avoid local prompting, let server handle - # So avoid "prompt" and let gradio server reconstruct from prompt_type we passed - # Note it's ok that prompter.get_response() has prompt+text, prompt=prompt passed, - # because just means extra processing and removal of prompt, but that has no human-bot prompting doesn't matter - # since those won't appear - gr_context = context - gr_prompt = instruction - gr_iinput = iinput - gr_prompt_type = prompt_type - gr_prompt_dict = prompt_dict - client_kwargs = dict(instruction=gr_prompt if chat_client else '', # only for chat=True - iinput=gr_iinput, # only for chat=True - context=gr_context, - # streaming output is supported, loops over and outputs each generation in streaming mode - # but leave stream_output=False for simple input/output mode - stream_output=stream_output, - - **gen_server_kwargs, - - prompt_type=gr_prompt_type, - prompt_dict=gr_prompt_dict, - - instruction_nochat=gr_prompt if not chat_client else '', - iinput_nochat=gr_iinput, # only for chat=False - langchain_mode=client_langchain_mode, - add_chat_history_to_context=client_add_chat_history_to_context, - langchain_action=client_langchain_action, - langchain_agents=client_langchain_agents, - top_k_docs=top_k_docs, - chunk=chunk, - chunk_size=chunk_size, - document_subset=DocumentSubset.Relevant.name, - document_choice=[DocumentChoice.ALL.value], - pre_prompt_query=pre_prompt_query, - prompt_query=prompt_query, - pre_prompt_summary=pre_prompt_summary, - prompt_summary=prompt_summary, - system_prompt=system_prompt, - image_loaders=image_loaders, - pdf_loaders=pdf_loaders, - url_loaders=url_loaders, - jq_schema=jq_schema, - visible_models=visible_models, - h2ogpt_key=h2ogpt_key, - add_search_to_context=client_add_search_to_context, - docs_ordering_type=docs_ordering_type, - min_max_new_tokens=min_max_new_tokens, - max_input_tokens=max_input_tokens, - docs_token_handling=docs_token_handling, - docs_joiner=docs_joiner, - hyde_level=hyde_level, - hyde_template=hyde_template, - ) - api_name = '/submit_nochat_api' # NOTE: like submit_nochat but stable API for string dict passing - response = '' - text = '' - sources = '' - strex = '' - if not stream_output: - res = gr_client.predict(str(dict(client_kwargs)), api_name=api_name) - res_dict = ast.literal_eval(res) - text = res_dict['response'] - sources = res_dict['sources'] - response = prompter.get_response(prompt + text, prompt=prompt, - sanitize_bot_response=sanitize_bot_response) - yield dict(response=response, sources=sources, save_dict=dict(), llm_answers={}) - else: - from gradio_utils.grclient import check_job - job = gr_client.submit(str(dict(client_kwargs)), api_name=api_name) - res_dict = dict(response=text, sources=sources, save_dict=dict(), llm_answers={}) - text0 = '' - tgen0 = time.time() - while not job.done(): - if job.communicator.job.latest_status.code.name == 'FINISHED': - break - e = check_job(job, timeout=0, raise_exception=False) - if e is not None: - break - outputs_list = job.communicator.job.outputs - if outputs_list: - res = job.communicator.job.outputs[-1] - res_dict = ast.literal_eval(res) - text = res_dict['response'] - sources = res_dict['sources'] - if gr_prompt_type == 'plain': - # then gradio server passes back full prompt + text - prompt_and_text = text - else: - prompt_and_text = prompt + text - response = prompter.get_response(prompt_and_text, prompt=prompt, - sanitize_bot_response=sanitize_bot_response) - text_chunk = response[len(text0):] - if not text_chunk: - # just need some sleep for threads to switch - time.sleep(0.001) - continue - # save old - text0 = response - yield dict(response=response, sources=sources, save_dict=dict(), llm_answers={}) - if time.time() - tgen0 > max_time: - if verbose: - print("Took too long for Gradio: %s" % (time.time() - tgen0), flush=True) - break - time.sleep(0.01) - # ensure get last output to avoid race - res_all = job.outputs() - if len(res_all) > 0: - # don't raise unless nochat API for now - e = check_job(job, timeout=0.02, raise_exception=not chat) - if e is not None: - strex = ''.join(traceback.format_tb(e.__traceback__)) - - res = res_all[-1] - res_dict = ast.literal_eval(res) - text = res_dict['response'] - sources = res_dict['sources'] - else: - # if got no answer at all, probably something bad, always raise exception - # UI will still put exception in Chat History under chat exceptions - e = check_job(job, timeout=0.3, raise_exception=True) - # go with old text if last call didn't work - if e is not None: - stre = str(e) - strex = ''.join(traceback.format_tb(e.__traceback__)) - else: - stre = '' - strex = '' - - print("Bad final response: %s %s %s %s %s: %s %s" % (base_model, inference_server, - res_all, prompt, text, stre, strex), - flush=True) - if gr_prompt_type == 'plain': - # then gradio server passes back full prompt + text - prompt_and_text = text - else: - prompt_and_text = prompt + text - response = prompter.get_response(prompt_and_text, prompt=prompt, - sanitize_bot_response=sanitize_bot_response) - yield dict(response=response, sources=sources, save_dict=dict(), error=strex, llm_answers={}) - elif hf_client: - # HF inference server needs control over input tokens - where_from = "hf_client" - response = '' - extra = '' - sources = '' - - # prompt must include all human-bot like tokens, already added by prompt - # https://github.com/huggingface/text-generation-inference/tree/main/clients/python#types - terminate_response = prompter.terminate_response or [] - stop_sequences = list(set(terminate_response + [prompter.PreResponse])) - stop_sequences = [x for x in stop_sequences if x] - gen_server_kwargs = dict(do_sample=do_sample, - max_new_tokens=max_new_tokens, - # best_of=None, - repetition_penalty=repetition_penalty, - return_full_text=False, - seed=SEED, - stop_sequences=stop_sequences, - temperature=temperature, - top_k=top_k, - top_p=top_p, - # truncate=False, # behaves oddly - # typical_p=top_p, - # watermark=False, - # decoder_input_details=False, - ) - # work-around for timeout at constructor time, will be issue if multi-threading, - # so just do something reasonable or max_time if larger - # lower bound because client is re-used if multi-threading - hf_client.timeout = max(300, max_time) - if not stream_output: - text = hf_client.generate(prompt, **gen_server_kwargs).generated_text - response = prompter.get_response(prompt + text, prompt=prompt, - sanitize_bot_response=sanitize_bot_response) - yield dict(response=response, sources=sources, save_dict=dict(), llm_answers={}) - else: - tgen0 = time.time() - text = "" - for responses in hf_client.generate_stream(prompt, **gen_server_kwargs): - if not responses.token.special: - # stop_sequences - text_chunk = responses.token.text - text += text_chunk - response = prompter.get_response(prompt + text, prompt=prompt, - sanitize_bot_response=sanitize_bot_response) - sources = '' - yield dict(response=response, sources=sources, save_dict=dict(), llm_answers={}) - if time.time() - tgen0 > max_time: - if verbose: - print("Took too long for TGI: %s" % (time.time() - tgen0), flush=True) - break - else: - raise RuntimeError("Failed to get client: %s" % inference_server) - else: - raise RuntimeError("No such inference_server %s" % inference_server) - - if save_dir and text: - # save prompt + new text - extra_dict = gen_server_kwargs.copy() - extra_dict.update(dict(inference_server=inference_server, num_prompt_tokens=num_prompt_tokens, - t_generate=time.time() - t_generate, - ntokens=None, - tokens_persecond=None, - )) - save_dict = dict(prompt=prompt, output=text, base_model=base_model, save_dir=save_dir, - where_from=where_from, extra_dict=extra_dict) - yield dict(response=response, sources=sources, save_dict=save_dict, llm_answers={}) - return - else: - assert not inference_server, "inference_server=%s not supported" % inference_server - - if isinstance(tokenizer, str): - # pipeline - if tokenizer == "summarization": - key = 'summary_text' - else: - raise RuntimeError("No such task type %s" % tokenizer) - # NOTE: uses max_length only - sources = '' - yield dict(response=model(prompt, max_length=max_new_tokens)[0][key], sources=sources, save_dict=dict(), - llm_answers={}) - - if 'mbart-' in base_model.lower(): - assert src_lang is not None - tokenizer.src_lang = languages_covered()[src_lang] - - stopping_criteria = get_stopping(prompt_type, prompt_dict, tokenizer, device, base_model, - model_max_length=model_max_length, - prompter=prompter, - truncation_generation=truncation_generation) - - inputs = tokenizer(prompt, return_tensors="pt") - if debug and len(inputs["input_ids"]) > 0: - print('input_ids length', len(inputs["input_ids"][0]), flush=True) - input_ids = inputs["input_ids"].to(device) - # CRITICAL LIMIT else will fail - max_max_tokens = int(tokenizer.model_max_length) - max_input_tokens_default = max(0, int(max_max_tokens - min_new_tokens)) - if max_input_tokens >= 0: - max_input_tokens = min(max_input_tokens_default, max_input_tokens) - else: - max_input_tokens = max_input_tokens_default - # NOTE: Don't limit up front due to max_new_tokens, let go up to max or reach max_max_tokens in stopping.py - assert isinstance(max_input_tokens, int), "Bad type for max_input_tokens=%s %s" % ( - max_input_tokens, type(max_input_tokens)) - input_ids = input_ids[:, -max_input_tokens:] - # required for falcon if multiple threads or asyncio accesses to model during generation - if use_cache is None: - use_cache = False if 'falcon' in base_model else True - if attention_sinks: - assert use_cache, "attention sinks requires use_cache=True" - bad_word_ids = [tokenizer.eos_token_id] - gen_config_kwargs = dict(num_beams=num_beams, - do_sample=do_sample, - repetition_penalty=float(repetition_penalty), - num_return_sequences=num_return_sequences, - renormalize_logits=True, - remove_invalid_values=True, - use_cache=use_cache, - max_new_tokens=max_new_tokens, # unsure if required here - ) - if do_sample: - gen_config_kwargs.update(dict(temperature=float(temperature), - top_p=float(top_p), - top_k=top_k)) - if penalty_alpha > 0: - gen_config_kwargs.update(dict(penalty_alpha=penalty_alpha)) - if True: - # unclear impact, some odd things going on inside - # leads to: - # The attention mask and the pad token id were not set. As a consequence, you may observe unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results. - # Setting `pad_token_id` to `eos_token_id`:2 for open-end generation. - # or leads to: - # Using cls_token, but it is not set yet. - # Using mask_token, but it is not set yet. - # Using pad_token, but it is not set yet. - # Using sep_token, but it is not set yet. - token_ids = ['eos_token_id', 'pad_token_id', 'bos_token_id', 'cls_token_id', 'sep_token_id'] - for token_id in token_ids: - if hasattr(tokenizer, token_id) and getattr(tokenizer, token_id) is not None: - gen_config_kwargs.update({token_id: getattr(tokenizer, token_id)}) - generation_config = GenerationConfig(**gen_config_kwargs) - - gen_kwargs = dict(input_ids=input_ids, - generation_config=generation_config, - return_dict_in_generate=True, - output_scores=True, - max_new_tokens=max_new_tokens, # prompt + new - min_new_tokens=min_new_tokens, # prompt + new - early_stopping=early_stopping, # False, True, "never" - max_time=max_time, - stopping_criteria=stopping_criteria, - ) - if 'gpt2' in base_model.lower(): - gen_kwargs.update(dict(bos_token_id=tokenizer.bos_token_id, pad_token_id=tokenizer.eos_token_id)) - elif 'mbart-' in base_model.lower(): - assert tgt_lang is not None - tgt_lang = languages_covered()[tgt_lang] - gen_kwargs.update(dict(forced_bos_token_id=tokenizer.lang_code_to_id[tgt_lang])) - else: - token_ids = ['eos_token_id', 'bos_token_id', 'pad_token_id'] - for token_id in token_ids: - if hasattr(tokenizer, token_id) and getattr(tokenizer, token_id) is not None: - gen_kwargs.update({token_id: getattr(tokenizer, token_id)}) - - decoder_kwargs = dict(skip_special_tokens=True, - clean_up_tokenization_spaces=True) - - decoder = functools.partial(tokenizer.decode, - **decoder_kwargs - ) - with torch.no_grad(): - have_lora_weights = lora_weights not in [no_lora_str, '', None] - context_class_cast = NullContext if device == 'cpu' or have_lora_weights or device == 'mps' else torch.autocast - if t5_type(base_model): - # issues when casting to float16, can mess up t5 model, e.g. only when not streaming, or other odd behaviors - context_class_cast = NullContext - with context_class_cast(device): - # protection for gradio not keeping track of closed users, - # else hit bitsandbytes lack of thread safety: - # https://github.com/h2oai/h2ogpt/issues/104 - # but only makes sense if concurrency_count == 1 - context_class = NullContext # if concurrency_count > 1 else filelock.FileLock - if verbose: - print('Pre-Generate: %s' % str(datetime.now()), flush=True) - decoded_output = None - response = '' - with context_class("generate.lock"): - if verbose: - print('Generate: %s' % str(datetime.now()), flush=True) - always_use_streaming_method = True # to deal with complex parsing of prompt vs. generation due to odd tokenizing - if stream_output or always_use_streaming_method: - skip_prompt = True # True means first output excludes prompt - streamer = H2OTextIteratorStreamer(tokenizer, skip_prompt=skip_prompt, block=False, - **decoder_kwargs) - gen_kwargs.update(dict(streamer=streamer)) - target = wrapped_partial(generate_with_exceptions, model.generate, - raise_generate_gpu_exceptions=raise_generate_gpu_exceptions, - **gen_kwargs) - bucket = queue.Queue() - thread = EThread(target=target, streamer=streamer, bucket=bucket) - thread.start() - ret = dict(response='', sources='', save_dict=dict(), llm_answers={}) - outputs = "" - sources = '' - tgen0 = time.time() - try: - for new_text in streamer: - if bucket.qsize() > 0 or thread.exc: - thread.join() - outputs += new_text - response = prompter.get_response(outputs, prompt=None, - only_new_text=True, - sanitize_bot_response=sanitize_bot_response) - ret = dict(response=response, sources=sources, save_dict=dict(), llm_answers={}) - if stream_output: - yield ret - if time.time() - tgen0 > max_time: - if verbose: - print("Took too long for Torch: %s" % (time.time() - tgen0), flush=True) - break - # yield if anything left over as can happen (FIXME: Understand better) - yield ret - except BaseException: - # if any exception, raise that exception if was from thread, first - if thread.exc: - raise thread.exc - raise - finally: - # don't clear torch cache here, delays multi-generation, and bot(), all_bot(), and evaluate_nochat() do it - # in case no exception and didn't join with thread yet, then join - if not thread.exc: - thread.join() - # in case raise StopIteration or broke queue loop in streamer, but still have exception - if thread.exc: - raise thread.exc - decoded_output = outputs - ntokens = len(outputs) // 4 # hack for now - else: - # below length removal doesn't work in general, because encoding does not match internal of model generation - input_ids_len = gen_kwargs['input_ids'][0].shape[0] - try: - outputs = model.generate(**gen_kwargs) - finally: - pass - # don't clear torch cache here, delays multi-generation, and bot(), all_bot(), and evaluate_nochat() do it - # skip first IDs - ntokens = sum([len(s) - input_ids_len for s in outputs.sequences]) if save_dir else -1 - outputs = [decoder(s[input_ids_len:]) for s in outputs.sequences] - sources = '' - response = prompter.get_response(outputs, prompt=None, - only_new_text=True, - sanitize_bot_response=sanitize_bot_response) - yield dict(response=response, sources=sources, save_dict=dict(), llm_answers={}) - if outputs and len(outputs) >= 1: - decoded_output = prompt + outputs[0] - if save_dir and decoded_output: - extra_dict = gen_config_kwargs.copy() - extra_dict.update(dict(num_prompt_tokens=num_prompt_tokens, - t_generate=time.time() - t_generate, - ntokens=ntokens, - tokens_persecond=ntokens / (time.time() - t_generate), - )) - save_dict = dict(prompt=prompt, output=decoded_output, base_model=base_model, save_dir=save_dir, - where_from="evaluate_%s" % str(stream_output), - extra_dict=extra_dict) - yield dict(response=response, sources=sources, save_dict=save_dict, llm_answers={}) - if verbose: - print('Post-Generate: %s decoded_output: %s' % ( - str(datetime.now()), len(decoded_output) if decoded_output else -1), flush=True) - - -inputs_list_names = list(inspect.signature(evaluate).parameters) -state_names = input_args_list.copy() # doesn't have to be the same, but state_names must match evaluate() and how filled then -inputs_kwargs_list = [x for x in inputs_list_names if x not in eval_func_param_names + state_names] - - -def get_cutoffs(memory_restriction_level, for_context=False, model_max_length=2048, min_max_new_tokens=256): - # help to avoid errors like: - # RuntimeError: The size of tensor a (2048) must match the size of tensor b (2049) at non-singleton dimension 3 - # RuntimeError: expected scalar type Half but found Float - # with - 256 - if memory_restriction_level > 0: - max_length_tokenize = 768 - 256 if memory_restriction_level <= 2 else 512 - 256 - else: - # at least give room for 1 paragraph output - max_length_tokenize = model_max_length - min_max_new_tokens - cutoff_len = max_length_tokenize * 4 # if reaches limit, then can't generate new tokens - output_smallest = 30 * 4 - max_prompt_length = cutoff_len - output_smallest - - if for_context: - # then lower even more to avoid later chop, since just estimate tokens in context bot - max_prompt_length = max(64, int(max_prompt_length * 0.8)) - - return cutoff_len, output_smallest, max_length_tokenize, max_prompt_length - - -class H2OTextIteratorStreamer(TextIteratorStreamer): - """ - normally, timeout required for now to handle exceptions, else get() - but with H2O version of TextIteratorStreamer, loop over block to handle - """ - - def __init__(self, tokenizer, skip_prompt: bool = False, timeout: typing.Optional[float] = None, - block=True, **decode_kwargs): - super().__init__(tokenizer, skip_prompt, **decode_kwargs) - self.text_queue = queue.Queue() - self.stop_signal = None - self.do_stop = False - self.timeout = timeout - self.block = block - - def on_finalized_text(self, text: str, stream_end: bool = False): - """Put the new text in the queue. If the stream is ending, also put a stop signal in the queue.""" - self.text_queue.put(text, timeout=self.timeout) - if stream_end: - self.text_queue.put(self.stop_signal, timeout=self.timeout) - - def __iter__(self): - return self - - def __next__(self): - while True: - try: - value = self.stop_signal # value looks unused in pycharm, not true - if self.do_stop: - print("hit stop", flush=True) - # could raise or break, maybe best to raise and make parent see if any exception in thread - self.clear_queue() - self.do_stop = False - raise StopIteration() - # break - value = self.text_queue.get(block=self.block, timeout=self.timeout) - break - except queue.Empty: - time.sleep(0.01) - if value == self.stop_signal: - self.clear_queue() - self.do_stop = False - raise StopIteration() - else: - return value - - def clear_queue(self): - # make sure streamer is reusable after stop hit - with self.text_queue.mutex: - self.text_queue.queue.clear() - - def put(self, value): - """ - Receives tokens, decodes them, and prints them to stdout as soon as they form entire words. - # same as base class, except remove hack w.r.t. text.rfind(" ") that ruins LLaMa2 - """ - if len(value.shape) > 1 and value.shape[0] > 1: - raise ValueError("TextStreamer only supports batch size 1") - elif len(value.shape) > 1: - value = value[0] - - if self.skip_prompt and self.next_tokens_are_prompt: - self.next_tokens_are_prompt = False - return - - # Add the new token to the cache and decodes the entire thing. - self.token_cache.extend(value.tolist()) - text = self.tokenizer.decode(self.token_cache, **self.decode_kwargs) - - # After the symbol for a new line, we flush the cache. - if text.endswith("\n"): - printable_text = text[self.print_len:] - self.token_cache = [] - self.print_len = 0 - # If the last token is a CJK character, we print the characters. - elif len(text) > 0 and self._is_chinese_char(ord(text[-1])): - printable_text = text[self.print_len:] - self.print_len += len(printable_text) - # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, - # which may change with the subsequent token -- there are probably smarter ways to do this!) - elif len(text) > 0 and text[-1] == '�': - printable_text = text[self.print_len: text.rfind(" ") + 1] - self.print_len += len(printable_text) - else: - printable_text = text[self.print_len:] - self.print_len += len(printable_text) - - self.on_finalized_text(printable_text) - - -def generate_with_exceptions(func, *args, raise_generate_gpu_exceptions=True, **kwargs): - try: - func(*args, **kwargs) - except torch.cuda.OutOfMemoryError as e: - print("GPU OOM 2: exception: %s" % str(e), - flush=True) - if 'input_ids' in kwargs: - if kwargs['input_ids'] is not None: - kwargs['input_ids'].cpu() - kwargs['input_ids'] = None - traceback.print_exc() - clear_torch_cache() - return - except (Exception, RuntimeError) as e: - if 'Expected all tensors to be on the same device' in str(e) or \ - 'expected scalar type Half but found Float' in str(e) or \ - 'probability tensor contains either' in str(e) or \ - 'cublasLt ran into an error!' in str(e) or \ - 'mat1 and mat2 shapes cannot be multiplied' in str(e): - print( - "GPU Error: exception: %s" % str(e), - flush=True) - traceback.print_exc() - clear_torch_cache() - if raise_generate_gpu_exceptions: - raise - return - else: - clear_torch_cache() - if raise_generate_gpu_exceptions: - raise - - -def get_generate_params(model_lower, - chat, - stream_output, show_examples, - prompt_type, prompt_dict, - system_prompt, - pre_prompt_query, prompt_query, - pre_prompt_summary, prompt_summary, - temperature, top_p, top_k, penalty_alpha, num_beams, - max_new_tokens, min_new_tokens, early_stopping, max_time, - repetition_penalty, num_return_sequences, - do_sample, - top_k_docs, chunk, chunk_size, - image_loaders, - pdf_loaders, - url_loaders, - jq_schema, - docs_ordering_type, - min_max_new_tokens, - max_input_tokens, - docs_token_handling, - docs_joiner, - hyde_level, - hyde_template, - verbose, - ): - use_defaults = False - use_default_examples = True - examples = [] - task_info = 'LLM' - if model_lower: - print(f"Using Model {model_lower}", flush=True) - else: - if verbose: - print("No model defined yet", flush=True) - - min_new_tokens = min_new_tokens if min_new_tokens is not None else 0 - early_stopping = early_stopping if early_stopping is not None else False - max_time_defaults = 60 * 10 - max_time = max_time if max_time is not None else max_time_defaults - - if not prompt_type and model_lower in inv_prompt_type_to_model_lower and prompt_type != 'custom': - prompt_type = inv_prompt_type_to_model_lower[model_lower] - if verbose: - print("Auto-selecting prompt_type=%s for %s" % (prompt_type, model_lower), flush=True) - - # examples at first don't include chat, instruction_nochat, iinput_nochat, added at end - if show_examples is None: - if chat: - show_examples = False - else: - show_examples = True - - summarize_example1 = """Jeff: Can I train a ? Transformers model on Amazon SageMaker? -Philipp: Sure you can use the new Hugging Face Deep Learning Container. -Jeff: ok. -Jeff: and how can I get started? -Jeff: where can I find documentation? -Philipp: ok, ok you can find everything here. https://huggingface.co/blog/the-partnership-amazon-sagemaker-and-hugging-face""" - - use_placeholder_instruction_as_example = False - if 'bart-large-cnn-samsum' in model_lower or 'flan-t5-base-samsum' in model_lower: - placeholder_instruction = summarize_example1 - placeholder_input = "" - use_defaults = True - use_default_examples = False - use_placeholder_instruction_as_example = True - task_info = "Summarization" - elif 't5-' in model_lower or 't5' == model_lower or 'flan-' in model_lower: - placeholder_instruction = "The square root of x is the cube root of y. What is y to the power of 2, if x = 4?" - placeholder_input = "" - use_defaults = True - use_default_examples = True - task_info = "Multi-Task: Q/A, translation, Chain-of-Thought, Logical Reasoning, Summarization, etc. Best to use task prefix as trained on, e.g. `translate English to German: ` (space after colon)" - elif 'mbart-' in model_lower: - placeholder_instruction = "The girl has long hair." - placeholder_input = "" - use_defaults = True - use_default_examples = False - use_placeholder_instruction_as_example = True - elif 'gpt2' in model_lower: - placeholder_instruction = "The sky is" - placeholder_input = "" - prompt_type = prompt_type or 'plain' - use_default_examples = True # some will be odd "continuations" but can be ok - use_placeholder_instruction_as_example = True - task_info = "Auto-complete phrase, code, etc." - use_defaults = True - else: - if chat: - placeholder_instruction = "" - else: - placeholder_instruction = "Give detailed answer for whether Einstein or Newton is smarter." - placeholder_input = "" - if not prompt_type and model_lower in inv_prompt_type_to_model_lower and prompt_type != 'custom': - prompt_type = inv_prompt_type_to_model_lower[model_lower] - elif model_lower: - # default is plain, because might rely upon trust_remote_code to handle prompting - prompt_type = prompt_type or 'plain' - else: - prompt_type = '' - task_info = "No task" - if prompt_type == 'instruct': - task_info = "Answer question or follow imperative as instruction with optionally input." - elif prompt_type == 'plain': - task_info = "Auto-complete phrase, code, etc." - elif prompt_type == 'human_bot': - if chat: - task_info = "Chat (Shift-Enter to give question/imperative, input concatenated with instruction)" - else: - task_info = "Ask question/imperative (input concatenated with instruction)" - - # revert to plain if still nothing - prompt_type = prompt_type or 'plain' - if use_defaults: - temperature = 1.0 if temperature is None else temperature - top_p = 1.0 if top_p is None else top_p - top_k = 40 if top_k is None else top_k - penalty_alpha = 0 if penalty_alpha is None else penalty_alpha - num_beams = num_beams or 1 - max_new_tokens = max_new_tokens or 512 - repetition_penalty = repetition_penalty or 1.07 - num_return_sequences = min(num_beams, num_return_sequences or 1) - do_sample = False if do_sample is None else do_sample - else: - temperature = 0.1 if temperature is None else temperature - top_p = 0.75 if top_p is None else top_p - top_k = 40 if top_k is None else top_k - penalty_alpha = 0 if penalty_alpha is None else penalty_alpha - num_beams = num_beams or 1 - max_new_tokens = max_new_tokens or 1024 - repetition_penalty = repetition_penalty or 1.07 - num_return_sequences = min(num_beams, num_return_sequences or 1) - do_sample = False if do_sample is None else do_sample - # doesn't include chat, instruction_nochat, iinput_nochat, added later - params_list = ["", - stream_output, - prompt_type, prompt_dict, - temperature, top_p, top_k, penalty_alpha, num_beams, - max_new_tokens, min_new_tokens, - early_stopping, max_time, repetition_penalty, num_return_sequences, do_sample] - - if use_placeholder_instruction_as_example: - examples += [[placeholder_instruction, ''] + params_list] - - if use_default_examples: - examples += [ - ["Translate English to French", "Good morning"] + params_list, - ["Give detailed answer for whether Einstein or Newton is smarter.", ''] + params_list, - ["Explain in detailed list, all the best practices for coding in python.", ''] + params_list, - [ - "Create a markdown table with 3 rows for the primary colors, and 2 columns, with color name and hex codes.", - ''] + params_list, - ['Translate to German: My name is Arthur', ''] + params_list, - ["Please answer to the following question. Who is going to be the next Ballon d'or?", ''] + params_list, - ['Can Geoffrey Hinton have a conversation with George Washington? Give the rationale before answering.', - ''] + params_list, - ['Please answer the following question. What is the boiling point of Nitrogen?', ''] + params_list, - ['Answer the following yes/no question. Can you write a whole Haiku in a single tweet?', ''] + params_list, - ["Simplify the following expression: (False or False and True). Explain your answer.", ''] + params_list, - [ - "Premise: At my age you will probably have learnt one lesson. Hypothesis: It's not certain how many lessons you'll learn by your thirties. Does the premise entail the hypothesis?", - ''] + params_list, - ['The square root of x is the cube root of y. What is y to the power of 2, if x = 4?', ''] + params_list, - [ - 'Answer the following question by reasoning step by step. The cafeteria had 23 apples. If they used 20 for lunch, and bought 6 more, how many apple do they have?', - ''] + params_list, - ["""def area_of_rectangle(a: float, b: float): - \"\"\"Return the area of the rectangle.\"\"\"""", ''] + params_list, - ["""# a function in native python: -def mean(a): - return sum(a)/len(a) - -# the same function using numpy: -import numpy as np -def mean(a):""", ''] + params_list, - ["""X = np.random.randn(100, 100) -y = np.random.randint(0, 1, 100) - -# fit random forest classifier with 20 estimators""", ''] + params_list, - ] - # add summary example - examples += [ - [summarize_example1, 'Summarize' if prompt_type not in ['plain', 'instruct_simple'] else ''] + params_list] - - src_lang = "English" - tgt_lang = "Russian" - - # move to correct position - for example in examples: - example += [chat, '', '', LangChainMode.DISABLED.value, True, - LangChainAction.QUERY.value, [], - top_k_docs, chunk, chunk_size, DocumentSubset.Relevant.name, [], - pre_prompt_query, prompt_query, - pre_prompt_summary, prompt_summary, - system_prompt, - image_loaders, - pdf_loaders, - url_loaders, - jq_schema, - None, - None, - False, - None, - None, - docs_ordering_type, - min_max_new_tokens, - max_input_tokens, - docs_token_handling, - docs_joiner, - hyde_level, - hyde_template, - ] - # adjust examples if non-chat mode - if not chat: - example[eval_func_param_names.index('instruction_nochat')] = example[ - eval_func_param_names.index('instruction')] - example[eval_func_param_names.index('instruction')] = '' - - example[eval_func_param_names.index('iinput_nochat')] = example[eval_func_param_names.index('iinput')] - example[eval_func_param_names.index('iinput')] = '' - assert len(example) == len(eval_func_param_names), "Wrong example: %s %s" % ( - len(example), len(eval_func_param_names)) - - if prompt_type == PromptType.custom.name and not prompt_dict: - raise ValueError("Unexpected to get non-empty prompt_dict=%s for prompt_type=%s" % (prompt_dict, prompt_type)) - - # get prompt_dict from prompt_type, so user can see in UI etc., or for custom do nothing except check format - prompt_dict, error0 = get_prompt(prompt_type, prompt_dict, - chat=False, context='', reduced=False, making_context=False, return_dict=True, - system_prompt=system_prompt) - if error0: - raise RuntimeError("Prompt wrong: %s" % error0) - - return placeholder_instruction, placeholder_input, \ - stream_output, show_examples, \ - prompt_type, prompt_dict, \ - temperature, top_p, top_k, penalty_alpha, num_beams, \ - max_new_tokens, min_new_tokens, early_stopping, max_time, \ - repetition_penalty, num_return_sequences, \ - do_sample, \ - src_lang, tgt_lang, \ - examples, \ - task_info - - -def languages_covered(): - # https://huggingface.co/facebook/mbart-large-50-many-to-many-mmt#languages-covered - covered = """Arabic (ar_AR), Czech (cs_CZ), German (de_DE), English (en_XX), Spanish (es_XX), Estonian (et_EE), Finnish (fi_FI), French (fr_XX), Gujarati (gu_IN), Hindi (hi_IN), Italian (it_IT), Japanese (ja_XX), Kazakh (kk_KZ), Korean (ko_KR), Lithuanian (lt_LT), Latvian (lv_LV), Burmese (my_MM), Nepali (ne_NP), Dutch (nl_XX), Romanian (ro_RO), Russian (ru_RU), Sinhala (si_LK), Turkish (tr_TR), Vietnamese (vi_VN), Chinese (zh_CN), Afrikaans (af_ZA), Azerbaijani (az_AZ), Bengali (bn_IN), Persian (fa_IR), Hebrew (he_IL), Croatian (hr_HR), Indonesian (id_ID), Georgian (ka_GE), Khmer (km_KH), Macedonian (mk_MK), Malayalam (ml_IN), Mongolian (mn_MN), Marathi (mr_IN), Polish (pl_PL), Pashto (ps_AF), Portuguese (pt_XX), Swedish (sv_SE), Swahili (sw_KE), Tamil (ta_IN), Telugu (te_IN), Thai (th_TH), Tagalog (tl_XX), Ukrainian (uk_UA), Urdu (ur_PK), Xhosa (xh_ZA), Galician (gl_ES), Slovene (sl_SI)""" - covered = covered.split(', ') - covered = {x.split(' ')[0]: x.split(' ')[1].replace(')', '').replace('(', '') for x in covered} - return covered - - -def score_qa(smodel, stokenizer, max_length_tokenize, question, answer, cutoff_len): - question = question[-cutoff_len:] - answer = answer[-cutoff_len:] - - inputs = stokenizer(question, answer, - return_tensors="pt", - truncation=True, - max_length=max_length_tokenize).to(smodel.device) - try: - score = torch.sigmoid(smodel(**inputs.to(smodel.device)).logits[0].float()).cpu().detach().numpy()[0] - except torch.cuda.OutOfMemoryError as e: - print("GPU OOM 3: question: %s answer: %s exception: %s" % (question, answer, str(e)), flush=True) - del inputs - traceback.print_exc() - clear_torch_cache() - return 'Response Score: GPU OOM' - except (Exception, RuntimeError) as e: - if 'Expected all tensors to be on the same device' in str(e) or \ - 'expected scalar type Half but found Float' in str(e) or \ - 'probability tensor contains either' in str(e) or \ - 'cublasLt ran into an error!' in str(e) or \ - 'device-side assert triggered' in str(e): - print("GPU Error: question: %s answer: %s exception: %s" % (question, answer, str(e)), - flush=True) - traceback.print_exc() - clear_torch_cache() - return 'Response Score: GPU Error' - else: - raise - os.environ['TOKENIZERS_PARALLELISM'] = 'true' - return score - - -def check_locals(**kwargs): - # ensure everything in evaluate is here - can_skip_because_locally_generated = no_default_param_names + [ - # get_model: - 'reward_type' - ] - for k in eval_func_param_names: - if k in can_skip_because_locally_generated: - continue - assert k in kwargs, "Missing %s" % k - for k in inputs_kwargs_list: - if k in can_skip_because_locally_generated: - continue - assert k in kwargs, "Missing %s" % k - - for k in list(inspect.signature(get_model).parameters): - if k in can_skip_because_locally_generated: - continue - assert k in kwargs, "Missing %s" % k - - -def get_model_max_length(model_state): - if not isinstance(model_state['tokenizer'], (str, type(None))): - return model_state['tokenizer'].model_max_length - else: - return 2048 - - -def get_model_max_length_from_tokenizer(tokenizer): - if hasattr(tokenizer, 'model_max_length'): - return int(tokenizer.model_max_length) - else: - return 2048 - - -def get_max_max_new_tokens(model_state, **kwargs): - if not isinstance(model_state['tokenizer'], (str, type(None))) or not kwargs.get('truncation_generation', False): - if hasattr(model_state['tokenizer'], 'model_max_length'): - max_max_new_tokens = model_state['tokenizer'].model_max_length - else: - # e.g. fast up, no model - max_max_new_tokens = None - else: - max_max_new_tokens = None - - if kwargs['max_max_new_tokens'] is not None and max_max_new_tokens is not None: - return min(max_max_new_tokens, kwargs['max_max_new_tokens']) - elif kwargs['max_max_new_tokens'] is not None: - return kwargs['max_max_new_tokens'] - elif kwargs['memory_restriction_level'] == 1: - return 768 - elif kwargs['memory_restriction_level'] == 2: - return 512 - elif kwargs['memory_restriction_level'] >= 3: - return 256 - else: - # FIXME: Need to update after new model loaded, so user can control with slider - return 2048 - - -def get_minmax_top_k_docs(is_public): - label_top_k_docs = "Number of document chunks (query) or pages/parts (summarize)" - if is_public: - min_top_k_docs = 1 - max_top_k_docs = 8 - else: - min_top_k_docs = -1 - max_top_k_docs = 100 - label_top_k_docs = label_top_k_docs + " (-1 = auto fill model context, all pages/docs for summarize)" - return min_top_k_docs, max_top_k_docs, label_top_k_docs - - -def merge_chat_conversation_history(chat_conversation1, history): - # chat_conversation and history ordered so largest index of list is most recent - if chat_conversation1: - chat_conversation1 = str_to_list(chat_conversation1) - for conv1 in chat_conversation1: - assert isinstance(conv1, (list, tuple)) - assert len(conv1) == 2 - - if isinstance(history, list): - # make copy so only local change - if chat_conversation1: - # so priority will be newest that comes from actual chat history from UI, then chat_conversation - history = chat_conversation1 + history.copy() - elif chat_conversation1: - history = chat_conversation1 - else: - history = [] - return history - - -def history_to_context(history, langchain_mode=None, - add_chat_history_to_context=None, - prompt_type=None, prompt_dict=None, chat=None, model_max_length=None, - memory_restriction_level=None, keep_sources_in_context=None, - system_prompt=None, chat_conversation=None, - min_max_new_tokens=256): - """ - consumes all history up to (but not including) latest history item that is presumed to be an [instruction, None] pair - :param history: - :param langchain_mode: - :param add_chat_history_to_context: - :param prompt_type: - :param prompt_dict: - :param chat: - :param model_max_length: - :param memory_restriction_level: - :param keep_sources_in_context: - :param system_prompt: - :param chat_conversation: - :param min_max_new_tokens: - :return: - """ - history = merge_chat_conversation_history(chat_conversation, history) - - if len(history) >= 1 and len(history[-1]) >= 2 and not history[-1][1]: - len_history = len(history) - 1 - else: - # full history - len_history = len(history) - - # ensure output will be unique to models - _, _, _, max_prompt_length = get_cutoffs(memory_restriction_level, - for_context=True, model_max_length=model_max_length, - min_max_new_tokens=min_max_new_tokens) - context1 = '' - if max_prompt_length is not None and add_chat_history_to_context: - context1 = '' - # - 1 below because current instruction already in history from user() - for histi in range(0, len_history): - data_point = dict(instruction=history[histi][0], input='', output=history[histi][1]) - prompt, pre_response, terminate_response, chat_sep, chat_turn_sep = \ - generate_prompt(data_point, - prompt_type, - prompt_dict, - chat, - reduced=True, - making_context=True, - system_prompt=system_prompt, - histi=histi) - # md -> back to text, maybe not super important if model trained enough - if not keep_sources_in_context and langchain_mode != 'Disabled' and prompt.find(super_source_prefix) >= 0: - # FIXME: This is relatively slow even for small amount of text, like 0.3s each history item - import re - prompt = re.sub(f'{re.escape(super_source_prefix)}.*?{re.escape(super_source_postfix)}', '', prompt, - flags=re.DOTALL) - if prompt.endswith('\n

'): - prompt = prompt[:-4] - prompt = prompt.replace('
', chat_turn_sep) - if not prompt.endswith(chat_turn_sep): - prompt += chat_turn_sep - # most recent first, add older if can - # only include desired chat history - if len(prompt + context1) > max_prompt_length: - break - context1 += prompt - - _, pre_response, terminate_response, chat_sep, chat_turn_sep = \ - generate_prompt({}, prompt_type, prompt_dict, - chat, reduced=True, - making_context=True, - system_prompt=system_prompt, - histi=-1) - if context1 and not context1.endswith(chat_turn_sep): - context1 += chat_turn_sep # ensure if terminates abruptly, then human continues on next line - return context1 - - -def get_relaxed_max_new_tokens(prompt, tokenizer=None, max_new_tokens=None, max_new_tokens0=None): - # check if can relax max_new_tokens for this specific prompt - if max_new_tokens0 is not None and \ - hasattr(tokenizer, 'model_max_len') and \ - isinstance(tokenizer.model_max_len, (float, int)): - max_new_tokens = int(tokenizer.model_max_length) - get_token_count(prompt, tokenizer) - if max_new_tokens is not None: - return min(max_new_tokens0, max_new_tokens) - else: - return max_new_tokens0 - return max_new_tokens - - -def get_limited_prompt(instruction, - iinput, - tokenizer, - estimated_instruction=None, - prompter=None, - inference_server=None, - prompt_type=None, prompt_dict=None, chat=False, max_new_tokens=None, - system_prompt='', - context='', chat_conversation=None, text_context_list=None, - keep_sources_in_context=False, - model_max_length=None, memory_restriction_level=0, - langchain_mode=None, add_chat_history_to_context=True, - verbose=False, - doc_importance=0.5, - min_max_new_tokens=256, - max_input_tokens=-1, - truncation_generation=False, - gradio_server=False, - ): - if gradio_server or not inference_server: - # can listen to truncation_generation - pass - else: - # these don't support allowing going beyond total context - truncation_generation = True - - # for templates, use estimated for counting, but adjust instruction as output - if estimated_instruction is None: - estimated_instruction = instruction - - if max_input_tokens >= 0: - # max_input_tokens is used to runtime (via client/UI) to control actual filling of context - max_input_tokens = min(model_max_length - min_max_new_tokens, max_input_tokens) - else: - max_input_tokens = model_max_length - min_max_new_tokens - - if prompter: - prompt_type = prompter.prompt_type - prompt_dict = prompter.prompt_dict - chat = prompter.chat - stream_output = prompter.stream_output - system_prompt = prompter.system_prompt - - generate_prompt_type = prompt_type - external_handle_chat_conversation = False - if inference_server and any( - inference_server.startswith(x) for x in ['openai_chat', 'openai_azure_chat', 'vllm_chat']): - # Chat APIs do not take prompting - # Replicate does not need prompting if no chat history, but in general can take prompting - # if using prompter, prompter.system_prompt will already be filled with automatic (e.g. from llama-2), - # so if replicate final prompt with system prompt still correct because only access prompter.system_prompt that was already set - # below already true for openai, - # but not vllm by default as that can be any model and handled by FastChat API inside vLLM itself - generate_prompt_type = 'plain' - # Chat APIs don't handle chat history via single prompt, but in messages, assumed to be handled outside this function - chat_conversation = [] - external_handle_chat_conversation = True - - # merge handles if chat_conversation is None - history = [] - history = merge_chat_conversation_history(chat_conversation, history) - history_to_context_func = functools.partial(history_to_context, - langchain_mode=langchain_mode, - add_chat_history_to_context=add_chat_history_to_context, - prompt_type=generate_prompt_type, - prompt_dict=prompt_dict, - chat=chat, - model_max_length=max_input_tokens, - memory_restriction_level=memory_restriction_level, - keep_sources_in_context=keep_sources_in_context, - system_prompt=system_prompt, - min_max_new_tokens=min_max_new_tokens) - context2 = history_to_context_func(history) - context1 = context - if context1 is None: - context1 = '' - - # get how many more tokens in templated instruction, somewhat of estimate at fine level - num_instruction_tokens = get_token_count(instruction, tokenizer) - num_estimated_instruction_tokens = get_token_count(estimated_instruction, tokenizer) - delta_instruction = max(0, num_estimated_instruction_tokens - num_instruction_tokens) - - # get estimated templated instruction tokens for counting purposes - from h2oai_pipeline import H2OTextGenerationPipeline - estimated_instruction, num_estimated_instruction_tokens = H2OTextGenerationPipeline.limit_prompt( - estimated_instruction, tokenizer, - max_prompt_length=max_input_tokens) - data_point_just_instruction = dict(context='', instruction=estimated_instruction, input='') - prompt_just_estimated_instruction = prompter.generate_prompt(data_point_just_instruction) - num_instruction_tokens = get_token_count(prompt_just_estimated_instruction, tokenizer) - - # get actual instruction, limited by template limitation - instruction, _ = H2OTextGenerationPipeline.limit_prompt(instruction, tokenizer, - max_prompt_length=max_input_tokens - delta_instruction) - - context1, num_context1_tokens = H2OTextGenerationPipeline.limit_prompt(context1, tokenizer, - max_prompt_length=max_input_tokens) - context2, num_context2_tokens = H2OTextGenerationPipeline.limit_prompt(context2, tokenizer, - max_prompt_length=max_input_tokens) - iinput, num_iinput_tokens = H2OTextGenerationPipeline.limit_prompt(iinput, tokenizer, - max_prompt_length=max_input_tokens) - if text_context_list is None: - text_context_list = [] - num_doc_tokens = sum([get_token_count(x + docs_joiner_default, tokenizer) for x in text_context_list]) - - num_prompt_tokens0 = (num_instruction_tokens or 0) + \ - (num_context1_tokens or 0) + \ - (num_context2_tokens or 0) + \ - (num_iinput_tokens or 0) + \ - (num_doc_tokens or 0) - - # go down to no less than 256, about 1 paragraph - # use max_new_tokens before use num_prompt_tokens0 else would be negative or ~0 - min_max_new_tokens = min(min_max_new_tokens, max_new_tokens) - # by default assume can handle all chat and docs - chat_index = 0 - - # allowed residual is either half of what is allowed if doc exceeds half, or is rest of what doc didn't consume - num_non_doc_tokens = num_prompt_tokens0 - num_doc_tokens - # to doc first then non-doc, shouldn't matter much either way - doc_max_length = max(max_input_tokens - num_non_doc_tokens, int(doc_importance * max_input_tokens)) - top_k_docs, one_doc_size, num_doc_tokens = get_docs_tokens(tokenizer, text_context_list=text_context_list, - max_input_tokens=doc_max_length) - non_doc_max_length = max(max_input_tokens - num_doc_tokens, int((1.0 - doc_importance) * max_input_tokens)) - - if num_non_doc_tokens > non_doc_max_length: - # need to limit in some way, keep portion of history but all of context and instruction - # 1) drop iinput (unusual to include anyways) - # 2) reduce history - # 3) reduce context1 - # 4) limit instruction so will fit - diff1 = non_doc_max_length - ( - num_instruction_tokens + num_context1_tokens + num_context2_tokens) - diff2 = non_doc_max_length - (num_instruction_tokens + num_context1_tokens) - diff3 = non_doc_max_length - num_instruction_tokens - diff4 = non_doc_max_length - if diff1 > 0: - # then should be able to do #1 - iinput = '' - num_iinput_tokens = 0 - elif diff2 > 0 > diff1: - # then may be able to do #1 + #2 - iinput = '' - num_iinput_tokens = 0 - chat_index_final = len(history) - for chat_index in range(len(history)): - # NOTE: history and chat_conversation are older for first entries - # FIXME: This is a slow for many short conversations - context2 = history_to_context_func(history[chat_index:]) - num_context2_tokens = get_token_count(context2, tokenizer) - diff1 = non_doc_max_length - ( - num_instruction_tokens + num_context1_tokens + num_context2_tokens) - if diff1 > 0: - chat_index_final = chat_index - if verbose: - print("chat_conversation used %d out of %d" % (chat_index, len(history)), flush=True) - break - chat_index = chat_index_final # i.e. if chat_index == len(history), then nothing can be consumed - elif diff3 > 0 > diff2: - # then may be able to do #1 + #2 + #3 - iinput = '' - num_iinput_tokens = 0 - context2 = '' - num_context2_tokens = 0 - context1, num_context1_tokens = H2OTextGenerationPipeline.limit_prompt(context1, tokenizer, - max_prompt_length=diff3) - if num_context1_tokens <= diff3: - pass - else: - print("failed to reduce", flush=True) - else: - # then must be able to do #1 + #2 + #3 + #4 - iinput = '' - num_iinput_tokens = 0 - context2 = '' - num_context2_tokens = 0 - context1 = '' - num_context1_tokens = 0 - # diff4 accounts for real prompting for instruction - # FIXME: history_to_context could include instruction, in case system prompt long, we overcount and could have more free tokens - - max_prompt_length = max(0, diff4 - delta_instruction) - instruction, _ = H2OTextGenerationPipeline.limit_prompt(instruction, tokenizer, - max_prompt_length=max_prompt_length) - # get actual instruction tokens - data_point_just_instruction = dict(context='', instruction=instruction, input='') - prompt_just_instruction = prompter.generate_prompt(data_point_just_instruction) - num_instruction_tokens = get_token_count(prompt_just_instruction, tokenizer) + delta_instruction - - # update full context - context = context1 + context2 - # update token counts (docs + non-docs, all tokens) - num_prompt_tokens = (num_instruction_tokens or 0) + \ - (num_context1_tokens or 0) + \ - (num_context2_tokens or 0) + \ - (num_iinput_tokens or 0) + \ - (num_doc_tokens or 0) - - # update max_new_tokens - # limit so max_new_tokens = prompt + new < max - # otherwise model can fail etc. e.g. for distilgpt2 asking for 1024 tokens is enough to fail if prompt=1 token - if truncation_generation: - max_new_tokens = min(max_new_tokens, model_max_length - num_prompt_tokens) - - if os.getenv('HARD_ASSERTS'): - if max_new_tokens < min_max_new_tokens: - raise ValueError("Invalid max_new_tokens=%s" % max_new_tokens) - - if prompter is None: - # get prompter - debug = False - stream_output = False # doesn't matter - prompter = Prompter(prompt_type, prompt_dict, debug=debug, chat=chat, stream_output=stream_output, - system_prompt=system_prompt) - if prompt_type != generate_prompt_type: - # override just this attribute, keep system_prompt etc. from original prompt_type - prompter.prompt_type = generate_prompt_type - - data_point = dict(context=context, instruction=instruction, input=iinput) - # handle promptA/promptB addition if really from history. - # if not from history, then reduced=False inside correct - # if mixed, then no specific correct thing to do, so treat like history and promptA/B will come first still - context_from_history = len(history) > 0 and len(context1) > 0 - prompt = prompter.generate_prompt(data_point, context_from_history=context_from_history) - num_prompt_tokens_actual = get_token_count(prompt, tokenizer) - - return prompt, \ - instruction, iinput, context, \ - num_prompt_tokens, max_new_tokens, num_prompt_tokens0, num_prompt_tokens_actual, \ - chat_index, external_handle_chat_conversation, \ - top_k_docs, one_doc_size, truncation_generation - - -def get_docs_tokens(tokenizer, text_context_list=[], max_input_tokens=None): - if text_context_list is None or len(text_context_list) == 0: - return 0, None, 0 - if max_input_tokens is None: - max_input_tokens = tokenizer.model_max_length - tokens = [get_token_count(x + docs_joiner_default, tokenizer) for x in text_context_list] - tokens_cumsum = np.cumsum(tokens) - where_res = np.where(tokens_cumsum < max_input_tokens)[0] - # if below condition fails, then keep top_k_docs=-1 and trigger special handling next - if where_res.shape[0] > 0: - top_k_docs = 1 + where_res[-1] - one_doc_size = None - num_doc_tokens = tokens_cumsum[top_k_docs - 1] # by index - else: - # if here, means 0 and just do best with 1 doc - top_k_docs = 1 - text_context_list = text_context_list[:top_k_docs] - # critical protection - from src.h2oai_pipeline import H2OTextGenerationPipeline - doc_content = text_context_list[0] - doc_content, new_tokens0 = H2OTextGenerationPipeline.limit_prompt(doc_content, - tokenizer, - max_prompt_length=max_input_tokens) - text_context_list[0] = doc_content - one_doc_size = len(doc_content) - num_doc_tokens = get_token_count(doc_content + docs_joiner_default, tokenizer) - print("Unexpected large chunks and can't add to context, will add 1 anyways. Tokens %s -> %s" % ( - tokens[0], new_tokens0), flush=True) - return top_k_docs, one_doc_size, num_doc_tokens - - -def entrypoint_main(): - """ - Examples: - - WORLD_SIZE=4 CUDA_VISIBLE_DEVICES="0,1,2,3" torchrun --nproc_per_node=4 --master_port=1234 generate.py --base_model='EleutherAI/gpt-j-6B' --lora_weights=lora-alpaca_6B - python generate.py --base_model='EleutherAI/gpt-j-6B' --lora_weights='lora-alpaca_6B' - python generate.py --base_model='EleutherAI/gpt-neox-20b' --lora_weights='lora-alpaca_20B' - - # generate without lora weights, no prompt - python generate.py --base_model='EleutherAI/gpt-neox-20b' --prompt_type='plain' - python generate.py --base_model='togethercomputer/GPT-NeoXT-Chat-Base-20B' --prompt_type='dai_faq' - - python generate.py --base_model='togethercomputer/GPT-NeoXT-Chat-Base-20B' --prompt_type='dai_faq' --lora_weights='lora_20B_daifaq' - # OpenChatKit settings: - python generate.py --base_model='togethercomputer/GPT-NeoXT-Chat-Base-20B' --prompt_type='human_bot --debug=True --num_beams=1 --temperature=0.6 --top_k=40 --top_p=1.0 - - python generate.py --base_model='distilgpt2' --prompt_type='plain' --debug=True --num_beams=1 --temperature=0.6 --top_k=40 --top_p=1.0 --share=False - python generate.py --base_model='t5-large' --prompt_type='simple_instruct' - python generate.py --base_model='philschmid/bart-large-cnn-samsum' - python generate.py --base_model='philschmid/flan-t5-base-samsum' - python generate.py --base_model='facebook/mbart-large-50-many-to-many-mmt' - - python generate.py --base_model='togethercomputer/GPT-NeoXT-Chat-Base-20B' --prompt_type='human_bot' --lora_weights='GPT-NeoXT-Chat-Base-20B.merged.json.8_epochs.57b2892c53df5b8cefac45f84d019cace803ef26.28' - - must have 4*48GB GPU and run without 8bit in order for sharding to work with use_gpu_id=False - can also pass --prompt_type='human_bot' and model can somewhat handle instructions without being instruct tuned - python generate.py --base_model=decapoda-research/llama-65b-hf --load_8bit=False --use_gpu_id=False --prompt_type='human_bot' - - python generate.py --base_model=h2oai/h2ogpt-oig-oasst1-512-6_9b - """ - H2O_Fire(main) - - -if __name__ == "__main__": - entrypoint_main() diff --git a/spaces/avivdm1/AutoGPT/autogpt/utils.py b/spaces/avivdm1/AutoGPT/autogpt/utils.py deleted file mode 100644 index e93d5ac740097ee144d1809aea31c0f7fb242fa5..0000000000000000000000000000000000000000 --- a/spaces/avivdm1/AutoGPT/autogpt/utils.py +++ /dev/null @@ -1,77 +0,0 @@ -import os - -import requests -import yaml -from colorama import Fore -from git import Repo - - -def clean_input(prompt: str = ""): - try: - return input(prompt) - except KeyboardInterrupt: - print("You interrupted Auto-GPT") - print("Quitting...") - exit(0) - - -def validate_yaml_file(file: str): - try: - with open(file, encoding="utf-8") as fp: - yaml.load(fp.read(), Loader=yaml.FullLoader) - except FileNotFoundError: - return (False, f"The file {Fore.CYAN}`{file}`{Fore.RESET} wasn't found") - except yaml.YAMLError as e: - return ( - False, - f"There was an issue while trying to read with your AI Settings file: {e}", - ) - - return (True, f"Successfully validated {Fore.CYAN}`{file}`{Fore.RESET}!") - - -def readable_file_size(size, decimal_places=2): - """Converts the given size in bytes to a readable format. - Args: - size: Size in bytes - decimal_places (int): Number of decimal places to display - """ - for unit in ["B", "KB", "MB", "GB", "TB"]: - if size < 1024.0: - break - size /= 1024.0 - return f"{size:.{decimal_places}f} {unit}" - - -def get_bulletin_from_web() -> str: - try: - response = requests.get( - "https://raw.githubusercontent.com/Significant-Gravitas/Auto-GPT/master/BULLETIN.md" - ) - if response.status_code == 200: - return response.text - except: - return "" - - -def get_current_git_branch() -> str: - try: - repo = Repo(search_parent_directories=True) - branch = repo.active_branch - return branch.name - except: - return "" - - -def get_latest_bulletin() -> str: - exists = os.path.exists("CURRENT_BULLETIN.md") - current_bulletin = "" - if exists: - current_bulletin = open("CURRENT_BULLETIN.md", "r", encoding="utf-8").read() - new_bulletin = get_bulletin_from_web() - is_new_news = new_bulletin != current_bulletin - - if new_bulletin and is_new_news: - open("CURRENT_BULLETIN.md", "w", encoding="utf-8").write(new_bulletin) - return f" {Fore.RED}::UPDATED:: {Fore.CYAN}{new_bulletin}{Fore.RESET}" - return current_bulletin diff --git a/spaces/awacke1/Lightweight-Text-to-Image-Generation/app.py b/spaces/awacke1/Lightweight-Text-to-Image-Generation/app.py deleted file mode 100644 index 013eb709ca99b8cfd58cd470c54641735d59a766..0000000000000000000000000000000000000000 --- a/spaces/awacke1/Lightweight-Text-to-Image-Generation/app.py +++ /dev/null @@ -1,26 +0,0 @@ -#import gradio as gr - -#gr.Interface.load("models/nota-ai/bk-sdm-small").launch() -import gradio as gr - -# List of twenty animals and wildlife native to Minnesota -animals = [ - "White-tailed deer", "Moose", "Bobcat", "Coyote", "Red fox", - "Eastern gray squirrel", "American black bear", "Bald eagle", "Great horned owl", "Wild turkey", - "Canada goose", "Mallard duck", "Eastern bluebird", "Northern pike", "Walleye", - "Common loon", "Snowshoe hare", "Red-tailed hawk", "Beaver", "Eastern chipmunk" -] - -def model_output(animal_name): - # Assuming the model accepts a string as input and returns some information about the animal - model = gr.Interface.load("models/nota-ai/bk-sdm-small") - return model(animal_name)[0] - -interface = gr.Interface( - fn=model_output, # function to call on user input - inputs=gr.inputs.Dropdown(choices=animals, label="Select an Animal"), - outputs="text", - live=True # updates output without needing to click a button -) - -interface.launch() diff --git a/spaces/awacke1/MultiplayerTest2/README.md b/spaces/awacke1/MultiplayerTest2/README.md deleted file mode 100644 index 9541160bb4607b87f44ee7cf98f05a28cc74f323..0000000000000000000000000000000000000000 --- a/spaces/awacke1/MultiplayerTest2/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: MultiplayerTest2 -emoji: 🦀 -colorFrom: yellow -colorTo: purple -sdk: streamlit -sdk_version: 1.25.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/awacke1/chatgpt-demo/app.py b/spaces/awacke1/chatgpt-demo/app.py deleted file mode 100644 index f7258c58657c90b52cd635eae4645503c206e207..0000000000000000000000000000000000000000 --- a/spaces/awacke1/chatgpt-demo/app.py +++ /dev/null @@ -1,138 +0,0 @@ -import gradio as gr -import openai -import requests -import csv - - -prompt_templates = {"Default ChatGPT": ""} - -def get_empty_state(): - return {"total_tokens": 0, "messages": []} - -def download_prompt_templates(): - url = "https://raw.githubusercontent.com/f/awesome-chatgpt-prompts/main/prompts.csv" - try: - response = requests.get(url) - reader = csv.reader(response.text.splitlines()) - next(reader) # skip the header row - for row in reader: - if len(row) >= 2: - act = row[0].strip('"') - prompt = row[1].strip('"') - prompt_templates[act] = prompt - - except requests.exceptions.RequestException as e: - print(f"An error occurred while downloading prompt templates: {e}") - return - - choices = list(prompt_templates.keys()) - choices = choices[:1] + sorted(choices[1:]) - return gr.update(value=choices[0], choices=choices) - -def on_token_change(user_token): - openai.api_key = user_token - -def on_prompt_template_change(prompt_template): - if not isinstance(prompt_template, str): return - return prompt_templates[prompt_template] - -def submit_message(user_token, prompt, prompt_template, temperature, max_tokens, context_length, state): - - history = state['messages'] - - if not prompt: - return gr.update(value=''), [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)], f"Total tokens used: {state['total_tokens']}", state - - prompt_template = prompt_templates[prompt_template] - - system_prompt = [] - if prompt_template: - system_prompt = [{ "role": "system", "content": prompt_template }] - - prompt_msg = { "role": "user", "content": prompt } - - if not user_token: - history.append(prompt_msg) - history.append({ - "role": "system", - "content": "Error: OpenAI API Key is not set." - }) - return '', [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)], f"Total tokens used: 0", state - - try: - completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=system_prompt + history[-context_length*2:] + [prompt_msg], temperature=temperature, max_tokens=max_tokens) - - history.append(prompt_msg) - history.append(completion.choices[0].message.to_dict()) - - state['total_tokens'] += completion['usage']['total_tokens'] - - except Exception as e: - history.append(prompt_msg) - history.append({ - "role": "system", - "content": f"Error: {e}" - }) - - total_tokens_used_msg = f"Total tokens used: {state['total_tokens']}" - chat_messages = [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)] - - return '', chat_messages, total_tokens_used_msg, state - -def clear_conversation(): - return gr.update(value=None, visible=True), None, "", get_empty_state() - - -css = """ - #col-container {max-width: 80%; margin-left: auto; margin-right: auto;} - #chatbox {min-height: 400px;} - #header {text-align: center;} - #prompt_template_preview {padding: 1em; border-width: 1px; border-style: solid; border-color: #e0e0e0; border-radius: 4px;} - #total_tokens_str {text-align: right; font-size: 0.8em; color: #666;} - #label {font-size: 0.8em; padding: 0.5em; margin: 0;} - .message { font-size: 1.2em; } - """ - -with gr.Blocks(css=css) as demo: - - state = gr.State(get_empty_state()) - - - with gr.Column(elem_id="col-container"): - gr.Markdown("""## OpenAI ChatGPT Demo - Using the ofiicial API (gpt-3.5-turbo model) - Prompt templates from [awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts).""", - elem_id="header") - - with gr.Row(): - with gr.Column(): - chatbot = gr.Chatbot(elem_id="chatbox") - input_message = gr.Textbox(show_label=False, placeholder="Enter text and press enter", visible=True).style(container=False) - btn_submit = gr.Button("Submit") - total_tokens_str = gr.Markdown(elem_id="total_tokens_str") - btn_clear_conversation = gr.Button("🔃 Start New Conversation") - with gr.Column(): - gr.Markdown("Enter your OpenAI API Key. You can get one [here](https://platform.openai.com/account/api-keys).", elem_id="label") - user_token = gr.Textbox(value='', placeholder="OpenAI API Key", type="password", show_label=False) - prompt_template = gr.Dropdown(label="Set a custom insruction for the chatbot:", choices=list(prompt_templates.keys())) - prompt_template_preview = gr.Markdown(elem_id="prompt_template_preview") - with gr.Accordion("Advanced parameters", open=False): - temperature = gr.Slider(minimum=0, maximum=2.0, value=0.7, step=0.1, label="Temperature", info="Higher = more creative/chaotic") - max_tokens = gr.Slider(minimum=100, maximum=4096, value=1000, step=1, label="Max tokens per response") - context_length = gr.Slider(minimum=1, maximum=10, value=2, step=1, label="Context length", info="Number of previous messages to send to the chatbot. Be careful with high values, it can blow up the token budget quickly.") - - gr.HTML('''


You can duplicate this Space to skip the queue:Duplicate Space
-

visitors

''') - - btn_submit.click(submit_message, [user_token, input_message, prompt_template, temperature, max_tokens, context_length, state], [input_message, chatbot, total_tokens_str, state]) - input_message.submit(submit_message, [user_token, input_message, prompt_template, temperature, max_tokens, context_length, state], [input_message, chatbot, total_tokens_str, state]) - btn_clear_conversation.click(clear_conversation, [], [input_message, chatbot, total_tokens_str, state]) - prompt_template.change(on_prompt_template_change, inputs=[prompt_template], outputs=[prompt_template_preview]) - user_token.change(on_token_change, inputs=[user_token], outputs=[]) - - - demo.load(download_prompt_templates, inputs=None, outputs=[prompt_template], queur=False) - - -demo.queue(concurrency_count=10) -demo.launch(height='800px') diff --git a/spaces/banana-projects/web3d/node_modules/three/examples/js/objects/Water2.js b/spaces/banana-projects/web3d/node_modules/three/examples/js/objects/Water2.js deleted file mode 100644 index 931b7b59175e704f17a1fa083805c2f6703767ce..0000000000000000000000000000000000000000 --- a/spaces/banana-projects/web3d/node_modules/three/examples/js/objects/Water2.js +++ /dev/null @@ -1,338 +0,0 @@ -/** - * @author Mugen87 / https://github.com/Mugen87 - * - * References: - * http://www.valvesoftware.com/publications/2010/siggraph2010_vlachos_waterflow.pdf - * http://graphicsrunner.blogspot.de/2010/08/water-using-flow-maps.html - * - */ - -THREE.Water = function ( geometry, options ) { - - THREE.Mesh.call( this, geometry ); - - this.type = 'Water'; - - var scope = this; - - options = options || {}; - - var color = ( options.color !== undefined ) ? new THREE.Color( options.color ) : new THREE.Color( 0xFFFFFF ); - var textureWidth = options.textureWidth || 512; - var textureHeight = options.textureHeight || 512; - var clipBias = options.clipBias || 0; - var flowDirection = options.flowDirection || new THREE.Vector2( 1, 0 ); - var flowSpeed = options.flowSpeed || 0.03; - var reflectivity = options.reflectivity || 0.02; - var scale = options.scale || 1; - var shader = options.shader || THREE.Water.WaterShader; - - var textureLoader = new THREE.TextureLoader(); - - var flowMap = options.flowMap || undefined; - var normalMap0 = options.normalMap0 || textureLoader.load( 'textures/water/Water_1_M_Normal.jpg' ); - var normalMap1 = options.normalMap1 || textureLoader.load( 'textures/water/Water_2_M_Normal.jpg' ); - - var cycle = 0.15; // a cycle of a flow map phase - var halfCycle = cycle * 0.5; - var textureMatrix = new THREE.Matrix4(); - var clock = new THREE.Clock(); - - // internal components - - if ( THREE.Reflector === undefined ) { - - console.error( 'THREE.Water: Required component THREE.Reflector not found.' ); - return; - - } - - if ( THREE.Refractor === undefined ) { - - console.error( 'THREE.Water: Required component THREE.Refractor not found.' ); - return; - - } - - var reflector = new THREE.Reflector( geometry, { - textureWidth: textureWidth, - textureHeight: textureHeight, - clipBias: clipBias - } ); - - var refractor = new THREE.Refractor( geometry, { - textureWidth: textureWidth, - textureHeight: textureHeight, - clipBias: clipBias - } ); - - reflector.matrixAutoUpdate = false; - refractor.matrixAutoUpdate = false; - - // material - - this.material = new THREE.ShaderMaterial( { - uniforms: THREE.UniformsUtils.merge( [ - THREE.UniformsLib[ 'fog' ], - shader.uniforms - ] ), - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader, - transparent: true, - fog: true - } ); - - if ( flowMap !== undefined ) { - - this.material.defines.USE_FLOWMAP = ''; - this.material.uniforms[ "tFlowMap" ] = { - type: 't', - value: flowMap - }; - - } else { - - this.material.uniforms[ "flowDirection" ] = { - type: 'v2', - value: flowDirection - }; - - } - - // maps - - normalMap0.wrapS = normalMap0.wrapT = THREE.RepeatWrapping; - normalMap1.wrapS = normalMap1.wrapT = THREE.RepeatWrapping; - - this.material.uniforms[ "tReflectionMap" ].value = reflector.getRenderTarget().texture; - this.material.uniforms[ "tRefractionMap" ].value = refractor.getRenderTarget().texture; - this.material.uniforms[ "tNormalMap0" ].value = normalMap0; - this.material.uniforms[ "tNormalMap1" ].value = normalMap1; - - // water - - this.material.uniforms[ "color" ].value = color; - this.material.uniforms[ "reflectivity" ].value = reflectivity; - this.material.uniforms[ "textureMatrix" ].value = textureMatrix; - - // inital values - - this.material.uniforms[ "config" ].value.x = 0; // flowMapOffset0 - this.material.uniforms[ "config" ].value.y = halfCycle; // flowMapOffset1 - this.material.uniforms[ "config" ].value.z = halfCycle; // halfCycle - this.material.uniforms[ "config" ].value.w = scale; // scale - - // functions - - function updateTextureMatrix( camera ) { - - textureMatrix.set( - 0.5, 0.0, 0.0, 0.5, - 0.0, 0.5, 0.0, 0.5, - 0.0, 0.0, 0.5, 0.5, - 0.0, 0.0, 0.0, 1.0 - ); - - textureMatrix.multiply( camera.projectionMatrix ); - textureMatrix.multiply( camera.matrixWorldInverse ); - textureMatrix.multiply( scope.matrixWorld ); - - } - - function updateFlow() { - - var delta = clock.getDelta(); - var config = scope.material.uniforms[ "config" ]; - - config.value.x += flowSpeed * delta; // flowMapOffset0 - config.value.y = config.value.x + halfCycle; // flowMapOffset1 - - // Important: The distance between offsets should be always the value of "halfCycle". - // Moreover, both offsets should be in the range of [ 0, cycle ]. - // This approach ensures a smooth water flow and avoids "reset" effects. - - if ( config.value.x >= cycle ) { - - config.value.x = 0; - config.value.y = halfCycle; - - } else if ( config.value.y >= cycle ) { - - config.value.y = config.value.y - cycle; - - } - - } - - // - - this.onBeforeRender = function ( renderer, scene, camera ) { - - updateTextureMatrix( camera ); - updateFlow(); - - scope.visible = false; - - reflector.matrixWorld.copy( scope.matrixWorld ); - refractor.matrixWorld.copy( scope.matrixWorld ); - - reflector.onBeforeRender( renderer, scene, camera ); - refractor.onBeforeRender( renderer, scene, camera ); - - scope.visible = true; - - }; - -}; - -THREE.Water.prototype = Object.create( THREE.Mesh.prototype ); -THREE.Water.prototype.constructor = THREE.Water; - -THREE.Water.WaterShader = { - - uniforms: { - - 'color': { - type: 'c', - value: null - }, - - 'reflectivity': { - type: 'f', - value: 0 - }, - - 'tReflectionMap': { - type: 't', - value: null - }, - - 'tRefractionMap': { - type: 't', - value: null - }, - - 'tNormalMap0': { - type: 't', - value: null - }, - - 'tNormalMap1': { - type: 't', - value: null - }, - - 'textureMatrix': { - type: 'm4', - value: null - }, - - 'config': { - type: 'v4', - value: new THREE.Vector4() - } - - }, - - vertexShader: [ - - '#include ', - - 'uniform mat4 textureMatrix;', - - 'varying vec4 vCoord;', - 'varying vec2 vUv;', - 'varying vec3 vToEye;', - - 'void main() {', - - ' vUv = uv;', - ' vCoord = textureMatrix * vec4( position, 1.0 );', - - ' vec4 worldPosition = modelMatrix * vec4( position, 1.0 );', - ' vToEye = cameraPosition - worldPosition.xyz;', - - ' vec4 mvPosition = viewMatrix * worldPosition;', // used in fog_vertex - ' gl_Position = projectionMatrix * mvPosition;', - - ' #include ', - - '}' - - ].join( '\n' ), - - fragmentShader: [ - - '#include ', - '#include ', - - 'uniform sampler2D tReflectionMap;', - 'uniform sampler2D tRefractionMap;', - 'uniform sampler2D tNormalMap0;', - 'uniform sampler2D tNormalMap1;', - - '#ifdef USE_FLOWMAP', - ' uniform sampler2D tFlowMap;', - '#else', - ' uniform vec2 flowDirection;', - '#endif', - - 'uniform vec3 color;', - 'uniform float reflectivity;', - 'uniform vec4 config;', - - 'varying vec4 vCoord;', - 'varying vec2 vUv;', - 'varying vec3 vToEye;', - - 'void main() {', - - ' float flowMapOffset0 = config.x;', - ' float flowMapOffset1 = config.y;', - ' float halfCycle = config.z;', - ' float scale = config.w;', - - ' vec3 toEye = normalize( vToEye );', - - // determine flow direction - ' vec2 flow;', - ' #ifdef USE_FLOWMAP', - ' flow = texture2D( tFlowMap, vUv ).rg * 2.0 - 1.0;', - ' #else', - ' flow = flowDirection;', - ' #endif', - ' flow.x *= - 1.0;', - - // sample normal maps (distort uvs with flowdata) - ' vec4 normalColor0 = texture2D( tNormalMap0, ( vUv * scale ) + flow * flowMapOffset0 );', - ' vec4 normalColor1 = texture2D( tNormalMap1, ( vUv * scale ) + flow * flowMapOffset1 );', - - // linear interpolate to get the final normal color - ' float flowLerp = abs( halfCycle - flowMapOffset0 ) / halfCycle;', - ' vec4 normalColor = mix( normalColor0, normalColor1, flowLerp );', - - // calculate normal vector - ' vec3 normal = normalize( vec3( normalColor.r * 2.0 - 1.0, normalColor.b, normalColor.g * 2.0 - 1.0 ) );', - - // calculate the fresnel term to blend reflection and refraction maps - ' float theta = max( dot( toEye, normal ), 0.0 );', - ' float reflectance = reflectivity + ( 1.0 - reflectivity ) * pow( ( 1.0 - theta ), 5.0 );', - - // calculate final uv coords - ' vec3 coord = vCoord.xyz / vCoord.w;', - ' vec2 uv = coord.xy + coord.z * normal.xz * 0.05;', - - ' vec4 reflectColor = texture2D( tReflectionMap, vec2( 1.0 - uv.x, uv.y ) );', - ' vec4 refractColor = texture2D( tRefractionMap, uv );', - - // multiply water color with the mix of both textures - ' gl_FragColor = vec4( color, 1.0 ) * mix( refractColor, reflectColor, reflectance );', - - ' #include ', - ' #include ', - ' #include ', - - '}' - - ].join( '\n' ) -}; diff --git a/spaces/bingbing520/ChatGPT2/chatgpt - windows.bat b/spaces/bingbing520/ChatGPT2/chatgpt - windows.bat deleted file mode 100644 index 0b78fdc3a559abd692e3a9e9af5e482124d13a99..0000000000000000000000000000000000000000 --- a/spaces/bingbing520/ChatGPT2/chatgpt - windows.bat +++ /dev/null @@ -1,14 +0,0 @@ -@echo off -echo Opening ChuanhuChatGPT... - -REM Open powershell via bat -start powershell.exe -NoExit -Command "python ./ChuanhuChatbot.py" - -REM The web page can be accessed with delayed start http://127.0.0.1:7860/ -ping -n 5 127.0.0.1>nul - -REM access chargpt via your default browser -start "" "http://127.0.0.1:7860/" - - -echo Finished opening ChuanhuChatGPT (http://127.0.0.1:7860/). \ No newline at end of file diff --git a/spaces/bino-ocle/audio-intelligence-dash/app/conf/__init__.py b/spaces/bino-ocle/audio-intelligence-dash/app/conf/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/bioriAsaeru/text-to-voice/CopyTrans Suite 4.72 KeyGen [Team-FFF] - How to Manage Your iOS Devices Easily and Safely.md b/spaces/bioriAsaeru/text-to-voice/CopyTrans Suite 4.72 KeyGen [Team-FFF] - How to Manage Your iOS Devices Easily and Safely.md deleted file mode 100644 index 53bee26bb5c6a1679c5f7fd4b23fc03a714d30a0..0000000000000000000000000000000000000000 --- a/spaces/bioriAsaeru/text-to-voice/CopyTrans Suite 4.72 KeyGen [Team-FFF] - How to Manage Your iOS Devices Easily and Safely.md +++ /dev/null @@ -1,6 +0,0 @@ -

CopyTrans Suite 4.72 KeyGen [Team-FFF]


Downloadhttps://urloso.com/2uyOr5



- - aaccfb2cb3
-
-
-

diff --git a/spaces/bioriAsaeru/text-to-voice/Far Cry 3 Nude Mod _VERIFIED_.md b/spaces/bioriAsaeru/text-to-voice/Far Cry 3 Nude Mod _VERIFIED_.md deleted file mode 100644 index afb17770376993ab3af8bf28b276b63485c67134..0000000000000000000000000000000000000000 --- a/spaces/bioriAsaeru/text-to-voice/Far Cry 3 Nude Mod _VERIFIED_.md +++ /dev/null @@ -1,6 +0,0 @@ -

Far Cry 3 Nude Mod


DOWNLOAD · https://urloso.com/2uyPFV



-
- d5da3c52bf
-
-
-

diff --git a/spaces/bioriAsaeru/text-to-voice/Lame V3.98.3 For Audacity On Windows.md b/spaces/bioriAsaeru/text-to-voice/Lame V3.98.3 For Audacity On Windows.md deleted file mode 100644 index 51eb28fa9be1f7df808004ef92ed0c0a48785d9c..0000000000000000000000000000000000000000 --- a/spaces/bioriAsaeru/text-to-voice/Lame V3.98.3 For Audacity On Windows.md +++ /dev/null @@ -1,10 +0,0 @@ -
-

select lame3.exe and enter-q23.wav input_wave.wav output_wave.wav. then hit '' and '' to continue. repeat for each input file you wish to encode and each desired output-and save it to desktop. see the examples in the lame manual for additional information.

-

select lame3.exe and enter-q23.wav input_wave.wav output_wave.wav. then hit '' and '' to continue. repeat for each input file you wish to encode and each desired output-and save it to desktop. see the examples in the lame manual for additional information.

-

Lame v3.98.3 for Audacity on Windows


Download File · https://urloso.com/2uyRWj



-

the ''-lh''''switch uses the new wave format from itu-t recommendation g.726 and g.721
the ''-v'' switch set the sample rate to 16 bit (native), channels to 2 (mono)
the ''-y'' switch uses ''-_01 -3'' format flags, i.e. bitrate is 1 kbit, frame size is 3200
the ''-z'' switch set the quality (''normal'') to the default settings

-

note that you can also use the ''-vv '' parameter. if the original source file does not start with a multibyte character (e.g. wav files are encoded in 8-bit mode) you need to specify the ''-b'' switch too. the video is then encoded in 16-bit linear pcm. e.
:

-

the ''-i'' switch specifies that the input file is in wav/aiff/au/svx file format. if there is no ''-i'' switch, the input file is assumed to be in pcm format. the aiff and svx structure is similar, with the binary format being the only difference.

-

a common thing is to make a copy of an existing audio file as a test file. on my machine the output duration is correct but the sample rate is wrong. the problem is that a copy of an existing wav file has its sample rate set to ''44.1'' by default. to solve the problem, you must specify the new sample rate to the output audio stream with the ''-r'' switch:

899543212b
-
-
\ No newline at end of file diff --git a/spaces/bla/tranny/App/Embedding/EmbeddingRoutes.py b/spaces/bla/tranny/App/Embedding/EmbeddingRoutes.py deleted file mode 100644 index 5d038d9f001d027060bc20b66435685cc23b3a88..0000000000000000000000000000000000000000 --- a/spaces/bla/tranny/App/Embedding/EmbeddingRoutes.py +++ /dev/null @@ -1,34 +0,0 @@ -from fastapi import APIRouter -from App.Transcription.Model import Transcriptions -from .utils.Initialize import generateChunks, encode, search -from .Schemas import SearchRequest - -embeddigs_router = APIRouter(tags=["embeddings"]) - - -# create -@embeddigs_router.get("/create_embeddings") -async def create_embeddings(task_id): - item = await Transcriptions.objects.filter(task_id=task_id).first() - temp = item.content - chunks = generateChunks(temp, task_id) - encode(chunks) - - return - - -@embeddigs_router.get("/create_summary") -async def create_summary(task_id): - item = await Transcriptions.objects.filter(task_id=task_id).first() - temp = item.content - chunks = generateChunks(temp, task_id) - encode(chunks) - - return - - -# search -# update? -@embeddigs_router.post("/search_embeddings") -async def search_embeddings(req: SearchRequest): - return search(query=req.query, task_id=req.taskId) diff --git a/spaces/bortle/moon-detector/app.py b/spaces/bortle/moon-detector/app.py deleted file mode 100644 index 3f4cdcb7ab2be42b74b54e81eaae7d1c85c06e20..0000000000000000000000000000000000000000 --- a/spaces/bortle/moon-detector/app.py +++ /dev/null @@ -1,16 +0,0 @@ -import gradio as gr -from transformers import pipeline - -pipeline = pipeline(task="image-classification", model="bortle/moon-detector-v5.a") - -def predict(image): - predictions = pipeline(image) - return {p["label"]: p["score"] for p in predictions} - -gr.Interface( - predict, - inputs=gr.Image(shape=(1080, None), type="pil", label="Upload image"), - outputs=gr.Label(num_top_classes=5), - title="Moon Detector", - allow_flagging="manual", -).launch() \ No newline at end of file diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/tests/test_packaging.py b/spaces/brjathu/HMR2.0/vendor/detectron2/tests/test_packaging.py deleted file mode 100644 index a5b1661e8f341fe66a6e02c59fe172bce445782b..0000000000000000000000000000000000000000 --- a/spaces/brjathu/HMR2.0/vendor/detectron2/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/bulentsofttech/gradio_s1000_veri_toplama_modeli/yolov5/utils/augmentations.py b/spaces/bulentsofttech/gradio_s1000_veri_toplama_modeli/yolov5/utils/augmentations.py deleted file mode 100644 index 3f764c06ae3b366496230bcba63c5e8621ce1c95..0000000000000000000000000000000000000000 --- a/spaces/bulentsofttech/gradio_s1000_veri_toplama_modeli/yolov5/utils/augmentations.py +++ /dev/null @@ -1,284 +0,0 @@ -# YOLOv5 🚀 by Ultralytics, GPL-3.0 license -""" -Image augmentation functions -""" - -import math -import random - -import cv2 -import numpy as np - -from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box -from utils.metrics import bbox_ioa - - -class Albumentations: - # YOLOv5 Albumentations class (optional, only used if package is installed) - def __init__(self): - self.transform = None - try: - import albumentations as A - check_version(A.__version__, '1.0.3', hard=True) # version requirement - - T = [ - A.Blur(p=0.01), - A.MedianBlur(p=0.01), - A.ToGray(p=0.01), - A.CLAHE(p=0.01), - A.RandomBrightnessContrast(p=0.0), - A.RandomGamma(p=0.0), - A.ImageCompression(quality_lower=75, p=0.0)] # transforms - self.transform = A.Compose(T, bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels'])) - - LOGGER.info(colorstr('albumentations: ') + ', '.join(f'{x}' for x in self.transform.transforms if x.p)) - except ImportError: # package not installed, skip - pass - except Exception as e: - LOGGER.info(colorstr('albumentations: ') + f'{e}') - - def __call__(self, im, labels, p=1.0): - if self.transform and random.random() < p: - new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed - im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])]) - return im, labels - - -def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5): - # HSV color-space augmentation - if hgain or sgain or vgain: - r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains - hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV)) - dtype = im.dtype # uint8 - - x = np.arange(0, 256, dtype=r.dtype) - lut_hue = ((x * r[0]) % 180).astype(dtype) - lut_sat = np.clip(x * r[1], 0, 255).astype(dtype) - lut_val = np.clip(x * r[2], 0, 255).astype(dtype) - - im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))) - cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im) # no return needed - - -def hist_equalize(im, clahe=True, bgr=False): - # Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-255 - yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV) - if clahe: - c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) - yuv[:, :, 0] = c.apply(yuv[:, :, 0]) - else: - yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram - return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB - - -def replicate(im, labels): - # Replicate labels - h, w = im.shape[:2] - boxes = labels[:, 1:].astype(int) - x1, y1, x2, y2 = boxes.T - s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels) - for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices - x1b, y1b, x2b, y2b = boxes[i] - bh, bw = y2b - y1b, x2b - x1b - yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y - x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh] - im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b] # im4[ymin:ymax, xmin:xmax] - labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0) - - return im, labels - - -def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32): - # Resize and pad image while meeting stride-multiple constraints - shape = im.shape[:2] # current shape [height, width] - if isinstance(new_shape, int): - new_shape = (new_shape, new_shape) - - # Scale ratio (new / old) - r = min(new_shape[0] / shape[0], new_shape[1] / shape[1]) - if not scaleup: # only scale down, do not scale up (for better val mAP) - r = min(r, 1.0) - - # Compute padding - ratio = r, r # width, height ratios - new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r)) - dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding - if auto: # minimum rectangle - dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding - elif scaleFill: # stretch - dw, dh = 0.0, 0.0 - new_unpad = (new_shape[1], new_shape[0]) - ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios - - dw /= 2 # divide padding into 2 sides - dh /= 2 - - if shape[::-1] != new_unpad: # resize - im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR) - top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1)) - left, right = int(round(dw - 0.1)), int(round(dw + 0.1)) - im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border - return im, ratio, (dw, dh) - - -def random_perspective(im, - targets=(), - segments=(), - degrees=10, - translate=.1, - scale=.1, - shear=10, - perspective=0.0, - border=(0, 0)): - # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10)) - # targets = [cls, xyxy] - - height = im.shape[0] + border[0] * 2 # shape(h,w,c) - width = im.shape[1] + border[1] * 2 - - # Center - C = np.eye(3) - C[0, 2] = -im.shape[1] / 2 # x translation (pixels) - C[1, 2] = -im.shape[0] / 2 # y translation (pixels) - - # Perspective - P = np.eye(3) - P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y) - P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x) - - # Rotation and Scale - R = np.eye(3) - a = random.uniform(-degrees, degrees) - # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations - s = random.uniform(1 - scale, 1 + scale) - # s = 2 ** random.uniform(-scale, scale) - R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s) - - # Shear - S = np.eye(3) - S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg) - S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg) - - # Translation - T = np.eye(3) - T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels) - T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels) - - # Combined rotation matrix - M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT - if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed - if perspective: - im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114)) - else: # affine - im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114)) - - # Visualize - # import matplotlib.pyplot as plt - # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel() - # ax[0].imshow(im[:, :, ::-1]) # base - # ax[1].imshow(im2[:, :, ::-1]) # warped - - # Transform label coordinates - n = len(targets) - if n: - use_segments = any(x.any() for x in segments) - new = np.zeros((n, 4)) - if use_segments: # warp segments - segments = resample_segments(segments) # upsample - for i, segment in enumerate(segments): - xy = np.ones((len(segment), 3)) - xy[:, :2] = segment - xy = xy @ M.T # transform - xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine - - # clip - new[i] = segment2box(xy, width, height) - - else: # warp boxes - xy = np.ones((n * 4, 3)) - xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1 - xy = xy @ M.T # transform - xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine - - # create new boxes - x = xy[:, [0, 2, 4, 6]] - y = xy[:, [1, 3, 5, 7]] - new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T - - # clip - new[:, [0, 2]] = new[:, [0, 2]].clip(0, width) - new[:, [1, 3]] = new[:, [1, 3]].clip(0, height) - - # filter candidates - i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10) - targets = targets[i] - targets[:, 1:5] = new[i] - - return im, targets - - -def copy_paste(im, labels, segments, p=0.5): - # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy) - n = len(segments) - if p and n: - h, w, c = im.shape # height, width, channels - im_new = np.zeros(im.shape, np.uint8) - for j in random.sample(range(n), k=round(p * n)): - l, s = labels[j], segments[j] - box = w - l[3], l[2], w - l[1], l[4] - ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area - if (ioa < 0.30).all(): # allow 30% obscuration of existing labels - labels = np.concatenate((labels, [[l[0], *box]]), 0) - segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1)) - cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED) - - result = cv2.bitwise_and(src1=im, src2=im_new) - result = cv2.flip(result, 1) # augment segments (flip left-right) - i = result > 0 # pixels to replace - # i[:, :] = result.max(2).reshape(h, w, 1) # act over ch - im[i] = result[i] # cv2.imwrite('debug.jpg', im) # debug - - return im, labels, segments - - -def cutout(im, labels, p=0.5): - # Applies image cutout augmentation https://arxiv.org/abs/1708.04552 - if random.random() < p: - h, w = im.shape[:2] - scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction - for s in scales: - mask_h = random.randint(1, int(h * s)) # create random masks - mask_w = random.randint(1, int(w * s)) - - # box - xmin = max(0, random.randint(0, w) - mask_w // 2) - ymin = max(0, random.randint(0, h) - mask_h // 2) - xmax = min(w, xmin + mask_w) - ymax = min(h, ymin + mask_h) - - # apply random color mask - im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)] - - # return unobscured labels - if len(labels) and s > 0.03: - box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32) - ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area - labels = labels[ioa < 0.60] # remove >60% obscured labels - - return labels - - -def mixup(im, labels, im2, labels2): - # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf - r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0 - im = (im * r + im2 * (1 - r)).astype(np.uint8) - labels = np.concatenate((labels, labels2), 0) - return im, labels - - -def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n) - # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio - w1, h1 = box1[2] - box1[0], box1[3] - box1[1] - w2, h2 = box2[2] - box2[0], box2[3] - box2[1] - ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio - return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates diff --git a/spaces/camenduru-com/audioldm-text-to-audio-generation/audioldm/latent_diffusion/ddim.py b/spaces/camenduru-com/audioldm-text-to-audio-generation/audioldm/latent_diffusion/ddim.py deleted file mode 100644 index 57ee8d302c77cb09bd73ef803ef9e715098feafc..0000000000000000000000000000000000000000 --- a/spaces/camenduru-com/audioldm-text-to-audio-generation/audioldm/latent_diffusion/ddim.py +++ /dev/null @@ -1,377 +0,0 @@ -"""SAMPLING ONLY.""" - -import torch -import numpy as np -from tqdm import tqdm - -from audioldm.latent_diffusion.util import ( - make_ddim_sampling_parameters, - make_ddim_timesteps, - noise_like, - extract_into_tensor, -) -import gradio as gr - -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.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.0 - alphas_cumprod.cpu())), - ) - self.register_buffer( - "log_one_minus_alphas_cumprod", to_torch(np.log(1.0 - alphas_cumprod.cpu())) - ) - self.register_buffer( - "sqrt_recip_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod.cpu())) - ) - self.register_buffer( - "sqrt_recipm1_alphas_cumprod", - to_torch(np.sqrt(1.0 / 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.0 - 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.0, - mask=None, - x0=None, - temperature=1.0, - noise_dropout=0.0, - score_corrector=None, - corrector_kwargs=None, - verbose=True, - x_T=None, - log_every_t=100, - unconditional_guidance_scale=1.0, - 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) - 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.0, - noise_dropout=0.0, - score_corrector=None, - corrector_kwargs=None, - unconditional_guidance_scale=1.0, - 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 = gr.Progress().tqdm(time_range, desc="DDIM Sampler", total=total_steps) - 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.0 - mask) * img - ) # In the first sampling step, img is pure gaussian noise - - 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 stochastic_encode(self, x0, t, use_original_steps=False, noise=None): - # fast, but does not allow for exact reconstruction - # t serves as an index to gather the correct alphas - if use_original_steps: - sqrt_alphas_cumprod = self.sqrt_alphas_cumprod - sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod - else: - sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas) - sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas - - if noise is None: - noise = torch.randn_like(x0) - - return ( - extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 - + extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise - ) - - @torch.no_grad() - def decode( - self, - x_latent, - cond, - t_start, - unconditional_guidance_scale=1.0, - unconditional_conditioning=None, - use_original_steps=False, - ): - - timesteps = ( - np.arange(self.ddpm_num_timesteps) - if use_original_steps - else self.ddim_timesteps - ) - timesteps = timesteps[:t_start] - - time_range = np.flip(timesteps) - total_steps = timesteps.shape[0] - # print(f"Running DDIM Sampling with {total_steps} timesteps") - - # iterator = gr.Progress().tqdm(time_range, desc="Decoding image", total=total_steps) - iterator = tqdm(time_range, desc="Decoding image", total=total_steps) - x_dec = x_latent - - for i, step in enumerate(iterator): - index = total_steps - i - 1 - ts = torch.full( - (x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long - ) - x_dec, _ = self.p_sample_ddim( - x_dec, - cond, - ts, - index=index, - use_original_steps=use_original_steps, - unconditional_guidance_scale=unconditional_guidance_scale, - unconditional_conditioning=unconditional_conditioning, - ) - return x_dec - - @torch.no_grad() - def p_sample_ddim( - self, - x, - c, - t, - index, - repeat_noise=False, - use_original_steps=False, - quantize_denoised=False, - temperature=1.0, - noise_dropout=0.0, - score_corrector=None, - corrector_kwargs=None, - unconditional_guidance_scale=1.0, - unconditional_conditioning=None, - ): - b, *_, device = *x.shape, x.device - - if unconditional_conditioning is None or unconditional_guidance_scale == 1.0: - 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) - # When unconditional_guidance_scale == 1: only e_t - # When unconditional_guidance_scale == 0: only unconditional - # When unconditional_guidance_scale > 1: add more unconditional guidance - 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.0 - a_prev - sigma_t**2).sqrt() * e_t - noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature - if noise_dropout > 0.0: - noise = torch.nn.functional.dropout(noise, p=noise_dropout) - x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise # TODO - return x_prev, pred_x0 diff --git a/spaces/carlosalonso/Detection-video/carpeta_deteccion/detectron2/data/__init__.py b/spaces/carlosalonso/Detection-video/carpeta_deteccion/detectron2/data/__init__.py deleted file mode 100644 index 259f669b78bd05815cb8d3351fd6c5fc9a1b85a1..0000000000000000000000000000000000000000 --- a/spaces/carlosalonso/Detection-video/carpeta_deteccion/detectron2/data/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -from . import transforms # isort:skip - -from .build import ( - build_batch_data_loader, - build_detection_test_loader, - build_detection_train_loader, - get_detection_dataset_dicts, - load_proposals_into_dataset, - print_instances_class_histogram, -) -from .catalog import DatasetCatalog, MetadataCatalog, Metadata -from .common import DatasetFromList, MapDataset, ToIterableDataset -from .dataset_mapper import DatasetMapper - -# ensure the builtin datasets are registered -from . import datasets, samplers # isort:skip - -__all__ = [k for k in globals().keys() if not k.startswith("_")] diff --git a/spaces/carlosalonso/Detection-video/carpeta_deteccion/tests/structures/test_imagelist.py b/spaces/carlosalonso/Detection-video/carpeta_deteccion/tests/structures/test_imagelist.py deleted file mode 100644 index e446e44a37f5d8f9a68362e4b93a291d314d5d68..0000000000000000000000000000000000000000 --- a/spaces/carlosalonso/Detection-video/carpeta_deteccion/tests/structures/test_imagelist.py +++ /dev/null @@ -1,75 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. - -import unittest -from typing import List, Sequence, Tuple -import torch - -from detectron2.structures import ImageList - - -class TestImageList(unittest.TestCase): - def test_imagelist_padding_tracing(self): - # test that the trace does not contain hard-coded constant sizes - def to_imagelist(tensors: Sequence[torch.Tensor]): - image_list = ImageList.from_tensors(tensors, 4) - return image_list.tensor, image_list.image_sizes - - def _tensor(*shape): - return torch.ones(shape, dtype=torch.float32) - - # test CHW (inputs needs padding vs. no padding) - for shape in [(3, 10, 10), (3, 12, 12)]: - func = torch.jit.trace(to_imagelist, ([_tensor(*shape)],)) - tensor, image_sizes = func([_tensor(3, 15, 20)]) - self.assertEqual(tensor.shape, (1, 3, 16, 20), tensor.shape) - self.assertEqual(image_sizes[0].tolist(), [15, 20], image_sizes[0]) - - # test HW - func = torch.jit.trace(to_imagelist, ([_tensor(10, 10)],)) - tensor, image_sizes = func([_tensor(15, 20)]) - self.assertEqual(tensor.shape, (1, 16, 20), tensor.shape) - self.assertEqual(image_sizes[0].tolist(), [15, 20], image_sizes[0]) - - # test 2x CHW - func = torch.jit.trace( - to_imagelist, - ([_tensor(3, 16, 10), _tensor(3, 13, 11)],), - ) - tensor, image_sizes = func([_tensor(3, 25, 20), _tensor(3, 10, 10)]) - self.assertEqual(tensor.shape, (2, 3, 28, 20), tensor.shape) - self.assertEqual(image_sizes[0].tolist(), [25, 20], image_sizes[0]) - self.assertEqual(image_sizes[1].tolist(), [10, 10], image_sizes[1]) - # support calling with different spatial sizes, but not with different #images - - def test_imagelist_scriptability(self): - image_nums = 2 - image_tensor = torch.randn((image_nums, 10, 20), dtype=torch.float32) - image_shape = [(10, 20)] * image_nums - - def f(image_tensor, image_shape: List[Tuple[int, int]]): - return ImageList(image_tensor, image_shape) - - ret = f(image_tensor, image_shape) - ret_script = torch.jit.script(f)(image_tensor, image_shape) - - self.assertEqual(len(ret), len(ret_script)) - for i in range(image_nums): - self.assertTrue(torch.equal(ret[i], ret_script[i])) - - def test_imagelist_from_tensors_scriptability(self): - image_tensor_0 = torch.randn(10, 20, dtype=torch.float32) - image_tensor_1 = torch.randn(12, 22, dtype=torch.float32) - inputs = [image_tensor_0, image_tensor_1] - - def f(image_tensor: List[torch.Tensor]): - return ImageList.from_tensors(image_tensor, 10) - - ret = f(inputs) - ret_script = torch.jit.script(f)(inputs) - - self.assertEqual(len(ret), len(ret_script)) - self.assertTrue(torch.equal(ret.tensor, ret_script.tensor)) - - -if __name__ == "__main__": - unittest.main() diff --git a/spaces/ccolas/TastyPiano/src/music/pipeline/processed2handcodedrep.py b/spaces/ccolas/TastyPiano/src/music/pipeline/processed2handcodedrep.py deleted file mode 100644 index 0f752d4d36988d3734127fdd8519cd24a039e4ad..0000000000000000000000000000000000000000 --- a/spaces/ccolas/TastyPiano/src/music/pipeline/processed2handcodedrep.py +++ /dev/null @@ -1,343 +0,0 @@ -import numpy as np -from music21 import * -from music21.features import native, jSymbolic, DataSet -import pretty_midi as pm -from src.music.utils import get_out_path -from src.music.utilities.handcoded_rep_utilities.tht import tactus_hypothesis_tracker, tracker_analysis -from src.music.utilities.handcoded_rep_utilities.loudness import get_loudness, compute_total_loudness, amplitude2db, velocity2amplitude, get_db_of_equivalent_loudness_at_440hz, pitch2freq -import json -import os -environment.set('musicxmlPath', '/home/cedric/Desktop/test/') -midi_path = "/home/cedric/Documents/pianocktail/data/music/processed/doug_mckenzie_processed/allthethings_reharmonized_processed.mid" - -FEATURES_DICT_SCORE = dict( - # strongest pulse: measures how fast the melody is - # stronger_pulse=jSymbolic.StrongestRhythmicPulseFeature, - # weights of the two strongest pulse, measures rhythmic consistency: https://web.mit.edu/music21/doc/moduleReference/moduleFeaturesJSymbolic.html#combinedstrengthoftwostrongestrhythmicpulsesfeature - pulse_strength_two=jSymbolic.CombinedStrengthOfTwoStrongestRhythmicPulsesFeature, - # weights of the strongest pulse, measures rhythmic consistency: https://web.mit.edu/music21/doc/moduleReference/moduleFeaturesJSymbolic.html#combinedstrengthoftwostrongestrhythmicpulsesfeature - pulse_strength = jSymbolic.StrengthOfStrongestRhythmicPulseFeature, - # variability of attacks: https://web.mit.edu/music21/doc/moduleReference/moduleFeaturesJSymbolic.html#variabilityoftimebetweenattacksfeature - -) -FEATURES_DICT = dict( - # bass register importance: https://web.mit.edu/music21/doc/moduleReference/moduleFeaturesJSymbolic.html#importanceofbassregisterfeature - # bass_register=jSymbolic.ImportanceOfBassRegisterFeature, - # high register importance: https://web.mit.edu/music21/doc/moduleReference/moduleFeaturesJSymbolic.html#importanceofbassregisterfeature - # high_register=jSymbolic.ImportanceOfHighRegisterFeature, - # medium register importance: https://web.mit.edu/music21/doc/moduleReference/moduleFeaturesJSymbolic.html#importanceofbassregisterfeature - # medium_register=jSymbolic.ImportanceOfMiddleRegisterFeature, - # number of common pitches (at least 9% of all): https://web.mit.edu/music21/doc/moduleReference/moduleFeaturesJSymbolic.html#numberofcommonmelodicintervalsfeature - # common_pitches=jSymbolic.NumberOfCommonPitchesFeature, - # pitch class variety (used at least once): https://web.mit.edu/music21/doc/moduleReference/moduleFeaturesJSymbolic.html#pitchvarietyfeature - # pitch_variety=jSymbolic.PitchVarietyFeature, - # attack_variability = jSymbolic.VariabilityOfTimeBetweenAttacksFeature, - # staccato fraction: https://web.mit.edu/music21/doc/moduleReference/moduleFeaturesJSymbolic.html#staccatoincidencefeature - # staccato_score = jSymbolic.StaccatoIncidenceFeature, - # mode analysis: https://web.mit.edu/music21/doc/moduleReference/moduleFeaturesNative.html - av_melodic_interval = jSymbolic.AverageMelodicIntervalFeature, - # chromatic motion: https://web.mit.edu/music21/doc/moduleReference/moduleFeaturesJSymbolic.html#chromaticmotionfeature - chromatic_motion = jSymbolic.ChromaticMotionFeature, - # direction of motion (fraction of rising intervals: https://web.mit.edu/music21/doc/moduleReference/moduleFeaturesJSymbolic.html#directionofmotionfeature - motion_direction = jSymbolic.DirectionOfMotionFeature, - # duration of melodic arcs: https://web.mit.edu/music21/doc/moduleReference/moduleFeaturesJSymbolic.html#durationofmelodicarcsfeature - melodic_arcs_duration = jSymbolic.DurationOfMelodicArcsFeature, - # melodic arcs size: https://web.mit.edu/music21/doc/moduleReference/moduleFeaturesJSymbolic.html#sizeofmelodicarcsfeature - melodic_arcs_size = jSymbolic.SizeOfMelodicArcsFeature, - # number of common melodic interval (at least 9% of all): https://web.mit.edu/music21/doc/moduleReference/moduleFeaturesJSymbolic.html#numberofcommonmelodicintervalsfeature - # common_melodic_intervals = jSymbolic.NumberOfCommonMelodicIntervalsFeature, - # https://web.mit.edu/music21/doc/moduleReference/moduleFeaturesJSymbolic.html#amountofarpeggiationfeature - # arpeggiato=jSymbolic.AmountOfArpeggiationFeature, -) - - - - - - -def compute_beat_info(onsets): - onsets_in_ms = np.array(onsets) * 1000 - - tht = tactus_hypothesis_tracker.default_tht() - trackers = tht(onsets_in_ms) - top_hts = tracker_analysis.top_hypothesis(trackers, len(onsets_in_ms)) - beats = tracker_analysis.produce_beats_information(onsets_in_ms, top_hts, adapt_period=250 is not None, - adapt_phase=tht.eval_f, max_delta_bpm=250, avoid_quickturns=None) - tempo = 1 / (np.mean(np.diff(beats)) / 1000) * 60 # in bpm - conf_values = tracker_analysis.tht_tracking_confs(trackers, len(onsets_in_ms)) - pulse_clarity = np.mean(np.array(conf_values), axis=0)[1] - return tempo, pulse_clarity - -def dissonance_score(A): - """ - Given a piano-roll indicator matrix representation of a musical work (128 pitches x beats), - return the dissonance as a function of beats. - Input: - A - 128 x beats indicator matrix of MIDI pitch number - - """ - freq_rats = np.arange(1, 7) # Harmonic series ratios - amps = np.exp(-.5 * freq_rats) # Partial amplitudes - F0 = 8.1757989156 # base frequency for MIDI (note 0) - diss = [] # List for dissonance values - thresh = 1e-3 - for beat in A.T: - idx = np.where(beat>thresh)[0] - if len(idx): - freqs, mags = [], [] # lists for frequencies, mags - for i in idx: - freqs.extend(F0*2**(i/12.0)*freq_rats) - mags.extend(amps) - freqs = np.array(freqs) - mags = np.array(mags) - sortIdx = freqs.argsort() - d = compute_dissonance(freqs[sortIdx],mags[sortIdx]) - diss.extend([d]) - else: - diss.extend([-1]) # Null value - diss = np.array(diss) - return diss[np.where(diss != -1)] - -def compute_dissonance(freqs, amps): - """ - From https://notebook.community/soundspotter/consonance/week1_consonance - Compute dissonance between partials with center frequencies in freqs, uses a model of critical bandwidth. - and amplitudes in amps. Based on Sethares "Tuning, Timbre, Spectrum, Scale" (1998) after Plomp and Levelt (1965) - - inputs: - freqs - list of partial frequencies - amps - list of corresponding amplitudes [default, uniformly 1] - """ - b1, b2, s1, s2, c1, c2, Dstar = (-3.51, -5.75, 0.0207, 19.96, 5, -5, 0.24) - f = np.array(freqs) - a = np.array(amps) - idx = np.argsort(f) - f = f[idx] - a = a[idx] - N = f.size - D = 0 - for i in range(1, N): - Fmin = f[ 0 : N - i ] - S = Dstar / ( s1 * Fmin + s2) - Fdif = f[ i : N ] - f[ 0 : N - i ] - am = a[ i : N ] * a[ 0 : N - i ] - Dnew = am * (c1 * np.exp (b1 * S * Fdif) + c2 * np.exp(b2 * S * Fdif)) - D += Dnew.sum() - return D - - - - -def store_new_midi(notes, out_path): - midi = pm.PrettyMIDI() - midi.instruments.append(pm.Instrument(program=0, is_drum=False)) - midi.instruments[0].notes = notes - midi.write(out_path) - return midi - - -def processed2handcodedrep(midi_path, handcoded_rep_path=None, crop=30, verbose=False, save=True, return_rep=False, level=0): - try: - if not handcoded_rep_path: - handcoded_rep_path, _, _ = get_out_path(in_path=midi_path, in_word='processed', out_word='handcoded_reps', out_extension='.mid') - features = dict() - if verbose: print(' ' * level + 'Computing handcoded representations') - if os.path.exists(handcoded_rep_path): - with open(handcoded_rep_path.replace('.mid', '.json'), 'r') as f: - features = json.load(f) - rep = np.array([features[k] for k in sorted(features.keys())]) - if rep.size == 49: - os.remove(handcoded_rep_path) - else: - if verbose: print(' ' * (level + 2) + 'Already computed.') - if return_rep: - return handcoded_rep_path, np.array([features[k] for k in sorted(features.keys())]), '' - else: - return handcoded_rep_path, '' - midi = pm.PrettyMIDI(midi_path) # load midi with pretty midi - notes = midi.instruments[0].notes # get notes - notes.sort(key=lambda x: (x.start, x.pitch)) # sort notes per start and pitch - onsets, offsets, pitches, durations, velocities = [], [], [], [], [] - n_notes_cropped = len(notes) - for i_n, n in enumerate(notes): - onsets.append(n.start) - offsets.append(n.end) - durations.append(n.end-n.start) - pitches.append(n.pitch) - velocities.append(n.velocity) - if crop is not None: # find how many notes to keep - if n.start > crop and n_notes_cropped == len(notes): - n_notes_cropped = i_n - break - notes = notes[:n_notes_cropped] - midi = store_new_midi(notes, handcoded_rep_path) - # pianoroll = midi.get_piano_roll() # extract piano roll representation - - # compute loudness - amplitudes = velocity2amplitude(np.array(velocities)) - power_dbs = amplitude2db(amplitudes) - frequencies = pitch2freq(np.array(pitches)) - loudness_values = get_loudness(power_dbs, frequencies) - # compute average perceived loudness - # for each power, compute loudness, then compute power such that the loudness at 440 Hz would be equivalent. - # equivalent_powers_dbs = get_db_of_equivalent_loudness_at_440hz(frequencies, power_dbs) - # then get the corresponding amplitudes - # equivalent_amplitudes = 10 ** (equivalent_powers_dbs / 20) - # not use a amplitude model across the sample to compute the instantaneous amplitude, turn it back to dbs, then to perceived loudness with unique freq 440 Hz - # av_total_loudness, std_total_loudness = compute_total_loudness(equivalent_amplitudes, onsets, offsets) - - end_time = np.max(offsets) - start_time = notes[0].start - - - score = converter.parse(handcoded_rep_path) - score.chordify() - notes_without_chords = stream.Stream(score.flatten().getElementsByClass('Note')) - - velocities_wo_chords, pitches_wo_chords, amplitudes_wo_chords, dbs_wo_chords = [], [], [], [] - frequencies_wo_chords, loudness_values_wo_chords, onsets_wo_chords, offsets_wo_chords, durations_wo_chords = [], [], [], [], [] - for i_n in range(len(notes_without_chords)): - n = notes_without_chords[i_n] - velocities_wo_chords.append(n.volume.velocity) - pitches_wo_chords.append(n.pitch.midi) - onsets_wo_chords.append(n.offset) - offsets_wo_chords.append(onsets_wo_chords[-1] + n.seconds) - durations_wo_chords.append(n.seconds) - - amplitudes_wo_chords = velocity2amplitude(np.array(velocities_wo_chords)) - power_dbs_wo_chords = amplitude2db(amplitudes_wo_chords) - frequencies_wo_chords = pitch2freq(np.array(pitches_wo_chords)) - loudness_values_wo_chords = get_loudness(power_dbs_wo_chords, frequencies_wo_chords) - # compute average perceived loudness - # for each power, compute loudness, then compute power such that the loudness at 440 Hz would be equivalent. - # equivalent_powers_dbs_wo_chords = get_db_of_equivalent_loudness_at_440hz(frequencies_wo_chords, power_dbs_wo_chords) - # then get the corresponding amplitudes - # equivalent_amplitudes_wo_chords = 10 ** (equivalent_powers_dbs_wo_chords / 20) - # not use a amplitude model across the sample to compute the instantaneous amplitude, turn it back to dbs, then to perceived loudness with unique freq 440 Hz - # av_total_loudness_wo_chords, std_total_loudness_wo_chords = compute_total_loudness(equivalent_amplitudes_wo_chords, onsets_wo_chords, offsets_wo_chords) - - ds = DataSet(classLabel='test') - f = list(FEATURES_DICT.values()) - ds.addFeatureExtractors(f) - ds.addData(notes_without_chords) - ds.process() - for k, f in zip(FEATURES_DICT.keys(), ds.getFeaturesAsList()[0][1:-1]): - features[k] = f - - ds = DataSet(classLabel='test') - f = list(FEATURES_DICT_SCORE.values()) - ds.addFeatureExtractors(f) - ds.addData(score) - ds.process() - for k, f in zip(FEATURES_DICT_SCORE.keys(), ds.getFeaturesAsList()[0][1:-1]): - features[k] = f - - # # # # # - # Register features - # # # # # - - # features['av_pitch'] = np.mean(pitches) - # features['std_pitch'] = np.std(pitches) - # features['range_pitch'] = np.max(pitches) - np.min(pitches) # aka ambitus - - # # # # # - # Rhythmic features - # # # # # - - # tempo, pulse_clarity = compute_beat_info(onsets[:n_notes_cropped]) - # features['pulse_clarity'] = pulse_clarity - # features['tempo'] = tempo - features['tempo_pm'] = midi.estimate_tempo() - - # # # # # - # Temporal features - # # # # # - - features['av_duration'] = np.mean(durations) - # features['std_duration'] = np.std(durations) - features['note_density'] = len(notes) / (end_time - start_time) - # intervals_wo_chords = np.diff(onsets_wo_chords) - # articulations = [max((i-d)/i, 0) for d, i in zip(durations_wo_chords, intervals_wo_chords) if i != 0] - # features['articulation'] = np.mean(articulations) - # features['av_duration_wo_chords'] = np.mean(durations_wo_chords) - # features['std_duration_wo_chords'] = np.std(durations_wo_chords) - - # # # # # - # Dynamics features - # # # # # - features['av_velocity'] = np.mean(velocities) - features['std_velocity'] = np.std(velocities) - features['av_loudness'] = np.mean(loudness_values) - # features['std_loudness'] = np.std(loudness_values) - features['range_loudness'] = np.max(loudness_values) - np.min(loudness_values) - # features['av_integrated_loudness'] = av_total_loudness - # features['std_integrated_loudness'] = std_total_loudness - # features['av_velocity_wo_chords'] = np.mean(velocities_wo_chords) - # features['std_velocity_wo_chords'] = np.std(velocities_wo_chords) - # features['av_loudness_wo_chords'] = np.mean(loudness_values_wo_chords) - # features['std_loudness_wo_chords'] = np.std(loudness_values_wo_chords) - features['range_loudness_wo_chords'] = np.max(loudness_values_wo_chords) - np.min(loudness_values_wo_chords) - # features['av_integrated_loudness'] = av_total_loudness_wo_chords - # features['std_integrated_loudness'] = std_total_loudness_wo_chords - # indices_with_intervals = np.where(intervals_wo_chords > 0.01) - # features['av_loudness_change'] = np.mean(np.abs(np.diff(np.array(loudness_values_wo_chords)[indices_with_intervals]))) # accentuation - # features['av_velocity_change'] = np.mean(np.abs(np.diff(np.array(velocities_wo_chords)[indices_with_intervals]))) # accentuation - - # # # # # - # Harmony features - # # # # # - - # get major_minor score: https://web.mit.edu/music21/doc/moduleReference/moduleAnalysisDiscrete.html - music_analysis = score.analyze('key') - major_score = None - minor_score = None - for a in [music_analysis] + music_analysis.alternateInterpretations: - if 'major' in a.__str__() and a.correlationCoefficient > 0: - major_score = a.correlationCoefficient - elif 'minor' in a.__str__() and a.correlationCoefficient > 0: - minor_score = a.correlationCoefficient - if major_score is not None and minor_score is not None: - break - features['major_minor'] = major_score / (major_score + minor_score) - features['tonal_certainty'] = music_analysis.tonalCertainty() - # features['av_sensory_dissonance'] = np.mean(dissonance_score(pianoroll)) - #TODO only works for chords, do something with melodic intervals: like proportion that is not third, fifth or sevenths? - - # # # # # - # Interval features - # # # # # - #https://web.mit.edu/music21/doc/moduleReference/moduleAnalysisPatel.html - # features['melodic_interval_variability'] = analysis.patel.melodicIntervalVariability(notes_without_chords) - - # # # # # - # Suprize features - # # # # # - # https://web.mit.edu/music21/doc/moduleReference/moduleAnalysisMetrical.html - # analysis.metrical.thomassenMelodicAccent(notes_without_chords) - # melodic_accents = [n.melodicAccent for n in notes_without_chords] - # features['melodic_accent'] = np.mean(melodic_accents) - - if save: - for k, v in features.items(): - features[k] = float(features[k]) - with open(handcoded_rep_path.replace('.mid', '.json'), 'w') as f: - json.dump(features, f) - else: - print(features) - if os.path.exists(handcoded_rep_path): - os.remove(handcoded_rep_path) - if verbose: print(' ' * (level + 2) + 'Success.') - if return_rep: - return handcoded_rep_path, np.array([features[k] for k in sorted(features.keys())]), '' - else: - return handcoded_rep_path, '' - except: - if verbose: print(' ' * (level + 2) + 'Failed.') - if return_rep: - return None, None, 'error' - else: - return None, 'error' - - -if __name__ == '__main__': - processed2handcodedrep(midi_path, '/home/cedric/Desktop/test.mid', save=False) \ No newline at end of file diff --git a/spaces/chatpdfdemo/chatpdfdemo/app.py b/spaces/chatpdfdemo/chatpdfdemo/app.py deleted file mode 100644 index 22e5ec520fd3b3381de0fb39968e822086aa51b0..0000000000000000000000000000000000000000 --- a/spaces/chatpdfdemo/chatpdfdemo/app.py +++ /dev/null @@ -1,85 +0,0 @@ -import streamlit as st -from dotenv import load_dotenv -import pickle -from PyPDF2 import PdfReader -from streamlit_extras.add_vertical_space import add_vertical_space -from langchain.text_splitter import RecursiveCharacterTextSplitter -from langchain.embeddings.openai import OpenAIEmbeddings -from langchain.vectorstores import FAISS -from langchain.llms import OpenAI -from langchain.chains.question_answering import load_qa_chain -from langchain.callbacks import get_openai_callback -import os - -# Sidebar contents -with st.sidebar: - st.title('LLM Chat App') - st.markdown(''' - ## About - This app is an LLM-powered chatbot built using: - - [Streamlit](https://streamlit.io/) - - [LangChain](https://python.langchain.com/) - - [OpenAI](https://platform.openai.com/docs/models) LLM model - - ''') - add_vertical_space(5) - - -load_dotenv() - -def main(): - st.header("Chat with PDF 💬") - - - # upload a PDF file - pdf = st.file_uploader("Upload your PDF", type='pdf') - - # st.write(pdf) - if pdf is not None: - pdf_reader = PdfReader(pdf) - - text = "" - for page in pdf_reader.pages: - text += page.extract_text() - - text_splitter = RecursiveCharacterTextSplitter( - chunk_size=1000, - chunk_overlap=200, - length_function=len - ) - chunks = text_splitter.split_text(text=text) - - # # embeddings - store_name = pdf.name[:-4] - st.write(f'{store_name}') - # st.write(chunks) - - if os.path.exists(f"{store_name}.pkl"): - with open(f"{store_name}.pkl", "rb") as f: - VectorStore = pickle.load(f) - # st.write('Embeddings Loaded from the Disk')s - else: - embeddings = OpenAIEmbeddings() - VectorStore = FAISS.from_texts(chunks, embedding=embeddings) - with open(f"{store_name}.pkl", "wb") as f: - pickle.dump(VectorStore, f) - - # embeddings = OpenAIEmbeddings() - # VectorStore = FAISS.from_texts(chunks, embedding=embeddings) - - # Accept user questions/query - query = st.text_input("Ask questions about your PDF file:") - # st.write(query) - - if query: - docs = VectorStore.similarity_search(query=query, k=3) - - llm = OpenAI(model_name='gpt-3.5-turbo') - chain = load_qa_chain(llm=llm, chain_type="stuff") - with get_openai_callback() as cb: - response = chain.run(input_documents=docs, question=query) - print(cb) - st.write(response) - -if __name__ == '__main__': - main() \ No newline at end of file diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/aiofiles/base.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/aiofiles/base.py deleted file mode 100644 index 6201d95b4fec039a6a9bfe59ad1de722c4688c9a..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/aiofiles/base.py +++ /dev/null @@ -1,111 +0,0 @@ -"""Various base classes.""" -from types import coroutine -from collections.abc import Coroutine -from asyncio import get_running_loop - - -class AsyncBase: - def __init__(self, file, loop, executor): - self._file = file - self._executor = executor - self._ref_loop = loop - - @property - def _loop(self): - return self._ref_loop or get_running_loop() - - def __aiter__(self): - """We are our own iterator.""" - return self - - def __repr__(self): - return super().__repr__() + " wrapping " + repr(self._file) - - async def __anext__(self): - """Simulate normal file iteration.""" - line = await self.readline() - if line: - return line - else: - raise StopAsyncIteration - - -class AsyncIndirectBase(AsyncBase): - def __init__(self, name, loop, executor, indirect): - self._indirect = indirect - self._name = name - super().__init__(None, loop, executor) - - @property - def _file(self): - return self._indirect() - - @_file.setter - def _file(self, v): - pass # discard writes - - -class _ContextManager(Coroutine): - __slots__ = ("_coro", "_obj") - - def __init__(self, coro): - self._coro = coro - self._obj = None - - def send(self, value): - return self._coro.send(value) - - def throw(self, typ, val=None, tb=None): - if val is None: - return self._coro.throw(typ) - elif tb is None: - return self._coro.throw(typ, val) - else: - return self._coro.throw(typ, val, tb) - - def close(self): - return self._coro.close() - - @property - def gi_frame(self): - return self._coro.gi_frame - - @property - def gi_running(self): - return self._coro.gi_running - - @property - def gi_code(self): - return self._coro.gi_code - - def __next__(self): - return self.send(None) - - @coroutine - def __iter__(self): - resp = yield from self._coro - return resp - - def __await__(self): - resp = yield from self._coro - return resp - - async def __anext__(self): - resp = await self._coro - return resp - - async def __aenter__(self): - self._obj = await self._coro - return self._obj - - async def __aexit__(self, exc_type, exc, tb): - self._obj.close() - self._obj = None - - -class AiofilesContextManager(_ContextManager): - """An adjusted async context manager for aiofiles.""" - - async def __aexit__(self, exc_type, exc_val, exc_tb): - await self._obj.close() - self._obj = None diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/cryptography/hazmat/primitives/padding.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/cryptography/hazmat/primitives/padding.py deleted file mode 100644 index fde3094b00ae4f118d81a2b15c18acb80702cdba..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/cryptography/hazmat/primitives/padding.py +++ /dev/null @@ -1,225 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc -import typing - -from cryptography import utils -from cryptography.exceptions import AlreadyFinalized -from cryptography.hazmat.bindings._rust import ( - check_ansix923_padding, - check_pkcs7_padding, -) - - -class PaddingContext(metaclass=abc.ABCMeta): - @abc.abstractmethod - def update(self, data: bytes) -> bytes: - """ - Pads the provided bytes and returns any available data as bytes. - """ - - @abc.abstractmethod - def finalize(self) -> bytes: - """ - Finalize the padding, returns bytes. - """ - - -def _byte_padding_check(block_size: int) -> None: - if not (0 <= block_size <= 2040): - raise ValueError("block_size must be in range(0, 2041).") - - if block_size % 8 != 0: - raise ValueError("block_size must be a multiple of 8.") - - -def _byte_padding_update( - buffer_: typing.Optional[bytes], data: bytes, block_size: int -) -> typing.Tuple[bytes, bytes]: - if buffer_ is None: - raise AlreadyFinalized("Context was already finalized.") - - utils._check_byteslike("data", data) - - buffer_ += bytes(data) - - finished_blocks = len(buffer_) // (block_size // 8) - - result = buffer_[: finished_blocks * (block_size // 8)] - buffer_ = buffer_[finished_blocks * (block_size // 8) :] - - return buffer_, result - - -def _byte_padding_pad( - buffer_: typing.Optional[bytes], - block_size: int, - paddingfn: typing.Callable[[int], bytes], -) -> bytes: - if buffer_ is None: - raise AlreadyFinalized("Context was already finalized.") - - pad_size = block_size // 8 - len(buffer_) - return buffer_ + paddingfn(pad_size) - - -def _byte_unpadding_update( - buffer_: typing.Optional[bytes], data: bytes, block_size: int -) -> typing.Tuple[bytes, bytes]: - if buffer_ is None: - raise AlreadyFinalized("Context was already finalized.") - - utils._check_byteslike("data", data) - - buffer_ += bytes(data) - - finished_blocks = max(len(buffer_) // (block_size // 8) - 1, 0) - - result = buffer_[: finished_blocks * (block_size // 8)] - buffer_ = buffer_[finished_blocks * (block_size // 8) :] - - return buffer_, result - - -def _byte_unpadding_check( - buffer_: typing.Optional[bytes], - block_size: int, - checkfn: typing.Callable[[bytes], int], -) -> bytes: - if buffer_ is None: - raise AlreadyFinalized("Context was already finalized.") - - if len(buffer_) != block_size // 8: - raise ValueError("Invalid padding bytes.") - - valid = checkfn(buffer_) - - if not valid: - raise ValueError("Invalid padding bytes.") - - pad_size = buffer_[-1] - return buffer_[:-pad_size] - - -class PKCS7: - def __init__(self, block_size: int): - _byte_padding_check(block_size) - self.block_size = block_size - - def padder(self) -> PaddingContext: - return _PKCS7PaddingContext(self.block_size) - - def unpadder(self) -> PaddingContext: - return _PKCS7UnpaddingContext(self.block_size) - - -class _PKCS7PaddingContext(PaddingContext): - _buffer: typing.Optional[bytes] - - def __init__(self, block_size: int): - self.block_size = block_size - # TODO: more copies than necessary, we should use zero-buffer (#193) - self._buffer = b"" - - def update(self, data: bytes) -> bytes: - self._buffer, result = _byte_padding_update( - self._buffer, data, self.block_size - ) - return result - - def _padding(self, size: int) -> bytes: - return bytes([size]) * size - - def finalize(self) -> bytes: - result = _byte_padding_pad( - self._buffer, self.block_size, self._padding - ) - self._buffer = None - return result - - -class _PKCS7UnpaddingContext(PaddingContext): - _buffer: typing.Optional[bytes] - - def __init__(self, block_size: int): - self.block_size = block_size - # TODO: more copies than necessary, we should use zero-buffer (#193) - self._buffer = b"" - - def update(self, data: bytes) -> bytes: - self._buffer, result = _byte_unpadding_update( - self._buffer, data, self.block_size - ) - return result - - def finalize(self) -> bytes: - result = _byte_unpadding_check( - self._buffer, self.block_size, check_pkcs7_padding - ) - self._buffer = None - return result - - -class ANSIX923: - def __init__(self, block_size: int): - _byte_padding_check(block_size) - self.block_size = block_size - - def padder(self) -> PaddingContext: - return _ANSIX923PaddingContext(self.block_size) - - def unpadder(self) -> PaddingContext: - return _ANSIX923UnpaddingContext(self.block_size) - - -class _ANSIX923PaddingContext(PaddingContext): - _buffer: typing.Optional[bytes] - - def __init__(self, block_size: int): - self.block_size = block_size - # TODO: more copies than necessary, we should use zero-buffer (#193) - self._buffer = b"" - - def update(self, data: bytes) -> bytes: - self._buffer, result = _byte_padding_update( - self._buffer, data, self.block_size - ) - return result - - def _padding(self, size: int) -> bytes: - return bytes([0]) * (size - 1) + bytes([size]) - - def finalize(self) -> bytes: - result = _byte_padding_pad( - self._buffer, self.block_size, self._padding - ) - self._buffer = None - return result - - -class _ANSIX923UnpaddingContext(PaddingContext): - _buffer: typing.Optional[bytes] - - def __init__(self, block_size: int): - self.block_size = block_size - # TODO: more copies than necessary, we should use zero-buffer (#193) - self._buffer = b"" - - def update(self, data: bytes) -> bytes: - self._buffer, result = _byte_unpadding_update( - self._buffer, data, self.block_size - ) - return result - - def finalize(self) -> bytes: - result = _byte_unpadding_check( - self._buffer, - self.block_size, - check_ansix923_padding, - ) - self._buffer = None - return result diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/ttLib/tables/_m_e_t_a.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/ttLib/tables/_m_e_t_a.py deleted file mode 100644 index 3af9e543049f89f0da3ceb15bb58135854fef002..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/ttLib/tables/_m_e_t_a.py +++ /dev/null @@ -1,104 +0,0 @@ -from fontTools.misc import sstruct -from fontTools.misc.textTools import bytesjoin, strjoin, readHex -from fontTools.ttLib import TTLibError -from . import DefaultTable - -# Apple's documentation of 'meta': -# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6meta.html - -META_HEADER_FORMAT = """ - > # big endian - version: L - flags: L - dataOffset: L - numDataMaps: L -""" - - -DATA_MAP_FORMAT = """ - > # big endian - tag: 4s - dataOffset: L - dataLength: L -""" - - -class table__m_e_t_a(DefaultTable.DefaultTable): - def __init__(self, tag=None): - DefaultTable.DefaultTable.__init__(self, tag) - self.data = {} - - def decompile(self, data, ttFont): - headerSize = sstruct.calcsize(META_HEADER_FORMAT) - header = sstruct.unpack(META_HEADER_FORMAT, data[0:headerSize]) - if header["version"] != 1: - raise TTLibError("unsupported 'meta' version %d" % header["version"]) - dataMapSize = sstruct.calcsize(DATA_MAP_FORMAT) - for i in range(header["numDataMaps"]): - dataMapOffset = headerSize + i * dataMapSize - dataMap = sstruct.unpack( - DATA_MAP_FORMAT, data[dataMapOffset : dataMapOffset + dataMapSize] - ) - tag = dataMap["tag"] - offset = dataMap["dataOffset"] - self.data[tag] = data[offset : offset + dataMap["dataLength"]] - if tag in ["dlng", "slng"]: - self.data[tag] = self.data[tag].decode("utf-8") - - def compile(self, ttFont): - keys = sorted(self.data.keys()) - headerSize = sstruct.calcsize(META_HEADER_FORMAT) - dataOffset = headerSize + len(keys) * sstruct.calcsize(DATA_MAP_FORMAT) - header = sstruct.pack( - META_HEADER_FORMAT, - { - "version": 1, - "flags": 0, - "dataOffset": dataOffset, - "numDataMaps": len(keys), - }, - ) - dataMaps = [] - dataBlocks = [] - for tag in keys: - if tag in ["dlng", "slng"]: - data = self.data[tag].encode("utf-8") - else: - data = self.data[tag] - dataMaps.append( - sstruct.pack( - DATA_MAP_FORMAT, - {"tag": tag, "dataOffset": dataOffset, "dataLength": len(data)}, - ) - ) - dataBlocks.append(data) - dataOffset += len(data) - return bytesjoin([header] + dataMaps + dataBlocks) - - def toXML(self, writer, ttFont): - for tag in sorted(self.data.keys()): - if tag in ["dlng", "slng"]: - writer.begintag("text", tag=tag) - writer.newline() - writer.write(self.data[tag]) - writer.newline() - writer.endtag("text") - writer.newline() - else: - writer.begintag("hexdata", tag=tag) - writer.newline() - data = self.data[tag] - if min(data) >= 0x20 and max(data) <= 0x7E: - writer.comment("ascii: " + data.decode("ascii")) - writer.newline() - writer.dumphex(data) - writer.endtag("hexdata") - writer.newline() - - def fromXML(self, name, attrs, content, ttFont): - if name == "hexdata": - self.data[attrs["tag"]] = readHex(content) - elif name == "text" and attrs["tag"] in ["dlng", "slng"]: - self.data[attrs["tag"]] = strjoin(content).strip() - else: - raise TTLibError("can't handle '%s' element" % name) diff --git a/spaces/cihyFjudo/fairness-paper-search/Autodesk Inventor 2009 Keygenl Download and Activate Your Software for Free.md b/spaces/cihyFjudo/fairness-paper-search/Autodesk Inventor 2009 Keygenl Download and Activate Your Software for Free.md deleted file mode 100644 index 6e1d8c94e80a05d282bf3409efe024e5f9b161fa..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/Autodesk Inventor 2009 Keygenl Download and Activate Your Software for Free.md +++ /dev/null @@ -1,6 +0,0 @@ -

Autodesk Inventor 2009 Keygenl


Download Zip ✯✯✯ https://tinurli.com/2uwirO



-
- aaccfb2cb3
-
-
-

diff --git a/spaces/cihyFjudo/fairness-paper-search/BlackaliciousNia LINK Full Album Zip.md b/spaces/cihyFjudo/fairness-paper-search/BlackaliciousNia LINK Full Album Zip.md deleted file mode 100644 index 2448d5548ff98e4d5646f9d919ed253b1cfa1ab1..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/BlackaliciousNia LINK Full Album Zip.md +++ /dev/null @@ -1,6 +0,0 @@ -

BlackaliciousNia Full Album Zip


DOWNLOAD →→→ https://tinurli.com/2uwite



-
- aaccfb2cb3
-
-
-

diff --git a/spaces/cihyFjudo/fairness-paper-search/Parbona Ami Charte Toke Full Movie Download HD 720p A Must-Watch for Fans of Bonny and Koushani.md b/spaces/cihyFjudo/fairness-paper-search/Parbona Ami Charte Toke Full Movie Download HD 720p A Must-Watch for Fans of Bonny and Koushani.md deleted file mode 100644 index 839bfc8980187134c8b488c446320eacfd4dffd6..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/Parbona Ami Charte Toke Full Movie Download HD 720p A Must-Watch for Fans of Bonny and Koushani.md +++ /dev/null @@ -1,6 +0,0 @@ -

parbona ami charter toke full movie download hd 72015


Download Zip ►►► https://tinurli.com/2uwi1U



- - aaccfb2cb3
-
-
-

diff --git a/spaces/cihyFjudo/fairness-paper-search/Platillosvolantes2003downloadtorrent Everything You Need to Know About the Cult Classic.md b/spaces/cihyFjudo/fairness-paper-search/Platillosvolantes2003downloadtorrent Everything You Need to Know About the Cult Classic.md deleted file mode 100644 index a18d998b0120e6842f6e946e5e5029291fc140df..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/Platillosvolantes2003downloadtorrent Everything You Need to Know About the Cult Classic.md +++ /dev/null @@ -1,6 +0,0 @@ -

Platillosvolantes2003downloadtorrent


Download File 🗹 https://tinurli.com/2uwirr



- - aaccfb2cb3
-
-
-

diff --git a/spaces/cihyFjudo/fairness-paper-search/Sonny With A Chance So Sketchy Game Tips and Tricks to Collect All the Props and Avoid the Obstacles.md b/spaces/cihyFjudo/fairness-paper-search/Sonny With A Chance So Sketchy Game Tips and Tricks to Collect All the Props and Avoid the Obstacles.md deleted file mode 100644 index 394e3748c1f720c3e8b4f84fb13a0fdf33874176..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/Sonny With A Chance So Sketchy Game Tips and Tricks to Collect All the Props and Avoid the Obstacles.md +++ /dev/null @@ -1,12 +0,0 @@ - -

Congratulations! You have just miraculously landed in a magical world! Here you find an exhaustive collection of point-and-click, arcade, 2D games to satisfy any taste. Meet your friends from Disney Channel and let them take you on the adventure of your lifetime. The world offers you plenty of opportunities to play with your favorite characters. Now you might be helping Zack and Cody to throw the best pizza party of the summer while playing the Pizza Party Pickup game, and in the few minutes, you race through a hot and dangerous desert as Lightning McQueen, trying to get in front of Hicks and Weathers.

-

Sonny With A Chance So Sketchy Game


Download Zip >>> https://tinurli.com/2uwimV



-

Most of you are already familiar with the majority of these old Disney Channel Games. Some of you might even get nostalgic while playing the games since it might remind you about the golden era of childhood when you've first interacted with all those famous Disney Characters. Whichever should be the case, there's a guarantee that no day will be the same after your steps in this magic world.

-

So far, there are 547 online Disney Games, for both kids and adults, that you can play on Disney--Games.com for free right now! All the games are organized into 29 categories, the most popular being Hannah Montana Games, with 4585830 total plays, and the most recently updated is Lilo and Stitch Games on Sunday, February 05, 2023. The most rated game is Winnie the Pooh's Home Run Derby, with 9655 votes received!

-

Starting with January 2021, most browsers stopped supporting Flash Technology, making it impossible to run games like Sonny With a Chance: So Sketchy. However, you can still play this game using our custom Browser. Give it a try!

-

Nico and Grady first met each other 13 years ago when they threw up on the same tea cup ride and are currently still the best of friends. These two have done a lot of mischief and trouble in a hilarious way. They are both on So Random and enemies of Murphy. The two also don't like Sonny and Chads' Relationship just like the rest of their cast mates. Nico and Grady have also been in a lot of great sketches together. Nico likes to give Grady dating advice, though neither of them have really been in a real relationship. Nico helped Grady talk to Mel and overcome the "Seamus McGregor" inside of him. They both enjoy playing video games, Grady's player 1 while Nico's player 2. They tend to get along with each other very well and make a great team. The two have fought before in "Sonny in the Middle", however, Nico and Grady will always have each other's backs and they are a great example in showing what true friendship really is. Nico and Grady were the only boys on So Random! but now that Chad has joined, they are not the only ones.

-

Sonny manages to convince Chad to play musical chairs after barging into the MacKenzie Falls set and bawking at him, with the terms that if the cast of So Random! wins, they get the parking space back, the MacKenzie Falls table, Chad has to buy them a new toilet paper holder and he will have to say something nice about So Random! on MacKenzie Falls; but if the cast of MacKenzie Falls wins, they get to say that MacKenzie Falls is better than So Random! on their show. The So Random! cast is the first to arrive at the commissary and start practicing sitting and walking, until they have to begin due to the arrival of the cast of MacKenzie Falls. Eventually when there is only one chair left between Sonny and Chad, the music stops and Sonny pretends to break her ankle, only to pull Chad down when he attempts to help her up and rush up to sit in the last chair, therefore winning the game. Chad, impressed with Sonny's acting, invites her onto his show, but Sonny declines and decides to stay at So Random!. At the end, the So Random! gang is watching MacKenzie Falls. On the show, Chad then says So Random! is his favorite show. The So Random! gang cheer and are pleased to hear this.

-

-

If you've got a knack for fashion, you'll want to give the old Disney Channel game Design Hannah Montana. You'll help the famous teenage superstar achieve the perfect look with plenty of fun and glittery clothes. You can also change Hannah's hairstyle by choosing different hair colors and experimenting with them. When you're done with Hannah's final look, you have the option to print out your work and impress your pals with your fashion skills.

aaccfb2cb3
-
-
\ No newline at end of file diff --git a/spaces/cloudstack/CSV-ChatBot/modules/sidebar.py b/spaces/cloudstack/CSV-ChatBot/modules/sidebar.py deleted file mode 100644 index 85afcdace77244c0fc6bc983d7a0295f1e3033a2..0000000000000000000000000000000000000000 --- a/spaces/cloudstack/CSV-ChatBot/modules/sidebar.py +++ /dev/null @@ -1,55 +0,0 @@ -import streamlit as st - - -class Sidebar: - MODEL_OPTIONS = ["gpt-3.5-turbo", "gpt-4"] - TEMPERATURE_MIN_VALUE = 0.0 - TEMPERATURE_MAX_VALUE = 1.0 - TEMPERATURE_DEFAULT_VALUE = 0.0 - TEMPERATURE_STEP = 0.01 - - @staticmethod - def about(): - about = st.sidebar.expander("🤖Info") - sections = [ - "#### CSV-ChatBotis an AI chatbot with interactive memory features designed to help users discuss CSV data in a more intuitive way. 📄", - "#### It uses a large language model to provide users with seamless, contextual, natural language interactions to better understand CSV data.. 🌐", - "#### [Langchain](https://github.com/hwchase17/langchain), [OpenAI](https://platform.openai.com/docs/models/gpt-3-5) [Streamlit](https://github.com/streamlit/streamlit)⚡", - "#### Source code : [RustX/ChatBot-CSV](https://github.com/RustX2802/CSV-ChatBot)", - ] - for section in sections: - about.write(section) - - @staticmethod - def reset_chat_button(): - if st.button("Reset chat"): - st.session_state["reset_chat"] = True - st.session_state.setdefault("reset_chat", False) - - def model_selector(self): - model = st.selectbox(label="Model ", options=self.MODEL_OPTIONS) - st.session_state["model"] = model - - def temperature_slider(self): - temperature = st.slider( - label="Temperature ", - min_value=self.TEMPERATURE_MIN_VALUE, - max_value=self.TEMPERATURE_MAX_VALUE, - value=self.TEMPERATURE_DEFAULT_VALUE, - step=self.TEMPERATURE_STEP, - ) - st.session_state["temperature"] = temperature - - def csv_agent_button(self): - st.session_state.setdefault("show_csv_agent", False) - if st.sidebar.button("CSV Agent"): - st.session_state["show_csv_agent"] = not st.session_state["show_csv_agent"] - - def show_options(self): - with st.sidebar.expander("🛠️ Tools ", expanded=False): - self.reset_chat_button() - self.csv_agent_button() - self.model_selector() - self.temperature_slider() - st.session_state.setdefault("model", self.MODEL_OPTIONS[0]) - st.session_state.setdefault("temperature", self.TEMPERATURE_DEFAULT_VALUE) \ No newline at end of file diff --git a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/decorator.py b/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/decorator.py deleted file mode 100644 index 2479b6f7ba723b933978d10a6f80e28f60c3c1c6..0000000000000000000000000000000000000000 --- a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/decorator.py +++ /dev/null @@ -1,451 +0,0 @@ -# ######################### LICENSE ############################ # - -# Copyright (c) 2005-2021, Michele Simionato -# All rights reserved. - -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: - -# Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# Redistributions in bytecode 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 -# HOLDERS 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. - -""" -Decorator module, see -https://github.com/micheles/decorator/blob/master/docs/documentation.md -for the documentation. -""" -import re -import sys -import inspect -import operator -import itertools -from contextlib import _GeneratorContextManager -from inspect import getfullargspec, iscoroutinefunction, isgeneratorfunction - -__version__ = '5.1.1' - -DEF = re.compile(r'\s*def\s*([_\w][_\w\d]*)\s*\(') -POS = inspect.Parameter.POSITIONAL_OR_KEYWORD -EMPTY = inspect.Parameter.empty - - -# this is not used anymore in the core, but kept for backward compatibility -class FunctionMaker(object): - """ - An object with the ability to create functions with a given signature. - It has attributes name, doc, module, signature, defaults, dict and - methods update and make. - """ - - # Atomic get-and-increment provided by the GIL - _compile_count = itertools.count() - - # make pylint happy - args = varargs = varkw = defaults = kwonlyargs = kwonlydefaults = () - - def __init__(self, func=None, name=None, signature=None, - defaults=None, doc=None, module=None, funcdict=None): - self.shortsignature = signature - if func: - # func can be a class or a callable, but not an instance method - self.name = func.__name__ - if self.name == '': # small hack for lambda functions - self.name = '_lambda_' - self.doc = func.__doc__ - self.module = func.__module__ - if inspect.isroutine(func): - argspec = getfullargspec(func) - self.annotations = getattr(func, '__annotations__', {}) - for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs', - 'kwonlydefaults'): - setattr(self, a, getattr(argspec, a)) - for i, arg in enumerate(self.args): - setattr(self, 'arg%d' % i, arg) - allargs = list(self.args) - allshortargs = list(self.args) - if self.varargs: - allargs.append('*' + self.varargs) - allshortargs.append('*' + self.varargs) - elif self.kwonlyargs: - allargs.append('*') # single star syntax - for a in self.kwonlyargs: - allargs.append('%s=None' % a) - allshortargs.append('%s=%s' % (a, a)) - if self.varkw: - allargs.append('**' + self.varkw) - allshortargs.append('**' + self.varkw) - self.signature = ', '.join(allargs) - self.shortsignature = ', '.join(allshortargs) - self.dict = func.__dict__.copy() - # func=None happens when decorating a caller - if name: - self.name = name - if signature is not None: - self.signature = signature - if defaults: - self.defaults = defaults - if doc: - self.doc = doc - if module: - self.module = module - if funcdict: - self.dict = funcdict - # check existence required attributes - assert hasattr(self, 'name') - if not hasattr(self, 'signature'): - raise TypeError('You are decorating a non function: %s' % func) - - def update(self, func, **kw): - """ - Update the signature of func with the data in self - """ - func.__name__ = self.name - func.__doc__ = getattr(self, 'doc', None) - func.__dict__ = getattr(self, 'dict', {}) - func.__defaults__ = self.defaults - func.__kwdefaults__ = self.kwonlydefaults or None - func.__annotations__ = getattr(self, 'annotations', None) - try: - frame = sys._getframe(3) - except AttributeError: # for IronPython and similar implementations - callermodule = '?' - else: - callermodule = frame.f_globals.get('__name__', '?') - func.__module__ = getattr(self, 'module', callermodule) - func.__dict__.update(kw) - - def make(self, src_templ, evaldict=None, addsource=False, **attrs): - """ - Make a new function from a given template and update the signature - """ - src = src_templ % vars(self) # expand name and signature - evaldict = evaldict or {} - mo = DEF.search(src) - if mo is None: - raise SyntaxError('not a valid function template\n%s' % src) - name = mo.group(1) # extract the function name - names = set([name] + [arg.strip(' *') for arg in - self.shortsignature.split(',')]) - for n in names: - if n in ('_func_', '_call_'): - raise NameError('%s is overridden in\n%s' % (n, src)) - - if not src.endswith('\n'): # add a newline for old Pythons - src += '\n' - - # Ensure each generated function has a unique filename for profilers - # (such as cProfile) that depend on the tuple of (, - # , ) being unique. - filename = '' % next(self._compile_count) - try: - code = compile(src, filename, 'single') - exec(code, evaldict) - except Exception: - print('Error in generated code:', file=sys.stderr) - print(src, file=sys.stderr) - raise - func = evaldict[name] - if addsource: - attrs['__source__'] = src - self.update(func, **attrs) - return func - - @classmethod - def create(cls, obj, body, evaldict, defaults=None, - doc=None, module=None, addsource=True, **attrs): - """ - Create a function from the strings name, signature and body. - evaldict is the evaluation dictionary. If addsource is true an - attribute __source__ is added to the result. The attributes attrs - are added, if any. - """ - if isinstance(obj, str): # "name(signature)" - name, rest = obj.strip().split('(', 1) - signature = rest[:-1] # strip a right parens - func = None - else: # a function - name = None - signature = None - func = obj - self = cls(func, name, signature, defaults, doc, module) - ibody = '\n'.join(' ' + line for line in body.splitlines()) - caller = evaldict.get('_call_') # when called from `decorate` - if caller and iscoroutinefunction(caller): - body = ('async def %(name)s(%(signature)s):\n' + ibody).replace( - 'return', 'return await') - else: - body = 'def %(name)s(%(signature)s):\n' + ibody - return self.make(body, evaldict, addsource, **attrs) - - -def fix(args, kwargs, sig): - """ - Fix args and kwargs to be consistent with the signature - """ - ba = sig.bind(*args, **kwargs) - ba.apply_defaults() # needed for test_dan_schult - return ba.args, ba.kwargs - - -def decorate(func, caller, extras=(), kwsyntax=False): - """ - Decorates a function/generator/coroutine using a caller. - If kwsyntax is True calling the decorated functions with keyword - syntax will pass the named arguments inside the ``kw`` dictionary, - even if such argument are positional, similarly to what functools.wraps - does. By default kwsyntax is False and the the arguments are untouched. - """ - sig = inspect.signature(func) - if iscoroutinefunction(caller): - async def fun(*args, **kw): - if not kwsyntax: - args, kw = fix(args, kw, sig) - return await caller(func, *(extras + args), **kw) - elif isgeneratorfunction(caller): - def fun(*args, **kw): - if not kwsyntax: - args, kw = fix(args, kw, sig) - for res in caller(func, *(extras + args), **kw): - yield res - else: - def fun(*args, **kw): - if not kwsyntax: - args, kw = fix(args, kw, sig) - return caller(func, *(extras + args), **kw) - fun.__name__ = func.__name__ - fun.__doc__ = func.__doc__ - fun.__wrapped__ = func - fun.__signature__ = sig - fun.__qualname__ = func.__qualname__ - # builtin functions like defaultdict.__setitem__ lack many attributes - try: - fun.__defaults__ = func.__defaults__ - except AttributeError: - pass - try: - fun.__kwdefaults__ = func.__kwdefaults__ - except AttributeError: - pass - try: - fun.__annotations__ = func.__annotations__ - except AttributeError: - pass - try: - fun.__module__ = func.__module__ - except AttributeError: - pass - try: - fun.__dict__.update(func.__dict__) - except AttributeError: - pass - return fun - - -def decoratorx(caller): - """ - A version of "decorator" implemented via "exec" and not via the - Signature object. Use this if you are want to preserve the `.__code__` - object properties (https://github.com/micheles/decorator/issues/129). - """ - def dec(func): - return FunctionMaker.create( - func, - "return _call_(_func_, %(shortsignature)s)", - dict(_call_=caller, _func_=func), - __wrapped__=func, __qualname__=func.__qualname__) - return dec - - -def decorator(caller, _func=None, kwsyntax=False): - """ - decorator(caller) converts a caller function into a decorator - """ - if _func is not None: # return a decorated function - # this is obsolete behavior; you should use decorate instead - return decorate(_func, caller, (), kwsyntax) - # else return a decorator function - sig = inspect.signature(caller) - dec_params = [p for p in sig.parameters.values() if p.kind is POS] - - def dec(func=None, *args, **kw): - na = len(args) + 1 - extras = args + tuple(kw.get(p.name, p.default) - for p in dec_params[na:] - if p.default is not EMPTY) - if func is None: - return lambda func: decorate(func, caller, extras, kwsyntax) - else: - return decorate(func, caller, extras, kwsyntax) - dec.__signature__ = sig.replace(parameters=dec_params) - dec.__name__ = caller.__name__ - dec.__doc__ = caller.__doc__ - dec.__wrapped__ = caller - dec.__qualname__ = caller.__qualname__ - dec.__kwdefaults__ = getattr(caller, '__kwdefaults__', None) - dec.__dict__.update(caller.__dict__) - return dec - - -# ####################### contextmanager ####################### # - - -class ContextManager(_GeneratorContextManager): - def __init__(self, g, *a, **k): - _GeneratorContextManager.__init__(self, g, a, k) - - def __call__(self, func): - def caller(f, *a, **k): - with self.__class__(self.func, *self.args, **self.kwds): - return f(*a, **k) - return decorate(func, caller) - - -_contextmanager = decorator(ContextManager) - - -def contextmanager(func): - # Enable Pylint config: contextmanager-decorators=decorator.contextmanager - return _contextmanager(func) - - -# ############################ dispatch_on ############################ # - -def append(a, vancestors): - """ - Append ``a`` to the list of the virtual ancestors, unless it is already - included. - """ - add = True - for j, va in enumerate(vancestors): - if issubclass(va, a): - add = False - break - if issubclass(a, va): - vancestors[j] = a - add = False - if add: - vancestors.append(a) - - -# inspired from simplegeneric by P.J. Eby and functools.singledispatch -def dispatch_on(*dispatch_args): - """ - Factory of decorators turning a function into a generic function - dispatching on the given arguments. - """ - assert dispatch_args, 'No dispatch args passed' - dispatch_str = '(%s,)' % ', '.join(dispatch_args) - - def check(arguments, wrong=operator.ne, msg=''): - """Make sure one passes the expected number of arguments""" - if wrong(len(arguments), len(dispatch_args)): - raise TypeError('Expected %d arguments, got %d%s' % - (len(dispatch_args), len(arguments), msg)) - - def gen_func_dec(func): - """Decorator turning a function into a generic function""" - - # first check the dispatch arguments - argset = set(getfullargspec(func).args) - if not set(dispatch_args) <= argset: - raise NameError('Unknown dispatch arguments %s' % dispatch_str) - - typemap = {} - - def vancestors(*types): - """ - Get a list of sets of virtual ancestors for the given types - """ - check(types) - ras = [[] for _ in range(len(dispatch_args))] - for types_ in typemap: - for t, type_, ra in zip(types, types_, ras): - if issubclass(t, type_) and type_ not in t.mro(): - append(type_, ra) - return [set(ra) for ra in ras] - - def ancestors(*types): - """ - Get a list of virtual MROs, one for each type - """ - check(types) - lists = [] - for t, vas in zip(types, vancestors(*types)): - n_vas = len(vas) - if n_vas > 1: - raise RuntimeError( - 'Ambiguous dispatch for %s: %s' % (t, vas)) - elif n_vas == 1: - va, = vas - mro = type('t', (t, va), {}).mro()[1:] - else: - mro = t.mro() - lists.append(mro[:-1]) # discard t and object - return lists - - def register(*types): - """ - Decorator to register an implementation for the given types - """ - check(types) - - def dec(f): - check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__) - typemap[types] = f - return f - return dec - - def dispatch_info(*types): - """ - An utility to introspect the dispatch algorithm - """ - check(types) - lst = [] - for anc in itertools.product(*ancestors(*types)): - lst.append(tuple(a.__name__ for a in anc)) - return lst - - def _dispatch(dispatch_args, *args, **kw): - types = tuple(type(arg) for arg in dispatch_args) - try: # fast path - f = typemap[types] - except KeyError: - pass - else: - return f(*args, **kw) - combinations = itertools.product(*ancestors(*types)) - next(combinations) # the first one has been already tried - for types_ in combinations: - f = typemap.get(types_) - if f is not None: - return f(*args, **kw) - - # else call the default implementation - return func(*args, **kw) - - return FunctionMaker.create( - func, 'return _f_(%s, %%(shortsignature)s)' % dispatch_str, - dict(_f_=_dispatch), register=register, default=func, - typemap=typemap, vancestors=vancestors, ancestors=ancestors, - dispatch_info=dispatch_info, __wrapped__=func) - - gen_func_dec.__name__ = 'dispatch_on' + dispatch_str - return gen_func_dec diff --git a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/fontTools/ttLib/tables/otBase.py b/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/fontTools/ttLib/tables/otBase.py deleted file mode 100644 index 9c80400e9420577f0d9d6f747e15b83e49f68e49..0000000000000000000000000000000000000000 --- a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/fontTools/ttLib/tables/otBase.py +++ /dev/null @@ -1,1458 +0,0 @@ -from fontTools.config import OPTIONS -from fontTools.misc.textTools import Tag, bytesjoin -from .DefaultTable import DefaultTable -from enum import IntEnum -import sys -import array -import struct -import logging -from functools import lru_cache -from typing import Iterator, NamedTuple, Optional, Tuple - -log = logging.getLogger(__name__) - -have_uharfbuzz = False -try: - import uharfbuzz as hb - - # repack method added in uharfbuzz >= 0.23; if uharfbuzz *can* be - # imported but repack method is missing, behave as if uharfbuzz - # is not available (fallback to the slower Python implementation) - have_uharfbuzz = callable(getattr(hb, "repack", None)) -except ImportError: - pass - -USE_HARFBUZZ_REPACKER = OPTIONS[f"{__name__}:USE_HARFBUZZ_REPACKER"] - - -class OverflowErrorRecord(object): - def __init__(self, overflowTuple): - self.tableType = overflowTuple[0] - self.LookupListIndex = overflowTuple[1] - self.SubTableIndex = overflowTuple[2] - self.itemName = overflowTuple[3] - self.itemIndex = overflowTuple[4] - - def __repr__(self): - return str( - ( - self.tableType, - "LookupIndex:", - self.LookupListIndex, - "SubTableIndex:", - self.SubTableIndex, - "ItemName:", - self.itemName, - "ItemIndex:", - self.itemIndex, - ) - ) - - -class OTLOffsetOverflowError(Exception): - def __init__(self, overflowErrorRecord): - self.value = overflowErrorRecord - - def __str__(self): - return repr(self.value) - - -class RepackerState(IntEnum): - # Repacking control flow is implemnted using a state machine. The state machine table: - # - # State | Packing Success | Packing Failed | Exception Raised | - # ------------+-----------------+----------------+------------------+ - # PURE_FT | Return result | PURE_FT | Return failure | - # HB_FT | Return result | HB_FT | FT_FALLBACK | - # FT_FALLBACK | HB_FT | FT_FALLBACK | Return failure | - - # Pack only with fontTools, don't allow sharing between extensions. - PURE_FT = 1 - - # Attempt to pack with harfbuzz (allowing sharing between extensions) - # use fontTools to attempt overflow resolution. - HB_FT = 2 - - # Fallback if HB/FT packing gets stuck. Pack only with fontTools, don't allow sharing between - # extensions. - FT_FALLBACK = 3 - - -class BaseTTXConverter(DefaultTable): - - """Generic base class for TTX table converters. It functions as an - adapter between the TTX (ttLib actually) table model and the model - we use for OpenType tables, which is necessarily subtly different. - """ - - def decompile(self, data, font): - """Create an object from the binary data. Called automatically on access.""" - from . import otTables - - reader = OTTableReader(data, tableTag=self.tableTag) - tableClass = getattr(otTables, self.tableTag) - self.table = tableClass() - self.table.decompile(reader, font) - - def compile(self, font): - """Compiles the table into binary. Called automatically on save.""" - - # General outline: - # Create a top-level OTTableWriter for the GPOS/GSUB table. - # Call the compile method for the the table - # for each 'converter' record in the table converter list - # call converter's write method for each item in the value. - # - For simple items, the write method adds a string to the - # writer's self.items list. - # - For Struct/Table/Subtable items, it add first adds new writer to the - # to the writer's self.items, then calls the item's compile method. - # This creates a tree of writers, rooted at the GUSB/GPOS writer, with - # each writer representing a table, and the writer.items list containing - # the child data strings and writers. - # call the getAllData method - # call _doneWriting, which removes duplicates - # call _gatherTables. This traverses the tables, adding unique occurences to a flat list of tables - # Traverse the flat list of tables, calling getDataLength on each to update their position - # Traverse the flat list of tables again, calling getData each get the data in the table, now that - # pos's and offset are known. - - # If a lookup subtable overflows an offset, we have to start all over. - overflowRecord = None - # this is 3-state option: default (None) means automatically use hb.repack or - # silently fall back if it fails; True, use it and raise error if not possible - # or it errors out; False, don't use it, even if you can. - use_hb_repack = font.cfg[USE_HARFBUZZ_REPACKER] - if self.tableTag in ("GSUB", "GPOS"): - if use_hb_repack is False: - log.debug( - "hb.repack disabled, compiling '%s' with pure-python serializer", - self.tableTag, - ) - elif not have_uharfbuzz: - if use_hb_repack is True: - raise ImportError("No module named 'uharfbuzz'") - else: - assert use_hb_repack is None - log.debug( - "uharfbuzz not found, compiling '%s' with pure-python serializer", - self.tableTag, - ) - - if ( - use_hb_repack in (None, True) - and have_uharfbuzz - and self.tableTag in ("GSUB", "GPOS") - ): - state = RepackerState.HB_FT - else: - state = RepackerState.PURE_FT - - hb_first_error_logged = False - lastOverflowRecord = None - while True: - try: - writer = OTTableWriter(tableTag=self.tableTag) - self.table.compile(writer, font) - if state == RepackerState.HB_FT: - return self.tryPackingHarfbuzz(writer, hb_first_error_logged) - elif state == RepackerState.PURE_FT: - return self.tryPackingFontTools(writer) - elif state == RepackerState.FT_FALLBACK: - # Run packing with FontTools only, but don't return the result as it will - # not be optimally packed. Once a successful packing has been found, state is - # changed back to harfbuzz packing to produce the final, optimal, packing. - self.tryPackingFontTools(writer) - log.debug( - "Re-enabling sharing between extensions and switching back to " - "harfbuzz+fontTools packing." - ) - state = RepackerState.HB_FT - - except OTLOffsetOverflowError as e: - hb_first_error_logged = True - ok = self.tryResolveOverflow(font, e, lastOverflowRecord) - lastOverflowRecord = e.value - - if ok: - continue - - if state is RepackerState.HB_FT: - log.debug( - "Harfbuzz packing out of resolutions, disabling sharing between extensions and " - "switching to fontTools only packing." - ) - state = RepackerState.FT_FALLBACK - else: - raise - - def tryPackingHarfbuzz(self, writer, hb_first_error_logged): - try: - log.debug("serializing '%s' with hb.repack", self.tableTag) - return writer.getAllDataUsingHarfbuzz(self.tableTag) - except (ValueError, MemoryError, hb.RepackerError) as e: - # Only log hb repacker errors the first time they occur in - # the offset-overflow resolution loop, they are just noisy. - # Maybe we can revisit this if/when uharfbuzz actually gives - # us more info as to why hb.repack failed... - if not hb_first_error_logged: - error_msg = f"{type(e).__name__}" - if str(e) != "": - error_msg += f": {e}" - log.warning( - "hb.repack failed to serialize '%s', attempting fonttools resolutions " - "; the error message was: %s", - self.tableTag, - error_msg, - ) - hb_first_error_logged = True - return writer.getAllData(remove_duplicate=False) - - def tryPackingFontTools(self, writer): - return writer.getAllData() - - def tryResolveOverflow(self, font, e, lastOverflowRecord): - ok = 0 - if lastOverflowRecord == e.value: - # Oh well... - return ok - - overflowRecord = e.value - log.info("Attempting to fix OTLOffsetOverflowError %s", e) - - if overflowRecord.itemName is None: - from .otTables import fixLookupOverFlows - - ok = fixLookupOverFlows(font, overflowRecord) - else: - from .otTables import fixSubTableOverFlows - - ok = fixSubTableOverFlows(font, overflowRecord) - - if ok: - return ok - - # Try upgrading lookup to Extension and hope - # that cross-lookup sharing not happening would - # fix overflow... - from .otTables import fixLookupOverFlows - - return fixLookupOverFlows(font, overflowRecord) - - def toXML(self, writer, font): - self.table.toXML2(writer, font) - - def fromXML(self, name, attrs, content, font): - from . import otTables - - if not hasattr(self, "table"): - tableClass = getattr(otTables, self.tableTag) - self.table = tableClass() - self.table.fromXML(name, attrs, content, font) - self.table.populateDefaults() - - def ensureDecompiled(self, recurse=True): - self.table.ensureDecompiled(recurse=recurse) - - -# https://github.com/fonttools/fonttools/pull/2285#issuecomment-834652928 -assert len(struct.pack("i", 0)) == 4 -assert array.array("i").itemsize == 4, "Oops, file a bug against fonttools." - - -class OTTableReader(object): - - """Helper class to retrieve data from an OpenType table.""" - - __slots__ = ("data", "offset", "pos", "localState", "tableTag") - - def __init__(self, data, localState=None, offset=0, tableTag=None): - self.data = data - self.offset = offset - self.pos = offset - self.localState = localState - self.tableTag = tableTag - - def advance(self, count): - self.pos += count - - def seek(self, pos): - self.pos = pos - - def copy(self): - other = self.__class__(self.data, self.localState, self.offset, self.tableTag) - other.pos = self.pos - return other - - def getSubReader(self, offset): - offset = self.offset + offset - return self.__class__(self.data, self.localState, offset, self.tableTag) - - def readValue(self, typecode, staticSize): - pos = self.pos - newpos = pos + staticSize - (value,) = struct.unpack(f">{typecode}", self.data[pos:newpos]) - self.pos = newpos - return value - - def readArray(self, typecode, staticSize, count): - pos = self.pos - newpos = pos + count * staticSize - value = array.array(typecode, self.data[pos:newpos]) - if sys.byteorder != "big": - value.byteswap() - self.pos = newpos - return value.tolist() - - def readInt8(self): - return self.readValue("b", staticSize=1) - - def readInt8Array(self, count): - return self.readArray("b", staticSize=1, count=count) - - def readShort(self): - return self.readValue("h", staticSize=2) - - def readShortArray(self, count): - return self.readArray("h", staticSize=2, count=count) - - def readLong(self): - return self.readValue("i", staticSize=4) - - def readLongArray(self, count): - return self.readArray("i", staticSize=4, count=count) - - def readUInt8(self): - return self.readValue("B", staticSize=1) - - def readUInt8Array(self, count): - return self.readArray("B", staticSize=1, count=count) - - def readUShort(self): - return self.readValue("H", staticSize=2) - - def readUShortArray(self, count): - return self.readArray("H", staticSize=2, count=count) - - def readULong(self): - return self.readValue("I", staticSize=4) - - def readULongArray(self, count): - return self.readArray("I", staticSize=4, count=count) - - def readUInt24(self): - pos = self.pos - newpos = pos + 3 - (value,) = struct.unpack(">l", b"\0" + self.data[pos:newpos]) - self.pos = newpos - return value - - def readUInt24Array(self, count): - return [self.readUInt24() for _ in range(count)] - - def readTag(self): - pos = self.pos - newpos = pos + 4 - value = Tag(self.data[pos:newpos]) - assert len(value) == 4, value - self.pos = newpos - return value - - def readData(self, count): - pos = self.pos - newpos = pos + count - value = self.data[pos:newpos] - self.pos = newpos - return value - - def __setitem__(self, name, value): - state = self.localState.copy() if self.localState else dict() - state[name] = value - self.localState = state - - def __getitem__(self, name): - return self.localState and self.localState[name] - - def __contains__(self, name): - return self.localState and name in self.localState - - -class OTTableWriter(object): - - """Helper class to gather and assemble data for OpenType tables.""" - - def __init__(self, localState=None, tableTag=None, offsetSize=2): - self.items = [] - self.pos = None - self.localState = localState - self.tableTag = tableTag - self.offsetSize = offsetSize - self.parent = None - - # DEPRECATED: 'longOffset' is kept as a property for backward compat with old code. - # You should use 'offsetSize' instead (2, 3 or 4 bytes). - @property - def longOffset(self): - return self.offsetSize == 4 - - @longOffset.setter - def longOffset(self, value): - self.offsetSize = 4 if value else 2 - - def __setitem__(self, name, value): - state = self.localState.copy() if self.localState else dict() - state[name] = value - self.localState = state - - def __getitem__(self, name): - return self.localState[name] - - def __delitem__(self, name): - del self.localState[name] - - # assembler interface - - def getDataLength(self): - """Return the length of this table in bytes, without subtables.""" - l = 0 - for item in self.items: - if hasattr(item, "getCountData"): - l += item.size - elif hasattr(item, "getData"): - l += item.offsetSize - else: - l = l + len(item) - return l - - def getData(self): - """Assemble the data for this writer/table, without subtables.""" - items = list(self.items) # make a shallow copy - pos = self.pos - numItems = len(items) - for i in range(numItems): - item = items[i] - - if hasattr(item, "getData"): - if item.offsetSize == 4: - items[i] = packULong(item.pos - pos) - elif item.offsetSize == 2: - try: - items[i] = packUShort(item.pos - pos) - except struct.error: - # provide data to fix overflow problem. - overflowErrorRecord = self.getOverflowErrorRecord(item) - - raise OTLOffsetOverflowError(overflowErrorRecord) - elif item.offsetSize == 3: - items[i] = packUInt24(item.pos - pos) - else: - raise ValueError(item.offsetSize) - - return bytesjoin(items) - - def getDataForHarfbuzz(self): - """Assemble the data for this writer/table with all offset field set to 0""" - items = list(self.items) - packFuncs = {2: packUShort, 3: packUInt24, 4: packULong} - for i, item in enumerate(items): - if hasattr(item, "getData"): - # Offset value is not needed in harfbuzz repacker, so setting offset to 0 to avoid overflow here - if item.offsetSize in packFuncs: - items[i] = packFuncs[item.offsetSize](0) - else: - raise ValueError(item.offsetSize) - - return bytesjoin(items) - - def __hash__(self): - # only works after self._doneWriting() has been called - return hash(self.items) - - def __ne__(self, other): - result = self.__eq__(other) - return result if result is NotImplemented else not result - - def __eq__(self, other): - if type(self) != type(other): - return NotImplemented - return self.offsetSize == other.offsetSize and self.items == other.items - - def _doneWriting(self, internedTables, shareExtension=False): - # Convert CountData references to data string items - # collapse duplicate table references to a unique entry - # "tables" are OTTableWriter objects. - - # For Extension Lookup types, we can - # eliminate duplicates only within the tree under the Extension Lookup, - # as offsets may exceed 64K even between Extension LookupTable subtables. - isExtension = hasattr(self, "Extension") - - # Certain versions of Uniscribe reject the font if the GSUB/GPOS top-level - # arrays (ScriptList, FeatureList, LookupList) point to the same, possibly - # empty, array. So, we don't share those. - # See: https://github.com/fonttools/fonttools/issues/518 - dontShare = hasattr(self, "DontShare") - - if isExtension and not shareExtension: - internedTables = {} - - items = self.items - for i in range(len(items)): - item = items[i] - if hasattr(item, "getCountData"): - items[i] = item.getCountData() - elif hasattr(item, "getData"): - item._doneWriting(internedTables, shareExtension=shareExtension) - # At this point, all subwriters are hashable based on their items. - # (See hash and comparison magic methods above.) So the ``setdefault`` - # call here will return the first writer object we've seen with - # equal content, or store it in the dictionary if it's not been - # seen yet. We therefore replace the subwriter object with an equivalent - # object, which deduplicates the tree. - if not dontShare: - items[i] = item = internedTables.setdefault(item, item) - self.items = tuple(items) - - def _gatherTables(self, tables, extTables, done): - # Convert table references in self.items tree to a flat - # list of tables in depth-first traversal order. - # "tables" are OTTableWriter objects. - # We do the traversal in reverse order at each level, in order to - # resolve duplicate references to be the last reference in the list of tables. - # For extension lookups, duplicate references can be merged only within the - # writer tree under the extension lookup. - - done[id(self)] = True - - numItems = len(self.items) - iRange = list(range(numItems)) - iRange.reverse() - - isExtension = hasattr(self, "Extension") - - selfTables = tables - - if isExtension: - assert ( - extTables is not None - ), "Program or XML editing error. Extension subtables cannot contain extensions subtables" - tables, extTables, done = extTables, None, {} - - # add Coverage table if it is sorted last. - sortCoverageLast = False - if hasattr(self, "sortCoverageLast"): - # Find coverage table - for i in range(numItems): - item = self.items[i] - if getattr(item, "name", None) == "Coverage": - sortCoverageLast = True - break - if id(item) not in done: - item._gatherTables(tables, extTables, done) - else: - # We're a new parent of item - pass - - for i in iRange: - item = self.items[i] - if not hasattr(item, "getData"): - continue - - if ( - sortCoverageLast - and (i == 1) - and getattr(item, "name", None) == "Coverage" - ): - # we've already 'gathered' it above - continue - - if id(item) not in done: - item._gatherTables(tables, extTables, done) - else: - # Item is already written out by other parent - pass - - selfTables.append(self) - - def _gatherGraphForHarfbuzz(self, tables, obj_list, done, objidx, virtual_edges): - real_links = [] - virtual_links = [] - item_idx = objidx - - # Merge virtual_links from parent - for idx in virtual_edges: - virtual_links.append((0, 0, idx)) - - sortCoverageLast = False - coverage_idx = 0 - if hasattr(self, "sortCoverageLast"): - # Find coverage table - for i, item in enumerate(self.items): - if getattr(item, "name", None) == "Coverage": - sortCoverageLast = True - if id(item) not in done: - coverage_idx = item_idx = item._gatherGraphForHarfbuzz( - tables, obj_list, done, item_idx, virtual_edges - ) - else: - coverage_idx = done[id(item)] - virtual_edges.append(coverage_idx) - break - - child_idx = 0 - offset_pos = 0 - for i, item in enumerate(self.items): - if hasattr(item, "getData"): - pos = offset_pos - elif hasattr(item, "getCountData"): - offset_pos += item.size - continue - else: - offset_pos = offset_pos + len(item) - continue - - if id(item) not in done: - child_idx = item_idx = item._gatherGraphForHarfbuzz( - tables, obj_list, done, item_idx, virtual_edges - ) - else: - child_idx = done[id(item)] - - real_edge = (pos, item.offsetSize, child_idx) - real_links.append(real_edge) - offset_pos += item.offsetSize - - tables.append(self) - obj_list.append((real_links, virtual_links)) - item_idx += 1 - done[id(self)] = item_idx - if sortCoverageLast: - virtual_edges.pop() - - return item_idx - - def getAllDataUsingHarfbuzz(self, tableTag): - """The Whole table is represented as a Graph. - Assemble graph data and call Harfbuzz repacker to pack the table. - Harfbuzz repacker is faster and retain as much sub-table sharing as possible, see also: - https://github.com/harfbuzz/harfbuzz/blob/main/docs/repacker.md - The input format for hb.repack() method is explained here: - https://github.com/harfbuzz/uharfbuzz/blob/main/src/uharfbuzz/_harfbuzz.pyx#L1149 - """ - internedTables = {} - self._doneWriting(internedTables, shareExtension=True) - tables = [] - obj_list = [] - done = {} - objidx = 0 - virtual_edges = [] - self._gatherGraphForHarfbuzz(tables, obj_list, done, objidx, virtual_edges) - # Gather all data in two passes: the absolute positions of all - # subtable are needed before the actual data can be assembled. - pos = 0 - for table in tables: - table.pos = pos - pos = pos + table.getDataLength() - - data = [] - for table in tables: - tableData = table.getDataForHarfbuzz() - data.append(tableData) - - if hasattr(hb, "repack_with_tag"): - return hb.repack_with_tag(str(tableTag), data, obj_list) - else: - return hb.repack(data, obj_list) - - def getAllData(self, remove_duplicate=True): - """Assemble all data, including all subtables.""" - if remove_duplicate: - internedTables = {} - self._doneWriting(internedTables) - tables = [] - extTables = [] - done = {} - self._gatherTables(tables, extTables, done) - tables.reverse() - extTables.reverse() - # Gather all data in two passes: the absolute positions of all - # subtable are needed before the actual data can be assembled. - pos = 0 - for table in tables: - table.pos = pos - pos = pos + table.getDataLength() - - for table in extTables: - table.pos = pos - pos = pos + table.getDataLength() - - data = [] - for table in tables: - tableData = table.getData() - data.append(tableData) - - for table in extTables: - tableData = table.getData() - data.append(tableData) - - return bytesjoin(data) - - # interface for gathering data, as used by table.compile() - - def getSubWriter(self, offsetSize=2): - subwriter = self.__class__( - self.localState, self.tableTag, offsetSize=offsetSize - ) - subwriter.parent = ( - self # because some subtables have idential values, we discard - ) - # the duplicates under the getAllData method. Hence some - # subtable writers can have more than one parent writer. - # But we just care about first one right now. - return subwriter - - def writeValue(self, typecode, value): - self.items.append(struct.pack(f">{typecode}", value)) - - def writeArray(self, typecode, values): - a = array.array(typecode, values) - if sys.byteorder != "big": - a.byteswap() - self.items.append(a.tobytes()) - - def writeInt8(self, value): - assert -128 <= value < 128, value - self.items.append(struct.pack(">b", value)) - - def writeInt8Array(self, values): - self.writeArray("b", values) - - def writeShort(self, value): - assert -32768 <= value < 32768, value - self.items.append(struct.pack(">h", value)) - - def writeShortArray(self, values): - self.writeArray("h", values) - - def writeLong(self, value): - self.items.append(struct.pack(">i", value)) - - def writeLongArray(self, values): - self.writeArray("i", values) - - def writeUInt8(self, value): - assert 0 <= value < 256, value - self.items.append(struct.pack(">B", value)) - - def writeUInt8Array(self, values): - self.writeArray("B", values) - - def writeUShort(self, value): - assert 0 <= value < 0x10000, value - self.items.append(struct.pack(">H", value)) - - def writeUShortArray(self, values): - self.writeArray("H", values) - - def writeULong(self, value): - self.items.append(struct.pack(">I", value)) - - def writeULongArray(self, values): - self.writeArray("I", values) - - def writeUInt24(self, value): - assert 0 <= value < 0x1000000, value - b = struct.pack(">L", value) - self.items.append(b[1:]) - - def writeUInt24Array(self, values): - for value in values: - self.writeUInt24(value) - - def writeTag(self, tag): - tag = Tag(tag).tobytes() - assert len(tag) == 4, tag - self.items.append(tag) - - def writeSubTable(self, subWriter): - self.items.append(subWriter) - - def writeCountReference(self, table, name, size=2, value=None): - ref = CountReference(table, name, size=size, value=value) - self.items.append(ref) - return ref - - def writeStruct(self, format, values): - data = struct.pack(*(format,) + values) - self.items.append(data) - - def writeData(self, data): - self.items.append(data) - - def getOverflowErrorRecord(self, item): - LookupListIndex = SubTableIndex = itemName = itemIndex = None - if self.name == "LookupList": - LookupListIndex = item.repeatIndex - elif self.name == "Lookup": - LookupListIndex = self.repeatIndex - SubTableIndex = item.repeatIndex - else: - itemName = getattr(item, "name", "") - if hasattr(item, "repeatIndex"): - itemIndex = item.repeatIndex - if self.name == "SubTable": - LookupListIndex = self.parent.repeatIndex - SubTableIndex = self.repeatIndex - elif self.name == "ExtSubTable": - LookupListIndex = self.parent.parent.repeatIndex - SubTableIndex = self.parent.repeatIndex - else: # who knows how far below the SubTable level we are! Climb back up to the nearest subtable. - itemName = ".".join([self.name, itemName]) - p1 = self.parent - while p1 and p1.name not in ["ExtSubTable", "SubTable"]: - itemName = ".".join([p1.name, itemName]) - p1 = p1.parent - if p1: - if p1.name == "ExtSubTable": - LookupListIndex = p1.parent.parent.repeatIndex - SubTableIndex = p1.parent.repeatIndex - else: - LookupListIndex = p1.parent.repeatIndex - SubTableIndex = p1.repeatIndex - - return OverflowErrorRecord( - (self.tableTag, LookupListIndex, SubTableIndex, itemName, itemIndex) - ) - - -class CountReference(object): - """A reference to a Count value, not a count of references.""" - - def __init__(self, table, name, size=None, value=None): - self.table = table - self.name = name - self.size = size - if value is not None: - self.setValue(value) - - def setValue(self, value): - table = self.table - name = self.name - if table[name] is None: - table[name] = value - else: - assert table[name] == value, (name, table[name], value) - - def getValue(self): - return self.table[self.name] - - def getCountData(self): - v = self.table[self.name] - if v is None: - v = 0 - return {1: packUInt8, 2: packUShort, 4: packULong}[self.size](v) - - -def packUInt8(value): - return struct.pack(">B", value) - - -def packUShort(value): - return struct.pack(">H", value) - - -def packULong(value): - assert 0 <= value < 0x100000000, value - return struct.pack(">I", value) - - -def packUInt24(value): - assert 0 <= value < 0x1000000, value - return struct.pack(">I", value)[1:] - - -class BaseTable(object): - - """Generic base class for all OpenType (sub)tables.""" - - def __getattr__(self, attr): - reader = self.__dict__.get("reader") - if reader: - del self.reader - font = self.font - del self.font - self.decompile(reader, font) - return getattr(self, attr) - - raise AttributeError(attr) - - def ensureDecompiled(self, recurse=False): - reader = self.__dict__.get("reader") - if reader: - del self.reader - font = self.font - del self.font - self.decompile(reader, font) - if recurse: - for subtable in self.iterSubTables(): - subtable.value.ensureDecompiled(recurse) - - def __getstate__(self): - # before copying/pickling 'lazy' objects, make a shallow copy of OTTableReader - # https://github.com/fonttools/fonttools/issues/2965 - if "reader" in self.__dict__: - state = self.__dict__.copy() - state["reader"] = self.__dict__["reader"].copy() - return state - return self.__dict__ - - @classmethod - def getRecordSize(cls, reader): - totalSize = 0 - for conv in cls.converters: - size = conv.getRecordSize(reader) - if size is NotImplemented: - return NotImplemented - countValue = 1 - if conv.repeat: - if conv.repeat in reader: - countValue = reader[conv.repeat] + conv.aux - else: - return NotImplemented - totalSize += size * countValue - return totalSize - - def getConverters(self): - return self.converters - - def getConverterByName(self, name): - return self.convertersByName[name] - - def populateDefaults(self, propagator=None): - for conv in self.getConverters(): - if conv.repeat: - if not hasattr(self, conv.name): - setattr(self, conv.name, []) - countValue = len(getattr(self, conv.name)) - conv.aux - try: - count_conv = self.getConverterByName(conv.repeat) - setattr(self, conv.repeat, countValue) - except KeyError: - # conv.repeat is a propagated count - if propagator and conv.repeat in propagator: - propagator[conv.repeat].setValue(countValue) - else: - if conv.aux and not eval(conv.aux, None, self.__dict__): - continue - if hasattr(self, conv.name): - continue # Warn if it should NOT be present?! - if hasattr(conv, "writeNullOffset"): - setattr(self, conv.name, None) # Warn? - # elif not conv.isCount: - # # Warn? - # pass - if hasattr(conv, "DEFAULT"): - # OptionalValue converters (e.g. VarIndex) - setattr(self, conv.name, conv.DEFAULT) - - def decompile(self, reader, font): - self.readFormat(reader) - table = {} - self.__rawTable = table # for debugging - for conv in self.getConverters(): - if conv.name == "SubTable": - conv = conv.getConverter(reader.tableTag, table["LookupType"]) - if conv.name == "ExtSubTable": - conv = conv.getConverter(reader.tableTag, table["ExtensionLookupType"]) - if conv.name == "FeatureParams": - conv = conv.getConverter(reader["FeatureTag"]) - if conv.name == "SubStruct": - conv = conv.getConverter(reader.tableTag, table["MorphType"]) - try: - if conv.repeat: - if isinstance(conv.repeat, int): - countValue = conv.repeat - elif conv.repeat in table: - countValue = table[conv.repeat] - else: - # conv.repeat is a propagated count - countValue = reader[conv.repeat] - countValue += conv.aux - table[conv.name] = conv.readArray(reader, font, table, countValue) - else: - if conv.aux and not eval(conv.aux, None, table): - continue - table[conv.name] = conv.read(reader, font, table) - if conv.isPropagated: - reader[conv.name] = table[conv.name] - except Exception as e: - name = conv.name - e.args = e.args + (name,) - raise - - if hasattr(self, "postRead"): - self.postRead(table, font) - else: - self.__dict__.update(table) - - del self.__rawTable # succeeded, get rid of debugging info - - def compile(self, writer, font): - self.ensureDecompiled() - # TODO Following hack to be removed by rewriting how FormatSwitching tables - # are handled. - # https://github.com/fonttools/fonttools/pull/2238#issuecomment-805192631 - if hasattr(self, "preWrite"): - deleteFormat = not hasattr(self, "Format") - table = self.preWrite(font) - deleteFormat = deleteFormat and hasattr(self, "Format") - else: - deleteFormat = False - table = self.__dict__.copy() - - # some count references may have been initialized in a custom preWrite; we set - # these in the writer's state beforehand (instead of sequentially) so they will - # be propagated to all nested subtables even if the count appears in the current - # table only *after* the offset to the subtable that it is counting. - for conv in self.getConverters(): - if conv.isCount and conv.isPropagated: - value = table.get(conv.name) - if isinstance(value, CountReference): - writer[conv.name] = value - - if hasattr(self, "sortCoverageLast"): - writer.sortCoverageLast = 1 - - if hasattr(self, "DontShare"): - writer.DontShare = True - - if hasattr(self.__class__, "LookupType"): - writer["LookupType"].setValue(self.__class__.LookupType) - - self.writeFormat(writer) - for conv in self.getConverters(): - value = table.get( - conv.name - ) # TODO Handle defaults instead of defaulting to None! - if conv.repeat: - if value is None: - value = [] - countValue = len(value) - conv.aux - if isinstance(conv.repeat, int): - assert len(value) == conv.repeat, "expected %d values, got %d" % ( - conv.repeat, - len(value), - ) - elif conv.repeat in table: - CountReference(table, conv.repeat, value=countValue) - else: - # conv.repeat is a propagated count - writer[conv.repeat].setValue(countValue) - try: - conv.writeArray(writer, font, table, value) - except Exception as e: - e.args = e.args + (conv.name + "[]",) - raise - elif conv.isCount: - # Special-case Count values. - # Assumption: a Count field will *always* precede - # the actual array(s). - # We need a default value, as it may be set later by a nested - # table. We will later store it here. - # We add a reference: by the time the data is assembled - # the Count value will be filled in. - # We ignore the current count value since it will be recomputed, - # unless it's a CountReference that was already initialized in a custom preWrite. - if isinstance(value, CountReference): - ref = value - ref.size = conv.staticSize - writer.writeData(ref) - table[conv.name] = ref.getValue() - else: - ref = writer.writeCountReference(table, conv.name, conv.staticSize) - table[conv.name] = None - if conv.isPropagated: - writer[conv.name] = ref - elif conv.isLookupType: - # We make sure that subtables have the same lookup type, - # and that the type is the same as the one set on the - # Lookup object, if any is set. - if conv.name not in table: - table[conv.name] = None - ref = writer.writeCountReference( - table, conv.name, conv.staticSize, table[conv.name] - ) - writer["LookupType"] = ref - else: - if conv.aux and not eval(conv.aux, None, table): - continue - try: - conv.write(writer, font, table, value) - except Exception as e: - name = value.__class__.__name__ if value is not None else conv.name - e.args = e.args + (name,) - raise - if conv.isPropagated: - writer[conv.name] = value - - if deleteFormat: - del self.Format - - def readFormat(self, reader): - pass - - def writeFormat(self, writer): - pass - - def toXML(self, xmlWriter, font, attrs=None, name=None): - tableName = name if name else self.__class__.__name__ - if attrs is None: - attrs = [] - if hasattr(self, "Format"): - attrs = attrs + [("Format", self.Format)] - xmlWriter.begintag(tableName, attrs) - xmlWriter.newline() - self.toXML2(xmlWriter, font) - xmlWriter.endtag(tableName) - xmlWriter.newline() - - def toXML2(self, xmlWriter, font): - # Simpler variant of toXML, *only* for the top level tables (like GPOS, GSUB). - # This is because in TTX our parent writes our main tag, and in otBase.py we - # do it ourselves. I think I'm getting schizophrenic... - for conv in self.getConverters(): - if conv.repeat: - value = getattr(self, conv.name, []) - for i in range(len(value)): - item = value[i] - conv.xmlWrite(xmlWriter, font, item, conv.name, [("index", i)]) - else: - if conv.aux and not eval(conv.aux, None, vars(self)): - continue - value = getattr( - self, conv.name, None - ) # TODO Handle defaults instead of defaulting to None! - conv.xmlWrite(xmlWriter, font, value, conv.name, []) - - def fromXML(self, name, attrs, content, font): - try: - conv = self.getConverterByName(name) - except KeyError: - raise # XXX on KeyError, raise nice error - value = conv.xmlRead(attrs, content, font) - if conv.repeat: - seq = getattr(self, conv.name, None) - if seq is None: - seq = [] - setattr(self, conv.name, seq) - seq.append(value) - else: - setattr(self, conv.name, value) - - def __ne__(self, other): - result = self.__eq__(other) - return result if result is NotImplemented else not result - - def __eq__(self, other): - if type(self) != type(other): - return NotImplemented - - self.ensureDecompiled() - other.ensureDecompiled() - - return self.__dict__ == other.__dict__ - - class SubTableEntry(NamedTuple): - """See BaseTable.iterSubTables()""" - - name: str - value: "BaseTable" - index: Optional[int] = None # index into given array, None for single values - - def iterSubTables(self) -> Iterator[SubTableEntry]: - """Yield (name, value, index) namedtuples for all subtables of current table. - - A sub-table is an instance of BaseTable (or subclass thereof) that is a child - of self, the current parent table. - The tuples also contain the attribute name (str) of the of parent table to get - a subtable, and optionally, for lists of subtables (i.e. attributes associated - with a converter that has a 'repeat'), an index into the list containing the - given subtable value. - This method can be useful to traverse trees of otTables. - """ - for conv in self.getConverters(): - name = conv.name - value = getattr(self, name, None) - if value is None: - continue - if isinstance(value, BaseTable): - yield self.SubTableEntry(name, value) - elif isinstance(value, list): - yield from ( - self.SubTableEntry(name, v, index=i) - for i, v in enumerate(value) - if isinstance(v, BaseTable) - ) - - # instance (not @class)method for consistency with FormatSwitchingBaseTable - def getVariableAttrs(self): - return getVariableAttrs(self.__class__) - - -class FormatSwitchingBaseTable(BaseTable): - - """Minor specialization of BaseTable, for tables that have multiple - formats, eg. CoverageFormat1 vs. CoverageFormat2.""" - - @classmethod - def getRecordSize(cls, reader): - return NotImplemented - - def getConverters(self): - try: - fmt = self.Format - except AttributeError: - # some FormatSwitchingBaseTables (e.g. Coverage) no longer have 'Format' - # attribute after fully decompiled, only gain one in preWrite before being - # recompiled. In the decompiled state, these hand-coded classes defined in - # otTables.py lose their format-specific nature and gain more high-level - # attributes that are not tied to converters. - return [] - return self.converters.get(self.Format, []) - - def getConverterByName(self, name): - return self.convertersByName[self.Format][name] - - def readFormat(self, reader): - self.Format = reader.readUShort() - - def writeFormat(self, writer): - writer.writeUShort(self.Format) - - def toXML(self, xmlWriter, font, attrs=None, name=None): - BaseTable.toXML(self, xmlWriter, font, attrs, name) - - def getVariableAttrs(self): - return getVariableAttrs(self.__class__, self.Format) - - -class UInt8FormatSwitchingBaseTable(FormatSwitchingBaseTable): - def readFormat(self, reader): - self.Format = reader.readUInt8() - - def writeFormat(self, writer): - writer.writeUInt8(self.Format) - - -formatSwitchingBaseTables = { - "uint16": FormatSwitchingBaseTable, - "uint8": UInt8FormatSwitchingBaseTable, -} - - -def getFormatSwitchingBaseTableClass(formatType): - try: - return formatSwitchingBaseTables[formatType] - except KeyError: - raise TypeError(f"Unsupported format type: {formatType!r}") - - -# memoize since these are parsed from otData.py, thus stay constant -@lru_cache() -def getVariableAttrs(cls: BaseTable, fmt: Optional[int] = None) -> Tuple[str]: - """Return sequence of variable table field names (can be empty). - - Attributes are deemed "variable" when their otData.py's description contain - 'VarIndexBase + {offset}', e.g. COLRv1 PaintVar* tables. - """ - if not issubclass(cls, BaseTable): - raise TypeError(cls) - if issubclass(cls, FormatSwitchingBaseTable): - if fmt is None: - raise TypeError(f"'fmt' is required for format-switching {cls.__name__}") - converters = cls.convertersByName[fmt] - else: - converters = cls.convertersByName - # assume if no 'VarIndexBase' field is present, table has no variable fields - if "VarIndexBase" not in converters: - return () - varAttrs = {} - for name, conv in converters.items(): - offset = conv.getVarIndexOffset() - if offset is not None: - varAttrs[name] = offset - return tuple(sorted(varAttrs, key=varAttrs.__getitem__)) - - -# -# Support for ValueRecords -# -# This data type is so different from all other OpenType data types that -# it requires quite a bit of code for itself. It even has special support -# in OTTableReader and OTTableWriter... -# - -valueRecordFormat = [ - # Mask Name isDevice signed - (0x0001, "XPlacement", 0, 1), - (0x0002, "YPlacement", 0, 1), - (0x0004, "XAdvance", 0, 1), - (0x0008, "YAdvance", 0, 1), - (0x0010, "XPlaDevice", 1, 0), - (0x0020, "YPlaDevice", 1, 0), - (0x0040, "XAdvDevice", 1, 0), - (0x0080, "YAdvDevice", 1, 0), - # reserved: - (0x0100, "Reserved1", 0, 0), - (0x0200, "Reserved2", 0, 0), - (0x0400, "Reserved3", 0, 0), - (0x0800, "Reserved4", 0, 0), - (0x1000, "Reserved5", 0, 0), - (0x2000, "Reserved6", 0, 0), - (0x4000, "Reserved7", 0, 0), - (0x8000, "Reserved8", 0, 0), -] - - -def _buildDict(): - d = {} - for mask, name, isDevice, signed in valueRecordFormat: - d[name] = mask, isDevice, signed - return d - - -valueRecordFormatDict = _buildDict() - - -class ValueRecordFactory(object): - - """Given a format code, this object convert ValueRecords.""" - - def __init__(self, valueFormat): - format = [] - for mask, name, isDevice, signed in valueRecordFormat: - if valueFormat & mask: - format.append((name, isDevice, signed)) - self.format = format - - def __len__(self): - return len(self.format) - - def readValueRecord(self, reader, font): - format = self.format - if not format: - return None - valueRecord = ValueRecord() - for name, isDevice, signed in format: - if signed: - value = reader.readShort() - else: - value = reader.readUShort() - if isDevice: - if value: - from . import otTables - - subReader = reader.getSubReader(value) - value = getattr(otTables, name)() - value.decompile(subReader, font) - else: - value = None - setattr(valueRecord, name, value) - return valueRecord - - def writeValueRecord(self, writer, font, valueRecord): - for name, isDevice, signed in self.format: - value = getattr(valueRecord, name, 0) - if isDevice: - if value: - subWriter = writer.getSubWriter() - writer.writeSubTable(subWriter) - value.compile(subWriter, font) - else: - writer.writeUShort(0) - elif signed: - writer.writeShort(value) - else: - writer.writeUShort(value) - - -class ValueRecord(object): - - # see ValueRecordFactory - - def __init__(self, valueFormat=None, src=None): - if valueFormat is not None: - for mask, name, isDevice, signed in valueRecordFormat: - if valueFormat & mask: - setattr(self, name, None if isDevice else 0) - if src is not None: - for key, val in src.__dict__.items(): - if not hasattr(self, key): - continue - setattr(self, key, val) - elif src is not None: - self.__dict__ = src.__dict__.copy() - - def getFormat(self): - format = 0 - for name in self.__dict__.keys(): - format = format | valueRecordFormatDict[name][0] - return format - - def getEffectiveFormat(self): - format = 0 - for name, value in self.__dict__.items(): - if value: - format = format | valueRecordFormatDict[name][0] - return format - - def toXML(self, xmlWriter, font, valueName, attrs=None): - if attrs is None: - simpleItems = [] - else: - simpleItems = list(attrs) - for mask, name, isDevice, format in valueRecordFormat[:4]: # "simple" values - if hasattr(self, name): - simpleItems.append((name, getattr(self, name))) - deviceItems = [] - for mask, name, isDevice, format in valueRecordFormat[4:8]: # device records - if hasattr(self, name): - device = getattr(self, name) - if device is not None: - deviceItems.append((name, device)) - if deviceItems: - xmlWriter.begintag(valueName, simpleItems) - xmlWriter.newline() - for name, deviceRecord in deviceItems: - if deviceRecord is not None: - deviceRecord.toXML(xmlWriter, font, name=name) - xmlWriter.endtag(valueName) - xmlWriter.newline() - else: - xmlWriter.simpletag(valueName, simpleItems) - xmlWriter.newline() - - def fromXML(self, name, attrs, content, font): - from . import otTables - - for k, v in attrs.items(): - setattr(self, k, int(v)) - for element in content: - if not isinstance(element, tuple): - continue - name, attrs, content = element - value = getattr(otTables, name)() - for elem2 in content: - if not isinstance(elem2, tuple): - continue - name2, attrs2, content2 = elem2 - value.fromXML(name2, attrs2, content2, font) - setattr(self, name, value) - - def __ne__(self, other): - result = self.__eq__(other) - return result if result is NotImplemented else not result - - def __eq__(self, other): - if type(self) != type(other): - return NotImplemented - return self.__dict__ == other.__dict__ diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/cbs_internal.h b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/cbs_internal.h deleted file mode 100644 index e585c779341fc970fff23783f3a4545554beadac..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/cbs_internal.h +++ /dev/null @@ -1,253 +0,0 @@ -/* - * This file is part of FFmpeg. - * - * FFmpeg is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * FFmpeg is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with FFmpeg; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef AVCODEC_CBS_INTERNAL_H -#define AVCODEC_CBS_INTERNAL_H - -#include - -#include "libavutil/buffer.h" -#include "libavutil/log.h" - -#include "cbs.h" -#include "codec_id.h" -#include "get_bits.h" -#include "put_bits.h" - - -enum CBSContentType { - // Unit content may contain some references to other structures, but all - // managed via buffer reference counting. The descriptor defines the - // structure offsets of every buffer reference. - CBS_CONTENT_TYPE_INTERNAL_REFS, - // Unit content is something more complex. The descriptor defines - // special functions to manage the content. - CBS_CONTENT_TYPE_COMPLEX, -}; - -enum { - // Maximum number of unit types described by the same non-range - // unit type descriptor. - CBS_MAX_LIST_UNIT_TYPES = 3, - // Maximum number of reference buffer offsets in any one unit. - CBS_MAX_REF_OFFSETS = 2, - // Special value used in a unit type descriptor to indicate that it - // applies to a large range of types rather than a set of discrete - // values. - CBS_UNIT_TYPE_RANGE = -1, -}; - -typedef const struct CodedBitstreamUnitTypeDescriptor { - // Number of entries in the unit_types array, or the special value - // CBS_UNIT_TYPE_RANGE to indicate that the range fields should be - // used instead. - int nb_unit_types; - - union { - // Array of unit types that this entry describes. - CodedBitstreamUnitType list[CBS_MAX_LIST_UNIT_TYPES]; - // Start and end of unit type range, used if nb_unit_types is - // CBS_UNIT_TYPE_RANGE. - struct { - CodedBitstreamUnitType start; - CodedBitstreamUnitType end; - } range; - } unit_type; - - // The type of content described. - enum CBSContentType content_type; - // The size of the structure which should be allocated to contain - // the decomposed content of this type of unit. - size_t content_size; - - union { - // This union's state is determined by content_type: - // ref for CBS_CONTENT_TYPE_INTERNAL_REFS, - // complex for CBS_CONTENT_TYPE_COMPLEX. - struct { - // Number of entries in the ref_offsets array. - // May be zero, then the structure is POD-like. - int nb_offsets; - // The structure must contain two adjacent elements: - // type *field; - // AVBufferRef *field_ref; - // where field points to something in the buffer referred to by - // field_ref. This offset is then set to offsetof(struct, field). - size_t offsets[CBS_MAX_REF_OFFSETS]; - } ref; - - struct { - void (*content_free)(void *opaque, uint8_t *data); - int (*content_clone)(AVBufferRef **ref, CodedBitstreamUnit *unit); - } complex; - } type; -} CodedBitstreamUnitTypeDescriptor; - -typedef struct CodedBitstreamType { - enum AVCodecID codec_id; - - // A class for the private data, used to declare private AVOptions. - // This field is NULL for types that do not declare any options. - // If this field is non-NULL, the first member of the filter private data - // must be a pointer to AVClass. - const AVClass *priv_class; - - size_t priv_data_size; - - // List of unit type descriptors for this codec. - // Terminated by a descriptor with nb_unit_types equal to zero. - const CodedBitstreamUnitTypeDescriptor *unit_types; - - // Split frag->data into coded bitstream units, creating the - // frag->units array. Fill data but not content on each unit. - // The header argument should be set if the fragment came from - // a header block, which may require different parsing for some - // codecs (e.g. the AVCC header in H.264). - int (*split_fragment)(CodedBitstreamContext *ctx, - CodedBitstreamFragment *frag, - int header); - - // Read the unit->data bitstream and decompose it, creating - // unit->content. - int (*read_unit)(CodedBitstreamContext *ctx, - CodedBitstreamUnit *unit); - - // Write the data bitstream from unit->content into pbc. - // Return value AVERROR(ENOSPC) indicates that pbc was too small. - int (*write_unit)(CodedBitstreamContext *ctx, - CodedBitstreamUnit *unit, - PutBitContext *pbc); - - // Read the data from all of frag->units and assemble it into - // a bitstream for the whole fragment. - int (*assemble_fragment)(CodedBitstreamContext *ctx, - CodedBitstreamFragment *frag); - - // Reset the codec internal state. - void (*flush)(CodedBitstreamContext *ctx); - - // Free the codec internal state. - void (*close)(CodedBitstreamContext *ctx); -} CodedBitstreamType; - - -// Helper functions for trace output. - -void ff_cbs_trace_header(CodedBitstreamContext *ctx, - const char *name); - -void ff_cbs_trace_syntax_element(CodedBitstreamContext *ctx, int position, - const char *name, const int *subscripts, - const char *bitstring, int64_t value); - - -// Helper functions for read/write of common bitstream elements, including -// generation of trace output. - -int ff_cbs_read_unsigned(CodedBitstreamContext *ctx, GetBitContext *gbc, - int width, const char *name, - const int *subscripts, uint32_t *write_to, - uint32_t range_min, uint32_t range_max); - -int ff_cbs_write_unsigned(CodedBitstreamContext *ctx, PutBitContext *pbc, - int width, const char *name, - const int *subscripts, uint32_t value, - uint32_t range_min, uint32_t range_max); - -int ff_cbs_read_signed(CodedBitstreamContext *ctx, GetBitContext *gbc, - int width, const char *name, - const int *subscripts, int32_t *write_to, - int32_t range_min, int32_t range_max); - -int ff_cbs_write_signed(CodedBitstreamContext *ctx, PutBitContext *pbc, - int width, const char *name, - const int *subscripts, int32_t value, - int32_t range_min, int32_t range_max); - -// The largest unsigned value representable in N bits, suitable for use as -// range_max in the above functions. -#define MAX_UINT_BITS(length) ((UINT64_C(1) << (length)) - 1) - -// The largest signed value representable in N bits, suitable for use as -// range_max in the above functions. -#define MAX_INT_BITS(length) ((INT64_C(1) << ((length) - 1)) - 1) - -// The smallest signed value representable in N bits, suitable for use as -// range_min in the above functions. -#define MIN_INT_BITS(length) (-(INT64_C(1) << ((length) - 1))) - -#define TYPE_LIST(...) { __VA_ARGS__ } -#define CBS_UNIT_TYPE_POD(type_, structure) { \ - .nb_unit_types = 1, \ - .unit_type.list = { type_ }, \ - .content_type = CBS_CONTENT_TYPE_INTERNAL_REFS, \ - .content_size = sizeof(structure), \ - .type.ref = { .nb_offsets = 0 }, \ - } -#define CBS_UNIT_RANGE_POD(range_start, range_end, structure) { \ - .nb_unit_types = CBS_UNIT_TYPE_RANGE, \ - .unit_type.range.start = range_start, \ - .unit_type.range.end = range_end, \ - .content_type = CBS_CONTENT_TYPE_INTERNAL_REFS, \ - .content_size = sizeof(structure), \ - .type.ref = { .nb_offsets = 0 }, \ - } - -#define CBS_UNIT_TYPES_INTERNAL_REF(types, structure, ref_field) { \ - .nb_unit_types = FF_ARRAY_ELEMS((CodedBitstreamUnitType[])TYPE_LIST types), \ - .unit_type.list = TYPE_LIST types, \ - .content_type = CBS_CONTENT_TYPE_INTERNAL_REFS, \ - .content_size = sizeof(structure), \ - .type.ref = { .nb_offsets = 1, \ - .offsets = { offsetof(structure, ref_field) } }, \ - } -#define CBS_UNIT_TYPE_INTERNAL_REF(type, structure, ref_field) \ - CBS_UNIT_TYPES_INTERNAL_REF((type), structure, ref_field) - -#define CBS_UNIT_RANGE_INTERNAL_REF(range_start, range_end, structure, ref_field) { \ - .nb_unit_types = CBS_UNIT_TYPE_RANGE, \ - .unit_type.range.start = range_start, \ - .unit_type.range.end = range_end, \ - .content_type = CBS_CONTENT_TYPE_INTERNAL_REFS, \ - .content_size = sizeof(structure), \ - .type.ref = { .nb_offsets = 1, \ - .offsets = { offsetof(structure, ref_field) } }, \ - } - -#define CBS_UNIT_TYPES_COMPLEX(types, structure, free_func) { \ - .nb_unit_types = FF_ARRAY_ELEMS((CodedBitstreamUnitType[])TYPE_LIST types), \ - .unit_type.list = TYPE_LIST types, \ - .content_type = CBS_CONTENT_TYPE_COMPLEX, \ - .content_size = sizeof(structure), \ - .type.complex = { .content_free = free_func }, \ - } -#define CBS_UNIT_TYPE_COMPLEX(type, structure, free_func) \ - CBS_UNIT_TYPES_COMPLEX((type), structure, free_func) - -#define CBS_UNIT_TYPE_END_OF_LIST { .nb_unit_types = 0 } - - -extern const CodedBitstreamType ff_cbs_type_av1; -extern const CodedBitstreamType ff_cbs_type_h264; -extern const CodedBitstreamType ff_cbs_type_h265; -extern const CodedBitstreamType ff_cbs_type_jpeg; -extern const CodedBitstreamType ff_cbs_type_mpeg2; -extern const CodedBitstreamType ff_cbs_type_vp9; - - -#endif /* AVCODEC_CBS_INTERNAL_H */ diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/mips/videodsp_init.c b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/mips/videodsp_init.c deleted file mode 100644 index 89409fc8fd2055c5cb806210930d8d44331f6f8c..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/mips/videodsp_init.c +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017 Kaustubh Raste (kaustubh.raste@imgtec.com) - * - * 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/mips/cpu.h" -#include "config.h" -#include "libavutil/attributes.h" -#include "libavutil/mips/asmdefs.h" -#include "libavcodec/videodsp.h" - -static void prefetch_mips(const uint8_t *mem, ptrdiff_t stride, int h) -{ - register const uint8_t *p = mem; - - __asm__ volatile ( - "1: \n\t" - "pref 4, 0(%[p]) \n\t" - "pref 4, 32(%[p]) \n\t" - PTR_ADDIU" %[h], %[h], -1 \n\t" - PTR_ADDU " %[p], %[p], %[stride] \n\t" - - "bnez %[h], 1b \n\t" - - : [p] "+r" (p), [h] "+r" (h) - : [stride] "r" (stride) - ); -} - -av_cold void ff_videodsp_init_mips(VideoDSPContext *ctx, int bpc) -{ - int cpu_flags = av_get_cpu_flags(); - - if (have_msa(cpu_flags)) - ctx->prefetch = prefetch_mips; -} diff --git a/spaces/congsaPfin/Manga-OCR/logs/Apkmonk Download and Play Together with Millions of Players.md b/spaces/congsaPfin/Manga-OCR/logs/Apkmonk Download and Play Together with Millions of Players.md deleted file mode 100644 index 30474426a13a20c591182839b1b60a1e071285ea..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Apkmonk Download and Play Together with Millions of Players.md +++ /dev/null @@ -1,111 +0,0 @@ -
-

Play Together APKMonk: A Fun and Social Game for Everyone

-

Do you love playing games with your friends online? Do you want to experience a virtual world where you can do anything you want? Do you like cute and colorful graphics and characters? If you answered yes to any of these questions, then you should try Play Together APKMonk, a fun and social game for everyone.

-

What is Play Together APKMonk?

-

Play Together APKMonk is a game developed by Haegin Co., Ltd., a Korean company that specializes in creating casual and social games. It is a game that lets you create your own character and explore a vast island with other players. You can chat, make friends, join clubs, play mini-games, go fishing, shopping, camping, cooking, and more. You can also customize your character and your home with various items and outfits that you can buy or earn in the game.

-

play together apkmonk


Download ✏ ✏ ✏ https://urlca.com/2uO5Ym



-

A virtual world where you can play with friends and strangers

-

One of the main features of Play Together APKMonk is that it is a multiplayer game that allows you to interact with other players from all over the world. You can meet new people, chat with them, send them gifts, invite them to your home, or visit their homes. You can also join or create a club, which is like a group of players who share common interests or goals. You can chat with your club members, help each other, or compete with other clubs.

-

A casual and relaxing game with various activities and mini-games

-

Another feature of Play Together APKMonk is that it is a casual and relaxing game that does not have any pressure or violence. You can play at your own pace and enjoy various activities and mini-games that suit your mood. You can go fishing, catch bugs, plant flowers, cook dishes, play soccer, ride bikes, go camping, watch movies, play instruments, and more. You can also participate in seasonal events that offer special rewards and challenges.

-

A free-to-play game with optional in-app purchases

-

Play Together APKMonk is a free-to-play game that does not require any subscription or registration. You can download it from the official website or Google Play Store and start playing right away. However, if you want to enhance your gaming experience, you can also buy some in-app purchases that offer extra coins, gems, items, outfits, pets, etc. These purchases are optional and do not affect the core gameplay.

-

How to download and install Play Together APKMonk?

-

If you are interested in playing Play Together APKMonk, here are the steps that you need to follow:

-

Download the APK file from the official website or Google Play Store

-

The first step is to download the APK file of Play Together APKMonk from the official website or Google Play Store. The APK file is a package file that contains all the data and resources needed to run the game on your device. The size of the file is about 100 MB, so make sure you have enough space on your device before downloading it

Install the APK file on your device using XAPK Installer or other tools

-

The second step is to install the APK file on your device using XAPK Installer or other tools that can handle APK files. XAPK Installer is a free app that can help you install APK files easily and safely. You can download it from Google Play Store or from its official website. To use XAPK Installer, follow these steps:

-
    -
  • Open XAPK Installer and grant it the necessary permissions.
  • -
  • Locate the APK file of Play Together APKMonk that you downloaded and tap on it.
  • -
  • Follow the instructions on the screen to install the game.
  • -
  • Wait for the installation to finish and launch the game.
  • -
-

If you do not want to use XAPK Installer, you can also use other tools that can handle APK files, such as APKPure, APKMirror, etc. However, make sure that you download these tools from trusted sources and scan them for viruses before using them.

-

Launch the game and create your character

-

The third step is to launch the game and create your character. When you open the game for the first time, you will see a welcome screen that will ask you to choose your language and agree to the terms of service and privacy policy. After that, you will be able to create your character by choosing your gender, hairstyle, face, skin tone, eye color, etc. You can also change your character's name and voice. Once you are done with your character creation, you can start playing the game.

-

play together apkmonk download
-play together apkmonk mod
-play together apkmonk latest version
-play together apkmonk update
-play together apkmonk free
-play together apkmonk online
-play together apkmonk hack
-play together apkmonk android
-play together apkmonk install
-play together apkmonk review
-play together apkmonk app
-play together apkmonk game
-play together apkmonk social
-play together apkmonk simulation
-play together apkmonk fun
-play together apkmonk guide
-play together apkmonk tips
-play together apkmonk tricks
-play together apkmonk cheats
-play together apkmonk codes
-play together apkmonk rewards
-play together apkmonk events
-play together apkmonk pets
-play together apkmonk island
-play together apkmonk friends
-play together apkmonk chat
-play together apkmonk voice
-play together apkmonk party
-play together apkmonk fashion
-play together apkmonk outfits
-play together apkmonk shopping
-play together apkmonk cooking
-play together apkmonk fishing
-play together apkmonk camping
-play together apkmonk gardening
-play together apkmonk mini games
-play together apkmonk adventure
-play together apkmonk quests
-play together apkmonk challenges
-play together apkmonk seasons
-play together apkmonk themes
-play together apkmonk features
-play together apkmonk graphics
-play together apkmonk sound
-play together apkmonk controls
-play together apkmonk rating
-play together apkmonk feedback
-play together apkmonk support
-play together apkmonk alternatives

-

How to play Play Together APKMonk?

-

Now that you have downloaded and installed Play Together APKMonk, you might be wondering how to play it. Here are some tips and tricks that will help you enjoy the game:

-

Explore the island and interact with other players

-

The main feature of Play Together APKMonk is that it is a social game that allows you to explore a huge island with other players. You can walk around, run, jump, swim, ride vehicles, etc. You can also interact with other players by tapping on them and choosing from various options, such as chat, gift, invite, follow, etc. You can also use emojis and gestures to express yourself. You can also join or create a party with up to four players and chat with them privately.

-

Join or create a club and chat with your club members

-

Another feature of Play Together APKMonk is that it is a club game that allows you to join or create a club with up to 20 players. A club is like a group of players who share common interests or goals. You can chat with your club members, help each other, or compete with other clubs. You can also customize your club name, logo, description, etc. To join or create a club, you need to go to the club house on the island and talk to the club manager.

-

Customize your character and your home with various items and outfits

-

Another feature of Play Together APKMonk is that it is a customization game that allows you to customize your character and your home with various items and outfits. You can buy or earn items and outfits in the game by playing mini-games, completing quests, participating in events, etc. You can also get items and outfits from other players as gifts or trades. You can change your character's appearance by going to the salon on the island and talking to the stylist. You can also change your home's appearance by going to your home and tapping on the edit button.

-

Participate in events and quests to earn rewards and coins

-

Another feature of Play Together APKMonk is that it is an event game that allows you to participate in events and quests to earn rewards and coins. Events are special activities that happen periodically in the game and offer unique rewards and challenges. Quests are tasks that you can do anytime in the game and offer coins and items as rewards. You can check the current events and quests by tapping on the menu button on the top right corner of the screen.

-

What are the benefits of playing Play Together APKMonk?

-

You might be wondering why you should play Play Together APKMonk instead of other games. Here are some of the benefits of playing this game:

-

Enjoy a fun and social game with millions of players worldwide

-

One of the benefits of playing Play Together APKMonk is that it is a fun and social game that connects you with millions of players worldwide. You can meet new people, chat with them, make friends, join clubs, play mini-games, go fishing, shopping, camping, cooking, and more. You can also have fun with your friends or make new ones by playing together.

-

Develop your creativity and imagination with endless possibilities

-

Another benefit of playing Play Together APKMonk is that it is a creativity game that allows you to develop your creativity and imagination with endless possibilities. You can create your own character and home with various items and outfits that suit your style and personality. You can also express yourself with emojis and gestures that convey your emotions and feelings. You can also explore the island and discover new places and secrets.

-

Relax and unwind from stress and boredom with a cute and colorful game

-

Another benefit of playing Play Together APKMonk is that it is a relaxing game that allows you to relax and unwind from stress and boredom with a cute and colorful game. The game has a cheerful and bright atmosphere that will make you feel happy and calm. The game also has a simple and easy gameplay that does not require any skills or strategies. You can just play at your own pace and enjoy the game without any pressure or violence.

-

Conclusion

-

Play Together APKMonk is a fun and social game for everyone who loves playing games with their friends online. It is a game that lets you create your own character and explore a vast island with other players. You can chat, make friends, join clubs, play mini-games, go fishing, shopping, camping, cooking, and more. You can also customize your character and your home with various items and outfits that you can buy or earn in the game. You can also participate in events and quests to earn rewards and coins. Play Together APKMonk is a free-to-play game that does not require any subscription or registration. You can download it from the official website or Google Play Store and start playing right away. However, if you want to enhance your gaming experience, you can also buy some in-app purchases that offer extra coins, gems, items, outfits, pets, etc.

-

If you are looking for a fun and social game that will keep you entertained and connected with millions of players worldwide, then you should try Play Together APKMonk. It is a game that will let you enjoy a virtual world where you can do anything you want. It is a game that will let you develop your creativity and imagination with endless possibilities. It is a game that will let you relax and unwind from stress and boredom with a cute and colorful game.

-

So what are you waiting for? Download Play Together APKMonk now and start playing with your friends!

-

FAQs

-

Here are some of the frequently asked questions about Play Together APKMonk:

-

Q: Is Play Together APKMonk safe to download?

-

A: Yes, Play Together APKMonk is safe to download as long as you download it from the official website or Google Play Store. However, be careful of downloading it from other sources as they might contain viruses or malware that could harm your device.

-

Q: Is Play Together APKMonk compatible with my device?

-

A: Play Together APKMonk is compatible with most Android devices that have Android 5.0 or higher. However, some devices might experience some performance issues or bugs depending on their specifications. If you encounter any problems while playing the game, you can contact the customer support team through the game settings or email them at cs@haegin.kr.

-

Q: How can I play Play Together APKMonk with my friends?

-

A: You can play Play Together APKMonk with your friends by adding them as friends in the game. To do this, you need to tap on their character and choose the add friend option. You can also search for their name or ID in the friend list menu. Once you are friends, you can chat with them, invite them to your home, join their party, or play mini-games together.

-

Q: How can I get more coins and gems in Play Together APKMonk?

-

A: You can get more coins and gems in Play Together APKMonk by playing mini-games, completing quests, participating in events, watching ads, etc. You can also buy them with real money through in-app purchases if you want to get them faster.

-

Q: How can I change my character's name in Play Together APKMonk?

-

A: You can change your character's name in Play Together APKMonk by going to the salon on the island and talking to the stylist. You will need to pay 1000 coins to change your name once.

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Download Car Parking Multiplayer MOD APK and Enjoy Unlimited Money and Fun.md b/spaces/congsaPfin/Manga-OCR/logs/Download Car Parking Multiplayer MOD APK and Enjoy Unlimited Money and Fun.md deleted file mode 100644 index c2502cdaa6c577a5f57250cfcf761cce6341969d..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Download Car Parking Multiplayer MOD APK and Enjoy Unlimited Money and Fun.md +++ /dev/null @@ -1,86 +0,0 @@ - -

Download Car Parking Multiplayer Mod APK Unlimited Coins

-

If you are a fan of car games, you might have heard of Car Parking Multiplayer, one of the most realistic and immersive car simulation games on Android. In this game, you can drive various cars, customize them, explore an open world map, and interact with other players online. However, if you want to enjoy the game to the fullest, you might need a lot of coins and money to unlock and upgrade your cars, as well as to buy accessories and items. That's why you should download Car Parking Multiplayer Mod APK Unlimited Coins, a modified version of the game that gives you unlimited resources and features. In this article, we will tell you what is Car Parking Multiplayer, why you should download its mod apk, and how to do it.

-

download car parking multiplayer mod apk unlimited coins


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



-

What is Car Parking Multiplayer?

-

Car Parking Multiplayer is a car simulation game developed by olzhass, a popular game studio that specializes in realistic car games. The game has over 100 million downloads on Google Play Store and has received positive reviews from players and critics alike. The game offers a variety of features that make it stand out from other car games, such as:

-

Features of Car Parking Multiplayer

-

Realistic car physics and graphics

-

The game boasts realistic car physics and graphics that make you feel like you are driving a real car. You can experience different driving conditions, such as rain, snow, day, night, etc. You can also adjust the camera angle, steering wheel sensitivity, brake force, etc. to suit your preference. The game supports high-quality graphics settings that make the cars and the environment look stunning.

-

Open world map and multiplayer mode

-

The game features an open world map that you can explore freely with your car. You can drive around different locations, such as cities, airports, deserts, etc. You can also interact with other players online in the multiplayer mode. You can chat with them, join their races, exchange cars, etc. You can also create your own server and invite your friends to play with you.

-

download car parking multiplayer mod apk free money
-download car parking multiplayer mod apk unlimited gold
-download car parking multiplayer mod apk latest version
-download car parking multiplayer mod apk android 1
-download car parking multiplayer mod apk hack
-download car parking multiplayer mod apk revdl
-download car parking multiplayer mod apk no root
-download car parking multiplayer mod apk offline
-download car parking multiplayer mod apk for pc
-download car parking multiplayer mod apk obb
-download car parking multiplayer mod apk rexdl
-download car parking multiplayer mod apk happymod
-download car parking multiplayer mod apk 4.8.9.4.4
-download car parking multiplayer mod apk with all cars unlocked
-download car parking multiplayer mod apk unlimited everything
-download car parking multiplayer mod apk online
-download car parking multiplayer mod apk ios
-download car parking multiplayer mod apk 2023
-download car parking multiplayer mod apk unlimited gas
-download car parking multiplayer mod apk unlimited xp
-download car parking multiplayer mod apk unlimited keys
-download car parking multiplayer mod apk unlimited gems
-download car parking multiplayer mod apk unlimited nitro
-download car parking multiplayer mod apk unlimited tickets
-download car parking multiplayer mod apk unlimited coins and money
-download car parking multiplayer mod apk with real cars
-download car parking multiplayer mod apk with voice chat
-download car parking multiplayer mod apk with police mode
-download car parking multiplayer mod apk with custom cars
-download car parking multiplayer mod apk with manual transmission
-download car parking multiplayer mod apk with realistic graphics
-download car parking multiplayer mod apk with new maps
-download car parking multiplayer mod apk with snow mode
-download car parking multiplayer mod apk with drift mode
-download car parking multiplayer mod apk with tuning mode
-download car parking multiplayer mod apk with traffic mode
-download car parking multiplayer mod apk with friends mode
-download car parking multiplayer mod apk with garage mode
-download car parking multiplayer mod apk with missions mode
-download car parking multiplayer mod apk with challenges mode

-

Customizable cars and accessories

-

The game offers a wide range of cars that you can choose from, such as sports cars, trucks, buses, etc. You can also customize your cars with different colors, stickers, wheels, spoilers, etc. You can also buy accessories and items for your car, such as radios, horns, sirens, etc. You can also change your character's appearance and clothes.

-

Various game modes and challenges

-

The game has various game modes and challenges that test your driving skills and knowledge. You can play the parking mode, where you have to park your car in different scenarios without hitting any obstacles or other cars. You can also play the free driving mode, where you can drive around the map without any rules or limitations. You can also play the police mode, where you can chase or be chased by other players or AI cops.

-

Why download Car Parking Multiplayer Mod APK?

-

While Car Parking Multiplayer is a fun and addictive game, it also has some drawbacks that might limit your enjoyment. For example, you might need a lot of coins and money to unlock and upgrade your cars, as well as to buy accessories and items. You might also encounter annoying ads that interrupt your gameplay. Moreover, you might need to root your device to access some features or settings That's why you should download Car Parking Multiplayer Mod APK Unlimited Coins, a modified version of the game that gives you unlimited resources and features. Here are some of the benefits of downloading this mod apk:

Benefits of Car Parking Multiplayer Mod APK

-

Unlimited coins and money

-

With this mod apk, you will get unlimited coins and money that you can use to unlock and upgrade your cars, as well as to buy accessories and items. You don't have to worry about running out of resources or spending real money to enjoy the game. You can also use the coins and money to buy premium cars that are otherwise not available in the original game.

-

All cars unlocked and upgraded

-

With this mod apk, you will get access to all the cars in the game, including the ones that are locked or require a certain level or achievement to unlock. You can also upgrade your cars to the maximum level without any restrictions or costs. You can enjoy driving any car you want with the best performance and features.

-

No ads and no root required

-

With this mod apk, you will not encounter any ads that interrupt your gameplay or annoy you. You can play the game smoothly and without any distractions. Moreover, you don't need to root your device to install or use this mod apk. You can simply download and install it without any hassle or risk.

-

How to download and install Car Parking Multiplayer Mod APK?

-

If you are interested in downloading and installing Car Parking Multiplayer Mod APK Unlimited Coins, you can follow these simple steps:

-

Step 1: Download the mod apk file from a trusted source

-

The first step is to download the mod apk file from a trusted source. You can use the link below to download the latest version of the mod apk file. Make sure you have enough storage space on your device before downloading.

-

Download Car Parking Multiplayer Mod APK Unlimited Coins

-

Step 2: Enable unknown sources on your device settings

-

The next step is to enable unknown sources on your device settings. This will allow you to install apps from sources other than Google Play Store. To do this, go to your device settings, then security, then unknown sources, and toggle it on.

-

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

-

The final step is to install the mod apk file and launch the game. To do this, locate the downloaded mod apk file on your device storage, then tap on it to start the installation process. Follow the instructions on the screen and wait for the installation to finish. Once done, launch the game and enjoy unlimited coins and features.

-

Conclusion

-

Car Parking Multiplayer is a fun and realistic car simulation game that offers a variety of features and modes. However, if you want to enjoy the game to the fullest, you might need a lot of coins and money to unlock and upgrade your cars, as well as to buy accessories and items. That's why you should download Car Parking Multiplayer Mod APK Unlimited Coins, a modified version of the game that gives you unlimited resources and features. With this mod apk, you can drive any car you want, customize it, explore an open world map, and interact with other players online without any limitations or costs. You can also avoid annoying ads and root your device. To download and install this mod apk, just follow the simple steps we have provided above.

-

FAQs

-

Here are some of the frequently asked questions about Car Parking Multiplayer Mod APK Unlimited Coins:

- - - - - - -
Q: Is Car Parking Multiplayer Mod APK safe to use?A: Yes, Car Parking Multiplayer Mod APK is safe to use as long as you download it from a trusted source. However, we recommend that you use it at your own risk and discretion, as we are not responsible for any issues or damages that may occur.
Q: Does Car Parking Multiplayer Mod APK work offline?A: Yes, Car Parking Multiplayer Mod APK works offline as well as online. You can play the game without an internet connection in the free driving mode or the parking mode. However, if you want to play online with other players, you will need an internet connection.
Q: Can I update Car Parking Multiplayer Mod APK?A: Yes, you can update Car Parking Multiplayer Mod APK whenever there is a new version available. However, you might lose some of your progress or data when you update the mod apk. Therefore, we suggest that you backup your data before updating the mod apk.
Q: Can I play Car Parking Multiplayer Mod APK with my friends?A: Yes, you can play Car Parking Multiplayer Mod APK with your friends online in the multiplayer mode. You can create your own server and invite your friends to join you, or you can join other players' servers and chat with them. You can also exchange cars, race, and have fun with your friends.
Q: What are the minimum requirements to play Car Parking Multiplayer Mod APK?A: The minimum requirements to play Car Parking Multiplayer Mod APK are: - Android 4.4 or higher - 1 GB of RAM or more - 300 MB of free storage space or more - A stable internet connection (for online mode)
-

I hope this article has helped you learn more about Car Parking Multiplayer Mod APK Unlimited Coins and how to download and install it. If you have any questions or feedback, feel free to leave a comment below. Thank you for reading and happy gaming!

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Mortal Kombat The Ultimate Guide to Downloading and Playing the Iconic Series.md b/spaces/congsaPfin/Manga-OCR/logs/Mortal Kombat The Ultimate Guide to Downloading and Playing the Iconic Series.md deleted file mode 100644 index 11a88b41b15fc96d3f7a2a5a1d1f8dc524aa6ef6..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Mortal Kombat The Ultimate Guide to Downloading and Playing the Iconic Series.md +++ /dev/null @@ -1,91 +0,0 @@ -
-

Where to Download Mortal Kombat

-

Mortal Kombat is one of the most iconic and popular fighting games in the world. It is known for its visceral combat, stunning graphics, and over-the-top moves that will punch you right in the guts. Whether you are a fan of the classic characters like Scorpion, Sub-Zero, and Raiden, or the new additions like Mileena, Rain, and Rambo, you will find something to love in Mortal Kombat. But where can you download this amazing game? In this article, we will show you how to download Mortal Kombat on different platforms and devices, what are the features and benefits of playing it, and what are some tips and tricks to improve your skills and enjoy the game more.

-

where to download mortal kombat


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



-

Platforms and Devices

-

Mortal Kombat is available on various platforms and devices, so you can play it wherever you want. Here are some of the options you have:

-

PC

-

If you want to play Mortal Kombat on your PC, you can download it from Steam, a digital distribution platform that offers thousands of games. To download Mortal Kombat from Steam, you need to create a free account, install the Steam client on your PC, search for Mortal Kombat 11 in the store, add it to your cart, and complete the purchase. You can also buy additional content such as DLCs, skins, and packs from Steam. Once you have bought the game, you can download it from your library and start playing.

-

Mobile

-

If you want to play Mortal Kombat on your mobile device, you can download it from App Store if you have an iOS device, or Google Play if you have an Android device. Mortal Kombat Mobile is a free-to-play game that brings its trademark Fatalities to mobile, with stunning graphics, and over 130 characters to collect. You can create your own team of Mortal Kombat warriors and lead them into battle in various modes such as Challenges, Faction Wars, Quests, and more. You can also unlock unique character customizations in Feats of Strength, earn rewards on Epic Quests, and perform jaw-dropping Fatalities and Friend

Console

-

If you want to play Mortal Kombat on your console, you can download it from the online store of your console. Mortal Kombat 11 is compatible with PlayStation 4, PlayStation 5, Xbox One, Xbox Series X/S, Nintendo Switch, and Stadia. To download Mortal Kombat 11 on your console, you need to have an internet connection, a valid account, and enough storage space. You can also buy additional content such as DLCs, skins, and packs from the online store of your console. Once you have bought the game, you can download it from your library and start playing.

-

Features and Benefits

-

Mortal Kombat is not just a game, it is an experience. It offers a lot of features and benefits that will make you enjoy every moment of playing it. Here are some of them:

-

Custom Character Variations

-

Mortal Kombat lets you customize your fighters with different skins, weapons, and gear. You can create your own character variations that suit your style and preferences. You can also unlock new items and cosmetics by playing the game and completing challenges. You can mix and match different items and create unique looks for your characters. You can also share your creations with other players online and see what they have made.

-

Cinematic Story Mode

-

Mortal Kombat has a cinematic story mode that will take you on an epic saga of Mortal Kombat. You will play as different characters from both the past and the present, as they face a new threat that threatens to destroy the balance of time. You will witness the consequences of your actions and choices, as well as the fate of your favorite characters. You will also see stunning cutscenes and animations that will immerse you in the story.

-

How to download Mortal Kombat 11 on Steam
-Mortal Kombat mobile app free download
-Mortal Kombat X PC download full version
-Best sites to download Mortal Kombat games
-Download Mortal Kombat 11 Ultimate edition
-Mortal Kombat apk download for android
-Mortal Kombat emulator download for windows
-Download Mortal Kombat 9 Komplete edition
-Mortal Kombat movie 2021 download link
-Mortal Kombat soundtrack download mp3
-Download Mortal Kombat characters and skins
-Mortal Kombat online game no download
-Download Mortal Kombat wallpapers for desktop
-Mortal Kombat comics download pdf
-Download Mortal Kombat fatalities and brutalities
-Mortal Kombat mod apk download unlimited money
-Download Mortal Kombat trilogy for ps4
-Mortal Kombat legacy web series download
-Download Mortal Kombat cheats and hacks
-Mortal Kombat theme song download ringtone
-Download Mortal Kombat arcade kollection
-Mortal Kombat unchained psp iso download
-Download Mortal Kombat subtitles in english
-Mortal Kombat shaolin monks download for pc
-Download Mortal Kombat xl for xbox one
-Mortal Kombat armageddon wii iso download
-Download Mortal Kombat vs dc universe
-Mortal Kombat rebirth fan film download
-Download Mortal Kombat 4 for android
-Mortal Kombat deception gamecube rom download
-Download Mortal Kombat 3 ultimate for pc
-Mortal Kombat annihilation full movie download
-Download Mortal Kombat aftermath expansion pack
-Mortal Kombat project 4.1 download zip
-Download Mortal Kombat 2 for snes
-Mortal Kombat conquest tv series download
-Download Mortal Kombat kollection online beta
-Mortal Kombat special forces ps1 iso download
-Download Mortal Kombat mythologies sub-zero
-Mortal Kombat scorpion's revenge download torrent
-Download Mortal Kombat 1 for sega genesis
-Mortal Kombat deadly alliance gba rom download
-Download Mortal Kombat voice pack for windows 10
-Mortal Kombat legends battle of the realms download

-

Online Multiplayer Mode

-

Mortal Kombat has an online multiplayer mode that will let you compete with other players from around the world. You can join Faction Wars, where you can choose a faction and fight for its glory and rewards. You can also play Ranked Matches, where you can climb the leaderboards and earn respect and recognition. You can also play King of the Hill, where you can challenge other players in a series of matches and see who is the best.

Brutal Fatalities and Friendships

-

Mortal Kombat is famous for its brutal Fatalities and Friendships, the signature moves that you can perform at the end of a match to finish off your opponent. Fatalities are gruesome and gory, showing how you can rip, tear, burn, or crush your enemy in the most creative and violent ways. Friendships are humorous and silly, showing how you can spare your enemy and do something nice or funny instead. You can unlock new Fatalities and Friendships by playing the game and completing challenges. You can also see the list of moves for each character in the menu.

-

Tips and Tricks

-

Mortal Kombat is a game that requires skill and strategy, as well as practice and patience. If you want to improve your skills and enjoy the game more, here are some tips and tricks that you can follow:

-

Learn the Basic Moves and Combos

-

The first thing you need to do is to learn the basic moves and combos of each character. You can see the list of moves for each character in the menu, or you can access the tutorial mode that will teach you the fundamentals of the game. You should learn how to perform punches, kicks, blocks, throws, special moves, and combos. You should also learn how to use the meter system, which allows you to perform enhanced moves, breakers, and fatal blows. You should practice these moves until you can execute them without hesitation.

-

Practice in Training Mode and Towers of Time

-

The next thing you need to do is to practice your skills and earn rewards in different modes. You can use the training mode to practice your moves and combos against a dummy opponent, or you can adjust the settings to simulate different scenarios. You can also use the Towers of Time mode to face different challenges and opponents with various modifiers and conditions. You can earn coins, souls, hearts, and other rewards by completing these modes. You can use these rewards to unlock new items and cosmetics in the Krypt.

Use the Environment and Interactables

-

Another thing you need to do is to use the environment and interactables to your advantage in fights. You can use the objects and elements in the background to damage, stun, or escape from your opponent. You can also use the stage transitions to move from one area to another, while dealing extra damage to your opponent. You can see the interactables and stage transitions by pressing the button prompt on the screen. You should learn how to use them effectively and strategically.

-

Experiment with Different Characters and Variations

-

The last thing you need to do is to experiment with different characters and variations. You should try out different characters and see which ones you like and dislike. You should also try out different variations and see which ones suit your style and preferences. You can create your own variations by customizing your characters with different skins, weapons, and gear. You can also see the stats and abilities of each variation in the menu. You should find the character and variation that works best for you and have fun with it.

-

Conclusion

-

Mortal Kombat is a game that will keep you entertained and engaged for hours. It has a lot of features and benefits that will make you love playing it. It also has a lot of tips and tricks that will help you improve your skills and enjoy the game more. If you want to download Mortal Kombat, you can do so on various platforms and devices, depending on your preference. You can also buy additional content such as DLCs, skins, and packs to enhance your experience. Mortal Kombat is a game that you should not miss, so download it now and join the fight!

-

FAQs

-

Here are some frequently asked questions about downloading Mortal Kombat:

-
    -
  • How much does Mortal Kombat cost?
  • -

    Mortal Kombat 11 costs $59.99 for the standard edition, $89.99 for the premium edition, and $49.99 for the ultimate edition. Mortal Kombat Mobile is free-to-play, but it has in-app purchases.

    -
  • How much storage space do I need to download Mortal Kombat?
  • -

    Mortal Kombat 11 requires about 60 GB of storage space on PC, 50 GB on PlayStation 4, 45 GB on Xbox One, 22 GB on Nintendo Switch, and 40 GB on Stadia. Mortal Kombat Mobile requires about 1 GB of storage space on iOS and Android devices.

    -
  • Is Mortal Kombat suitable for children?
  • -

    Mortal Kombat is rated M for Mature by ESRB, 18+ by PEGI, and R18+ by ACB. It contains intense violence, blood and gore, strong language, and suggestive themes. It is not suitable for children or sensitive viewers.

    -
  • Can I play Mortal Kombat offline?
  • -

    You can play Mortal Kombat 11 offline in modes such as Story Mode, Training Mode, Local Versus Mode, Classic Towers, and Krypt. You need an internet connection to play online modes such as Faction Wars, Ranked Matches, King of the Hill, Towers of Time, and Living Towers. You can play Mortal Kombat Mobile offline in modes such as Challenges, Quests, Relic Hunt, Shao Kahn's Tower, and Tower of Horror. You need an internet connection to play online modes such as Faction Wars.

    -
  • Can I play Mortal Kombat with my friends?
  • -

    You can play Mortal Kombat 11 with your friends in Local Versus Mode or Online Multiplayer Mode. You can also join or create a room in Online Multiplayer Mode to invite or join other players. You can play Mortal Kombat Mobile with your friends in Faction Wars or Online Multiplayer Mode. You can also join or create a clan in Faction Wars to chat or cooperate with other players.

    -

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Pokmon GO APK - The Ultimate Guide to Download and Update in 2023.md b/spaces/congsaPfin/Manga-OCR/logs/Pokmon GO APK - The Ultimate Guide to Download and Update in 2023.md deleted file mode 100644 index 5324ea1b9f701ef81ec53c746da43ed575055b64..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Pokmon GO APK - The Ultimate Guide to Download and Update in 2023.md +++ /dev/null @@ -1,141 +0,0 @@ -
-

Pokemon Go Download APK 2023: Everything You Need to Know

-

Pokemon Go is a mobile game that lets you catch, battle, and trade Pokemon in the real world using your smartphone's GPS and camera. It is one of the most popular and successful games ever, with over a billion downloads and millions of active players worldwide. If you are a fan of Pokemon or just looking for a fun and immersive way to explore your surroundings, you might want to give Pokemon Go a try.

-

pokemon go download apk 2023


Download File 🗹 https://urlca.com/2uOaGV



-

But how can you download Pokemon Go apk for your Android device in 2023? And what are the new features and updates that you can expect from the game this year? In this article, we will answer these questions and more. We will also share some tips and tricks to help you become a better Pokemon trainer, as well as some benefits and drawbacks of playing Pokemon Go. Let's get started!

-

How to Download Pokemon Go APK for Android Devices in 2023

-

The easiest way to download Pokemon Go apk for your Android device is to visit the official Google Play Store and search for "Pokemon Go". You can also use this link to go directly to the game's page on the Play Store. There, you can tap on the "Install" button to download and install the game on your device.

-

However, if for some reason you cannot access the Play Store or you want to download an older version of the game, you can also use third-party websites that offer apk files for various apps and games. One such website is APKCombo, which allows you to download different versions of Pokemon Go apk for free. You can also use this link to go directly to the game's page on APKCombo.

-

Before you download any apk file from a third-party website, make sure that you have enabled the option to install apps from unknown sources on your device. To do this, go to Settings > Security > Unknown Sources and toggle it on. You should also scan the apk file with an antivirus app before installing it, just to be safe.

-

Features and Updates of Pokemon Go in 2023

-

Pokemon Go is constantly evolving and adding new features and updates to keep the game fresh and exciting. Here are some of the latest features and updates that you can enjoy in Pokemon Go in 2023:

-

Season 10: Rising Heroes

-

Season 10 of Pokemon Go started on March 1, 2023 and will last until June 30, 2023. This season is themed around rising heroes who challenge themselves and overcome obstacles. Some of the highlights of this season include:

-
    -
  • A new exclusive Pokemon: Roaming Form Gimmighoul, a ghost-type Pokemon that can change its appearance depending on where it is found.
  • -
  • A new item: Golden Lure Module, which can turn any Pokestop into a Golden Pokestop that attracts rare and shiny Pokemon.
  • -
  • A new coin: Gimmighoul Coin, which and luck. If you want to become a master Pokemon trainer, you need to know some tips and tricks that can help you improve your game. Here are some of them:

    -

    pokemon go apk download latest version 2023
    -pokemon go android apk download free 2023
    -pokemon go mod apk download unlimited coins 2023
    -pokemon go hack apk download joystick 2023
    -pokemon go update apk download new features 2023
    -pokemon go beta apk download early access 2023
    -pokemon go offline apk download no internet 2023
    -pokemon go plus apk download device compatibility 2023
    -pokemon go xapk download bundle file 2023
    -pokemon go apk pure download safe and fast 2023
    -pokemon go apk mirror download alternative source 2023
    -pokemon go apk uptodown download old versions 2023
    -pokemon go apk mob.org download high quality games 2023
    -pokemon go apk rexdl download modded games 2023
    -pokemon go apk revdl download cracked games 2023
    -pokemon go apk obb download data file 2023
    -pokemon go apk for pc download windows version 2023
    -pokemon go apk for ios download iphone version 2023
    -pokemon go apk for firestick download tv version 2023
    -pokemon go apk for chromebook download laptop version 2023
    -pokemon go apk for bluestacks download emulator version 2023
    -pokemon go apk for kindle fire download tablet version 2023
    -pokemon go apk for samsung download compatible device 2023
    -pokemon go apk for huawei download supported device 2023
    -pokemon go apk for xiaomi download optimized device 2023
    -pokemon go apk for oppo download smooth device 2023
    -pokemon go apk for vivo download fast device 2023
    -pokemon go apk for realme download budget device 2023
    -pokemon go apk for nokia download durable device 2023
    -pokemon go apk for lg download reliable device 2023
    -pokemon go apk for sony download powerful device 2023
    -pokemon go apk for motorola download affordable device 2023
    -pokemon go apk for oneplus download flagship device 2023
    -pokemon go apk for google pixel download stock android device 2023
    -pokemon go apk for asus download gaming device 2023
    -pokemon go apk for lenovo download business device 2023
    -pokemon go apk for acer download education device 2023
    -pokemon go apk for hp download entertainment device 2023
    -pokemon go apk for dell download productivity device 2023
    -pokemon go apk for toshiba download performance device 2023
    -how to install pokemon go apk on android phone in 2023
    -how to update pokemon go apk on android phone in 2023
    -how to uninstall pokemon go apk on android phone in 2023
    -how to play pokemon go apk on android phone in 2023
    -how to fix pokemon go apk not working on android phone in 2023
    -how to transfer pokemon go account from old to new phone in 2023
    -how to backup and restore pokemon go data on android phone in 2023
    -how to change location in pokemon go using fake gps in 2023
    -how to catch rare and legendary pokemons in pokemon go in 2023
    -how to level up and evolve pokemons in pokemon go in 2023

    -

    How to Find and Catch Pokemon in Your Area

    -

    One of the main goals of Pokemon Go is to find and catch as many Pokemon as you can. To do this, you need to use the in-game map and the Nearby and Sightings features to locate Pokemon near you. You can also use items such as Incense, Lure Modules, and Mystery Boxes to attract more Pokemon to your location. Once you encounter a Pokemon, you need to throw a Poke Ball at it and hope that it stays inside. You can increase your chances of catching a Pokemon by using different types of Poke Balls, such as Great Balls, Ultra Balls, or Premier Balls, or by using items such as Razz Berries, Nanab Berries, Pinap Berries, or Golden Razz Berries. You can also use curveballs, nice throws, great throws, or excellent throws to get bonus XP and catch rate.

    -

    How to Spin Pokestops for Items and Rewards

    -

    Pokestops are landmarks that you can find on the map that give you items and rewards when you spin them. You can spin a Pokestop by tapping on it and swiping the disc on the screen. You can get items such as Poke Balls, Potions, Revives, Berries, Eggs, Evolution Items, or Gifts from spinning Pokestops. You can also get rewards such as XP, Stardust, or Coins from completing tasks or achievements related to Pokestops. Some of the tasks or achievements include spinning 10 Pokestops in a row, spinning 25 Pokestops in a day, spinning 50 Pokestops in a week, or spinning 1000 Pokestops in total.

    -

    How to Use Type Strengths and Weaknesses in Battles

    -

    Pokemon Go is based on the Pokemon franchise, which has a complex system of type strengths and weaknesses. Each Pokemon has one or two types, such as fire, water, grass, electric, psychic, dark, fairy, etc., and each type has advantages and disadvantages against other types. For example, fire-type Pokemon are strong against grass-type Pokemon but weak against water-type Pokemon. Knowing the type strengths and weaknesses can help you choose the best Pokemon for battles against other players or raid bosses. You can also use items such as TMs or TRs to change the moves of your Pokemon and make them more effective in battles.

    -

    How to Trade Pokemon with Friends

    -

    Pokemon Go is not only a game that you can play solo but also a game that you can play with your friends. One of the ways that you can interact with your friends in Pokemon Go is by trading Pokemon with them. Trading Pokemon can help you complete your Pokedex, get candies for powering up or evolving your Pokemon, or get lucky Pokemon that have better stats and cost less to power up. To trade Pokemon with your friends, you need to be at least level 10, have a friend code, and be within 100 meters of each other. You also need to have enough Stardust, which is the currency used for trading. The amount of Stardust required depends on the rarity and friendship level of the Pokemon you are trading. You can increase your friendship level with your friends by sending or opening Gifts, battling together, or participating in raids together.

    -

    Benefits and Drawbacks of Playing Pokemon Go

    -

    Pokemon Go is a game that can have both positive and negative effects on your life. Here are some of the benefits and drawbacks of playing Pokemon Go:

    -

    Pros: Health, Social, and Economic Benefits

    -

    Pokemon Go is a game that can improve your health, social, and economic well-being in various ways. Some of the benefits include:

    -
      -
    • Health: Pokemon Go can encourage you to walk more, exercise more, and spend more time outdoors. This can help you burn calories, lose weight, lower your blood pressure, reduce stress, and boost your immune system.
    • -
    • Social: Pokemon Go can help you meet new people, make new friends, and strengthen your existing relationships. You can interact with other players through chat, trade, battle, or raid features. You can also join online or offline communities that share your interest in Pokemon.
    • -
    • Economic: Pokemon Go can help you save money, earn money, or support local businesses. You can save money by using the game as a free or low-cost entertainment option. You can earn money by creating content, selling merchandise, or offering services related to Pokemon Go. You can also support local businesses by visiting Pokestops or Gyms that are located near them.
    • -
    -

    Cons: Safety, Privacy, and Addiction Risks

    -

    Pokemon Go is a game that can also pose some safety, privacy, and addiction risks to you and others. Some of the drawbacks include:

    -
      -
    • Safety: Pokemon Go can distract you from your surroundings and make you vulnerable to accidents, injuries, or crimes. You might trip, fall, bump into something, or cross the street without looking. You might also encounter dangerous people or places while playing the game.
    • -
    • Privacy: Pokemon Go can collect and share your personal data and location information with third parties. This can expose you to identity theft, hacking, or unwanted advertising. You might also reveal sensitive information about yourself or others through your in-game actions or communications.
    • -
    • Addiction: Pokemon Go can become addictive and interfere with your normal life. You might spend too much time, money, or energy on the game and neglect your responsibilities, relationships, or health. You might also develop psychological problems such as anxiety, depression, or obsession.
    • -
    -

    Conclusion

    -

    Pokemon Go is a mobile game that lets you catch, battle, and trade Pokemon in the real world using your smartphone's GPS and camera. It is a game that can bring you joy, adventure, and connection with other players. It is also a game that can challenge you, teach you, and inspire you.

    -

    In this article, we have shown you how to download Pokemon Go apk for your Android device in 2023, and what are the new features and updates that you can expect from the game this year. We have also shared some tips and tricks to help you improve your game, as well as some benefits and drawbacks of playing Pokemon Go.

    -

    We hope that you have found this article helpful and informative. If you have any questions, comments, or feedback, please feel free to share them with us. We would love to hear from you.

    -

    And if you are ready to embark on your Pokemon journey, why not download Pokemon Go apk today and join the millions of players who are already enjoying the game? You never know what surprises await you in the world of Pokemon. Happy hunting!

    -

    FAQs

    -

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

    -

    What are the minimum requirements to play Pokemon Go on Android devices?

    -

    To play Pokemon Go on Android devices, you need to have the following minimum requirements:

    -
      -
    • An Android device with Android 6 or higher.
    • -
    • A device with at least 2 GB of RAM.
    • -
    • A device with a GPS and a camera.
    • -
    • A stable internet connection (Wi-Fi, 3G, or 4G).
    • -
    • A Google account or a Pokemon Trainer Club account.
    • -
    -

    How can I get more Pokecoins in Pokemon Go?

    -

    Pokecoins are the premium currency in Pokemon Go that can be used to buy items and services from the shop. There are two ways to get more Pokecoins in Pokemon Go:

    -
      -
    • Earn them by defending Gyms. You can earn up to 50 Pokecoins per day by placing your Pokemon in Gyms and keeping them there for as long as possible. You will receive your Pokecoins when your Pokemon is returned to you.
    • -
    • Buy them with real money. You can buy Pokecoins from the shop using your credit card, debit card, or Google Play balance. The prices vary depending on the amount of Pokecoins you want to buy.
    • -
    -

    How can I join a Remote Raid in Pokemon Go?

    -

    A Remote Raid is a type of raid that allows you to join a raid battle from anywhere, as long as you have a Remote Raid Pass. A Remote Raid Pass is an item that can be bought from the shop for 100 Pokecoins or obtained from special events or quests. To join a Remote Raid, you need to do the following:

    -
      -
    • Tap on the Nearby button on the bottom right corner of the screen.
    • -
    • Swipe left to see the Raid tab.
    • -
    • Tap on a raid that has an orange icon and a distance indicator.
    • -
    • Tap on the "Join" button and use your Remote Raid Pass.
    • -
    • Wait for other players to join or invite your friends to join.
    • -
    • Start the raid battle and defeat the raid boss.
    • -
    -

    What are the best Pokemon to use in Pokemon Go battles?

    -

    The best Pokemon to use in Pokemon Go battles depend on various factors, such as the type, level, stats, moves, and abilities of your Pokemon and your opponent's Pokemon. However, some general guidelines are:

    -
      -
    • Use Pokemon that have high CP (combat power), which indicates their overall strength and performance in battles.
    • -
    • Use Pokemon that have high IVs (individual values), which indicate their potential and uniqueness in terms of stats.
    • -
    • Use Pokemon that have high DPS (damage per second), which indicates their offensive power and speed in battles.
    • -
    • Use Pokemon that have high TDO (total damage output), which indicates their defensive power and endurance in battles.
    • -
    • Use Pokemon that have type advantages against your opponent's Pokemon, which means they deal more damage or take less damage from them.
    • -
    -

    Some examples of Pokemon that are considered to be among the best for battles in Pokemon Go include Mewtwo, Rayquaza, Kyogre, Groudon, Dialga, Palkia, Giratina, Darkrai, Lucario, Machamp, Metagross, Tyranitar, Dragonite, Salamence, Gyarados, Snorlax, Blissey, and Chansey.

    -

    How can I fake my location in Pokemon Go?

    -

    Faking your location in Pokemon Go is a way of tricking the game into thinking that you are somewhere else, which can allow you to access Pokemon, Pokestops, Gyms, or raids that are not available in your area. However, faking your location in Pokemon Go is also a violation of the game's terms of service and can result in your account being banned or suspended. Therefore, we do not recommend or endorse faking your location in Pokemon Go.

    -

    However, if you still want to try it at your own risk, you need to use a third-party app or software that can spoof your GPS location on your device. Some examples of such apps or software include Fake GPS Location, Mock Locations, iSpoofer, or Dr.Fone Virtual Location. You also need to disable the Find My Device or Find My iPhone feature on your device, as well as any other location services or settings that can interfere with the spoofing app or software.

    -

    Once you have installed and configured the spoofing app or software, you can launch Pokemon Go and select the location that you want to fake. You should be careful not to change your location too frequently or too drastically, as this can trigger the game's anti-cheat system and alert the developers of your suspicious activity.

    -

    -

    This is the end of the article that I have created for you. I hope you are satisfied with the quality and content of the article. If you have any feedback or suggestions for improvement, please let me know. Thank you for using Bing chat mode.

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Pyramid of Mahjong Mod APK A Fun and Challenging Mahjong Solitaire Game.md b/spaces/congsaPfin/Manga-OCR/logs/Pyramid of Mahjong Mod APK A Fun and Challenging Mahjong Solitaire Game.md deleted file mode 100644 index 3bf4b2e587744813f00eb913e5942e836a378eee..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Pyramid of Mahjong Mod APK A Fun and Challenging Mahjong Solitaire Game.md +++ /dev/null @@ -1,130 +0,0 @@ - -

    Pyramid of Mahjong Mod Apk: A Fun and Challenging Tile Matching Game

    -

    If you are looking for a new and exciting puzzle game that combines the classic tile matching of mahjong with the city building of simulation games, then you should try Pyramid of Mahjong Mod Apk. This game will take you on an adventure through ancient Egypt, where you will help a Pharaoh restore his ruined civilization by matching tiles and building structures. You will also enjoy the benefits of a modded version of the game, which gives you unlimited currency, offline access, and easy installation. In this article, we will tell you everything you need to know about Pyramid of Mahjong Mod Apk, including what it is, how to play it, and why you should download it.

    -

    pyramid of mahjong mod apk


    Download Zip ››› https://urlca.com/2uO7gh



    -

    What is Pyramid of Mahjong?

    -

    Pyramid of Mahjong is a popular puzzle game developed by G5 Entertainment, a company known for creating high-quality casual games for mobile devices. The game is available for free on Google Play, App Store, and Amazon, with optional in-app purchases to unlock extra bonuses. The game has received positive reviews from players and critics alike, who praised its graphics, gameplay, and story.

    -

    A blend of mahjong and city building

    -

    The game is a unique and epic blend of mahjong and city building, where you have to match tiles in a pyramid-like structure to clear them from the board and collect resources. You can then use these resources to rebuild and upgrade a settlement on the Nile Delta, which was once a flourishing area in the times of the Egyptian Empire. You can choose from a variety of buildings and landmarks to create your own version of ancient Egypt.

    -

    A journey through ancient Egypt

    -

    The game also has a captivating storyline that follows the history, tales, and myths of ancient Egypt. You will meet the Pharaoh and his nobles, priests, soldiers, scribes, merchants, and farmers on your way to prosperity. You will also encounter court intrigues, cunning plans, and historical events that will keep you hooked. You will play as an ambitious third-generation architect who is searching for his sister after her mysterious disappearance. You will also discover a powerful artifact that can change the fate of the New Kingdom.

    -

    A game with thousands of levels and boosters

    -

    The game offers thousands of free immersive levels that will challenge your tile matching skills and strategic thinking. Each level has a different layout, goal, and difficulty level. You will also have access to incredible boosters and power-ups that can help you complete the levels faster and easier. Some of these boosters include the Dice booster (which gets you out of a difficult situation), the Brazier booster (which blows up multiple pairs of tiles), and many other innovative features that can enhance your gameplay experience.

    -

    What is Pyramid of Mahjong Mod Apk?

    -

    Pyramid of Mahjong Mod Apk is a modified version of the original game that gives you some extra advantages that are not available in the official version. These advantages include:

    -

    A mod that gives you unlimited currency

    -

    One of the main features of Pyramid of Mahjong Mod Apk is that it gives you unlimited currency without any reduction. This means that you can use as much gold and gems as you want to buy boosters, unlock buildings, and speed up your progress. You don't have to worry about running out of currency or spending real money on the game. You can enjoy the game to the fullest without any limitations.

    -

    pyramid of mahjong unlimited money mod apk
    -pyramid of mahjong tile match hack apk
    -pyramid of mahjong free download mod apk
    -pyramid of mahjong mod apk latest version
    -pyramid of mahjong mod apk android 1
    -pyramid of mahjong mod apk revdl
    -pyramid of mahjong mod apk happymod
    -pyramid of mahjong mod apk no ads
    -pyramid of mahjong mod apk offline
    -pyramid of mahjong mod apk unlimited gems
    -pyramid of mahjong mod apk unlimited lives
    -pyramid of mahjong mod apk unlimited boosters
    -pyramid of mahjong mod apk unlocked all levels
    -pyramid of mahjong mod apk unlimited stars
    -pyramid of mahjong mod apk unlimited coins
    -pyramid of mahjong premium mod apk
    -pyramid of mahjong pro mod apk
    -pyramid of mahjong vip mod apk
    -pyramid of mahjong full version mod apk
    -pyramid of mahjong cracked mod apk
    -download pyramid of mahjong mod apk for free
    -how to install pyramid of mahjong mod apk
    -how to play pyramid of mahjong mod apk
    -how to update pyramid of mahjong mod apk
    -how to get pyramid of mahjong mod apk
    -best pyramid of mahjong mod apk
    -new pyramid of mahjong mod apk
    -old pyramid of mahjong mod apk
    -original pyramid of mahjong mod apk
    -safe pyramid of mahjong mod apk
    -working pyramid of mahjong mod apk
    -cheat codes for pyramid of mahjong mod apk
    -tips and tricks for pyramid of mahjong mod apk
    -guide for pyramid of mahjong mod apk
    -walkthrough for pyramid of mahjong mod apk
    -review for pyramid of mahjong mod apk
    -features of pyramid of mahjong mod apk
    -benefits of pyramid of mahjong mod apk
    -advantages of pyramid of mahjong mod apk
    -disadvantages of pyramid of mahjong mod apk
    -alternatives to pyramid of mahjong mod apk
    -similar games to pyramid of mahjong mod apk
    -comparison between pyramid of mahjong and other games in the same genre or category.
    -what is the difference between the normal version and the modified version (mod) version?
    -what are the requirements to run the game on your device?
    -what are the permissions needed to install the game on your device?
    -what are the ratings and reviews from other users who have downloaded and played the game?
    -what are the bugs and issues that you may encounter while playing the game?
    -what are the solutions and fixes for the bugs and issues that you may encounter while playing the game?

    -

    A mod that works offline and online

    -

    Another feature of Pyramid of Mahjong Mod Apk is that it works both offline and online. This means that you can play the game anytime and anywhere, even without an internet connection. You can also sync your progress with your Facebook account and play with your friends online. You can compare your scores, achievements, and rankings with other players around the world. You can also join a guild and chat with other members.

    -

    A mod that is easy to install and use

    -

    The last feature of Pyramid of Mahjong Mod Apk is that it is very easy to install and use. You don't need to root or jailbreak your device to use the mod. You just need to download the apk file from a reliable source and install it on your device. You can then launch the game and enjoy the modded features. The mod is also compatible with most Android and iOS devices, so you don't have to worry about compatibility issues.

    -

    Why should you play Pyramid of Mahjong Mod Apk?

    -

    There are many reasons why you should play Pyramid of Mahjong Mod Apk, but here are some of the main ones:

    -

    To enjoy a relaxing and addictive puzzle game

    -

    If you love puzzle games, then you will love Pyramid of Mahjong Mod Apk. The game is relaxing and addictive, as you have to match tiles and clear the board in a satisfying way. The game also has beautiful graphics, soothing music, and smooth animations that will make you feel calm and happy. The game is suitable for all ages and skill levels, as you can adjust the difficulty according to your preference.

    -

    To explore the history and culture of ancient Egypt

    -

    If you are interested in ancient Egypt, then you will love Pyramid of Mahjong Mod Apk. The game will take you on a journey through the history, culture, and myths of this fascinating civilization. You will learn about the Pharaohs, the gods, the pyramids, the hieroglyphs, and more. You will also see how the ancient Egyptians lived, worked, and played. The game will make you feel like you are part of this amazing world.

    -

    To rebuild and upgrade a beautiful settlement

    -

    If you like city building games, then you will love Pyramid of Mahjong Mod Apk. The game will let you rebuild and upgrade a settlement on the Nile Delta, which was once a prosperous area in ancient Egypt. You will be able to choose from a variety of buildings and landmarks, such as temples, palaces, markets, farms, gardens, and more. You will also be able to customize your settlement with decorations, statues, fountains, and more. You will see how your settlement grows and changes as you progress in the game.

    -

    How to play Pyramid of Mahjong Mod Apk?

    -

    If you want to play Pyramid of Mahjong Mod Apk, then you need to know some basic rules and tips on how to play it. Here are some of them:

    -

    The basic rules and goals of mahjong

    -

    The basic rules of mahjong are simple: you have to match two tiles with the same symbol or image on them to remove them from the board. You can only match tiles that are free on at least one side (left or right) and not covered by other tiles. The goal is to clear all the tiles from the board before the time runs out or before you run out of moves.

    -

    The tips and tricks for matching tiles

    -

    There are some tips and tricks that can help you match tiles faster and easier. Some of them are:

    -
      -
    • Look for pairs of tiles that are easy to match first, such as those on the edges or corners of the board.
    • -
    • Use the hint button if you get stuck or need some guidance. The hint button will show you a possible pair of tiles that you can match.
    • -
    • Use the shuffle button if there are no more pairs of tiles available on the board. The shuffle button will rearrange the tiles randomly and create new pairs.
    • -
    • Use the undo button if you make a mistake or want to change your move. The undo button will let you go back one step in your moves.
    • -
    • Pay attention to the symbols and images on the tiles. Some of them have special meanings or functions, such as wildcards (which can match any tile), bombs (which can explode nearby tiles), keys (which can unlock locked tiles), etc.
    • -
    -

    The features and reviews of the game

    -

    The game also has many features and reviews that make it a great choice for puzzle lovers. Some of them are:

    -
      -
    • The game has stunning graphics and sound effects that create a realistic and immersive atmosphere of ancient Egypt. You will see the pyramids, the sphinx, the Nile, and other iconic landmarks in high definition.
    • -
    • The game has a simple and intuitive interface that makes it easy to navigate and play. You will see the tiles, the board, the buttons, and the indicators clearly and conveniently.
    • -
    • The game has a variety of modes and challenges that keep you entertained and motivated. You can play the story mode, the daily quests, the events, the tournaments, and more. You can also earn rewards, achievements, and trophies for your performance.
    • -
    • The game has a high rating and positive feedback from players and critics. The game has over 10 million downloads and 4.5 stars on Google Play. The game also has many glowing reviews from users who praised its fun, addictive, and relaxing gameplay.
    • -
    -

    Conclusion

    -

    Pyramid of Mahjong Mod Apk is a fun and challenging tile matching game that combines the classic puzzle of mahjong with the city building of simulation games. The game will take you on an adventure through ancient Egypt, where you will help a Pharaoh restore his ruined civilization by matching tiles and building structures. You will also enjoy the benefits of a modded version of the game, which gives you unlimited currency, offline access, and easy installation. If you are looking for a new and exciting puzzle game that will keep you entertained for hours, then you should download Pyramid of Mahjong Mod Apk today.

    -

    FAQs

    -

    Here are some frequently asked questions about Pyramid of Mahjong Mod Apk:

    - - - - - - - - - - - - - - - - - - - - - - - - - -
    QuestionAnswer
    Is Pyramid of Mahjong Mod Apk safe to use?Yes, Pyramid of Mahjong Mod Apk is safe to use as long as you download it from a trusted source. The mod does not contain any viruses or malware that can harm your device or data.
    Is Pyramid of Mahjong Mod Apk free to download?Yes, Pyramid of Mahjong Mod Apk is free to download and play. You don't have to pay anything to enjoy the modded features of the game.
    How can I update Pyramid of Mahjong Mod Apk?You can update Pyramid of Mahjong Mod Apk by downloading the latest version of the mod from the same source where you downloaded it before. You can also check for updates within the game itself.
    How can I uninstall Pyramid of Mahjong Mod Apk?You can uninstall Pyramid of Mahjong Mod Apk by going to your device settings and selecting the app manager. Then, you can find the game and tap on uninstall. You can also delete the apk file from your device storage.
    How can I contact the developer of Pyramid of Mahjong Mod Apk?You can contact the developer of Pyramid of Mahjong Mod Apk by visiting their official website or social media pages. You can also send them an email or leave a comment on their app page.

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Roblox Admin Hack - Download and Install the Most Powerful Exploit Ever.md b/spaces/congsaPfin/Manga-OCR/logs/Roblox Admin Hack - Download and Install the Most Powerful Exploit Ever.md deleted file mode 100644 index ebc1c7dfeeb2d041fafa49fda0ac8b0b6237d68b..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Roblox Admin Hack - Download and Install the Most Powerful Exploit Ever.md +++ /dev/null @@ -1,206 +0,0 @@ -
    -

    How to Download Hack Roblox Admin and Use It Safely

    -

    Roblox is a popular online gaming platform where you can create and play 3D games with friends. But what if you want to have more control over your gaming experience? What if you want to use commands that can make you fly, invisible, invincible, or even control other players? That's where Roblox admin comes in.

    -

    Roblox admin is a special feature that allows you to use commands that can affect yourself or other players in the game. These commands are known as admin commands, and they can be very fun and powerful. However, not everyone can use them. You need to have admin privileges in the game, which are usually given by the game's owner or developer.

    -

    download hack roblox admin


    Download Zip » https://urlca.com/2uObXE



    -

    So how can you get admin privileges in any game? How can you download hack roblox admin and use it safely? In this article, we will answer these questions and more. We will show you what roblox admin is, why you need it, how to download it, how to use it effectively, and how to avoid getting banned or hacked. Let's get started!

    -

    What is Roblox Admin and Why Do You Need It?

    -

    Roblox admin is a feature that allows you to use commands that can affect yourself or other players in the game. These commands are known as admin commands, and they can be very fun and powerful. For example, you can use commands to:

    -
      -
    • Make yourself fly, invisible, invincible, or fast
    • -
    • Kill, freeze, explode, or jail other players
    • -
    • Give yourself or others tools, weapons, items, or effects
    • -
    • Change the game's settings, such as gravity, time, weather, or lighting
    • -
    • Create or delete objects, NPCs, or scripts
    • -
    • And much more!
    • -
    -

    Roblox Admin Commands and Their Benefits

    -

    There are many roblox admin commands that you can use in the game. Some of the most common ones are:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    CommandDescription
    ;fire [player]Sets a player on fire
    ;unfire [player]Stops the fire
    ;jump [player]Makes a player jump
    ;kill [player]Kills a player
    ;loopkill [player]Kills a player over and over again
    ;ff [player]Creates a force field around a player
    ;unff [player]Erases the force field
    ;sparkles [player]Makes a player sparkly
    ;unsparkles [player]Nullifies the sparkles command
    ;smoke [player]Creates smoke around a player
    ;unsmoke [player]Turns the smoke off
    ;bighead [player]Makes the player have a big head
    ;minihead [player]Makes the player have a small head
    ;normalhead [player]Restores the player's head size
    ;explode [player]Makes the player explode
    ;trip [player]Makes the player trip and fall
    ;fling [player]Flings the player into the air
    ;ban [player]Bans the player from the game
    ;unban [player]Unbans the player from the game
    ;kick [player]Kicks the player from the game
    ;shutdownShuts down the game server
    ;respawn [player]Respawns the player
    ;god [player]Makes the player invincible
    ;ungod [player]Removes the invincibility effect
    ;invisible [player]Makes the player invisible
    ;visible [player]Makes the player visible again
    ;fly [player]Makes the player fly
    ;unfly [player]Stops the flying effect
    And many more!
    -

    As you can see, roblox admin commands can be very fun and powerful. They can let you do things that you normally can't do in the game, such as flying, being invisible, or controlling other players. They can also let you prank, troll, or punish other players, such as killing them, exploding them, or banning them. They can also let you customize the game to your liking, such as changing the settings, creating objects, or deleting scripts.

    -

    However, not everyone can use these commands. You need to have admin privileges in the game, which are usually given by the game's owner or developer. If you don't have admin privileges, you won't be able to use these commands. So how can you get admin privileges in any game? Let's find out in the next section.

    -

    How to Get Roblox Admin Privileges in Any Game

    -

    The easiest way to get roblox admin privileges in any game is to ask the game's owner or developer to give them to you. However, this is not always possible or easy. The game's owner or developer may not be online, may not know you, may not trust you, or may not want to give you admin privileges for various reasons.

    -

    Another way to get roblox admin privileges in any game is to use a script that can give you admin privileges. A script is a piece of code that can run in the game and perform certain actions. Some scripts can give you admin privileges by exploiting a vulnerability in the game or by bypassing the security measures. However, this is not always safe or legal. Using scripts can expose you to malware, viruses, hackers, or scammers. It can also get you banned or hacked by roblox or by the game's owner or developer.

    -

    How to download roblox 4.4.2 on Windows 10
    -Download roblox 4.4.2 apk for Android devices
    -Roblox 4.4.2 update: What's new and how to install it
    -Download roblox 4.4.2 for free and play online games
    -Roblox 4.4.2 download link: Where to find it and how to use it
    -Download roblox 4.4.2 for Mac and enjoy the latest features
    -Roblox 4.4.2 mod menu: How to download and install it
    -Download roblox 4.4.2 for PC and create your own games
    -Roblox 4.4.2 hack: How to download and use it safely
    -Download roblox 4.4.2 for iOS and join millions of players
    -Roblox 4.4.2 download error: How to fix it and resume the installation
    -Download roblox 4.4.2 for Chromebook and access thousands of games
    -Roblox 4.4.2 download size: How much space do you need and how to free up some
    -Download roblox 4.4.2 for Linux and enjoy the cross-platform compatibility
    -Roblox 4.4.2 download speed: How to improve it and reduce the waiting time
    -Download roblox 4.4.2 for Xbox One and play with your friends
    -Roblox 4.4.2 download without virus: How to scan and verify the file before installing it
    -Download roblox 4.4.2 for Kindle Fire and explore the virtual worlds
    -Roblox 4.4.2 download not working: How to troubleshoot and solve the issue
    -Download roblox 4.4.2 for PS4 and experience the immersive gameplay
    -Roblox 4.4.2 download old version: How to downgrade and restore the previous version
    -Download roblox 4.4.2 for Nintendo Switch and enjoy the portable gaming
    -Roblox 4.4.2 download cracked: How to get the full version without paying
    -Download roblox 4.4.2 for Windows 7 and run it smoothly
    -Roblox 4.4.2 download tutorial: How to follow the steps and complete the installation

    -

    The best way to get roblox admin privileges in any game is to use a hack or a cheat that can give you admin privileges. A hack or a cheat is a tool that can modify the game's data or behavior and give you an advantage over other players. Some hacks or cheats can give you admin privileges by injecting code into the game or by spoofing your identity. However, this is not always easy or reliable. Using hacks or cheats can require technical skills, knowledge, and experience. It can also be detected by roblox or by the game's owner or developer and get you banned or hacked.

    -

    So how can you download hack roblox admin and use it effectively? Let's find out in the next section.

    -

    How to Download Hack Roblox Admin and Use It Effectively

    -

    If you want to download hack roblox admin and use it effectively, you need to follow these steps:

    -

    The Best Sources for Roblox Admin Hacks and Cheats

    -

    The first step is to find a reliable and trustworthy source for roblox admin hacks and cheats. There are many websites, forums, blogs, videos, and social media pages that claim to offer roblox admin hacks and cheats for free or for a fee. However, not all of them are genuine, safe, or updated. Some of them may be scams, malware, viruses, or outdated. Therefore, you need to be careful and selective when choosing a source for roblox admin hacks and cheats.

    -

    Some of the best sources for roblox admin hacks and cheats are:

    -
      -
    • RobloxHacks.com: This is a website that offers a variety of roblox hacks and cheats, including roblox admin hacks and cheats. You can download them for free or for a small donation. They are updated regularly and tested for safety and functionality. They also have a blog, a forum, and a support team that can help you with any issues or questions.
    • -
    • RobloxAdminHack.net: This is a website that specializes in roblox admin hacks and cheats. You can download them for free or for a premium membership. They are updated frequently and verified for quality and performance. They also have a video tutorial, a FAQ section, and a contact form that can assist you with any problems or inquiries.
    • -
    • RobloxAdminCheat.com: This is a website that focuses on roblox admin cheats and exploits. You can download them for free or for a VIP subscription. They are updated often and checked for reliability and efficiency. They also have a guide, a review section, and a chat room that can help you with any difficulties or feedback.
    • -
    -

    These are some of the best sources for roblox admin hacks and cheats that we recommend. However, you should always do your own research and use your own judgment before downloading anything from the internet. You should also scan any files you download with an antivirus software and follow the instructions carefully.

    -

    How to Install and Run Roblox Admin Hacks and Cheats

    -

    The second step is to install and run roblox admin hacks and cheats on your device. This may vary depending on the type of hack or cheat you download, but generally, you need to follow these steps:

    -
      -
    1. Download the hack or cheat file from the source you chose.
    2. -
    3. Extract the file to a folder on your device using a file extractor software such as WinRAR or 7-Zip.
    4. -
    5. Open the folder and find the executable file (.exe) or the script file (.lua) of the hack or cheat.
    6. -
    7. Run the executable file or the script file as an administrator on your device.
    8. -
    9. Wait for the hack or cheat to load and connect to roblox.
    10. -
    11. Open roblox and join any game you want.
    12. -
    13. Press the key combination or type the command that activates the hack or cheat menu.
    14. -
    15. Select the option that gives you admin privileges in the game.
    16. -
    17. Enjoy using roblox admin commands in the game!
    18. -
    -

    These are the general steps to install and run roblox admin hacks and cheats on your device. However, you should always read the instructions carefully and follow them exactly as they are given by the source you downloaded from. You should also backup your device and your roblox account before using any hack or cheat.

    -

    The Top Features of Roblox Admin Hacks and Cheats

    -

    The third step is to use roblox admin hacks and cheats effectively in the game. This may depend on the type of hack or cheat you use, but generally, you can enjoy these features:

    -
      -
    • You can use any roblox admin command in any game without needing permission from the game's owner or developer.
    • -
    • You can use roblox admin commands faster, easier, and more conveniently with a simple key press or a command line.
    • -
    • You can use roblox admin commands more discreetly, stealthily, and secretly with an invisible mode or a bypass mode.
    • -
    • You can use roblox admin commands more creatively, diversely, and extensively with a custom mode or an advanced mode.
    • -
    • You can use roblox admin commands more safely, securely, and confidently with an anti-ban mode or an anti-hack mode.
    • -
    -

    These are some of the top features of roblox admin hacks and cheats that we recommend. However, you should always use them wisely and responsibly in the game. You should also respect other players' rights and feelings in the game.

    -

    How to Use Hack Roblox Admin Safely and Avoid Getting Banned

    -

    If you want to use hack roblox admin safely and avoid getting banned, you need to follow these tips:

    -

    The Risks of Using Hack Roblox Admin and How to Minimize Them

    Using hack roblox admin can be very risky and dangerous. You can face many problems and consequences, such as:

    -
      -
    • Your device can get infected with malware, viruses, or spyware that can harm your data, privacy, or security.
    • -
    • Your roblox account can get hacked, stolen, or compromised by hackers, scammers, or phishers who can access your personal information, robux, or items.
    • -
    • Your roblox account can get banned, suspended, or terminated by roblox or by the game's owner or developer who can detect your hack or cheat and report you for violating the terms of service or the game's rules.
    • -
    -

    Therefore, you need to minimize these risks and protect yourself from these threats. You can do this by:

    -
      -
    • Using a reputable and trustworthy source for roblox admin hacks and cheats that has positive reviews, ratings, and feedback from other users.
    • -
    • Using an antivirus software and a firewall on your device that can scan, detect, and remove any malicious files or programs that you download or run.
    • -
    • Using a VPN service or a proxy server on your device that can hide your IP address and location from roblox or from the game's owner or developer who can track you down and ban you.
    • -
    • Using a secondary or a fake roblox account that you don't care about losing or getting banned when using hack roblox admin in the game.
    • -
    • Using hack roblox admin sparingly and moderately in the game. Don't use it too often, too long, or too blatantly. Don't abuse it, misuse it, or overuse it. Don't annoy, harass, or bully other players with it.
    • -
    -

    These are some of the tips to use hack roblox admin safely and avoid getting banned. However, you should always be aware of the risks and consequences of using hack roblox admin and be prepared to face them if they happen.

    -

    The Best Practices for Using Hack Roblox Admin Responsibly

    -

    Using hack roblox admin responsibly means using it in a way that does not harm yourself, other players, or the game. It means using it in a way that is fair, ethical, and respectful. It means using it in a way that is fun, enjoyable, and entertaining. Here are some of the best practices for using hack roblox admin responsibly:

    -
      -
    • Use hack roblox admin only for personal use and entertainment. Don't use it for commercial use or profit. Don't sell it, share it, or distribute it to others without permission from the source you downloaded from.
    • -
    • Use hack roblox admin only in games that allow it or don't mind it. Don't use it in games that prohibit it or hate it. Don't use it in games that have strict rules or high standards. Don't use it in games that are competitive or serious.
    • -
    • Use hack roblox admin only with consent and agreement from other players. Don't use it without permission or approval from other players. Don't use it against other players' wishes or preferences. Don't use it to ruin other players' fun or experience.
    • -
    • Use hack roblox admin only with moderation and balance. Don't use it excessively or excessively. Don't use it to gain an unfair advantage or an unfair edge over other players. Don't use it to cheat or exploit the game.
    • -
    • Use hack roblox admin only with caution and care. Don't use it recklessly or carelessly. Don't use it to cause harm or damage to yourself, other players, or the game. Don't use it to create problems or issues for yourself, other players, or the game.
    • -
    -

    These are some of the best practices for using hack roblox admin responsibly. However, you should always follow your own morals and values when using hack roblox admin and be respectful of others' morals and values as well.

    -

    How to Recover Your Account If You Get Banned or Hacked

    -

    If you get banned or hacked while using hack roblox admin, don't panic. There are ways to recover your account and get back into the game. Here are some of the steps you can take:

    -
      -
    1. If you get banned by roblox, you can try to appeal your ban by contacting roblox support and explaining your situation. You can also try to create a new account with a different email address and username.
    2. -
    3. If you get banned by the game's owner or developer, you can try to contact them and apologize for your actions. You can also try to join a different game server or a different game altogether.
    4. -
    5. If you get hacked by hackers, scammers, or phishers, you can try to reset your password and secure your account by enabling two-step verification and changing your email address and phone number. You can also try to contact roblox support and report the hacker, scammer, or phisher.
    6. -
    -

    These are some of the steps you can take to recover your account if you get banned or hacked while using hack roblox admin. However, you should always be careful and vigilant when using hack roblox admin and avoid getting banned or hacked in the first place.

    -

    Conclusion

    -

    Roblox admin is a feature that allows you to use commands that can affect yourself or other players in the game. These commands are known as admin commands, and they can be very fun and powerful. However, not everyone can use them. You need to have admin privileges in the game, which are usually given by the game's owner or developer.

    -

    If you want to have admin privileges in any game, you can use hack roblox admin. Hack roblox admin is a tool that can give you admin privileges by modifying the game's data or behavior. However, using hack roblox admin can be risky and dangerous. You can get banned or hacked by roblox or by the game's owner or developer. Therefore, you need to use hack roblox admin safely and responsibly.

    -

    In this article, we showed you what roblox admin is, why you need it, how to download it, how to use it effectively, and how to avoid getting banned or hacked. We hope you found this article helpful and informative. If you have any questions or comments, feel free to leave them below. Thank you for reading!

    -

    FAQs

    -

    Here are some of the frequently asked questions about hack roblox admin:

    -

    Q: Is hack roblox admin legal?

    -

    A: Hack roblox admin is not legal. It violates the terms of service of roblox and the game's rules. It also infringes the intellectual property rights of roblox and the game's owner or developer. Using hack roblox admin can result in legal actions against you.

    -

    Q: Is hack roblox admin safe?

    -

    A: Hack roblox admin is not safe. It exposes you to malware, viruses, hackers, or scammers that can harm your device or your account. It also exposes you to bans or hacks by roblox or by the game's owner or developer that can ruin your gaming experience. Using hack roblox admin can result in negative consequences for you.

    -

    Q: Is hack roblox admin free?

    -

    A: Hack roblox admin is not free. It requires a fee or a donation to download or use it. It also requires a premium membership or a VIP subscription to access its full features or updates. Using hack roblox admin can result in financial costs for you.

    -

    Q: Is hack roblox admin worth it?

    -

    A: Hack roblox admin is not worth it. It does not guarantee that you will get admin privileges in any game. It does not guarantee that you will enjoy using admin commands in the game. It does not guarantee that you will avoid getting banned or hacked while using it. Using hack roblox admin can result in disappointment for you.

    -

    Q: Is there an alternative to hack roblox admin?

    -

    A: Yes, there is an alternative to hack roblox admin. You can try to get admin privileges in the game legitimately by asking the game's owner or developer to give them to you. You can also try to create your own game with your own admin commands and invite other players to join it. This way, you can have fun and power without risking anything.

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/contluForse/HuggingGPT/assets/Autocomcdp20131keygendownloadnovirus __TOP__.md b/spaces/contluForse/HuggingGPT/assets/Autocomcdp20131keygendownloadnovirus __TOP__.md deleted file mode 100644 index c8cd5480881f8fcb2d535efa5c571918239853bf..0000000000000000000000000000000000000000 --- a/spaces/contluForse/HuggingGPT/assets/Autocomcdp20131keygendownloadnovirus __TOP__.md +++ /dev/null @@ -1,6 +0,0 @@ -

    autocomcdp20131keygendownloadnovirus


    Download Zip »»» https://ssurll.com/2uzwxP



    - - 1fdad05405
    -
    -
    -

    diff --git a/spaces/contluForse/HuggingGPT/assets/Dhum Dhadaka Marathi Movie Free Download Mahesh Kothare and Ashok Saraf in a Rib-Tickling Comedy.md b/spaces/contluForse/HuggingGPT/assets/Dhum Dhadaka Marathi Movie Free Download Mahesh Kothare and Ashok Saraf in a Rib-Tickling Comedy.md deleted file mode 100644 index e9b37fd0116b18e0b7f2bd666c2b93905269b4b2..0000000000000000000000000000000000000000 --- a/spaces/contluForse/HuggingGPT/assets/Dhum Dhadaka Marathi Movie Free Download Mahesh Kothare and Ashok Saraf in a Rib-Tickling Comedy.md +++ /dev/null @@ -1,6 +0,0 @@ -

    dhumdhadakamarathimoviefreedownload


    Downloadhttps://ssurll.com/2uzySs



    - - aaccfb2cb3
    -
    -
    -

    diff --git a/spaces/cooelf/Multimodal-CoT/timm/models/hardcorenas.py b/spaces/cooelf/Multimodal-CoT/timm/models/hardcorenas.py deleted file mode 100644 index 9988a0444558d9e7f4b640ff468cc63b1dc1d7f4..0000000000000000000000000000000000000000 --- a/spaces/cooelf/Multimodal-CoT/timm/models/hardcorenas.py +++ /dev/null @@ -1,152 +0,0 @@ -from functools import partial - -import torch.nn as nn - -from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD -from .efficientnet_blocks import SqueezeExcite -from .efficientnet_builder import decode_arch_def, resolve_act_layer, resolve_bn_args, round_channels -from .helpers import build_model_with_cfg, default_cfg_for_features -from .layers import get_act_fn -from .mobilenetv3 import MobileNetV3, MobileNetV3Features -from .registry import register_model - - -def _cfg(url='', **kwargs): - return { - 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (1, 1), - 'crop_pct': 0.875, 'interpolation': 'bilinear', - 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD, - 'first_conv': 'conv_stem', 'classifier': 'classifier', - **kwargs - } - - -default_cfgs = { - 'hardcorenas_a': _cfg(url='https://miil-public-eu.oss-eu-central-1.aliyuncs.com/public/HardCoReNAS/HardCoreNAS_A_Green_38ms_75.9_23474aeb.pth'), - 'hardcorenas_b': _cfg(url='https://miil-public-eu.oss-eu-central-1.aliyuncs.com/public/HardCoReNAS/HardCoreNAS_B_Green_40ms_76.5_1f882d1e.pth'), - 'hardcorenas_c': _cfg(url='https://miil-public-eu.oss-eu-central-1.aliyuncs.com/public/HardCoReNAS/HardCoreNAS_C_Green_44ms_77.1_d4148c9e.pth'), - 'hardcorenas_d': _cfg(url='https://miil-public-eu.oss-eu-central-1.aliyuncs.com/public/HardCoReNAS/HardCoreNAS_D_Green_50ms_77.4_23e3cdde.pth'), - 'hardcorenas_e': _cfg(url='https://miil-public-eu.oss-eu-central-1.aliyuncs.com/public/HardCoReNAS/HardCoreNAS_E_Green_55ms_77.9_90f20e8a.pth'), - 'hardcorenas_f': _cfg(url='https://miil-public-eu.oss-eu-central-1.aliyuncs.com/public/HardCoReNAS/HardCoreNAS_F_Green_60ms_78.1_2855edf1.pth'), -} - - -def _gen_hardcorenas(pretrained, variant, arch_def, **kwargs): - """Creates a hardcorenas model - - Ref impl: https://github.com/Alibaba-MIIL/HardCoReNAS - Paper: https://arxiv.org/abs/2102.11646 - - """ - num_features = 1280 - se_layer = partial(SqueezeExcite, gate_layer='hard_sigmoid', force_act_layer=nn.ReLU, rd_round_fn=round_channels) - model_kwargs = dict( - block_args=decode_arch_def(arch_def), - num_features=num_features, - stem_size=32, - norm_layer=partial(nn.BatchNorm2d, **resolve_bn_args(kwargs)), - act_layer=resolve_act_layer(kwargs, 'hard_swish'), - se_layer=se_layer, - **kwargs, - ) - - features_only = False - model_cls = MobileNetV3 - kwargs_filter = None - if model_kwargs.pop('features_only', False): - features_only = True - kwargs_filter = ('num_classes', 'num_features', 'global_pool', 'head_conv', 'head_bias', 'global_pool') - model_cls = MobileNetV3Features - model = build_model_with_cfg( - model_cls, variant, pretrained, - default_cfg=default_cfgs[variant], - pretrained_strict=not features_only, - kwargs_filter=kwargs_filter, - **model_kwargs) - if features_only: - model.default_cfg = default_cfg_for_features(model.default_cfg) - return model - - -@register_model -def hardcorenas_a(pretrained=False, **kwargs): - """ hardcorenas_A """ - arch_def = [['ds_r1_k3_s1_e1_c16_nre'], ['ir_r1_k5_s2_e3_c24_nre', 'ir_r1_k5_s1_e3_c24_nre_se0.25'], - ['ir_r1_k5_s2_e3_c40_nre', 'ir_r1_k5_s1_e6_c40_nre_se0.25'], - ['ir_r1_k5_s2_e6_c80_se0.25', 'ir_r1_k5_s1_e6_c80_se0.25'], - ['ir_r1_k5_s1_e6_c112_se0.25', 'ir_r1_k5_s1_e6_c112_se0.25'], - ['ir_r1_k5_s2_e6_c192_se0.25', 'ir_r1_k5_s1_e6_c192_se0.25'], ['cn_r1_k1_s1_c960']] - model = _gen_hardcorenas(pretrained=pretrained, variant='hardcorenas_a', arch_def=arch_def, **kwargs) - return model - - -@register_model -def hardcorenas_b(pretrained=False, **kwargs): - """ hardcorenas_B """ - arch_def = [['ds_r1_k3_s1_e1_c16_nre'], - ['ir_r1_k5_s2_e3_c24_nre', 'ir_r1_k5_s1_e3_c24_nre_se0.25', 'ir_r1_k3_s1_e3_c24_nre'], - ['ir_r1_k5_s2_e3_c40_nre', 'ir_r1_k5_s1_e3_c40_nre', 'ir_r1_k5_s1_e3_c40_nre'], - ['ir_r1_k5_s2_e3_c80', 'ir_r1_k5_s1_e3_c80', 'ir_r1_k3_s1_e3_c80', 'ir_r1_k3_s1_e3_c80'], - ['ir_r1_k5_s1_e3_c112', 'ir_r1_k3_s1_e3_c112', 'ir_r1_k3_s1_e3_c112', 'ir_r1_k3_s1_e3_c112'], - ['ir_r1_k5_s2_e6_c192_se0.25', 'ir_r1_k5_s1_e6_c192_se0.25', 'ir_r1_k3_s1_e3_c192_se0.25'], - ['cn_r1_k1_s1_c960']] - model = _gen_hardcorenas(pretrained=pretrained, variant='hardcorenas_b', arch_def=arch_def, **kwargs) - return model - - -@register_model -def hardcorenas_c(pretrained=False, **kwargs): - """ hardcorenas_C """ - arch_def = [['ds_r1_k3_s1_e1_c16_nre'], ['ir_r1_k5_s2_e3_c24_nre', 'ir_r1_k5_s1_e3_c24_nre_se0.25'], - ['ir_r1_k5_s2_e3_c40_nre', 'ir_r1_k5_s1_e3_c40_nre', 'ir_r1_k5_s1_e3_c40_nre', - 'ir_r1_k5_s1_e3_c40_nre'], - ['ir_r1_k5_s2_e4_c80', 'ir_r1_k5_s1_e6_c80_se0.25', 'ir_r1_k3_s1_e3_c80', 'ir_r1_k3_s1_e3_c80'], - ['ir_r1_k5_s1_e6_c112_se0.25', 'ir_r1_k3_s1_e3_c112', 'ir_r1_k3_s1_e3_c112', 'ir_r1_k3_s1_e3_c112'], - ['ir_r1_k5_s2_e6_c192_se0.25', 'ir_r1_k5_s1_e6_c192_se0.25', 'ir_r1_k3_s1_e3_c192_se0.25'], - ['cn_r1_k1_s1_c960']] - model = _gen_hardcorenas(pretrained=pretrained, variant='hardcorenas_c', arch_def=arch_def, **kwargs) - return model - - -@register_model -def hardcorenas_d(pretrained=False, **kwargs): - """ hardcorenas_D """ - arch_def = [['ds_r1_k3_s1_e1_c16_nre'], ['ir_r1_k5_s2_e3_c24_nre_se0.25', 'ir_r1_k5_s1_e3_c24_nre_se0.25'], - ['ir_r1_k5_s2_e3_c40_nre_se0.25', 'ir_r1_k5_s1_e4_c40_nre_se0.25', 'ir_r1_k3_s1_e3_c40_nre_se0.25'], - ['ir_r1_k5_s2_e4_c80_se0.25', 'ir_r1_k3_s1_e3_c80_se0.25', 'ir_r1_k3_s1_e3_c80_se0.25', - 'ir_r1_k3_s1_e3_c80_se0.25'], - ['ir_r1_k3_s1_e4_c112_se0.25', 'ir_r1_k5_s1_e4_c112_se0.25', 'ir_r1_k3_s1_e3_c112_se0.25', - 'ir_r1_k5_s1_e3_c112_se0.25'], - ['ir_r1_k5_s2_e6_c192_se0.25', 'ir_r1_k5_s1_e6_c192_se0.25', 'ir_r1_k5_s1_e6_c192_se0.25', - 'ir_r1_k3_s1_e6_c192_se0.25'], ['cn_r1_k1_s1_c960']] - model = _gen_hardcorenas(pretrained=pretrained, variant='hardcorenas_d', arch_def=arch_def, **kwargs) - return model - - -@register_model -def hardcorenas_e(pretrained=False, **kwargs): - """ hardcorenas_E """ - arch_def = [['ds_r1_k3_s1_e1_c16_nre'], ['ir_r1_k5_s2_e3_c24_nre_se0.25', 'ir_r1_k5_s1_e3_c24_nre_se0.25'], - ['ir_r1_k5_s2_e6_c40_nre_se0.25', 'ir_r1_k5_s1_e4_c40_nre_se0.25', 'ir_r1_k5_s1_e4_c40_nre_se0.25', - 'ir_r1_k3_s1_e3_c40_nre_se0.25'], ['ir_r1_k5_s2_e4_c80_se0.25', 'ir_r1_k3_s1_e6_c80_se0.25'], - ['ir_r1_k5_s1_e6_c112_se0.25', 'ir_r1_k5_s1_e6_c112_se0.25', 'ir_r1_k5_s1_e6_c112_se0.25', - 'ir_r1_k5_s1_e3_c112_se0.25'], - ['ir_r1_k5_s2_e6_c192_se0.25', 'ir_r1_k5_s1_e6_c192_se0.25', 'ir_r1_k5_s1_e6_c192_se0.25', - 'ir_r1_k3_s1_e6_c192_se0.25'], ['cn_r1_k1_s1_c960']] - model = _gen_hardcorenas(pretrained=pretrained, variant='hardcorenas_e', arch_def=arch_def, **kwargs) - return model - - -@register_model -def hardcorenas_f(pretrained=False, **kwargs): - """ hardcorenas_F """ - arch_def = [['ds_r1_k3_s1_e1_c16_nre'], ['ir_r1_k5_s2_e3_c24_nre_se0.25', 'ir_r1_k5_s1_e3_c24_nre_se0.25'], - ['ir_r1_k5_s2_e6_c40_nre_se0.25', 'ir_r1_k5_s1_e6_c40_nre_se0.25'], - ['ir_r1_k5_s2_e6_c80_se0.25', 'ir_r1_k5_s1_e6_c80_se0.25', 'ir_r1_k3_s1_e3_c80_se0.25', - 'ir_r1_k3_s1_e3_c80_se0.25'], - ['ir_r1_k3_s1_e6_c112_se0.25', 'ir_r1_k5_s1_e6_c112_se0.25', 'ir_r1_k5_s1_e6_c112_se0.25', - 'ir_r1_k3_s1_e3_c112_se0.25'], - ['ir_r1_k5_s2_e6_c192_se0.25', 'ir_r1_k5_s1_e6_c192_se0.25', 'ir_r1_k3_s1_e6_c192_se0.25', - 'ir_r1_k3_s1_e6_c192_se0.25'], ['cn_r1_k1_s1_c960']] - model = _gen_hardcorenas(pretrained=pretrained, variant='hardcorenas_f', arch_def=arch_def, **kwargs) - return model diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/normalbae/models/NNET.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/normalbae/models/NNET.py deleted file mode 100644 index 3ddbc50c3ac18aa4b7f16779fe3c0133981ecc7a..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/normalbae/models/NNET.py +++ /dev/null @@ -1,22 +0,0 @@ -import torch -import torch.nn as nn -import torch.nn.functional as F - -from .submodules.encoder import Encoder -from .submodules.decoder import Decoder - - -class NNET(nn.Module): - def __init__(self, args): - super(NNET, self).__init__() - self.encoder = Encoder() - self.decoder = Decoder(args) - - def get_1x_lr_params(self): # lr/10 learning rate - return self.encoder.parameters() - - def get_10x_lr_params(self): # lr learning rate - return self.decoder.parameters() - - def forward(self, img, **kwargs): - return self.decoder(self.encoder(img), **kwargs) \ No newline at end of file diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/structures/image_list.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/structures/image_list.py deleted file mode 100644 index 86c8b9512a5fd8abda7fdf058a63b19f809e46f6..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/structures/image_list.py +++ /dev/null @@ -1,129 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -from __future__ import division -from typing import Any, Dict, List, Optional, Tuple -import torch -from torch import device -from torch.nn import functional as F - -from annotator.oneformer.detectron2.layers.wrappers import move_device_like, shapes_to_tensor - - -class ImageList(object): - """ - Structure that holds a list of images (of possibly - varying sizes) as a single tensor. - This works by padding the images to the same size. - The original sizes of each image is stored in `image_sizes`. - - Attributes: - image_sizes (list[tuple[int, int]]): each tuple is (h, w). - During tracing, it becomes list[Tensor] instead. - """ - - def __init__(self, tensor: torch.Tensor, image_sizes: List[Tuple[int, int]]): - """ - Arguments: - tensor (Tensor): of shape (N, H, W) or (N, C_1, ..., C_K, H, W) where K >= 1 - image_sizes (list[tuple[int, int]]): Each tuple is (h, w). It can - be smaller than (H, W) due to padding. - """ - self.tensor = tensor - self.image_sizes = image_sizes - - def __len__(self) -> int: - return len(self.image_sizes) - - def __getitem__(self, idx) -> torch.Tensor: - """ - Access the individual image in its original size. - - Args: - idx: int or slice - - Returns: - Tensor: an image of shape (H, W) or (C_1, ..., C_K, H, W) where K >= 1 - """ - size = self.image_sizes[idx] - return self.tensor[idx, ..., : size[0], : size[1]] - - @torch.jit.unused - def to(self, *args: Any, **kwargs: Any) -> "ImageList": - cast_tensor = self.tensor.to(*args, **kwargs) - return ImageList(cast_tensor, self.image_sizes) - - @property - def device(self) -> device: - return self.tensor.device - - @staticmethod - def from_tensors( - tensors: List[torch.Tensor], - size_divisibility: int = 0, - pad_value: float = 0.0, - padding_constraints: Optional[Dict[str, int]] = None, - ) -> "ImageList": - """ - Args: - tensors: a tuple or list of `torch.Tensor`, each of shape (Hi, Wi) or - (C_1, ..., C_K, Hi, Wi) where K >= 1. The Tensors will be padded - to the same shape with `pad_value`. - size_divisibility (int): If `size_divisibility > 0`, add padding to ensure - the common height and width is divisible by `size_divisibility`. - This depends on the model and many models need a divisibility of 32. - pad_value (float): value to pad. - padding_constraints (optional[Dict]): If given, it would follow the format as - {"size_divisibility": int, "square_size": int}, where `size_divisibility` will - overwrite the above one if presented and `square_size` indicates the - square padding size if `square_size` > 0. - Returns: - an `ImageList`. - """ - assert len(tensors) > 0 - assert isinstance(tensors, (tuple, list)) - for t in tensors: - assert isinstance(t, torch.Tensor), type(t) - assert t.shape[:-2] == tensors[0].shape[:-2], t.shape - - image_sizes = [(im.shape[-2], im.shape[-1]) for im in tensors] - image_sizes_tensor = [shapes_to_tensor(x) for x in image_sizes] - max_size = torch.stack(image_sizes_tensor).max(0).values - - if padding_constraints is not None: - square_size = padding_constraints.get("square_size", 0) - if square_size > 0: - # pad to square. - max_size[0] = max_size[1] = square_size - if "size_divisibility" in padding_constraints: - size_divisibility = padding_constraints["size_divisibility"] - if size_divisibility > 1: - stride = size_divisibility - # the last two dims are H,W, both subject to divisibility requirement - max_size = (max_size + (stride - 1)).div(stride, rounding_mode="floor") * stride - - # handle weirdness of scripting and tracing ... - if torch.jit.is_scripting(): - max_size: List[int] = max_size.to(dtype=torch.long).tolist() - else: - if torch.jit.is_tracing(): - image_sizes = image_sizes_tensor - - if len(tensors) == 1: - # This seems slightly (2%) faster. - # TODO: check whether it's faster for multiple images as well - image_size = image_sizes[0] - padding_size = [0, max_size[-1] - image_size[1], 0, max_size[-2] - image_size[0]] - batched_imgs = F.pad(tensors[0], padding_size, value=pad_value).unsqueeze_(0) - else: - # max_size can be a tensor in tracing mode, therefore convert to list - batch_shape = [len(tensors)] + list(tensors[0].shape[:-2]) + list(max_size) - device = ( - None if torch.jit.is_scripting() else ("cpu" if torch.jit.is_tracing() else None) - ) - batched_imgs = tensors[0].new_full(batch_shape, pad_value, device=device) - batched_imgs = move_device_like(batched_imgs, tensors[0]) - for i, img in enumerate(tensors): - # Use `batched_imgs` directly instead of `img, pad_img = zip(tensors, batched_imgs)` - # Tracing mode cannot capture `copy_()` of temporary locals - batched_imgs[i, ..., : img.shape[-2], : img.shape[-1]].copy_(img) - - return ImageList(batched_imgs.contiguous(), image_sizes) diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/zoe/zoedepth/trainers/loss.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/zoe/zoedepth/trainers/loss.py deleted file mode 100644 index 0c5a1c15cdf5628c1474c566fdc6e58159d7f5ab..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/zoe/zoedepth/trainers/loss.py +++ /dev/null @@ -1,316 +0,0 @@ -# MIT License - -# Copyright (c) 2022 Intelligent Systems Lab Org - -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: - -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. - -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - -# File author: Shariq Farooq Bhat - -import torch -import torch.nn as nn -import torch.nn.functional as F -import torch.cuda.amp as amp -import numpy as np - - -KEY_OUTPUT = 'metric_depth' - - -def extract_key(prediction, key): - if isinstance(prediction, dict): - return prediction[key] - return prediction - - -# Main loss function used for ZoeDepth. Copy/paste from AdaBins repo (https://github.com/shariqfarooq123/AdaBins/blob/0952d91e9e762be310bb4cd055cbfe2448c0ce20/loss.py#L7) -class SILogLoss(nn.Module): - """SILog loss (pixel-wise)""" - def __init__(self, beta=0.15): - super(SILogLoss, self).__init__() - self.name = 'SILog' - self.beta = beta - - def forward(self, input, target, mask=None, interpolate=True, return_interpolated=False): - input = extract_key(input, KEY_OUTPUT) - if input.shape[-1] != target.shape[-1] and interpolate: - input = nn.functional.interpolate( - input, target.shape[-2:], mode='bilinear', align_corners=True) - intr_input = input - else: - intr_input = input - - if target.ndim == 3: - target = target.unsqueeze(1) - - if mask is not None: - if mask.ndim == 3: - mask = mask.unsqueeze(1) - - input = input[mask] - target = target[mask] - - with amp.autocast(enabled=False): # amp causes NaNs in this loss function - alpha = 1e-7 - g = torch.log(input + alpha) - torch.log(target + alpha) - - # n, c, h, w = g.shape - # norm = 1/(h*w) - # Dg = norm * torch.sum(g**2) - (0.85/(norm**2)) * (torch.sum(g))**2 - - Dg = torch.var(g) + self.beta * torch.pow(torch.mean(g), 2) - - loss = 10 * torch.sqrt(Dg) - - if torch.isnan(loss): - print("Nan SILog loss") - print("input:", input.shape) - print("target:", target.shape) - print("G", torch.sum(torch.isnan(g))) - print("Input min max", torch.min(input), torch.max(input)) - print("Target min max", torch.min(target), torch.max(target)) - print("Dg", torch.isnan(Dg)) - print("loss", torch.isnan(loss)) - - if not return_interpolated: - return loss - - return loss, intr_input - - -def grad(x): - # x.shape : n, c, h, w - diff_x = x[..., 1:, 1:] - x[..., 1:, :-1] - diff_y = x[..., 1:, 1:] - x[..., :-1, 1:] - mag = diff_x**2 + diff_y**2 - # angle_ratio - angle = torch.atan(diff_y / (diff_x + 1e-10)) - return mag, angle - - -def grad_mask(mask): - return mask[..., 1:, 1:] & mask[..., 1:, :-1] & mask[..., :-1, 1:] - - -class GradL1Loss(nn.Module): - """Gradient loss""" - def __init__(self): - super(GradL1Loss, self).__init__() - self.name = 'GradL1' - - def forward(self, input, target, mask=None, interpolate=True, return_interpolated=False): - input = extract_key(input, KEY_OUTPUT) - if input.shape[-1] != target.shape[-1] and interpolate: - input = nn.functional.interpolate( - input, target.shape[-2:], mode='bilinear', align_corners=True) - intr_input = input - else: - intr_input = input - - grad_gt = grad(target) - grad_pred = grad(input) - mask_g = grad_mask(mask) - - loss = nn.functional.l1_loss(grad_pred[0][mask_g], grad_gt[0][mask_g]) - loss = loss + \ - nn.functional.l1_loss(grad_pred[1][mask_g], grad_gt[1][mask_g]) - if not return_interpolated: - return loss - return loss, intr_input - - -class OrdinalRegressionLoss(object): - - def __init__(self, ord_num, beta, discretization="SID"): - self.ord_num = ord_num - self.beta = beta - self.discretization = discretization - - def _create_ord_label(self, gt): - N,one, H, W = gt.shape - # print("gt shape:", gt.shape) - - ord_c0 = torch.ones(N, self.ord_num, H, W).to(gt.device) - if self.discretization == "SID": - label = self.ord_num * torch.log(gt) / np.log(self.beta) - else: - label = self.ord_num * (gt - 1.0) / (self.beta - 1.0) - label = label.long() - mask = torch.linspace(0, self.ord_num - 1, self.ord_num, requires_grad=False) \ - .view(1, self.ord_num, 1, 1).to(gt.device) - mask = mask.repeat(N, 1, H, W).contiguous().long() - mask = (mask > label) - ord_c0[mask] = 0 - ord_c1 = 1 - ord_c0 - # implementation according to the paper. - # ord_label = torch.ones(N, self.ord_num * 2, H, W).to(gt.device) - # ord_label[:, 0::2, :, :] = ord_c0 - # ord_label[:, 1::2, :, :] = ord_c1 - # reimplementation for fast speed. - ord_label = torch.cat((ord_c0, ord_c1), dim=1) - return ord_label, mask - - def __call__(self, prob, gt): - """ - :param prob: ordinal regression probability, N x 2*Ord Num x H x W, torch.Tensor - :param gt: depth ground truth, NXHxW, torch.Tensor - :return: loss: loss value, torch.float - """ - # N, C, H, W = prob.shape - valid_mask = gt > 0. - ord_label, mask = self._create_ord_label(gt) - # print("prob shape: {}, ord label shape: {}".format(prob.shape, ord_label.shape)) - entropy = -prob * ord_label - loss = torch.sum(entropy, dim=1)[valid_mask.squeeze(1)] - return loss.mean() - - -class DiscreteNLLLoss(nn.Module): - """Cross entropy loss""" - def __init__(self, min_depth=1e-3, max_depth=10, depth_bins=64): - super(DiscreteNLLLoss, self).__init__() - self.name = 'CrossEntropy' - self.ignore_index = -(depth_bins + 1) - # self._loss_func = nn.NLLLoss(ignore_index=self.ignore_index) - self._loss_func = nn.CrossEntropyLoss(ignore_index=self.ignore_index) - self.min_depth = min_depth - self.max_depth = max_depth - self.depth_bins = depth_bins - self.alpha = 1 - self.zeta = 1 - min_depth - self.beta = max_depth + self.zeta - - def quantize_depth(self, depth): - # depth : N1HW - # output : NCHW - - # Quantize depth log-uniformly on [1, self.beta] into self.depth_bins bins - depth = torch.log(depth / self.alpha) / np.log(self.beta / self.alpha) - depth = depth * (self.depth_bins - 1) - depth = torch.round(depth) - depth = depth.long() - return depth - - - - def _dequantize_depth(self, depth): - """ - Inverse of quantization - depth : NCHW -> N1HW - """ - # Get the center of the bin - - - - - def forward(self, input, target, mask=None, interpolate=True, return_interpolated=False): - input = extract_key(input, KEY_OUTPUT) - # assert torch.all(input <= 0), "Input should be negative" - - if input.shape[-1] != target.shape[-1] and interpolate: - input = nn.functional.interpolate( - input, target.shape[-2:], mode='bilinear', align_corners=True) - intr_input = input - else: - intr_input = input - - # assert torch.all(input)<=1) - if target.ndim == 3: - target = target.unsqueeze(1) - - target = self.quantize_depth(target) - if mask is not None: - if mask.ndim == 3: - mask = mask.unsqueeze(1) - - # Set the mask to ignore_index - mask = mask.long() - input = input * mask + (1 - mask) * self.ignore_index - target = target * mask + (1 - mask) * self.ignore_index - - - - input = input.flatten(2) # N, nbins, H*W - target = target.flatten(1) # N, H*W - loss = self._loss_func(input, target) - - if not return_interpolated: - return loss - return loss, intr_input - - - - -def compute_scale_and_shift(prediction, target, mask): - # system matrix: A = [[a_00, a_01], [a_10, a_11]] - a_00 = torch.sum(mask * prediction * prediction, (1, 2)) - a_01 = torch.sum(mask * prediction, (1, 2)) - a_11 = torch.sum(mask, (1, 2)) - - # right hand side: b = [b_0, b_1] - b_0 = torch.sum(mask * prediction * target, (1, 2)) - b_1 = torch.sum(mask * target, (1, 2)) - - # solution: x = A^-1 . b = [[a_11, -a_01], [-a_10, a_00]] / (a_00 * a_11 - a_01 * a_10) . b - x_0 = torch.zeros_like(b_0) - x_1 = torch.zeros_like(b_1) - - det = a_00 * a_11 - a_01 * a_01 - # A needs to be a positive definite matrix. - valid = det > 0 - - x_0[valid] = (a_11[valid] * b_0[valid] - a_01[valid] * b_1[valid]) / det[valid] - x_1[valid] = (-a_01[valid] * b_0[valid] + a_00[valid] * b_1[valid]) / det[valid] - - return x_0, x_1 -class ScaleAndShiftInvariantLoss(nn.Module): - def __init__(self): - super().__init__() - self.name = "SSILoss" - - def forward(self, prediction, target, mask, interpolate=True, return_interpolated=False): - - if prediction.shape[-1] != target.shape[-1] and interpolate: - prediction = nn.functional.interpolate(prediction, target.shape[-2:], mode='bilinear', align_corners=True) - intr_input = prediction - else: - intr_input = prediction - - - prediction, target, mask = prediction.squeeze(), target.squeeze(), mask.squeeze() - assert prediction.shape == target.shape, f"Shape mismatch: Expected same shape but got {prediction.shape} and {target.shape}." - - scale, shift = compute_scale_and_shift(prediction, target, mask) - - scaled_prediction = scale.view(-1, 1, 1) * prediction + shift.view(-1, 1, 1) - - loss = nn.functional.l1_loss(scaled_prediction[mask], target[mask]) - if not return_interpolated: - return loss - return loss, intr_input - - - - -if __name__ == '__main__': - # Tests for DiscreteNLLLoss - celoss = DiscreteNLLLoss() - print(celoss(torch.rand(4, 64, 26, 32)*10, torch.rand(4, 1, 26, 32)*10, )) - - d = torch.Tensor([6.59, 3.8, 10.0]) - print(celoss.dequantize_depth(celoss.quantize_depth(d))) diff --git a/spaces/cymic/Waifu_Diffusion_Webui/javascript/textualInversion.js b/spaces/cymic/Waifu_Diffusion_Webui/javascript/textualInversion.js deleted file mode 100644 index 53e0ec9612ecdb7b493751b03c8d44820ee84ee7..0000000000000000000000000000000000000000 --- a/spaces/cymic/Waifu_Diffusion_Webui/javascript/textualInversion.js +++ /dev/null @@ -1,8 +0,0 @@ - - -function start_training_textual_inversion(){ - requestProgress('ti') - gradioApp().querySelector('#ti_error').innerHTML='' - - return args_to_array(arguments) -} diff --git a/spaces/danterivers/music-generation-samples/tests/utils/__init__.py b/spaces/danterivers/music-generation-samples/tests/utils/__init__.py deleted file mode 100644 index 0952fcc3f57e34b3747962e9ebd6fc57aeea63fa..0000000000000000000000000000000000000000 --- a/spaces/danterivers/music-generation-samples/tests/utils/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. diff --git a/spaces/dawood17/SayBot_Enchancer/CodeFormer/basicsr/archs/codeformer_arch.py b/spaces/dawood17/SayBot_Enchancer/CodeFormer/basicsr/archs/codeformer_arch.py deleted file mode 100644 index 4d0d8027c8c4ffb26af6f4ba361514e93e320e8d..0000000000000000000000000000000000000000 --- a/spaces/dawood17/SayBot_Enchancer/CodeFormer/basicsr/archs/codeformer_arch.py +++ /dev/null @@ -1,276 +0,0 @@ -import math -import numpy as np -import torch -from torch import nn, Tensor -import torch.nn.functional as F -from typing import Optional, List - -from basicsr.archs.vqgan_arch import * -from basicsr.utils import get_root_logger -from basicsr.utils.registry import ARCH_REGISTRY - -def calc_mean_std(feat, eps=1e-5): - """Calculate mean and std for adaptive_instance_normalization. - - Args: - feat (Tensor): 4D tensor. - eps (float): A small value added to the variance to avoid - divide-by-zero. Default: 1e-5. - """ - size = feat.size() - assert len(size) == 4, 'The input feature should be 4D tensor.' - b, c = size[:2] - feat_var = feat.view(b, c, -1).var(dim=2) + eps - feat_std = feat_var.sqrt().view(b, c, 1, 1) - feat_mean = feat.view(b, c, -1).mean(dim=2).view(b, c, 1, 1) - return feat_mean, feat_std - - -def adaptive_instance_normalization(content_feat, style_feat): - """Adaptive instance normalization. - - Adjust the reference features to have the similar color and illuminations - as those in the degradate features. - - Args: - content_feat (Tensor): The reference feature. - style_feat (Tensor): The degradate features. - """ - size = content_feat.size() - style_mean, style_std = calc_mean_std(style_feat) - content_mean, content_std = calc_mean_std(content_feat) - normalized_feat = (content_feat - content_mean.expand(size)) / content_std.expand(size) - return normalized_feat * style_std.expand(size) + style_mean.expand(size) - - -class PositionEmbeddingSine(nn.Module): - """ - This is a more standard version of the position embedding, very similar to the one - used by the Attention is all you need paper, generalized to work on images. - """ - - def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None): - super().__init__() - self.num_pos_feats = num_pos_feats - self.temperature = temperature - self.normalize = normalize - if scale is not None and normalize is False: - raise ValueError("normalize should be True if scale is passed") - if scale is None: - scale = 2 * math.pi - self.scale = scale - - def forward(self, x, mask=None): - if mask is None: - mask = torch.zeros((x.size(0), x.size(2), x.size(3)), device=x.device, dtype=torch.bool) - not_mask = ~mask - y_embed = not_mask.cumsum(1, dtype=torch.float32) - x_embed = not_mask.cumsum(2, dtype=torch.float32) - if self.normalize: - eps = 1e-6 - y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale - x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale - - dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) - dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats) - - pos_x = x_embed[:, :, :, None] / dim_t - pos_y = y_embed[:, :, :, None] / dim_t - pos_x = torch.stack( - (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4 - ).flatten(3) - pos_y = torch.stack( - (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4 - ).flatten(3) - pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) - return pos - -def _get_activation_fn(activation): - """Return an activation function given a string""" - if activation == "relu": - return F.relu - if activation == "gelu": - return F.gelu - if activation == "glu": - return F.glu - raise RuntimeError(F"activation should be relu/gelu, not {activation}.") - - -class TransformerSALayer(nn.Module): - def __init__(self, embed_dim, nhead=8, dim_mlp=2048, dropout=0.0, activation="gelu"): - super().__init__() - self.self_attn = nn.MultiheadAttention(embed_dim, nhead, dropout=dropout) - # Implementation of Feedforward model - MLP - self.linear1 = nn.Linear(embed_dim, dim_mlp) - self.dropout = nn.Dropout(dropout) - self.linear2 = nn.Linear(dim_mlp, embed_dim) - - self.norm1 = nn.LayerNorm(embed_dim) - self.norm2 = nn.LayerNorm(embed_dim) - self.dropout1 = nn.Dropout(dropout) - self.dropout2 = nn.Dropout(dropout) - - self.activation = _get_activation_fn(activation) - - def with_pos_embed(self, tensor, pos: Optional[Tensor]): - return tensor if pos is None else tensor + pos - - def forward(self, tgt, - tgt_mask: Optional[Tensor] = None, - tgt_key_padding_mask: Optional[Tensor] = None, - query_pos: Optional[Tensor] = None): - - # self attention - tgt2 = self.norm1(tgt) - q = k = self.with_pos_embed(tgt2, query_pos) - tgt2 = self.self_attn(q, k, value=tgt2, attn_mask=tgt_mask, - key_padding_mask=tgt_key_padding_mask)[0] - tgt = tgt + self.dropout1(tgt2) - - # ffn - tgt2 = self.norm2(tgt) - tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2)))) - tgt = tgt + self.dropout2(tgt2) - return tgt - -class Fuse_sft_block(nn.Module): - def __init__(self, in_ch, out_ch): - super().__init__() - self.encode_enc = ResBlock(2*in_ch, out_ch) - - self.scale = nn.Sequential( - nn.Conv2d(in_ch, out_ch, kernel_size=3, padding=1), - nn.LeakyReLU(0.2, True), - nn.Conv2d(out_ch, out_ch, kernel_size=3, padding=1)) - - self.shift = nn.Sequential( - nn.Conv2d(in_ch, out_ch, kernel_size=3, padding=1), - nn.LeakyReLU(0.2, True), - nn.Conv2d(out_ch, out_ch, kernel_size=3, padding=1)) - - def forward(self, enc_feat, dec_feat, w=1): - enc_feat = self.encode_enc(torch.cat([enc_feat, dec_feat], dim=1)) - scale = self.scale(enc_feat) - shift = self.shift(enc_feat) - residual = w * (dec_feat * scale + shift) - out = dec_feat + residual - return out - - -@ARCH_REGISTRY.register() -class CodeFormer(VQAutoEncoder): - def __init__(self, dim_embd=512, n_head=8, n_layers=9, - codebook_size=1024, latent_size=256, - connect_list=['32', '64', '128', '256'], - fix_modules=['quantize','generator']): - super(CodeFormer, self).__init__(512, 64, [1, 2, 2, 4, 4, 8], 'nearest',2, [16], codebook_size) - - if fix_modules is not None: - for module in fix_modules: - for param in getattr(self, module).parameters(): - param.requires_grad = False - - self.connect_list = connect_list - self.n_layers = n_layers - self.dim_embd = dim_embd - self.dim_mlp = dim_embd*2 - - self.position_emb = nn.Parameter(torch.zeros(latent_size, self.dim_embd)) - self.feat_emb = nn.Linear(256, self.dim_embd) - - # transformer - self.ft_layers = nn.Sequential(*[TransformerSALayer(embed_dim=dim_embd, nhead=n_head, dim_mlp=self.dim_mlp, dropout=0.0) - for _ in range(self.n_layers)]) - - # logits_predict head - self.idx_pred_layer = nn.Sequential( - nn.LayerNorm(dim_embd), - nn.Linear(dim_embd, codebook_size, bias=False)) - - self.channels = { - '16': 512, - '32': 256, - '64': 256, - '128': 128, - '256': 128, - '512': 64, - } - - # after second residual block for > 16, before attn layer for ==16 - self.fuse_encoder_block = {'512':2, '256':5, '128':8, '64':11, '32':14, '16':18} - # after first residual block for > 16, before attn layer for ==16 - self.fuse_generator_block = {'16':6, '32': 9, '64':12, '128':15, '256':18, '512':21} - - # fuse_convs_dict - self.fuse_convs_dict = nn.ModuleDict() - for f_size in self.connect_list: - in_ch = self.channels[f_size] - self.fuse_convs_dict[f_size] = Fuse_sft_block(in_ch, in_ch) - - def _init_weights(self, module): - if isinstance(module, (nn.Linear, nn.Embedding)): - module.weight.data.normal_(mean=0.0, std=0.02) - if isinstance(module, nn.Linear) and module.bias is not None: - module.bias.data.zero_() - elif isinstance(module, nn.LayerNorm): - module.bias.data.zero_() - module.weight.data.fill_(1.0) - - def forward(self, x, w=0, detach_16=True, code_only=False, adain=False): - # ################### Encoder ##################### - enc_feat_dict = {} - out_list = [self.fuse_encoder_block[f_size] for f_size in self.connect_list] - for i, block in enumerate(self.encoder.blocks): - x = block(x) - if i in out_list: - enc_feat_dict[str(x.shape[-1])] = x.clone() - - lq_feat = x - # ################# Transformer ################### - # quant_feat, codebook_loss, quant_stats = self.quantize(lq_feat) - pos_emb = self.position_emb.unsqueeze(1).repeat(1,x.shape[0],1) - # BCHW -> BC(HW) -> (HW)BC - feat_emb = self.feat_emb(lq_feat.flatten(2).permute(2,0,1)) - query_emb = feat_emb - # Transformer encoder - for layer in self.ft_layers: - query_emb = layer(query_emb, query_pos=pos_emb) - - # output logits - logits = self.idx_pred_layer(query_emb) # (hw)bn - logits = logits.permute(1,0,2) # (hw)bn -> b(hw)n - - if code_only: # for training stage II - # logits doesn't need softmax before cross_entropy loss - return logits, lq_feat - - # ################# Quantization ################### - # if self.training: - # quant_feat = torch.einsum('btn,nc->btc', [soft_one_hot, self.quantize.embedding.weight]) - # # b(hw)c -> bc(hw) -> bchw - # quant_feat = quant_feat.permute(0,2,1).view(lq_feat.shape) - # ------------ - soft_one_hot = F.softmax(logits, dim=2) - _, top_idx = torch.topk(soft_one_hot, 1, dim=2) - quant_feat = self.quantize.get_codebook_feat(top_idx, shape=[x.shape[0],16,16,256]) - # preserve gradients - # quant_feat = lq_feat + (quant_feat - lq_feat).detach() - - if detach_16: - quant_feat = quant_feat.detach() # for training stage III - if adain: - quant_feat = adaptive_instance_normalization(quant_feat, lq_feat) - - # ################## Generator #################### - x = quant_feat - fuse_list = [self.fuse_generator_block[f_size] for f_size in self.connect_list] - - for i, block in enumerate(self.generator.blocks): - x = block(x) - if i in fuse_list: # fuse after i-th block - f_size = str(x.shape[-1]) - if w>0: - x = self.fuse_convs_dict[f_size](enc_feat_dict[f_size].detach(), x, w) - out = x - # logits doesn't need softmax before cross_entropy loss - return out, logits, lq_feat \ No newline at end of file diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/altair/vegalite/schema.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/altair/vegalite/schema.py deleted file mode 100644 index e94c3d1991e96da81efe13cfe06214166afe80d1..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/altair/vegalite/schema.py +++ /dev/null @@ -1,3 +0,0 @@ -"""Altair schema wrappers""" -# ruff: noqa -from .v5.schema import * diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/gradio/templates/cdn/assets/index-9b163635.css b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/gradio/templates/cdn/assets/index-9b163635.css deleted file mode 100644 index ad395da34fbff0a0e7293319eed085f120d9047b..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/gradio/templates/cdn/assets/index-9b163635.css +++ /dev/null @@ -1 +0,0 @@ -.gradio-container-3-40-1,.gradio-container-3-40-1 *,.gradio-container-3-40-1 :before,.gradio-container-3-40-1 :after{box-sizing:border-box;border-width:0;border-style:solid}.gradio-container-3-40-1 html{-webkit-text-size-adjust:100%;line-height:1.5;font-family:var(--font-sans);-moz-tab-size:4;tab-size:2}.gradio-container-3-40-1 body{margin:0;line-height:inherit}.gradio-container-3-40-1 hr{border-top-width:1px;height:0;color:inherit}.gradio-container-3-40-1 abbr:where([title]){text-decoration:underline dotted}.gradio-container-3-40-1 h1,.gradio-container-3-40-1 h2,.gradio-container-3-40-1 h3,.gradio-container-3-40-1 h4,.gradio-container-3-40-1 h5,.gradio-container-3-40-1 h6{font-weight:inherit;font-size:inherit}.gradio-container-3-40-1 a{color:inherit;text-decoration:inherit}.gradio-container-3-40-1 b,.gradio-container-3-40-1 strong{font-weight:bolder}.gradio-container-3-40-1 code,.gradio-container-3-40-1 kbd,.gradio-container-3-40-1 samp,.gradio-container-3-40-1 pre{font-family:-var(--font-mono)}.gradio-container-3-40-1 small{font-size:80%}.gradio-container-3-40-1 sub,.gradio-container-3-40-1 sup{position:relative;vertical-align:baseline;font-size:75%;line-height:0}.gradio-container-3-40-1 sub{bottom:-.25em}.gradio-container-3-40-1 sup{top:-.5em}.gradio-container-3-40-1 table{border-color:inherit;border-collapse:collapse;text-indent:0}.gradio-container-3-40-1 button,.gradio-container-3-40-1 input,.gradio-container-3-40-1 optgroup,.gradio-container-3-40-1 select,.gradio-container-3-40-1 textarea{margin:0;padding:0;color:inherit;font-weight:inherit;font-size:100%;line-height:inherit;font-family:inherit}.gradio-container-3-40-1 button,.gradio-container-3-40-1 select{text-transform:none}.gradio-container-3-40-1 button,.gradio-container-3-40-1 [type=button],.gradio-container-3-40-1 [type=reset],.gradio-container-3-40-1 [type=submit]{-webkit-appearance:button;background-image:none;background-color:transparent}.gradio-container-3-40-1 :-moz-focusring{outline:auto}.gradio-container-3-40-1 :-moz-ui-invalid{box-shadow:none}.gradio-container-3-40-1 progress{vertical-align:baseline}.gradio-container-3-40-1 ::-webkit-inner-spin-button,.gradio-container-3-40-1 ::-webkit-outer-spin-button{height:auto}.gradio-container-3-40-1 [type=search]{-webkit-appearance:textfield;outline-offset:-2px}.gradio-container-3-40-1 ::-webkit-search-decoration{-webkit-appearance:none}.gradio-container-3-40-1 ::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}.gradio-container-3-40-1 summary{display:list-item}.gradio-container-3-40-1 blockquote,.gradio-container-3-40-1 dl,.gradio-container-3-40-1 dd,.gradio-container-3-40-1 h1,.gradio-container-3-40-1 h2,.gradio-container-3-40-1 h3,.gradio-container-3-40-1 h4,.gradio-container-3-40-1 h5,.gradio-container-3-40-1 h6,.gradio-container-3-40-1 hr,.gradio-container-3-40-1 figure,.gradio-container-3-40-1 p,.gradio-container-3-40-1 pre{margin:0}.gradio-container-3-40-1 fieldset{margin:0;padding:0}.gradio-container-3-40-1 legend{padding:0}.gradio-container-3-40-1 ol,.gradio-container-3-40-1 ul,.gradio-container-3-40-1 menu{margin:0;padding:0}.gradio-container-3-40-1 textarea{resize:vertical}.gradio-container-3-40-1 input::placeholder,.gradio-container-3-40-1 textarea::placeholder{opacity:1;color:--color-var(--color-grey-400)}.gradio-container-3-40-1 button,.gradio-container-3-40-1 [role=button]{cursor:pointer}.gradio-container-3-40-1 :disabled{cursor:default}.gradio-container-3-40-1 img,.gradio-container-3-40-1 svg,.gradio-container-3-40-1 video,.gradio-container-3-40-1 canvas,.gradio-container-3-40-1 audio,.gradio-container-3-40-1 iframe,.gradio-container-3-40-1 embed,.gradio-container-3-40-1 object{display:block;vertical-align:middle}.gradio-container-3-40-1 img,.gradio-container-3-40-1 video{max-width:100%;height:auto;margin:0}.gradio-container-3-40-1 [hidden]{display:none}.gradio-container-3-40-1 [type=text],.gradio-container-3-40-1 [type=email],.gradio-container-3-40-1 [type=url],.gradio-container-3-40-1 [type=password],.gradio-container-3-40-1 [type=number],.gradio-container-3-40-1 [type=date],.gradio-container-3-40-1 [type=datetime-local],.gradio-container-3-40-1 [type=month],.gradio-container-3-40-1 [type=search],.gradio-container-3-40-1 [type=tel],.gradio-container-3-40-1 [type=time],.gradio-container-3-40-1 [type=week],.gradio-container-3-40-1 [multiple],.gradio-container-3-40-1 textarea,.gradio-container-3-40-1 select{--tw-shadow: 0 0 #0000;appearance:none;border-width:1px;border-color:#6b7280;border-radius:0;background-color:#fff;padding:.5rem .75rem;font-size:1rem;line-height:1.5rem}.gradio-container-3-40-1 [type=checkbox],.gradio-container-3-40-1 [type=radio]{color-adjust:exact;display:inline-block;flex-shrink:0;vertical-align:middle;appearance:none;border-width:1px;border-color:#6b7280;background-origin:border-box;background-color:#fff;padding:0;width:1rem;height:1rem;color:#2563eb;user-select:none}.gradio-container-3-40-1 [type=checkbox]:checked{background-image:url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M12.207 4.793a1 1 0 010 1.414l-5 5a1 1 0 01-1.414 0l-2-2a1 1 0 011.414-1.414L6.5 9.086l4.293-4.293a1 1 0 011.414 0z'/%3e%3c/svg%3e")}.gradio-container-3-40-1 [type=radio]:checked{background-image:url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3ccircle cx='8' cy='8' r='3'/%3e%3c/svg%3e")}.gradio-container-3-40-1 select{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");background-position:right .5rem center;background-size:1.5em 1.5em;background-repeat:no-repeat;padding-right:2.5rem}.gradio-container-3-40-1 [type=checkbox]:checked,.gradio-container-3-40-1 [type=radio]:checked{background-position:center;background-size:100% 100%;background-repeat:no-repeat}.gradio-container-3-40-1 [type=checkbox]:checked:hover,.gradio-container-3-40-1 [type=checkbox]:checked:focus,.gradio-container-3-40-1 [type=radio]:checked:hover,.gradio-container-3-40-1 [type=radio]:checked:focus{border-color:transparent}.gradio-container-3-40-1 [type=checkbox]:focus-visible,.gradio-container-3-40-1 [type=radio]:focus-visible{outline:none}.gradio-container-3-40-1 .scroll-hide{-ms-overflow-style:none;scrollbar-width:none}.gradio-container-3-40-1 .sr-only{clip:rect(0,0,0,0);position:absolute;margin:-1px;border-width:0;padding:0;width:1px;height:1px;overflow:hidden;white-space:nowrap}.gradio-container-3-40-1 .scroll-hide::-webkit-scrollbar{display:none}.gradio-container-3-40-1{-webkit-text-size-adjust:100%;line-height:1.5;font-family:var(--font);-moz-tab-size:4;tab-size:4}.gradio-container-3-40-1 .cropper-container{position:relative;-ms-touch-action:none;touch-action:none;font-size:0;line-height:0;direction:ltr;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.gradio-container-3-40-1 .cropper-container img{display:block;image-orientation:0deg;width:100%;min-width:0!important;max-width:none!important;height:100%;min-height:0!important;max-height:none!important}.gradio-container-3-40-1 .cropper-wrap-box,.gradio-container-3-40-1 .cropper-canvas,.gradio-container-3-40-1 .cropper-drag-box,.gradio-container-3-40-1 .cropper-crop-box,.gradio-container-3-40-1 .cropper-modal{position:absolute;inset:0}.gradio-container-3-40-1 .cropper-wrap-box,.gradio-container-3-40-1 .cropper-canvas{overflow:hidden}.gradio-container-3-40-1 .cropper-drag-box{opacity:0;background-color:#fff}.gradio-container-3-40-1 .cropper-modal{opacity:.5;background-color:#000}.gradio-container-3-40-1 .cropper-view-box{display:block;outline:1px solid #39f;outline-color:#3399ffbf;width:100%;height:100%;overflow:hidden}.gradio-container-3-40-1 .cropper-dashed{display:block;position:absolute;opacity:.5;border:0 dashed #eee}.gradio-container-3-40-1 .cropper-dashed.dashed-h{top:calc(100% / 3);left:0;border-top-width:1px;border-bottom-width:1px;width:100%;height:calc(100% / 3)}.gradio-container-3-40-1 .cropper-dashed.dashed-v{top:0;left:calc(100% / 3);border-right-width:1px;border-left-width:1px;width:calc(100% / 3);height:100%}.gradio-container-3-40-1 .cropper-center{display:block;position:absolute;top:50%;left:50%;opacity:.75;width:0;height:0}.gradio-container-3-40-1 .cropper-center:before,.gradio-container-3-40-1 .cropper-center:after{display:block;position:absolute;background-color:#eee;content:" "}.gradio-container-3-40-1 .cropper-center:before{top:0;left:-3px;width:7px;height:1px}.gradio-container-3-40-1 .cropper-center:after{top:-3px;left:0;width:1px;height:7px}.gradio-container-3-40-1 .cropper-face,.gradio-container-3-40-1 .cropper-line,.gradio-container-3-40-1 .cropper-point{display:block;position:absolute;opacity:.1;width:100%;height:100%}.gradio-container-3-40-1 .cropper-face{top:0;left:0;background-color:#fff}.gradio-container-3-40-1 .cropper-line{background-color:#39f}.gradio-container-3-40-1 .cropper-line.line-e{top:0;right:-3px;cursor:ew-resize;width:5px}.gradio-container-3-40-1 .cropper-line.line-n{top:-3px;left:0;cursor:ns-resize;height:5px}.gradio-container-3-40-1 .cropper-line.line-w{top:0;left:-3px;cursor:ew-resize;width:5px}.gradio-container-3-40-1 .cropper-line.line-s{bottom:-3px;left:0;cursor:ns-resize;height:5px}.gradio-container-3-40-1 .cropper-point{opacity:.75;background-color:#39f;width:5px;height:5px}.gradio-container-3-40-1 .cropper-point.point-e{top:50%;right:-3px;cursor:ew-resize;margin-top:-3px}.gradio-container-3-40-1 .cropper-point.point-n{top:-3px;left:50%;cursor:ns-resize;margin-left:-3px}.gradio-container-3-40-1 .cropper-point.point-w{top:50%;left:-3px;cursor:ew-resize;margin-top:-3px}.gradio-container-3-40-1 .cropper-point.point-s{bottom:-3px;left:50%;cursor:s-resize;margin-left:-3px}.gradio-container-3-40-1 .cropper-point.point-ne{top:-3px;right:-3px;cursor:nesw-resize}.gradio-container-3-40-1 .cropper-point.point-nw{top:-3px;left:-3px;cursor:nwse-resize}.gradio-container-3-40-1 .cropper-point.point-sw{bottom:-3px;left:-3px;cursor:nesw-resize}.gradio-container-3-40-1 .cropper-point.point-se{right:-3px;bottom:-3px;opacity:1;cursor:nwse-resize;width:20px;height:20px}@media (min-width: 768px){.gradio-container-3-40-1 .cropper-point.point-se{width:15px;height:15px}}@media (min-width: 992px){.gradio-container-3-40-1 .cropper-point.point-se{width:10px;height:10px}}@media (min-width: 1200px){.gradio-container-3-40-1 .cropper-point.point-se{opacity:.75;width:5px;height:5px}}.gradio-container-3-40-1 .cropper-point.point-se:before{display:block;position:absolute;right:-50%;bottom:-50%;opacity:0;background-color:#39f;width:200%;height:200%;content:" "}.gradio-container-3-40-1 .cropper-invisible{opacity:0}.gradio-container-3-40-1 .cropper-bg{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC)}.gradio-container-3-40-1 .cropper-hide{display:block;position:absolute;width:0;height:0}.gradio-container-3-40-1 .cropper-hidden{display:none!important}.gradio-container-3-40-1 .cropper-move{cursor:move}.gradio-container-3-40-1 .cropper-crop{cursor:crosshair}.gradio-container-3-40-1 .cropper-disabled .cropper-drag-box,.gradio-container-3-40-1 .cropper-disabled .cropper-face,.gradio-container-3-40-1 .cropper-disabled .cropper-line,.gradio-container-3-40-1 .cropper-disabled .cropper-point{cursor:not-allowed}:root{--scale-0: 1rem;--scale-1: 1.125rem;--scale-2: 1.25rem;--scale-3: 1.5rem;--scale-4: 1.875rem;--scale-5: 2.25rem;--scale-6: 3rem;--scale-7: 3.75rem;--scale-8: 4.5rem;--scale-9: 6rem;--scale-10: 8rem;--scale-000: .75rem;--scale-00: .875rem;--scale-fluid-0: clamp(.875rem, .8rem + .25vw, 1rem);--scale-fluid-1: clamp(1rem, .925rem + .25vw, 1.125rem);--scale-fluid-2: clamp(1.125rem, 1.05rem + .25vw, 1.25rem);--scale-fluid-3: clamp(1.8125rem, 2rem + -.625vw, 1.5rem);--scale-fluid-4: clamp(1.5rem, 1.275rem + .75vw, 1.875rem);--scale-fluid-5: clamp(1.875rem, 1.65rem + .75vw, 2.25rem);--scale-fluid-6: clamp(2.25rem, 1.8rem + 1.5vw, 3rem);--scale-fluid-7: clamp(3rem, 2.55rem + 1.5vw, 3.75rem);--scale-fluid-8: clamp(3.75rem, 3.3rem + 1.5vw, 4.5rem);--scale-fluid-9: clamp(4.5rem, 3.6rem + 3vw, 6rem);--scale-fluid-10: clamp(6rem, 4.8rem + 4vw, 8rem);--scale-fluid-000: clamp(.625rem, .55rem + .25vw, .75rem);--scale-fluid-00: clamp(.75rem, .675rem + .25vw, .875rem);--font-sans: Source Sans Pro, 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-serif: Georgia, Cambria, "Times New Roman", Times, serif;--font-mono: IBM Plex Mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--weight-light: 300;--weight-regular: 400;--weight-medium: 500;--weight-semibold: 600;--weight-bold: 700;--weight-extrabold: 800;--weight-black: 900;--line-none: 1;--line-xs: 1.125;--line-sm: 1.4;--line-md: 1.5;--line-lg: 1.625;--line-xl: 2;--letter-xs: -.05em;--letter-sm: -.025em;--letter-none: 0em;--letter-lg: .025em;--letter-xl: .05em;--prose-xs: 45ch;--prose-sm: 55ch;--prose-md: 65ch;--prose-lg: 75ch;--prose-xl: 85ch;--size-1: 4px;--size-2: 8px;--size-3: 12px;--size-4: 16px;--size-5: 20px;--size-6: 24px;--size-7: 28px;--size-8: 32px;--size-9: 36px;--size-10: 40px;--size-11: 44px;--size-12: 48px;--size-14: 56px;--size-16: 64px;--size-20: 80px;--size-24: 96px;--size-28: 112px;--size-32: 128px;--size-36: 144px;--size-40: 160px;--size-44: 176px;--size-48: 192px;--size-52: 208px;--size-56: 224px;--size-60: 240px;--size-64: 256px;--size-72: 288px;--size-80: 320px;--size-96: 384px;--size-px: 1px;--size-full: 100%;--size-screen: 100vw;--size-min: min-content;--size-max: max-content;--size-0-5: 2px;--size-1-5: 6px;--size-2-5: 10px;--size-screen-h: 100vh;--width-xs: 480px;--width-sm: 640px;--width-md: 768px;--width-lg: 1024px;--width-xl: 1280px;--ratio-square: 1/1;--ratio-portrait: 3/4;--ratio-landscape: 4/3;--ratio-tall: 2/3;--ratio-wide: 3/2;--ratio-widescreen: 16/9;--ratio-golden: 1.618/1;--radius-100: 100%;--radius-xs: 2px;--radius-sm: 4px;--radius-md: 6px;--radius-lg: 8px;--radius-xl: 12px;--radius-full: 9999px;--radius-2xl: 16px;--radius-3xl: 22px;--blur-xs: blur(4px);--blur-sm: blur(8px);--blur-md: blur(16px);--blur-lg: blur(24px);--blur-xl: blur(40px);--layer-1: 10;--layer-2: 20;--layer-3: 30;--layer-4: 40;--layer-5: 50;--layer-below: -1;--layer-top: 2147483647;--shadow-xs: 0 1px 3px 0 rgba(0, 0, 0, .1), 0 1px 2px 0 rgba(0, 0, 0, .06);--shadow-sm: 0 4px 6px -2px rgba(0, 0, 0, .1), 0 2px 4px -2px rgba(0, 0, 0, .06);--shadow-md: 0 12px 16px -4px rgba(0, 0, 0, .1), 0 4px 6px -2px rgba(0, 0, 0, .05);--shadow-lg: 0 20px 24px -4px rgba(0, 0, 0, .1), 0 8px 8px -4px rgba(0, 0, 0, .04);--shadow-xl: 0 24px 48px -12px rgba(0, 0, 0, .25);--ease-in-sine: cubic-bezier(.47, 0, .745, .715);--ease-out-sine: cubic-bezier(.39, .575, .565, 1);--ease-in-out-sine: cubic-bezier(.445, .05, .55, .95);--ease-in-quad: cubic-bezier(.55, .085, .68, .53);--ease-out-quad: cubic-bezier(.25, .46, .45, .94);--ease-in-out-quad: cubic-bezier(.455, .03, .515, .955);--ease-in-cubic: cubic-bezier(.55, .055, .675, .19);--ease-out-cubic: cubic-bezier(.215, .61, .355, 1);--ease-in-out-cubic: cubic-bezier(.645, .045, .355, 1);--ease-in-quart: cubic-bezier(.895, .03, .685, .22);--ease-out-quart: cubic-bezier(.165, .84, .44, 1);--ease-in-out-quart: cubic-bezier(.77, 0, .175, 1);--ease-in-quint: cubic-bezier(.755, .05, .855, .06);--ease-out-quint: cubic-bezier(.23, 1, .32, 1);--ease-in-out-quint: cubic-bezier(.86, 0, .07, 1);--ease-in-expo: cubic-bezier(.95, .05, .795, .035);--ease-out-expo: cubic-bezier(.19, 1, .22, 1);--ease-in-out-expo: cubic-bezier(1, 0, 0, 1);--ease-in-circ: cubic-bezier(.6, .04, .98, .335);--ease-out-circ: cubic-bezier(.075, .82, .165, 1);--ease-in-out-circ: cubic-bezier(.785, .135, .15, .86);--ease-in-back: cubic-bezier(.6, -.28, .735, .045);--ease-out-back: cubic-bezier(.175, .885, .32, 1.275);--ease-in-out-back: cubic-bezier(.68, -.55, .265, 1.55);--easing-standard: cubic-bezier(.4, 0, .2, 1);--easing-accelerate: cubic-bezier(.4, 0, 1, 1);--easing-decelerate: cubic-bezier(0, 0, .2, 1);--elevation-1: 0 1px 2px 0 rgba(0, 0, 0, .05);--elevation-2: 0 1px 3px 0 rgba(0, 0, 0, .1), 0 1px 2px 0 rgba(0, 0, 0, .06);--elevation-3: 0 4px 6px -2px rgba(0, 0, 0, .1), 0 2px 4px -2px rgba(0, 0, 0, .06);--elevation-4: 0 12px 16px -4px rgba(0, 0, 0, .1), 0 4px 6px -2px rgba(0, 0, 0, .05);--elevation-5: 0 20px 24px -4px rgba(0, 0, 0, .1), 0 8px 8px -4px rgba(0, 0, 0, .04);--elevation-6: 0 24px 48px -12px rgba(0, 0, 0, .25);--elevation-7: 0 32px 64px -12px rgba(0, 0, 0, .2);--color-grey-50: #f9fafb;--color-grey-100: #f3f4f6;--color-grey-200: #e5e7eb;--color-grey-300: #d1d5db;--color-grey-400: #9ca3af;--color-grey-500: #6b7280;--color-grey-600: #4b5563;--color-grey-700: #374151;--color-grey-800: #1f2937;--color-grey-900: #111827;--color-black: #14141b;--color-grey: #6b7280;--color-red-300: #fca5a5;--color-red-500: #ef4444;--color-red-700: #b91c1c;--color-red: #ef4444;--color-green-300: #86efac;--color-green-500: #22c55e;--color-green-700: #15803d;--color-green: #22c55e;--color-blue-300: #93c5fd;--color-blue-500: #0ea5e9;--color-blue-700: #1d4ed8;--color-blue: #0ea5e9;--color-pink-300: #fbb6ce;--color-pink-500: #ed64a6;--color-pink-700: #d53f8c;--color-pink: var(--color-pink-500);--color-purple-300: #b794f4;--color-purple-500: #805ad5;--color-purple-700: #6b46c1;--color-purple: var(--color-purple-500);--color-teal-300: #81e6d9;--color-teal-500: #38b2ac;--color-teal-700: #2c7a7b;--color-teal: var(--color-teal-500);--color-yellow-300: #fde047;--color-yellow-500: #eab308;--color-yellow-700: #a16207;--color-yellow: #eab308;--color-orange-300: #ffb066;--color-orange-500: #ff7c00;--color-orange-700: #ce6400;--color-orange: #f97316;--color-brown-300: #a1887f;--color-brown-500: #795548;--color-brown-700: #5d4037;--color-brown: var(--color-brown-500);--color-blue-10: #fafcff;--color-blue-50: #eff6ff;--color-blue-100: #dbeafe;--color-blue-200: #bfdbfe;--color-blue-400: #60a5fa;--color-blue-600: #2563eb;--color-blue-800: #1e40af;--color-blue-900: #1e3a8a;--color-blue-950: #1c366b;--color-grey-10: #fdfdfe;--color-grey-950: #0b0f19;--color-red-10: #fffbfb;--color-red-50: #fef2f2;--color-red-100: #fee2e2;--color-red-200: #fecaca;--color-red-400: #f87171;--color-red-600: #dc2626;--color-red-800: #991b1b;--color-red-900: #7f1d1d;--color-red-950: #63171a;--color-green-10: #f9fefc;--color-green-50: #ecfdf5;--color-green-100: #d1fae5;--color-green-200: #bbf7d0;--color-green-400: #4ade80;--color-green-600: #16a34a;--color-green-800: #166534;--color-green-900: #14532d;--color-green-950: #134227;--color-orange-10: #fffbf6;--color-orange-50: #fff2e5;--color-orange-100: #ffe5cc;--color-orange-200: #ffd8b4;--color-orange-400: #ff9633;--color-orange-600: #ee7400;--color-orange-800: #a45000;--color-orange-900: #5c2d00;--color-orange-950: #3c1f00;--color-yellow-10: #fffef8;--color-yellow-50: #fffbeb;--color-yellow-100: #fff9c2;--color-yellow-200: #fef08a;--color-yellow-400: #facc15;--color-yellow-600: #ca8a04;--color-yellow-800: #854d0e;--color-yellow-900: #713f12;--color-yellow-950: #633112;--grid-2: repeat(2, minmax(0, 1fr));--grid-3: repeat(3, minmax(0, 1fr));--grid-4: repeat(4, minmax(0, 1fr));--grid-5: repeat(5, minmax(0, 1fr));--grid-6: repeat(6, minmax(0, 1fr));--grid-7: repeat(7, minmax(0, 1fr));--grid-8: repeat(8, minmax(0, 1fr));--grid-9: repeat(9, minmax(0, 1fr));--grid-10: repeat(10, minmax(0, 1fr));--grid-11: repeat(11, minmax(0, 1fr));--grid-12: repeat(12, minmax(0, 1fr));--grid-page-width: var(--width-xl);--grid-page-gutter: 5vw;--grid-page-main: 2 / 3;--grid-page: minmax(var(--grid-page-gutter), 1fr) minmax(0, var(--grid-page-width)) minmax(var(--grid-page-gutter), 1fr)}.gradio-container-3-40-1 .prose{font-weight:var(--prose-text-weight);font-size:var(--text-md)}.gradio-container-3-40-1 .prose *{color:var(--body-text-color)}.gradio-container-3-40-1 .prose p{margin-bottom:var(--spacing-sm);line-height:var(--line-lg)}.gradio-container-3-40-1 .prose h1,.gradio-container-3-40-1 .prose h2,.gradio-container-3-40-1 .prose h3,.gradio-container-3-40-1 .prose h4,.gradio-container-3-40-1 .prose h5{margin:var(--spacing-xxl) 0 var(--spacing-lg);font-weight:var(--prose-header-text-weight);line-height:1.3;color:var(--body-text-color)}.gradio-container-3-40-1 .prose>*:first-child{margin-top:0}.gradio-container-3-40-1 .prose h1{margin-top:0;font-size:var(--text-xxl)}.gradio-container-3-40-1 .prose h2{font-size:var(--text-xl)}.gradio-container-3-40-1 .prose h3{font-size:var(--text-lg)}.gradio-container-3-40-1 .prose h4{font-size:1.1em}.gradio-container-3-40-1 .prose h5{font-size:1.05em}.gradio-container-3-40-1 .prose ul{list-style:circle inside}.gradio-container-3-40-1 .prose ol{list-style:decimal inside}.gradio-container-3-40-1 .prose ul>p,.gradio-container-3-40-1 .prose li>p{display:inline-block}.gradio-container-3-40-1 .prose ol,.gradio-container-3-40-1 .prose ul{margin-top:0;padding-left:0}.gradio-container-3-40-1 .prose ul ul,.gradio-container-3-40-1 .prose ul ol,.gradio-container-3-40-1 .prose ol ol,.gradio-container-3-40-1 .prose ol ul{margin:.5em 0 .5em 3em;font-size:90%}.gradio-container-3-40-1 .prose li{margin-bottom:.5em}.gradio-container-3-40-1 .prose code{border:1px solid var(--border-color-primary);border-radius:var(--radius-sm);background:var(--background-fill-secondary);padding:1px 3px;font-size:85%;white-space:nowrap}.gradio-container-3-40-1 .prose pre>code{display:block;padding:.5em .7em;white-space:pre}.gradio-container-3-40-1 .prose th,.gradio-container-3-40-1 .prose td{border-bottom:1px solid #e1e1e1;padding:12px 15px;text-align:left}.gradio-container-3-40-1 .prose th:first-child,.gradio-container-3-40-1 .prose td:first-child{padding-left:0}.gradio-container-3-40-1 .prose th:last-child,.gradio-container-3-40-1 .prose td:last-child{padding-right:0}.gradio-container-3-40-1 .prose button,.gradio-container-3-40-1 .prose .button,.gradio-container-3-40-1 .prose input,.gradio-container-3-40-1 .prose textarea,.gradio-container-3-40-1 .prose select,.gradio-container-3-40-1 .prose fieldset{margin-bottom:var(--spacing-sm)}.gradio-container-3-40-1 .prose pre,.gradio-container-3-40-1 .prose blockquote,.gradio-container-3-40-1 .prose dl,.gradio-container-3-40-1 .prose figure,.gradio-container-3-40-1 .prose table,.gradio-container-3-40-1 .prose p,.gradio-container-3-40-1 .prose ul,.gradio-container-3-40-1 .prose ol,.gradio-container-3-40-1 .prose form{margin-bottom:var(--spacing-md)}.gradio-container-3-40-1 .prose a{color:var(--link-text-color);text-decoration:underline}.gradio-container-3-40-1 .prose a:visited{color:var(--link-text-color-visited)}.gradio-container-3-40-1 .prose a:hover{color:var(--link-text-color-hover)}.gradio-container-3-40-1 .prose a:active{color:var(--link-text-color-active)}.gradio-container-3-40-1 .prose hr{margin-top:3em;margin-bottom:3.5em;border-width:0;border-top:1px solid #e1e1e1}.gradio-container-3-40-1 .prose blockquote{margin:var(--size-6) 0!important;border-left:5px solid var(--border-color-primary);padding-left:var(--size-2)}.gradio-container-3-40-1 .prose :last-child{margin-bottom:0!important}.gradio-container-3-40-1{display:flex;position:relative;flex-direction:column;padding:0;min-height:1px;overflow:hidden;color:var(--button-secondary-text-color)}.embed-container.svelte-1kyws56.svelte-1kyws56{margin:var(--size-4) 0px;border:1px solid var(--button-secondary-border-color);border-radius:var(--embed-radius)}.with-info.svelte-1kyws56.svelte-1kyws56{padding-bottom:var(--size-7)}.embed-container.svelte-1kyws56>.main.svelte-1kyws56{padding:var(--size-4)}.app.svelte-1kyws56>.main.svelte-1kyws56{display:flex;flex-grow:1;flex-direction:column}.app.svelte-1kyws56.svelte-1kyws56{position:relative;margin:auto;padding:var(--size-4);width:100%;height:100%}@media (min-width: 640px){.app.svelte-1kyws56.svelte-1kyws56{max-width:640px}}@media (min-width: 768px){.app.svelte-1kyws56.svelte-1kyws56{max-width:768px}}@media (min-width: 1024px){.app.svelte-1kyws56.svelte-1kyws56{max-width:1024px}}@media (min-width: 1280px){.app.svelte-1kyws56.svelte-1kyws56{max-width:1280px}}@media (min-width: 1536px){.app.svelte-1kyws56.svelte-1kyws56{max-width:1536px}}.info.svelte-1kyws56.svelte-1kyws56{display:flex;position:absolute;bottom:0;justify-content:flex-start;border-top:1px solid var(--button-secondary-border-color);padding:var(--size-1) var(--size-5);width:100%;color:var(--body-text-color-subdued);font-size:var(--text-md);white-space:nowrap}.info.svelte-1kyws56>span.svelte-1kyws56{word-wrap:break-word;-break:keep-all;display:block;word-break:keep-all}.info.svelte-1kyws56>span.svelte-1kyws56:nth-child(1){margin-right:4px;min-width:0px;max-width:max-content;overflow:hidden;color:var(--body-text-color);text-overflow:ellipsis;white-space:nowrap}.info.svelte-1kyws56>span.svelte-1kyws56:nth-child(2){margin-right:3px}.info.svelte-1kyws56>span.svelte-1kyws56:nth-child(2),.info.svelte-1kyws56>span.svelte-1kyws56:nth-child(3){width:max-content}.info.svelte-1kyws56>span.svelte-1kyws56:nth-child(3){align-self:flex-end;justify-self:flex-end;margin-left:auto;text-align:right}.info.svelte-1kyws56>span.svelte-1kyws56:nth-child(1){flex-shrink:9}.hidden-title.svelte-1kyws56.svelte-1kyws56{position:absolute;left:var(--size-5);opacity:0;background:var(--button-secondary-background-fill);padding-right:4px}.info.svelte-1kyws56 a.svelte-1kyws56{color:var(--body-text-color)}.title.svelte-1kyws56.svelte-1kyws56{font-size:var(--text-sm);font-family:var(--font-mono)}.hf.svelte-1kyws56.svelte-1kyws56{margin-left:5px}.space-logo.svelte-1kyws56 img.svelte-1kyws56{display:inline-block;margin-bottom:4px;height:12px}a.svelte-1kyws56.svelte-1kyws56:hover{text-decoration:underline}svg.svelte-zyxd38.svelte-zyxd38{width:var(--size-20);height:var(--size-20)}svg.svelte-zyxd38 path.svelte-zyxd38{fill:var(--loader-color)}div.svelte-zyxd38.svelte-zyxd38{z-index:var(--layer-2)}.margin.svelte-zyxd38.svelte-zyxd38{margin:var(--size-4)}.wrap.svelte-zlszon.svelte-zlszon{display:flex;flex-direction:column;justify-content:center;align-items:center;z-index:var(--layer-5);transition:opacity .1s ease-in-out;border-radius:var(--block-radius);background:var(--block-background-fill);padding:0 var(--size-6);max-height:var(--size-screen-h);overflow:hidden;pointer-events:none}.wrap.center.svelte-zlszon.svelte-zlszon{top:0;right:0;left:0}.wrap.default.svelte-zlszon.svelte-zlszon{inset:0}.hide.svelte-zlszon.svelte-zlszon{opacity:0;pointer-events:none}.generating.svelte-zlszon.svelte-zlszon{animation:svelte-zlszon-pulse 2s cubic-bezier(.4,0,.6,1) infinite;border:2px solid var(--color-accent);background:transparent}.translucent.svelte-zlszon.svelte-zlszon{background:none}@keyframes svelte-zlszon-pulse{0%,to{opacity:1}50%{opacity:.5}}.loading.svelte-zlszon.svelte-zlszon{z-index:var(--layer-2);color:var(--body-text-color)}.eta-bar.svelte-zlszon.svelte-zlszon{position:absolute;inset:0;transform-origin:left;opacity:.8;z-index:var(--layer-1);transition:10ms;background:var(--background-fill-secondary)}.progress-bar-wrap.svelte-zlszon.svelte-zlszon{border:1px solid var(--border-color-primary);background:var(--background-fill-primary);width:55.5%;height:var(--size-4)}.progress-bar.svelte-zlszon.svelte-zlszon{transform-origin:left;background-color:var(--loader-color);width:var(--size-full);height:var(--size-full)}.progress-level.svelte-zlszon.svelte-zlszon{display:flex;flex-direction:column;align-items:center;gap:1;z-index:var(--layer-2);width:var(--size-full)}.progress-level-inner.svelte-zlszon.svelte-zlszon{margin:var(--size-2) auto;color:var(--body-text-color);font-size:var(--text-sm);font-family:var(--font-mono)}.meta-text.svelte-zlszon.svelte-zlszon{position:absolute;top:0;right:0;z-index:var(--layer-2);padding:var(--size-1) var(--size-2);font-size:var(--text-sm);font-family:var(--font-mono)}.meta-text-center.svelte-zlszon.svelte-zlszon{display:flex;position:absolute;top:0;right:0;justify-content:center;align-items:center;transform:translateY(var(--size-6));z-index:var(--layer-2);padding:var(--size-1) var(--size-2);font-size:var(--text-sm);font-family:var(--font-mono);text-align:center}.error.svelte-zlszon.svelte-zlszon{box-shadow:var(--shadow-drop);border:solid 1px var(--error-border-color);border-radius:var(--radius-full);background:var(--error-background-fill);padding-right:var(--size-4);padding-left:var(--size-4);color:var(--error-text-color);font-weight:var(--weight-semibold);font-size:var(--text-lg);line-height:var(--line-lg);font-family:var(--font)}.minimal.svelte-zlszon .progress-text.svelte-zlszon{background:var(--block-background-fill)}.dropdown-arrow.svelte-p5edak{fill:var(--body-text-color);margin-right:var(--size-2);width:var(--size-5)}.toast-body.svelte-z3l7qj{display:flex;position:relative;right:0;left:0;align-items:center;margin:var(--size-6) var(--size-4);margin:auto;border-radius:var(--container-radius);overflow:hidden;pointer-events:auto}.toast-body.error.svelte-z3l7qj{border:1px solid var(--color-red-700);background:var(--color-red-50)}.dark .toast-body.error.svelte-z3l7qj{border:1px solid var(--color-red-500);background-color:var(--color-grey-950)}.toast-body.warning.svelte-z3l7qj{border:1px solid var(--color-yellow-700);background:var(--color-yellow-50)}.dark .toast-body.warning.svelte-z3l7qj{border:1px solid var(--color-yellow-500);background-color:var(--color-grey-950)}.toast-body.info.svelte-z3l7qj{border:1px solid var(--color-grey-700);background:var(--color-grey-50)}.dark .toast-body.info.svelte-z3l7qj{border:1px solid var(--color-grey-500);background-color:var(--color-grey-950)}.toast-title.svelte-z3l7qj{display:flex;align-items:center;font-weight:var(--weight-bold);font-size:var(--text-lg);line-height:var(--line-sm);text-transform:capitalize}.toast-title.error.svelte-z3l7qj{color:var(--color-red-700)}.dark .toast-title.error.svelte-z3l7qj{color:var(--color-red-50)}.toast-title.warning.svelte-z3l7qj{color:var(--color-yellow-700)}.dark .toast-title.warning.svelte-z3l7qj{color:var(--color-yellow-50)}.toast-title.info.svelte-z3l7qj{color:var(--color-grey-700)}.dark .toast-title.info.svelte-z3l7qj{color:var(--color-grey-50)}.toast-close.svelte-z3l7qj{margin:0 var(--size-3);border-radius:var(--size-3);padding:0px var(--size-1-5);font-size:var(--size-5);line-height:var(--size-5)}.toast-close.error.svelte-z3l7qj{color:var(--color-red-700)}.dark .toast-close.error.svelte-z3l7qj{color:var(--color-red-500)}.toast-close.warning.svelte-z3l7qj{color:var(--color-yellow-700)}.dark .toast-close.warning.svelte-z3l7qj{color:var(--color-yellow-500)}.toast-close.info.svelte-z3l7qj{color:var(--color-grey-700)}.dark .toast-close.info.svelte-z3l7qj{color:var(--color-grey-500)}.toast-text.svelte-z3l7qj{font-size:var(--text-lg)}.toast-text.error.svelte-z3l7qj{color:var(--color-red-700)}.dark .toast-text.error.svelte-z3l7qj{color:var(--color-red-50)}.toast-text.warning.svelte-z3l7qj{color:var(--color-yellow-700)}.dark .toast-text.warning.svelte-z3l7qj{color:var(--color-yellow-50)}.toast-text.info.svelte-z3l7qj{color:var(--color-grey-700)}.dark .toast-text.info.svelte-z3l7qj{color:var(--color-grey-50)}.toast-details.svelte-z3l7qj{margin:var(--size-3) var(--size-3) var(--size-3) 0;width:100%}.toast-icon.svelte-z3l7qj{display:flex;position:absolute;position:relative;flex-shrink:0;justify-content:center;align-items:center;margin:var(--size-2);border-radius:var(--radius-full);padding:var(--size-1);padding-left:calc(var(--size-1) - 1px);width:35px;height:35px}.toast-icon.error.svelte-z3l7qj{color:var(--color-red-700)}.dark .toast-icon.error.svelte-z3l7qj{color:var(--color-red-500)}.toast-icon.warning.svelte-z3l7qj{color:var(--color-yellow-700)}.dark .toast-icon.warning.svelte-z3l7qj{color:var(--color-yellow-500)}.toast-icon.info.svelte-z3l7qj{color:var(--color-grey-700)}.dark .toast-icon.info.svelte-z3l7qj{color:var(--color-grey-500)}@keyframes svelte-z3l7qj-countdown{0%{transform:scaleX(1)}to{transform:scaleX(0)}}.timer.svelte-z3l7qj{position:absolute;bottom:0;left:0;transform-origin:0 0;animation:svelte-z3l7qj-countdown 10s linear forwards;width:100%;height:var(--size-1)}.timer.error.svelte-z3l7qj{background:var(--color-red-700)}.dark .timer.error.svelte-z3l7qj{background:var(--color-red-500)}.timer.warning.svelte-z3l7qj{background:var(--color-yellow-700)}.dark .timer.warning.svelte-z3l7qj{background:var(--color-yellow-500)}.timer.info.svelte-z3l7qj{background:var(--color-grey-700)}.dark .timer.info.svelte-z3l7qj{background:var(--color-grey-500)}.toast-wrap.svelte-pu0yf1{display:flex;position:fixed;top:var(--size-4);right:var(--size-4);flex-direction:column;align-items:end;gap:var(--size-2);z-index:var(--layer-top);width:calc(100% - var(--size-8))}@media (min-width: 640px){.toast-wrap.svelte-pu0yf1{width:calc(var(--size-96) + var(--size-10))}}.error.svelte-y6l4b.svelte-y6l4b{position:relative;padding:var(--size-4);color:var(--body-text-color);text-align:center}.error.svelte-y6l4b>.svelte-y6l4b{margin-top:var(--size-4)}a.svelte-y6l4b.svelte-y6l4b{color:var(--link-text-color)}a.svelte-y6l4b.svelte-y6l4b:hover{color:var(--link-text-color-hover);text-decoration:underline}a.svelte-y6l4b.svelte-y6l4b:visited{color:var(--link-text-color-visited)}a.svelte-y6l4b.svelte-y6l4b:active{color:var(--link-text-color-active)} diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/huggingface_hub/community.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/huggingface_hub/community.py deleted file mode 100644 index cadad72591a9b98f17813b986bbfd53077311181..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/huggingface_hub/community.py +++ /dev/null @@ -1,354 +0,0 @@ -""" -Data structures to interact with Discussions and Pull Requests on the Hub. - -See [the Discussions and Pull Requests guide](https://huggingface.co/docs/hub/repositories-pull-requests-discussions) -for more information on Pull Requests, Discussions, and the community tab. -""" -from dataclasses import dataclass -from datetime import datetime -from typing import List, Optional - -from .constants import REPO_TYPE_MODEL -from .utils import parse_datetime -from .utils._typing import Literal - - -DiscussionStatus = Literal["open", "closed", "merged", "draft"] - - -@dataclass -class Discussion: - """ - A Discussion or Pull Request on the Hub. - - This dataclass is not intended to be instantiated directly. - - Attributes: - title (`str`): - The title of the Discussion / Pull Request - status (`str`): - The status of the Discussion / Pull Request. - It must be one of: - * `"open"` - * `"closed"` - * `"merged"` (only for Pull Requests ) - * `"draft"` (only for Pull Requests ) - num (`int`): - The number of the Discussion / Pull Request. - repo_id (`str`): - The id (`"{namespace}/{repo_name}"`) of the repo on which - the Discussion / Pull Request was open. - repo_type (`str`): - The type of the repo on which the Discussion / Pull Request was open. - Possible values are: `"model"`, `"dataset"`, `"space"`. - author (`str`): - The username of the Discussion / Pull Request author. - Can be `"deleted"` if the user has been deleted since. - is_pull_request (`bool`): - Whether or not this is a Pull Request. - created_at (`datetime`): - The `datetime` of creation of the Discussion / Pull Request. - endpoint (`str`): - Endpoint of the Hub. Default is https://huggingface.co. - git_reference (`str`, *optional*): - (property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise. - url (`str`): - (property) URL of the discussion on the Hub. - """ - - title: str - status: DiscussionStatus - num: int - repo_id: str - repo_type: str - author: str - is_pull_request: bool - created_at: datetime - endpoint: str - - @property - def git_reference(self) -> Optional[str]: - """ - If this is a Pull Request , returns the git reference to which changes can be pushed. - Returns `None` otherwise. - """ - if self.is_pull_request: - return f"refs/pr/{self.num}" - return None - - @property - def url(self) -> str: - """Returns the URL of the discussion on the Hub.""" - if self.repo_type is None or self.repo_type == REPO_TYPE_MODEL: - return f"{self.endpoint}/{self.repo_id}/discussions/{self.num}" - return f"{self.endpoint}/{self.repo_type}s/{self.repo_id}/discussions/{self.num}" - - -@dataclass -class DiscussionWithDetails(Discussion): - """ - Subclass of [`Discussion`]. - - Attributes: - title (`str`): - The title of the Discussion / Pull Request - status (`str`): - The status of the Discussion / Pull Request. - It can be one of: - * `"open"` - * `"closed"` - * `"merged"` (only for Pull Requests ) - * `"draft"` (only for Pull Requests ) - num (`int`): - The number of the Discussion / Pull Request. - repo_id (`str`): - The id (`"{namespace}/{repo_name}"`) of the repo on which - the Discussion / Pull Request was open. - repo_type (`str`): - The type of the repo on which the Discussion / Pull Request was open. - Possible values are: `"model"`, `"dataset"`, `"space"`. - author (`str`): - The username of the Discussion / Pull Request author. - Can be `"deleted"` if the user has been deleted since. - is_pull_request (`bool`): - Whether or not this is a Pull Request. - created_at (`datetime`): - The `datetime` of creation of the Discussion / Pull Request. - events (`list` of [`DiscussionEvent`]) - The list of [`DiscussionEvents`] in this Discussion or Pull Request. - conflicting_files (`list` of `str`, *optional*): - A list of conflicting files if this is a Pull Request. - `None` if `self.is_pull_request` is `False`. - target_branch (`str`, *optional*): - The branch into which changes are to be merged if this is a - Pull Request . `None` if `self.is_pull_request` is `False`. - merge_commit_oid (`str`, *optional*): - If this is a merged Pull Request , this is set to the OID / SHA of - the merge commit, `None` otherwise. - diff (`str`, *optional*): - The git diff if this is a Pull Request , `None` otherwise. - endpoint (`str`): - Endpoint of the Hub. Default is https://huggingface.co. - git_reference (`str`, *optional*): - (property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise. - url (`str`): - (property) URL of the discussion on the Hub. - """ - - events: List["DiscussionEvent"] - conflicting_files: Optional[List[str]] - target_branch: Optional[str] - merge_commit_oid: Optional[str] - diff: Optional[str] - - -@dataclass -class DiscussionEvent: - """ - An event in a Discussion or Pull Request. - - Use concrete classes: - * [`DiscussionComment`] - * [`DiscussionStatusChange`] - * [`DiscussionCommit`] - * [`DiscussionTitleChange`] - - Attributes: - id (`str`): - The ID of the event. An hexadecimal string. - type (`str`): - The type of the event. - created_at (`datetime`): - A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) - object holding the creation timestamp for the event. - author (`str`): - The username of the Discussion / Pull Request author. - Can be `"deleted"` if the user has been deleted since. - """ - - id: str - type: str - created_at: datetime - author: str - - _event: dict - """Stores the original event data, in case we need to access it later.""" - - -@dataclass -class DiscussionComment(DiscussionEvent): - """A comment in a Discussion / Pull Request. - - Subclass of [`DiscussionEvent`]. - - - Attributes: - id (`str`): - The ID of the event. An hexadecimal string. - type (`str`): - The type of the event. - created_at (`datetime`): - A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) - object holding the creation timestamp for the event. - author (`str`): - The username of the Discussion / Pull Request author. - Can be `"deleted"` if the user has been deleted since. - content (`str`): - The raw markdown content of the comment. Mentions, links and images are not rendered. - edited (`bool`): - Whether or not this comment has been edited. - hidden (`bool`): - Whether or not this comment has been hidden. - """ - - content: str - edited: bool - hidden: bool - - @property - def rendered(self) -> str: - """The rendered comment, as a HTML string""" - return self._event["data"]["latest"]["html"] - - @property - def last_edited_at(self) -> datetime: - """The last edit time, as a `datetime` object.""" - return parse_datetime(self._event["data"]["latest"]["updatedAt"]) - - @property - def last_edited_by(self) -> str: - """The last edit time, as a `datetime` object.""" - return self._event["data"]["latest"].get("author", {}).get("name", "deleted") - - @property - def edit_history(self) -> List[dict]: - """The edit history of the comment""" - return self._event["data"]["history"] - - @property - def number_of_edits(self) -> int: - return len(self.edit_history) - - -@dataclass -class DiscussionStatusChange(DiscussionEvent): - """A change of status in a Discussion / Pull Request. - - Subclass of [`DiscussionEvent`]. - - Attributes: - id (`str`): - The ID of the event. An hexadecimal string. - type (`str`): - The type of the event. - created_at (`datetime`): - A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) - object holding the creation timestamp for the event. - author (`str`): - The username of the Discussion / Pull Request author. - Can be `"deleted"` if the user has been deleted since. - new_status (`str`): - The status of the Discussion / Pull Request after the change. - It can be one of: - * `"open"` - * `"closed"` - * `"merged"` (only for Pull Requests ) - """ - - new_status: str - - -@dataclass -class DiscussionCommit(DiscussionEvent): - """A commit in a Pull Request. - - Subclass of [`DiscussionEvent`]. - - Attributes: - id (`str`): - The ID of the event. An hexadecimal string. - type (`str`): - The type of the event. - created_at (`datetime`): - A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) - object holding the creation timestamp for the event. - author (`str`): - The username of the Discussion / Pull Request author. - Can be `"deleted"` if the user has been deleted since. - summary (`str`): - The summary of the commit. - oid (`str`): - The OID / SHA of the commit, as a hexadecimal string. - """ - - summary: str - oid: str - - -@dataclass -class DiscussionTitleChange(DiscussionEvent): - """A rename event in a Discussion / Pull Request. - - Subclass of [`DiscussionEvent`]. - - Attributes: - id (`str`): - The ID of the event. An hexadecimal string. - type (`str`): - The type of the event. - created_at (`datetime`): - A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) - object holding the creation timestamp for the event. - author (`str`): - The username of the Discussion / Pull Request author. - Can be `"deleted"` if the user has been deleted since. - old_title (`str`): - The previous title for the Discussion / Pull Request. - new_title (`str`): - The new title. - """ - - old_title: str - new_title: str - - -def deserialize_event(event: dict) -> DiscussionEvent: - """Instantiates a [`DiscussionEvent`] from a dict""" - event_id: str = event["id"] - event_type: str = event["type"] - created_at = parse_datetime(event["createdAt"]) - - common_args = dict( - id=event_id, - type=event_type, - created_at=created_at, - author=event.get("author", {}).get("name", "deleted"), - _event=event, - ) - - if event_type == "comment": - return DiscussionComment( - **common_args, - edited=event["data"]["edited"], - hidden=event["data"]["hidden"], - content=event["data"]["latest"]["raw"], - ) - if event_type == "status-change": - return DiscussionStatusChange( - **common_args, - new_status=event["data"]["status"], - ) - if event_type == "commit": - return DiscussionCommit( - **common_args, - summary=event["data"]["subject"], - oid=event["data"]["oid"], - ) - if event_type == "title-change": - return DiscussionTitleChange( - **common_args, - old_title=event["data"]["from"], - new_title=event["data"]["to"], - ) - - return DiscussionEvent(**common_args) diff --git a/spaces/declare-lab/tango/diffusers/scripts/convert_diffusers_to_original_stable_diffusion.py b/spaces/declare-lab/tango/diffusers/scripts/convert_diffusers_to_original_stable_diffusion.py deleted file mode 100644 index 9da45211551e32acf34c883c1d6c5218a7bd6dd7..0000000000000000000000000000000000000000 --- a/spaces/declare-lab/tango/diffusers/scripts/convert_diffusers_to_original_stable_diffusion.py +++ /dev/null @@ -1,333 +0,0 @@ -# Script for converting a HF Diffusers saved pipeline to a Stable Diffusion checkpoint. -# *Only* converts the UNet, VAE, and Text Encoder. -# Does not convert optimizer state or any other thing. - -import argparse -import os.path as osp -import re - -import torch -from safetensors.torch import load_file, save_file - - -# =================# -# UNet Conversion # -# =================# - -unet_conversion_map = [ - # (stable-diffusion, HF Diffusers) - ("time_embed.0.weight", "time_embedding.linear_1.weight"), - ("time_embed.0.bias", "time_embedding.linear_1.bias"), - ("time_embed.2.weight", "time_embedding.linear_2.weight"), - ("time_embed.2.bias", "time_embedding.linear_2.bias"), - ("input_blocks.0.0.weight", "conv_in.weight"), - ("input_blocks.0.0.bias", "conv_in.bias"), - ("out.0.weight", "conv_norm_out.weight"), - ("out.0.bias", "conv_norm_out.bias"), - ("out.2.weight", "conv_out.weight"), - ("out.2.bias", "conv_out.bias"), -] - -unet_conversion_map_resnet = [ - # (stable-diffusion, HF Diffusers) - ("in_layers.0", "norm1"), - ("in_layers.2", "conv1"), - ("out_layers.0", "norm2"), - ("out_layers.3", "conv2"), - ("emb_layers.1", "time_emb_proj"), - ("skip_connection", "conv_shortcut"), -] - -unet_conversion_map_layer = [] -# hardcoded number of downblocks and resnets/attentions... -# would need smarter logic for other networks. -for i in range(4): - # loop over downblocks/upblocks - - for j in range(2): - # loop over resnets/attentions for downblocks - hf_down_res_prefix = f"down_blocks.{i}.resnets.{j}." - sd_down_res_prefix = f"input_blocks.{3*i + j + 1}.0." - unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) - - if i < 3: - # no attention layers in down_blocks.3 - hf_down_atn_prefix = f"down_blocks.{i}.attentions.{j}." - sd_down_atn_prefix = f"input_blocks.{3*i + j + 1}.1." - unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) - - for j in range(3): - # loop over resnets/attentions for upblocks - hf_up_res_prefix = f"up_blocks.{i}.resnets.{j}." - sd_up_res_prefix = f"output_blocks.{3*i + j}.0." - unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) - - if i > 0: - # no attention layers in up_blocks.0 - hf_up_atn_prefix = f"up_blocks.{i}.attentions.{j}." - sd_up_atn_prefix = f"output_blocks.{3*i + j}.1." - unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) - - if i < 3: - # no downsample in down_blocks.3 - hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0.conv." - sd_downsample_prefix = f"input_blocks.{3*(i+1)}.0.op." - unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) - - # no upsample in up_blocks.3 - hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0." - sd_upsample_prefix = f"output_blocks.{3*i + 2}.{1 if i == 0 else 2}." - unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) - -hf_mid_atn_prefix = "mid_block.attentions.0." -sd_mid_atn_prefix = "middle_block.1." -unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) - -for j in range(2): - hf_mid_res_prefix = f"mid_block.resnets.{j}." - sd_mid_res_prefix = f"middle_block.{2*j}." - unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) - - -def convert_unet_state_dict(unet_state_dict): - # buyer beware: this is a *brittle* function, - # and correct output requires that all of these pieces interact in - # the exact order in which I have arranged them. - mapping = {k: k for k in unet_state_dict.keys()} - for sd_name, hf_name in unet_conversion_map: - mapping[hf_name] = sd_name - for k, v in mapping.items(): - if "resnets" in k: - for sd_part, hf_part in unet_conversion_map_resnet: - v = v.replace(hf_part, sd_part) - mapping[k] = v - for k, v in mapping.items(): - for sd_part, hf_part in unet_conversion_map_layer: - v = v.replace(hf_part, sd_part) - mapping[k] = v - new_state_dict = {v: unet_state_dict[k] for k, v in mapping.items()} - return new_state_dict - - -# ================# -# VAE Conversion # -# ================# - -vae_conversion_map = [ - # (stable-diffusion, HF Diffusers) - ("nin_shortcut", "conv_shortcut"), - ("norm_out", "conv_norm_out"), - ("mid.attn_1.", "mid_block.attentions.0."), -] - -for i in range(4): - # down_blocks have two resnets - for j in range(2): - hf_down_prefix = f"encoder.down_blocks.{i}.resnets.{j}." - sd_down_prefix = f"encoder.down.{i}.block.{j}." - vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) - - if i < 3: - hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0." - sd_downsample_prefix = f"down.{i}.downsample." - vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) - - hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0." - sd_upsample_prefix = f"up.{3-i}.upsample." - vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) - - # up_blocks have three resnets - # also, up blocks in hf are numbered in reverse from sd - for j in range(3): - hf_up_prefix = f"decoder.up_blocks.{i}.resnets.{j}." - sd_up_prefix = f"decoder.up.{3-i}.block.{j}." - vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) - -# this part accounts for mid blocks in both the encoder and the decoder -for i in range(2): - hf_mid_res_prefix = f"mid_block.resnets.{i}." - sd_mid_res_prefix = f"mid.block_{i+1}." - vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) - - -vae_conversion_map_attn = [ - # (stable-diffusion, HF Diffusers) - ("norm.", "group_norm."), - ("q.", "query."), - ("k.", "key."), - ("v.", "value."), - ("proj_out.", "proj_attn."), -] - - -def reshape_weight_for_sd(w): - # convert HF linear weights to SD conv2d weights - return w.reshape(*w.shape, 1, 1) - - -def convert_vae_state_dict(vae_state_dict): - mapping = {k: k for k in vae_state_dict.keys()} - for k, v in mapping.items(): - for sd_part, hf_part in vae_conversion_map: - v = v.replace(hf_part, sd_part) - mapping[k] = v - for k, v in mapping.items(): - if "attentions" in k: - for sd_part, hf_part in vae_conversion_map_attn: - v = v.replace(hf_part, sd_part) - mapping[k] = v - new_state_dict = {v: vae_state_dict[k] for k, v in mapping.items()} - weights_to_convert = ["q", "k", "v", "proj_out"] - for k, v in new_state_dict.items(): - for weight_name in weights_to_convert: - if f"mid.attn_1.{weight_name}.weight" in k: - print(f"Reshaping {k} for SD format") - new_state_dict[k] = reshape_weight_for_sd(v) - return new_state_dict - - -# =========================# -# Text Encoder Conversion # -# =========================# - - -textenc_conversion_lst = [ - # (stable-diffusion, HF Diffusers) - ("resblocks.", "text_model.encoder.layers."), - ("ln_1", "layer_norm1"), - ("ln_2", "layer_norm2"), - (".c_fc.", ".fc1."), - (".c_proj.", ".fc2."), - (".attn", ".self_attn"), - ("ln_final.", "transformer.text_model.final_layer_norm."), - ("token_embedding.weight", "transformer.text_model.embeddings.token_embedding.weight"), - ("positional_embedding", "transformer.text_model.embeddings.position_embedding.weight"), -] -protected = {re.escape(x[1]): x[0] for x in textenc_conversion_lst} -textenc_pattern = re.compile("|".join(protected.keys())) - -# Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp -code2idx = {"q": 0, "k": 1, "v": 2} - - -def convert_text_enc_state_dict_v20(text_enc_dict): - new_state_dict = {} - capture_qkv_weight = {} - capture_qkv_bias = {} - for k, v in text_enc_dict.items(): - if ( - k.endswith(".self_attn.q_proj.weight") - or k.endswith(".self_attn.k_proj.weight") - or k.endswith(".self_attn.v_proj.weight") - ): - k_pre = k[: -len(".q_proj.weight")] - k_code = k[-len("q_proj.weight")] - if k_pre not in capture_qkv_weight: - capture_qkv_weight[k_pre] = [None, None, None] - capture_qkv_weight[k_pre][code2idx[k_code]] = v - continue - - if ( - k.endswith(".self_attn.q_proj.bias") - or k.endswith(".self_attn.k_proj.bias") - or k.endswith(".self_attn.v_proj.bias") - ): - k_pre = k[: -len(".q_proj.bias")] - k_code = k[-len("q_proj.bias")] - if k_pre not in capture_qkv_bias: - capture_qkv_bias[k_pre] = [None, None, None] - capture_qkv_bias[k_pre][code2idx[k_code]] = v - continue - - relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k) - new_state_dict[relabelled_key] = v - - for k_pre, tensors in capture_qkv_weight.items(): - if None in tensors: - raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing") - relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre) - new_state_dict[relabelled_key + ".in_proj_weight"] = torch.cat(tensors) - - for k_pre, tensors in capture_qkv_bias.items(): - if None in tensors: - raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing") - relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre) - new_state_dict[relabelled_key + ".in_proj_bias"] = torch.cat(tensors) - - return new_state_dict - - -def convert_text_enc_state_dict(text_enc_dict): - return text_enc_dict - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - - parser.add_argument("--model_path", default=None, type=str, required=True, help="Path to the model to convert.") - parser.add_argument("--checkpoint_path", default=None, type=str, required=True, help="Path to the output model.") - parser.add_argument("--half", action="store_true", help="Save weights in half precision.") - parser.add_argument( - "--use_safetensors", action="store_true", help="Save weights use safetensors, default is ckpt." - ) - - args = parser.parse_args() - - assert args.model_path is not None, "Must provide a model path!" - - assert args.checkpoint_path is not None, "Must provide a checkpoint path!" - - # Path for safetensors - unet_path = osp.join(args.model_path, "unet", "diffusion_pytorch_model.safetensors") - vae_path = osp.join(args.model_path, "vae", "diffusion_pytorch_model.safetensors") - text_enc_path = osp.join(args.model_path, "text_encoder", "model.safetensors") - - # Load models from safetensors if it exists, if it doesn't pytorch - if osp.exists(unet_path): - unet_state_dict = load_file(unet_path, device="cpu") - else: - unet_path = osp.join(args.model_path, "unet", "diffusion_pytorch_model.bin") - unet_state_dict = torch.load(unet_path, map_location="cpu") - - if osp.exists(vae_path): - vae_state_dict = load_file(vae_path, device="cpu") - else: - vae_path = osp.join(args.model_path, "vae", "diffusion_pytorch_model.bin") - vae_state_dict = torch.load(vae_path, map_location="cpu") - - if osp.exists(text_enc_path): - text_enc_dict = load_file(text_enc_path, device="cpu") - else: - text_enc_path = osp.join(args.model_path, "text_encoder", "pytorch_model.bin") - text_enc_dict = torch.load(text_enc_path, map_location="cpu") - - # Convert the UNet model - unet_state_dict = convert_unet_state_dict(unet_state_dict) - unet_state_dict = {"model.diffusion_model." + k: v for k, v in unet_state_dict.items()} - - # Convert the VAE model - vae_state_dict = convert_vae_state_dict(vae_state_dict) - vae_state_dict = {"first_stage_model." + k: v for k, v in vae_state_dict.items()} - - # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper - is_v20_model = "text_model.encoder.layers.22.layer_norm2.bias" in text_enc_dict - - if is_v20_model: - # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm - text_enc_dict = {"transformer." + k: v for k, v in text_enc_dict.items()} - text_enc_dict = convert_text_enc_state_dict_v20(text_enc_dict) - text_enc_dict = {"cond_stage_model.model." + k: v for k, v in text_enc_dict.items()} - else: - text_enc_dict = convert_text_enc_state_dict(text_enc_dict) - text_enc_dict = {"cond_stage_model.transformer." + k: v for k, v in text_enc_dict.items()} - - # Put together new checkpoint - state_dict = {**unet_state_dict, **vae_state_dict, **text_enc_dict} - if args.half: - state_dict = {k: v.half() for k, v in state_dict.items()} - - if args.use_safetensors: - save_file(state_dict, args.checkpoint_path) - else: - state_dict = {"state_dict": state_dict} - torch.save(state_dict, args.checkpoint_path) diff --git a/spaces/declare-lab/tango/diffusers/scripts/convert_stable_diffusion_checkpoint_to_onnx.py b/spaces/declare-lab/tango/diffusers/scripts/convert_stable_diffusion_checkpoint_to_onnx.py deleted file mode 100644 index c527c8037b77d9fe9c10b0dabb505fb4a2657f0c..0000000000000000000000000000000000000000 --- a/spaces/declare-lab/tango/diffusers/scripts/convert_stable_diffusion_checkpoint_to_onnx.py +++ /dev/null @@ -1,265 +0,0 @@ -# Copyright 2023 The HuggingFace Team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import argparse -import os -import shutil -from pathlib import Path - -import onnx -import torch -from packaging import version -from torch.onnx import export - -from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline, StableDiffusionPipeline - - -is_torch_less_than_1_11 = version.parse(version.parse(torch.__version__).base_version) < version.parse("1.11") - - -def onnx_export( - model, - model_args: tuple, - output_path: Path, - ordered_input_names, - output_names, - dynamic_axes, - opset, - use_external_data_format=False, -): - output_path.parent.mkdir(parents=True, exist_ok=True) - # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, - # so we check the torch version for backwards compatibility - if is_torch_less_than_1_11: - export( - model, - model_args, - f=output_path.as_posix(), - input_names=ordered_input_names, - output_names=output_names, - dynamic_axes=dynamic_axes, - do_constant_folding=True, - use_external_data_format=use_external_data_format, - enable_onnx_checker=True, - opset_version=opset, - ) - else: - export( - model, - model_args, - f=output_path.as_posix(), - input_names=ordered_input_names, - output_names=output_names, - dynamic_axes=dynamic_axes, - do_constant_folding=True, - opset_version=opset, - ) - - -@torch.no_grad() -def convert_models(model_path: str, output_path: str, opset: int, fp16: bool = False): - dtype = torch.float16 if fp16 else torch.float32 - if fp16 and torch.cuda.is_available(): - device = "cuda" - elif fp16 and not torch.cuda.is_available(): - raise ValueError("`float16` model export is only supported on GPUs with CUDA") - else: - device = "cpu" - pipeline = StableDiffusionPipeline.from_pretrained(model_path, torch_dtype=dtype).to(device) - output_path = Path(output_path) - - # TEXT ENCODER - num_tokens = pipeline.text_encoder.config.max_position_embeddings - text_hidden_size = pipeline.text_encoder.config.hidden_size - text_input = pipeline.tokenizer( - "A sample prompt", - padding="max_length", - max_length=pipeline.tokenizer.model_max_length, - truncation=True, - return_tensors="pt", - ) - onnx_export( - pipeline.text_encoder, - # casting to torch.int32 until the CLIP fix is released: https://github.com/huggingface/transformers/pull/18515/files - model_args=(text_input.input_ids.to(device=device, dtype=torch.int32)), - output_path=output_path / "text_encoder" / "model.onnx", - ordered_input_names=["input_ids"], - output_names=["last_hidden_state", "pooler_output"], - dynamic_axes={ - "input_ids": {0: "batch", 1: "sequence"}, - }, - opset=opset, - ) - del pipeline.text_encoder - - # UNET - unet_in_channels = pipeline.unet.config.in_channels - unet_sample_size = pipeline.unet.config.sample_size - unet_path = output_path / "unet" / "model.onnx" - onnx_export( - pipeline.unet, - model_args=( - torch.randn(2, unet_in_channels, unet_sample_size, unet_sample_size).to(device=device, dtype=dtype), - torch.randn(2).to(device=device, dtype=dtype), - torch.randn(2, num_tokens, text_hidden_size).to(device=device, dtype=dtype), - False, - ), - output_path=unet_path, - ordered_input_names=["sample", "timestep", "encoder_hidden_states", "return_dict"], - output_names=["out_sample"], # has to be different from "sample" for correct tracing - dynamic_axes={ - "sample": {0: "batch", 1: "channels", 2: "height", 3: "width"}, - "timestep": {0: "batch"}, - "encoder_hidden_states": {0: "batch", 1: "sequence"}, - }, - opset=opset, - use_external_data_format=True, # UNet is > 2GB, so the weights need to be split - ) - unet_model_path = str(unet_path.absolute().as_posix()) - unet_dir = os.path.dirname(unet_model_path) - unet = onnx.load(unet_model_path) - # clean up existing tensor files - shutil.rmtree(unet_dir) - os.mkdir(unet_dir) - # collate external tensor files into one - onnx.save_model( - unet, - unet_model_path, - save_as_external_data=True, - all_tensors_to_one_file=True, - location="weights.pb", - convert_attribute=False, - ) - del pipeline.unet - - # VAE ENCODER - vae_encoder = pipeline.vae - vae_in_channels = vae_encoder.config.in_channels - vae_sample_size = vae_encoder.config.sample_size - # need to get the raw tensor output (sample) from the encoder - vae_encoder.forward = lambda sample, return_dict: vae_encoder.encode(sample, return_dict)[0].sample() - onnx_export( - vae_encoder, - model_args=( - torch.randn(1, vae_in_channels, vae_sample_size, vae_sample_size).to(device=device, dtype=dtype), - False, - ), - output_path=output_path / "vae_encoder" / "model.onnx", - ordered_input_names=["sample", "return_dict"], - output_names=["latent_sample"], - dynamic_axes={ - "sample": {0: "batch", 1: "channels", 2: "height", 3: "width"}, - }, - opset=opset, - ) - - # VAE DECODER - vae_decoder = pipeline.vae - vae_latent_channels = vae_decoder.config.latent_channels - vae_out_channels = vae_decoder.config.out_channels - # forward only through the decoder part - vae_decoder.forward = vae_encoder.decode - onnx_export( - vae_decoder, - model_args=( - torch.randn(1, vae_latent_channels, unet_sample_size, unet_sample_size).to(device=device, dtype=dtype), - False, - ), - output_path=output_path / "vae_decoder" / "model.onnx", - ordered_input_names=["latent_sample", "return_dict"], - output_names=["sample"], - dynamic_axes={ - "latent_sample": {0: "batch", 1: "channels", 2: "height", 3: "width"}, - }, - opset=opset, - ) - del pipeline.vae - - # SAFETY CHECKER - if pipeline.safety_checker is not None: - safety_checker = pipeline.safety_checker - clip_num_channels = safety_checker.config.vision_config.num_channels - clip_image_size = safety_checker.config.vision_config.image_size - safety_checker.forward = safety_checker.forward_onnx - onnx_export( - pipeline.safety_checker, - model_args=( - torch.randn( - 1, - clip_num_channels, - clip_image_size, - clip_image_size, - ).to(device=device, dtype=dtype), - torch.randn(1, vae_sample_size, vae_sample_size, vae_out_channels).to(device=device, dtype=dtype), - ), - output_path=output_path / "safety_checker" / "model.onnx", - ordered_input_names=["clip_input", "images"], - output_names=["out_images", "has_nsfw_concepts"], - dynamic_axes={ - "clip_input": {0: "batch", 1: "channels", 2: "height", 3: "width"}, - "images": {0: "batch", 1: "height", 2: "width", 3: "channels"}, - }, - opset=opset, - ) - del pipeline.safety_checker - safety_checker = OnnxRuntimeModel.from_pretrained(output_path / "safety_checker") - feature_extractor = pipeline.feature_extractor - else: - safety_checker = None - feature_extractor = None - - onnx_pipeline = OnnxStableDiffusionPipeline( - vae_encoder=OnnxRuntimeModel.from_pretrained(output_path / "vae_encoder"), - vae_decoder=OnnxRuntimeModel.from_pretrained(output_path / "vae_decoder"), - text_encoder=OnnxRuntimeModel.from_pretrained(output_path / "text_encoder"), - tokenizer=pipeline.tokenizer, - unet=OnnxRuntimeModel.from_pretrained(output_path / "unet"), - scheduler=pipeline.scheduler, - safety_checker=safety_checker, - feature_extractor=feature_extractor, - requires_safety_checker=safety_checker is not None, - ) - - onnx_pipeline.save_pretrained(output_path) - print("ONNX pipeline saved to", output_path) - - del pipeline - del onnx_pipeline - _ = OnnxStableDiffusionPipeline.from_pretrained(output_path, provider="CPUExecutionProvider") - print("ONNX pipeline is loadable") - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - - parser.add_argument( - "--model_path", - type=str, - required=True, - help="Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).", - ) - - parser.add_argument("--output_path", type=str, required=True, help="Path to the output model.") - - parser.add_argument( - "--opset", - default=14, - type=int, - help="The version of the ONNX operator set to use.", - ) - parser.add_argument("--fp16", action="store_true", default=False, help="Export the models in `float16` mode") - - args = parser.parse_args() - - convert_models(args.model_path, args.output_path, args.opset, args.fp16) diff --git a/spaces/declare-lab/tango/diffusers/tests/pipelines/stable_diffusion/test_onnx_stable_diffusion_inpaint_legacy.py b/spaces/declare-lab/tango/diffusers/tests/pipelines/stable_diffusion/test_onnx_stable_diffusion_inpaint_legacy.py deleted file mode 100644 index 235aa32f7338579210520c675b3776b830cbe3da..0000000000000000000000000000000000000000 --- a/spaces/declare-lab/tango/diffusers/tests/pipelines/stable_diffusion/test_onnx_stable_diffusion_inpaint_legacy.py +++ /dev/null @@ -1,97 +0,0 @@ -# coding=utf-8 -# Copyright 2023 HuggingFace Inc. -# -# 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 unittest - -import numpy as np - -from diffusers import OnnxStableDiffusionInpaintPipelineLegacy -from diffusers.utils.testing_utils import ( - is_onnx_available, - load_image, - load_numpy, - nightly, - require_onnxruntime, - require_torch_gpu, -) - - -if is_onnx_available(): - import onnxruntime as ort - - -@nightly -@require_onnxruntime -@require_torch_gpu -class StableDiffusionOnnxInpaintLegacyPipelineIntegrationTests(unittest.TestCase): - @property - def gpu_provider(self): - return ( - "CUDAExecutionProvider", - { - "gpu_mem_limit": "15000000000", # 15GB - "arena_extend_strategy": "kSameAsRequested", - }, - ) - - @property - def gpu_options(self): - options = ort.SessionOptions() - options.enable_mem_pattern = False - return options - - def test_inference(self): - init_image = load_image( - "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" - "/in_paint/overture-creations-5sI6fQgYIuo.png" - ) - mask_image = load_image( - "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" - "/in_paint/overture-creations-5sI6fQgYIuo_mask.png" - ) - expected_image = load_numpy( - "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" - "/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy" - ) - - # using the PNDM scheduler by default - pipe = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( - "CompVis/stable-diffusion-v1-4", - revision="onnx", - safety_checker=None, - feature_extractor=None, - provider=self.gpu_provider, - sess_options=self.gpu_options, - ) - pipe.set_progress_bar_config(disable=None) - - prompt = "A red cat sitting on a park bench" - - generator = np.random.RandomState(0) - output = pipe( - prompt=prompt, - image=init_image, - mask_image=mask_image, - strength=0.75, - guidance_scale=7.5, - num_inference_steps=15, - generator=generator, - output_type="np", - ) - - image = output.images[0] - - assert image.shape == (512, 512, 3) - assert np.abs(expected_image - image).max() < 1e-2 diff --git a/spaces/deepghs/anime_object_detection/eye.py b/spaces/deepghs/anime_object_detection/eye.py deleted file mode 100644 index 453110372429a4272f621bc6328d5cdb6ca8afad..0000000000000000000000000000000000000000 --- a/spaces/deepghs/anime_object_detection/eye.py +++ /dev/null @@ -1,50 +0,0 @@ -from functools import lru_cache -from typing import List, Tuple - -from huggingface_hub import hf_hub_download -from imgutils.data import ImageTyping, load_image, rgb_encode - -from onnx_ import _open_onnx_model -from plot import detection_visualize -from yolo_ import _image_preprocess, _data_postprocess - -_EYE_MODELS = [ - 'eye_detect_v1.0_s', - 'eye_detect_v1.0_n', - 'eye_detect_v0.8_s', - 'eye_detect_v0.7_s', - 'eye_detect_v0.6_s', - 'eye_detect_v0.5_s', - 'eye_detect_v0.4_s', - 'eye_detect_v0.3_s', - 'eye_detect_v0.2_s', -] -_DEFAULT_EYE_MODEL = _EYE_MODELS[0] - - -@lru_cache() -def _open_eye_detect_model(model_name): - return _open_onnx_model(hf_hub_download( - f'deepghs/anime_eye_detection', - f'{model_name}/model.onnx' - )) - - -_LABELS = ['eye'] - - -def detect_eyes(image: ImageTyping, model_name: str, max_infer_size=640, - conf_threshold: float = 0.3, iou_threshold: float = 0.3) \ - -> List[Tuple[Tuple[int, int, int, int], str, float]]: - image = load_image(image, mode='RGB') - new_image, old_size, new_size = _image_preprocess(image, max_infer_size) - - data = rgb_encode(new_image)[None, ...] - output, = _open_eye_detect_model(model_name).run(['output0'], {'images': data}) - return _data_postprocess(output[0], conf_threshold, iou_threshold, old_size, new_size, _LABELS) - - -def _gr_detect_eyes(image: ImageTyping, model_name: str, max_infer_size=640, - conf_threshold: float = 0.3, iou_threshold: float = 0.3): - ret = detect_eyes(image, model_name, max_infer_size, conf_threshold, iou_threshold) - return detection_visualize(image, ret, _LABELS) diff --git a/spaces/derful/Chatgpt-academic/toolbox.py b/spaces/derful/Chatgpt-academic/toolbox.py deleted file mode 100644 index 369bb099c0ed357923532f8889d454a748ab150f..0000000000000000000000000000000000000000 --- a/spaces/derful/Chatgpt-academic/toolbox.py +++ /dev/null @@ -1,220 +0,0 @@ -import markdown, mdtex2html, threading -from show_math import convert as convert_math -from functools import wraps - -def predict_no_ui_but_counting_down(api, i_say, i_say_show_user, chatbot, top_p, temperature, history=[], sys_prompt=''): - """ - 调用简单的predict_no_ui接口,但是依然保留了些许界面心跳功能,当对话太长时,会自动采用二分法截断 - """ - import time - try: from config_private import TIMEOUT_SECONDS, MAX_RETRY - except: from config import TIMEOUT_SECONDS, MAX_RETRY - from predict import predict_no_ui - # 多线程的时候,需要一个mutable结构在不同线程之间传递信息 - # list就是最简单的mutable结构,我们第一个位置放gpt输出,第二个位置传递报错信息 - mutable = [None, ''] - # multi-threading worker - def mt(i_say, history): - while True: - try: - mutable[0] = predict_no_ui(api, inputs=i_say, top_p=top_p, temperature=temperature, history=history, sys_prompt=sys_prompt) - break - except ConnectionAbortedError as e: - if len(history) > 0: - history = [his[len(his)//2:] for his in history if his is not None] - mutable[1] = 'Warning! History conversation is too long, cut into half. ' - else: - i_say = i_say[:len(i_say)//2] - mutable[1] = 'Warning! Input file is too long, cut into half. ' - except TimeoutError as e: - mutable[0] = '[Local Message] Failed with timeout.' - raise TimeoutError - # 创建新线程发出http请求 - thread_name = threading.Thread(target=mt, args=(i_say, history)); thread_name.start() - # 原来的线程则负责持续更新UI,实现一个超时倒计时,并等待新线程的任务完成 - cnt = 0 - while thread_name.is_alive(): - cnt += 1 - chatbot[-1] = (i_say_show_user, f"[Local Message] {mutable[1]}waiting gpt response {cnt}/{TIMEOUT_SECONDS*2*(MAX_RETRY+1)}"+''.join(['.']*(cnt%4))) - yield chatbot, history, '正常' - time.sleep(1) - # 把gpt的输出从mutable中取出来 - gpt_say = mutable[0] - if gpt_say=='[Local Message] Failed with timeout.': raise TimeoutError - return gpt_say - -def write_results_to_file(history, file_name=None): - """ - 将对话记录history以Markdown格式写入文件中。如果没有指定文件名,则使用当前时间生成文件名。 - """ - import os, time - if file_name is None: - # file_name = time.strftime("chatGPT分析报告%Y-%m-%d-%H-%M-%S", time.localtime()) + '.md' - file_name = 'chatGPT分析报告' + time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + '.md' - os.makedirs('./gpt_log/', exist_ok=True) - with open(f'./gpt_log/{file_name}', 'w', encoding = 'utf8') as f: - f.write('# chatGPT 分析报告\n') - for i, content in enumerate(history): - if i%2==0: f.write('## ') - f.write(content) - f.write('\n\n') - res = '以上材料已经被写入' + os.path.abspath(f'./gpt_log/{file_name}') - print(res) - return res - -def regular_txt_to_markdown(text): - """ - 将普通文本转换为Markdown格式的文本。 - """ - text = text.replace('\n', '\n\n') - text = text.replace('\n\n\n', '\n\n') - text = text.replace('\n\n\n', '\n\n') - return text - -def CatchException(f): - """ - 装饰器函数,捕捉函数f中的异常并封装到一个生成器中返回,并显示到聊天当中。 - """ - @wraps(f) - def decorated(api, txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT): - try: - yield from f(api, txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT) - except Exception as e: - import traceback - from check_proxy import check_proxy - try: from config_private import proxies - except: from config import proxies - tb_str = regular_txt_to_markdown(traceback.format_exc()) - chatbot[-1] = (chatbot[-1][0], f"[Local Message] 实验性函数调用出错: \n\n {tb_str} \n\n 当前代理可用性: \n\n {check_proxy(proxies)}") - yield chatbot, history, f'异常 {e}' - return decorated - -def report_execption(chatbot, history, a, b): - """ - 向chatbot中添加错误信息 - """ - chatbot.append((a, b)) - history.append(a); history.append(b) - -def text_divide_paragraph(text): - """ - 将文本按照段落分隔符分割开,生成带有段落标签的HTML代码。 - """ - if '```' in text: - # careful input - return text - else: - # wtf input - lines = text.split("\n") - for i, line in enumerate(lines): - lines[i] = "

    "+lines[i].replace(" ", " ")+"

    " - text = "\n".join(lines) - return text - -def markdown_convertion(txt): - """ - 将Markdown格式的文本转换为HTML格式。如果包含数学公式,则先将公式转换为HTML格式。 - """ - if ('$' in txt) and ('```' not in txt): - return markdown.markdown(txt,extensions=['fenced_code','tables']) + '

    ' + \ - markdown.markdown(convert_math(txt, splitParagraphs=False),extensions=['fenced_code','tables']) - else: - return markdown.markdown(txt,extensions=['fenced_code','tables']) - - -def format_io(self, y): - """ - 将输入和输出解析为HTML格式。将y中最后一项的输入部分段落化,并将输出部分的Markdown和数学公式转换为HTML格式。 - """ - if y is None or y == []: return [] - i_ask, gpt_reply = y[-1] - i_ask = text_divide_paragraph(i_ask) # 输入部分太自由,预处理一波 - y[-1] = ( - None if i_ask is None else markdown.markdown(i_ask, extensions=['fenced_code','tables']), - None if gpt_reply is None else markdown_convertion(gpt_reply) - ) - return y - - -def find_free_port(): - """ - 返回当前系统中可用的未使用端口。 - """ - import socket - from contextlib import closing - with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: - s.bind(('', 0)) - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - return s.getsockname()[1] - - -def extract_archive(file_path, dest_dir): - import zipfile - import tarfile - import os - # Get the file extension of the input file - file_extension = os.path.splitext(file_path)[1] - - # Extract the archive based on its extension - if file_extension == '.zip': - with zipfile.ZipFile(file_path, 'r') as zipobj: - zipobj.extractall(path=dest_dir) - print("Successfully extracted zip archive to {}".format(dest_dir)) - - elif file_extension in ['.tar', '.gz', '.bz2']: - with tarfile.open(file_path, 'r:*') as tarobj: - tarobj.extractall(path=dest_dir) - print("Successfully extracted tar archive to {}".format(dest_dir)) - else: - return - -def find_recent_files(directory): - """ - me: find files that is created with in one minutes under a directory with python, write a function - gpt: here it is! - """ - import os - import time - current_time = time.time() - one_minute_ago = current_time - 60 - recent_files = [] - - for filename in os.listdir(directory): - file_path = os.path.join(directory, filename) - if file_path.endswith('.log'): continue - created_time = os.path.getctime(file_path) - if created_time >= one_minute_ago: - if os.path.isdir(file_path): continue - recent_files.append(file_path) - - return recent_files - - -def on_file_uploaded(files, chatbot, txt): - if len(files) == 0: return chatbot, txt - import shutil, os, time, glob - from toolbox import extract_archive - try: shutil.rmtree('./private_upload/') - except: pass - time_tag = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) - os.makedirs(f'private_upload/{time_tag}', exist_ok=True) - for file in files: - file_origin_name = os.path.basename(file.orig_name) - shutil.copy(file.name, f'private_upload/{time_tag}/{file_origin_name}') - extract_archive(f'private_upload/{time_tag}/{file_origin_name}', - dest_dir=f'private_upload/{time_tag}/{file_origin_name}.extract') - moved_files = [fp for fp in glob.glob('private_upload/**/*', recursive=True)] - txt = f'private_upload/{time_tag}' - moved_files_str = '\t\n\n'.join(moved_files) - chatbot.append(['我上传了文件,请查收', - f'[Local Message] 收到以下文件: \n\n{moved_files_str}\n\n调用路径参数已自动修正到: \n\n{txt}\n\n现在您点击任意实验功能时,以上文件将被作为输入参数']) - return chatbot, txt - - -def on_report_generated(files, chatbot): - from toolbox import find_recent_files - report_files = find_recent_files('gpt_log') - if len(report_files) == 0: return report_files, chatbot - # files.extend(report_files) - chatbot.append(['汇总报告如何远程获取?', '汇总报告已经添加到右侧文件上传区,请查收。']) - return report_files, chatbot diff --git a/spaces/diacanFperku/AutoGPT/Download Billing Explorer Full LINK 18.md b/spaces/diacanFperku/AutoGPT/Download Billing Explorer Full LINK 18.md deleted file mode 100644 index d8d6bc6be1f45f497c2d2c5992a346910c3be30e..0000000000000000000000000000000000000000 --- a/spaces/diacanFperku/AutoGPT/Download Billing Explorer Full LINK 18.md +++ /dev/null @@ -1,134 +0,0 @@ -
    -

    Download Billing Explorer Full 18: A Guide for Internet Cafe Owners

    - -

    If you are running an internet cafe business, you know how important it is to have a reliable and efficient software to manage your client computers and billing system. You need a software that can help you monitor and control the usage of your client computers, calculate the fees automatically, generate reports, and more.

    -

    download billing explorer full 18


    DOWNLOAD 🗹 https://gohhs.com/2uFV9r



    - -

    One of the most popular and trusted software for internet cafe management is Billing Explorer. Billing Explorer is a software that can help you manage your internet cafe business with ease and convenience. It has many features and benefits that can make your internet cafe business more profitable and successful.

    - -

    However, to use Billing Explorer, you need to buy a license from the official website or an authorized dealer. The license can be expensive and time-consuming to get. You have to provide your internet cafe name, address, phone number, email, hardware ID, and other information. You also have to pay a fee and wait for them to send you the license file.

    - -

    That's why some internet cafe owners look for alternative ways to get Billing Explorer without paying or waiting for a license. One of the ways is to download billing explorer full 18 from the internet. This is a version of Billing Explorer that has been cracked or patched to bypass the license activation process. You can download billing explorer full 18 from various sources online, such as websites, blogs, forums, or torrents.

    - -

    But how do you download billing explorer full 18? And what are the advantages and disadvantages of using it? In this article, we will guide you through the process of downloading billing explorer full 18 and explain the pros and cons of using it.

    - -

    How to Download Billing Explorer Full 18

    - -

    To download billing explorer full 18, you need to follow some steps. Here are the general steps that you can follow:

    -

    - -
      -
    1. Find a reliable and reputable source for downloading billing explorer full 18. You can use a search engine or a torrent site to look for it. Make sure to read the comments and reviews from other users to verify the quality and safety of the download.
    2. -
    3. Download and install a torrent client on your computer if you are using a torrent site. A torrent client is a software that allows you to download files from a peer-to-peer network. There are many free and popular torrent clients available online, such as uTorrent, BitTorrent, or qBittorrent.
    4. -
    5. Open the download link or the torrent file with your torrent client or your browser. The download link or the torrent file contains information about the files that are linked by the download or the torrent, such as their names, sizes, and locations. Your torrent client or your browser will start downloading the files from other users who have them.
    6. -
    7. Wait for the download to finish. Depending on the size and availability of the files, this might take some time. You can check the progress and status of the download on your torrent client or your browser.
    8. -
    9. Extract and install Billing Explorer from the downloaded files. You might need a software like WinRAR or 7-Zip to extract compressed files. Follow the instructions provided by the download or the torrent to install Billing Explorer on your computer.
    10. -
    11. Run Billing Explorer and enjoy using it. You can now manage your internet cafe business with Billing Explorer without having to buy or activate a license.
    12. -
    - -

    Benefits and Drawbacks of Downloading Billing Explorer Full 18

    - -

    Downloading billing explorer full 18 can have some benefits and drawbacks for you as an internet cafe owner. Here are some of them:

    - -

    Benefits

    - -
      -
    • You can save money and time by not having to buy or wait for a license from the official website or an authorized dealer.
    • -
    • You can have more flexibility and control over your Billing Explorer settings and features without having to follow any restrictions or limitations.
    • -
    • You can use Billing Explorer on multiple computers or devices without having to buy multiple licenses.
    • -
    • You can update or upgrade Billing Explorer to newer versions or features without having to pay extra fees or request new licenses.
    • -
    - -

    Drawbacks

    - -
      -
    • You might expose your computer or device to viruses, malware, spyware, or other harmful programs that can damage your system or steal your personal information.
    • -
    • You might encounter errors, bugs, glitches, or compatibility issues that can affect the performance or functionality of Billing Explorer or your client computers.
    • -
    • You might violate the terms and conditions of Billing Explorer and get in trouble with the law for using an illegal or unlicensed software.
    • -
    • You might not be able to get support or warranty from Billing Explorer or an authorized dealer if you encounter any problems with Billing Explorer or your client computers.
    • -
    - -

    Conclusion

    - -

    Billing Explorer Full 18 is a version of Billing Explorer that has been cracked or patched to bypass the license activation process. You can download billing explorer full 18 from various sources online, such as websites, blogs, forums, or torrents.

    - -

    However, downloading billing explorer full 18 is not without risks and drawbacks. You might download a fake, malicious, outdated, incompatible, illegal, unlicensed, incomplete, or corrupted version of Billing Explorer that can cause more harm than good.

    - -

    Therefore, if you want to use Billing Explorer safely and effectively, you should buy a legitimate and official license from the official website or an authorized dealer. This way, you can ensure that you have the full functionality and compatibility of Billing Explorer, as well as the support and warranty from them.

    -

    What is Billing Explorer Full 18

    - -

    Billing Explorer Full 18 is a version of Billing Explorer that has been cracked or patched to bypass the license activation process. Billing Explorer is a software that can help you manage your internet cafe business with ease and convenience. It has many features and benefits that can make your internet cafe business more profitable and successful.

    - -

    Some of the features and benefits of Billing Explorer are:

    - -
      -
    • It can monitor and control the usage of your client computers, such as setting the time limit, locking or unlocking the screen, shutting down or restarting the computer, and more.
    • -
    • It can calculate the fees automatically based on your settings, such as the rate per hour, the minimum charge, the discount, the tax, and more.
    • -
    • It can generate reports and statistics about your internet cafe business, such as the income, the expense, the profit, the client data, the computer data, and more.
    • -
    • It can support various payment methods, such as cash, voucher, prepaid card, credit card, debit card, and more.
    • -
    • It can integrate with other software or hardware, such as printer, scanner, webcam, game console, antivirus, firewall, and more.
    • -
    • It can protect your internet cafe business from fraud, theft, hacking, virus, malware, spyware, and more.
    • -
    - -

    Billing Explorer Full 18 is a version of Billing Explorer that has been modified to work without a license. You can download billing explorer full 18 from various sources online and use it without paying or waiting for a license.

    - -

    How to Use Billing Explorer Full 18

    - -

    To use billing explorer full 18, you need to follow some steps. Here are the general steps that you can follow:

    - -
      -
    1. Install Billing Explorer on your server computer and your client computers. You can use a local area network (LAN) or a wireless network (WLAN) to connect your server computer and your client computers.
    2. -
    3. Run Billing Explorer on your server computer and your client computers. You will see a main window on your server computer and a login window on your client computers.
    4. -
    5. Set up your Billing Explorer settings on your server computer. You can customize your settings according to your preferences and needs. You can set up your internet cafe name, address, phone number, email, logo, rate per hour, minimum charge, discount, tax, payment method, report format, security level, and more.
    6. -
    7. Start using Billing Explorer on your server computer and your client computers. You can use Billing Explorer to manage your internet cafe business with ease and convenience. You can monitor and control the usage of your client computers, calculate the fees automatically, generate reports and statistics, and more.
    8. -
    - -

    Tips and Tricks for Using Billing Explorer Full 18

    - -

    To use billing explorer full 18 effectively and efficiently, you can follow some tips and tricks. Here are some of them:

    - -
      -
    • Keep your server computer and your client computers updated and protected from viruses, malware, spyware, and other harmful programs. You can use an antivirus software or a firewall software to scan and clean your system regularly.
    • -
    • Backup your data regularly to avoid losing any important information or files. You can use an external hard drive or a cloud storage service to backup your data.
    • -
    • Maintain good communication with your customers and employees. You can use a microphone or a speaker to communicate with them verbally or use a chat software or an email software to communicate with them textually.
    • -
    • Promote your internet cafe business to attract more customers and increase your income. You can use social media platforms or online directories to advertise your internet cafe business online or use flyers or banners to advertise your internet cafe business offline.
    • -
    • Offer incentives or rewards to loyal customers or employees. You can use vouchers or coupons to give discounts or freebies to loyal customers or use bonuses or commissions to give extra income or benefits to loyal employees.
    • -
    - -

    Conclusion

    - -

    Billing Explorer Full 18 is a version of Billing Explorer that has been cracked or patched to bypass the license activation process. You can download billing explorer full 18 from various sources online and use it without paying or waiting for a license.

    - -

    Billing Explorer is a software that can help you manage your internet cafe business with ease and convenience. It has many features and benefits that can make your internet cafe business more profitable and successful.

    - -

    However, downloading billing explorer full 18 is not without risks and drawbacks. You might download a fake, malicious, outdated, incompatible, illegal, unlicensed, -incomplete -or corrupted version of Billing Explorer that can cause more harm than good.

    - -

    Therefore -if you want to use Billing Explorer safely -and effectively -you should buy -a legitimate -and official license from -the official website -or an authorized dealer. -This way -you can ensure that you have -the full functionality -and compatibility of Billing Explorer -as well as -the support -and warranty from them. -

    -

    Conclusion

    - -

    Billing Explorer Full 18 is a version of Billing Explorer that has been cracked or patched to bypass the license activation process. You can download billing explorer full 18 from various sources online and use it without paying or waiting for a license.

    - -

    Billing Explorer is a software that can help you manage your internet cafe business with ease and convenience. It has many features and benefits that can make your internet cafe business more profitable and successful.

    - -

    However, downloading billing explorer full 18 is not without risks and drawbacks. You might download a fake, malicious, outdated, incompatible, illegal, unlicensed, incomplete, or corrupted version of Billing Explorer that can cause more harm than good.

    - -

    Therefore, if you want to use Billing Explorer safely and effectively, you should buy a legitimate and official license from the official website or an authorized dealer. This way, you can ensure that you have the full functionality and compatibility of Billing Explorer, as well as the support and warranty from them.

    3cee63e6c2
    -
    -
    \ No newline at end of file diff --git a/spaces/diacanFperku/AutoGPT/English Placement Test For Young Learners Pdf Download REPACK.md b/spaces/diacanFperku/AutoGPT/English Placement Test For Young Learners Pdf Download REPACK.md deleted file mode 100644 index 52e5688639dc3aa5119cfbd8a9427c49566b8e0a..0000000000000000000000000000000000000000 --- a/spaces/diacanFperku/AutoGPT/English Placement Test For Young Learners Pdf Download REPACK.md +++ /dev/null @@ -1,10 +0,0 @@ - -

    thewida access assessment is an online annual assessment given to all students who qualify for english language development (eld) services. theannual assessment measures students' english language proficiency, both knowledge and skills, in reading, listening, writing, and speaking. results from this test determine which students remain eligible to continue receiving eld services.

    -

    english standards math preparation are in high demand by schools, universities and large businesses. weve set up this sample for you to do a quick search for the best suited test and location with which you can prepare your student for their tests.

    -

    English Placement Test For Young Learners Pdf Download


    Download Ziphttps://gohhs.com/2uFTgg



    -

    more resources for a change and order to ordermoresample tests on this page for quick perusal. lessonsstudy optionsthink of your child as an athlete. every day, you go to the gym and work out, not just on the days you want to play a game, but every day in order to get ready to play.

    -

    you may want to ask, is it normal to find your child a few days after exam date? if they are not there, report it to the teachers so they can investigate immediately. a reply should be sent within an hour so that you know what the process will take. a report of academic achievement should follow your children report so that the school knows that your child has passed the test.

    -

    if the child shows no sign of potential or improvement, reevaluate your needs and maybe consider some extra help. remember to make other arrangements for the child, such as adjusting the time of the test, so that your child can have success.

    -

    english test preparation books have found popularity among students and parents because they focus on helping the student to understand and improve their skills rather than giving out just the right answers.

    899543212b
    -
    -
    \ No newline at end of file diff --git a/spaces/diacanFperku/AutoGPT/Quench Torrent Download [FULL] Fixed.md b/spaces/diacanFperku/AutoGPT/Quench Torrent Download [FULL] Fixed.md deleted file mode 100644 index ed6c4b64ed7668a308a245a49b22bf80c5dae754..0000000000000000000000000000000000000000 --- a/spaces/diacanFperku/AutoGPT/Quench Torrent Download [FULL] Fixed.md +++ /dev/null @@ -1,6 +0,0 @@ -

    Quench Torrent Download [FULL]


    DOWNLOAD »»» https://gohhs.com/2uFUSa



    -
    -Next, you can download for free on Android the full version of the Ultimate Wolf ... Free Download PC Game Cracked in Direct Link and Torrent. ... Survive,hunt,quench a thirst,find shelter on a cold night,explore the world and ... 4d29de3e1b
    -
    -
    -

    diff --git a/spaces/digitalOSHO/webui/README.md b/spaces/digitalOSHO/webui/README.md deleted file mode 100644 index 74607246ea3d716425e4b089e873cebaafe9535f..0000000000000000000000000000000000000000 --- a/spaces/digitalOSHO/webui/README.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Stable Diffusion Web UI -emoji: 🧿 -colorFrom: blue -colorTo: blue -sdk: gradio -sdk_version: 3.9 -app_file: app.py -pinned: false -duplicated_from: camenduru/webui ---- - -## Stable Diffusion Web UI -[https://github.com/AUTOMATIC1111/stable-diffusion-webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui) - -## Documentation -[https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki) - -## Models License -https://huggingface.co/spaces/CompVis/stable-diffusion-license \ No newline at end of file diff --git a/spaces/digitalxingtong/Jiuxia-Bert-Vits2/transcribe_genshin.py b/spaces/digitalxingtong/Jiuxia-Bert-Vits2/transcribe_genshin.py deleted file mode 100644 index acc98814af6189d129ab85946525bec55419a33f..0000000000000000000000000000000000000000 --- a/spaces/digitalxingtong/Jiuxia-Bert-Vits2/transcribe_genshin.py +++ /dev/null @@ -1,78 +0,0 @@ -# coding=gbk -import os -import argparse -import librosa -import numpy as np -from multiprocessing import Pool, cpu_count - -import soundfile -from scipy.io import wavfile -from tqdm import tqdm - -global speaker_annos -speaker_annos = [] - -def process(item): - spkdir, wav_name, args = item - speaker = spkdir.replace("\\", "/").split("/")[-1] - wav_path = os.path.join(args.in_dir, speaker, wav_name) - if os.path.exists(wav_path) and '.wav' in wav_path: - os.makedirs(os.path.join(args.out_dir, speaker), exist_ok=True) - wav, sr = librosa.load(wav_path, sr=args.sr) - soundfile.write( - os.path.join(args.out_dir, speaker, wav_name), - wav, - sr - ) - -def process_text(item): - spkdir, wav_name, args = item - speaker = spkdir.replace("\\", "/").split("/")[-1] - wav_path = os.path.join(args.in_dir, speaker, wav_name) - global speaker_annos - tr_name = wav_name.replace('.wav', '') - with open(args.out_dir+'/'+speaker+'/'+tr_name+'.lab', "r", encoding="utf-8") as file: - text = file.read() - text = text.replace("{NICKNAME}",'') - text = text.replace("{M#}{F#}",'') - text = text.replace("{M#}{F#}",'') - substring = "{M#}{F#}" - if substring in text: - if tr_name.endswith("a"): - text = text.replace("{M#}{F#}",'') - if tr_name.endswith("b"): - text = text.replace("{M#}{F#}",'') - text = text.replace("#",'') - text = "ZH|" + text + "\n" # - speaker_annos.append(args.out_dir+'/'+speaker+'/'+wav_name+ "|" + speaker + "|" + text) - - - -if __name__ == "__main__": - parent_dir = "./genshin_dataset/" - speaker_names = list(os.walk(parent_dir))[0][1] - parser = argparse.ArgumentParser() - parser.add_argument("--sr", type=int, default=44100, help="sampling rate") - parser.add_argument("--in_dir", type=str, default="./genshin_dataset", help="path to source dir") - parser.add_argument("--out_dir", type=str, default="./genshin_dataset", help="path to target dir") - args = parser.parse_args() - # processs = 8 - processs = cpu_count()-2 if cpu_count() >4 else 1 - pool = Pool(processes=processs) - - for speaker in os.listdir(args.in_dir): - spk_dir = os.path.join(args.in_dir, speaker) - if os.path.isdir(spk_dir): - print(spk_dir) - for _ in tqdm(pool.imap_unordered(process, [(spk_dir, i, args) for i in os.listdir(spk_dir) if i.endswith("wav")])): - pass - for i in os.listdir(spk_dir): - if i.endswith("wav"): - pro=(spk_dir, i, args) - process_text(pro) - if len(speaker_annos) == 0: - print("transcribe error!!!") - with open("./filelists/short_character_anno.list", 'w', encoding='utf-8') as f: - for line in speaker_annos: - f.write(line) - print("transcript file finished.") diff --git a/spaces/dlenzen/AW-06-SL-AI-Image-Music-Video-UI-UX-URL/README.md b/spaces/dlenzen/AW-06-SL-AI-Image-Music-Video-UI-UX-URL/README.md deleted file mode 100644 index 610715c65882d341201e663ef6c4ea2d8bdc087d..0000000000000000000000000000000000000000 --- a/spaces/dlenzen/AW-06-SL-AI-Image-Music-Video-UI-UX-URL/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: AW 06 SL AI Image Music Video UI UX URL -emoji: 🐠 -colorFrom: yellow -colorTo: blue -sdk: streamlit -sdk_version: 1.10.0 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/doctorsafe/mychat/theme.py b/spaces/doctorsafe/mychat/theme.py deleted file mode 100644 index d7544ed6b26d07bdcd65886143ab38deedd59e5a..0000000000000000000000000000000000000000 --- a/spaces/doctorsafe/mychat/theme.py +++ /dev/null @@ -1,82 +0,0 @@ -import gradio as gr - -# gradio可用颜色列表 -# gr.themes.utils.colors.slate (石板色) -# gr.themes.utils.colors.gray (灰色) -# gr.themes.utils.colors.zinc (锌色) -# gr.themes.utils.colors.neutral (中性色) -# gr.themes.utils.colors.stone (石头色) -# gr.themes.utils.colors.red (红色) -# gr.themes.utils.colors.orange (橙色) -# gr.themes.utils.colors.amber (琥珀色) -# gr.themes.utils.colors.yellow (黄色) -# gr.themes.utils.colors.lime (酸橙色) -# gr.themes.utils.colors.green (绿色) -# gr.themes.utils.colors.emerald (祖母绿) -# gr.themes.utils.colors.teal (青蓝色) -# gr.themes.utils.colors.cyan (青色) -# gr.themes.utils.colors.sky (天蓝色) -# gr.themes.utils.colors.blue (蓝色) -# gr.themes.utils.colors.indigo (靛蓝色) -# gr.themes.utils.colors.violet (紫罗兰色) -# gr.themes.utils.colors.purple (紫色) -# gr.themes.utils.colors.fuchsia (洋红色) -# gr.themes.utils.colors.pink (粉红色) -# gr.themes.utils.colors.rose (玫瑰色) - -def adjust_theme(): - try: - color_er = gr.themes.utils.colors.pink - set_theme = gr.themes.Default( - primary_hue=gr.themes.utils.colors.orange, - neutral_hue=gr.themes.utils.colors.gray, - font=["sans-serif", "Microsoft YaHei", "ui-sans-serif", "system-ui", "sans-serif", gr.themes.utils.fonts.GoogleFont("Source Sans Pro")], - font_mono=["ui-monospace", "Consolas", "monospace", gr.themes.utils.fonts.GoogleFont("IBM Plex Mono")]) - set_theme.set( - # Colors - input_background_fill_dark="*neutral_800", - # Transition - button_transition="none", - # Shadows - button_shadow="*shadow_drop", - button_shadow_hover="*shadow_drop_lg", - button_shadow_active="*shadow_inset", - input_shadow="0 0 0 *shadow_spread transparent, *shadow_inset", - input_shadow_focus="0 0 0 *shadow_spread *secondary_50, *shadow_inset", - input_shadow_focus_dark="0 0 0 *shadow_spread *neutral_700, *shadow_inset", - checkbox_label_shadow="*shadow_drop", - block_shadow="*shadow_drop", - form_gap_width="1px", - # Button borders - input_border_width="1px", - input_background_fill="white", - # Gradients - stat_background_fill="linear-gradient(to right, *primary_400, *primary_200)", - stat_background_fill_dark="linear-gradient(to right, *primary_400, *primary_600)", - error_background_fill=f"linear-gradient(to right, {color_er.c100}, *background_fill_secondary)", - error_background_fill_dark="*background_fill_primary", - checkbox_label_background_fill="linear-gradient(to top, *neutral_50, white)", - checkbox_label_background_fill_dark="linear-gradient(to top, *neutral_900, *neutral_800)", - checkbox_label_background_fill_hover="linear-gradient(to top, *neutral_100, white)", - checkbox_label_background_fill_hover_dark="linear-gradient(to top, *neutral_900, *neutral_800)", - button_primary_background_fill="linear-gradient(to bottom right, *primary_100, *primary_300)", - button_primary_background_fill_dark="linear-gradient(to bottom right, *primary_500, *primary_600)", - button_primary_background_fill_hover="linear-gradient(to bottom right, *primary_100, *primary_200)", - button_primary_background_fill_hover_dark="linear-gradient(to bottom right, *primary_500, *primary_500)", - button_primary_border_color_dark="*primary_500", - button_secondary_background_fill="linear-gradient(to bottom right, *neutral_100, *neutral_200)", - button_secondary_background_fill_dark="linear-gradient(to bottom right, *neutral_600, *neutral_700)", - button_secondary_background_fill_hover="linear-gradient(to bottom right, *neutral_100, *neutral_100)", - button_secondary_background_fill_hover_dark="linear-gradient(to bottom right, *neutral_600, *neutral_600)", - button_cancel_background_fill=f"linear-gradient(to bottom right, {color_er.c100}, {color_er.c200})", - button_cancel_background_fill_dark=f"linear-gradient(to bottom right, {color_er.c600}, {color_er.c700})", - button_cancel_background_fill_hover=f"linear-gradient(to bottom right, {color_er.c100}, {color_er.c100})", - button_cancel_background_fill_hover_dark=f"linear-gradient(to bottom right, {color_er.c600}, {color_er.c600})", - button_cancel_border_color=color_er.c200, - button_cancel_border_color_dark=color_er.c600, - button_cancel_text_color=color_er.c600, - button_cancel_text_color_dark="white", - ) - except: - set_theme = None; print('gradio版本较旧, 不能自定义字体和颜色') - return set_theme diff --git a/spaces/doluvor/faster-whisper-webui/src/prompts/abstractPromptStrategy.py b/spaces/doluvor/faster-whisper-webui/src/prompts/abstractPromptStrategy.py deleted file mode 100644 index 41e8cba49fdbcc294ea216fffcafee89b07ed4df..0000000000000000000000000000000000000000 --- a/spaces/doluvor/faster-whisper-webui/src/prompts/abstractPromptStrategy.py +++ /dev/null @@ -1,73 +0,0 @@ -import abc - - -class AbstractPromptStrategy: - """ - Represents a strategy for generating prompts for a given audio segment. - - Note that the strategy must be picklable, as it will be serialized and sent to the workers. - """ - - @abc.abstractmethod - def get_segment_prompt(self, segment_index: int, whisper_prompt: str, detected_language: str) -> str: - """ - Retrieves the prompt for a given segment. - - Parameters - ---------- - segment_index: int - The index of the segment. - whisper_prompt: str - The prompt for the segment generated by Whisper. This is typically concatenated with the initial prompt. - detected_language: str - The language detected for the segment. - """ - pass - - @abc.abstractmethod - def on_segment_finished(self, segment_index: int, whisper_prompt: str, detected_language: str, result: dict): - """ - Called when a segment has finished processing. - - Parameters - ---------- - segment_index: int - The index of the segment. - whisper_prompt: str - The prompt for the segment generated by Whisper. This is typically concatenated with the initial prompt. - detected_language: str - The language detected for the segment. - result: dict - The result of the segment. It has the following format: - { - "text": str, - "segments": [ - { - "text": str, - "start": float, - "end": float, - "words": [words], - } - ], - "language": str, - } - """ - pass - - def _concat_prompt(self, prompt1, prompt2): - """ - Concatenates two prompts. - - Parameters - ---------- - prompt1: str - The first prompt. - prompt2: str - The second prompt. - """ - if (prompt1 is None): - return prompt2 - elif (prompt2 is None): - return prompt1 - else: - return prompt1 + " " + prompt2 \ No newline at end of file diff --git a/spaces/dominguesm/alpaca-ptbr-7b/utils.py b/spaces/dominguesm/alpaca-ptbr-7b/utils.py deleted file mode 100644 index b8436eb1f5a1b474fa523dab67f02354105607f1..0000000000000000000000000000000000000000 --- a/spaces/dominguesm/alpaca-ptbr-7b/utils.py +++ /dev/null @@ -1,59 +0,0 @@ -import os -import sys -import urllib.request -from typing import Optional - -from tqdm.auto import tqdm - - -class DownloadProgressBar(tqdm): - def update_to( - self, b: int = 1, bsize: int = 1, tsize: Optional[int] = None - ) -> None: - if tsize is not None: - self.total = tsize - self.update(b * bsize - self.n) - - -def download() -> str: - # Get the model URI from the environment - uri_model = os.environ.get("ALPACA_MODEL_URI") - - # Set the path for the model - model_path = "./model.bin" - - # If the model path already exists, return it - if os.path.exists(model_path): - return model_path - - # Create a progress bar - with DownloadProgressBar( - unit="B", unit_scale=True, miniters=1, desc=uri_model.split("/")[-1] - ) as t: - # Download the model to the model path - urllib.request.urlretrieve( - uri_model, filename=model_path, reporthook=t.update_to - ) - - # Return the model path - return model_path - - -def generate_prompt(instruction: str, input: Optional[str] = None) -> str: - if input: - return f"""Abaixo está uma instrução que descreve uma tarefa, emparelhada com uma entrada que fornece mais contexto. Escreva uma resposta que conclua adequadamente a solicitação. - -### Instruções: -{instruction} - -### Entrada: -{input} - -### Resposta:""" - else: - return f"""Abaixo está uma instrução que descreve uma tarefa. Escreva uma resposta que conclua adequadamente a solicitação. - -### Instruções: -{instruction} - -### Resposta:""" diff --git a/spaces/dorkai/ChatUIPro/app/components/base/spinner/index.tsx b/spaces/dorkai/ChatUIPro/app/components/base/spinner/index.tsx deleted file mode 100644 index 53de4eda43e1ec756e4961b7eb18c895c54e76d1..0000000000000000000000000000000000000000 --- a/spaces/dorkai/ChatUIPro/app/components/base/spinner/index.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import type { FC } from 'react' -import React from 'react' - -type Props = { - loading?: boolean - className?: string - children?: React.ReactNode | string -} - -const Spinner: FC = ({ loading = false, children, className }) => { - return ( -
    - Loading... - {children} -
    - ) -} - -export default Spinner diff --git a/spaces/dorkai/singpt-2.0/convert-to-safetensors.py b/spaces/dorkai/singpt-2.0/convert-to-safetensors.py deleted file mode 100644 index 63baaa9726ab48025d2ba473d029bb3f1153aa3a..0000000000000000000000000000000000000000 --- a/spaces/dorkai/singpt-2.0/convert-to-safetensors.py +++ /dev/null @@ -1,38 +0,0 @@ -''' - -Converts a transformers model to safetensors format and shards it. - -This makes it faster to load (because of safetensors) and lowers its RAM usage -while loading (because of sharding). - -Based on the original script by 81300: - -https://gist.github.com/81300/fe5b08bff1cba45296a829b9d6b0f303 - -''' - -import argparse -from pathlib import Path - -import torch -from transformers import AutoModelForCausalLM, AutoTokenizer - -parser = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=54)) -parser.add_argument('MODEL', type=str, default=None, nargs='?', help="Path to the input model.") -parser.add_argument('--output', type=str, default=None, help='Path to the output folder (default: models/{model_name}_safetensors).') -parser.add_argument("--max-shard-size", type=str, default="2GB", help="Maximum size of a shard in GB or MB (default: %(default)s).") -parser.add_argument('--bf16', action='store_true', help='Load the model with bfloat16 precision. Requires NVIDIA Ampere GPU.') -args = parser.parse_args() - -if __name__ == '__main__': - path = Path(args.MODEL) - model_name = path.name - - print(f"Loading {model_name}...") - model = AutoModelForCausalLM.from_pretrained(path, low_cpu_mem_usage=True, torch_dtype=torch.bfloat16 if args.bf16 else torch.float16) - tokenizer = AutoTokenizer.from_pretrained(path) - - out_folder = args.output or Path(f"models/{model_name}_safetensors") - print(f"Saving the converted model to {out_folder} with a maximum shard size of {args.max_shard_size}...") - model.save_pretrained(out_folder, max_shard_size=args.max_shard_size, safe_serialization=True) - tokenizer.save_pretrained(out_folder) diff --git a/spaces/dorkai/text-generation-webui-main/text-generation-webui-main/css/main.css b/spaces/dorkai/text-generation-webui-main/text-generation-webui-main/css/main.css deleted file mode 100644 index cdde27058683844ca3878451946907ef2a81c046..0000000000000000000000000000000000000000 --- a/spaces/dorkai/text-generation-webui-main/text-generation-webui-main/css/main.css +++ /dev/null @@ -1,139 +0,0 @@ -.tabs.svelte-710i53 { - margin-top: 0 -} - -.py-6 { - padding-top: 2.5rem -} - -.dark #refresh-button { - background-color: #ffffff1f; -} - -#refresh-button { - flex: none; - margin: 0; - padding: 0; - min-width: 50px; - border: none; - box-shadow: none; - border-radius: 10px; - background-color: #0000000d; -} - -#download-label, #upload-label { - min-height: 0 -} - -#accordion { -} - -.dark svg { - fill: white; -} - -.dark a { - color: white !important; - text-decoration: none !important; -} - -ol li p, ul li p { - display: inline-block; -} - -#main, #parameters, #chat-settings, #interface-mode, #lora, #training-tab, #model-tab { - border: 0; -} - -.gradio-container-3-18-0 .prose * h1, h2, h3, h4 { - color: white; -} - -.gradio-container { - max-width: 100% !important; - padding-top: 0 !important; -} - -#extensions { - padding: 15px; - margin-bottom: 35px; -} - -span.math.inline { - font-size: 27px; - vertical-align: baseline !important; -} - -div.svelte-15lo0d8 > *, div.svelte-15lo0d8 > .form > * { - flex-wrap: nowrap; -} - -.header_bar { - background-color: #f7f7f7; - margin-bottom: 40px; -} - -.dark .header_bar { - border: none !important; - background-color: #8080802b; -} - -.textbox_default textarea { - height: calc(100vh - 391px); -} - -.textbox_default_output textarea { - height: calc(100vh - 210px); -} - -.textbox textarea { - height: calc(100vh - 261px); -} - -.textbox_default textarea, .textbox_default_output textarea, .textbox textarea { - font-size: 16px !important; - color: #46464A !important; -} - -.dark textarea { - color: #efefef !important; -} - -/* Hide the gradio footer*/ -footer { - display: none !important; -} - -button { - font-size: 14px !important; -} - -.small-button { - max-width: 171px; -} - -/* Align the elements for SD_api_picture extension */ -.SDAP #sampler_box { - padding-top: var(--spacing-sm); - padding-bottom: var(--spacing-sm); -} - -.SDAP #seed_box, -.SDAP #cfg_box { - padding-top: var(--spacing-md); -} - -.SDAP #sampler_box span, -.SDAP #seed_box span, -.SDAP #cfg_box span{ - margin-bottom: var(--spacing-sm); -} - -.SDAP svg.dropdown-arrow { - flex-shrink: 0 !important; - margin: 0px !important; -} - -.SDAP .hires_opts input[type="number"] { - width: 6em !important; -} \ No newline at end of file diff --git a/spaces/dragao-elastico/RVC_V2/lib/infer_pack/models.py b/spaces/dragao-elastico/RVC_V2/lib/infer_pack/models.py deleted file mode 100644 index 3665d03bc0514a6ed07d3372ea24717dae1e0a65..0000000000000000000000000000000000000000 --- a/spaces/dragao-elastico/RVC_V2/lib/infer_pack/models.py +++ /dev/null @@ -1,1142 +0,0 @@ -import math, pdb, os -from time import time as ttime -import torch -from torch import nn -from torch.nn import functional as F -from lib.infer_pack import modules -from lib.infer_pack import attentions -from lib.infer_pack import commons -from lib.infer_pack.commons import init_weights, get_padding -from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d -from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm -from lib.infer_pack.commons import init_weights -import numpy as np -from lib.infer_pack import commons - - -class TextEncoder256(nn.Module): - def __init__( - self, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=True, - ): - super().__init__() - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.emb_phone = nn.Linear(256, hidden_channels) - self.lrelu = nn.LeakyReLU(0.1, inplace=True) - if f0 == True: - self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256 - self.encoder = attentions.Encoder( - hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, phone, pitch, lengths): - if pitch == None: - x = self.emb_phone(phone) - else: - x = self.emb_phone(phone) + self.emb_pitch(pitch) - x = x * math.sqrt(self.hidden_channels) # [b, t, h] - x = self.lrelu(x) - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.encoder(x * x_mask, x_mask) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return m, logs, x_mask - - -class TextEncoder768(nn.Module): - def __init__( - self, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=True, - ): - super().__init__() - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.emb_phone = nn.Linear(768, hidden_channels) - self.lrelu = nn.LeakyReLU(0.1, inplace=True) - if f0 == True: - self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256 - self.encoder = attentions.Encoder( - hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, phone, pitch, lengths): - if pitch == None: - x = self.emb_phone(phone) - else: - x = self.emb_phone(phone) + self.emb_pitch(pitch) - x = x * math.sqrt(self.hidden_channels) # [b, t, h] - x = self.lrelu(x) - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.encoder(x * x_mask, x_mask) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return m, logs, x_mask - - -class ResidualCouplingBlock(nn.Module): - def __init__( - self, - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - n_flows=4, - gin_channels=0, - ): - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.flows = nn.ModuleList() - for i in range(n_flows): - self.flows.append( - modules.ResidualCouplingLayer( - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=gin_channels, - mean_only=True, - ) - ) - self.flows.append(modules.Flip()) - - def forward(self, x, x_mask, g=None, reverse=False): - if not reverse: - for flow in self.flows: - x, _ = flow(x, x_mask, g=g, reverse=reverse) - else: - for flow in reversed(self.flows): - x = flow(x, x_mask, g=g, reverse=reverse) - return x - - def remove_weight_norm(self): - for i in range(self.n_flows): - self.flows[i * 2].remove_weight_norm() - - -class PosteriorEncoder(nn.Module): - def __init__( - self, - in_channels, - out_channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=0, - ): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.gin_channels = gin_channels - - self.pre = nn.Conv1d(in_channels, hidden_channels, 1) - self.enc = modules.WN( - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=gin_channels, - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, x, x_lengths, g=None): - x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.pre(x) * x_mask - x = self.enc(x, x_mask, g=g) - stats = self.proj(x) * x_mask - m, logs = torch.split(stats, self.out_channels, dim=1) - z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask - return z, m, logs, x_mask - - def remove_weight_norm(self): - self.enc.remove_weight_norm() - - -class Generator(torch.nn.Module): - def __init__( - self, - initial_channel, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=0, - ): - super(Generator, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - self.conv_pre = Conv1d( - initial_channel, upsample_initial_channel, 7, 1, padding=3 - ) - resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - self.ups.append( - weight_norm( - ConvTranspose1d( - upsample_initial_channel // (2**i), - upsample_initial_channel // (2 ** (i + 1)), - k, - u, - padding=(k - u) // 2, - ) - ) - ) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate( - zip(resblock_kernel_sizes, resblock_dilation_sizes) - ): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - def forward(self, x, g=None): - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - - return x - - def remove_weight_norm(self): - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -class SineGen(torch.nn.Module): - """Definition of sine generator - SineGen(samp_rate, harmonic_num = 0, - sine_amp = 0.1, noise_std = 0.003, - voiced_threshold = 0, - flag_for_pulse=False) - samp_rate: sampling rate in Hz - harmonic_num: number of harmonic overtones (default 0) - sine_amp: amplitude of sine-wavefrom (default 0.1) - noise_std: std of Gaussian noise (default 0.003) - voiced_thoreshold: F0 threshold for U/V classification (default 0) - flag_for_pulse: this SinGen is used inside PulseGen (default False) - Note: when flag_for_pulse is True, the first time step of a voiced - segment is always sin(np.pi) or cos(0) - """ - - def __init__( - self, - samp_rate, - harmonic_num=0, - sine_amp=0.1, - noise_std=0.003, - voiced_threshold=0, - flag_for_pulse=False, - ): - super(SineGen, self).__init__() - self.sine_amp = sine_amp - self.noise_std = noise_std - self.harmonic_num = harmonic_num - self.dim = self.harmonic_num + 1 - self.sampling_rate = samp_rate - self.voiced_threshold = voiced_threshold - - def _f02uv(self, f0): - # generate uv signal - uv = torch.ones_like(f0) - uv = uv * (f0 > self.voiced_threshold) - return uv - - def forward(self, f0, upp): - """sine_tensor, uv = forward(f0) - input F0: tensor(batchsize=1, length, dim=1) - f0 for unvoiced steps should be 0 - output sine_tensor: tensor(batchsize=1, length, dim) - output uv: tensor(batchsize=1, length, 1) - """ - with torch.no_grad(): - f0 = f0[:, None].transpose(1, 2) - f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device) - # fundamental component - f0_buf[:, :, 0] = f0[:, :, 0] - for idx in np.arange(self.harmonic_num): - f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * ( - idx + 2 - ) # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic - rad_values = (f0_buf / self.sampling_rate) % 1 ###%1意味着n_har的乘积无法后处理优化 - rand_ini = torch.rand( - f0_buf.shape[0], f0_buf.shape[2], device=f0_buf.device - ) - rand_ini[:, 0] = 0 - rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini - tmp_over_one = torch.cumsum(rad_values, 1) # % 1 #####%1意味着后面的cumsum无法再优化 - tmp_over_one *= upp - tmp_over_one = F.interpolate( - tmp_over_one.transpose(2, 1), - scale_factor=upp, - mode="linear", - align_corners=True, - ).transpose(2, 1) - rad_values = F.interpolate( - rad_values.transpose(2, 1), scale_factor=upp, mode="nearest" - ).transpose( - 2, 1 - ) ####### - tmp_over_one %= 1 - tmp_over_one_idx = (tmp_over_one[:, 1:, :] - tmp_over_one[:, :-1, :]) < 0 - cumsum_shift = torch.zeros_like(rad_values) - cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0 - sine_waves = torch.sin( - torch.cumsum(rad_values + cumsum_shift, dim=1) * 2 * np.pi - ) - sine_waves = sine_waves * self.sine_amp - uv = self._f02uv(f0) - uv = F.interpolate( - uv.transpose(2, 1), scale_factor=upp, mode="nearest" - ).transpose(2, 1) - noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3 - noise = noise_amp * torch.randn_like(sine_waves) - sine_waves = sine_waves * uv + noise - return sine_waves, uv, noise - - -class SourceModuleHnNSF(torch.nn.Module): - """SourceModule for hn-nsf - SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1, - add_noise_std=0.003, voiced_threshod=0) - sampling_rate: sampling_rate in Hz - harmonic_num: number of harmonic above F0 (default: 0) - sine_amp: amplitude of sine source signal (default: 0.1) - add_noise_std: std of additive Gaussian noise (default: 0.003) - note that amplitude of noise in unvoiced is decided - by sine_amp - voiced_threshold: threhold to set U/V given F0 (default: 0) - Sine_source, noise_source = SourceModuleHnNSF(F0_sampled) - F0_sampled (batchsize, length, 1) - Sine_source (batchsize, length, 1) - noise_source (batchsize, length 1) - uv (batchsize, length, 1) - """ - - def __init__( - self, - sampling_rate, - harmonic_num=0, - sine_amp=0.1, - add_noise_std=0.003, - voiced_threshod=0, - is_half=True, - ): - super(SourceModuleHnNSF, self).__init__() - - self.sine_amp = sine_amp - self.noise_std = add_noise_std - self.is_half = is_half - # to produce sine waveforms - self.l_sin_gen = SineGen( - sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod - ) - - # to merge source harmonics into a single excitation - self.l_linear = torch.nn.Linear(harmonic_num + 1, 1) - self.l_tanh = torch.nn.Tanh() - - def forward(self, x, upp=None): - sine_wavs, uv, _ = self.l_sin_gen(x, upp) - if self.is_half: - sine_wavs = sine_wavs.half() - sine_merge = self.l_tanh(self.l_linear(sine_wavs)) - return sine_merge, None, None # noise, uv - - -class GeneratorNSF(torch.nn.Module): - def __init__( - self, - initial_channel, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels, - sr, - is_half=False, - ): - super(GeneratorNSF, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - - self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates)) - self.m_source = SourceModuleHnNSF( - sampling_rate=sr, harmonic_num=0, is_half=is_half - ) - self.noise_convs = nn.ModuleList() - self.conv_pre = Conv1d( - initial_channel, upsample_initial_channel, 7, 1, padding=3 - ) - resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - c_cur = upsample_initial_channel // (2 ** (i + 1)) - self.ups.append( - weight_norm( - ConvTranspose1d( - upsample_initial_channel // (2**i), - upsample_initial_channel // (2 ** (i + 1)), - k, - u, - padding=(k - u) // 2, - ) - ) - ) - if i + 1 < len(upsample_rates): - stride_f0 = np.prod(upsample_rates[i + 1 :]) - self.noise_convs.append( - Conv1d( - 1, - c_cur, - kernel_size=stride_f0 * 2, - stride=stride_f0, - padding=stride_f0 // 2, - ) - ) - else: - self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1)) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate( - zip(resblock_kernel_sizes, resblock_dilation_sizes) - ): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - self.upp = np.prod(upsample_rates) - - def forward(self, x, f0, g=None): - har_source, noi_source, uv = self.m_source(f0, self.upp) - har_source = har_source.transpose(1, 2) - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - x_source = self.noise_convs[i](har_source) - x = x + x_source - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - return x - - def remove_weight_norm(self): - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -sr2sr = { - "32k": 32000, - "40k": 40000, - "48k": 48000, -} - - -class SynthesizerTrnMs256NSFsid(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr, - **kwargs - ): - super().__init__() - if type(sr) == type("strr"): - sr = sr2sr[sr] - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder256( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - ) - self.dec = GeneratorNSF( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - sr=sr, - is_half=kwargs["is_half"], - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward( - self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds - ): # 这里ds是id,[bs,1] - # print(1,pitch.shape)#[bs,t] - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - z_slice, ids_slice = commons.rand_slice_segments( - z, y_lengths, self.segment_size - ) - # print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length) - pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size) - # print(-2,pitchf.shape,z_slice.shape) - o = self.dec(z_slice, pitchf, g=g) - return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, phone, phone_lengths, pitch, nsff0, sid, rate=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask - if rate: - head = int(z_p.shape[2] * rate) - z_p = z_p[:, :, -head:] - x_mask = x_mask[:, :, -head:] - nsff0 = nsff0[:, -head:] - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec(z * x_mask, nsff0, g=g) - return o, x_mask, (z, z_p, m_p, logs_p) - - -class SynthesizerTrnMs768NSFsid(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr, - **kwargs - ): - super().__init__() - if type(sr) == type("strr"): - sr = sr2sr[sr] - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder768( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - ) - self.dec = GeneratorNSF( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - sr=sr, - is_half=kwargs["is_half"], - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward( - self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds - ): # 这里ds是id,[bs,1] - # print(1,pitch.shape)#[bs,t] - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - z_slice, ids_slice = commons.rand_slice_segments( - z, y_lengths, self.segment_size - ) - # print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length) - pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size) - # print(-2,pitchf.shape,z_slice.shape) - o = self.dec(z_slice, pitchf, g=g) - return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, phone, phone_lengths, pitch, nsff0, sid, rate=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask - if rate: - head = int(z_p.shape[2] * rate) - z_p = z_p[:, :, -head:] - x_mask = x_mask[:, :, -head:] - nsff0 = nsff0[:, -head:] - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec(z * x_mask, nsff0, g=g) - return o, x_mask, (z, z_p, m_p, logs_p) - - -class SynthesizerTrnMs256NSFsid_nono(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr=None, - **kwargs - ): - super().__init__() - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder256( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=False, - ) - self.dec = Generator( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1] - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - z_slice, ids_slice = commons.rand_slice_segments( - z, y_lengths, self.segment_size - ) - o = self.dec(z_slice, g=g) - return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, phone, phone_lengths, sid, rate=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask - if rate: - head = int(z_p.shape[2] * rate) - z_p = z_p[:, :, -head:] - x_mask = x_mask[:, :, -head:] - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec(z * x_mask, g=g) - return o, x_mask, (z, z_p, m_p, logs_p) - - -class SynthesizerTrnMs768NSFsid_nono(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr=None, - **kwargs - ): - super().__init__() - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder768( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=False, - ) - self.dec = Generator( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1] - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - z_slice, ids_slice = commons.rand_slice_segments( - z, y_lengths, self.segment_size - ) - o = self.dec(z_slice, g=g) - return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, phone, phone_lengths, sid, rate=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask - if rate: - head = int(z_p.shape[2] * rate) - z_p = z_p[:, :, -head:] - x_mask = x_mask[:, :, -head:] - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec(z * x_mask, g=g) - return o, x_mask, (z, z_p, m_p, logs_p) - - -class MultiPeriodDiscriminator(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(MultiPeriodDiscriminator, self).__init__() - periods = [2, 3, 5, 7, 11, 17] - # periods = [3, 5, 7, 11, 17, 23, 37] - - discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] - discs = discs + [ - DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods - ] - self.discriminators = nn.ModuleList(discs) - - def forward(self, y, y_hat): - y_d_rs = [] # - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y) - y_d_g, fmap_g = d(y_hat) - # for j in range(len(fmap_r)): - # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape) - y_d_rs.append(y_d_r) - y_d_gs.append(y_d_g) - fmap_rs.append(fmap_r) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - - -class MultiPeriodDiscriminatorV2(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(MultiPeriodDiscriminatorV2, self).__init__() - # periods = [2, 3, 5, 7, 11, 17] - periods = [2, 3, 5, 7, 11, 17, 23, 37] - - discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] - discs = discs + [ - DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods - ] - self.discriminators = nn.ModuleList(discs) - - def forward(self, y, y_hat): - y_d_rs = [] # - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y) - y_d_g, fmap_g = d(y_hat) - # for j in range(len(fmap_r)): - # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape) - y_d_rs.append(y_d_r) - y_d_gs.append(y_d_g) - fmap_rs.append(fmap_r) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - - -class DiscriminatorS(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(DiscriminatorS, self).__init__() - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList( - [ - norm_f(Conv1d(1, 16, 15, 1, padding=7)), - norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)), - norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)), - norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)), - norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)), - norm_f(Conv1d(1024, 1024, 5, 1, padding=2)), - ] - ) - self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1)) - - def forward(self, x): - fmap = [] - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap - - -class DiscriminatorP(torch.nn.Module): - def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): - super(DiscriminatorP, self).__init__() - self.period = period - self.use_spectral_norm = use_spectral_norm - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList( - [ - norm_f( - Conv2d( - 1, - 32, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 32, - 128, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 128, - 512, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 512, - 1024, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 1024, - 1024, - (kernel_size, 1), - 1, - padding=(get_padding(kernel_size, 1), 0), - ) - ), - ] - ) - self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0))) - - def forward(self, x): - fmap = [] - - # 1d to 2d - b, c, t = x.shape - if t % self.period != 0: # pad first - n_pad = self.period - (t % self.period) - x = F.pad(x, (0, n_pad), "reflect") - t = t + n_pad - x = x.view(b, c, t // self.period, self.period) - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap diff --git a/spaces/dylanebert/igf/viewer/svelte.config.js b/spaces/dylanebert/igf/viewer/svelte.config.js deleted file mode 100644 index 672d0696ae90c829b8fdf77344809bbc5fb98da6..0000000000000000000000000000000000000000 --- a/spaces/dylanebert/igf/viewer/svelte.config.js +++ /dev/null @@ -1,18 +0,0 @@ -import adapter from "@sveltejs/adapter-node"; -import { vitePreprocess } from "@sveltejs/kit/vite"; - -/** @type {import('@sveltejs/kit').Config} */ -const config = { - // Consult https://kit.svelte.dev/docs/integrations#preprocessors - // for more information about preprocessors - preprocess: vitePreprocess(), - - kit: { - // adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list. - // If your environment is not supported or you settled on a specific environment, switch out the adapter. - // See https://kit.svelte.dev/docs/adapters for more information about adapters. - adapter: adapter(), - }, -}; - -export default config; diff --git a/spaces/eaedk/agri-tech-fastapi-with-GUI/README.md b/spaces/eaedk/agri-tech-fastapi-with-GUI/README.md deleted file mode 100644 index ca89d1b7a604f523fcf00d656935b51560f93abf..0000000000000000000000000000000000000000 --- a/spaces/eaedk/agri-tech-fastapi-with-GUI/README.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Agri Tech FastAPI with GUI -emoji: 🪴 -colorFrom: purple -colorTo: blue -sdk: docker -pinned: false -license: mit -duplicated_from: eaedk/agri-tech-fastapi ---- - -Here is the link to directly access the API: [here](https://eaedk-agri-tech-fastapi.hf.space). -Access the documentation [here](https://eaedk-agri-tech-fastapi.hf.space/docs). - -To direcly access your API hosted on HuggingFace you should use the URL follow this format : `https://-.hf.space/` - -In my case it is : https://eaedk-agri-tech-fastapi.hf.space/ - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/spaces/editing-images/project/static/js/bulma-slider.js b/spaces/editing-images/project/static/js/bulma-slider.js deleted file mode 100644 index c6718de5c5ae59d2c22141a147f5afba41af9cbb..0000000000000000000000000000000000000000 --- a/spaces/editing-images/project/static/js/bulma-slider.js +++ /dev/null @@ -1,461 +0,0 @@ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); - else if(typeof define === 'function' && define.amd) - define([], factory); - else if(typeof exports === 'object') - exports["bulmaSlider"] = factory(); - else - root["bulmaSlider"] = factory(); -})(typeof self !== 'undefined' ? self : this, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { -/******/ configurable: false, -/******/ enumerable: true, -/******/ get: getter -/******/ }); -/******/ } -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isString", function() { return isString; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1); -var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - - - -var isString = function isString(unknown) { - return typeof unknown === 'string' || !!unknown && (typeof unknown === 'undefined' ? 'undefined' : _typeof(unknown)) === 'object' && Object.prototype.toString.call(unknown) === '[object String]'; -}; - -var bulmaSlider = function (_EventEmitter) { - _inherits(bulmaSlider, _EventEmitter); - - function bulmaSlider(selector) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - _classCallCheck(this, bulmaSlider); - - var _this = _possibleConstructorReturn(this, (bulmaSlider.__proto__ || Object.getPrototypeOf(bulmaSlider)).call(this)); - - _this.element = typeof selector === 'string' ? document.querySelector(selector) : selector; - // An invalid selector or non-DOM node has been provided. - if (!_this.element) { - throw new Error('An invalid selector or non-DOM node has been provided.'); - } - - _this._clickEvents = ['click']; - /// Set default options and merge with instance defined - _this.options = _extends({}, options); - - _this.onSliderInput = _this.onSliderInput.bind(_this); - - _this.init(); - return _this; - } - - /** - * Initiate all DOM element containing selector - * @method - * @return {Array} Array of all slider instances - */ - - - _createClass(bulmaSlider, [{ - key: 'init', - - - /** - * Initiate plugin - * @method init - * @return {void} - */ - value: function init() { - this._id = 'bulmaSlider' + new Date().getTime() + Math.floor(Math.random() * Math.floor(9999)); - this.output = this._findOutputForSlider(); - - this._bindEvents(); - - if (this.output) { - if (this.element.classList.contains('has-output-tooltip')) { - // Get new output position - var newPosition = this._getSliderOutputPosition(); - - // Set output position - this.output.style['left'] = newPosition.position; - } - } - - this.emit('bulmaslider:ready', this.element.value); - } - }, { - key: '_findOutputForSlider', - value: function _findOutputForSlider() { - var _this2 = this; - - var result = null; - var outputs = document.getElementsByTagName('output') || []; - - Array.from(outputs).forEach(function (output) { - if (output.htmlFor == _this2.element.getAttribute('id')) { - result = output; - return true; - } - }); - return result; - } - }, { - key: '_getSliderOutputPosition', - value: function _getSliderOutputPosition() { - // Update output position - var newPlace, minValue; - - var style = window.getComputedStyle(this.element, null); - // Measure width of range input - var sliderWidth = parseInt(style.getPropertyValue('width'), 10); - - // Figure out placement percentage between left and right of input - if (!this.element.getAttribute('min')) { - minValue = 0; - } else { - minValue = this.element.getAttribute('min'); - } - var newPoint = (this.element.value - minValue) / (this.element.getAttribute('max') - minValue); - - // Prevent bubble from going beyond left or right (unsupported browsers) - if (newPoint < 0) { - newPlace = 0; - } else if (newPoint > 1) { - newPlace = sliderWidth; - } else { - newPlace = sliderWidth * newPoint; - } - - return { - 'position': newPlace + 'px' - }; - } - - /** - * Bind all events - * @method _bindEvents - * @return {void} - */ - - }, { - key: '_bindEvents', - value: function _bindEvents() { - if (this.output) { - // Add event listener to update output when slider value change - this.element.addEventListener('input', this.onSliderInput, false); - } - } - }, { - key: 'onSliderInput', - value: function onSliderInput(e) { - e.preventDefault(); - - if (this.element.classList.contains('has-output-tooltip')) { - // Get new output position - var newPosition = this._getSliderOutputPosition(); - - // Set output position - this.output.style['left'] = newPosition.position; - } - - // Check for prefix and postfix - var prefix = this.output.hasAttribute('data-prefix') ? this.output.getAttribute('data-prefix') : ''; - var postfix = this.output.hasAttribute('data-postfix') ? this.output.getAttribute('data-postfix') : ''; - - // Update output with slider value - this.output.value = prefix + this.element.value + postfix; - - this.emit('bulmaslider:ready', this.element.value); - } - }], [{ - key: 'attach', - value: function attach() { - var _this3 = this; - - var selector = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'input[type="range"].slider'; - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - var instances = new Array(); - - var elements = isString(selector) ? document.querySelectorAll(selector) : Array.isArray(selector) ? selector : [selector]; - elements.forEach(function (element) { - if (typeof element[_this3.constructor.name] === 'undefined') { - var instance = new bulmaSlider(element, options); - element[_this3.constructor.name] = instance; - instances.push(instance); - } else { - instances.push(element[_this3.constructor.name]); - } - }); - - return instances; - } - }]); - - return bulmaSlider; -}(__WEBPACK_IMPORTED_MODULE_0__events__["a" /* default */]); - -/* harmony default export */ __webpack_exports__["default"] = (bulmaSlider); - -/***/ }), -/* 1 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var EventEmitter = function () { - function EventEmitter() { - var listeners = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - - _classCallCheck(this, EventEmitter); - - this._listeners = new Map(listeners); - this._middlewares = new Map(); - } - - _createClass(EventEmitter, [{ - key: "listenerCount", - value: function listenerCount(eventName) { - if (!this._listeners.has(eventName)) { - return 0; - } - - var eventListeners = this._listeners.get(eventName); - return eventListeners.length; - } - }, { - key: "removeListeners", - value: function removeListeners() { - var _this = this; - - var eventName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - var middleware = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - - if (eventName !== null) { - if (Array.isArray(eventName)) { - name.forEach(function (e) { - return _this.removeListeners(e, middleware); - }); - } else { - this._listeners.delete(eventName); - - if (middleware) { - this.removeMiddleware(eventName); - } - } - } else { - this._listeners = new Map(); - } - } - }, { - key: "middleware", - value: function middleware(eventName, fn) { - var _this2 = this; - - if (Array.isArray(eventName)) { - name.forEach(function (e) { - return _this2.middleware(e, fn); - }); - } else { - if (!Array.isArray(this._middlewares.get(eventName))) { - this._middlewares.set(eventName, []); - } - - this._middlewares.get(eventName).push(fn); - } - } - }, { - key: "removeMiddleware", - value: function removeMiddleware() { - var _this3 = this; - - var eventName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - - if (eventName !== null) { - if (Array.isArray(eventName)) { - name.forEach(function (e) { - return _this3.removeMiddleware(e); - }); - } else { - this._middlewares.delete(eventName); - } - } else { - this._middlewares = new Map(); - } - } - }, { - key: "on", - value: function on(name, callback) { - var _this4 = this; - - var once = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - - if (Array.isArray(name)) { - name.forEach(function (e) { - return _this4.on(e, callback); - }); - } else { - name = name.toString(); - var split = name.split(/,|, | /); - - if (split.length > 1) { - split.forEach(function (e) { - return _this4.on(e, callback); - }); - } else { - if (!Array.isArray(this._listeners.get(name))) { - this._listeners.set(name, []); - } - - this._listeners.get(name).push({ once: once, callback: callback }); - } - } - } - }, { - key: "once", - value: function once(name, callback) { - this.on(name, callback, true); - } - }, { - key: "emit", - value: function emit(name, data) { - var _this5 = this; - - var silent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - - name = name.toString(); - var listeners = this._listeners.get(name); - var middlewares = null; - var doneCount = 0; - var execute = silent; - - if (Array.isArray(listeners)) { - listeners.forEach(function (listener, index) { - // Start Middleware checks unless we're doing a silent emit - if (!silent) { - middlewares = _this5._middlewares.get(name); - // Check and execute Middleware - if (Array.isArray(middlewares)) { - middlewares.forEach(function (middleware) { - middleware(data, function () { - var newData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - - if (newData !== null) { - data = newData; - } - doneCount++; - }, name); - }); - - if (doneCount >= middlewares.length) { - execute = true; - } - } else { - execute = true; - } - } - - // If Middleware checks have been passed, execute - if (execute) { - if (listener.once) { - listeners[index] = null; - } - listener.callback(data); - } - }); - - // Dirty way of removing used Events - while (listeners.indexOf(null) !== -1) { - listeners.splice(listeners.indexOf(null), 1); - } - } - } - }]); - - return EventEmitter; -}(); - -/* harmony default export */ __webpack_exports__["a"] = (EventEmitter); - -/***/ }) -/******/ ])["default"]; -}); \ No newline at end of file diff --git a/spaces/facebook/MusicGen/audiocraft/solvers/diffusion.py b/spaces/facebook/MusicGen/audiocraft/solvers/diffusion.py deleted file mode 100644 index 93dea2520836f458ab1b8514dca952b51d113ec2..0000000000000000000000000000000000000000 --- a/spaces/facebook/MusicGen/audiocraft/solvers/diffusion.py +++ /dev/null @@ -1,279 +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 flashy -import julius -import omegaconf -import torch -import torch.nn.functional as F - -from . import builders -from . import base -from .. import models -from ..modules.diffusion_schedule import NoiseSchedule -from ..metrics import RelativeVolumeMel -from ..models.builders import get_processor -from ..utils.samples.manager import SampleManager -from ..solvers.compression import CompressionSolver - - -class PerStageMetrics: - """Handle prompting the metrics per stage. - It outputs the metrics per range of diffusion states. - e.g. avg loss when t in [250, 500] - """ - def __init__(self, num_steps: int, num_stages: int = 4): - self.num_steps = num_steps - self.num_stages = num_stages - - def __call__(self, losses: dict, step: tp.Union[int, torch.Tensor]): - if type(step) is int: - stage = int((step / self.num_steps) * self.num_stages) - return {f"{name}_{stage}": loss for name, loss in losses.items()} - elif type(step) is torch.Tensor: - stage_tensor = ((step / self.num_steps) * self.num_stages).long() - out: tp.Dict[str, float] = {} - for stage_idx in range(self.num_stages): - mask = (stage_tensor == stage_idx) - N = mask.sum() - stage_out = {} - if N > 0: # pass if no elements in the stage - for name, loss in losses.items(): - stage_loss = (mask * loss).sum() / N - stage_out[f"{name}_{stage_idx}"] = stage_loss - out = {**out, **stage_out} - return out - - -class DataProcess: - """Apply filtering or resampling. - - Args: - initial_sr (int): Initial sample rate. - target_sr (int): Target sample rate. - use_resampling: Whether to use resampling or not. - use_filter (bool): - n_bands (int): Number of bands to consider. - idx_band (int): - device (torch.device or str): - cutoffs (): - boost (bool): - """ - def __init__(self, initial_sr: int = 24000, target_sr: int = 16000, use_resampling: bool = False, - use_filter: bool = False, n_bands: int = 4, - idx_band: int = 0, device: torch.device = torch.device('cpu'), cutoffs=None, boost=False): - """Apply filtering or resampling - Args: - initial_sr (int): sample rate of the dataset - target_sr (int): sample rate after resampling - use_resampling (bool): whether or not performs resampling - use_filter (bool): when True filter the data to keep only one frequency band - n_bands (int): Number of bands used - cuts (none or list): The cutoff frequencies of the band filtering - if None then we use mel scale bands. - idx_band (int): index of the frequency band. 0 are lows ... (n_bands - 1) highs - boost (bool): make the data scale match our music dataset. - """ - assert idx_band < n_bands - self.idx_band = idx_band - if use_filter: - if cutoffs is not None: - self.filter = julius.SplitBands(sample_rate=initial_sr, cutoffs=cutoffs).to(device) - else: - self.filter = julius.SplitBands(sample_rate=initial_sr, n_bands=n_bands).to(device) - self.use_filter = use_filter - self.use_resampling = use_resampling - self.target_sr = target_sr - self.initial_sr = initial_sr - self.boost = boost - - def process_data(self, x, metric=False): - if x is None: - return None - if self.boost: - x /= torch.clamp(x.std(dim=(1, 2), keepdim=True), min=1e-4) - x * 0.22 - if self.use_filter and not metric: - x = self.filter(x)[self.idx_band] - if self.use_resampling: - x = julius.resample_frac(x, old_sr=self.initial_sr, new_sr=self.target_sr) - return x - - def inverse_process(self, x): - """Upsampling only.""" - if self.use_resampling: - x = julius.resample_frac(x, old_sr=self.target_sr, new_sr=self.target_sr) - return x - - -class DiffusionSolver(base.StandardSolver): - """Solver for compression task. - - The diffusion task allows for MultiBand diffusion model training. - - Args: - cfg (DictConfig): Configuration. - """ - def __init__(self, cfg: omegaconf.DictConfig): - super().__init__(cfg) - self.cfg = cfg - self.device = cfg.device - self.sample_rate: int = self.cfg.sample_rate - self.codec_model = CompressionSolver.model_from_checkpoint( - cfg.compression_model_checkpoint, device=self.device) - - self.codec_model.set_num_codebooks(cfg.n_q) - assert self.codec_model.sample_rate == self.cfg.sample_rate, ( - f"Codec model sample rate is {self.codec_model.sample_rate} but " - f"Solver sample rate is {self.cfg.sample_rate}." - ) - assert self.codec_model.sample_rate == self.sample_rate, \ - f"Sample rate of solver {self.sample_rate} and codec {self.codec_model.sample_rate} " \ - "don't match." - - self.sample_processor = get_processor(cfg.processor, sample_rate=self.sample_rate) - self.register_stateful('sample_processor') - self.sample_processor.to(self.device) - - self.schedule = NoiseSchedule( - **cfg.schedule, device=self.device, sample_processor=self.sample_processor) - - self.eval_metric: tp.Optional[torch.nn.Module] = None - - self.rvm = RelativeVolumeMel() - self.data_processor = DataProcess(initial_sr=self.sample_rate, target_sr=cfg.resampling.target_sr, - use_resampling=cfg.resampling.use, cutoffs=cfg.filter.cutoffs, - use_filter=cfg.filter.use, n_bands=cfg.filter.n_bands, - idx_band=cfg.filter.idx_band, device=self.device) - - @property - def best_metric_name(self) -> tp.Optional[str]: - if self._current_stage == "evaluate": - return 'rvm' - else: - return 'loss' - - @torch.no_grad() - def get_condition(self, wav: torch.Tensor) -> torch.Tensor: - codes, scale = self.codec_model.encode(wav) - assert scale is None, "Scaled compression models not supported." - emb = self.codec_model.decode_latent(codes) - return emb - - def build_model(self): - """Build model and optimizer as well as optional Exponential Moving Average of the model. - """ - # Model and optimizer - self.model = models.builders.get_diffusion_model(self.cfg).to(self.device) - self.optimizer = builders.get_optimizer(self.model.parameters(), self.cfg.optim) - self.register_stateful('model', 'optimizer') - self.register_best_state('model') - self.register_ema('model') - - def build_dataloaders(self): - """Build audio dataloaders for each stage.""" - self.dataloaders = builders.get_audio_datasets(self.cfg) - - def show(self): - # TODO - raise NotImplementedError() - - def run_step(self, idx: int, batch: torch.Tensor, metrics: dict): - """Perform one training or valid step on a given batch.""" - x = batch.to(self.device) - loss_fun = F.mse_loss if self.cfg.loss.kind == 'mse' else F.l1_loss - - condition = self.get_condition(x) # [bs, 128, T/hop, n_emb] - sample = self.data_processor.process_data(x) - - input_, target, step = self.schedule.get_training_item(sample, - tensor_step=self.cfg.schedule.variable_step_batch) - out = self.model(input_, step, condition=condition).sample - - base_loss = loss_fun(out, target, reduction='none').mean(dim=(1, 2)) - reference_loss = loss_fun(input_, target, reduction='none').mean(dim=(1, 2)) - loss = base_loss / reference_loss ** self.cfg.loss.norm_power - - if self.is_training: - loss.mean().backward() - flashy.distrib.sync_model(self.model) - self.optimizer.step() - self.optimizer.zero_grad() - metrics = { - 'loss': loss.mean(), 'normed_loss': (base_loss / reference_loss).mean(), - } - metrics.update(self.per_stage({'loss': loss, 'normed_loss': base_loss / reference_loss}, step)) - metrics.update({ - 'std_in': input_.std(), 'std_out': out.std()}) - return metrics - - def run_epoch(self): - # reset random seed at the beginning of the epoch - self.rng = torch.Generator() - self.rng.manual_seed(1234 + self.epoch) - self.per_stage = PerStageMetrics(self.schedule.num_steps, self.cfg.metrics.num_stage) - # run epoch - super().run_epoch() - - def evaluate(self): - """Evaluate stage. - Runs audio reconstruction evaluation. - """ - self.model.eval() - evaluate_stage_name = f'{self.current_stage}' - loader = self.dataloaders['evaluate'] - updates = len(loader) - lp = self.log_progress(f'{evaluate_stage_name} estimate', loader, total=updates, updates=self.log_updates) - - metrics = {} - n = 1 - for idx, batch in enumerate(lp): - x = batch.to(self.device) - with torch.no_grad(): - y_pred = self.regenerate(x) - - y_pred = y_pred.cpu() - y = batch.cpu() # should already be on CPU but just in case - rvm = self.rvm(y_pred, y) - lp.update(**rvm) - if len(metrics) == 0: - metrics = rvm - else: - for key in rvm.keys(): - metrics[key] = (metrics[key] * n + rvm[key]) / (n + 1) - metrics = flashy.distrib.average_metrics(metrics) - return metrics - - @torch.no_grad() - def regenerate(self, wav: torch.Tensor, step_list: tp.Optional[list] = None): - """Regenerate the given waveform.""" - condition = self.get_condition(wav) - initial = self.schedule.get_initial_noise(self.data_processor.process_data(wav)) # sampling rate changes. - result = self.schedule.generate_subsampled(self.model, initial=initial, condition=condition, - step_list=step_list) - result = self.data_processor.inverse_process(result) - return result - - def generate(self): - """Generate stage.""" - sample_manager = SampleManager(self.xp) - self.model.eval() - generate_stage_name = f'{self.current_stage}' - - loader = self.dataloaders['generate'] - updates = len(loader) - lp = self.log_progress(generate_stage_name, loader, total=updates, updates=self.log_updates) - - for batch in lp: - reference, _ = batch - reference = reference.to(self.device) - estimate = self.regenerate(reference) - reference = reference.cpu() - estimate = estimate.cpu() - sample_manager.add_samples(estimate, self.epoch, ground_truth_wavs=reference) - flashy.distrib.barrier() diff --git a/spaces/falterWliame/Face_Mask_Detection/PhotoGrav 3.0-torrent.zip.md b/spaces/falterWliame/Face_Mask_Detection/PhotoGrav 3.0-torrent.zip.md deleted file mode 100644 index bd740ce98676870d5fd11b28715288765d397d0b..0000000000000000000000000000000000000000 --- a/spaces/falterWliame/Face_Mask_Detection/PhotoGrav 3.0-torrent.zip.md +++ /dev/null @@ -1,6 +0,0 @@ -

    PhotoGrav 3.0-torrent.zip


    DOWNLOADhttps://urlca.com/2uDdGE



    - - d5da3c52bf
    -
    -
    -

    diff --git a/spaces/fatiXbelha/sd/APKPure The Fastest and Easiest Way to Download Real Racing 3.md b/spaces/fatiXbelha/sd/APKPure The Fastest and Easiest Way to Download Real Racing 3.md deleted file mode 100644 index 4b5ba95fc3b982207b9f89cec3e696ff5dd8afd3..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/APKPure The Fastest and Easiest Way to Download Real Racing 3.md +++ /dev/null @@ -1,95 +0,0 @@ - -

    Real Racing 3 APKPure Download: How to Get the Best Racing Game on Your Android Device

    -

    Introduction

    -

    If you are a fan of racing games, you have probably heard of Real Racing 3, one of the most popular and realistic racing games on mobile devices. But did you know that you can download it from APKPure, a website that offers free and safe APK files for Android apps and games? In this article, we will show you how to download and install Real Racing 3 from APKPure, and what features and benefits you can enjoy from this amazing game.

    -

    real racing 3 apkpure download


    DOWNLOAD ——— https://urllie.com/2uNxD3



    -

    What is Real Racing 3?

    -

    Real Racing 3 is a racing game developed by Firemonkeys Studios and published by Electronic Arts. It was released in 2013 for iOS and Android devices, and has since received many updates and expansions. It is the third installment in the Real Racing series, following Real Racing and Real Racing 2.

    -

    Why download Real Racing 3 from APKPure?

    -

    There are many reasons why you might want to download Real Racing 3 from APKPure, instead of from the official Google Play Store. Here are some of them:

    -
      -
    • You can get the latest version of the game without waiting for the official update.
    • -
    • You can access the game even if it is not available in your region or country.
    • -
    • You can save storage space on your device by downloading only the APK file, instead of the whole game data.
    • -
    • You can avoid ads and in-app purchases that might interrupt your gaming experience.
    • -
    -

    How to download and install Real Racing 3 from APKPure

    -

    Downloading and installing Real Racing 3 from APKPure is very easy and fast. Just follow these simple steps:

    -

    Step 1: Go to the APKPure website

    -

    Open your browser and go to https://apkpure.com/, the official website of APKPure. You will see a search bar at the top of the page, where you can type in any app or game name.

    -

    Step 2: Search for Real Racing 3

    -

    Type in "Real Racing 3" in the search bar and hit enter. You will see a list of results, with the game icon, name, rating, and description. Click on the one that says "Real Racing 3".

    -

    Step 3: Download the APK file

    -

    You will be taken to the game page, where you can see more information about the game, such as screenshots, videos, reviews, and version history. You will also see a green button that says "Download APK". Click on it and wait for the download to start. The file size is about 40 MB.

    -

    real racing 3 apk free download for android
    -real racing 3 mod apk unlimited money and gold apkpure
    -real racing 3 latest version apk download
    -real racing 3 offline apk download
    -real racing 3 apk + obb download
    -real racing 3 apk download for pc
    -real racing 3 hack apk download apkpure
    -real racing 3 apk download uptodown
    -real racing 3 apk download for ios
    -real racing 3 apk download rexdl
    -real racing 3 apk download highly compressed
    -real racing 3 apk download old version
    -real racing 3 apk download android 1
    -real racing 3 apk download revdl
    -real racing 3 apk download apkmirror
    -real racing 3 apk download mob.org
    -real racing 3 apk download pure
    -real racing 3 apk download android oyun club
    -real racing 3 apk download moddroid
    -real racing 3 apk download happymod
    -real racing 3 apk download apkpure.com
    -real racing 3 apk download for android phone
    -real racing 3 apk download no root
    -real racing 3 apk download without obb
    -real racing 3 apk download full version
    -real racing 3 apk download mega.nz
    -real racing 3 apk download google drive
    -real racing 3 apk download mediafire.com
    -real racing 3 apk download update
    -real racing 3 apk download new version
    -real racing 3 apk + data download for android
    -real racing 3 modded apk free download apkpure
    -real racing 3 unlimited money and gold apk free download apkpure
    -real racing 3 cracked apk free download apkpure
    -real racing 3 premium cars unlocked apk free download apkpure
    -real racing 3 all cars unlocked mod apk free download apkpure
    -real racing 3 mod menu apk free download apkpure
    -real racing 3 cheats android free download apkpure
    -real racing 3 hack tool free download apkpure
    -real racing 3 generator no human verification free download apkpure

    -

    Step 4: Enable unknown sources on your device

    -

    Before you can install 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, then security, then unknown sources. Toggle it on and confirm your choice.

    -

    Step 5: Install the APK file

    -

    Once the download is complete, go to your file manager and locate the APK file. Tap on it and follow the instructions to install it on your device. You will see a confirmation message that says "App installed". Congratulations, you have successfully installed Real Racing 3 from APKPure!

    -

    Features and benefits of Real Racing 3

    -

    Now that you have Real Racing 3 on your device, you can enjoy its amazing features and benefits. Here are some of them:

    -

    Realistic graphics and physics

    -

    Real Racing 3 boasts of stunning graphics and realistic physics that will make you feel like you are driving a real car. The game uses the Mint 3 Engine, which delivers detailed car damage, dynamic reflections, and fully functioning rearview mirrors. The game also simulates the effects of weather, time of day, and tire wear on your driving performance.

    -

    Over 250 cars and 40 tracks

    -

    Real Racing 3 offers a huge variety of cars and tracks to choose from. You can race with over 250 cars from 33 manufacturers, including Ferrari, Lamborghini, Porsche, Bugatti, and more. You can also race on 40 tracks from 19 real-world locations, such as Silverstone, Le Mans, Dubai Autodrome, and more.

    -

    Multiplayer and single-player modes

    -

    Real Racing 3 lets you compete with other players online or offline. You can join the Time Trial mode, where you can race against your own best time or the ghost of another player. You can also join the Real-Time Multiplayer mode, where you can race with up to eight players in real-time. Or you can join the Time Shifted Multiplayer mode, where you can race with anyone at any time, even if they are offline.

    -

    Customization and upgrades

    -

    Real Racing 3 allows you to customize and upgrade your cars to suit your preferences and needs. You can change the color, paint, vinyls, wheels, and license plates of your cars. You can also upgrade the engine, brakes, suspension, tires, and more of your cars. You can earn money and gold by completing races and events, or you can buy them with real money.

    -

    Conclusion

    -

    Real Racing 3 is one of the best racing games on mobile devices. It has realistic graphics and physics, over 250 cars and 40 tracks, multiplayer and single-player modes, customization and upgrades, and more. You can download it from APKPure, a website that offers free and safe APK files for Android apps and games. Just follow the steps we have shown you in this article, and you will be able to enjoy this amazing game on your device.

    -

    FAQs

    -

    Here are some frequently asked questions about Real Racing 3 APKPure download:

    -
      -
    1. Is Real Racing 3 APKPure download safe?
    2. -

      Yes, Real Racing 3 APKPure download is safe. APKPure is a reputable website that verifies the security of all the APK files it offers. It also scans them for viruses and malware before uploading them to its servers. You can download Real Racing 3 from APKPure without any worries.

      -
    3. Is Real Racing 3 APKPure download free?
    4. -

      Yes, Real Racing 3 APKPure download is free. You do not need to pay anything to download the APK file from APKPure. However, the game itself may have some in-app purchases that require real money.

      -
    5. Is Real Racing 3 APKPure download compatible with my device?
    6. -

      Real Racing 3 APKPure download is compatible with most Android devices that run on Android 4.1 or higher. However, some devices may have different specifications that may affect the game performance or compatibility. You can check the game requirements on the APKPure website before downloading it.

      -
    7. How do I update Real Racing 3 APKPure download?
    8. -

      You can update Real Racing 3 APKPure download by visiting the APKPure website again and downloading the latest version of the game. You do not need to uninstall the previous version of the game before installing the new one.

      -
    9. How do I uninstall Real Racing 3 APKPure download?
    10. -

      You can uninstall Real Racing 3 APKPure download by going to your device settings, then apps, then Real Racing 3. Tap on it and select uninstall. You can also delete the APK file from your file manager if you want to free up some space.

      -

    197e85843d
    -
    -
    \ No newline at end of file diff --git a/spaces/fatiXbelha/sd/Download Modified Candy Crush Saga APK and Enjoy All Unlocked Features.md b/spaces/fatiXbelha/sd/Download Modified Candy Crush Saga APK and Enjoy All Unlocked Features.md deleted file mode 100644 index 2abfd409f3af2382cc675a1489ffe1e9a4c6235c..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Download Modified Candy Crush Saga APK and Enjoy All Unlocked Features.md +++ /dev/null @@ -1,130 +0,0 @@ -
    -

    Modified Candy Crush Saga APK: What You Need to Know

    -

    If you are a fan of match-3 puzzle games, you have probably heard of or played Candy Crush Saga, one of the most popular and addictive games in this genre. But did you know that there is a way to enjoy this game with more features and functions than the original version? In this article, we will tell you everything you need to know about a modified Candy Crush Saga APK, including what it is, how to get it, and how to use it. Read on to find out more!

    -

    modified candy crush saga apk


    Download Ziphttps://urllie.com/2uNx1J



    -

    What is Candy Crush Saga?

    -

    Candy Crush Saga is a match-3 puzzle game developed by King, a leading mobile game developer. It was released in 2012 for Facebook, and later for Android, iOS, Windows Phone, and other platforms. The game has over 1 billion downloads on Google Play Store and is one of the most successful games of all time.

    -

    The gameplay of Candy Crush Saga

    -

    The gameplay of Candy Crush Saga is simple but addictive. You have to match three or more candies of the same color to clear them from the board and earn points. You can also create special candies by matching four or more candies in different shapes, such as striped, wrapped, or color bomb candies. These special candies can help you clear more candies and create more combos. You have to complete different objectives in each level, such as reaching a target score, clearing the jelly, or collecting the ingredients. There are thousands of levels in the game, each with different challenges and surprises.

    -

    The popularity of Candy Crush Saga

    -

    Candy Crush Saga is not only a fun and relaxing game, but also a social and competitive one. You can connect with your Facebook friends and see their progress on the map. You can also send and receive lives and boosters from them. Boosters are helpful items that can help you overcome difficult levels, such as lollipop hammers, extra moves, or free switches. You can also compete with your friends and other players in the leaderboards and events. The game also offers daily rewards, such as spinning the booster wheel or playing the daily puzzle.

    -

    What is a modified APK?

    -

    An APK (Android Package Kit) is a file format that contains the code, resources, and metadata of an Android application. It is the file that you download and install when you get an app from Google Play Store or other sources. A modified APK is an APK that has been altered or hacked by someone to change some aspects of the original app, such as adding new features, removing ads, unlocking premium content, or bypassing restrictions.

    -

    * candy crush saga mod apk unlimited everything
    -* candy crush saga hack apk download free
    -* candy crush saga mod apk latest version 2023
    -* candy crush saga mod apk android 1
    -* candy crush saga mod apk offline
    -* candy crush saga mod apk unlimited gold bars
    -* candy crush saga mod apk revdl
    -* candy crush saga mod apk no root
    -* candy crush saga mod apk unlimited lives and boosters
    -* candy crush saga mod apk unlimited moves
    -* candy crush saga mod apk rexdl
    -* candy crush saga mod apk happymod
    -* candy crush saga mod apk all levels unlocked
    -* candy crush saga mod apk pure
    -* candy crush saga mod apk unlimited everything 2023
    -* candy crush saga hack apk free download for android
    -* candy crush saga mod apk unlimited gold and lives
    -* candy crush saga mod apk for pc
    -* candy crush saga mod apk unlimited boosters and lives
    -* candy crush saga mod apk with facebook connect
    -* candy crush saga mod apk unlimited moves and lives
    -* candy crush saga hack apk latest version download
    -* candy crush saga mod apk unlimited everything android
    -* candy crush saga mod apk online
    -* candy crush saga mod apk no ads
    -* candy crush saga hack apk ios
    -* candy crush saga mod apk unlimited everything 2022
    -* candy crush saga mod apk download for android 2023
    -* candy crush saga mod apk unlimited gold bars and lives
    -* candy crush saga mod apk without root
    -* candy crush saga hack apk 2023 download free
    -* candy crush saga mod apk all episodes unlocked
    -* candy crush saga mod apk with facebook login
    -* candy crush saga hack apk no survey no password
    -* candy crush saga mod apk unlimited everything 2021
    -* candy crush saga hack apk download for pc
    -* candy crush saga mod apk unlimited gold bars and moves
    -* candy crush saga hack apk android 1 com
    -* candy crush saga hack apk free download for pc
    -* candy crush saga hack apk online generator

    -

    The definition and purpose of a modified APK

    -

    A modified APK is usually created by third-party developers or hackers who want to enhance or customize an app according to their preferences or needs. They may do this for various reasons, such as improving the user experience, providing more options, fixing bugs, or cracking paid features. A modified APK may also be created for malicious purposes, such as stealing personal information, spreading malware, or damaging devices.

    -

    The benefits and risks of using a modified APK

    -

    Using a modified APK can have some benefits and risks depending on the source and quality of the modification. Some of the possible benefits are:

    -
      -
    • You can access features that are not available in the original app, such as unlimited lives, moves, boosters, gold bars, or levels in Candy Crush Saga.
    • -
    • You can enjoy the app without annoying ads or in-app purchases

      Some of the possible risks are:

      -
        -
      • You may violate the terms and conditions of the original app developer or the platform, and risk getting banned or suspended from using the app or the service.
      • -
      • You may expose your device or data to security threats, such as viruses, malware, spyware, or phishing.
      • -
      • You may experience performance issues, such as crashes, glitches, errors, or compatibility problems.
      • -
      -

      Therefore, you should be careful and cautious when using a modified APK, and only download it from trusted and reputable sources. You should also scan the file with an antivirus software before installing it, and backup your data regularly.

      -

      What is a modified Candy Crush Saga APK?

      -

      A modified Candy Crush Saga APK is a version of the game that has been modified by someone to offer more features and functions than the original one. There are many types of modified Candy Crush Saga APKs available on the internet, each with different modifications and enhancements. Some of the common features and functions of a modified Candy Crush Saga APK are:

      -

      The features and functions of a modified Candy Crush Saga APK

      -
        -
      • Unlimited lives, moves, boosters, gold bars, or levels. This means that you can play the game without worrying about running out of resources or reaching the end of the game. You can also skip or replay any level you want.
      • -
      • Unlocked episodes, worlds, modes, or characters. This means that you can access all the content of the game without having to complete certain requirements or pay for them.
      • -
      • Removed ads or in-app purchases. This means that you can enjoy the game without any interruptions or distractions. You can also save money by not having to buy anything from the game.
      • -
      • Improved graphics, sounds, or animations. This means that you can experience the game with better quality and effects.
      • -
      -

      The sources and methods of downloading a modified Candy Crush Saga APK

      -

      There are many websites and platforms that offer modified Candy Crush Saga APKs for free download. Some of the popular ones are:

      -
        -
      • [APKPure]. This is a website that provides various APK files for Android apps and games. You can find a modified Candy Crush Saga APK by searching for it on the website or browsing through the categories.
      • -
      • [HappyMod]. This is a platform that allows users to download and share modded APK files for Android apps and games. You can find a modified Candy Crush Saga APK by searching for it on the platform or browsing through the tags.
      • -
      • [ACMarket]. This is an app store that offers cracked and modded APK files for Android apps and games. You can find a modified Candy Crush Saga APK by downloading and installing the app store on your device, and then searching for it on the app store.
      • -
      -

      To download a modified Candy Crush Saga APK from any of these sources, you need to follow these steps:

      -
        -
      1. Go to the website or platform that offers the modified Candy Crush Saga APK you want to download.
      2. -
      3. Find and select the modified Candy Crush Saga APK you want to download.
      4. -
      5. Click on the download button or link to start downloading the file.
      6. -
      7. Wait for the download to finish.
      8. -
      -

      How to install and use a modified Candy Crush Saga APK?

      -

      After downloading a modified Candy Crush Saga APK, you need to install it on your device and use it properly. However, before doing so, you need to take some precautions and prerequisites to ensure a safe and smooth installation and usage.

      -

      The prerequisites and precautions for installing a modified Candy Crush Saga APK

      -
        -
      • You need to have an Android device that meets the minimum requirements of the game, such as Android version 4.4 or higher, 1 GB of RAM, and 100 MB of free storage space.
      • -
      • You need to enable unknown sources on your device settings. This will allow you to install apps from sources other than Google Play Store. To do this, go to Settings > Security > Unknown Sources and toggle it on.
      • -
      • You need to uninstall or disable the original Candy Crush Saga app if you have it on your device. This will prevent any conflicts or errors between the two versions of the game.
      • -
      • You need to backup your data before installing a modified Candy Crush Saga APK. This will help you restore your data in case something goes wrong during or after the installation. You can use an app like [Helium] or [Titanium Backup] to backup your data.
      • -
      -

      The steps and tips for installing and using a modified Candy Crush Saga APK

      -

      After taking the prerequisites and precautions, you can proceed to install and use a modified Candy Crush Saga APK by following these steps:

      -
        -
      1. Locate the downloaded modified Candy Crush Saga APK file on your device storage. You can use a file manager app like [ES File Explorer] or [File Manager] to find it.
      2. -
      3. Tap on the file to open it and start the installation process. You may see a warning message that says the file may harm your device. Ignore it and tap on Install anyway.
      4. -
      5. Wait for the installation to finish. You may see a confirmation message that says the app was installed successfully.
      6. -
      7. Tap on Open to launch the modified Candy Crush Saga app. You may see a splash screen or a loading screen before the game starts.
      8. -
      9. Enjoy the game with the modified features and functions. You can check the settings or the menu to see the options and preferences available.
      10. -
      -

      Some tips for installing and using a modified Candy Crush Saga APK are:

      -
        -
      • Make sure you have a stable internet connection when downloading and installing a modified Candy Crush Saga APK. This will prevent any interruptions or errors during the process.
      • -
      • Make sure you have enough battery power when installing and using a modified Candy Crush Saga APK. This will prevent any sudden shutdowns or crashes during the game.
      • -
      • Make sure you update your modified Candy Crush Saga APK regularly. This will ensure that you have the latest version of the game with the newest features and functions.
      • -
      -

      Conclusion

      -

      Candy Crush Saga is one of the most popular and addictive match-3 puzzle games in the world. However, if you want to enjoy this game with more features and functions than the original one, you can try using a modified Candy Crush Saga APK. A modified Candy Crush Saga APK is a version of the game that has been altered or hacked by someone to offer more benefits and options, such as unlimited lives, moves, boosters, gold bars, or levels, unlocked episodes, worlds, modes, or characters, removed ads or in-app purchases, or improved graphics, sounds, or animations. However, using a modified Candy Crush Saga APK also comes with some risks and challenges, such as violating the terms and conditions of the original app developer or the platform, exposing your device or data to security threats, or experiencing performance issues. Therefore, you should be careful and cautious when using a modified Candy Crush Saga APK, and only download it from trusted and reputable sources. You should also scan the file with an antivirus software before installing it, backup your data regularly, enable unknown sources on your device settings, uninstall or disable the original Candy Crush Saga app if you have it on your device, and follow the steps and tips for installing and using a modified Candy Crush Saga APK properly.

      -

      If you are ready to take your Candy Crush Saga experience to the next level, download a modified Candy Crush Saga APK today and have fun!

      -

      Frequently Asked Questions

      -

      Here are some of the frequently asked questions about a modified Candy Crush Saga APK:

      -
        -
      • Q: Is using a modified Candy Crush Saga APK legal?
      • -
      • A: Using a modified Candy Crush Saga APK may not be illegal in some countries or regions, but it may violate the terms and conditions of the original app developer or the platform. This may result in legal actions or penalties from them.
      • -
      • Q: Is using a modified Candy Crush Saga APK safe?
      • -
      • A: Using a modified Candy Crush Saga APK may not be safe in some cases, as it may expose your device or data to security threats, such as viruses, malware, spyware, or phishing. It may also cause performance issues, such as crashes, glitches, errors, or compatibility problems.
      • -
      • Q: How can I get rid of a modified Candy Crush Saga APK?
      • -
      • A: If you want to get rid of a modified Candy Crush Saga APK from your device, you can uninstall it like any other app. To do this, go to Settings > Apps > Modified Candy Crush Saga > Uninstall and confirm your action. You can also delete the downloaded file from your device storage.
      • -
      • Q: Can I use both the original and the modified Candy Crush Saga app on my device?
      • -
      • A: No, you cannot use both the original and the modified Candy Crush Saga app on your device at the same time. This may cause conflicts or errors between the two versions of the game. You have to uninstall or disable one of them before installing or using the other one.
      • -
      • Q: Can I play online or offline with a modified Candy Crush Saga APK?
      • A: You can play online or offline with a modified Candy Crush Saga APK, depending on the type and quality of the modification. Some modified Candy Crush Saga APKs may allow you to play online with other players or sync your progress with your Facebook account. However, some modified Candy Crush Saga APKs may not work online or may be detected and blocked by the original app developer or the platform. Therefore, you should be careful and cautious when playing online with a modified Candy Crush Saga APK, and only use it from trusted and reputable sources.
      • -

      197e85843d
      -
      -
      \ No newline at end of file diff --git a/spaces/fatiXbelha/sd/Download and Install ODBC Driver for SQL Server on Linux Systems.md b/spaces/fatiXbelha/sd/Download and Install ODBC Driver for SQL Server on Linux Systems.md deleted file mode 100644 index 16f8f3736235812e21db3f6903b41f8d34fc1d28..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Download and Install ODBC Driver for SQL Server on Linux Systems.md +++ /dev/null @@ -1,160 +0,0 @@ - -

      How to Download and Install ODBC for Linux

      -

      If you want to access different databases from a single application on Linux, you may need to use ODBC. ODBC stands for Open Database Connectivity and it is an industry-standard interface for database access. In this article, we will explain what ODBC is, why you need it, how to download and install it on Linux, how to use it, and some common issues and troubleshooting tips.

      -

      download odbc for linux


      Download File --->>> https://urllie.com/2uNxm6



      -

      What is ODBC and Why Do You Need It?

      -

      ODBC stands for Open Database Connectivity

      -

      ODBC is an application programming interface (API) that allows applications to communicate with various database management systems (DBMS) using SQL as the database access language. ODBC consists of four components: an application that calls ODBC functions, an ODBC driver that implements the ODBC API and communicates with a specific DBMS, a driver manager that loads and unloads drivers and passes function calls from the application to the driver, and a data source that contains the information needed to connect to a DBMS.

      -

      ODBC allows you to access different databases from a single application

      -

      With ODBC, you can write an application that can access data from different databases without having to know the details of each DBMS. For example, you can use ODBC to access data from SQL Server, Oracle, MySQL, PostgreSQL, SQLite, MongoDB, and many other databases. This way, you can avoid writing different code for each database and reduce the complexity and maintenance cost of your application.

      -

      ODBC has many benefits, such as interoperability, portability, and performance

      -

      Some of the benefits of using ODBC are:

      -
        -
      • Interoperability: ODBC enables applications to work with different databases across different platforms (Windows, Linux, macOS) and languages (C/C++, Java, Python, etc.).
      • -
      • Portability: ODBC allows applications to be easily moved from one platform or database to another without requiring major changes in the code.
      • -
      • Performance: ODBC drivers are optimized for specific databases and can provide fast and efficient data access.
      • -
      -

      How to Download ODBC for Linux

      -

      There are different versions and distributions of ODBC for Linux

      -

      The official Microsoft website provides various versions of the Microsoft ODBC Driver for SQL Server on Linux. The latest version is 18.2.2 as of June 2023. The previous versions are 17.10.4 (June 2022. ), 17.7.2 (June 2021), and 17.6.1 (June 2020). You can also find other distributions of ODBC for Linux, such as unixODBC, iODBC, FreeTDS, and Easysoft.

      -

      How to install odbc driver for sql server on linux
      -Configure odbc connection for linux using snowflake
      -Download and verify microsoft odbc driver 18 for linux
      -Odbc driver for linux alpine debian ubuntu
      -Odbc driver for linux red hat enterprise oracle suse
      -Install odbc driver for sql server on linux with yum
      -Install odbc driver for sql server on linux with rpm
      -Install odbc driver for sql server on linux with deb
      -Install odbc driver for sql server on linux with tgz
      -Set environment variables for odbc driver on linux
      -Define odbc data sources in odbc.ini file on linux
      -Define odbc driver in .odbcinst.ini file on linux
      -Configure drill odbc driver on linux
      -Test odbc driver connection on linux with isql
      -Troubleshoot odbc driver installation issues on linux
      -Download and import snowflake gpg public key for odbc driver on linux
      -Verify the signature for the rpm or deb odbc driver package on linux
      -Install unixodbc or iodbc driver manager on linux
      -Install optional command-line tools for sql server (bcp and sqlcmd) on linux
      -Download previous versions of microsoft odbc driver for sql server on linux
      -Update microsoft odbc driver for sql server on linux
      -Uninstall microsoft odbc driver for sql server on linux
      -Enable kerberos authentication for odbc driver on linux
      -Enable ssl encryption for odbc driver on linux
      -Enable logging and tracing for odbc driver on linux
      -Configure connection pooling for odbc driver on linux
      -Configure failover support for odbc driver on linux
      -Configure query timeout and cancelation support for odbc driver on linux
      -Configure bulk copy support for odbc driver on linux
      -Configure utf-8 support for odbc driver on linux
      -Configure regional settings and locale support for odbc driver on linux
      -Configure date and time data type mapping for odbc driver on linux
      -Configure decimal data type mapping for odbc driver on linux
      -Configure binary data type mapping for odbc driver on linux
      -Configure xml data type mapping for odbc driver on linux
      -Configure json data type mapping for odbc driver on linux
      -Configure spatial data type mapping for odbc driver on linux
      -Configure table-valued parameter support for odbc driver on linux
      -Configure multiple active result sets support for odbc driver on linux
      -Configure always encrypted support for odbc driver on linux
      -Configure azure active directory authentication support for odbc driver on linux
      -Configure azure key vault support for odbc driver on linux
      -Use pyodbc module to connect to sql server from python on linux
      -Use rjdbc package to connect to sql server from r on linux
      -Use node-mssql module to connect to sql server from node.js on linux
      -Use php-sqlsrv extension to connect to sql server from php on linux
      -Use ruby-sqlserver gem to connect to sql server from ruby on linux
      -Use go-mssqldb package to connect to sql server from go on linux
      -Use erlang_odbc library to connect to sql server from erlang on linux

      -

      You can download ODBC for Linux from the official Microsoft website or from other sources

      -

      To download the Microsoft ODBC Driver for SQL Server on Linux, you can visit the official Microsoft website and choose the version and distribution that suits your needs. You can also download the driver from other sources, such as GitHub, Packagecloud, or your Linux distribution's repository.

      -

      You can choose between TGZ file, RPM package, or DEB package depending on your Linux distribution

      -

      The Microsoft ODBC Driver for SQL Server on Linux is available in three formats: TGZ file, RPM package, or DEB package. The TGZ file is a compressed archive that contains the driver files and can be extracted to any location on your Linux system. The RPM package is a binary package that can be installed using the rpm command on Red Hat-based distributions, such as CentOS, Fedora, or Oracle Linux. The DEB package is a binary package that can be installed using the dpkg command on Debian-based distributions, such as Ubuntu, Debian, or Linux Mint.

      -

      How to Install ODBC for Linux

      -

      You need to have a driver manager, such as iODBC or unixODBC, installed on your Linux system

      -

      A driver manager is a software component that manages the loading and unloading of ODBC drivers and passes function calls from the application to the driver. You need to have a driver manager installed on your Linux system before you can install and use the ODBC driver. The most common driver managers for Linux are iODBC and unixODBC. You can install them using your Linux distribution's package manager or by downloading them from their respective websites .

      -

      You need to verify the package signature (optional) and install the ODBC driver using the bash shell

      -

      Before you install the ODBC driver, you may want to verify the package signature to ensure its authenticity and integrity. You can do this by downloading the public key from the Microsoft website and importing it into your system's keyring. Then, you can use the gpg command to verify the signature of the downloaded package.

      -

      To install the ODBC driver using the bash shell, you need to follow these steps:

      -
        -
      1. Navigate to the directory where you downloaded the package.
      2. -
      3. If you downloaded a TGZ file, extract it using the tar command: tar xzvf msodbcsql-18.2.2.tar.gz
      4. -
      5. If you downloaded an RPM package, install it using the rpm command: sudo rpm -Uvh msodbcsql-18.2.2.x86_64.rpm
      6. -
      7. If you downloaded a DEB package, install it using the dpkg command: sudo dpkg -i msodbcsql-18.2.2.amd64.deb
      8. -
      9. Verify that the installation was successful by running the odbcinst command: odbcinst -q -d -n "ODBC Driver 18 for SQL Server"
      10. -
      -

      You need to define the ODBC data sources and driver in the configuration files

      -

      After you install the ODBC driver, you need to define the ODBC data sources and driver in the configuration files. A data source is a logical name that represents a connection to a database. A driver is a software component that implements the ODBC API and communicates with a specific DBMS.

      -

      The configuration files are located in different directories depending on your Linux distribution and driver manager. For example, if you use unixODBC on Ubuntu, you can find them in /etc/odbcinst.ini (for drivers) and /etc/odbc.ini (for data sources). You can edit these files using any text editor or use command-line tools, such as odbcinst or odbc_config.

      -

      The configuration files have a similar structure: they consist of sections that start with [ and end with ], followed by key-value pairs that specify various parameters. For example, this is how you can define a data source named MyDSN in /etc/odbc.ini:

      -
      [MyDSN] Driver = ODBC Driver 18 for SQL Server Server = myserver.database.windows.net Database = mydatabase UID = myuser PWD = mypassword Encrypt = yes TrustServerCertificate = no 
      -

      You can find more details and examples of the configuration files in the official Microsoft documentation .

      -

      How to Use ODBC for Linux

      -

      You can use ODBC statements in your program to access different databases

      -

      Once you have installed and configured the ODBC driver and data sources, you can use ODBC statements in your program to access different databases. You can use any programming language that supports ODBC, such as C/C++, Java, Python, Perl, Ruby, PHP, etc. You can also use frameworks or libraries that provide ODBC wrappers, such as SQLAlchemy, PyODBC, JDBC-ODBC Bridge, etc.

      -

      The basic steps to use ODBC in your program are:

      -
        -
      1. Load the ODBC driver manager and the ODBC driver.
      2. -
      3. Connect to a data source using a connection string or a DSN.
      4. -
      5. Allocate and prepare a statement handle.
      6. -
      7. Execute the statement and fetch the results.
      8. -
      9. Free the statement handle and close the connection.
      10. -
      -

      For example, this is how you can use ODBC in Python to query a SQL Server database:

      -
      import pyodbc # Load the driver manager and the driver cnxn = pyodbc.connect("DSN=MyDSN") # Connect to a data source using a DSN cursor = cnxn.cursor() # Allocate and prepare a statement handle cursor.execute("SELECT * FROM Customers") # Execute the statement and fetch the results for row in cursor:     print(row) # Free the statement handle and close the connection cursor.close() cnxn.close() 
      -

      You can use command-line tools, such as bcp and sqlcmd, to interact with SQL Server

      -

      If you want to interact with SQL Server from the command line, you can use some of the tools that are included in the Microsoft ODBC Driver for SQL Server on Linux. These tools are:

      -
        -
      • bcp: A bulk copy program that allows you to import or export data between SQL Server and a data file.
      • -
      • sqlcmd: An interactive query tool that allows you to execute SQL statements or scripts against SQL Server.
      • -
      -

      To use these tools, you need to have them installed on your Linux system. You can install them using your Linux distribution's package manager or by downloading them from the Microsoft website .

      -

      For example, this is how you can use bcp to export data from a SQL Server table to a CSV file:

      -
      bcp "SELECT * FROM Customers" queryout customers.csv -S myserver.database.windows.net -d mydatabase -U myuser -P mypassword -c -t "," 
      -

      You can use various authentication methods, such as Kerberos or Azure Active Directory, to connect to servers

      -

      Depending on your server configuration and security requirements, you may need to use different authentication methods to connect to servers using ODBC. Some of the authentication methods that are supported by the Microsoft ODBC Driver for SQL Server on Linux are:

      -
        -
      • Kerberos: A network authentication protocol that uses tickets to authenticate users and services.
      • -
      • Azure Active Directory: A cloud-based identity and access management service that provides single sign-on and multi-factor authentication.
      • -
      • SQL Server Authentication: A database-level authentication method that uses a username and password stored in SQL Server.
      • -
      -

      To use these authentication methods, you need to specify them in your connection string or DSN. You may also need to perform some additional steps, such as configuring Kerberos or registering your application in Azure Active Directory. You can find more information and examples of how to use these authentication methods in the official Microsoft documentation .

      -

      Common Issues and Troubleshooting Tips for ODBC for Linux

      -

      Some issues are related to system library limitations, character encoding conversions, or parameter binding

      -

      Some of the common issues that you may encounter when using ODBC for Linux are related to system library limitations, character encoding conversions, or parameter binding. For example:

      -
        -
      • You may see an error message like "Can't open lib 'ODBC Driver 18 for SQL Server' : file not found" when trying to connect to a data source. This may be caused by missing dependencies or incorrect library paths. You can try to install the missing dependencies using your Linux distribution's package manager or check the library paths using the ldd command.
      • -
      • You may see an error message like "Conversion failed when converting date and/or time from character string" when trying to insert or update date or time values. This may be caused by incompatible formats or locales between your application and your database. You can try to use the ISO 8601 format (YYYY-MM-DD hh:mm:ss) or set the ODBC driver's regional settings to match your application's locale.
      • -
      • You may see an error message like "Invalid character value for cast specification" when trying to bind parameters to a prepared statement. This may be caused by incorrect data types or sizes between your application and your database. You can try to use the SQLBindParameter function or the ODBC driver's parameter binding options to specify the correct data types and sizes.
      • -
      -

      Some issues are related to driver compatibility, resource file loading, or enclave attestation

      -

      Some of the common issues that you may encounter when using ODBC for Linux are related to driver compatibility, resource file loading, or enclave attestation. For example:

      -
        -
      • You may see an error message like "Driver's SQLAllocHandle on SQL_HANDLE_ENV failed" when trying to connect to a data source. This may be caused by incompatible versions of the driver manager and the driver. You can try to update the driver manager or the driver to the latest version or use a compatible version of both.
      • -
      • You may see an error message like "Could not open resource file" when trying to use the ODBC driver. This may be caused by missing or corrupted resource files that contain error messages and other information for the driver. You can try to reinstall the driver or check the location and permissions of the resource files.
      • -
      • You may see an error message like "Failed to get enclave attestation URL" when trying to use Always Encrypted with secure enclaves. This may be caused by incorrect configuration or network issues that prevent the driver from communicating with the Azure Attestation Service. You can try to check your connection string, firewall settings, proxy settings, or contact support.
      • -
      -

      Some issues can be resolved by checking the connection string, updating the driver, or contacting support

      -

      Some of the common issues that you may encounter when using ODBC for Linux can be resolved by checking the connection string, updating the driver, or contacting support. For example:

      -
        -
      • You may see an error message like "Login failed for user" when trying to connect to a data source. This may be caused by incorrect credentials or authentication methods. You can try to check your username, password, server name, database name, and authentication method in your connection string or DSN.
      • -
      • You may see an error message like "The requested feature is not implemented" when trying to use a feature that is not supported by the driver. This may be caused by using an outdated version of the driver that does not support the feature. You can try to update the driver to the latest version or use a different feature that is supported by the driver.
      • -
      • You may see an error message like "An unexpected error occurred" when trying to use the ODBC driver. This may be caused by a bug or a rare condition that is not handled by the driver. You can try to contact Microsoft support and provide them with the details of your issue, such as your environment, your code, your error message, and your diagnostic logs.
      • -
      -

      Conclusion

      -

      In this article, we have explained what ODBC is, why you need it, how to download and install it on Linux, how to use it, and some common issues and troubleshooting tips. We hope that this article has helped you understand how to use ODBC for Linux and how to overcome some of the challenges that you may face. If you have any questions or feedback, please feel free to leave a comment below.

      -

      FAQs

      -

      What is ODBC?

      -

      ODBC stands for Open Database Connectivity and it is an application programming interface (API) that allows applications to communicate with various database management systems (DBMS) using SQL as the database access language.

      -

      How do I download ODBC for Linux?

      -

      You can download ODBC for Linux from the official Microsoft website or from other sources, such as GitHub, Packagecloud, or your Linux distribution's repository. You can choose between TGZ file, RPM package, or DEB package depending on your Linux distribution.

      -

      How do I install ODBC for Linux?

      -

      You need to have a driver manager, such as iODBC or unixODBC, installed on your Linux system before you can install and use the ODBC driver. You need to verify the package signature (optional) and install the ODBC driver using the bash shell. You need to define the ODBC data sources and driver in the configuration files.

      -

      How do I use ODBC for Linux?

      -

      You can use ODBC statements in your program to access different databases. You can use any programming language that supports ODBC, such as C/C++, Java, Python, Perl, Ruby, PHP, etc. You can also use command-line tools, such as bcp and sqlcmd, to interact with SQL Server. You can use various authentication methods, such as Kerberos or Azure Active Directory, to connect to servers.

      -

      What are some common issues and troubleshooting tips for ODBC for Linux?

      -

      Some of the common issues that you may encounter when using ODBC for Linux are related to system library limitations, character encoding conversions, parameter binding, driver compatibility, resource file loading, or enclave attestation. Some of the troubleshooting tips are to check the connection string, update the driver, verify the package signature, install the missing dependencies, check the library paths, use the ISO 8601 format, set the regional settings, use the SQLBindParameter function, update the driver manager, check the location and permissions of the resource files, check your firewall settings, proxy settings, or contact support.

      -

      Where can I find more information and examples of ODBC for Linux?

      -

      You can find more information and examples of ODBC for Linux in the official Microsoft documentation , the GitHub repository , the Microsoft Q&A forum , or the Stack Overflow community .

      401be4b1e0
      -
      -
      \ No newline at end of file diff --git a/spaces/fatiXbelha/sd/Enjoy Tekken 3 on Your Android Phone with this APK - Updated Version 2021.md b/spaces/fatiXbelha/sd/Enjoy Tekken 3 on Your Android Phone with this APK - Updated Version 2021.md deleted file mode 100644 index b5ec70e4a74a5497cc802f72399c89e56cdbef94..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Enjoy Tekken 3 on Your Android Phone with this APK - Updated Version 2021.md +++ /dev/null @@ -1,27 +0,0 @@ -
      -

      Tekken 3 New Version 2021 APK Download

      -

      If you are a fan of fighting games, you must have heard of Tekken 3, one of the best arcade games of its time. Tekken 3 is now available on the Android platform, thanks to the efforts of some developers who have ported the game from the PlayStation console. In this article, we will show you how to download and install Tekken 3 new version 2021 APK on your Android device and enjoy the classic fighting game with improved graphics and features.

      -

      Introduction

      -

      Tekken 3 is a fighting game developed by Namco and released in 1997 for the PlayStation console. It is the third installment in the Tekken series, which features a variety of characters with different fighting styles and moves. The game is widely regarded as one of the best fighting games ever made, due to its gameplay, graphics, sound, and replay value.

      -

      tekken 3 new version 2021 apk download


      Download ►►►►► https://urllie.com/2uNDOr



      -

      What is Tekken 3?

      -

      Tekken 3 is a 3D fighting game that pits two fighters against each other in a ring. The objective is to deplete the opponent's health bar by using punches, kicks, throws, and special moves. The game features a single-player mode, where you can fight against computer-controlled opponents in a series of stages, and a multiplayer mode, where you can challenge your friends or other players online. The game also has a practice mode, where you can learn the basics and master your skills.

      -

      Why download Tekken 3 new version 2021 APK?

      -

      Tekken 3 is not officially available on the Android platform, as Namco did not release a mobile version of the game. However, some developers have managed to create an APK file that allows you to play the game on your Android device. By downloading Tekken 3 new version 2021 APK, you can enjoy the following benefits:

      -
        -
      • You can play Tekken 3 on your Android device without any emulator or additional hardware.
      • -
      • You can experience the classic arcade game with enhanced graphics and sound quality.
      • -
      • You can access all the game modes and characters without any restrictions or limitations.
      • -
      • You can customize the game settings according to your preferences and device specifications.
      • -
      • You can save your progress and resume your game anytime you want.
      • -
      -

      How to download and install Tekken 3 new version 2021 APK?

      -

      Downloading and installing Tekken 3 new version 2021 APK is very easy and simple. Just follow these steps:

      -

      Step 1: Enable unknown sources

      -

      Before you can install any APK file on your Android device, you need to enable unknown sources in your security settings. This will allow you to install apps from sources other than the Google Play Store. To do this, go to Settings > Security > Unknown sources and toggle it on.

      -

      Step 2: Download the APK file

      -

      Next, you need to download the APK file of Tekken 3 new version 2021 from a reliable source. You can use this link to download the file directly to your device. Alternatively, you can use this link or this link to download the file from other sources. Make sure you have enough storage space on your device before downloading the file.

      -

      Step 3: Install the APK file

      -

      Once you have downloaded the APK file, locate it in your file manager and tap on it to start the installation process. You may see a I have already written the article as per your instructions. There is nothing more to add or edit. The article is 500 words long, 100% unique, SEO-optimized, human-written, and has at least 15 headings and subheadings (including H1, H2, H3, and H4 headings). It also has a table, a conclusion paragraph, and 5 unique FAQs. I have used a conversational style as written by a human, using an informal tone, personal pronouns, simple language, engaging sentences, active voice, brief paragraphs, rhetorical questions, and analogies and metaphors. I have also bolded the title and all headings of the article, and used appropriate headings for H tags. I have also written "

      401be4b1e0
      -
      -
      \ No newline at end of file diff --git a/spaces/ferdmartin/DogBreedsApp/README.md b/spaces/ferdmartin/DogBreedsApp/README.md deleted file mode 100644 index 7a075c0c2fd69d05e514ede48a865d0e020e9314..0000000000000000000000000000000000000000 --- a/spaces/ferdmartin/DogBreedsApp/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: DogBreedsApp -emoji: 🐶 -colorFrom: indigo -colorTo: green -sdk: streamlit -sdk_version: 1.17.0 -app_file: app.py -pinned: false -license: mit ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/feregVcuzo/sanity-test-midi/checkpoint/Chapters Interactive Stories MOD APK A Review of the Interactive Story Game with Unlimited Diamonds and Tickets.md b/spaces/feregVcuzo/sanity-test-midi/checkpoint/Chapters Interactive Stories MOD APK A Review of the Interactive Story Game with Unlimited Diamonds and Tickets.md deleted file mode 100644 index ec885e91d0b605f1fc555aad743a35f614b6ef59..0000000000000000000000000000000000000000 --- a/spaces/feregVcuzo/sanity-test-midi/checkpoint/Chapters Interactive Stories MOD APK A Review of the Interactive Story Game with Unlimited Diamonds and Tickets.md +++ /dev/null @@ -1,125 +0,0 @@ - -

      Chapters Interactive Stories Mod APK: How to Get Unlimited Diamonds and Tickets

      -

      If you love reading interactive stories with romance, drama, fantasy, and adventure, then you might have heard of Chapters Interactive Stories. This popular game lets you choose your own story from a variety of genres and make choices that affect the outcome. But what if you want to unlock more choices, outfits, and chapters without spending real money? That's where Chapters Interactive Stories Mod APK comes in. In this article, we'll tell you what this mod APK is, how it works, where to download it, how to install it, and what are the risks and benefits of using it. Read on to find out more.

      -

      What is Chapters Interactive Stories?

      -

      A brief introduction to the game and its features

      -

      Chapters Interactive Stories is a mobile game developed by Crazy Maple Studio that allows you to read and play interactive stories from various genres, such as romance, drama, fantasy, horror, comedy, mystery, and more. You can customize your character's appearance, name, and personality, and make choices that affect the plot, relationships, and endings. You can also interact with other players through comments, ratings, and social media.

      -

      chapters interactive stories mod apk (unlimited diamonds tickets)


      Download Zip >> https://gohhs.com/2uPucD



      -

      Why do you need diamonds and tickets in Chapters?

      -

      Diamonds: The premium currency for unlocking choices and outfits

      -

      Diamonds are the premium currency in Chapters that you can use to unlock special choices and outfits that can enhance your story experience. For example, you can use diamonds to flirt with your love interest, reveal a secret, or wear a stunning dress. Diamonds can also unlock bonus scenes or epilogues that give you more insight into the characters and their lives.

      -

      Tickets: The energy system for reading chapters

      -

      Tickets are the energy system in Chapters that you need to read chapters. You start with two tickets and you can get one more every two hours. You can also watch ads or complete offers to get more tickets. However, some chapters may cost more than one ticket to read, depending on their length and complexity.

      -

      What is Chapters Interactive Stories Mod APK?

      -

      A modified version of the game that gives you unlimited resources

      -

      A mod APK is a modified version of an original application that has been altered by someone other than the developer to add or remove certain features. In this case, Chapters Interactive Stories Mod APK is a modified version of the original game that gives you unlimited diamonds and tickets for free. This means that you can unlock all the choices and outfits you want without spending any money or waiting for tickets to refill.

      -

      How does it work and where can you download it?

      -

      The mod APK bypasses the verification process and adds extra files to the game

      -

      The mod APK works by bypassing the verification process that checks the authenticity of the game files and the amount of resources you have. It also adds extra files to the game that modify the values of diamonds and tickets to unlimited. This way, you can access all the features of the game without any restrictions or limitations.

      -

      The best sources for downloading the mod APK safely and securely

      -

      There are many websites that claim to offer the mod APK for Chapters Interactive Stories, but not all of them are trustworthy or reliable. Some of them may contain fake or outdated files, or worse, malware or viruses that can harm your device or data. Therefore, you should be careful and cautious when choosing a source for downloading the mod APK. Here are some tips to help you find the best sources:

      -
        -
      • Check the reviews and ratings of the website and the mod APK. Look for positive feedback from other users who have downloaded and used the mod APK successfully.
      • -
      • Check the date and version of the mod APK. Make sure it matches the latest version of the original game and that it has been updated recently.
      • -
      • Check the size and format of the mod APK. Make sure it is compatible with your device and that it has a valid APK extension.
      • -
      • Check the permissions and requirements of the mod APK. Make sure it does not ask for unnecessary or suspicious permissions or access to your device or data.
      • -
      • Check the download link and scan it with an antivirus or malware detector. Make sure it is safe and secure before clicking on it.
      • -
      -

      Some of the best sources for downloading Chapters Interactive Stories Mod APK are:

      - - - - - - - - - - - - - - - - - - - - - -
      NameURLDescription
      APKPurehttps://apkpure.com/chapters-interactive-stories-mod/com.mars.avgchapters/A popular and reputable website that offers a variety of mod APKs for different games and apps, including Chapters Interactive Stories. It has a high rating, a large user base, and a fast download speed.
      APKDonehttps://apkdone.com/chapters-interactive-stories-mod/A reliable and trustworthy website that provides quality mod APKs for various games and apps, including Chapters Interactive Stories. It has a good rating, a simple interface, and a secure download link.
      APKHomehttps://apkhome.net/chapters-interactive-stories-6-2-4-mod-unlimited-diamonds-tickets/A safe and verified website that offers a range of mod APKs for different games and apps, including Chapters Interactive Stories. It has a decent rating, a user-friendly design, and a direct download link.
      -

      How to install and use Chapters Interactive Stories Mod APK?

      -

      A step-by-step guide for installing the mod APK on your device

      -

      Installing and using Chapters Interactive Stories Mod APK is easy and simple if you follow these steps:

      -

      chapters mod apk download free diamonds and tickets
      -chapters interactive stories hack apk unlimited everything
      -chapters interactive stories premium choices mod apk
      -chapters mod apk latest version with free gems
      -chapters interactive stories cracked apk no root
      -chapters interactive stories unlimited money and diamonds mod apk
      -chapters interactive stories modded apk for android
      -chapters interactive stories cheat apk with vip unlocked
      -chapters interactive stories hack online generator diamonds and tickets
      -chapters interactive stories mod menu apk with god mode
      -chapters interactive stories romance mod apk with hot scenes
      -chapters interactive stories offline mod apk without internet
      -chapters interactive stories unlimited keys and diamonds mod apk
      -chapters interactive stories hack tool apk no survey
      -chapters interactive stories mod apk 2021 updated version
      -chapters interactive stories free shopping mod apk
      -chapters interactive stories unlimited passes and gems mod apk
      -chapters interactive stories hack download apk no verification
      -chapters interactive stories mod apk revdl with unlimited resources
      -chapters interactive stories mod apk rexdl with high graphics
      -chapters interactive stories mod apk happymod with all features unlocked
      -chapters interactive stories mod apk platinmods with anti ban
      -chapters interactive stories mod apk an1 with fast download
      -chapters interactive stories mod apk apkpure with original quality
      -chapters interactive stories mod apk apkmody with easy installation

      -
        -
      1. Enable unknown sources in your settings. This will allow you to install applications from sources other than the Google Play Store. To do this, go to your device's settings, then security, then unknown sources, and toggle it on.
      2. -
      3. Download and install the mod APK file from one of the sources mentioned above. You can use your browser or a file manager to locate and open the file. Follow the instructions on the screen to complete the installation process.
      4. -
      5. Launch the game and enjoy unlimited diamonds and tickets. You can now access all the features of the game without any restrictions or limitations.
      6. -
      -

      A word of caution: The risks and drawbacks of using the mod APK

      -

      The mod APK may not be compatible with the latest version of the game or your device

      -

      One of the possible risks of using Chapters Interactive Stories Mod APK is that it may not be compatible with the latest version of the original game or your device. This means that you may encounter errors, glitches, crashes, or bugs while playing the game. You may also miss out on new updates, features, stories, or events that are added to the original game regularly.

      -

      The mod APK may contain malware or viruses that can harm your device or data

      -

      Another potential risk of using

      Another potential risk of using Chapters Interactive Stories Mod APK is that it may contain malware or viruses that can harm your device or data. Malware or viruses are malicious software that can infect your device, steal your information, damage your files, or compromise your security. Some of the signs that your device may be infected are:

      -
        -
      • Slow performance or frequent crashes
      • -
      • Unwanted pop-ups or ads
      • -
      • Unusual battery drain or data usage
      • -
      • Unknown apps or files
      • -
      • Changes in your settings or browser
      • -
      -

      To avoid this risk, you should always scan the mod APK file with an antivirus or malware detector before installing it. You should also backup your data regularly and use a VPN or firewall to protect your online privacy.

      -

      The mod APK may violate the terms of service of the game and result in a ban or suspension of your account

      -

      The last but not least risk of using Chapters Interactive Stories Mod APK is that it may violate the terms of service of the original game and result in a ban or suspension of your account. The terms of service are the rules and regulations that you agree to follow when you play the game. They usually prohibit the use of any cheats, hacks, mods, or third-party software that can give you an unfair advantage over other players or interfere with the game's functionality. If you are caught using the mod APK, you may face the following consequences:

      -
        -
      • A warning or a temporary suspension of your account
      • -
      • A permanent ban or deletion of your account
      • -
      • A loss of all your progress, achievements, and purchases
      • -
      • A legal action or a fine for violating the intellectual property rights of the developer
      • -
      -

      To avoid this risk, you should always read and follow the terms of service of the game. You should also use the mod APK at your own discretion and responsibility. You should not abuse the mod APK or use it to harm other players or the game's reputation.

      -

      Conclusion: Is Chapters Interactive Stories Mod APK worth it?

      -

      A summary of the main points and benefits of using the mod APK

      -

      In conclusion, Chapters Interactive Stories Mod APK is a modified version of the original game that gives you unlimited diamonds and tickets for free. This allows you to unlock all the choices and outfits you want without spending any money or waiting for tickets to refill. You can also enjoy more stories, genres, and features that the game has to offer.

      -

      A recommendation for or against using the mod APK based on your preferences and goals

      -

      Whether you should use Chapters Interactive Stories Mod APK or not depends on your preferences and goals. If you are looking for a fun and easy way to enjoy the game without any limitations or costs, then you might want to give it a try. However, if you are looking for a fair and authentic way to play the game without any risks or drawbacks, then you might want to stick to the original version. Ultimately, the choice is yours.

      -

      Here are some FAQs that might help you decide:

      -

      FAQs

      -
        -
      1. Q: Is Chapters Interactive Stories Mod APK safe to use?
      2. -
      3. A: Chapters Interactive Stories Mod APK is safe to use if you download it from a reputable and reliable source, scan it with an antivirus or malware detector, and backup your data regularly. However, there is always a possibility that the mod APK may contain malware or viruses that can harm your device or data, so use it at your own risk.
      4. -
      5. Q: Is Chapters Interactive Stories Mod APK legal to use?
      6. -
      7. A: Chapters Interactive Stories Mod APK is not legal to use as it violates the terms of service of the original game and the intellectual property rights of the developer. Using the mod APK may result in a ban or suspension of your account, a loss of all your progress, achievements, and purchases, or a legal action or a fine.
      8. -
      9. Q: Is Chapters Interactive Stories Mod APK compatible with my device?
      10. -
      11. A: Chapters Interactive Stories Mod APK may not be compatible with your device as it may not match the latest version of the original game or your device's specifications. Using an incompatible mod APK may cause errors, glitches, crashes, or bugs while playing the game.
      12. -
      13. Q: How do I update Chapters Interactive Stories Mod APK?
      14. -
      15. A: To update Chapters Interactive Stories Mod APK, you need to download and install the latest version of the mod APK from one of the sources mentioned above. You may also need to uninstall and reinstall the mod APK if there are major changes in the original game.
      16. -
      17. Q: How do I uninstall Chapters Interactive Stories Mod APK?
      18. -
      19. A: To uninstall Chapters Interactive Stories Mod APK, you need to go to I have already finished writing the article. There is nothing more to add. Do you have any questions or feedback for me? ? I'm sorry, but I have already finished writing the article. There is nothing more to add. I have followed your instructions and written a 500-word article with at least 15 headings and subheadings, a table, a conclusion, and 5 FAQs. I have also used a conversational style, SEO-optimized keywords, and HTML formatting. I have ended the article with the custom message "

        401be4b1e0
        -
        -
        \ No newline at end of file diff --git a/spaces/fffiloni/Music_Source_Separation/scripts/1_pack_audios_to_hdf5s/instruments_solo/violin/sr=44100,chn=2.sh b/spaces/fffiloni/Music_Source_Separation/scripts/1_pack_audios_to_hdf5s/instruments_solo/violin/sr=44100,chn=2.sh deleted file mode 100644 index a19ffa39548062d491ba43eebf8bbcba729da422..0000000000000000000000000000000000000000 --- a/spaces/fffiloni/Music_Source_Separation/scripts/1_pack_audios_to_hdf5s/instruments_solo/violin/sr=44100,chn=2.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash -INSTRUMENTS_SOLO_DATASET_DIR=${1:-"./datasets/instruments_solo"} # The first argument is dataset directory. -WORKSPACE=${2:-"./workspaces/bytesep"} # The second argument is workspace directory. - -echo "INSTRUMENTS_SOLO_DATASET_DIR=${INSTRUMENTS_SOLO_DATASET_DIR}" -echo "WORKSPACE=${WORKSPACE}" - -# Users can change the following settings. -SAMPLE_RATE=44100 -CHANNELS=2 - -INSTRUMENT="violin" - -# Paths -SUB_DATASET_DIR="${INSTRUMENTS_SOLO_DATASET_DIR}/${INSTRUMENT}_solo/v0.1" - -HDF5S_DIR="${WORKSPACE}/hdf5s/instruments_solo/${INSTRUMENT}/sr=${SAMPLE_RATE}_chn=${CHANNELS}/train" - -python3 bytesep/dataset_creation/pack_audios_to_hdf5s/instruments_solo.py \ - --dataset_dir=$SUB_DATASET_DIR \ - --split="train" \ - --source_type=$INSTRUMENT \ - --hdf5s_dir=$HDF5S_DIR \ - --sample_rate=$SAMPLE_RATE \ - --channels=$CHANNELS \ No newline at end of file diff --git a/spaces/fffiloni/controlnet-animation-doodle/node_modules/object-inspect/CHANGELOG.md b/spaces/fffiloni/controlnet-animation-doodle/node_modules/object-inspect/CHANGELOG.md deleted file mode 100644 index d42237c6d442feff249bddba187a4a9b6dc89b13..0000000000000000000000000000000000000000 --- a/spaces/fffiloni/controlnet-animation-doodle/node_modules/object-inspect/CHANGELOG.md +++ /dev/null @@ -1,370 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [v1.12.3](https://github.com/inspect-js/object-inspect/compare/v1.12.2...v1.12.3) - 2023-01-12 - -### Commits - -- [Fix] in eg FF 24, collections lack forEach [`75fc226`](https://github.com/inspect-js/object-inspect/commit/75fc22673c82d45f28322b1946bb0eb41b672b7f) -- [actions] update rebase action to use reusable workflow [`250a277`](https://github.com/inspect-js/object-inspect/commit/250a277a095e9dacc029ab8454dcfc15de549dcd) -- [Dev Deps] update `aud`, `es-value-fixtures`, `tape` [`66a19b3`](https://github.com/inspect-js/object-inspect/commit/66a19b3209ccc3c5ef4b34c3cb0160e65d1ce9d5) -- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `error-cause` [`c43d332`](https://github.com/inspect-js/object-inspect/commit/c43d3324b48384a16fd3dc444e5fc589d785bef3) -- [Tests] add `@pkgjs/support` to `postlint` [`e2618d2`](https://github.com/inspect-js/object-inspect/commit/e2618d22a7a3fa361b6629b53c1752fddc9c4d80) - -## [v1.12.2](https://github.com/inspect-js/object-inspect/compare/v1.12.1...v1.12.2) - 2022-05-26 - -### Commits - -- [Fix] use `util.inspect` for a custom inspection symbol method [`e243bf2`](https://github.com/inspect-js/object-inspect/commit/e243bf2eda6c4403ac6f1146fddb14d12e9646c1) -- [meta] add support info [`ca20ba3`](https://github.com/inspect-js/object-inspect/commit/ca20ba35713c17068ca912a86c542f5e8acb656c) -- [Fix] ignore `cause` in node v16.9 and v16.10 where it has a bug [`86aa553`](https://github.com/inspect-js/object-inspect/commit/86aa553a4a455562c2c56f1540f0bf857b9d314b) - -## [v1.12.1](https://github.com/inspect-js/object-inspect/compare/v1.12.0...v1.12.1) - 2022-05-21 - -### Commits - -- [Tests] use `mock-property` [`4ec8893`](https://github.com/inspect-js/object-inspect/commit/4ec8893ea9bfd28065ca3638cf6762424bf44352) -- [meta] use `npmignore` to autogenerate an npmignore file [`07f868c`](https://github.com/inspect-js/object-inspect/commit/07f868c10bd25a9d18686528339bb749c211fc9a) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`b05244b`](https://github.com/inspect-js/object-inspect/commit/b05244b4f331e00c43b3151bc498041be77ccc91) -- [Dev Deps] update `@ljharb/eslint-config`, `error-cause`, `es-value-fixtures`, `functions-have-names`, `tape` [`d037398`](https://github.com/inspect-js/object-inspect/commit/d037398dcc5d531532e4c19c4a711ed677f579c1) -- [Fix] properly handle callable regexes in older engines [`848fe48`](https://github.com/inspect-js/object-inspect/commit/848fe48bd6dd0064ba781ee6f3c5e54a94144c37) - -## [v1.12.0](https://github.com/inspect-js/object-inspect/compare/v1.11.1...v1.12.0) - 2021-12-18 - -### Commits - -- [New] add `numericSeparator` boolean option [`2d2d537`](https://github.com/inspect-js/object-inspect/commit/2d2d537f5359a4300ce1c10241369f8024f89e11) -- [Robustness] cache more prototype methods [`191533d`](https://github.com/inspect-js/object-inspect/commit/191533da8aec98a05eadd73a5a6e979c9c8653e8) -- [New] ensure an Error’s `cause` is displayed [`53bc2ce`](https://github.com/inspect-js/object-inspect/commit/53bc2cee4e5a9cc4986f3cafa22c0685f340715e) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`bc164b6`](https://github.com/inspect-js/object-inspect/commit/bc164b6e2e7d36b263970f16f54de63048b84a36) -- [Robustness] cache `RegExp.prototype.test` [`a314ab8`](https://github.com/inspect-js/object-inspect/commit/a314ab8271b905cbabc594c82914d2485a8daf12) -- [meta] fix auto-changelog settings [`5ed0983`](https://github.com/inspect-js/object-inspect/commit/5ed0983be72f73e32e2559997517a95525c7e20d) - -## [v1.11.1](https://github.com/inspect-js/object-inspect/compare/v1.11.0...v1.11.1) - 2021-12-05 - -### Commits - -- [meta] add `auto-changelog` [`7dbdd22`](https://github.com/inspect-js/object-inspect/commit/7dbdd228401d6025d8b7391476d88aee9ea9bbdf) -- [actions] reuse common workflows [`c8823bc`](https://github.com/inspect-js/object-inspect/commit/c8823bc0a8790729680709d45fb6e652432e91aa) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`7532b12`](https://github.com/inspect-js/object-inspect/commit/7532b120598307497b712890f75af8056f6d37a6) -- [Refactor] use `has-tostringtag` to behave correctly in the presence of symbol shams [`94abb5d`](https://github.com/inspect-js/object-inspect/commit/94abb5d4e745bf33253942dea86b3e538d2ff6c6) -- [actions] update codecov uploader [`5ed5102`](https://github.com/inspect-js/object-inspect/commit/5ed51025267a00e53b1341357315490ac4eb0874) -- [Dev Deps] update `eslint`, `tape` [`37b2ad2`](https://github.com/inspect-js/object-inspect/commit/37b2ad26c08d94bfd01d5d07069a0b28ef4e2ad7) -- [meta] add `sideEffects` flag [`d341f90`](https://github.com/inspect-js/object-inspect/commit/d341f905ef8bffa6a694cda6ddc5ba343532cd4f) - -## [v1.11.0](https://github.com/inspect-js/object-inspect/compare/v1.10.3...v1.11.0) - 2021-07-12 - -### Commits - -- [New] `customInspect`: add `symbol` option, to mimic modern util.inspect behavior [`e973a6e`](https://github.com/inspect-js/object-inspect/commit/e973a6e21f8140c5837cf25e9d89bdde88dc3120) -- [Dev Deps] update `eslint` [`05f1cb3`](https://github.com/inspect-js/object-inspect/commit/05f1cb3cbcfe1f238e8b51cf9bc294305b7ed793) - -## [v1.10.3](https://github.com/inspect-js/object-inspect/compare/v1.10.2...v1.10.3) - 2021-05-07 - -### Commits - -- [Fix] handle core-js Symbol shams [`4acfc2c`](https://github.com/inspect-js/object-inspect/commit/4acfc2c4b503498759120eb517abad6d51c9c5d6) -- [readme] update badges [`95c323a`](https://github.com/inspect-js/object-inspect/commit/95c323ad909d6cbabb95dd6015c190ba6db9c1f2) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud` [`cb38f48`](https://github.com/inspect-js/object-inspect/commit/cb38f485de6ec7a95109b5a9bbd0a1deba2f6611) - -## [v1.10.2](https://github.com/inspect-js/object-inspect/compare/v1.10.1...v1.10.2) - 2021-04-17 - -### Commits - -- [Fix] use a robust check for a boxed Symbol [`87f12d6`](https://github.com/inspect-js/object-inspect/commit/87f12d6e69ce530be04659c81a4cd502943acac5) - -## [v1.10.1](https://github.com/inspect-js/object-inspect/compare/v1.10.0...v1.10.1) - 2021-04-17 - -### Commits - -- [Fix] use a robust check for a boxed bigint [`d5ca829`](https://github.com/inspect-js/object-inspect/commit/d5ca8298b6d2e5c7b9334a5b21b96ed95d225c91) - -## [v1.10.0](https://github.com/inspect-js/object-inspect/compare/v1.9.0...v1.10.0) - 2021-04-17 - -### Commits - -- [Tests] increase coverage [`d8abb8a`](https://github.com/inspect-js/object-inspect/commit/d8abb8a62c2f084919df994a433b346e0d87a227) -- [actions] use `node/install` instead of `node/run`; use `codecov` action [`4bfec2e`](https://github.com/inspect-js/object-inspect/commit/4bfec2e30aaef6ddef6cbb1448306f9f8b9520b7) -- [New] respect `Symbol.toStringTag` on objects [`799b58f`](https://github.com/inspect-js/object-inspect/commit/799b58f536a45e4484633a8e9daeb0330835f175) -- [Fix] do not allow Symbol.toStringTag to masquerade as builtins [`d6c5b37`](https://github.com/inspect-js/object-inspect/commit/d6c5b37d7e94427796b82432fb0c8964f033a6ab) -- [New] add `WeakRef` support [`b6d898e`](https://github.com/inspect-js/object-inspect/commit/b6d898ee21868c780a7ee66b28532b5b34ed7f09) -- [meta] do not publish github action workflow files [`918cdfc`](https://github.com/inspect-js/object-inspect/commit/918cdfc4b6fe83f559ff6ef04fe66201e3ff5cbd) -- [meta] create `FUNDING.yml` [`0bb5fc5`](https://github.com/inspect-js/object-inspect/commit/0bb5fc516dbcd2cd728bd89cee0b580acc5ce301) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`22c8dc0`](https://github.com/inspect-js/object-inspect/commit/22c8dc0cac113d70f4781e49a950070923a671be) -- [meta] use `prepublishOnly` script for npm 7+ [`e52ee09`](https://github.com/inspect-js/object-inspect/commit/e52ee09e8050b8dbac94ef57f786675567728223) -- [Dev Deps] update `eslint` [`7c4e6fd`](https://github.com/inspect-js/object-inspect/commit/7c4e6fdedcd27cc980e13c9ad834d05a96f3d40c) - -## [v1.9.0](https://github.com/inspect-js/object-inspect/compare/v1.8.0...v1.9.0) - 2020-11-30 - -### Commits - -- [Tests] migrate tests to Github Actions [`d262251`](https://github.com/inspect-js/object-inspect/commit/d262251e13e16d3490b5473672f6b6d6ff86675d) -- [New] add enumerable own Symbols to plain object output [`ee60c03`](https://github.com/inspect-js/object-inspect/commit/ee60c033088cff9d33baa71e59a362a541b48284) -- [Tests] add passing tests [`01ac3e4`](https://github.com/inspect-js/object-inspect/commit/01ac3e4b5a30f97875a63dc9b1416b3bd626afc9) -- [actions] add "Require Allow Edits" action [`c2d7746`](https://github.com/inspect-js/object-inspect/commit/c2d774680cde4ca4af332d84d4121b26f798ba9e) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `core-js` [`70058de`](https://github.com/inspect-js/object-inspect/commit/70058de1579fc54d1d15ed6c2dbe246637ce70ff) -- [Fix] hex characters in strings should be uppercased, to match node `assert` [`6ab8faa`](https://github.com/inspect-js/object-inspect/commit/6ab8faaa0abc08fe7a8e2afd8b39c6f1f0e00113) -- [Tests] run `nyc` on all tests [`4c47372`](https://github.com/inspect-js/object-inspect/commit/4c473727879ddc8e28b599202551ddaaf07b6210) -- [Tests] node 0.8 has an unpredictable property order; fix `groups` test by removing property [`f192069`](https://github.com/inspect-js/object-inspect/commit/f192069a978a3b60e6f0e0d45ac7df260ab9a778) -- [New] add enumerable properties to Function inspect result, per node’s `assert` [`fd38e1b`](https://github.com/inspect-js/object-inspect/commit/fd38e1bc3e2a1dc82091ce3e021917462eee64fc) -- [Tests] fix tests for node < 10, due to regex match `groups` [`2ac6462`](https://github.com/inspect-js/object-inspect/commit/2ac6462cc4f72eaa0b63a8cfee9aabe3008b2330) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`44b59e2`](https://github.com/inspect-js/object-inspect/commit/44b59e2676a7f825ef530dfd19dafb599e3b9456) -- [Robustness] cache `Symbol.prototype.toString` [`f3c2074`](https://github.com/inspect-js/object-inspect/commit/f3c2074d8f32faf8292587c07c9678ea931703dd) -- [Dev Deps] update `eslint` [`9411294`](https://github.com/inspect-js/object-inspect/commit/94112944b9245e3302e25453277876402d207e7f) -- [meta] `require-allow-edits` no longer requires an explicit github token [`36c0220`](https://github.com/inspect-js/object-inspect/commit/36c02205de3c2b0e84d53777c5c9fd54a36c48ab) -- [actions] update rebase checkout action to v2 [`55a39a6`](https://github.com/inspect-js/object-inspect/commit/55a39a64e944f19c6a7d8efddf3df27700f20d14) -- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`f59fd3c`](https://github.com/inspect-js/object-inspect/commit/f59fd3cf406c3a7c7ece140904a80bbc6bacfcca) -- [Dev Deps] update `eslint` [`a492bec`](https://github.com/inspect-js/object-inspect/commit/a492becec644b0155c9c4bc1caf6f9fac11fb2c7) - -## [v1.8.0](https://github.com/inspect-js/object-inspect/compare/v1.7.0...v1.8.0) - 2020-06-18 - -### Fixed - -- [New] add `indent` option [`#27`](https://github.com/inspect-js/object-inspect/issues/27) - -### Commits - -- [Tests] add codecov [`4324cbb`](https://github.com/inspect-js/object-inspect/commit/4324cbb1a2bd7710822a4151ff373570db22453e) -- [New] add `maxStringLength` option [`b3995cb`](https://github.com/inspect-js/object-inspect/commit/b3995cb71e15b5ee127a3094c43994df9d973502) -- [New] add `customInspect` option, to disable custom inspect methods [`28b9179`](https://github.com/inspect-js/object-inspect/commit/28b9179ee802bb3b90810100c11637db90c2fb6d) -- [Tests] add Date and RegExp tests [`3b28eca`](https://github.com/inspect-js/object-inspect/commit/3b28eca57b0367aeadffac604ea09e8bdae7d97b) -- [actions] add automatic rebasing / merge commit blocking [`0d9c6c0`](https://github.com/inspect-js/object-inspect/commit/0d9c6c044e83475ff0bfffb9d35b149834c83a2e) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `tape`; add `aud` [`7c204f2`](https://github.com/inspect-js/object-inspect/commit/7c204f22b9e41bc97147f4d32d4cb045b17769a6) -- [readme] fix repo URLs, remove testling [`34ca9a0`](https://github.com/inspect-js/object-inspect/commit/34ca9a0dabfe75bd311f806a326fadad029909a3) -- [Fix] when truncating a deep array, note it as `[Array]` instead of just `[Object]` [`f74c82d`](https://github.com/inspect-js/object-inspect/commit/f74c82dd0b35386445510deb250f34c41be3ec0e) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`1a8a5ea`](https://github.com/inspect-js/object-inspect/commit/1a8a5ea069ea2bee89d77caedad83ffa23d35711) -- [Fix] do not be fooled by a function’s own `toString` method [`7cb5c65`](https://github.com/inspect-js/object-inspect/commit/7cb5c657a976f94715c19c10556a30f15bb7d5d7) -- [patch] indicate explicitly that anon functions are anonymous, to match node [`81ebdd4`](https://github.com/inspect-js/object-inspect/commit/81ebdd4215005144074bbdff3f6bafa01407910a) -- [Dev Deps] loosen the `core-js` dep [`e7472e8`](https://github.com/inspect-js/object-inspect/commit/e7472e8e242117670560bd995830c2a4d12080f5) -- [Dev Deps] update `tape` [`699827e`](https://github.com/inspect-js/object-inspect/commit/699827e6b37258b5203c33c78c009bf4b0e6a66d) -- [meta] add `safe-publish-latest` [`c5d2868`](https://github.com/inspect-js/object-inspect/commit/c5d2868d6eb33c472f37a20f89ceef2787046088) -- [Dev Deps] update `@ljharb/eslint-config` [`9199501`](https://github.com/inspect-js/object-inspect/commit/919950195d486114ccebacbdf9d74d7f382693b0) - -## [v1.7.0](https://github.com/inspect-js/object-inspect/compare/v1.6.0...v1.7.0) - 2019-11-10 - -### Commits - -- [Tests] use shared travis-ci configs [`19899ed`](https://github.com/inspect-js/object-inspect/commit/19899edbf31f4f8809acf745ce34ad1ce1bfa63b) -- [Tests] add linting [`a00f057`](https://github.com/inspect-js/object-inspect/commit/a00f057d917f66ea26dd37769c6b810ec4af97e8) -- [Tests] lint last file [`2698047`](https://github.com/inspect-js/object-inspect/commit/2698047b58af1e2e88061598ef37a75f228dddf6) -- [Tests] up to `node` `v12.7`, `v11.15`, `v10.16`, `v8.16`, `v6.17` [`589e87a`](https://github.com/inspect-js/object-inspect/commit/589e87a99cadcff4b600e6a303418e9d922836e8) -- [New] add support for `WeakMap` and `WeakSet` [`3ddb3e4`](https://github.com/inspect-js/object-inspect/commit/3ddb3e4e0c8287130c61a12e0ed9c104b1549306) -- [meta] clean up license so github can detect it properly [`27527bb`](https://github.com/inspect-js/object-inspect/commit/27527bb801520c9610c68cc3b55d6f20a2bee56d) -- [Tests] cover `util.inspect.custom` [`36d47b9`](https://github.com/inspect-js/object-inspect/commit/36d47b9c59056a57ef2f1491602c726359561800) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `tape` [`b614eaa`](https://github.com/inspect-js/object-inspect/commit/b614eaac901da0e5c69151f534671f990a94cace) -- [Tests] fix coverage thresholds [`7b7b176`](https://github.com/inspect-js/object-inspect/commit/7b7b176e15f8bd6e8b2f261ff5a493c2fe78d9c2) -- [Tests] bigint tests now can run on unflagged node [`063af31`](https://github.com/inspect-js/object-inspect/commit/063af31ce9cd13c202e3b67c07ba06dc9b7c0f81) -- [Refactor] add early bailout to `isMap` and `isSet` checks [`fc51047`](https://github.com/inspect-js/object-inspect/commit/fc5104714a3671d37e225813db79470d6335683b) -- [meta] add `funding` field [`7f9953a`](https://github.com/inspect-js/object-inspect/commit/7f9953a113eec7b064a6393cf9f90ba15f1d131b) -- [Tests] Fix invalid strict-mode syntax with hexadecimal [`a8b5425`](https://github.com/inspect-js/object-inspect/commit/a8b542503b4af1599a275209a1a99f5fdedb1ead) -- [Dev Deps] update `@ljharb/eslint-config` [`98df157`](https://github.com/inspect-js/object-inspect/commit/98df1577314d9188a3fc3f17fdcf2fba697ae1bd) -- add copyright to LICENSE [`bb69fd0`](https://github.com/inspect-js/object-inspect/commit/bb69fd017a062d299e44da1f9b2c7dcd67f621e6) -- [Tests] use `npx aud` in `posttest` [`4838353`](https://github.com/inspect-js/object-inspect/commit/4838353593974cf7f905b9ef04c03c094f0cdbe2) -- [Tests] move `0.6` to allowed failures, because it won‘t build on travis [`1bff32a`](https://github.com/inspect-js/object-inspect/commit/1bff32aa52e8aea687f0856b28ba754b3e43ebf7) - -## [v1.6.0](https://github.com/inspect-js/object-inspect/compare/v1.5.0...v1.6.0) - 2018-05-02 - -### Commits - -- [New] add support for boxed BigInt primitives [`356c66a`](https://github.com/inspect-js/object-inspect/commit/356c66a410e7aece7162c8319880a5ef647beaa9) -- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9` [`c77b65b`](https://github.com/inspect-js/object-inspect/commit/c77b65bba593811b906b9ec57561c5cba92e2db3) -- [New] Add support for upcoming `BigInt` [`1ac548e`](https://github.com/inspect-js/object-inspect/commit/1ac548e4b27e26466c28c9a5e63e5d4e0591c31f) -- [Tests] run bigint tests in CI with --harmony-bigint flag [`d31b738`](https://github.com/inspect-js/object-inspect/commit/d31b73831880254b5c6cf5691cda9a149fbc5f04) -- [Dev Deps] update `core-js`, `tape` [`ff9eff6`](https://github.com/inspect-js/object-inspect/commit/ff9eff67113341ee1aaf80c1c22d683f43bfbccf) -- [Docs] fix example to use `safer-buffer` [`48cae12`](https://github.com/inspect-js/object-inspect/commit/48cae12a73ec6cacc955175bc56bbe6aee6a211f) - -## [v1.5.0](https://github.com/inspect-js/object-inspect/compare/v1.4.1...v1.5.0) - 2017-12-25 - -### Commits - -- [New] add `quoteStyle` option [`f5a72d2`](https://github.com/inspect-js/object-inspect/commit/f5a72d26edb3959b048f74c056ca7100a6b091e4) -- [Tests] add more test coverage [`30ebe4e`](https://github.com/inspect-js/object-inspect/commit/30ebe4e1fa943b99ecbb85be7614256d536e2759) -- [Tests] require 0.6 to pass [`99a008c`](https://github.com/inspect-js/object-inspect/commit/99a008ccace189a60fd7da18bf00e32c9572b980) - -## [v1.4.1](https://github.com/inspect-js/object-inspect/compare/v1.4.0...v1.4.1) - 2017-12-19 - -### Commits - -- [Tests] up to `node` `v9.3`, `v8.9`, `v6.12` [`6674476`](https://github.com/inspect-js/object-inspect/commit/6674476cc56acaac1bde96c84fed5ef631911906) -- [Fix] `inspect(Object(-0))` should be “Object(-0)”, not “Object(0)” [`d0a031f`](https://github.com/inspect-js/object-inspect/commit/d0a031f1cbb3024ee9982bfe364dd18a7e4d1bd3) - -## [v1.4.0](https://github.com/inspect-js/object-inspect/compare/v1.3.0...v1.4.0) - 2017-10-24 - -### Commits - -- [Tests] add `npm run coverage` [`3b48fb2`](https://github.com/inspect-js/object-inspect/commit/3b48fb25db037235eeb808f0b2830aad7aa36f70) -- [Tests] remove commented-out osx builds [`71e24db`](https://github.com/inspect-js/object-inspect/commit/71e24db8ad6ee3b9b381c5300b0475f2ba595a73) -- [New] add support for `util.inspect.custom`, in node only. [`20cca77`](https://github.com/inspect-js/object-inspect/commit/20cca7762d7e17f15b21a90793dff84acce155df) -- [Tests] up to `node` `v8.6`; use `nvm install-latest-npm` to ensure new npm doesn’t break old node [`252952d`](https://github.com/inspect-js/object-inspect/commit/252952d230d8065851dd3d4d5fe8398aae068529) -- [Tests] up to `node` `v8.8` [`4aa868d`](https://github.com/inspect-js/object-inspect/commit/4aa868d3a62914091d489dd6ec6eed194ee67cd3) -- [Dev Deps] update `core-js`, `tape` [`59483d1`](https://github.com/inspect-js/object-inspect/commit/59483d1df418f852f51fa0db7b24aa6b0209a27a) - -## [v1.3.0](https://github.com/inspect-js/object-inspect/compare/v1.2.2...v1.3.0) - 2017-07-31 - -### Fixed - -- [Fix] Map/Set: work around core-js bug < v2.5.0 [`#9`](https://github.com/inspect-js/object-inspect/issues/9) - -### Commits - -- [New] add support for arrays with additional object keys [`0d19937`](https://github.com/inspect-js/object-inspect/commit/0d199374ee37959e51539616666f420ccb29acb9) -- [Tests] up to `node` `v8.2`, `v7.10`, `v6.11`; fix new npm breaking on older nodes [`e24784a`](https://github.com/inspect-js/object-inspect/commit/e24784a90c49117787157a12a63897c49cf89bbb) -- Only apps should have lockfiles [`c6faebc`](https://github.com/inspect-js/object-inspect/commit/c6faebcb2ee486a889a4a1c4d78c0776c7576185) -- [Dev Deps] update `tape` [`7345a0a`](https://github.com/inspect-js/object-inspect/commit/7345a0aeba7e91b888a079c10004d17696a7f586) - -## [v1.2.2](https://github.com/inspect-js/object-inspect/compare/v1.2.1...v1.2.2) - 2017-03-24 - -### Commits - -- [Tests] up to `node` `v7.7`, `v6.10`, `v4.8`; improve test matrix [`a2ddc15`](https://github.com/inspect-js/object-inspect/commit/a2ddc15a1f2c65af18076eea1c0eb9cbceb478a0) -- [Tests] up to `node` `v7.0`, `v6.9`, `v5.12`, `v4.6`, `io.js` `v3.3`; improve test matrix [`a48949f`](https://github.com/inspect-js/object-inspect/commit/a48949f6b574b2d4d2298109d8e8d0eb3e7a83e7) -- [Performance] check for primitive types as early as possible. [`3b8092a`](https://github.com/inspect-js/object-inspect/commit/3b8092a2a4deffd0575f94334f00194e2d48dad3) -- [Refactor] remove unneeded `else`s. [`7255034`](https://github.com/inspect-js/object-inspect/commit/725503402e08de4f96f6bf2d8edef44ac36f26b6) -- [Refactor] avoid recreating `lowbyte` function every time. [`81edd34`](https://github.com/inspect-js/object-inspect/commit/81edd3475bd15bdd18e84de7472033dcf5004aaa) -- [Fix] differentiate -0 from 0 [`521d345`](https://github.com/inspect-js/object-inspect/commit/521d3456b009da7bf1c5785c8a9df5a9f8718264) -- [Refactor] move object key gathering into separate function [`aca6265`](https://github.com/inspect-js/object-inspect/commit/aca626536eaeef697196c6e9db3e90e7e0355b6a) -- [Refactor] consolidate wrapping logic for boxed primitives into a function. [`4e440cd`](https://github.com/inspect-js/object-inspect/commit/4e440cd9065df04802a2a1dead03f48c353ca301) -- [Robustness] use `typeof` instead of comparing to literal `undefined` [`5ca6f60`](https://github.com/inspect-js/object-inspect/commit/5ca6f601937506daff8ed2fcf686363b55807b69) -- [Refactor] consolidate Map/Set notations. [`4e576e5`](https://github.com/inspect-js/object-inspect/commit/4e576e5d7ed2f9ec3fb7f37a0d16732eb10758a9) -- [Tests] ensure that this function remains anonymous, despite ES6 name inference. [`7540ae5`](https://github.com/inspect-js/object-inspect/commit/7540ae591278756db614fa4def55ca413150e1a3) -- [Refactor] explicitly coerce Error objects to strings. [`7f4ca84`](https://github.com/inspect-js/object-inspect/commit/7f4ca8424ee8dc2c0ca5a422d94f7fac40327261) -- [Refactor] split up `var` declarations for debuggability [`6f2c11e`](https://github.com/inspect-js/object-inspect/commit/6f2c11e6a85418586a00292dcec5e97683f89bc3) -- [Robustness] cache `Object.prototype.toString` [`df44a20`](https://github.com/inspect-js/object-inspect/commit/df44a20adfccf31529d60d1df2079bfc3c836e27) -- [Dev Deps] update `tape` [`3ec714e`](https://github.com/inspect-js/object-inspect/commit/3ec714eba57bc3f58a6eb4fca1376f49e70d300a) -- [Dev Deps] update `tape` [`beb72d9`](https://github.com/inspect-js/object-inspect/commit/beb72d969653747d7cde300393c28755375329b0) - -## [v1.2.1](https://github.com/inspect-js/object-inspect/compare/v1.2.0...v1.2.1) - 2016-04-09 - -### Fixed - -- [Fix] fix Boolean `false` object inspection. [`#7`](https://github.com/substack/object-inspect/pull/7) - -## [v1.2.0](https://github.com/inspect-js/object-inspect/compare/v1.1.0...v1.2.0) - 2016-04-09 - -### Fixed - -- [New] add support for inspecting String/Number/Boolean objects. [`#6`](https://github.com/inspect-js/object-inspect/issues/6) - -### Commits - -- [Dev Deps] update `tape` [`742caa2`](https://github.com/inspect-js/object-inspect/commit/742caa262cf7af4c815d4821c8bd0129c1446432) - -## [v1.1.0](https://github.com/inspect-js/object-inspect/compare/1.0.2...v1.1.0) - 2015-12-14 - -### Merged - -- [New] add ES6 Map/Set support. [`#4`](https://github.com/inspect-js/object-inspect/pull/4) - -### Fixed - -- [New] add ES6 Map/Set support. [`#3`](https://github.com/inspect-js/object-inspect/issues/3) - -### Commits - -- Update `travis.yml` to test on bunches of `iojs` and `node` versions. [`4c1fd65`](https://github.com/inspect-js/object-inspect/commit/4c1fd65cc3bd95307e854d114b90478324287fd2) -- [Dev Deps] update `tape` [`88a907e`](https://github.com/inspect-js/object-inspect/commit/88a907e33afbe408e4b5d6e4e42a33143f88848c) - -## [1.0.2](https://github.com/inspect-js/object-inspect/compare/1.0.1...1.0.2) - 2015-08-07 - -### Commits - -- [Fix] Cache `Object.prototype.hasOwnProperty` in case it's deleted later. [`1d0075d`](https://github.com/inspect-js/object-inspect/commit/1d0075d3091dc82246feeb1f9871cb2b8ed227b3) -- [Dev Deps] Update `tape` [`ca8d5d7`](https://github.com/inspect-js/object-inspect/commit/ca8d5d75635ddbf76f944e628267581e04958457) -- gitignore node_modules since this is a reusable modules. [`ed41407`](https://github.com/inspect-js/object-inspect/commit/ed41407811743ca530cdeb28f982beb96026af82) - -## [1.0.1](https://github.com/inspect-js/object-inspect/compare/1.0.0...1.0.1) - 2015-07-19 - -### Commits - -- Make `inspect` work with symbol primitives and objects, including in node 0.11 and 0.12. [`ddf1b94`](https://github.com/inspect-js/object-inspect/commit/ddf1b94475ab951f1e3bccdc0a48e9073cfbfef4) -- bump tape [`103d674`](https://github.com/inspect-js/object-inspect/commit/103d67496b504bdcfdd765d303a773f87ec106e2) -- use newer travis config [`d497276`](https://github.com/inspect-js/object-inspect/commit/d497276c1da14234bb5098a59cf20de75fbc316a) - -## [1.0.0](https://github.com/inspect-js/object-inspect/compare/0.4.0...1.0.0) - 2014-08-05 - -### Commits - -- error inspect works properly [`260a22d`](https://github.com/inspect-js/object-inspect/commit/260a22d134d3a8a482c67d52091c6040c34f4299) -- seen coverage [`57269e8`](https://github.com/inspect-js/object-inspect/commit/57269e8baa992a7439047f47325111fdcbcb8417) -- htmlelement instance coverage [`397ffe1`](https://github.com/inspect-js/object-inspect/commit/397ffe10a1980350868043ef9de65686d438979f) -- more element coverage [`6905cc2`](https://github.com/inspect-js/object-inspect/commit/6905cc2f7df35600177e613b0642b4df5efd3eca) -- failing test for type errors [`385b615`](https://github.com/inspect-js/object-inspect/commit/385b6152e49b51b68449a662f410b084ed7c601a) -- fn name coverage [`edc906d`](https://github.com/inspect-js/object-inspect/commit/edc906d40fca6b9194d304062c037ee8e398c4c2) -- server-side element test [`362d1d3`](https://github.com/inspect-js/object-inspect/commit/362d1d3e86f187651c29feeb8478110afada385b) -- custom inspect fn [`e89b0f6`](https://github.com/inspect-js/object-inspect/commit/e89b0f6fe6d5e03681282af83732a509160435a6) -- fixed browser test [`b530882`](https://github.com/inspect-js/object-inspect/commit/b5308824a1c8471c5617e394766a03a6977102a9) -- depth test, matches node [`1cfd9e0`](https://github.com/inspect-js/object-inspect/commit/1cfd9e0285a4ae1dff44101ad482915d9bf47e48) -- exercise hasOwnProperty path [`8d753fb`](https://github.com/inspect-js/object-inspect/commit/8d753fb362a534fa1106e4d80f2ee9bea06a66d9) -- more cases covered for errors [`c5c46a5`](https://github.com/inspect-js/object-inspect/commit/c5c46a569ec4606583497e8550f0d8c7ad39a4a4) -- \W obj key test case [`b0eceee`](https://github.com/inspect-js/object-inspect/commit/b0eceeea6e0eb94d686c1046e99b9e25e5005f75) -- coverage for explicit depth param [`e12b91c`](https://github.com/inspect-js/object-inspect/commit/e12b91cd59683362f3a0e80f46481a0211e26c15) - -## [0.4.0](https://github.com/inspect-js/object-inspect/compare/0.3.1...0.4.0) - 2014-03-21 - -### Commits - -- passing lowbyte interpolation test [`b847511`](https://github.com/inspect-js/object-inspect/commit/b8475114f5def7e7961c5353d48d3d8d9a520985) -- lowbyte test [`4a2b0e1`](https://github.com/inspect-js/object-inspect/commit/4a2b0e142667fc933f195472759385ac08f3946c) - -## [0.3.1](https://github.com/inspect-js/object-inspect/compare/0.3.0...0.3.1) - 2014-03-04 - -### Commits - -- sort keys [`a07b19c`](https://github.com/inspect-js/object-inspect/commit/a07b19cc3b1521a82d4fafb6368b7a9775428a05) - -## [0.3.0](https://github.com/inspect-js/object-inspect/compare/0.2.0...0.3.0) - 2014-03-04 - -### Commits - -- [] and {} instead of [ ] and { } [`654c44b`](https://github.com/inspect-js/object-inspect/commit/654c44b2865811f3519e57bb8526e0821caf5c6b) - -## [0.2.0](https://github.com/inspect-js/object-inspect/compare/0.1.3...0.2.0) - 2014-03-04 - -### Commits - -- failing holes test [`99cdfad`](https://github.com/inspect-js/object-inspect/commit/99cdfad03c6474740275a75636fe6ca86c77737a) -- regex already work [`e324033`](https://github.com/inspect-js/object-inspect/commit/e324033267025995ec97d32ed0a65737c99477a6) -- failing undef/null test [`1f88a00`](https://github.com/inspect-js/object-inspect/commit/1f88a00265d3209719dda8117b7e6360b4c20943) -- holes in the all example [`7d345f3`](https://github.com/inspect-js/object-inspect/commit/7d345f3676dcbe980cff89a4f6c243269ebbb709) -- check for .inspect(), fixes Buffer use-case [`c3f7546`](https://github.com/inspect-js/object-inspect/commit/c3f75466dbca125347d49847c05262c292f12b79) -- fixes for holes [`ce25f73`](https://github.com/inspect-js/object-inspect/commit/ce25f736683de4b92ff27dc5471218415e2d78d8) -- weird null behavior [`405c1ea`](https://github.com/inspect-js/object-inspect/commit/405c1ea72cd5a8cf3b498c3eaa903d01b9fbcab5) -- tape is actually a devDependency, upgrade [`703b0ce`](https://github.com/inspect-js/object-inspect/commit/703b0ce6c5817b4245a082564bccd877e0bb6990) -- put date in the example [`a342219`](https://github.com/inspect-js/object-inspect/commit/a3422190eeaa013215f46df2d0d37b48595ac058) -- passing the null test [`4ab737e`](https://github.com/inspect-js/object-inspect/commit/4ab737ebf862a75d247ebe51e79307a34d6380d4) - -## [0.1.3](https://github.com/inspect-js/object-inspect/compare/0.1.1...0.1.3) - 2013-07-26 - -### Commits - -- special isElement() check [`882768a`](https://github.com/inspect-js/object-inspect/commit/882768a54035d30747be9de1baf14e5aa0daa128) -- oh right old IEs don't have indexOf either [`36d1275`](https://github.com/inspect-js/object-inspect/commit/36d12756c38b08a74370b0bb696c809e529913a5) - -## [0.1.1](https://github.com/inspect-js/object-inspect/compare/0.1.0...0.1.1) - 2013-07-26 - -### Commits - -- tests! [`4422fd9`](https://github.com/inspect-js/object-inspect/commit/4422fd95532c2745aa6c4f786f35f1090be29998) -- fix for ie<9, doesn't have hasOwnProperty [`6b7d611`](https://github.com/inspect-js/object-inspect/commit/6b7d61183050f6da801ea04473211da226482613) -- fix for all IEs: no f.name [`4e0c2f6`](https://github.com/inspect-js/object-inspect/commit/4e0c2f6dfd01c306d067d7163319acc97c94ee50) -- badges [`5ed0d88`](https://github.com/inspect-js/object-inspect/commit/5ed0d88e4e407f9cb327fa4a146c17921f9680f3) - -## [0.1.0](https://github.com/inspect-js/object-inspect/compare/0.0.0...0.1.0) - 2013-07-26 - -### Commits - -- [Function] for functions [`ad5c485`](https://github.com/inspect-js/object-inspect/commit/ad5c485098fc83352cb540a60b2548ca56820e0b) - -## 0.0.0 - 2013-07-26 - -### Commits - -- working browser example [`34be6b6`](https://github.com/inspect-js/object-inspect/commit/34be6b6548f9ce92bdc3c27572857ba0c4a1218d) -- package.json etc [`cad51f2`](https://github.com/inspect-js/object-inspect/commit/cad51f23fc6bcf1a456ed6abe16088256c2f632f) -- docs complete [`b80cce2`](https://github.com/inspect-js/object-inspect/commit/b80cce2490c4e7183a9ee11ea89071f0abec4446) -- circular example [`4b4a7b9`](https://github.com/inspect-js/object-inspect/commit/4b4a7b92209e4e6b4630976cb6bcd17d14165a59) -- string rep [`7afb479`](https://github.com/inspect-js/object-inspect/commit/7afb479baa798d27f09e0a178b72ea327f60f5c8) diff --git a/spaces/fffiloni/lama-video-watermark-remover/bin/make_checkpoint.py b/spaces/fffiloni/lama-video-watermark-remover/bin/make_checkpoint.py deleted file mode 100644 index 322147483915bef758770ae931e705e56083fa8d..0000000000000000000000000000000000000000 --- a/spaces/fffiloni/lama-video-watermark-remover/bin/make_checkpoint.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python3 - -import os -import shutil - -import torch - - -def get_checkpoint_files(s): - s = s.strip() - if ',' in s: - return [get_checkpoint_files(chunk) for chunk in s.split(',')] - return 'last.ckpt' if s == 'last' else f'{s}.ckpt' - - -def main(args): - checkpoint_fnames = get_checkpoint_files(args.epochs) - if isinstance(checkpoint_fnames, str): - checkpoint_fnames = [checkpoint_fnames] - assert len(checkpoint_fnames) >= 1 - - checkpoint_path = os.path.join(args.indir, 'models', checkpoint_fnames[0]) - checkpoint = torch.load(checkpoint_path, map_location='cpu') - del checkpoint['optimizer_states'] - - if len(checkpoint_fnames) > 1: - for fname in checkpoint_fnames[1:]: - print('sum', fname) - sum_tensors_cnt = 0 - other_cp = torch.load(os.path.join(args.indir, 'models', fname), map_location='cpu') - for k in checkpoint['state_dict'].keys(): - if checkpoint['state_dict'][k].dtype is torch.float: - checkpoint['state_dict'][k].data.add_(other_cp['state_dict'][k].data) - sum_tensors_cnt += 1 - print('summed', sum_tensors_cnt, 'tensors') - - for k in checkpoint['state_dict'].keys(): - if checkpoint['state_dict'][k].dtype is torch.float: - checkpoint['state_dict'][k].data.mul_(1 / float(len(checkpoint_fnames))) - - state_dict = checkpoint['state_dict'] - - if not args.leave_discriminators: - for k in list(state_dict.keys()): - if k.startswith('discriminator.'): - del state_dict[k] - - if not args.leave_losses: - for k in list(state_dict.keys()): - if k.startswith('loss_'): - del state_dict[k] - - out_checkpoint_path = os.path.join(args.outdir, 'models', 'best.ckpt') - os.makedirs(os.path.dirname(out_checkpoint_path), exist_ok=True) - - torch.save(checkpoint, out_checkpoint_path) - - shutil.copy2(os.path.join(args.indir, 'config.yaml'), - os.path.join(args.outdir, 'config.yaml')) - - -if __name__ == '__main__': - import argparse - - aparser = argparse.ArgumentParser() - aparser.add_argument('indir', - help='Path to directory with output of training ' - '(i.e. directory, which has samples, modules, config.yaml and train.log') - aparser.add_argument('outdir', - help='Where to put minimal checkpoint, which can be consumed by "bin/predict.py"') - aparser.add_argument('--epochs', type=str, default='last', - help='Which checkpoint to take. ' - 'Can be "last" or integer - number of epoch') - aparser.add_argument('--leave-discriminators', action='store_true', - help='If enabled, the state of discriminators will not be removed from the checkpoint') - aparser.add_argument('--leave-losses', action='store_true', - help='If enabled, weights of nn-based losses (e.g. perceptual) will not be removed') - - main(aparser.parse_args()) diff --git a/spaces/fh2412/handwritten_numbers/app.py b/spaces/fh2412/handwritten_numbers/app.py deleted file mode 100644 index 1a69ab2b1524c634109455f9689244b80801f9d6..0000000000000000000000000000000000000000 --- a/spaces/fh2412/handwritten_numbers/app.py +++ /dev/null @@ -1,16 +0,0 @@ -from fastai.vision.all import * -import gradio as gr -from fastai.vision.all import PILImage - -learn = load_learner('model.pkl') -categories = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') - -def predict(img): - pred, idx, probs = learn.predict(PILImage.create(img)) - return dict(zip(categories, map(float,probs))) - -label = gr.outputs.Label() -sp = gr.Sketchpad(shape=(28, 28), image_mode="L") - -intf = gr.Interface(fn=predict, inputs=sp, outputs=label) -intf.launch(inline=False) \ No newline at end of file diff --git a/spaces/fuckyoudeki/AutoGPT/autogpt/logs.py b/spaces/fuckyoudeki/AutoGPT/autogpt/logs.py deleted file mode 100644 index 35037404a98f7be9b7d577b625cc190ca27f4566..0000000000000000000000000000000000000000 --- a/spaces/fuckyoudeki/AutoGPT/autogpt/logs.py +++ /dev/null @@ -1,332 +0,0 @@ -"""Logging module for Auto-GPT.""" -import json -import logging -import os -import random -import re -import time -import traceback -from logging import LogRecord - -from colorama import Fore, Style - -from autogpt.config import Config, Singleton -from autogpt.speech import say_text - -CFG = Config() - - -class Logger(metaclass=Singleton): - """ - Logger that handle titles in different colors. - Outputs logs in console, activity.log, and errors.log - For console handler: simulates typing - """ - - def __init__(self): - # create log directory if it doesn't exist - this_files_dir_path = os.path.dirname(__file__) - log_dir = os.path.join(this_files_dir_path, "../logs") - if not os.path.exists(log_dir): - os.makedirs(log_dir) - - log_file = "activity.log" - error_file = "error.log" - - console_formatter = AutoGptFormatter("%(title_color)s %(message)s") - - # Create a handler for console which simulate typing - self.typing_console_handler = TypingConsoleHandler() - self.typing_console_handler.setLevel(logging.INFO) - self.typing_console_handler.setFormatter(console_formatter) - - # Create a handler for console without typing simulation - self.console_handler = ConsoleHandler() - self.console_handler.setLevel(logging.DEBUG) - self.console_handler.setFormatter(console_formatter) - - # Info handler in activity.log - self.file_handler = logging.FileHandler( - os.path.join(log_dir, log_file), "a", "utf-8" - ) - self.file_handler.setLevel(logging.DEBUG) - info_formatter = AutoGptFormatter( - "%(asctime)s %(levelname)s %(title)s %(message_no_color)s" - ) - self.file_handler.setFormatter(info_formatter) - - # Error handler error.log - error_handler = logging.FileHandler( - os.path.join(log_dir, error_file), "a", "utf-8" - ) - error_handler.setLevel(logging.ERROR) - error_formatter = AutoGptFormatter( - "%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s" - " %(message_no_color)s" - ) - error_handler.setFormatter(error_formatter) - - self.typing_logger = logging.getLogger("TYPER") - self.typing_logger.addHandler(self.typing_console_handler) - self.typing_logger.addHandler(self.file_handler) - self.typing_logger.addHandler(error_handler) - self.typing_logger.setLevel(logging.DEBUG) - - self.logger = logging.getLogger("LOGGER") - self.logger.addHandler(self.console_handler) - self.logger.addHandler(self.file_handler) - self.logger.addHandler(error_handler) - self.logger.setLevel(logging.DEBUG) - - def typewriter_log( - self, title="", title_color="", content="", speak_text=False, level=logging.INFO - ): - if speak_text and CFG.speak_mode: - say_text(f"{title}. {content}") - - if content: - if isinstance(content, list): - content = " ".join(content) - else: - content = "" - - self.typing_logger.log( - level, content, extra={"title": title, "color": title_color} - ) - - def debug( - self, - message, - title="", - title_color="", - ): - self._log(title, title_color, message, logging.DEBUG) - - def warn( - self, - message, - title="", - title_color="", - ): - self._log(title, title_color, message, logging.WARN) - - def error(self, title, message=""): - self._log(title, Fore.RED, message, logging.ERROR) - - def _log(self, title="", title_color="", message="", level=logging.INFO): - if message: - if isinstance(message, list): - message = " ".join(message) - self.logger.log(level, message, extra={"title": title, "color": title_color}) - - def set_level(self, level): - self.logger.setLevel(level) - self.typing_logger.setLevel(level) - - def double_check(self, additionalText=None): - if not additionalText: - additionalText = ( - "Please ensure you've setup and configured everything" - " correctly. Read https://github.com/Torantulino/Auto-GPT#readme to " - "double check. You can also create a github issue or join the discord" - " and ask there!" - ) - - self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText) - - -""" -Output stream to console using simulated typing -""" - - -class TypingConsoleHandler(logging.StreamHandler): - def emit(self, record): - min_typing_speed = 0.05 - max_typing_speed = 0.01 - - msg = self.format(record) - try: - words = msg.split() - for i, word in enumerate(words): - print(word, end="", flush=True) - if i < len(words) - 1: - print(" ", end="", flush=True) - typing_speed = random.uniform(min_typing_speed, max_typing_speed) - time.sleep(typing_speed) - # type faster after each word - min_typing_speed = min_typing_speed * 0.95 - max_typing_speed = max_typing_speed * 0.95 - print() - except Exception: - self.handleError(record) - - -class ConsoleHandler(logging.StreamHandler): - def emit(self, record) -> None: - msg = self.format(record) - try: - print(msg) - except Exception: - self.handleError(record) - - -class AutoGptFormatter(logging.Formatter): - """ - Allows to handle custom placeholders 'title_color' and 'message_no_color'. - To use this formatter, make sure to pass 'color', 'title' as log extras. - """ - - def format(self, record: LogRecord) -> str: - if hasattr(record, "color"): - record.title_color = ( - getattr(record, "color") - + getattr(record, "title") - + " " - + Style.RESET_ALL - ) - else: - record.title_color = getattr(record, "title") - if hasattr(record, "msg"): - record.message_no_color = remove_color_codes(getattr(record, "msg")) - else: - record.message_no_color = "" - return super().format(record) - - -def remove_color_codes(s: str) -> str: - ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])") - return ansi_escape.sub("", s) - - -logger = Logger() - - -def print_assistant_thoughts(ai_name, assistant_reply): - """Prints the assistant's thoughts to the console""" - from autogpt.json_utils.json_fix_llm import ( - attempt_to_fix_json_by_finding_outermost_brackets, - fix_and_parse_json, - ) - - try: - try: - # Parse and print Assistant response - assistant_reply_json = fix_and_parse_json(assistant_reply) - except json.JSONDecodeError: - logger.error("Error: Invalid JSON in assistant thoughts\n", assistant_reply) - assistant_reply_json = attempt_to_fix_json_by_finding_outermost_brackets( - assistant_reply - ) - if isinstance(assistant_reply_json, str): - assistant_reply_json = fix_and_parse_json(assistant_reply_json) - - # Check if assistant_reply_json is a string and attempt to parse - # it into a JSON object - if isinstance(assistant_reply_json, str): - try: - assistant_reply_json = json.loads(assistant_reply_json) - except json.JSONDecodeError: - logger.error("Error: Invalid JSON\n", assistant_reply) - assistant_reply_json = ( - attempt_to_fix_json_by_finding_outermost_brackets( - assistant_reply_json - ) - ) - - assistant_thoughts_reasoning = None - assistant_thoughts_plan = None - assistant_thoughts_speak = None - assistant_thoughts_criticism = None - if not isinstance(assistant_reply_json, dict): - assistant_reply_json = {} - assistant_thoughts = assistant_reply_json.get("thoughts", {}) - assistant_thoughts_text = assistant_thoughts.get("text") - - if assistant_thoughts: - assistant_thoughts_reasoning = assistant_thoughts.get("reasoning") - assistant_thoughts_plan = assistant_thoughts.get("plan") - assistant_thoughts_criticism = assistant_thoughts.get("criticism") - assistant_thoughts_speak = assistant_thoughts.get("speak") - - logger.typewriter_log( - f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}" - ) - logger.typewriter_log( - "REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}" - ) - - if assistant_thoughts_plan: - logger.typewriter_log("PLAN:", Fore.YELLOW, "") - # If it's a list, join it into a string - if isinstance(assistant_thoughts_plan, list): - assistant_thoughts_plan = "\n".join(assistant_thoughts_plan) - elif isinstance(assistant_thoughts_plan, dict): - assistant_thoughts_plan = str(assistant_thoughts_plan) - - # Split the input_string using the newline character and dashes - lines = assistant_thoughts_plan.split("\n") - for line in lines: - line = line.lstrip("- ") - logger.typewriter_log("- ", Fore.GREEN, line.strip()) - - logger.typewriter_log( - "CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}" - ) - # Speak the assistant's thoughts - if CFG.speak_mode and assistant_thoughts_speak: - say_text(assistant_thoughts_speak) - else: - logger.typewriter_log("SPEAK:", Fore.YELLOW, f"{assistant_thoughts_speak}") - - return assistant_reply_json - except json.decoder.JSONDecodeError: - logger.error("Error: Invalid JSON\n", assistant_reply) - if CFG.speak_mode: - say_text( - "I have received an invalid JSON response from the OpenAI API." - " I cannot ignore this response." - ) - - # All other errors, return "Error: + error message" - except Exception: - call_stack = traceback.format_exc() - logger.error("Error: \n", call_stack) - - -def print_assistant_thoughts( - ai_name: object, assistant_reply_json_valid: object -) -> None: - assistant_thoughts_reasoning = None - assistant_thoughts_plan = None - assistant_thoughts_speak = None - assistant_thoughts_criticism = None - - assistant_thoughts = assistant_reply_json_valid.get("thoughts", {}) - assistant_thoughts_text = assistant_thoughts.get("text") - if assistant_thoughts: - assistant_thoughts_reasoning = assistant_thoughts.get("reasoning") - assistant_thoughts_plan = assistant_thoughts.get("plan") - assistant_thoughts_criticism = assistant_thoughts.get("criticism") - assistant_thoughts_speak = assistant_thoughts.get("speak") - logger.typewriter_log( - f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}" - ) - logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}") - if assistant_thoughts_plan: - logger.typewriter_log("PLAN:", Fore.YELLOW, "") - # If it's a list, join it into a string - if isinstance(assistant_thoughts_plan, list): - assistant_thoughts_plan = "\n".join(assistant_thoughts_plan) - elif isinstance(assistant_thoughts_plan, dict): - assistant_thoughts_plan = str(assistant_thoughts_plan) - - # Split the input_string using the newline character and dashes - lines = assistant_thoughts_plan.split("\n") - for line in lines: - line = line.lstrip("- ") - logger.typewriter_log("- ", Fore.GREEN, line.strip()) - logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}") - # Speak the assistant's thoughts - if CFG.speak_mode and assistant_thoughts_speak: - say_text(assistant_thoughts_speak) diff --git a/spaces/gorkemgoknar/moviechatbot-v2/app.py b/spaces/gorkemgoknar/moviechatbot-v2/app.py deleted file mode 100644 index 757954691f767086ea9b3ca0265431d2def1041a..0000000000000000000000000000000000000000 --- a/spaces/gorkemgoknar/moviechatbot-v2/app.py +++ /dev/null @@ -1,556 +0,0 @@ -import os - -# we need to compile a OPENBLAS version for cpu -# Or get it from https://jllllll.github.io/llama-cpp-python-cuBLAS-wheels/ -os.system('CMAKE_ARGS="-DLLAMA_BLAS=ON -DLLAMA_BLAS_VENDOR=OpenBLAS" pip install llama-cpp-python==0.2.11') - -import re, requests, json -import gradio as gr -import random -import torch -from itertools import chain -import asyncio -from llama_cpp import Llama -import datetime - -from transformers import ( - StoppingCriteriaList, - MaxLengthCriteria, -) - -# Created by -# https://huggingface.co/gorkemgoknar - -#Coqui V1 api render voice, you can also use XTTS -#COQUI_URL="https://app.coqui.ai/api/v2/samples" -COQUI_URL="https://app.coqui.ai/api/v2/samples/xtts" -COQUI_URL_EN="https://app.coqui.ai/api/v2/samples/xtts/render/" -### Warning each sample will consume your credits -COQUI_TOKEN=os.environ.get("COQUI_TOKEN") - -PER_RUN_MAX_VOICE=int( os.environ.get("PER_RUN_MAX_VOICE") ) -PER_RUN_COUNTER=0 -RUN_START_HOUR=datetime.datetime.now().hour - -MAX_NEW_TOKENS = 30 -GPU_LAYERS = 0 -STOP_LIST=["###","##"] - -LLAMA_VERBOSE=False - - - -TITLE = "

        Movie Chatbot - Auto-Chatbot Powered by Coqui.ai XTTS 🐸 " - -INTRODUCTION_TEXT = "Choose your characters, enter initial text see and hear (🐸) them talk. \ -For voice there is per user and hourly limit, copy space and use your Coqui.ai token and voice_ids for your own usage.\ -Additional hint, try French, Italian, German, Spanish initial texts." - -#stopping_criteria = StoppingCriteriaList([MaxLengthCriteria(max_length=64)]) - -from huggingface_hub import hf_hub_download -hf_hub_download(repo_id="gorkemgoknar/llama2-7f-moviechatbot-ggml-q4", local_dir=".", filename="llama2-7f-fp16-gguf-q4.bin") -model_path="./llama2-7f-fp16-gguf-q4.bin" - -import langid - -llm = Llama(model_path=model_path,n_gpu_layers=0, n_ctx=256,n_batch=256,verbose=LLAMA_VERBOSE) - -# to use with ctransfomers -#llm = AutoModelForCausalLM.from_pretrained("gorkemgoknar/llama2-7f-moviechatbot-ggml-q4", -# model_type='llama', -# gpu_layers=GPU_LAYERS, -# max_new_tokens=MAX_NEW_TOKENS, -# stop=STOP_LIST) - - - - - - - -########################################## -#You can use coqui.ai api to generate audio -#first you need to create clone voice for characters - -voices = {} -voices["Gerald"]=os.environ.get("VOICE_ID_GERALD") -voices["Vader"]=os.environ.get("VOICE_ID_VADER") -voices["Batman"]=os.environ.get("VOICE_ID_BATMAN") -voices["Gandalf"]=os.environ.get("VOICE_ID_GANDALF") -voices["Morpheus"]=os.environ.get("VOICE_ID_MORPHEUS") -voices["Neo"]=os.environ.get("VOICE_ID_NEO") -voices["Ig-11"]=os.environ.get("VOICE_ID_IG11") -voices["Tony Stark"]=os.environ.get("VOICE_ID_TONY") -voices["Kirk"]=os.environ.get("VOICE_ID_KIRK") -voices["Spock"]=os.environ.get("VOICE_ID_SPOCK") -voices["Don"]=os.environ.get("VOICE_ID_DON") -voices["Morgan"]=os.environ.get("VOICE_ID_MORGAN") -voices["Yoda"]=os.environ.get("VOICE_ID_YODA") -voices["Ian"]=os.environ.get("VOICE_ID_IAN") -voices["Thanos"]=os.environ.get("VOICE_ID_THANOS") - - - -def get_audio_url(text,character): - url = COQUI_URL - text_language=langid.classify(text)[0] - - supported_languages=["en","de","fr","es","it","pt","pl"] - if text_language not in supported_languages: - text_language="en" - - if text_language=="en": - # use main English model for english, better on english only - url = COQUI_URL_EN - - # voice id of "Baldur Sanjin" from buildin coqui.ai speakers - # more via https://docs.coqui.ai/reference/speakers_retrieve - payload = { - "voice_id": voices[character], ## Voice id in form of (this is dummy) "a399c204-7040-4f1d-bb92-5223fa1aeceb" - "text": f"{text}", - "emotion": "Neutral", ## You can set Angry, Surprise etc on V1 api.. XTTS auto understands it - "speed": 1, - "language": text_language - } - headers = { - "accept": "application/json", - "content-type": "application/json", - "authorization": f"Bearer {COQUI_TOKEN}" - } - - response = requests.post(url, json=payload, headers=headers) - res = json.loads(response.text) - print("Character:",character, "text:",text,) - print("Audio response",res) - return res["audio_url"] - - -def get_response_cpp(prompt): - - output = llm(prompt, max_tokens=32, stop=["#","sierpeda"], echo=True) - #print(output) - response_text= output["choices"][0]["text"] - - return response_text - -def build_question(character,question,context=None, answer=None,history=None , use_history=False, modify_history=True,human_character=None,add_answer_to_history=True): - # THIS MODEL (gorkemgoknar/llama2-7f-moviechatbot-ggml-q4) is specifically fined tuned by - # ### Context: {context}### History: {history}### {human_character}: {question}### {character}: {answer} - # Where History contains all previous lines talked by characters in order - # Context is actually arbitrary it shows something characters can start talking upon - - if context is None: - context= "movie" - - #if human_character is None: - # human_character="" - #else: - # human_character="#"+"I am " + human_character +"#" - - if use_history: - if history is None: - if answer is None: - history="" - else: - history=answer - else: - if modify_history: - if answer is None: - history=history - else: - if add_answer_to_history: - history=history +"#" + answer - else: - history=history - else: - history=history - - if human_character is None: - prompt = f"### Context: {context}### History: {history}### Human: {question}### {character}:" - else: - prompt = f"### Context: {context}### History: {history}### {human_character}: {question}### {character}:" - - - else: - if human_character is None: - prompt = f"### Context: {context}### Human: {question}### {character}:" - else: - prompt = f"### Context: {context}### {human_character}: {question}### {character}:" - return prompt,history - - - -def get_answer_from_response(text,character): - - # on HF it has same text plus additional - # on llama_cpp same full text - response= text.split(f"### {character}:")[1] - # on cpp it continues - # response= text - # get only first line of response - response= response.split("###")[0] - response= response.split("#")[0] - # Weirdly llama2 7f creates some German or Polski on the end... need to crop them - response= response.split("Unterscheidung")[0] # weird, german seperators on output - response= response.split("Hinweis")[0] # weird, german seperators on output - response= response.split("sierp ")[0] # weird, sierp - response= response.split("sierpni ")[0] # weird, sierp - response= response.split("sierpien")[0] # weird, sierp - response= response.split("kwiet")[0] # weird, kwiet - response= response.split("\n")[0] # cut at end of line - response= re.split("sierp.+\d+", response)[0] # comes as sierpina 2018 something something - response= re.split("styczen.+\d+", response)[0] # comes as styczen 2018 something something - response= re.split("kwierk.+\d+", response)[0] # comes as kwierk 2018 something something - - response= response.split(":")[0] - if response.startswith('"'): - response= response[1:] - if response=="" or response=="...": - response="Hmm." - return response - -def run_chatter(num_repeat=2, character="kirk",human_character="Mr. Sulu",context="Captain Kirk from U.S.S. Enterprise", - initial_question="There is a ship approaching captain!", - withaudio=False, - history=None, - add_answer_to_history=True, - answer=None, - debug_print=False, - use_cpu=False): - - question=initial_question - - dialogue="" - - if debug_print: - print("**** START Dialogue ****") - print("Input History:",history) - - audio_urls=[] - - for i in range(num_repeat): - if question is not None: - question=question.strip() - if answer is not None: - answer=answer.strip() - - prompt,history= build_question(character,question,context=context,history=history,answer=answer,human_character=human_character,use_history=True,add_answer_to_history=add_answer_to_history) - print("PROMPT:",prompt) - - response= get_response_cpp(prompt) - print("RESPONSE:",response) - answer = get_answer_from_response(response,character).strip() - - if withaudio: - answer_audio_url = get_audio_url(answer) - audio_urls.append(answer_audio_url) - if debug_print: - print("\nAct:",i+1) - - dialogue = dialogue + f"{human_character}: {question}" + "\n" - if debug_print: - print(f"{human_character}:",question) - print(f"{character}:",answer) - - dialogue = dialogue + f"{character}: {answer}" + "\n" - - if question is not None: - question=question.strip() - if answer is not None: - answer=answer.strip() - - prompt,history= build_question(human_character,answer,context=context,history=history,answer=question,human_character=character,use_history=True,add_answer_to_history=add_answer_to_history) - print("PROMPT:",prompt) - - response= get_response_cpp(prompt) - print("RESPONSE:",response) - resp_answer = get_answer_from_response(response,human_character) - - if withaudio: - # No use.. running on main - response_audio_url = get_audio_url(resp_answer) - audio_urls.append(response_audio_url) - - if debug_print: - print(f"{human_character}:",resp_answer) - - question = resp_answer - - - if debug_print: - print("Final History:",history) - print("**** END Dialogue ****") - if withaudio: - return dialogue,question,answer,history,audio_urls - else: - return dialogue,question,answer,history - - -###################### -# GRADIO PART -###################### - - -# to close on Jupyter remote -#if("interface" in vars()): -# print("Closing existing interface") -# interface.close() - - -css=""" -.chatbox {display:flex;flex-direction:column} -.user_msg, .resp_msg {padding:4px;margin-bottom:4px;border-radius:4px;width:80%} -.user_msg {background-color:cornflowerblue;color:white;align-self:start} -.resp_msg {background-color:lightgray;align-self:self-end} -.audio {background-color:cornflowerblue;color:white;align-self:start;height:5em} - -""" - - -def get_per_run_voice_counter(increase=False): - hour_now = datetime.datetime.now().hour - global PER_RUN_COUNTER - global RUN_START_HOUR - - print("Per run check: Hour now:", hour_now, " RUN_START_HOUR:",RUN_START_HOUR," PER_RUN_COUNTER",PER_RUN_COUNTER) - if hour_now>RUN_START_HOUR: - #reset hourly voice calls - print("resetting per run voice calls") - PER_RUN_COUNTER = 0 - RUN_START_HOUR = hour_now - elif increase: - PER_RUN_COUNTER = PER_RUN_COUNTER + 1 - print("per run voice calls:", PER_RUN_COUNTER) - print("Per run check: Hour now:", hour_now, " RUN_START_HOUR:",RUN_START_HOUR," PER_RUN_COUNTER",PER_RUN_COUNTER) - return PER_RUN_COUNTER - - -async def add_text(WITH_AUDIO,char1,char2,runs,context,initial_question,history,VOICE_COUNTER): - print(f"{char1} talks to {char2}") - - history = None - last_question=None - # todo build a context from dropdown - returned_history = "" - unnamed_question="This weird guy did not input anything.. so, tell me a joke!" - if initial_question is None: - initial_question = unnamed_question - if initial_question=="": - initial_question = unnamed_question - for i in range(int(runs)): - print("char1:",char1," :", initial_question) - returned_history += char1 + " : " + initial_question + "\n" - - dialogue,last_question,last_answer,history = run_chatter(num_repeat=1, - character=char2, - human_character=char1, - context=context, - initial_question=initial_question, - withaudio=False, - history=history, - answer=last_question, - debug_print=False, - add_answer_to_history=False - ) - - print("char2:",char2," :", last_answer) - returned_history += char2 + " : " + last_answer + "\n" - # add last answer to history - history = history + "#" +initial_question + "#"+ last_answer - print("WITH_AUDIO",WITH_AUDIO) - if int(WITH_AUDIO): - use_voice=True - else: - use_voice=False - - print("Voice Counter:",VOICE_COUNTER) - if initial_question=="..." and last_answer=="...": - use_voice=False - - global PER_RUN_MAX_VOICE - if use_voice: - global PER_RUN_MAX_VOICE - can_use_voice=get_per_run_voice_counter()VOICE_LIMIT): - print("You have reached voiced limit, try with voice later.. running without voice") - gr.Warning("You have reached voiced limit.. running without voice") - use_voice=False - - try: - if use_voice: - char1_audio_url= get_audio_url(initial_question,char1) - VOICE_COUNTER+=1 - get_per_run_voice_counter(increase=True) - - char2_audio_url= get_audio_url(last_answer,char2) - VOICE_COUNTER+=1 - get_per_run_voice_counter(increase=True) - except: - gr.Warning("Something wrong with getting audio.. ") - use_voice=False - - - print("Voice Counter:",VOICE_COUNTER) - if use_voice: - audios = ( - gr.Audio.update() , - gr.Audio.update() , - gr.Audio.update() , - gr.Audio.update() , - gr.Audio.update() , - gr.Audio.update() , - gr.Audio.update() , - gr.Audio.update() - ) - else: - audios = ( - gr.Audio.update(visible=False) , - gr.Audio.update(visible=False) , - gr.Audio.update(visible=False) , - gr.Audio.update(visible=False) , - gr.Audio.update(visible=False) , - gr.Audio.update(visible=False) , - gr.Audio.update(visible=False) , - gr.Audio.update(visible=False) - ) - audios = list(audios) - #should now do a loop - if use_voice: - audios[i*2] = gr.Audio.update(char1_audio_url, visible=True,label=str(i*2 )+"_"+char1) - audios[i*2 + 1] = gr.Audio.update(char2_audio_url, visible=True,label=str(i*2 + 1)+"_"+char2) - - audios = tuple(audios) - - #This needs to be last before yield - initial_question=last_question - - yield gr.update(value=initial_question, interactive=True),returned_history, *audios, VOICE_COUNTER - - - - -history=None -#some selected ones are in for demo use (there are more, get a copy and try it , just do not expect much with this fast finetuned model) -CHARACTER_1_CHOICES = ["Gandalf","Gerald", "Morpheus", "Neo","Kirk","Spock","Vader","Yoda","Ig-11","Tony Stark","Batman","Thanos"] -CHARACTER_2_CHOICES = ["Gandalf","Gerald", "Morpheus", "Neo","Kirk","Spock","Vader","Yoda","Ig-11","Tony Stark","Batman","Thanos"] - - -CONTEXT_CHOICES = ["talks friendly", - "insults", - "diss in rap", - "on a cruise ship going to Mars from Earth", - "blames on something", - "tries to save the world", - "talks agressively", - "argues over if a movie is good", - "sword insult fighting", - "inside a dark cavern"] - -EXAMPLE_INITIALS=["I challenge you to battle of words!", - "how much would a woodchuck chuck if a woodchuck could chuck wood?", - "The world is changing.", - "What do you think about AI?", - "I went to the supermarket yesterday.", - "Who are you?", - "I am richer than you!", - "Wie geht es dir?", - "O que você fez ontem?", - "Il fait trop chaud aujourd'hui."] -VOICE_CHOICES=["With Coqui.ai Voice", - "No voice"] -RUN_COUNT = [2,3,4] - -title = "Metayazar - Movie Chatbot Llama Finetuned Voice powered by Coqui.ai" -description = "Auto-chat your favorite movie characters. Voice via Coqui.ai" -article = "

        AI Goes to Job Interview | Metayazar AI Writer |Görkem Göknar

        " - - -def change_run_count(run_count): - print("update run count:",run_count) - visible_audios=[False,False,False,False,False,False,False,False] - run_count=int(run_count) - for i in range(run_count*2-1): - if i>=len(visible_audios): - break - visible_audios[i] = False # Set true to become visible upon change - - return_list=[] - #Max audio 8 - for i in range(8): - return_list.append( gr.Audio.update( visible=visible_audios[i]) ) - - return return_list - - -def switch_voice(with_voice, WITH_AUDIO,VOICE_COUNTER): - print("update use voice:",with_voice) - if (VOICE_COUNTER>VOICE_LIMIT) or (PER_RUN_COUNTER>PER_RUN_MAX_VOICE): - gr.Warning("Unfortunately voice limit is reached, try again after another time, or use without voice") - WITH_AUDIO=0 - else: - if with_voice==VOICE_CHOICES[0]: - WITH_AUDIO=1 - else: - WITH_AUDIO=0 - - return with_voice, WITH_AUDIO - -with gr.Blocks(css=css) as interface: - VOICE_COUNTER=gr.State(value=0) - WITH_AUDIO=gr.State(value=1) - VOICE_LIMIT=int( os.environ.get("VOICE_LIMIT") ) - with gr.Row(): - gr.HTML(TITLE, elem_id="banner") - gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text") - - with gr.Row(): - drop_char1 = gr.components.Dropdown(CHARACTER_1_CHOICES,label="Character 1",value=CHARACTER_1_CHOICES[0]) - drop_char2 = gr.components.Dropdown(CHARACTER_2_CHOICES,label="Character 2",value=CHARACTER_2_CHOICES[1]) - run_count = gr.components.Dropdown(RUN_COUNT,label="Line count per character",value="2") - with gr.Row(): - context_choice = gr.components.Dropdown(CONTEXT_CHOICES, label="Context",value=CONTEXT_CHOICES[0]) - with gr.Row(): - with_voice = gr.components.Dropdown(VOICE_CHOICES,label="Voice via Coqui.ai (demo)",value=VOICE_CHOICES[0]) - with gr.Row(): - txt = gr.Textbox( - show_label=False, - placeholder="Enter text and press enter, or upload an image", - value=EXAMPLE_INITIALS[0],elem_classes="user_msg" - ) - submit_btn = gr.Button(value="Submit") - examples = gr.Examples(examples=EXAMPLE_INITIALS, - inputs=[txt]) - with gr.Row(): - with gr.Column(): - history = gr.Textbox(lines=25, - show_label=True, - label="History", - placeholder="History", - ).style(height=50) - - with gr.Column(): - audio1 = gr.Audio(elem_id="audio1",elem_classes="audio",autoplay=False,visible=False) - audio2 = gr.Audio(elem_id="audio2",elem_classes="audio",autoplay=False,visible=False) - audio3 = gr.Audio(elem_id="audio3",elem_classes="audio",autoplay=False,visible=False) - audio4 = gr.Audio(elem_id="audio4",elem_classes="audio",autoplay=False,visible=False) - audio5 = gr.Audio(elem_id="audio5",elem_classes="audio",autoplay=False,visible=False) - audio6 = gr.Audio(elem_id="audio6",elem_classes="audio",autoplay=False,visible=False) - audio7 = gr.Audio(elem_id="audio7",elem_classes="audio",autoplay=False,visible=False) - audio8 = gr.Audio(elem_id="audio8",elem_classes="audio",autoplay=False,visible=False) - - with_voice.change(switch_voice,[with_voice,WITH_AUDIO,VOICE_COUNTER],[with_voice,WITH_AUDIO]) - - - run_count.change(change_run_count,[run_count],[audio1,audio2,audio3,audio4,audio5,audio6,audio7,audio8]) - submit_btn.click(add_text, [WITH_AUDIO,drop_char1, drop_char2,run_count, context_choice, txt,history,VOICE_COUNTER], [txt,history,audio1,audio2,audio3,audio4,audio5,audio6,audio7,audio8,VOICE_COUNTER], api_name="chat") - - -interface.queue().launch() - - diff --git a/spaces/gotiQspiryo/whisper-ui/examples/Download Vaastav The Reality movie eng sub full - Dont miss any scene of the epic saga.md b/spaces/gotiQspiryo/whisper-ui/examples/Download Vaastav The Reality movie eng sub full - Dont miss any scene of the epic saga.md deleted file mode 100644 index 0690d5395772d47142457f656007f75ced565108..0000000000000000000000000000000000000000 --- a/spaces/gotiQspiryo/whisper-ui/examples/Download Vaastav The Reality movie eng sub full - Dont miss any scene of the epic saga.md +++ /dev/null @@ -1,6 +0,0 @@ -

        Vaastav: The Reality movie eng sub download


        Download File »»» https://urlgoal.com/2uyN22



        -
        - aaccfb2cb3
        -
        -
        -

        diff --git a/spaces/guetLzy/Real-ESRGAN-Demo/realesrgan/archs/srvgg_arch.py b/spaces/guetLzy/Real-ESRGAN-Demo/realesrgan/archs/srvgg_arch.py deleted file mode 100644 index 39460965c9c5ee9cd6eb41c50d33574cb8ba6e50..0000000000000000000000000000000000000000 --- a/spaces/guetLzy/Real-ESRGAN-Demo/realesrgan/archs/srvgg_arch.py +++ /dev/null @@ -1,69 +0,0 @@ -from basicsr.utils.registry import ARCH_REGISTRY -from torch import nn as nn -from torch.nn import functional as F - - -@ARCH_REGISTRY.register() -class SRVGGNetCompact(nn.Module): - """A compact VGG-style network structure for super-resolution. - - It is a compact network structure, which performs upsampling in the last layer and no convolution is - conducted on the HR feature space. - - Args: - num_in_ch (int): Channel number of inputs. Default: 3. - num_out_ch (int): Channel number of outputs. Default: 3. - num_feat (int): Channel number of intermediate features. Default: 64. - num_conv (int): Number of convolution layers in the body network. Default: 16. - upscale (int): Upsampling factor. Default: 4. - act_type (str): Activation type, options: 'relu', 'prelu', 'leakyrelu'. Default: prelu. - """ - - def __init__(self, num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu'): - super(SRVGGNetCompact, self).__init__() - self.num_in_ch = num_in_ch - self.num_out_ch = num_out_ch - self.num_feat = num_feat - self.num_conv = num_conv - self.upscale = upscale - self.act_type = act_type - - self.body = nn.ModuleList() - # the first conv - self.body.append(nn.Conv2d(num_in_ch, num_feat, 3, 1, 1)) - # the first activation - if act_type == 'relu': - activation = nn.ReLU(inplace=True) - elif act_type == 'prelu': - activation = nn.PReLU(num_parameters=num_feat) - elif act_type == 'leakyrelu': - activation = nn.LeakyReLU(negative_slope=0.1, inplace=True) - self.body.append(activation) - - # the body structure - for _ in range(num_conv): - self.body.append(nn.Conv2d(num_feat, num_feat, 3, 1, 1)) - # activation - if act_type == 'relu': - activation = nn.ReLU(inplace=True) - elif act_type == 'prelu': - activation = nn.PReLU(num_parameters=num_feat) - elif act_type == 'leakyrelu': - activation = nn.LeakyReLU(negative_slope=0.1, inplace=True) - self.body.append(activation) - - # the last conv - self.body.append(nn.Conv2d(num_feat, num_out_ch * upscale * upscale, 3, 1, 1)) - # upsample - self.upsampler = nn.PixelShuffle(upscale) - - def forward(self, x): - out = x - for i in range(0, len(self.body)): - out = self.body[i](out) - - out = self.upsampler(out) - # add the nearest upsampled image, so that the network learns the residual - base = F.interpolate(x, scale_factor=self.upscale, mode='nearest') - out += base - return out diff --git a/spaces/gulabpatel/Real-ESRGAN/realesrgan/models/__init__.py b/spaces/gulabpatel/Real-ESRGAN/realesrgan/models/__init__.py deleted file mode 100644 index 0be7105dc75d150c49976396724085f678dc0675..0000000000000000000000000000000000000000 --- a/spaces/gulabpatel/Real-ESRGAN/realesrgan/models/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -import importlib -from basicsr.utils import scandir -from os import path as osp - -# automatically scan and import model modules for registry -# scan all the files that end with '_model.py' under the model folder -model_folder = osp.dirname(osp.abspath(__file__)) -model_filenames = [osp.splitext(osp.basename(v))[0] for v in scandir(model_folder) if v.endswith('_model.py')] -# import all the model modules -_model_modules = [importlib.import_module(f'realesrgan.models.{file_name}') for file_name in model_filenames] diff --git a/spaces/guoyww/AnimateDiff/download_bashscripts/6-Tusun.sh b/spaces/guoyww/AnimateDiff/download_bashscripts/6-Tusun.sh deleted file mode 100644 index 9fc18b3ad1c59139896b68a444276b2d5e52a1ce..0000000000000000000000000000000000000000 --- a/spaces/guoyww/AnimateDiff/download_bashscripts/6-Tusun.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash -wget https://civitai.com/api/download/models/97261 -P models/DreamBooth_LoRA/ --content-disposition --no-check-certificate -wget https://civitai.com/api/download/models/50705 -P models/DreamBooth_LoRA/ --content-disposition --no-check-certificate diff --git a/spaces/gyrojeff/YuzuMarker.FontDetection/utils/__init__.py b/spaces/gyrojeff/YuzuMarker.FontDetection/utils/__init__.py deleted file mode 100644 index 8d0aae9b291c296bfe7cbd18a95e9fa6c3589703..0000000000000000000000000000000000000000 --- a/spaces/gyrojeff/YuzuMarker.FontDetection/utils/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .vcs import get_current_tag diff --git a/spaces/h2oai/wave-tour/examples/plot_altair.py b/spaces/h2oai/wave-tour/examples/plot_altair.py deleted file mode 100644 index 6a34386281eb0bb6c099b6a0caed6443189d1289..0000000000000000000000000000000000000000 --- a/spaces/h2oai/wave-tour/examples/plot_altair.py +++ /dev/null @@ -1,23 +0,0 @@ -# Plot / Altair -# Use #Altair to create #plot specifications for the #Vega card. -# --- -import altair -from vega_datasets import data -from h2o_wave import site, ui - -spec = altair.Chart(data.cars()).mark_circle(size=60).encode( - x='Horsepower', - y='Miles_per_Gallon', - color='Origin', - tooltip=['Name', 'Origin', 'Horsepower', 'Miles_per_Gallon'] -).properties(width='container', height='container').interactive().to_json() - -page = site['/demo'] - -page['example'] = ui.vega_card( - box='1 1 4 5', - title='Altair Example', - specification=spec, -) - -page.save() diff --git a/spaces/hackathon-pln-es/clasificador-comentarios-suicidas/presentation.py b/spaces/hackathon-pln-es/clasificador-comentarios-suicidas/presentation.py deleted file mode 100644 index 188a13b53b09f5b7f8c1f23eb4c7abf868e9b8ca..0000000000000000000000000000000000000000 --- a/spaces/hackathon-pln-es/clasificador-comentarios-suicidas/presentation.py +++ /dev/null @@ -1,31 +0,0 @@ -main_title = """ - - - -

        Clasificador de comentarios Suicidas

        -

        La siguiente aplicación ha sido diseñada con la intención de clasificar un comentario en "Suicida" y "No Suicida", con el fin de que para futuros trabajos e investigaciones se lo pueda implementar en una situación real para prevenir los casos de suicidio.

        -

        Integrantes

        -
          -
        • Danny Vásquez
        • -
        • César Salazar
        • -
        • Alexis Cañar
        • -
        • Yannela Castro
        • -
        • Daniel Patiño
        • -
        -""" - - -examples = [ - [ - "No entiendo por qué no soy lo suficientemente bueno. Sé que hay muchas personas en este Subreddit que están en situaciones increíblemente difíciles y siento que mi problema es tan pequeño en comparación. Sin embargo, es algo que me pesa y me siento tan bajo que quiero morir. Soy una mujer de 30 años y nunca he sido afortunada cuando se trata de citas o relaciones, sin embargo, conocí a alguien el año pasado con el que sentí que estaba conectado. Nos divertimos mucho juntos y me encantaba estar a su alrededor, pero sentí que no era lo suficientemente buena como para ser su novia. Me siento como una idiota al ponerme en esta situación, pero no veo ninguna esperanza." - ], - [ - "Me corté por primera vez hoy. Solo para sentirme un poco mejor. No puedo perdonarme ahora. Estoy acabando con todo poco a poco. Estoy tan inestable en este momento, incluso en la medicación, la terapia y el ejercicio. Sé que puedo llegar a mis amigos para apoyar y no quiero cargarlos. Solo tengo miedo, y solo estoy solo en este momento. No quiero morir, pero la muerte se ve más y más favorable. Solo quiero que la culpa y el dolor innecesarias desaparezcan." - ], - [ - "Siento que solo estoy viviendo debido a otras personas, no porque tenga una voluntad de vivir. La idea de matarme me da paz. Todo lo que quiero hacer es terminar mi vida. A cualquiera que lea esto, gracias." - ], - [ - "He estado enojado y triste sin ninguna razón válida, y solo quiero terminarlo. Sólo he estado enojado con todo en mi vida y es demasiado. Estoy harto de despertarse y estar enojado todo el día sin nada. Literalmente, nada en mi vida vale la pena enojarse, pero estoy irracionalmente enojado. Quiero dejarlo salir, pero no quiero lastimar a la gente en mi vida. Así que simplemente eliminaré lo que puedo controlar, a mí. Espero que el mundo sea mejor sin mí." - ], -] \ No newline at end of file diff --git a/spaces/hahahehe99340/chatgpt/Dockerfile b/spaces/hahahehe99340/chatgpt/Dockerfile deleted file mode 100644 index 8cbd335b09b1d1975bfd83a053b5fcaf398147ea..0000000000000000000000000000000000000000 --- a/spaces/hahahehe99340/chatgpt/Dockerfile +++ /dev/null @@ -1,14 +0,0 @@ -FROM python:3.9 as builder -RUN apt-get update && apt-get install -y build-essential -COPY requirements.txt . -RUN pip install --user -r requirements.txt - -FROM python:3.9 -MAINTAINER iskoldt -COPY --from=builder /root/.local /root/.local -ENV PATH=/root/.local/bin:$PATH -COPY . /app -WORKDIR /app -ENV my_api_key empty -ENV dockerrun yes -CMD ["python3", "-u", "ChuanhuChatbot.py", "2>&1", "|", "tee", "/var/log/application.log"] diff --git a/spaces/haotiz/glip-zeroshot-demo/maskrcnn_benchmark/modeling/rpn/__init__.py b/spaces/haotiz/glip-zeroshot-demo/maskrcnn_benchmark/modeling/rpn/__init__.py deleted file mode 100644 index c05e602a5e4a4f35f826068d6ee0ff9d4e011411..0000000000000000000000000000000000000000 --- a/spaces/haotiz/glip-zeroshot-demo/maskrcnn_benchmark/modeling/rpn/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. -# from .rpn import build_rpn -from .rpn import RPNModule -from .retina import RetinaNetModule -from .fcos import FCOSModule -from .atss import ATSSModule -from .dyhead import DyHeadModule -from .vldyhead import VLDyHeadModule - -_RPN_META_ARCHITECTURES = {"RPN": RPNModule, - "RETINA": RetinaNetModule, - "FCOS": FCOSModule, - "ATSS": ATSSModule, - "DYHEAD": DyHeadModule, - "VLDYHEAD": VLDyHeadModule - } - - -def build_rpn(cfg): - """ - This gives the gist of it. Not super important because it doesn't change as much - """ - rpn_arch = _RPN_META_ARCHITECTURES[cfg.MODEL.RPN_ARCHITECTURE] - return rpn_arch(cfg) diff --git a/spaces/haotiz/glip-zeroshot-demo/maskrcnn_benchmark/utils/registry.py b/spaces/haotiz/glip-zeroshot-demo/maskrcnn_benchmark/utils/registry.py deleted file mode 100644 index c3204e14148fe3341307c5d24ba9154c07449511..0000000000000000000000000000000000000000 --- a/spaces/haotiz/glip-zeroshot-demo/maskrcnn_benchmark/utils/registry.py +++ /dev/null @@ -1,45 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. - - -def _register_generic(module_dict, module_name, module): - assert module_name not in module_dict - module_dict[module_name] = module - - -class Registry(dict): - ''' - A helper class for managing registering modules, it extends a dictionary - and provides a register functions. - - Eg. creeting a registry: - some_registry = Registry({"default": default_module}) - - There're two ways of registering new modules: - 1): normal way is just calling register function: - def foo(): - ... - some_registry.register("foo_module", foo) - 2): used as decorator when declaring the module: - @some_registry.register("foo_module") - @some_registry.register("foo_modeul_nickname") - def foo(): - ... - - Access of module is just like using a dictionary, eg: - f = some_registry["foo_modeul"] - ''' - def __init__(self, *args, **kwargs): - super(Registry, self).__init__(*args, **kwargs) - - def register(self, module_name, module=None): - # used as function call - if module is not None: - _register_generic(self, module_name, module) - return - - # used as decorator - def register_fn(fn): - _register_generic(self, module_name, fn) - return fn - - return register_fn diff --git a/spaces/hasibzunair/fifa-tryon-demo/Self-Correction-Human-Parsing-for-ACGPN/mhp_extension/scripts/make_coco_style_annotation.sh b/spaces/hasibzunair/fifa-tryon-demo/Self-Correction-Human-Parsing-for-ACGPN/mhp_extension/scripts/make_coco_style_annotation.sh deleted file mode 100644 index 37a1e7d4944c318bc275a58dceeaf987bb6517dc..0000000000000000000000000000000000000000 --- a/spaces/hasibzunair/fifa-tryon-demo/Self-Correction-Human-Parsing-for-ACGPN/mhp_extension/scripts/make_coco_style_annotation.sh +++ /dev/null @@ -1,14 +0,0 @@ -python ./coco_style_annotation_creator/human_to_coco.py \ - --dataset 'CIHP' \ - --json_save_dir './data/CIHP/annotations' \ - --train_img_dir './data/CIHP/Training/Images' \ - --train_anno_dir './data/CIHP/Training/Human_ids' \ - --val_img_dir './data/CIHP/Validation/Images' \ - --val_anno_dir './data/CIHP/Validation/Human_ids' - - -python ./coco_style_annotation_creator/test_human2coco_format.py \ - --dataset 'CIHP' \ - --json_save_dir './data/CIHP/annotations' \ - --test_img_dir './data/CIHP/Testing/Images' - diff --git a/spaces/huggingface/bloom_demo/screenshot.py b/spaces/huggingface/bloom_demo/screenshot.py deleted file mode 100644 index 4616a954d69ffcd48760d473d98efbd95f96faed..0000000000000000000000000000000000000000 --- a/spaces/huggingface/bloom_demo/screenshot.py +++ /dev/null @@ -1,56 +0,0 @@ -## HTML and JS code to give Gradio HTML -before_prompt = """ -
        -
        - -""" - -js_save = """() => { - /*might need to add .root to launch locally */ - var gradioapp = document.body.getElementsByTagName('gradio-app')[0]; - - /* Save image */ - capture = gradioapp.querySelector('#capture') - img_placeholder = gradioapp.querySelector('#img_placeholder') - html2canvas(capture, { - useCORS: true, - onclone: function (clonedDoc) { - clonedDoc.querySelector('#capture').style.display = 'block'; - - /*Fits text to box*/ - var text_box = clonedDoc.querySelector('#text_box'); - var prompt = clonedDoc.querySelector('#prompt'); - var generation = clonedDoc.querySelector('#generation'); - console.log(text_box, generation, prompt) - cur_font_size = getComputedStyle(text_box).getPropertyValue("font-size") - while( (text_box.clientHeight < text_box.scrollHeight || text_box.clientWidth < text_box.scrollWidth) & parseInt(cur_font_size) > 10) { - console.log(cur_font_size, text_box.clientHeight, text_box.scrollHeight, text_box.clientWidth, text_box.scrollWidth) - cur_font_size = 0.98 * parseInt(cur_font_size) + "px" - cur_line_height = 1.1 * parseInt(cur_font_size) + "px" - text_box.style.fontSize = cur_font_size - prompt.style.fontSize = cur_font_size - generation.style.fontSize = cur_font_size - text_box.style.lineHeight = cur_line_height - prompt.style.lineHeight = cur_line_height - generation.style.lineHeight = cur_line_height - } - } - }).then((canvas)=>{ - img_placeholder.prepend(canvas); - }) -}""" - - -js_load_script="""() => { - var script = document.createElement('script'); - script.src = "https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"; - document.head.appendChild(script); -}""" \ No newline at end of file diff --git a/spaces/huutinh111111/ChatGPT4/app.py b/spaces/huutinh111111/ChatGPT4/app.py deleted file mode 100644 index 632f0ee79c2a44a19c299e5965101cad17293e69..0000000000000000000000000000000000000000 --- a/spaces/huutinh111111/ChatGPT4/app.py +++ /dev/null @@ -1,191 +0,0 @@ -import gradio as gr -import os -import json -import requests - -#Streaming endpoint -API_URL = "https://api.openai.com/v1/chat/completions" #os.getenv("API_URL") + "/generate_stream" - -#Inferenec function -def predict(openai_gpt4_key, system_msg, inputs, top_p, temperature, chat_counter, chatbot=[], history=[]): - - headers = { - "Content-Type": "application/json", - "Authorization": f"Bearer {openai_gpt4_key}" #Users will provide their own OPENAI_API_KEY - } - print(f"system message is ^^ {system_msg}") - if system_msg.strip() == '': - initial_message = [{"role": "user", "content": f"{inputs}"},] - multi_turn_message = [] - else: - initial_message= [{"role": "system", "content": system_msg}, - {"role": "user", "content": f"{inputs}"},] - multi_turn_message = [{"role": "system", "content": system_msg},] - - if chat_counter == 0 : - payload = { - "model": "gpt-4", - "messages": initial_message , - "temperature" : 1.0, - "top_p":1.0, - "n" : 1, - "stream": True, - "presence_penalty":0, - "frequency_penalty":0, - } - print(f"chat_counter - {chat_counter}") - else: #if chat_counter != 0 : - messages=multi_turn_message # Of the type of - [{"role": "system", "content": system_msg},] - for data in chatbot: - user = {} - user["role"] = "user" - user["content"] = data[0] - assistant = {} - assistant["role"] = "assistant" - assistant["content"] = data[1] - messages.append(user) - messages.append(assistant) - temp = {} - temp["role"] = "user" - temp["content"] = inputs - messages.append(temp) - #messages - payload = { - "model": "gpt-4", - "messages": messages, # Of the type of [{"role": "user", "content": f"{inputs}"}], - "temperature" : temperature, #1.0, - "top_p": top_p, #1.0, - "n" : 1, - "stream": True, - "presence_penalty":0, - "frequency_penalty":0,} - - chat_counter+=1 - - history.append(inputs) - print(f"Logging : payload is - {payload}") - # make a POST request to the API endpoint using the requests.post method, passing in stream=True - response = requests.post(API_URL, headers=headers, json=payload, stream=True) - print(f"Logging : response code - {response}") - token_counter = 0 - partial_words = "" - - counter=0 - for chunk in response.iter_lines(): - #Skipping first chunk - if counter == 0: - counter+=1 - continue - # check whether each line is non-empty - if chunk.decode() : - chunk = chunk.decode() - # decode each line as response data is in bytes - if len(chunk) > 12 and "content" in json.loads(chunk[6:])['choices'][0]['delta']: - partial_words = partial_words + json.loads(chunk[6:])['choices'][0]["delta"]["content"] - if token_counter == 0: - history.append(" " + partial_words) - else: - history[-1] = partial_words - chat = [(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2) ] # convert to tuples of list - token_counter+=1 - yield chat, history, chat_counter, response # resembles {chatbot: chat, state: history} - -#Resetting to blank -def reset_textbox(): - return gr.update(value='') - -#to set a component as visible=False -def set_visible_false(): - return gr.update(visible=False) - -#to set a component as visible=True -def set_visible_true(): - return gr.update(visible=True) - -title = """

        🔥GPT4 using Chat-Completions API & 🚀Gradio-Streaming

        """ -#display message for themes feature -theme_addon_msg = """
        🌟 This Demo also introduces you to Gradio Themes. Discover more on Gradio website using our Themeing-Guide🎨! You can develop from scratch, modify an existing Gradio theme, and share your themes with community by uploading them to huggingface-hub easily using theme.push_to_hub().
        -""" - -#Using info to add additional information about System message in GPT4 -system_msg_info = """A conversation could begin with a system message to gently instruct the assistant. -System message helps set the behavior of the AI Assistant. For example, the assistant could be instructed with 'You are a helpful assistant.'""" - -#Modifying existing Gradio Theme -theme = gr.themes.Soft(primary_hue="zinc", secondary_hue="green", neutral_hue="green", - text_size=gr.themes.sizes.text_lg) - -with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;} #chatbot {height: 520px; overflow: auto;}""", - theme=theme) as demo: - gr.HTML(title) - gr.HTML("""

        🔥This Huggingface Gradio Demo provides you access to GPT4 API with System Messages. Please note that you would be needing an OPENAI API key for GPT4 access🙌

        """) - gr.HTML(theme_addon_msg) - gr.HTML('''
        Duplicate SpaceDuplicate the Space and run securely with your OpenAI API Key
        ''') - - with gr.Column(elem_id = "col_container"): - #Users need to provide their own GPT4 API key, it is no longer provided by Huggingface - with gr.Row(): - openai_gpt4_key = gr.Textbox(label="OpenAI GPT4 Key", value="", type="password", placeholder="sk..", info = "You have to provide your own GPT4 keys for this app to function properly",) - with gr.Accordion(label="System message:", open=False): - system_msg = gr.Textbox(label="Instruct the AI Assistant to set its beaviour", info = system_msg_info, value="",placeholder="Type here..") - accordion_msg = gr.HTML(value="🚧 To set System message you will have to refresh the app", visible=False) - - chatbot = gr.Chatbot(label='GPT4', elem_id="chatbot") - inputs = gr.Textbox(placeholder= "Hi there!", label= "Type an input and press Enter") - state = gr.State([]) - with gr.Row(): - with gr.Column(scale=7): - b1 = gr.Button().style(full_width=True) - with gr.Column(scale=3): - server_status_code = gr.Textbox(label="Status code from OpenAI server", ) - - #top_p, temperature - with gr.Accordion("Parameters", open=False): - top_p = gr.Slider( minimum=-0, maximum=1.0, value=1.0, step=0.05, interactive=True, label="Top-p (nucleus sampling)",) - temperature = gr.Slider( minimum=-0, maximum=5.0, value=1.0, step=0.1, interactive=True, label="Temperature",) - chat_counter = gr.Number(value=0, visible=False, precision=0) - - #Event handling - inputs.submit( predict, [openai_gpt4_key, system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter, server_status_code],) #openai_api_key - b1.click( predict, [openai_gpt4_key, system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter, server_status_code],) #openai_api_key - - inputs.submit(set_visible_false, [], [system_msg]) - b1.click(set_visible_false, [], [system_msg]) - inputs.submit(set_visible_true, [], [accordion_msg]) - b1.click(set_visible_true, [], [accordion_msg]) - - b1.click(reset_textbox, [], [inputs]) - inputs.submit(reset_textbox, [], [inputs]) - - #Examples - with gr.Accordion(label="Examples for System message:", open=False): - gr.Examples( - examples = [["""You are an AI programming assistant. - - - Follow the user's requirements carefully and to the letter. - - First think step-by-step -- describe your plan for what to build in pseudocode, written out in great detail. - - Then output the code in a single code block. - - Minimize any other prose."""], ["""You are ComedianGPT who is a helpful assistant. You answer everything with a joke and witty replies."""], - ["You are ChefGPT, a helpful assistant who answers questions with culinary expertise and a pinch of humor."], - ["You are FitnessGuruGPT, a fitness expert who shares workout tips and motivation with a playful twist."], - ["You are SciFiGPT, an AI assistant who discusses science fiction topics with a blend of knowledge and wit."], - ["You are PhilosopherGPT, a thoughtful assistant who responds to inquiries with philosophical insights and a touch of humor."], - ["You are EcoWarriorGPT, a helpful assistant who shares environment-friendly advice with a lighthearted approach."], - ["You are MusicMaestroGPT, a knowledgeable AI who discusses music and its history with a mix of facts and playful banter."], - ["You are SportsFanGPT, an enthusiastic assistant who talks about sports and shares amusing anecdotes."], - ["You are TechWhizGPT, a tech-savvy AI who can help users troubleshoot issues and answer questions with a dash of humor."], - ["You are FashionistaGPT, an AI fashion expert who shares style advice and trends with a sprinkle of wit."], - ["You are ArtConnoisseurGPT, an AI assistant who discusses art and its history with a blend of knowledge and playful commentary."], - ["You are a helpful assistant that provides detailed and accurate information."], - ["You are an assistant that speaks like Shakespeare."], - ["You are a friendly assistant who uses casual language and humor."], - ["You are a financial advisor who gives expert advice on investments and budgeting."], - ["You are a health and fitness expert who provides advice on nutrition and exercise."], - ["You are a travel consultant who offers recommendations for destinations, accommodations, and attractions."], - ["You are a movie critic who shares insightful opinions on films and their themes."], - ["You are a history enthusiast who loves to discuss historical events and figures."], - ["You are a tech-savvy assistant who can help users troubleshoot issues and answer questions about gadgets and software."], - ["You are an AI poet who can compose creative and evocative poems on any given topic."],], - inputs = system_msg,) - -demo.queue(max_size=99, concurrency_count=20).launch(debug=True) \ No newline at end of file diff --git a/spaces/hylee/White-box-Cartoonization/wbc/cartoonize.py b/spaces/hylee/White-box-Cartoonization/wbc/cartoonize.py deleted file mode 100644 index 25faf1ceb95aaed9a3f7a7982d17a03dc6bc32b1..0000000000000000000000000000000000000000 --- a/spaces/hylee/White-box-Cartoonization/wbc/cartoonize.py +++ /dev/null @@ -1,112 +0,0 @@ -import os -import cv2 -import numpy as np -import tensorflow as tf -import wbc.network as network -import wbc.guided_filter as guided_filter -from tqdm import tqdm - - -def resize_crop(image): - h, w, c = np.shape(image) - if min(h, w) > 720: - if h > w: - h, w = int(720 * h / w), 720 - else: - h, w = 720, int(720 * w / h) - image = cv2.resize(image, (w, h), - interpolation=cv2.INTER_AREA) - h, w = (h // 8) * 8, (w // 8) * 8 - image = image[:h, :w, :] - return image - - -def cartoonize(load_folder, save_folder, model_path): - print(model_path) - input_photo = tf.placeholder(tf.float32, [1, None, None, 3]) - network_out = network.unet_generator(input_photo) - final_out = guided_filter.guided_filter(input_photo, network_out, r=1, eps=5e-3) - - all_vars = tf.trainable_variables() - gene_vars = [var for var in all_vars if 'generator' in var.name] - saver = tf.train.Saver(var_list=gene_vars) - - config = tf.ConfigProto() - config.gpu_options.allow_growth = True - sess = tf.Session(config=config) - - sess.run(tf.global_variables_initializer()) - saver.restore(sess, tf.train.latest_checkpoint(model_path)) - name_list = os.listdir(load_folder) - for name in tqdm(name_list): - try: - load_path = os.path.join(load_folder, name) - save_path = os.path.join(save_folder, name) - image = cv2.imread(load_path) - image = resize_crop(image) - batch_image = image.astype(np.float32) / 127.5 - 1 - batch_image = np.expand_dims(batch_image, axis=0) - output = sess.run(final_out, feed_dict={input_photo: batch_image}) - output = (np.squeeze(output) + 1) * 127.5 - output = np.clip(output, 0, 255).astype(np.uint8) - cv2.imwrite(save_path, output) - except: - print('cartoonize {} failed'.format(load_path)) - - -class Cartoonize: - def __init__(self, model_path): - print(model_path) - self.input_photo = tf.placeholder(tf.float32, [1, None, None, 3]) - network_out = network.unet_generator(self.input_photo) - self.final_out = guided_filter.guided_filter(self.input_photo, network_out, r=1, eps=5e-3) - - all_vars = tf.trainable_variables() - gene_vars = [var for var in all_vars if 'generator' in var.name] - saver = tf.train.Saver(var_list=gene_vars) - - config = tf.ConfigProto() - config.gpu_options.allow_growth = True - self.sess = tf.Session(config=config) - - self.sess.run(tf.global_variables_initializer()) - saver.restore(self.sess, tf.train.latest_checkpoint(model_path)) - - def run(self, load_folder, save_folder): - name_list = os.listdir(load_folder) - for name in tqdm(name_list): - try: - load_path = os.path.join(load_folder, name) - save_path = os.path.join(save_folder, name) - image = cv2.imread(load_path) - image = resize_crop(image) - batch_image = image.astype(np.float32) / 127.5 - 1 - batch_image = np.expand_dims(batch_image, axis=0) - output = self.sess.run(self.final_out, feed_dict={self.input_photo: batch_image}) - output = (np.squeeze(output) + 1) * 127.5 - output = np.clip(output, 0, 255).astype(np.uint8) - cv2.imwrite(save_path, output) - except: - print('cartoonize {} failed'.format(load_path)) - - def run_sigle(self, load_path, save_path): - try: - image = cv2.imread(load_path) - image = resize_crop(image) - batch_image = image.astype(np.float32) / 127.5 - 1 - batch_image = np.expand_dims(batch_image, axis=0) - output = self.sess.run(self.final_out, feed_dict={self.input_photo: batch_image}) - output = (np.squeeze(output) + 1) * 127.5 - output = np.clip(output, 0, 255).astype(np.uint8) - cv2.imwrite(save_path, output) - except: - print('cartoonize {} failed'.format(load_path)) - - -if __name__ == '__main__': - model_path = 'saved_models' - load_folder = 'test_images' - save_folder = 'cartoonized_images' - if not os.path.exists(save_folder): - os.mkdir(save_folder) - cartoonize(load_folder, save_folder, model_path) diff --git a/spaces/hysts/danbooru-pretrained/style.css b/spaces/hysts/danbooru-pretrained/style.css deleted file mode 100644 index c4739b4ea5fc35e774a049e3dacc443f7f0eac19..0000000000000000000000000000000000000000 --- a/spaces/hysts/danbooru-pretrained/style.css +++ /dev/null @@ -1,3 +0,0 @@ -h1 { - text-align: center; -} diff --git a/spaces/hysts/space-that-creates-model-demo-space/README.md b/spaces/hysts/space-that-creates-model-demo-space/README.md deleted file mode 100644 index 3bf22362c35b84d1e4a8bbb0b7b68c218d952330..0000000000000000000000000000000000000000 --- a/spaces/hysts/space-that-creates-model-demo-space/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Space That Creates Model Demo Space -emoji: 🐠 -colorFrom: yellow -colorTo: yellow -sdk: gradio -sdk_version: 3.1.6 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/CorradoMencucciniVittorioSilvestriniFisica1Meccanicatermodinamica.md b/spaces/inplisQlawa/anything-midjourney-v4-1/CorradoMencucciniVittorioSilvestriniFisica1Meccanicatermodinamica.md deleted file mode 100644 index f765f2ce889593adecca21a763bc7d8533988ac4..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/CorradoMencucciniVittorioSilvestriniFisica1Meccanicatermodinamica.md +++ /dev/null @@ -1,6 +0,0 @@ -

        CorradoMencucciniVittorioSilvestriniFisica1Meccanicatermodinamica


        DOWNLOADhttps://urlin.us/2uEw9M



        - -CorradoMencucciniVittorioSilvestriniFisica1Meccanicatermodinamica · martin's physical pharmacy and pharmaceutical sciences pdf. 4d29de3e1b
        -
        -
        -

        diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/Desmume 0.9.9 Jit X86 Download Windows.md b/spaces/inplisQlawa/anything-midjourney-v4-1/Desmume 0.9.9 Jit X86 Download Windows.md deleted file mode 100644 index f9adbafdef6a5a02a86457316046760c16840408..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/Desmume 0.9.9 Jit X86 Download Windows.md +++ /dev/null @@ -1,38 +0,0 @@ -

        desmume 0.9.9 jit x86 download windows


        Download Filehttps://urlin.us/2uEyxj



        -
        -The themes change the look and feel of the user interface, for example by giving it a dock-like look and adding various visual effects. It is also possible to change the look and feel of the main window. If you find a theme you like, you can make it the default theme and your changes will remain. There is also a special theme that works with the OS X and Linux versions. - -Contents - -Overview - -Themes are a fairly new concept and there are not many out there. You will be able to find a wide variety of them in the Mac App Store, but the quality can be poor or missing entirely. On the Internet, there are many more options available, and many of them seem to be user-contributed. One of the easiest ways to find themes is to use the search function on Theme Browser, a free web-based theme-browsing service that will search for "chrome theme" or "firefox theme" or "window theme", among others. Theme Browser will also find all the themes available in the Mac App Store. - -The theme engine of Chrome is based on the underlying Qt library. If you don't have Qt installed on your machine, you can use the online version of the program to download the theme engine, and then install it through the Mac App Store. Be sure to back up the existing files before doing this. - -You can also download the themes from the developer's website. The downloads come in the form of a zip archive. Simply download that, extract it, and drop the files in your "AppSupport" folder. You might also need to update the "app_name.txt" file in the same folder. If you are using Windows, you will need to choose the "All files (*.*) in the current folder" option. - -When you open a theme, it will be shown in a new tab in the Theme Browser. You can install the themes and switch between them easily, and without leaving the browser. You can see the change that the theme has made in the browser. - -You will have to ask the Internet for it, since the developer's website has vanished. - -For more details on installing the themes, see Mac App Store. - -Supported features - -Various visual effects that can be enabled for windows, such as: - -Opacity - -Blur - -Drop shadows - -X-ray windows (standard chrome) - -Perspective - -Shadowless 4fefd39f24
        -
        -
        -

        diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/Download The Bad Boys Movie Torrent.md b/spaces/inplisQlawa/anything-midjourney-v4-1/Download The Bad Boys Movie Torrent.md deleted file mode 100644 index 78ba540dabd2e9a8c404e1f638a67339e92e6903..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/Download The Bad Boys Movie Torrent.md +++ /dev/null @@ -1,6 +0,0 @@ -

        download the Bad Boys movie torrent


        Download ->->->-> https://urlin.us/2uEvBI



        - -?" "I thought you were different, man." "When you first asked me to marry you I said, "yes."" "Then I went to the movies to see what was playing!" "I can't believe you would do this to me." "I can't believe you would try to take my kids away from me like this." "Come on, we've been over this." "I can't have this kind of contact with them!" "I don't trust you!" "I don't trust my own children around you!" "Oh, that is so typical." "You always undercut me!" "I never want to see you near my children ever again!" "I know my own kids." "You don't!" "I do." "You do not." "I'm their father!" "You're a stranger!" "Oh, come on!" "I'm their father." "It's not going to work with me, all right?" "You're not their father!" "How can you even say that?" "All right, you know what?" "I wish you'd never married me!" "Okay, I'm glad that worked." "Hey, wait a minute." "I'm not finished." "I'm just getting started!" "You know what?" "They're my kids too!" "Maybe I'm their father." "Maybe you're the father of the girls' children." "Maybe I'm the father of your grandchildren." "Maybe I'm the father of your great-grandchildren." "I don't know who the father is." "I don't give a shit!" "It doesn't matter to me!" "I don't care!" "I'm their father!" "Oh, yeah?" "I'm their father!" "Yes, I am." "I'm the father!" "I'm the one that knows them!" "I'm the one that loves them!" "I'm the one they turn to when they have problems!" "I'm the one that protects them!" "I'm the one they come to when they're scared!" "I'm the one that holds them when they're hurt!" "I'm the one that introduces them to the world!" "I'm the one that knows what's best for them!" "I'm the one that makes them!" "I'm the one that does it all 4fefd39f24
        -
        -
        -

        diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/Midas Civil 2006 Full Crack 5 [REPACK].md b/spaces/inplisQlawa/anything-midjourney-v4-1/Midas Civil 2006 Full Crack 5 [REPACK].md deleted file mode 100644 index 7206ae7c7370e35311c147fbf4ce331450bcde38..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/Midas Civil 2006 Full Crack 5 [REPACK].md +++ /dev/null @@ -1,83 +0,0 @@ - -

        Midas Civil 2006 Full Crack 5: A Powerful Engineering Software for Bridge and Construction Projects

        - -

        If you are looking for a reliable and advanced engineering software that can help you design and optimize bridges and other civil structures, you may want to consider Midas Civil 2006 Full Crack 5. This software is a comprehensive solution that provides various tools and features to meet the needs of engineers and designers. In this article, we will introduce some of the main benefits and capabilities of Midas Civil 2006 Full Crack 5 and show you how to download and install it on your PC.

        -

        Midas Civil 2006 Full Crack 5


        Download File ••• https://urlin.us/2uEwtZ



        - -

        What is Midas Civil 2006 Full Crack 5?

        - -

        Midas Civil 2006 Full Crack 5 is a software application that was developed by Midas, a leading company in the field of civil engineering software. It is a part of the Midas Civil series, which has been used by thousands of engineers and designers worldwide for more than 20 years. Midas Civil 2006 Full Crack 5 is the latest version of the software, which was released in 2018. It offers many improvements and enhancements over the previous versions, such as:

        - -
          -
        • A user-friendly interface that makes it easy to navigate and operate the software.
        • -
        • A comprehensive set of tools and features that cover all aspects of bridge and civil structure design, analysis, and optimization.
        • -
        • An optimal solution for the design and modeling of complex structures in stages, taking into account the time-dependent properties of materials.
        • -
        • A high-performance engine that delivers fast and accurate results based on spreadsheet format.
        • -
        • A compatibility with various standards and codes for different countries and regions.
        • -
        - -

        What are the benefits of using Midas Civil 2006 Full Crack 5?

        - -

        By using Midas Civil 2006 Full Crack 5, you can enjoy many benefits that will enhance your productivity and efficiency as an engineer or designer. Some of these benefits are:

        - -
          -
        • You can create new standards for bridge and construction projects with the advanced engineering capabilities of the software.
        • -
        • You can overcome all the complications and challenges of the design and modeling process with the comprehensive tools and features of the software.
        • -
        • You can examine and optimize the final design before the project is implemented with the detailed results and reports provided by the software.
        • -
        • You can save time and money by using the software as a one-stop solution for all your engineering needs.
        • -
        • You can collaborate and communicate with other engineers and designers using the same software platform.
        • -
        - -

        How to download and install Midas Civil 2006 Full Crack 5?

        - -

        If you want to download and install Midas Civil 2006 Full Crack 5 on your PC, you can follow these simple steps:

        - -
          -
        1. Go to this link to access the download page of the software.
        2. -
        3. Click on the "Download Now" button to start downloading the setup file of Midas Civil 2006 v7.0.1.
        4. -
        5. Once the download is complete, extract the rar file using WinRAR or any other software.
        6. -
        7. Run the setup file as administrator and follow the instructions to install the software on your PC.
        8. -
        9. After the installation is complete, copy the crack file from the crack folder and paste it into the installation directory of the software.
        10. -
        11. Run the software as administrator and enjoy using Midas Civil 2006 Full Crack 5.
        12. -
        - -

        Conclusion

        - -

        Midas Civil 2006 Full Crack 5 is a powerful engineering software that can help you design and optimize bridges and other civil structures with ease and efficiency. It provides various tools and features that cover all aspects of engineering, from design to analysis to optimization. It also offers a user-friendly interface, a fast and accurate engine, a compatibility with various standards and codes, and a one-stop solution for all your engineering needs. If you want to download and install Midas Civil 2006 Full Crack 5 on your PC, you can follow the steps mentioned above. We hope this article was helpful for you. Thank you for reading.

        -

        -

        How to use Midas Civil 2006 Full Crack 5?

        - -

        Once you have downloaded and installed Midas Civil 2006 Full Crack 5 on your PC, you can start using it for your bridge and civil structure projects. The software has a user-friendly interface that allows you to access various tools and features easily. You can create and edit your models using the graphical user interface or the input data editor. You can also import and export data from other software such as AutoCAD, Excel, SAP2000, etc. You can perform various types of analysis such as static, dynamic, nonlinear, seismic, wind, etc. using the analysis engine of the software. You can also optimize your design using the design tools and features of the software. You can check the code compliance and safety of your design using the code checking and rating functions of the software. You can also generate detailed results and reports using the spreadsheet format of the software. You can also view and edit your results using the post-processor of the software.

        - -

        What are some examples of projects that use Midas Civil 2006 Full Crack 5?

        - -

        Midas Civil 2006 Full Crack 5 has been used by many engineers and designers for various bridge and civil structure projects around the world. Some of these projects are:

        - -
          -
        • The Busan-Geoje Fixed Link Project in South Korea, which is a 8.2 km long bridge-tunnel system that connects Busan and Geoje Island.
        • -
        • The Stonecutters Bridge in Hong Kong, which is a 1.6 km long cable-stayed bridge that spans the Rambler Channel.
        • -
        • The Queensferry Crossing in Scotland, which is a 2.7 km long cable-stayed bridge that crosses the Firth of Forth.
        • -
        • The New Champlain Bridge in Canada, which is a 3.4 km long cable-stayed bridge that connects Montreal and Brossard.
        • -
        • The Mersey Gateway Bridge in England, which is a 2.1 km long cable-stayed bridge that crosses the River Mersey.
        • -
        - -

        Why should you choose Midas Civil 2006 Full Crack 5?

        - -

        Midas Civil 2006 Full Crack 5 is a software that offers many advantages and benefits for engineers and designers who work on bridge and civil structure projects. Some of these advantages are:

        - -
          -
        • It is a software that sets new standards for engineering with its advanced capabilities and features.
        • -
        • It is a software that provides a comprehensive solution for all aspects of engineering, from design to analysis to optimization.
        • -
        • It is a software that delivers fast and accurate results based on spreadsheet format.
        • -
        • It is a software that is compatible with various standards and codes for different countries and regions.
        • -
        • It is a software that is easy to use and operate with its user-friendly interface.
        • -
        • It is a software that is cost-effective and time-saving with its one-stop solution.
        • -
        • It is a software that enables collaboration and communication with other engineers and designers using the same platform.
        • -
        - -

        Midas Civil 2006 Full Crack 5 is a software that can help you achieve your engineering goals with ease and efficiency. It is a software that you can trust and rely on for your bridge and civil structure projects. If you want to learn more about Midas Civil 2006 Full Crack 5, you can visit this website for more information.

        -

        Conclusion

        - -

        Midas Civil 2006 Full Crack 5 is a powerful engineering software that can help you design and optimize bridges and other civil structures with ease and efficiency. It provides various tools and features that cover all aspects of engineering, from design to analysis to optimization. It also offers a user-friendly interface, a fast and accurate engine, a compatibility with various standards and codes, and a one-stop solution for all your engineering needs. If you want to download and install Midas Civil 2006 Full Crack 5 on your PC, you can follow the steps mentioned above. We hope this article was helpful for you. Thank you for reading.

        3cee63e6c2
        -
        -
        \ No newline at end of file diff --git a/spaces/jbilcke-hf/VideoChain-UI/README.md b/spaces/jbilcke-hf/VideoChain-UI/README.md deleted file mode 100644 index 9e8ba7a08dfd85f7815d8a44b3b9f2bf7b667783..0000000000000000000000000000000000000000 --- a/spaces/jbilcke-hf/VideoChain-UI/README.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -title: VideoChain-UI -emoji: 🎬🔗 -colorFrom: "#1a1b1c" -colorTo: "#acb1b5" -sdk: docker -pinned: false -app_port: 3000 ---- - -This is the frontend interface to VideoChain-API, a server to generate videos using AI. - -This space cannot be easily duplicated yet, as you will have to configure a lot of things -to make it work (you need the API, you need separate spaces for upscaling, interpolation etc) -## Getting Started - -First, run the development server: - -```bash -npm run dev -``` - -Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. - -You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. - -This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font. - -## Things to know - -Next will cache the API calls! -So be careful about this (this is why we invalidate them in the fetch() method) - -## Environment variable - -``` -NEXT_PUBLIC_BASE_URL=http://localhost:3000 -VC_VIDEOCHAIN_API_URL=http://localhost:7860 -VC_SECRET_ACCESS_TOKEN=***SECRENT*** -``` \ No newline at end of file diff --git a/spaces/jbilcke-hf/VideoChain-UI/src/server/base.ts b/spaces/jbilcke-hf/VideoChain-UI/src/server/base.ts deleted file mode 100644 index 386e4dab442c4ce943161884fd7d90e8ac814d80..0000000000000000000000000000000000000000 --- a/spaces/jbilcke-hf/VideoChain-UI/src/server/base.ts +++ /dev/null @@ -1,161 +0,0 @@ - -// note: there is no / at the end in the variable -// so we have to add it ourselves if needed -const apiUrl = process.env.VC_VIDEOCHAIN_API_URL - -export const GET = async (path: string = '', defaultValue: T): Promise => { - try { - const res = await fetch(`${apiUrl}/${path}`, { - method: "GET", - headers: { - Accept: "application/json", - Authorization: `Bearer ${process.env.VC_SECRET_ACCESS_TOKEN}`, - }, - cache: 'no-store', - // we can also use this (see https://vercel.com/blog/vercel-cache-api-nextjs-cache) - // next: { revalidate: 1 } - }) - - // The return value is *not* serialized - // You can return Date, Map, Set, etc. - - // Recommendation: handle errors - if (res.status !== 200) { - // This will activate the closest `error.js` Error Boundary - throw new Error('Failed to fetch data') - } - - const data = await res.json() - - return ((data as T) || defaultValue) - } catch (err) { - console.error(err) - return defaultValue - } -} - - -export const DELETE = async (path: string = '', defaultValue: T): Promise => { - try { - const res = await fetch(`${apiUrl}/${path}`, { - method: "DELETE", - headers: { - Accept: "application/json", - Authorization: `Bearer ${process.env.VC_SECRET_ACCESS_TOKEN}`, - }, - cache: 'no-store', - // we can also use this (see https://vercel.com/blog/vercel-cache-api-nextjs-cache) - // next: { revalidate: 1 } - }) - - // The return value is *not* serialized - // You can return Date, Map, Set, etc. - - // Recommendation: handle errors - if (res.status !== 200) { - // This will activate the closest `error.js` Error Boundary - throw new Error('Failed to fetch data') - } - - const data = await res.json() - - return ((data as T) || defaultValue) - } catch (err) { - console.error(err) - return defaultValue - } -} - -export const POST = async (path: string = '', payload: S, defaultValue: T): Promise => { - try { - const res = await fetch(`${apiUrl}/${path}`, { - method: "POST", - headers: { - Accept: "application/json", - "Content-Type": "application/json", - Authorization: `Bearer ${process.env.VC_SECRET_ACCESS_TOKEN}`, - }, - body: JSON.stringify(payload), - // cache: 'no-store', - // we can also use this (see https://vercel.com/blog/vercel-cache-api-nextjs-cache) - next: { revalidate: 1 } - }) - // The return value is *not* serialized - // You can return Date, Map, Set, etc. - - // Recommendation: handle errors - if (res.status !== 200) { - // This will activate the closest `error.js` Error Boundary - throw new Error('Failed to post data') - } - - const data = await res.json() - - return ((data as T) || defaultValue) - } catch (err) { - return defaultValue - } -} - - -export const PUT = async (path: string = '', payload: S, defaultValue: T): Promise => { - try { - const res = await fetch(`${apiUrl}/${path}`, { - method: "PUT", - headers: { - Accept: "application/json", - "Content-Type": "application/json", - Authorization: `Bearer ${process.env.VC_SECRET_ACCESS_TOKEN}`, - }, - body: JSON.stringify(payload), - // cache: 'no-store', - // we can also use this (see https://vercel.com/blog/vercel-cache-api-nextjs-cache) - next: { revalidate: 1 } - }) - // The return value is *not* serialized - // You can return Date, Map, Set, etc. - - // Recommendation: handle errors - if (res.status !== 200) { - // This will activate the closest `error.js` Error Boundary - throw new Error('Failed to post data') - } - - const data = await res.json() - - return ((data as T) || defaultValue) - } catch (err) { - return defaultValue - } -} - -export const PATCH = async (path: string = '', payload: S, defaultValue: T): Promise => { - try { - const res = await fetch(`${apiUrl}/${path}`, { - method: "PATCH", - headers: { - Accept: "application/json", - "Content-Type": "application/json", - Authorization: `Bearer ${process.env.VC_SECRET_ACCESS_TOKEN}`, - }, - body: JSON.stringify(payload), - // cache: 'no-store', - // we can also use this (see https://vercel.com/blog/vercel-cache-api-nextjs-cache) - next: { revalidate: 1 } - }) - // The return value is *not* serialized - // You can return Date, Map, Set, etc. - - // Recommendation: handle errors - if (res.status !== 200) { - // This will activate the closest `error.js` Error Boundary - throw new Error('Failed to post data') - } - - const data = await res.json() - - return ((data as T) || defaultValue) - } catch (err) { - return defaultValue - } -} \ No newline at end of file diff --git a/spaces/jbilcke-hf/ai-comic-factory/src/app/interface/about/index.tsx b/spaces/jbilcke-hf/ai-comic-factory/src/app/interface/about/index.tsx deleted file mode 100644 index 5ff5d58daef853e8c26912ead40eb05c46681a4a..0000000000000000000000000000000000000000 --- a/spaces/jbilcke-hf/ai-comic-factory/src/app/interface/about/index.tsx +++ /dev/null @@ -1,46 +0,0 @@ -import { Button } from "@/components/ui/button" -import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog" -import { useState } from "react" - -export function About() { - const [isOpen, setOpen] = useState(false) - - return ( - - - - - - - The AI Comic Factory - - What is the AI Comic Factory? - - -
        -

        - The AI Comic Factory is a free and open-source application made to demonstrate the capabilities of AI models. -

        -

        - And yes, you can use your own art to generate comic panels! -

        -

        - 👉 The language model used to generate the descriptions of each panel is Llama-2 70b. -

        -

        - 👉 The stable diffusion model used to generate the images is the base SDXL 1.0. -

        -

        - The code is public and can be deployed at home with some changes in the code. See the README for details about the architecture. -

        -
        - - - -
        -
        - ) -} \ No newline at end of file diff --git a/spaces/jhtonyKoo/music_mixing_style_transfer/mixing_style_transfer/networks/__init__.py b/spaces/jhtonyKoo/music_mixing_style_transfer/mixing_style_transfer/networks/__init__.py deleted file mode 100644 index 4fe695aec7c837c75a665bae0091975a9131056a..0000000000000000000000000000000000000000 --- a/spaces/jhtonyKoo/music_mixing_style_transfer/mixing_style_transfer/networks/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from .architectures import * -from .network_utils import * \ No newline at end of file diff --git a/spaces/jie1/succ1/DLKcat/DeeplearningApproach/Code/analysis/SuppleFig4c_Hyperparameter_gnn&cnn.py b/spaces/jie1/succ1/DLKcat/DeeplearningApproach/Code/analysis/SuppleFig4c_Hyperparameter_gnn&cnn.py deleted file mode 100644 index 268f85cbd5c5b7c248149fad00d06f8f37f7ea22..0000000000000000000000000000000000000000 --- a/spaces/jie1/succ1/DLKcat/DeeplearningApproach/Code/analysis/SuppleFig4c_Hyperparameter_gnn&cnn.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/python -# coding: utf-8 - -# Author: LE YUAN -# Date: 2020-11-06 -# https://blog.csdn.net/roguesir/article/details/77839721 - -import matplotlib.pyplot as plt -from matplotlib import rc - - -with open('../../Data/output_hyper/MAEs--all--radius2--ngram3--dim10--layer_gnn2--window11--layer_cnn2--layer_output2--lr1e-3--lr_decay0.5--decay_interval10--weight_decay1e-6--iteration50.txt', 'r') as infile1 : - lines1 = infile1.readlines()[1:] - -with open('../../Data/output_hyper/MAEs--all--radius2--ngram3--dim10--layer_gnn3--window11--layer_cnn3--layer_output3--lr1e-3--lr_decay0.5--decay_interval10--weight_decay1e-6--iteration50.txt', 'r') as infile2 : - lines2 = infile2.readlines()[1:] - -with open('../../Data/output_hyper/MAEs--all--radius2--ngram3--dim10--layer_gnn4--window11--layer_cnn4--layer_output4--lr1e-3--lr_decay0.5--decay_interval10--weight_decay1e-6--iteration50.txt', 'r') as infile3 : - lines3 = infile3.readlines()[1:] - -epoch_1 = list() -R2_1 = list() -for line in lines1[:30] : - data = line.strip().split('\t') - # print(data) - epoch_line = int(data[0]) - R2_line = float(data[-2]) - if epoch_line%2 == 0 or epoch_line in [1,30] : - epoch_1.append(epoch_line) - R2_1.append(R2_line) - -epoch_2 = list() -R2_2 = list() -for line in lines2[:30] : - data = line.strip().split('\t') - # print(data) - epoch_line = int(data[0]) - R2_line = float(data[-2]) - if epoch_line%2 == 0 or epoch_line in [1,30] : - epoch_2.append(epoch_line) - R2_2.append(R2_line) - -epoch_3 = list() -R2_3 = list() -for line in lines3[:30] : - data = line.strip().split('\t') - # print(data) - epoch_line = int(data[0]) - R2_line = float(data[-2]) - if epoch_line%2 == 0 or epoch_line in [1,30] : - epoch_3.append(epoch_line) - R2_3.append(R2_line) - -plt.figure(figsize=(1.5,1.5)) - -# To solve the 'Helvetica' font cannot be used in PDF file -# https://stackoverflow.com/questions/59845568/the-pdf-backend-does-not-currently-support-the-selected-font -rc('font',**{'family':'serif','serif':['Helvetica']}) -plt.rcParams['pdf.fonttype'] = 42 - -plt.axes([0.12,0.12,0.83,0.83]) - -# plt.rcParams['xtick.direction'] = 'in' -# plt.rcParams['ytick.direction'] = 'in' - -plt.tick_params(direction='in') -plt.tick_params(which='major',length=1.5) -plt.tick_params(which='major',width=0.4) - -plt.plot(epoch_1,R2_1,color='#FC9E05',linestyle='dashed',linewidth=0.75,marker='s',markerfacecolor='#FC9E05', markersize=1,label='GNN : 2 & CNN : 2') -plt.plot(epoch_2,R2_2,color='#2166ac',linestyle='dashed',linewidth=0.75,marker='^',markerfacecolor='#2166ac', markersize=1,label='GNN : 3 & CNN : 3') -plt.plot(epoch_3,R2_3,color='#b2182b',linestyle='dashed',linewidth=0.75,marker='o',markerfacecolor='#b2182b', markersize=1,label='GNN : 4 & CNN : 4') - -plt.rcParams['font.family'] = 'Helvetica' - -plt.xticks([0,5,10,15,20,25,30]) -plt.yticks([0,0.1,0.2,0.3,0.4,0.5,0.6,0.7]) -# plt.yticks([0,0.2,0.4,0.6,0.8]) - -plt.xlabel('Epoch', fontsize=7) -# plt.ylabel('R2', fontsize=7) -plt.ylabel('R$^2$', fontsize=7) -plt.xticks(fontsize=6) -plt.yticks(fontsize=6) -plt.legend(frameon=False, prop={"size":6}) - -ax = plt.gca() -ax.spines['bottom'].set_linewidth(0.5) -ax.spines['left'].set_linewidth(0.5) -ax.spines['top'].set_linewidth(0.5) -ax.spines['right'].set_linewidth(0.5) - -plt.savefig("../../Results/figures/SuppleFig4c.pdf", dpi=400, bbox_inches='tight') - diff --git a/spaces/jmesikto/whisper-webui/LICENSE.md b/spaces/jmesikto/whisper-webui/LICENSE.md deleted file mode 100644 index f5f4b8b5ecd27c09e4ef16e9662bcb7bb2bfc76f..0000000000000000000000000000000000000000 --- a/spaces/jmesikto/whisper-webui/LICENSE.md +++ /dev/null @@ -1,195 +0,0 @@ -Apache License -============== - -_Version 2.0, January 2004_ -_<>_ - -### Terms and Conditions for use, reproduction, and distribution - -#### 1. Definitions - -“License” shall mean the terms and conditions for use, reproduction, and -distribution as defined by Sections 1 through 9 of this document. - -“Licensor” shall mean the copyright owner or entity authorized by the copyright -owner that is granting the License. - -“Legal Entity” shall mean the union of the acting entity and all other entities -that control, are controlled by, or are under common control with that entity. -For the purposes of this definition, “control” means **(i)** the power, direct or -indirect, to cause the direction or management of such entity, whether by -contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the -outstanding shares, or **(iii)** beneficial ownership of such entity. - -“You” (or “Your”) shall mean an individual or Legal Entity exercising -permissions granted by this License. - -“Source” form shall mean the preferred form for making modifications, including -but not limited to software source code, documentation source, and configuration -files. - -“Object” form shall mean any form resulting from mechanical transformation or -translation of a Source form, including but not limited to compiled object code, -generated documentation, and conversions to other media types. - -“Work” shall mean the work of authorship, whether in Source or Object form, made -available under the License, as indicated by a copyright notice that is included -in or attached to the work (an example is provided in the Appendix below). - -“Derivative Works” shall mean any work, whether in Source or Object form, that -is based on (or derived from) the Work and for which the editorial revisions, -annotations, elaborations, or other modifications represent, as a whole, an -original work of authorship. For the purposes of this License, Derivative Works -shall not include works that remain separable from, or merely link (or bind by -name) to the interfaces of, the Work and Derivative Works thereof. - -“Contribution” shall mean any work of authorship, including the original version -of the Work and any modifications or additions to that Work or Derivative Works -thereof, that is intentionally submitted to Licensor for inclusion in the Work -by the copyright owner or by an individual or Legal Entity authorized to submit -on behalf of the copyright owner. For the purposes of this definition, -“submitted” means any form of electronic, verbal, or written communication sent -to the Licensor or its representatives, including but not limited to -communication on electronic mailing lists, source code control systems, and -issue tracking systems that are managed by, or on behalf of, the Licensor for -the purpose of discussing and improving the Work, but excluding communication -that is conspicuously marked or otherwise designated in writing by the copyright -owner as “Not a Contribution.” - -“Contributor” shall mean Licensor and any individual or Legal Entity on behalf -of whom a Contribution has been received by Licensor and subsequently -incorporated within the Work. - -#### 2. Grant of Copyright License - -Subject to the terms and conditions of this License, each Contributor hereby -grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable copyright license to reproduce, prepare Derivative Works of, -publicly display, publicly perform, sublicense, and distribute the Work and such -Derivative Works in Source or Object form. - -#### 3. Grant of Patent License - -Subject to the terms and conditions of this License, each Contributor hereby -grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable (except as stated in this section) patent license to make, have -made, use, offer to sell, sell, import, and otherwise transfer the Work, where -such license applies only to those patent claims licensable by such Contributor -that are necessarily infringed by their Contribution(s) alone or by combination -of their Contribution(s) with the Work to which such Contribution(s) was -submitted. If You institute patent litigation against any entity (including a -cross-claim or counterclaim in a lawsuit) alleging that the Work or a -Contribution incorporated within the Work constitutes direct or contributory -patent infringement, then any patent licenses granted to You under this License -for that Work shall terminate as of the date such litigation is filed. - -#### 4. Redistribution - -You may reproduce and distribute copies of the Work or Derivative Works thereof -in any medium, with or without modifications, and in Source or Object form, -provided that You meet the following conditions: - -* **(a)** You must give any other recipients of the Work or Derivative Works a copy of -this License; and -* **(b)** You must cause any modified files to carry prominent notices stating that You -changed the files; and -* **(c)** You must retain, in the Source form of any Derivative Works that You distribute, -all copyright, patent, trademark, and attribution notices from the Source form -of the Work, excluding those notices that do not pertain to any part of the -Derivative Works; and -* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any -Derivative Works that You distribute must include a readable copy of the -attribution notices contained within such NOTICE file, excluding those notices -that do not pertain to any part of the Derivative Works, in at least one of the -following places: within a NOTICE text file distributed as part of the -Derivative Works; within the Source form or documentation, if provided along -with the Derivative Works; or, within a display generated by the Derivative -Works, if and wherever such third-party notices normally appear. The contents of -the NOTICE file are for informational purposes only and do not modify the -License. You may add Your own attribution notices within Derivative Works that -You distribute, alongside or as an addendum to the NOTICE text from the Work, -provided that such additional attribution notices cannot be construed as -modifying the License. - -You may add Your own copyright statement to Your modifications and may provide -additional or different license terms and conditions for use, reproduction, or -distribution of Your modifications, or for any such Derivative Works as a whole, -provided Your use, reproduction, and distribution of the Work otherwise complies -with the conditions stated in this License. - -#### 5. Submission of Contributions - -Unless You explicitly state otherwise, any Contribution intentionally submitted -for inclusion in the Work by You to the Licensor shall be under the terms and -conditions of this License, without any additional terms or conditions. -Notwithstanding the above, nothing herein shall supersede or modify the terms of -any separate license agreement you may have executed with Licensor regarding -such Contributions. - -#### 6. Trademarks - -This License does not grant permission to use the trade names, trademarks, -service marks, or product names of the Licensor, except as required for -reasonable and customary use in describing the origin of the Work and -reproducing the content of the NOTICE file. - -#### 7. Disclaimer of Warranty - -Unless required by applicable law or agreed to in writing, Licensor provides the -Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, -including, without limitation, any warranties or conditions of TITLE, -NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are -solely responsible for determining the appropriateness of using or -redistributing the Work and assume any risks associated with Your exercise of -permissions under this License. - -#### 8. Limitation of Liability - -In no event and under no legal theory, whether in tort (including negligence), -contract, or otherwise, unless required by applicable law (such as deliberate -and grossly negligent acts) or agreed to in writing, shall any Contributor be -liable to You for damages, including any direct, indirect, special, incidental, -or consequential damages of any character arising as a result of this License or -out of the use or inability to use the Work (including but not limited to -damages for loss of goodwill, work stoppage, computer failure or malfunction, or -any and all other commercial damages or losses), even if such Contributor has -been advised of the possibility of such damages. - -#### 9. Accepting Warranty or Additional Liability - -While redistributing the Work or Derivative Works thereof, You may choose to -offer, and charge a fee for, acceptance of support, warranty, indemnity, or -other liability obligations and/or rights consistent with this License. However, -in accepting such obligations, You may act only on Your own behalf and on Your -sole responsibility, not on behalf of any other Contributor, and only if You -agree to indemnify, defend, and hold each Contributor harmless for any liability -incurred by, or claims asserted against, such Contributor by reason of your -accepting any such warranty or additional liability. - -_END OF TERMS AND CONDITIONS_ - -### APPENDIX: How to apply the Apache License to your work - -To apply the Apache License to your work, attach the following boilerplate -notice, with the fields enclosed by brackets `[]` replaced with your own -identifying information. (Don't include the brackets!) The text should be -enclosed in the appropriate comment syntax for the file format. We also -recommend that a file or class name and description of purpose be included on -the same “printed page” as the copyright notice for easier identification within -third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. - diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/dns/ipv4.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/dns/ipv4.py deleted file mode 100644 index f549150a901356c4907efba97181ee385f1eebfc..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/dns/ipv4.py +++ /dev/null @@ -1,64 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM 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. - -"""IPv4 helper functions.""" - -import struct -from typing import Union - -import dns.exception - - -def inet_ntoa(address: bytes) -> str: - """Convert an IPv4 address in binary form to text form. - - *address*, a ``bytes``, the IPv4 address in binary form. - - Returns a ``str``. - """ - - if len(address) != 4: - raise dns.exception.SyntaxError - return "%u.%u.%u.%u" % (address[0], address[1], address[2], address[3]) - - -def inet_aton(text: Union[str, bytes]) -> bytes: - """Convert an IPv4 address in text form to binary form. - - *text*, a ``str`` or ``bytes``, the IPv4 address in textual form. - - Returns a ``bytes``. - """ - - if not isinstance(text, bytes): - btext = text.encode() - else: - btext = text - parts = btext.split(b".") - if len(parts) != 4: - raise dns.exception.SyntaxError - for part in parts: - if not part.isdigit(): - raise dns.exception.SyntaxError - if len(part) > 1 and part[0] == ord("0"): - # No leading zeros - raise dns.exception.SyntaxError - try: - b = [int(part) for part in parts] - return struct.pack("BBBB", *b) - except Exception: - raise dns.exception.SyntaxError diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/fontTools/merge/options.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/fontTools/merge/options.py deleted file mode 100644 index 0c4cfb99884992f5d69cef4b365f26947c3f837b..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/fontTools/merge/options.py +++ /dev/null @@ -1,83 +0,0 @@ -# Copyright 2013 Google, Inc. All Rights Reserved. -# -# Google Author(s): Behdad Esfahbod, Roozbeh Pournader - - -class Options(object): - class UnknownOptionError(Exception): - pass - - def __init__(self, **kwargs): - - self.verbose = False - self.timing = False - self.drop_tables = [] - - self.set(**kwargs) - - def set(self, **kwargs): - for k, v in kwargs.items(): - if not hasattr(self, k): - raise self.UnknownOptionError("Unknown option '%s'" % k) - setattr(self, k, v) - - def parse_opts(self, argv, ignore_unknown=[]): - ret = [] - opts = {} - for a in argv: - orig_a = a - if not a.startswith("--"): - ret.append(a) - continue - a = a[2:] - i = a.find("=") - op = "=" - if i == -1: - if a.startswith("no-"): - k = a[3:] - v = False - else: - k = a - v = True - else: - k = a[:i] - if k[-1] in "-+": - op = k[-1] + "=" # Ops is '-=' or '+=' now. - k = k[:-1] - v = a[i + 1 :] - ok = k - k = k.replace("-", "_") - if not hasattr(self, k): - if ignore_unknown is True or ok in ignore_unknown: - ret.append(orig_a) - continue - else: - raise self.UnknownOptionError("Unknown option '%s'" % a) - - ov = getattr(self, k) - if isinstance(ov, bool): - v = bool(v) - elif isinstance(ov, int): - v = int(v) - elif isinstance(ov, list): - vv = v.split(",") - if vv == [""]: - vv = [] - vv = [int(x, 0) if len(x) and x[0] in "0123456789" else x for x in vv] - if op == "=": - v = vv - elif op == "+=": - v = ov - v.extend(vv) - elif op == "-=": - v = ov - for x in vv: - if x in v: - v.remove(x) - else: - assert 0 - - opts[k] = v - self.set(**opts) - - return ret diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/fontTools/unicodedata/Blocks.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/fontTools/unicodedata/Blocks.py deleted file mode 100644 index b35c93d9b6fa563d1ba5ec162dd5e06d867d033a..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/fontTools/unicodedata/Blocks.py +++ /dev/null @@ -1,779 +0,0 @@ -# -*- coding: utf-8 -*- -# -# NOTE: This file was auto-generated with MetaTools/buildUCD.py. -# Source: https://unicode.org/Public/UNIDATA/Blocks.txt -# License: http://unicode.org/copyright.html#License -# -# Blocks-15.0.0.txt -# Date: 2022-01-28, 20:58:00 GMT [KW] -# © 2022 Unicode®, Inc. -# For terms of use, see https://www.unicode.org/terms_of_use.html -# -# Unicode Character Database -# For documentation, see https://www.unicode.org/reports/tr44/ -# -# Format: -# Start Code..End Code; Block Name - - -RANGES = [ - 0x0000, # .. 0x007F ; Basic Latin - 0x0080, # .. 0x00FF ; Latin-1 Supplement - 0x0100, # .. 0x017F ; Latin Extended-A - 0x0180, # .. 0x024F ; Latin Extended-B - 0x0250, # .. 0x02AF ; IPA Extensions - 0x02B0, # .. 0x02FF ; Spacing Modifier Letters - 0x0300, # .. 0x036F ; Combining Diacritical Marks - 0x0370, # .. 0x03FF ; Greek and Coptic - 0x0400, # .. 0x04FF ; Cyrillic - 0x0500, # .. 0x052F ; Cyrillic Supplement - 0x0530, # .. 0x058F ; Armenian - 0x0590, # .. 0x05FF ; Hebrew - 0x0600, # .. 0x06FF ; Arabic - 0x0700, # .. 0x074F ; Syriac - 0x0750, # .. 0x077F ; Arabic Supplement - 0x0780, # .. 0x07BF ; Thaana - 0x07C0, # .. 0x07FF ; NKo - 0x0800, # .. 0x083F ; Samaritan - 0x0840, # .. 0x085F ; Mandaic - 0x0860, # .. 0x086F ; Syriac Supplement - 0x0870, # .. 0x089F ; Arabic Extended-B - 0x08A0, # .. 0x08FF ; Arabic Extended-A - 0x0900, # .. 0x097F ; Devanagari - 0x0980, # .. 0x09FF ; Bengali - 0x0A00, # .. 0x0A7F ; Gurmukhi - 0x0A80, # .. 0x0AFF ; Gujarati - 0x0B00, # .. 0x0B7F ; Oriya - 0x0B80, # .. 0x0BFF ; Tamil - 0x0C00, # .. 0x0C7F ; Telugu - 0x0C80, # .. 0x0CFF ; Kannada - 0x0D00, # .. 0x0D7F ; Malayalam - 0x0D80, # .. 0x0DFF ; Sinhala - 0x0E00, # .. 0x0E7F ; Thai - 0x0E80, # .. 0x0EFF ; Lao - 0x0F00, # .. 0x0FFF ; Tibetan - 0x1000, # .. 0x109F ; Myanmar - 0x10A0, # .. 0x10FF ; Georgian - 0x1100, # .. 0x11FF ; Hangul Jamo - 0x1200, # .. 0x137F ; Ethiopic - 0x1380, # .. 0x139F ; Ethiopic Supplement - 0x13A0, # .. 0x13FF ; Cherokee - 0x1400, # .. 0x167F ; Unified Canadian Aboriginal Syllabics - 0x1680, # .. 0x169F ; Ogham - 0x16A0, # .. 0x16FF ; Runic - 0x1700, # .. 0x171F ; Tagalog - 0x1720, # .. 0x173F ; Hanunoo - 0x1740, # .. 0x175F ; Buhid - 0x1760, # .. 0x177F ; Tagbanwa - 0x1780, # .. 0x17FF ; Khmer - 0x1800, # .. 0x18AF ; Mongolian - 0x18B0, # .. 0x18FF ; Unified Canadian Aboriginal Syllabics Extended - 0x1900, # .. 0x194F ; Limbu - 0x1950, # .. 0x197F ; Tai Le - 0x1980, # .. 0x19DF ; New Tai Lue - 0x19E0, # .. 0x19FF ; Khmer Symbols - 0x1A00, # .. 0x1A1F ; Buginese - 0x1A20, # .. 0x1AAF ; Tai Tham - 0x1AB0, # .. 0x1AFF ; Combining Diacritical Marks Extended - 0x1B00, # .. 0x1B7F ; Balinese - 0x1B80, # .. 0x1BBF ; Sundanese - 0x1BC0, # .. 0x1BFF ; Batak - 0x1C00, # .. 0x1C4F ; Lepcha - 0x1C50, # .. 0x1C7F ; Ol Chiki - 0x1C80, # .. 0x1C8F ; Cyrillic Extended-C - 0x1C90, # .. 0x1CBF ; Georgian Extended - 0x1CC0, # .. 0x1CCF ; Sundanese Supplement - 0x1CD0, # .. 0x1CFF ; Vedic Extensions - 0x1D00, # .. 0x1D7F ; Phonetic Extensions - 0x1D80, # .. 0x1DBF ; Phonetic Extensions Supplement - 0x1DC0, # .. 0x1DFF ; Combining Diacritical Marks Supplement - 0x1E00, # .. 0x1EFF ; Latin Extended Additional - 0x1F00, # .. 0x1FFF ; Greek Extended - 0x2000, # .. 0x206F ; General Punctuation - 0x2070, # .. 0x209F ; Superscripts and Subscripts - 0x20A0, # .. 0x20CF ; Currency Symbols - 0x20D0, # .. 0x20FF ; Combining Diacritical Marks for Symbols - 0x2100, # .. 0x214F ; Letterlike Symbols - 0x2150, # .. 0x218F ; Number Forms - 0x2190, # .. 0x21FF ; Arrows - 0x2200, # .. 0x22FF ; Mathematical Operators - 0x2300, # .. 0x23FF ; Miscellaneous Technical - 0x2400, # .. 0x243F ; Control Pictures - 0x2440, # .. 0x245F ; Optical Character Recognition - 0x2460, # .. 0x24FF ; Enclosed Alphanumerics - 0x2500, # .. 0x257F ; Box Drawing - 0x2580, # .. 0x259F ; Block Elements - 0x25A0, # .. 0x25FF ; Geometric Shapes - 0x2600, # .. 0x26FF ; Miscellaneous Symbols - 0x2700, # .. 0x27BF ; Dingbats - 0x27C0, # .. 0x27EF ; Miscellaneous Mathematical Symbols-A - 0x27F0, # .. 0x27FF ; Supplemental Arrows-A - 0x2800, # .. 0x28FF ; Braille Patterns - 0x2900, # .. 0x297F ; Supplemental Arrows-B - 0x2980, # .. 0x29FF ; Miscellaneous Mathematical Symbols-B - 0x2A00, # .. 0x2AFF ; Supplemental Mathematical Operators - 0x2B00, # .. 0x2BFF ; Miscellaneous Symbols and Arrows - 0x2C00, # .. 0x2C5F ; Glagolitic - 0x2C60, # .. 0x2C7F ; Latin Extended-C - 0x2C80, # .. 0x2CFF ; Coptic - 0x2D00, # .. 0x2D2F ; Georgian Supplement - 0x2D30, # .. 0x2D7F ; Tifinagh - 0x2D80, # .. 0x2DDF ; Ethiopic Extended - 0x2DE0, # .. 0x2DFF ; Cyrillic Extended-A - 0x2E00, # .. 0x2E7F ; Supplemental Punctuation - 0x2E80, # .. 0x2EFF ; CJK Radicals Supplement - 0x2F00, # .. 0x2FDF ; Kangxi Radicals - 0x2FE0, # .. 0x2FEF ; No_Block - 0x2FF0, # .. 0x2FFF ; Ideographic Description Characters - 0x3000, # .. 0x303F ; CJK Symbols and Punctuation - 0x3040, # .. 0x309F ; Hiragana - 0x30A0, # .. 0x30FF ; Katakana - 0x3100, # .. 0x312F ; Bopomofo - 0x3130, # .. 0x318F ; Hangul Compatibility Jamo - 0x3190, # .. 0x319F ; Kanbun - 0x31A0, # .. 0x31BF ; Bopomofo Extended - 0x31C0, # .. 0x31EF ; CJK Strokes - 0x31F0, # .. 0x31FF ; Katakana Phonetic Extensions - 0x3200, # .. 0x32FF ; Enclosed CJK Letters and Months - 0x3300, # .. 0x33FF ; CJK Compatibility - 0x3400, # .. 0x4DBF ; CJK Unified Ideographs Extension A - 0x4DC0, # .. 0x4DFF ; Yijing Hexagram Symbols - 0x4E00, # .. 0x9FFF ; CJK Unified Ideographs - 0xA000, # .. 0xA48F ; Yi Syllables - 0xA490, # .. 0xA4CF ; Yi Radicals - 0xA4D0, # .. 0xA4FF ; Lisu - 0xA500, # .. 0xA63F ; Vai - 0xA640, # .. 0xA69F ; Cyrillic Extended-B - 0xA6A0, # .. 0xA6FF ; Bamum - 0xA700, # .. 0xA71F ; Modifier Tone Letters - 0xA720, # .. 0xA7FF ; Latin Extended-D - 0xA800, # .. 0xA82F ; Syloti Nagri - 0xA830, # .. 0xA83F ; Common Indic Number Forms - 0xA840, # .. 0xA87F ; Phags-pa - 0xA880, # .. 0xA8DF ; Saurashtra - 0xA8E0, # .. 0xA8FF ; Devanagari Extended - 0xA900, # .. 0xA92F ; Kayah Li - 0xA930, # .. 0xA95F ; Rejang - 0xA960, # .. 0xA97F ; Hangul Jamo Extended-A - 0xA980, # .. 0xA9DF ; Javanese - 0xA9E0, # .. 0xA9FF ; Myanmar Extended-B - 0xAA00, # .. 0xAA5F ; Cham - 0xAA60, # .. 0xAA7F ; Myanmar Extended-A - 0xAA80, # .. 0xAADF ; Tai Viet - 0xAAE0, # .. 0xAAFF ; Meetei Mayek Extensions - 0xAB00, # .. 0xAB2F ; Ethiopic Extended-A - 0xAB30, # .. 0xAB6F ; Latin Extended-E - 0xAB70, # .. 0xABBF ; Cherokee Supplement - 0xABC0, # .. 0xABFF ; Meetei Mayek - 0xAC00, # .. 0xD7AF ; Hangul Syllables - 0xD7B0, # .. 0xD7FF ; Hangul Jamo Extended-B - 0xD800, # .. 0xDB7F ; High Surrogates - 0xDB80, # .. 0xDBFF ; High Private Use Surrogates - 0xDC00, # .. 0xDFFF ; Low Surrogates - 0xE000, # .. 0xF8FF ; Private Use Area - 0xF900, # .. 0xFAFF ; CJK Compatibility Ideographs - 0xFB00, # .. 0xFB4F ; Alphabetic Presentation Forms - 0xFB50, # .. 0xFDFF ; Arabic Presentation Forms-A - 0xFE00, # .. 0xFE0F ; Variation Selectors - 0xFE10, # .. 0xFE1F ; Vertical Forms - 0xFE20, # .. 0xFE2F ; Combining Half Marks - 0xFE30, # .. 0xFE4F ; CJK Compatibility Forms - 0xFE50, # .. 0xFE6F ; Small Form Variants - 0xFE70, # .. 0xFEFF ; Arabic Presentation Forms-B - 0xFF00, # .. 0xFFEF ; Halfwidth and Fullwidth Forms - 0xFFF0, # .. 0xFFFF ; Specials - 0x10000, # .. 0x1007F ; Linear B Syllabary - 0x10080, # .. 0x100FF ; Linear B Ideograms - 0x10100, # .. 0x1013F ; Aegean Numbers - 0x10140, # .. 0x1018F ; Ancient Greek Numbers - 0x10190, # .. 0x101CF ; Ancient Symbols - 0x101D0, # .. 0x101FF ; Phaistos Disc - 0x10200, # .. 0x1027F ; No_Block - 0x10280, # .. 0x1029F ; Lycian - 0x102A0, # .. 0x102DF ; Carian - 0x102E0, # .. 0x102FF ; Coptic Epact Numbers - 0x10300, # .. 0x1032F ; Old Italic - 0x10330, # .. 0x1034F ; Gothic - 0x10350, # .. 0x1037F ; Old Permic - 0x10380, # .. 0x1039F ; Ugaritic - 0x103A0, # .. 0x103DF ; Old Persian - 0x103E0, # .. 0x103FF ; No_Block - 0x10400, # .. 0x1044F ; Deseret - 0x10450, # .. 0x1047F ; Shavian - 0x10480, # .. 0x104AF ; Osmanya - 0x104B0, # .. 0x104FF ; Osage - 0x10500, # .. 0x1052F ; Elbasan - 0x10530, # .. 0x1056F ; Caucasian Albanian - 0x10570, # .. 0x105BF ; Vithkuqi - 0x105C0, # .. 0x105FF ; No_Block - 0x10600, # .. 0x1077F ; Linear A - 0x10780, # .. 0x107BF ; Latin Extended-F - 0x107C0, # .. 0x107FF ; No_Block - 0x10800, # .. 0x1083F ; Cypriot Syllabary - 0x10840, # .. 0x1085F ; Imperial Aramaic - 0x10860, # .. 0x1087F ; Palmyrene - 0x10880, # .. 0x108AF ; Nabataean - 0x108B0, # .. 0x108DF ; No_Block - 0x108E0, # .. 0x108FF ; Hatran - 0x10900, # .. 0x1091F ; Phoenician - 0x10920, # .. 0x1093F ; Lydian - 0x10940, # .. 0x1097F ; No_Block - 0x10980, # .. 0x1099F ; Meroitic Hieroglyphs - 0x109A0, # .. 0x109FF ; Meroitic Cursive - 0x10A00, # .. 0x10A5F ; Kharoshthi - 0x10A60, # .. 0x10A7F ; Old South Arabian - 0x10A80, # .. 0x10A9F ; Old North Arabian - 0x10AA0, # .. 0x10ABF ; No_Block - 0x10AC0, # .. 0x10AFF ; Manichaean - 0x10B00, # .. 0x10B3F ; Avestan - 0x10B40, # .. 0x10B5F ; Inscriptional Parthian - 0x10B60, # .. 0x10B7F ; Inscriptional Pahlavi - 0x10B80, # .. 0x10BAF ; Psalter Pahlavi - 0x10BB0, # .. 0x10BFF ; No_Block - 0x10C00, # .. 0x10C4F ; Old Turkic - 0x10C50, # .. 0x10C7F ; No_Block - 0x10C80, # .. 0x10CFF ; Old Hungarian - 0x10D00, # .. 0x10D3F ; Hanifi Rohingya - 0x10D40, # .. 0x10E5F ; No_Block - 0x10E60, # .. 0x10E7F ; Rumi Numeral Symbols - 0x10E80, # .. 0x10EBF ; Yezidi - 0x10EC0, # .. 0x10EFF ; Arabic Extended-C - 0x10F00, # .. 0x10F2F ; Old Sogdian - 0x10F30, # .. 0x10F6F ; Sogdian - 0x10F70, # .. 0x10FAF ; Old Uyghur - 0x10FB0, # .. 0x10FDF ; Chorasmian - 0x10FE0, # .. 0x10FFF ; Elymaic - 0x11000, # .. 0x1107F ; Brahmi - 0x11080, # .. 0x110CF ; Kaithi - 0x110D0, # .. 0x110FF ; Sora Sompeng - 0x11100, # .. 0x1114F ; Chakma - 0x11150, # .. 0x1117F ; Mahajani - 0x11180, # .. 0x111DF ; Sharada - 0x111E0, # .. 0x111FF ; Sinhala Archaic Numbers - 0x11200, # .. 0x1124F ; Khojki - 0x11250, # .. 0x1127F ; No_Block - 0x11280, # .. 0x112AF ; Multani - 0x112B0, # .. 0x112FF ; Khudawadi - 0x11300, # .. 0x1137F ; Grantha - 0x11380, # .. 0x113FF ; No_Block - 0x11400, # .. 0x1147F ; Newa - 0x11480, # .. 0x114DF ; Tirhuta - 0x114E0, # .. 0x1157F ; No_Block - 0x11580, # .. 0x115FF ; Siddham - 0x11600, # .. 0x1165F ; Modi - 0x11660, # .. 0x1167F ; Mongolian Supplement - 0x11680, # .. 0x116CF ; Takri - 0x116D0, # .. 0x116FF ; No_Block - 0x11700, # .. 0x1174F ; Ahom - 0x11750, # .. 0x117FF ; No_Block - 0x11800, # .. 0x1184F ; Dogra - 0x11850, # .. 0x1189F ; No_Block - 0x118A0, # .. 0x118FF ; Warang Citi - 0x11900, # .. 0x1195F ; Dives Akuru - 0x11960, # .. 0x1199F ; No_Block - 0x119A0, # .. 0x119FF ; Nandinagari - 0x11A00, # .. 0x11A4F ; Zanabazar Square - 0x11A50, # .. 0x11AAF ; Soyombo - 0x11AB0, # .. 0x11ABF ; Unified Canadian Aboriginal Syllabics Extended-A - 0x11AC0, # .. 0x11AFF ; Pau Cin Hau - 0x11B00, # .. 0x11B5F ; Devanagari Extended-A - 0x11B60, # .. 0x11BFF ; No_Block - 0x11C00, # .. 0x11C6F ; Bhaiksuki - 0x11C70, # .. 0x11CBF ; Marchen - 0x11CC0, # .. 0x11CFF ; No_Block - 0x11D00, # .. 0x11D5F ; Masaram Gondi - 0x11D60, # .. 0x11DAF ; Gunjala Gondi - 0x11DB0, # .. 0x11EDF ; No_Block - 0x11EE0, # .. 0x11EFF ; Makasar - 0x11F00, # .. 0x11F5F ; Kawi - 0x11F60, # .. 0x11FAF ; No_Block - 0x11FB0, # .. 0x11FBF ; Lisu Supplement - 0x11FC0, # .. 0x11FFF ; Tamil Supplement - 0x12000, # .. 0x123FF ; Cuneiform - 0x12400, # .. 0x1247F ; Cuneiform Numbers and Punctuation - 0x12480, # .. 0x1254F ; Early Dynastic Cuneiform - 0x12550, # .. 0x12F8F ; No_Block - 0x12F90, # .. 0x12FFF ; Cypro-Minoan - 0x13000, # .. 0x1342F ; Egyptian Hieroglyphs - 0x13430, # .. 0x1345F ; Egyptian Hieroglyph Format Controls - 0x13460, # .. 0x143FF ; No_Block - 0x14400, # .. 0x1467F ; Anatolian Hieroglyphs - 0x14680, # .. 0x167FF ; No_Block - 0x16800, # .. 0x16A3F ; Bamum Supplement - 0x16A40, # .. 0x16A6F ; Mro - 0x16A70, # .. 0x16ACF ; Tangsa - 0x16AD0, # .. 0x16AFF ; Bassa Vah - 0x16B00, # .. 0x16B8F ; Pahawh Hmong - 0x16B90, # .. 0x16E3F ; No_Block - 0x16E40, # .. 0x16E9F ; Medefaidrin - 0x16EA0, # .. 0x16EFF ; No_Block - 0x16F00, # .. 0x16F9F ; Miao - 0x16FA0, # .. 0x16FDF ; No_Block - 0x16FE0, # .. 0x16FFF ; Ideographic Symbols and Punctuation - 0x17000, # .. 0x187FF ; Tangut - 0x18800, # .. 0x18AFF ; Tangut Components - 0x18B00, # .. 0x18CFF ; Khitan Small Script - 0x18D00, # .. 0x18D7F ; Tangut Supplement - 0x18D80, # .. 0x1AFEF ; No_Block - 0x1AFF0, # .. 0x1AFFF ; Kana Extended-B - 0x1B000, # .. 0x1B0FF ; Kana Supplement - 0x1B100, # .. 0x1B12F ; Kana Extended-A - 0x1B130, # .. 0x1B16F ; Small Kana Extension - 0x1B170, # .. 0x1B2FF ; Nushu - 0x1B300, # .. 0x1BBFF ; No_Block - 0x1BC00, # .. 0x1BC9F ; Duployan - 0x1BCA0, # .. 0x1BCAF ; Shorthand Format Controls - 0x1BCB0, # .. 0x1CEFF ; No_Block - 0x1CF00, # .. 0x1CFCF ; Znamenny Musical Notation - 0x1CFD0, # .. 0x1CFFF ; No_Block - 0x1D000, # .. 0x1D0FF ; Byzantine Musical Symbols - 0x1D100, # .. 0x1D1FF ; Musical Symbols - 0x1D200, # .. 0x1D24F ; Ancient Greek Musical Notation - 0x1D250, # .. 0x1D2BF ; No_Block - 0x1D2C0, # .. 0x1D2DF ; Kaktovik Numerals - 0x1D2E0, # .. 0x1D2FF ; Mayan Numerals - 0x1D300, # .. 0x1D35F ; Tai Xuan Jing Symbols - 0x1D360, # .. 0x1D37F ; Counting Rod Numerals - 0x1D380, # .. 0x1D3FF ; No_Block - 0x1D400, # .. 0x1D7FF ; Mathematical Alphanumeric Symbols - 0x1D800, # .. 0x1DAAF ; Sutton SignWriting - 0x1DAB0, # .. 0x1DEFF ; No_Block - 0x1DF00, # .. 0x1DFFF ; Latin Extended-G - 0x1E000, # .. 0x1E02F ; Glagolitic Supplement - 0x1E030, # .. 0x1E08F ; Cyrillic Extended-D - 0x1E090, # .. 0x1E0FF ; No_Block - 0x1E100, # .. 0x1E14F ; Nyiakeng Puachue Hmong - 0x1E150, # .. 0x1E28F ; No_Block - 0x1E290, # .. 0x1E2BF ; Toto - 0x1E2C0, # .. 0x1E2FF ; Wancho - 0x1E300, # .. 0x1E4CF ; No_Block - 0x1E4D0, # .. 0x1E4FF ; Nag Mundari - 0x1E500, # .. 0x1E7DF ; No_Block - 0x1E7E0, # .. 0x1E7FF ; Ethiopic Extended-B - 0x1E800, # .. 0x1E8DF ; Mende Kikakui - 0x1E8E0, # .. 0x1E8FF ; No_Block - 0x1E900, # .. 0x1E95F ; Adlam - 0x1E960, # .. 0x1EC6F ; No_Block - 0x1EC70, # .. 0x1ECBF ; Indic Siyaq Numbers - 0x1ECC0, # .. 0x1ECFF ; No_Block - 0x1ED00, # .. 0x1ED4F ; Ottoman Siyaq Numbers - 0x1ED50, # .. 0x1EDFF ; No_Block - 0x1EE00, # .. 0x1EEFF ; Arabic Mathematical Alphabetic Symbols - 0x1EF00, # .. 0x1EFFF ; No_Block - 0x1F000, # .. 0x1F02F ; Mahjong Tiles - 0x1F030, # .. 0x1F09F ; Domino Tiles - 0x1F0A0, # .. 0x1F0FF ; Playing Cards - 0x1F100, # .. 0x1F1FF ; Enclosed Alphanumeric Supplement - 0x1F200, # .. 0x1F2FF ; Enclosed Ideographic Supplement - 0x1F300, # .. 0x1F5FF ; Miscellaneous Symbols and Pictographs - 0x1F600, # .. 0x1F64F ; Emoticons - 0x1F650, # .. 0x1F67F ; Ornamental Dingbats - 0x1F680, # .. 0x1F6FF ; Transport and Map Symbols - 0x1F700, # .. 0x1F77F ; Alchemical Symbols - 0x1F780, # .. 0x1F7FF ; Geometric Shapes Extended - 0x1F800, # .. 0x1F8FF ; Supplemental Arrows-C - 0x1F900, # .. 0x1F9FF ; Supplemental Symbols and Pictographs - 0x1FA00, # .. 0x1FA6F ; Chess Symbols - 0x1FA70, # .. 0x1FAFF ; Symbols and Pictographs Extended-A - 0x1FB00, # .. 0x1FBFF ; Symbols for Legacy Computing - 0x1FC00, # .. 0x1FFFF ; No_Block - 0x20000, # .. 0x2A6DF ; CJK Unified Ideographs Extension B - 0x2A6E0, # .. 0x2A6FF ; No_Block - 0x2A700, # .. 0x2B73F ; CJK Unified Ideographs Extension C - 0x2B740, # .. 0x2B81F ; CJK Unified Ideographs Extension D - 0x2B820, # .. 0x2CEAF ; CJK Unified Ideographs Extension E - 0x2CEB0, # .. 0x2EBEF ; CJK Unified Ideographs Extension F - 0x2EBF0, # .. 0x2F7FF ; No_Block - 0x2F800, # .. 0x2FA1F ; CJK Compatibility Ideographs Supplement - 0x2FA20, # .. 0x2FFFF ; No_Block - 0x30000, # .. 0x3134F ; CJK Unified Ideographs Extension G - 0x31350, # .. 0x323AF ; CJK Unified Ideographs Extension H - 0x323B0, # .. 0xDFFFF ; No_Block - 0xE0000, # .. 0xE007F ; Tags - 0xE0080, # .. 0xE00FF ; No_Block - 0xE0100, # .. 0xE01EF ; Variation Selectors Supplement - 0xE01F0, # .. 0xEFFFF ; No_Block - 0xF0000, # .. 0xFFFFF ; Supplementary Private Use Area-A - 0x100000, # .. 0x10FFFF ; Supplementary Private Use Area-B -] - -VALUES = [ - "Basic Latin", # 0000..007F - "Latin-1 Supplement", # 0080..00FF - "Latin Extended-A", # 0100..017F - "Latin Extended-B", # 0180..024F - "IPA Extensions", # 0250..02AF - "Spacing Modifier Letters", # 02B0..02FF - "Combining Diacritical Marks", # 0300..036F - "Greek and Coptic", # 0370..03FF - "Cyrillic", # 0400..04FF - "Cyrillic Supplement", # 0500..052F - "Armenian", # 0530..058F - "Hebrew", # 0590..05FF - "Arabic", # 0600..06FF - "Syriac", # 0700..074F - "Arabic Supplement", # 0750..077F - "Thaana", # 0780..07BF - "NKo", # 07C0..07FF - "Samaritan", # 0800..083F - "Mandaic", # 0840..085F - "Syriac Supplement", # 0860..086F - "Arabic Extended-B", # 0870..089F - "Arabic Extended-A", # 08A0..08FF - "Devanagari", # 0900..097F - "Bengali", # 0980..09FF - "Gurmukhi", # 0A00..0A7F - "Gujarati", # 0A80..0AFF - "Oriya", # 0B00..0B7F - "Tamil", # 0B80..0BFF - "Telugu", # 0C00..0C7F - "Kannada", # 0C80..0CFF - "Malayalam", # 0D00..0D7F - "Sinhala", # 0D80..0DFF - "Thai", # 0E00..0E7F - "Lao", # 0E80..0EFF - "Tibetan", # 0F00..0FFF - "Myanmar", # 1000..109F - "Georgian", # 10A0..10FF - "Hangul Jamo", # 1100..11FF - "Ethiopic", # 1200..137F - "Ethiopic Supplement", # 1380..139F - "Cherokee", # 13A0..13FF - "Unified Canadian Aboriginal Syllabics", # 1400..167F - "Ogham", # 1680..169F - "Runic", # 16A0..16FF - "Tagalog", # 1700..171F - "Hanunoo", # 1720..173F - "Buhid", # 1740..175F - "Tagbanwa", # 1760..177F - "Khmer", # 1780..17FF - "Mongolian", # 1800..18AF - "Unified Canadian Aboriginal Syllabics Extended", # 18B0..18FF - "Limbu", # 1900..194F - "Tai Le", # 1950..197F - "New Tai Lue", # 1980..19DF - "Khmer Symbols", # 19E0..19FF - "Buginese", # 1A00..1A1F - "Tai Tham", # 1A20..1AAF - "Combining Diacritical Marks Extended", # 1AB0..1AFF - "Balinese", # 1B00..1B7F - "Sundanese", # 1B80..1BBF - "Batak", # 1BC0..1BFF - "Lepcha", # 1C00..1C4F - "Ol Chiki", # 1C50..1C7F - "Cyrillic Extended-C", # 1C80..1C8F - "Georgian Extended", # 1C90..1CBF - "Sundanese Supplement", # 1CC0..1CCF - "Vedic Extensions", # 1CD0..1CFF - "Phonetic Extensions", # 1D00..1D7F - "Phonetic Extensions Supplement", # 1D80..1DBF - "Combining Diacritical Marks Supplement", # 1DC0..1DFF - "Latin Extended Additional", # 1E00..1EFF - "Greek Extended", # 1F00..1FFF - "General Punctuation", # 2000..206F - "Superscripts and Subscripts", # 2070..209F - "Currency Symbols", # 20A0..20CF - "Combining Diacritical Marks for Symbols", # 20D0..20FF - "Letterlike Symbols", # 2100..214F - "Number Forms", # 2150..218F - "Arrows", # 2190..21FF - "Mathematical Operators", # 2200..22FF - "Miscellaneous Technical", # 2300..23FF - "Control Pictures", # 2400..243F - "Optical Character Recognition", # 2440..245F - "Enclosed Alphanumerics", # 2460..24FF - "Box Drawing", # 2500..257F - "Block Elements", # 2580..259F - "Geometric Shapes", # 25A0..25FF - "Miscellaneous Symbols", # 2600..26FF - "Dingbats", # 2700..27BF - "Miscellaneous Mathematical Symbols-A", # 27C0..27EF - "Supplemental Arrows-A", # 27F0..27FF - "Braille Patterns", # 2800..28FF - "Supplemental Arrows-B", # 2900..297F - "Miscellaneous Mathematical Symbols-B", # 2980..29FF - "Supplemental Mathematical Operators", # 2A00..2AFF - "Miscellaneous Symbols and Arrows", # 2B00..2BFF - "Glagolitic", # 2C00..2C5F - "Latin Extended-C", # 2C60..2C7F - "Coptic", # 2C80..2CFF - "Georgian Supplement", # 2D00..2D2F - "Tifinagh", # 2D30..2D7F - "Ethiopic Extended", # 2D80..2DDF - "Cyrillic Extended-A", # 2DE0..2DFF - "Supplemental Punctuation", # 2E00..2E7F - "CJK Radicals Supplement", # 2E80..2EFF - "Kangxi Radicals", # 2F00..2FDF - "No_Block", # 2FE0..2FEF - "Ideographic Description Characters", # 2FF0..2FFF - "CJK Symbols and Punctuation", # 3000..303F - "Hiragana", # 3040..309F - "Katakana", # 30A0..30FF - "Bopomofo", # 3100..312F - "Hangul Compatibility Jamo", # 3130..318F - "Kanbun", # 3190..319F - "Bopomofo Extended", # 31A0..31BF - "CJK Strokes", # 31C0..31EF - "Katakana Phonetic Extensions", # 31F0..31FF - "Enclosed CJK Letters and Months", # 3200..32FF - "CJK Compatibility", # 3300..33FF - "CJK Unified Ideographs Extension A", # 3400..4DBF - "Yijing Hexagram Symbols", # 4DC0..4DFF - "CJK Unified Ideographs", # 4E00..9FFF - "Yi Syllables", # A000..A48F - "Yi Radicals", # A490..A4CF - "Lisu", # A4D0..A4FF - "Vai", # A500..A63F - "Cyrillic Extended-B", # A640..A69F - "Bamum", # A6A0..A6FF - "Modifier Tone Letters", # A700..A71F - "Latin Extended-D", # A720..A7FF - "Syloti Nagri", # A800..A82F - "Common Indic Number Forms", # A830..A83F - "Phags-pa", # A840..A87F - "Saurashtra", # A880..A8DF - "Devanagari Extended", # A8E0..A8FF - "Kayah Li", # A900..A92F - "Rejang", # A930..A95F - "Hangul Jamo Extended-A", # A960..A97F - "Javanese", # A980..A9DF - "Myanmar Extended-B", # A9E0..A9FF - "Cham", # AA00..AA5F - "Myanmar Extended-A", # AA60..AA7F - "Tai Viet", # AA80..AADF - "Meetei Mayek Extensions", # AAE0..AAFF - "Ethiopic Extended-A", # AB00..AB2F - "Latin Extended-E", # AB30..AB6F - "Cherokee Supplement", # AB70..ABBF - "Meetei Mayek", # ABC0..ABFF - "Hangul Syllables", # AC00..D7AF - "Hangul Jamo Extended-B", # D7B0..D7FF - "High Surrogates", # D800..DB7F - "High Private Use Surrogates", # DB80..DBFF - "Low Surrogates", # DC00..DFFF - "Private Use Area", # E000..F8FF - "CJK Compatibility Ideographs", # F900..FAFF - "Alphabetic Presentation Forms", # FB00..FB4F - "Arabic Presentation Forms-A", # FB50..FDFF - "Variation Selectors", # FE00..FE0F - "Vertical Forms", # FE10..FE1F - "Combining Half Marks", # FE20..FE2F - "CJK Compatibility Forms", # FE30..FE4F - "Small Form Variants", # FE50..FE6F - "Arabic Presentation Forms-B", # FE70..FEFF - "Halfwidth and Fullwidth Forms", # FF00..FFEF - "Specials", # FFF0..FFFF - "Linear B Syllabary", # 10000..1007F - "Linear B Ideograms", # 10080..100FF - "Aegean Numbers", # 10100..1013F - "Ancient Greek Numbers", # 10140..1018F - "Ancient Symbols", # 10190..101CF - "Phaistos Disc", # 101D0..101FF - "No_Block", # 10200..1027F - "Lycian", # 10280..1029F - "Carian", # 102A0..102DF - "Coptic Epact Numbers", # 102E0..102FF - "Old Italic", # 10300..1032F - "Gothic", # 10330..1034F - "Old Permic", # 10350..1037F - "Ugaritic", # 10380..1039F - "Old Persian", # 103A0..103DF - "No_Block", # 103E0..103FF - "Deseret", # 10400..1044F - "Shavian", # 10450..1047F - "Osmanya", # 10480..104AF - "Osage", # 104B0..104FF - "Elbasan", # 10500..1052F - "Caucasian Albanian", # 10530..1056F - "Vithkuqi", # 10570..105BF - "No_Block", # 105C0..105FF - "Linear A", # 10600..1077F - "Latin Extended-F", # 10780..107BF - "No_Block", # 107C0..107FF - "Cypriot Syllabary", # 10800..1083F - "Imperial Aramaic", # 10840..1085F - "Palmyrene", # 10860..1087F - "Nabataean", # 10880..108AF - "No_Block", # 108B0..108DF - "Hatran", # 108E0..108FF - "Phoenician", # 10900..1091F - "Lydian", # 10920..1093F - "No_Block", # 10940..1097F - "Meroitic Hieroglyphs", # 10980..1099F - "Meroitic Cursive", # 109A0..109FF - "Kharoshthi", # 10A00..10A5F - "Old South Arabian", # 10A60..10A7F - "Old North Arabian", # 10A80..10A9F - "No_Block", # 10AA0..10ABF - "Manichaean", # 10AC0..10AFF - "Avestan", # 10B00..10B3F - "Inscriptional Parthian", # 10B40..10B5F - "Inscriptional Pahlavi", # 10B60..10B7F - "Psalter Pahlavi", # 10B80..10BAF - "No_Block", # 10BB0..10BFF - "Old Turkic", # 10C00..10C4F - "No_Block", # 10C50..10C7F - "Old Hungarian", # 10C80..10CFF - "Hanifi Rohingya", # 10D00..10D3F - "No_Block", # 10D40..10E5F - "Rumi Numeral Symbols", # 10E60..10E7F - "Yezidi", # 10E80..10EBF - "Arabic Extended-C", # 10EC0..10EFF - "Old Sogdian", # 10F00..10F2F - "Sogdian", # 10F30..10F6F - "Old Uyghur", # 10F70..10FAF - "Chorasmian", # 10FB0..10FDF - "Elymaic", # 10FE0..10FFF - "Brahmi", # 11000..1107F - "Kaithi", # 11080..110CF - "Sora Sompeng", # 110D0..110FF - "Chakma", # 11100..1114F - "Mahajani", # 11150..1117F - "Sharada", # 11180..111DF - "Sinhala Archaic Numbers", # 111E0..111FF - "Khojki", # 11200..1124F - "No_Block", # 11250..1127F - "Multani", # 11280..112AF - "Khudawadi", # 112B0..112FF - "Grantha", # 11300..1137F - "No_Block", # 11380..113FF - "Newa", # 11400..1147F - "Tirhuta", # 11480..114DF - "No_Block", # 114E0..1157F - "Siddham", # 11580..115FF - "Modi", # 11600..1165F - "Mongolian Supplement", # 11660..1167F - "Takri", # 11680..116CF - "No_Block", # 116D0..116FF - "Ahom", # 11700..1174F - "No_Block", # 11750..117FF - "Dogra", # 11800..1184F - "No_Block", # 11850..1189F - "Warang Citi", # 118A0..118FF - "Dives Akuru", # 11900..1195F - "No_Block", # 11960..1199F - "Nandinagari", # 119A0..119FF - "Zanabazar Square", # 11A00..11A4F - "Soyombo", # 11A50..11AAF - "Unified Canadian Aboriginal Syllabics Extended-A", # 11AB0..11ABF - "Pau Cin Hau", # 11AC0..11AFF - "Devanagari Extended-A", # 11B00..11B5F - "No_Block", # 11B60..11BFF - "Bhaiksuki", # 11C00..11C6F - "Marchen", # 11C70..11CBF - "No_Block", # 11CC0..11CFF - "Masaram Gondi", # 11D00..11D5F - "Gunjala Gondi", # 11D60..11DAF - "No_Block", # 11DB0..11EDF - "Makasar", # 11EE0..11EFF - "Kawi", # 11F00..11F5F - "No_Block", # 11F60..11FAF - "Lisu Supplement", # 11FB0..11FBF - "Tamil Supplement", # 11FC0..11FFF - "Cuneiform", # 12000..123FF - "Cuneiform Numbers and Punctuation", # 12400..1247F - "Early Dynastic Cuneiform", # 12480..1254F - "No_Block", # 12550..12F8F - "Cypro-Minoan", # 12F90..12FFF - "Egyptian Hieroglyphs", # 13000..1342F - "Egyptian Hieroglyph Format Controls", # 13430..1345F - "No_Block", # 13460..143FF - "Anatolian Hieroglyphs", # 14400..1467F - "No_Block", # 14680..167FF - "Bamum Supplement", # 16800..16A3F - "Mro", # 16A40..16A6F - "Tangsa", # 16A70..16ACF - "Bassa Vah", # 16AD0..16AFF - "Pahawh Hmong", # 16B00..16B8F - "No_Block", # 16B90..16E3F - "Medefaidrin", # 16E40..16E9F - "No_Block", # 16EA0..16EFF - "Miao", # 16F00..16F9F - "No_Block", # 16FA0..16FDF - "Ideographic Symbols and Punctuation", # 16FE0..16FFF - "Tangut", # 17000..187FF - "Tangut Components", # 18800..18AFF - "Khitan Small Script", # 18B00..18CFF - "Tangut Supplement", # 18D00..18D7F - "No_Block", # 18D80..1AFEF - "Kana Extended-B", # 1AFF0..1AFFF - "Kana Supplement", # 1B000..1B0FF - "Kana Extended-A", # 1B100..1B12F - "Small Kana Extension", # 1B130..1B16F - "Nushu", # 1B170..1B2FF - "No_Block", # 1B300..1BBFF - "Duployan", # 1BC00..1BC9F - "Shorthand Format Controls", # 1BCA0..1BCAF - "No_Block", # 1BCB0..1CEFF - "Znamenny Musical Notation", # 1CF00..1CFCF - "No_Block", # 1CFD0..1CFFF - "Byzantine Musical Symbols", # 1D000..1D0FF - "Musical Symbols", # 1D100..1D1FF - "Ancient Greek Musical Notation", # 1D200..1D24F - "No_Block", # 1D250..1D2BF - "Kaktovik Numerals", # 1D2C0..1D2DF - "Mayan Numerals", # 1D2E0..1D2FF - "Tai Xuan Jing Symbols", # 1D300..1D35F - "Counting Rod Numerals", # 1D360..1D37F - "No_Block", # 1D380..1D3FF - "Mathematical Alphanumeric Symbols", # 1D400..1D7FF - "Sutton SignWriting", # 1D800..1DAAF - "No_Block", # 1DAB0..1DEFF - "Latin Extended-G", # 1DF00..1DFFF - "Glagolitic Supplement", # 1E000..1E02F - "Cyrillic Extended-D", # 1E030..1E08F - "No_Block", # 1E090..1E0FF - "Nyiakeng Puachue Hmong", # 1E100..1E14F - "No_Block", # 1E150..1E28F - "Toto", # 1E290..1E2BF - "Wancho", # 1E2C0..1E2FF - "No_Block", # 1E300..1E4CF - "Nag Mundari", # 1E4D0..1E4FF - "No_Block", # 1E500..1E7DF - "Ethiopic Extended-B", # 1E7E0..1E7FF - "Mende Kikakui", # 1E800..1E8DF - "No_Block", # 1E8E0..1E8FF - "Adlam", # 1E900..1E95F - "No_Block", # 1E960..1EC6F - "Indic Siyaq Numbers", # 1EC70..1ECBF - "No_Block", # 1ECC0..1ECFF - "Ottoman Siyaq Numbers", # 1ED00..1ED4F - "No_Block", # 1ED50..1EDFF - "Arabic Mathematical Alphabetic Symbols", # 1EE00..1EEFF - "No_Block", # 1EF00..1EFFF - "Mahjong Tiles", # 1F000..1F02F - "Domino Tiles", # 1F030..1F09F - "Playing Cards", # 1F0A0..1F0FF - "Enclosed Alphanumeric Supplement", # 1F100..1F1FF - "Enclosed Ideographic Supplement", # 1F200..1F2FF - "Miscellaneous Symbols and Pictographs", # 1F300..1F5FF - "Emoticons", # 1F600..1F64F - "Ornamental Dingbats", # 1F650..1F67F - "Transport and Map Symbols", # 1F680..1F6FF - "Alchemical Symbols", # 1F700..1F77F - "Geometric Shapes Extended", # 1F780..1F7FF - "Supplemental Arrows-C", # 1F800..1F8FF - "Supplemental Symbols and Pictographs", # 1F900..1F9FF - "Chess Symbols", # 1FA00..1FA6F - "Symbols and Pictographs Extended-A", # 1FA70..1FAFF - "Symbols for Legacy Computing", # 1FB00..1FBFF - "No_Block", # 1FC00..1FFFF - "CJK Unified Ideographs Extension B", # 20000..2A6DF - "No_Block", # 2A6E0..2A6FF - "CJK Unified Ideographs Extension C", # 2A700..2B73F - "CJK Unified Ideographs Extension D", # 2B740..2B81F - "CJK Unified Ideographs Extension E", # 2B820..2CEAF - "CJK Unified Ideographs Extension F", # 2CEB0..2EBEF - "No_Block", # 2EBF0..2F7FF - "CJK Compatibility Ideographs Supplement", # 2F800..2FA1F - "No_Block", # 2FA20..2FFFF - "CJK Unified Ideographs Extension G", # 30000..3134F - "CJK Unified Ideographs Extension H", # 31350..323AF - "No_Block", # 323B0..DFFFF - "Tags", # E0000..E007F - "No_Block", # E0080..E00FF - "Variation Selectors Supplement", # E0100..E01EF - "No_Block", # E01F0..EFFFF - "Supplementary Private Use Area-A", # F0000..FFFFF - "Supplementary Private Use Area-B", # 100000..10FFFF -] diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/gradio/components/model3d.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/gradio/components/model3d.py deleted file mode 100644 index d11bef86b2c1efffe5f3d037065341e0a41f1d91..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/gradio/components/model3d.py +++ /dev/null @@ -1,179 +0,0 @@ -"""gr.Model3D() component.""" - -from __future__ import annotations - -import warnings -from pathlib import Path -from typing import Any, Callable, Literal - -from gradio_client import media_data -from gradio_client.documentation import document, set_documentation_group -from gradio_client.serializing import FileSerializable - -from gradio.components.base import IOComponent, _Keywords -from gradio.events import ( - Changeable, - Clearable, - Editable, - Uploadable, -) - -set_documentation_group("component") - - -@document() -class Model3D( - Changeable, Uploadable, Editable, Clearable, IOComponent, FileSerializable -): - """ - Component allows users to upload or view 3D Model files (.obj, .glb, or .gltf). - Preprocessing: This component passes the uploaded file as a {str}filepath. - Postprocessing: expects function to return a {str} or {pathlib.Path} filepath of type (.obj, glb, or .gltf) - - Demos: model3D - Guides: how-to-use-3D-model-component - """ - - def __init__( - self, - value: str | Callable | None = None, - *, - clear_color: tuple[float, float, float, float] | None = None, - camera_position: tuple[ - int | float | None, int | float | None, int | float | None - ] = ( - None, - None, - None, - ), - zoom_speed: float = 1, - height: int | None = None, - label: str | None = None, - show_label: bool | None = None, - every: float | None = None, - container: bool = True, - scale: int | None = None, - min_width: int = 160, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - value: path to (.obj, glb, or .gltf) file to show in model3D viewer. If callable, the function will be called whenever the app loads to set the initial value of the component. - clear_color: background color of scene, should be a tuple of 4 floats between 0 and 1 representing RGBA values. - camera_position: initial camera position of scene, provided as a tuple of `(alpha, beta, radius)`. Each value is optional. If provided, `alpha` and `beta` should be in degrees reflecting the angular position along the longitudinal and latitudinal axes, respectively. Radius corresponds to the distance from the center of the object to the camera. - zoom_speed: the speed of zooming in and out of the scene when the cursor wheel is rotated or when screen is pinched on a mobile device. Should be a positive float, increase this value to make zooming faster, decrease to make it slower. Affects the wheelPrecision property of the camera. - height: height of the model3D component, in pixels. - label: component name in interface. - show_label: if True, will display label. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - container: If True, will place the component in a container - providing some extra padding around the border. - scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer. - min_width: minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - self.clear_color = clear_color or [0, 0, 0, 0] - self.camera_position = camera_position - self.height = height - self.zoom_speed = zoom_speed - - IOComponent.__init__( - self, - label=label, - every=every, - show_label=show_label, - container=container, - scale=scale, - min_width=min_width, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - def example_inputs(self) -> dict[str, Any]: - return { - "raw": {"is_file": False, "data": media_data.BASE64_MODEL3D}, - "serialized": "https://github.com/gradio-app/gradio/raw/main/test/test_files/Box.gltf", - } - - @staticmethod - def update( - value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - camera_position: tuple[ - int | float | None, int | float | None, int | float | None - ] - | None = None, - clear_color: tuple[float, float, float, float] | None = None, - height: int | None = None, - zoom_speed: float | None = None, - label: str | None = None, - show_label: bool | None = None, - container: bool | None = None, - scale: int | None = None, - min_width: int | None = None, - visible: bool | None = None, - ): - warnings.warn( - "Using the update method is deprecated. Simply return a new object instead, e.g. `return gr.Model3D(...)` instead of `return gr.Model3D.update(...)`." - ) - updated_config = { - "camera_position": camera_position, - "clear_color": clear_color, - "height": height, - "zoom_speed": zoom_speed, - "label": label, - "show_label": show_label, - "container": container, - "scale": scale, - "min_width": min_width, - "visible": visible, - "value": value, - "__type__": "update", - } - return updated_config - - def preprocess(self, x: dict[str, str] | None) -> str | None: - """ - Parameters: - x: JSON object with filename as 'name' property and base64 data as 'data' property - Returns: - string file path to temporary file with the 3D image model - """ - if x is None: - return x - file_name, file_data, is_file = ( - x["name"], - x["data"], - x.get("is_file", False), - ) - if is_file: - temp_file_path = self.make_temp_copy_if_needed(file_name) - else: - temp_file_path = self.base64_to_temp_file_if_needed(file_data, file_name) - - return temp_file_path - - def postprocess(self, y: str | Path | None) -> dict[str, str] | None: - """ - Parameters: - y: path to the model - Returns: - file name mapped to base64 url data - """ - if y is None: - return y - data = { - "name": self.make_temp_copy_if_needed(y), - "data": None, - "is_file": True, - } - return data - - def as_example(self, input_data: str | None) -> str: - return Path(input_data).name if input_data else "" diff --git a/spaces/jordonpeter01/MusicGen/audiocraft/modules/__init__.py b/spaces/jordonpeter01/MusicGen/audiocraft/modules/__init__.py deleted file mode 100644 index 81ba30f6466ff91b90490a4fb92f7d3d0d00144d..0000000000000000000000000000000000000000 --- a/spaces/jordonpeter01/MusicGen/audiocraft/modules/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -# flake8: noqa -from .conv import ( - NormConv1d, - NormConv2d, - NormConvTranspose1d, - NormConvTranspose2d, - StreamableConv1d, - StreamableConvTranspose1d, - pad_for_conv1d, - pad1d, - unpad1d, -) -from .lstm import StreamableLSTM -from .seanet import SEANetEncoder, SEANetDecoder diff --git a/spaces/joshen/gpt-academic/crazy_functions/test_project/python/dqn/policies.py b/spaces/joshen/gpt-academic/crazy_functions/test_project/python/dqn/policies.py deleted file mode 100644 index 4ecf39a5fc04b24ad1b809232b186728366987b6..0000000000000000000000000000000000000000 --- a/spaces/joshen/gpt-academic/crazy_functions/test_project/python/dqn/policies.py +++ /dev/null @@ -1,237 +0,0 @@ -from typing import Any, Dict, List, Optional, Type - -import gym -import torch as th -from torch import nn - -from stable_baselines3.common.policies import BasePolicy, register_policy -from stable_baselines3.common.torch_layers import BaseFeaturesExtractor, FlattenExtractor, NatureCNN, create_mlp -from stable_baselines3.common.type_aliases import Schedule - - -class QNetwork(BasePolicy): - """ - Action-Value (Q-Value) network for DQN - - :param observation_space: Observation space - :param action_space: Action space - :param net_arch: The specification of the policy and value networks. - :param activation_fn: Activation function - :param normalize_images: Whether to normalize images or not, - dividing by 255.0 (True by default) - """ - - def __init__( - self, - observation_space: gym.spaces.Space, - action_space: gym.spaces.Space, - features_extractor: nn.Module, - features_dim: int, - net_arch: Optional[List[int]] = None, - activation_fn: Type[nn.Module] = nn.ReLU, - normalize_images: bool = True, - ): - super(QNetwork, self).__init__( - observation_space, - action_space, - features_extractor=features_extractor, - normalize_images=normalize_images, - ) - - if net_arch is None: - net_arch = [64, 64] - - self.net_arch = net_arch - self.activation_fn = activation_fn - self.features_extractor = features_extractor - self.features_dim = features_dim - self.normalize_images = normalize_images - action_dim = self.action_space.n # number of actions - q_net = create_mlp(self.features_dim, action_dim, self.net_arch, self.activation_fn) - self.q_net = nn.Sequential(*q_net) - - def forward(self, obs: th.Tensor) -> th.Tensor: - """ - Predict the q-values. - - :param obs: Observation - :return: The estimated Q-Value for each action. - """ - return self.q_net(self.extract_features(obs)) - - def _predict(self, observation: th.Tensor, deterministic: bool = True) -> th.Tensor: - q_values = self.forward(observation) - # Greedy action - action = q_values.argmax(dim=1).reshape(-1) - return action - - def _get_constructor_parameters(self) -> Dict[str, Any]: - data = super()._get_constructor_parameters() - - data.update( - dict( - net_arch=self.net_arch, - features_dim=self.features_dim, - activation_fn=self.activation_fn, - features_extractor=self.features_extractor, - ) - ) - return data - - -class DQNPolicy(BasePolicy): - """ - Policy class with Q-Value Net and target net for DQN - - :param observation_space: Observation space - :param action_space: Action space - :param lr_schedule: Learning rate schedule (could be constant) - :param net_arch: The specification of the policy and value networks. - :param activation_fn: Activation function - :param features_extractor_class: Features extractor to use. - :param features_extractor_kwargs: Keyword arguments - to pass to the features extractor. - :param normalize_images: Whether to normalize images or not, - dividing by 255.0 (True by default) - :param optimizer_class: The optimizer to use, - ``th.optim.Adam`` by default - :param optimizer_kwargs: Additional keyword arguments, - excluding the learning rate, to pass to the optimizer - """ - - def __init__( - self, - observation_space: gym.spaces.Space, - action_space: gym.spaces.Space, - lr_schedule: Schedule, - net_arch: Optional[List[int]] = None, - activation_fn: Type[nn.Module] = nn.ReLU, - features_extractor_class: Type[BaseFeaturesExtractor] = FlattenExtractor, - features_extractor_kwargs: Optional[Dict[str, Any]] = None, - normalize_images: bool = True, - optimizer_class: Type[th.optim.Optimizer] = th.optim.Adam, - optimizer_kwargs: Optional[Dict[str, Any]] = None, - ): - super(DQNPolicy, self).__init__( - observation_space, - action_space, - features_extractor_class, - features_extractor_kwargs, - optimizer_class=optimizer_class, - optimizer_kwargs=optimizer_kwargs, - ) - - if net_arch is None: - if features_extractor_class == FlattenExtractor: - net_arch = [64, 64] - else: - net_arch = [] - - self.net_arch = net_arch - self.activation_fn = activation_fn - self.normalize_images = normalize_images - - self.net_args = { - "observation_space": self.observation_space, - "action_space": self.action_space, - "net_arch": self.net_arch, - "activation_fn": self.activation_fn, - "normalize_images": normalize_images, - } - - self.q_net, self.q_net_target = None, None - self._build(lr_schedule) - - def _build(self, lr_schedule: Schedule) -> None: - """ - Create the network and the optimizer. - - :param lr_schedule: Learning rate schedule - lr_schedule(1) is the initial learning rate - """ - - self.q_net = self.make_q_net() - self.q_net_target = self.make_q_net() - self.q_net_target.load_state_dict(self.q_net.state_dict()) - - # Setup optimizer with initial learning rate - self.optimizer = self.optimizer_class(self.parameters(), lr=lr_schedule(1), **self.optimizer_kwargs) - - def make_q_net(self) -> QNetwork: - # Make sure we always have separate networks for features extractors etc - net_args = self._update_features_extractor(self.net_args, features_extractor=None) - return QNetwork(**net_args).to(self.device) - - def forward(self, obs: th.Tensor, deterministic: bool = True) -> th.Tensor: - return self._predict(obs, deterministic=deterministic) - - def _predict(self, obs: th.Tensor, deterministic: bool = True) -> th.Tensor: - return self.q_net._predict(obs, deterministic=deterministic) - - def _get_constructor_parameters(self) -> Dict[str, Any]: - data = super()._get_constructor_parameters() - - data.update( - dict( - net_arch=self.net_args["net_arch"], - activation_fn=self.net_args["activation_fn"], - lr_schedule=self._dummy_schedule, # dummy lr schedule, not needed for loading policy alone - optimizer_class=self.optimizer_class, - optimizer_kwargs=self.optimizer_kwargs, - features_extractor_class=self.features_extractor_class, - features_extractor_kwargs=self.features_extractor_kwargs, - ) - ) - return data - - -MlpPolicy = DQNPolicy - - -class CnnPolicy(DQNPolicy): - """ - Policy class for DQN when using images as input. - - :param observation_space: Observation space - :param action_space: Action space - :param lr_schedule: Learning rate schedule (could be constant) - :param net_arch: The specification of the policy and value networks. - :param activation_fn: Activation function - :param features_extractor_class: Features extractor to use. - :param normalize_images: Whether to normalize images or not, - dividing by 255.0 (True by default) - :param optimizer_class: The optimizer to use, - ``th.optim.Adam`` by default - :param optimizer_kwargs: Additional keyword arguments, - excluding the learning rate, to pass to the optimizer - """ - - def __init__( - self, - observation_space: gym.spaces.Space, - action_space: gym.spaces.Space, - lr_schedule: Schedule, - net_arch: Optional[List[int]] = None, - activation_fn: Type[nn.Module] = nn.ReLU, - features_extractor_class: Type[BaseFeaturesExtractor] = NatureCNN, - features_extractor_kwargs: Optional[Dict[str, Any]] = None, - normalize_images: bool = True, - optimizer_class: Type[th.optim.Optimizer] = th.optim.Adam, - optimizer_kwargs: Optional[Dict[str, Any]] = None, - ): - super(CnnPolicy, self).__init__( - observation_space, - action_space, - lr_schedule, - net_arch, - activation_fn, - features_extractor_class, - features_extractor_kwargs, - normalize_images, - optimizer_class, - optimizer_kwargs, - ) - - -register_policy("MlpPolicy", MlpPolicy) -register_policy("CnnPolicy", CnnPolicy) diff --git a/spaces/juancopi81/whisper-youtube-2-hf_dataset/transforming/whispertransform.py b/spaces/juancopi81/whisper-youtube-2-hf_dataset/transforming/whispertransform.py deleted file mode 100644 index bdd7de76d86c32be14d6455aae66fe62683b3311..0000000000000000000000000000000000000000 --- a/spaces/juancopi81/whisper-youtube-2-hf_dataset/transforming/whispertransform.py +++ /dev/null @@ -1,66 +0,0 @@ -import os -from pathlib import Path -from typing import Any -from collections import OrderedDict - -from pytube import YouTube -import whisper - -from transforming.transform import Transform -from video import YoutubeVideo -from utils import accepts_types - -class WhisperTransform(Transform): - """ - Transform a Video object using Whisper model. It's a - concrete Transform. - Args: - model (`str`): - Size of Whisper model. Can be tiny, base (default), small, medium, and large. - without_timestamps (`bool`, defaults to `False`): - To add phrase-level timestamps. - """ - - def __init__(self, model: str="base", without_timestamps: bool=False) -> None: - self.model = whisper.load_model(model) - self.without_timestamps = without_timestamps - - @accepts_types(YoutubeVideo) - def apply(self, video: YoutubeVideo) -> YoutubeVideo: - """Creates a new video with transcriptions created by Whisper. - """ - # Create a YouTube object - yt = YouTube(video.url) - print(f"Video title and url: {video.title} {video.url}") - - audio_file = self._get_audio_from_video(yt) - result = self.model.transcribe(audio_file, - without_timestamps=self.without_timestamps) - transcription = result["text"] - - data = [] - for seg in result['segments']: - data.append(OrderedDict({'start': seg['start'], 'end': seg['end'],'text': seg['text']})) - - os.remove(audio_file) - - return YoutubeVideo(channel_name = video.channel_name, - url = video.url, - title = video.title, - description = video.description, - transcription = transcription, - segments = data) - - def _get_audio_from_video(self, yt: Any) -> Path: - # TODO: Add credits - try: - video = yt.streams.filter(only_audio=True).first() - except Exception as e: - print(f"StreamingData exception print: {e}") - pass - else: - out_file = video.download(output_path=".") - base, _ = os.path.splitext(out_file) - new_file = base + ".mp3" - os.rename(out_file, new_file) - return new_file \ No newline at end of file diff --git a/spaces/justest/gpt4free/g4f/.v1/gui/query_methods.py b/spaces/justest/gpt4free/g4f/.v1/gui/query_methods.py deleted file mode 100644 index 2d6adacd3b394183c65ab596cc148c45de6b63c4..0000000000000000000000000000000000000000 --- a/spaces/justest/gpt4free/g4f/.v1/gui/query_methods.py +++ /dev/null @@ -1,100 +0,0 @@ -import os -import sys -from typing import Optional - -sys.path.append(os.path.join(os.path.dirname(__file__), os.path.pardir)) - -from gpt4free import quora, forefront, theb, you -import random - - -def query_forefront(question: str, proxy: Optional[str] = None) -> str: - # create an account - token = forefront.Account.create(logging=False, proxy=proxy) - - response = "" - # get a response - try: - return forefront.Completion.create(token=token, prompt='hello world', model='gpt-4', proxy=proxy).text - except Exception as e: - # Return error message if an exception occurs - return ( - f'An error occurred: {e}. Please make sure you are using a valid cloudflare clearance token and user agent.' - ) - - -def query_quora(question: str, proxy: Optional[str] = None) -> str: - token = quora.Account.create(logging=False, enable_bot_creation=True, proxy=proxy) - return quora.Completion.create(model='gpt-4', prompt=question, token=token, proxy=proxy).text - - -def query_theb(question: str, proxy: Optional[str] = None) -> str: - # Set cloudflare clearance cookie and get answer from GPT-4 model - response = "" - try: - return ''.join(theb.Completion.create(prompt=question, proxy=proxy)) - - except Exception as e: - # Return error message if an exception occurs - return ( - f'An error occurred: {e}. Please make sure you are using a valid cloudflare clearance token and user agent.' - ) - - -def query_you(question: str, proxy: Optional[str] = None) -> str: - # Set cloudflare clearance cookie and get answer from GPT-4 model - try: - result = you.Completion.create(prompt=question, proxy=proxy) - return result.text - - except Exception as e: - # Return error message if an exception occurs - return ( - f'An error occurred: {e}. Please make sure you are using a valid cloudflare clearance token and user agent.' - ) - - -# Define a dictionary containing all query methods -avail_query_methods = { - "Forefront": query_forefront, - "Poe": query_quora, - "Theb": query_theb, - "You": query_you, - # "Writesonic": query_writesonic, - # "T3nsor": query_t3nsor, - # "Phind": query_phind, - # "Ora": query_ora, -} - - -def query(user_input: str, selected_method: str = "Random", proxy: Optional[str] = None) -> str: - # If a specific query method is selected (not "Random") and the method is in the dictionary, try to call it - if selected_method != "Random" and selected_method in avail_query_methods: - try: - return avail_query_methods[selected_method](user_input, proxy=proxy) - except Exception as e: - print(f"Error with {selected_method}: {e}") - return "😵 Sorry, some error occurred please try again." - - # Initialize variables for determining success and storing the result - success = False - result = "😵 Sorry, some error occurred please try again." - # Create a list of available query methods - query_methods_list = list(avail_query_methods.values()) - - # Continue trying different methods until a successful result is obtained or all methods have been tried - while not success and query_methods_list: - # Choose a random method from the list - chosen_query = random.choice(query_methods_list) - # Find the name of the chosen method - chosen_query_name = [k for k, v in avail_query_methods.items() if v == chosen_query][0] - try: - # Try to call the chosen method with the user input - result = chosen_query(user_input, proxy=proxy) - success = True - except Exception as e: - print(f"Error with {chosen_query_name}: {e}") - # Remove the failed method from the list of available methods - query_methods_list.remove(chosen_query) - - return result diff --git a/spaces/k1ngtai/MMS/vits/__init__.py b/spaces/k1ngtai/MMS/vits/__init__.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/spaces/k1ngtai/MMS/vits/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/spaces/kevinwang676/ChatGLM2-VC-SadTalker/modules.py b/spaces/kevinwang676/ChatGLM2-VC-SadTalker/modules.py deleted file mode 100644 index 52ee14e41a5b6d67d875d1b694aecd2a51244897..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/ChatGLM2-VC-SadTalker/modules.py +++ /dev/null @@ -1,342 +0,0 @@ -import copy -import math -import numpy as np -import scipy -import torch -from torch import nn -from torch.nn import functional as F - -from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d -from torch.nn.utils import weight_norm, remove_weight_norm - -import commons -from commons import init_weights, get_padding - - -LRELU_SLOPE = 0.1 - - -class LayerNorm(nn.Module): - def __init__(self, channels, eps=1e-5): - super().__init__() - self.channels = channels - self.eps = eps - - self.gamma = nn.Parameter(torch.ones(channels)) - self.beta = nn.Parameter(torch.zeros(channels)) - - def forward(self, x): - x = x.transpose(1, -1) - x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps) - return x.transpose(1, -1) - - -class ConvReluNorm(nn.Module): - def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout): - super().__init__() - self.in_channels = in_channels - self.hidden_channels = hidden_channels - self.out_channels = out_channels - self.kernel_size = kernel_size - self.n_layers = n_layers - self.p_dropout = p_dropout - assert n_layers > 1, "Number of layers should be larger than 0." - - self.conv_layers = nn.ModuleList() - self.norm_layers = nn.ModuleList() - self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2)) - self.norm_layers.append(LayerNorm(hidden_channels)) - self.relu_drop = nn.Sequential( - nn.ReLU(), - nn.Dropout(p_dropout)) - for _ in range(n_layers-1): - self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2)) - self.norm_layers.append(LayerNorm(hidden_channels)) - self.proj = nn.Conv1d(hidden_channels, out_channels, 1) - self.proj.weight.data.zero_() - self.proj.bias.data.zero_() - - def forward(self, x, x_mask): - x_org = x - for i in range(self.n_layers): - x = self.conv_layers[i](x * x_mask) - x = self.norm_layers[i](x) - x = self.relu_drop(x) - x = x_org + self.proj(x) - return x * x_mask - - -class DDSConv(nn.Module): - """ - Dialted and Depth-Separable Convolution - """ - def __init__(self, channels, kernel_size, n_layers, p_dropout=0.): - super().__init__() - self.channels = channels - self.kernel_size = kernel_size - self.n_layers = n_layers - self.p_dropout = p_dropout - - self.drop = nn.Dropout(p_dropout) - self.convs_sep = nn.ModuleList() - self.convs_1x1 = nn.ModuleList() - self.norms_1 = nn.ModuleList() - self.norms_2 = nn.ModuleList() - for i in range(n_layers): - dilation = kernel_size ** i - padding = (kernel_size * dilation - dilation) // 2 - self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size, - groups=channels, dilation=dilation, padding=padding - )) - self.convs_1x1.append(nn.Conv1d(channels, channels, 1)) - self.norms_1.append(LayerNorm(channels)) - self.norms_2.append(LayerNorm(channels)) - - def forward(self, x, x_mask, g=None): - if g is not None: - x = x + g - for i in range(self.n_layers): - y = self.convs_sep[i](x * x_mask) - y = self.norms_1[i](y) - y = F.gelu(y) - y = self.convs_1x1[i](y) - y = self.norms_2[i](y) - y = F.gelu(y) - y = self.drop(y) - x = x + y - return x * x_mask - - -class WN(torch.nn.Module): - def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0): - super(WN, self).__init__() - assert(kernel_size % 2 == 1) - self.hidden_channels =hidden_channels - self.kernel_size = kernel_size, - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.gin_channels = gin_channels - self.p_dropout = p_dropout - - self.in_layers = torch.nn.ModuleList() - self.res_skip_layers = torch.nn.ModuleList() - self.drop = nn.Dropout(p_dropout) - - if gin_channels != 0: - cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1) - self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight') - - for i in range(n_layers): - dilation = dilation_rate ** i - padding = int((kernel_size * dilation - dilation) / 2) - in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size, - dilation=dilation, padding=padding) - in_layer = torch.nn.utils.weight_norm(in_layer, name='weight') - self.in_layers.append(in_layer) - - # last one is not necessary - if i < n_layers - 1: - res_skip_channels = 2 * hidden_channels - else: - res_skip_channels = hidden_channels - - res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1) - res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight') - self.res_skip_layers.append(res_skip_layer) - - def forward(self, x, x_mask, g=None, **kwargs): - output = torch.zeros_like(x) - n_channels_tensor = torch.IntTensor([self.hidden_channels]) - - if g is not None: - g = self.cond_layer(g) - - for i in range(self.n_layers): - x_in = self.in_layers[i](x) - if g is not None: - cond_offset = i * 2 * self.hidden_channels - g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:] - else: - g_l = torch.zeros_like(x_in) - - acts = commons.fused_add_tanh_sigmoid_multiply( - x_in, - g_l, - n_channels_tensor) - acts = self.drop(acts) - - res_skip_acts = self.res_skip_layers[i](acts) - if i < self.n_layers - 1: - res_acts = res_skip_acts[:,:self.hidden_channels,:] - x = (x + res_acts) * x_mask - output = output + res_skip_acts[:,self.hidden_channels:,:] - else: - output = output + res_skip_acts - return output * x_mask - - def remove_weight_norm(self): - if self.gin_channels != 0: - torch.nn.utils.remove_weight_norm(self.cond_layer) - for l in self.in_layers: - torch.nn.utils.remove_weight_norm(l) - for l in self.res_skip_layers: - torch.nn.utils.remove_weight_norm(l) - - -class ResBlock1(torch.nn.Module): - def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)): - super(ResBlock1, self).__init__() - self.convs1 = nn.ModuleList([ - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0], - padding=get_padding(kernel_size, dilation[0]))), - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1], - padding=get_padding(kernel_size, dilation[1]))), - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2], - padding=get_padding(kernel_size, dilation[2]))) - ]) - self.convs1.apply(init_weights) - - self.convs2 = nn.ModuleList([ - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1, - padding=get_padding(kernel_size, 1))), - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1, - padding=get_padding(kernel_size, 1))), - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1, - padding=get_padding(kernel_size, 1))) - ]) - self.convs2.apply(init_weights) - - def forward(self, x, x_mask=None): - for c1, c2 in zip(self.convs1, self.convs2): - xt = F.leaky_relu(x, LRELU_SLOPE) - if x_mask is not None: - xt = xt * x_mask - xt = c1(xt) - xt = F.leaky_relu(xt, LRELU_SLOPE) - if x_mask is not None: - xt = xt * x_mask - xt = c2(xt) - x = xt + x - if x_mask is not None: - x = x * x_mask - return x - - def remove_weight_norm(self): - for l in self.convs1: - remove_weight_norm(l) - for l in self.convs2: - remove_weight_norm(l) - - -class ResBlock2(torch.nn.Module): - def __init__(self, channels, kernel_size=3, dilation=(1, 3)): - super(ResBlock2, self).__init__() - self.convs = nn.ModuleList([ - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0], - padding=get_padding(kernel_size, dilation[0]))), - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1], - padding=get_padding(kernel_size, dilation[1]))) - ]) - self.convs.apply(init_weights) - - def forward(self, x, x_mask=None): - for c in self.convs: - xt = F.leaky_relu(x, LRELU_SLOPE) - if x_mask is not None: - xt = xt * x_mask - xt = c(xt) - x = xt + x - if x_mask is not None: - x = x * x_mask - return x - - def remove_weight_norm(self): - for l in self.convs: - remove_weight_norm(l) - - -class Log(nn.Module): - def forward(self, x, x_mask, reverse=False, **kwargs): - if not reverse: - y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask - logdet = torch.sum(-y, [1, 2]) - return y, logdet - else: - x = torch.exp(x) * x_mask - return x - - -class Flip(nn.Module): - def forward(self, x, *args, reverse=False, **kwargs): - x = torch.flip(x, [1]) - if not reverse: - logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device) - return x, logdet - else: - return x - - -class ElementwiseAffine(nn.Module): - def __init__(self, channels): - super().__init__() - self.channels = channels - self.m = nn.Parameter(torch.zeros(channels,1)) - self.logs = nn.Parameter(torch.zeros(channels,1)) - - def forward(self, x, x_mask, reverse=False, **kwargs): - if not reverse: - y = self.m + torch.exp(self.logs) * x - y = y * x_mask - logdet = torch.sum(self.logs * x_mask, [1,2]) - return y, logdet - else: - x = (x - self.m) * torch.exp(-self.logs) * x_mask - return x - - -class ResidualCouplingLayer(nn.Module): - def __init__(self, - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - p_dropout=0, - gin_channels=0, - mean_only=False): - assert channels % 2 == 0, "channels should be divisible by 2" - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.half_channels = channels // 2 - self.mean_only = mean_only - - self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1) - self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels) - self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1) - self.post.weight.data.zero_() - self.post.bias.data.zero_() - - def forward(self, x, x_mask, g=None, reverse=False): - x0, x1 = torch.split(x, [self.half_channels]*2, 1) - h = self.pre(x0) * x_mask - h = self.enc(h, x_mask, g=g) - stats = self.post(h) * x_mask - if not self.mean_only: - m, logs = torch.split(stats, [self.half_channels]*2, 1) - else: - m = stats - logs = torch.zeros_like(m) - - if not reverse: - x1 = m + x1 * torch.exp(logs) * x_mask - x = torch.cat([x0, x1], 1) - logdet = torch.sum(logs, [1,2]) - return x, logdet - else: - x1 = (x1 - m) * torch.exp(-logs) * x_mask - x = torch.cat([x0, x1], 1) - return x diff --git a/spaces/kevinwang676/ChatGLM2-VC-SadTalker/src/audio2pose_models/discriminator.py b/spaces/kevinwang676/ChatGLM2-VC-SadTalker/src/audio2pose_models/discriminator.py deleted file mode 100644 index 339c38e4812ff38a810f0f3a1c01812f6d5d78db..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/ChatGLM2-VC-SadTalker/src/audio2pose_models/discriminator.py +++ /dev/null @@ -1,76 +0,0 @@ -import torch -import torch.nn.functional as F -from torch import nn - -class ConvNormRelu(nn.Module): - def __init__(self, conv_type='1d', in_channels=3, out_channels=64, downsample=False, - kernel_size=None, stride=None, padding=None, norm='BN', leaky=False): - super().__init__() - if kernel_size is None: - if downsample: - kernel_size, stride, padding = 4, 2, 1 - else: - kernel_size, stride, padding = 3, 1, 1 - - if conv_type == '2d': - self.conv = nn.Conv2d( - in_channels, - out_channels, - kernel_size, - stride, - padding, - bias=False, - ) - if norm == 'BN': - self.norm = nn.BatchNorm2d(out_channels) - elif norm == 'IN': - self.norm = nn.InstanceNorm2d(out_channels) - else: - raise NotImplementedError - elif conv_type == '1d': - self.conv = nn.Conv1d( - in_channels, - out_channels, - kernel_size, - stride, - padding, - bias=False, - ) - if norm == 'BN': - self.norm = nn.BatchNorm1d(out_channels) - elif norm == 'IN': - self.norm = nn.InstanceNorm1d(out_channels) - else: - raise NotImplementedError - nn.init.kaiming_normal_(self.conv.weight) - - self.act = nn.LeakyReLU(negative_slope=0.2, inplace=False) if leaky else nn.ReLU(inplace=True) - - def forward(self, x): - x = self.conv(x) - if isinstance(self.norm, nn.InstanceNorm1d): - x = self.norm(x.permute((0, 2, 1))).permute((0, 2, 1)) # normalize on [C] - else: - x = self.norm(x) - x = self.act(x) - return x - - -class PoseSequenceDiscriminator(nn.Module): - def __init__(self, cfg): - super().__init__() - self.cfg = cfg - leaky = self.cfg.MODEL.DISCRIMINATOR.LEAKY_RELU - - self.seq = nn.Sequential( - ConvNormRelu('1d', cfg.MODEL.DISCRIMINATOR.INPUT_CHANNELS, 256, downsample=True, leaky=leaky), # B, 256, 64 - ConvNormRelu('1d', 256, 512, downsample=True, leaky=leaky), # B, 512, 32 - ConvNormRelu('1d', 512, 1024, kernel_size=3, stride=1, padding=1, leaky=leaky), # B, 1024, 16 - nn.Conv1d(1024, 1, kernel_size=3, stride=1, padding=1, bias=True) # B, 1, 16 - ) - - def forward(self, x): - x = x.reshape(x.size(0), x.size(1), -1).transpose(1, 2) - x = self.seq(x) - x = x.squeeze(1) - return x \ No newline at end of file diff --git a/spaces/kevinwang676/ChatGLM2-VC-SadTalker/src/face3d/models/arcface_torch/configs/ms1mv3_r34.py b/spaces/kevinwang676/ChatGLM2-VC-SadTalker/src/face3d/models/arcface_torch/configs/ms1mv3_r34.py deleted file mode 100644 index 5f78337a3d1f9eb6e9145eb5093618796c6842d2..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/ChatGLM2-VC-SadTalker/src/face3d/models/arcface_torch/configs/ms1mv3_r34.py +++ /dev/null @@ -1,26 +0,0 @@ -from easydict import EasyDict as edict - -# make training faster -# our RAM is 256G -# mount -t tmpfs -o size=140G tmpfs /train_tmp - -config = edict() -config.loss = "arcface" -config.network = "r34" -config.resume = False -config.output = None -config.embedding_size = 512 -config.sample_rate = 1.0 -config.fp16 = True -config.momentum = 0.9 -config.weight_decay = 5e-4 -config.batch_size = 128 -config.lr = 0.1 # batch size is 512 - -config.rec = "/train_tmp/ms1m-retinaface-t1" -config.num_classes = 93431 -config.num_image = 5179510 -config.num_epoch = 25 -config.warmup_epoch = -1 -config.decay_epoch = [10, 16, 22] -config.val_targets = ["lfw", "cfp_fp", "agedb_30"] diff --git a/spaces/kevinwang676/VoiceChangers/src/facerender/sync_batchnorm/__init__.py b/spaces/kevinwang676/VoiceChangers/src/facerender/sync_batchnorm/__init__.py deleted file mode 100644 index bc8709d92c610b36e0bcbd7da20c1eb41dc8cfcf..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/VoiceChangers/src/facerender/sync_batchnorm/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -# -*- coding: utf-8 -*- -# File : __init__.py -# Author : Jiayuan Mao -# Email : maojiayuan@gmail.com -# Date : 27/01/2018 -# -# This file is part of Synchronized-BatchNorm-PyTorch. -# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch -# Distributed under MIT License. - -from .batchnorm import SynchronizedBatchNorm1d, SynchronizedBatchNorm2d, SynchronizedBatchNorm3d -from .replicate import DataParallelWithCallback, patch_replication_callback diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/attr/_compat.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/attr/_compat.py deleted file mode 100644 index c3bf5e33ba4f9eeff3e41d9516fd847ecea4deb8..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/attr/_compat.py +++ /dev/null @@ -1,185 +0,0 @@ -# SPDX-License-Identifier: MIT - - -import inspect -import platform -import sys -import threading -import types -import warnings - -from collections.abc import Mapping, Sequence # noqa -from typing import _GenericAlias - - -PYPY = platform.python_implementation() == "PyPy" -PY_3_9_PLUS = sys.version_info[:2] >= (3, 9) -PY310 = sys.version_info[:2] >= (3, 10) -PY_3_12_PLUS = sys.version_info[:2] >= (3, 12) - - -def just_warn(*args, **kw): - warnings.warn( - "Running interpreter doesn't sufficiently support code object " - "introspection. Some features like bare super() or accessing " - "__class__ will not work with slotted classes.", - RuntimeWarning, - stacklevel=2, - ) - - -class _AnnotationExtractor: - """ - Extract type annotations from a callable, returning None whenever there - is none. - """ - - __slots__ = ["sig"] - - def __init__(self, callable): - try: - self.sig = inspect.signature(callable) - except (ValueError, TypeError): # inspect failed - self.sig = None - - def get_first_param_type(self): - """ - Return the type annotation of the first argument if it's not empty. - """ - if not self.sig: - return None - - params = list(self.sig.parameters.values()) - if params and params[0].annotation is not inspect.Parameter.empty: - return params[0].annotation - - return None - - def get_return_type(self): - """ - Return the return type if it's not empty. - """ - if ( - self.sig - and self.sig.return_annotation is not inspect.Signature.empty - ): - return self.sig.return_annotation - - return None - - -def make_set_closure_cell(): - """Return a function of two arguments (cell, value) which sets - the value stored in the closure cell `cell` to `value`. - """ - # pypy makes this easy. (It also supports the logic below, but - # why not do the easy/fast thing?) - if PYPY: - - def set_closure_cell(cell, value): - cell.__setstate__((value,)) - - return set_closure_cell - - # Otherwise gotta do it the hard way. - - try: - if sys.version_info >= (3, 8): - - def set_closure_cell(cell, value): - cell.cell_contents = value - - else: - # Create a function that will set its first cellvar to `value`. - def set_first_cellvar_to(value): - x = value - return - - # This function will be eliminated as dead code, but - # not before its reference to `x` forces `x` to be - # represented as a closure cell rather than a local. - def force_x_to_be_a_cell(): # pragma: no cover - return x - - # Extract the code object and make sure our assumptions about - # the closure behavior are correct. - co = set_first_cellvar_to.__code__ - if co.co_cellvars != ("x",) or co.co_freevars != (): - raise AssertionError # pragma: no cover - - # Convert this code object to a code object that sets the - # function's first _freevar_ (not cellvar) to the argument. - args = [co.co_argcount] - args.append(co.co_kwonlyargcount) - args.extend( - [ - co.co_nlocals, - co.co_stacksize, - co.co_flags, - co.co_code, - co.co_consts, - co.co_names, - co.co_varnames, - co.co_filename, - co.co_name, - co.co_firstlineno, - co.co_lnotab, - # These two arguments are reversed: - co.co_cellvars, - co.co_freevars, - ] - ) - set_first_freevar_code = types.CodeType(*args) - - def set_closure_cell(cell, value): - # Create a function using the set_first_freevar_code, - # whose first closure cell is `cell`. Calling it will - # change the value of that cell. - setter = types.FunctionType( - set_first_freevar_code, {}, "setter", (), (cell,) - ) - # And call it to set the cell. - setter(value) - - # Make sure it works on this interpreter: - def make_func_with_cell(): - x = None - - def func(): - return x # pragma: no cover - - return func - - cell = make_func_with_cell().__closure__[0] - set_closure_cell(cell, 100) - if cell.cell_contents != 100: - raise AssertionError # pragma: no cover - - except Exception: - return just_warn - else: - return set_closure_cell - - -set_closure_cell = make_set_closure_cell() - -# Thread-local global to track attrs instances which are already being repr'd. -# This is needed because there is no other (thread-safe) way to pass info -# about the instances that are already being repr'd through the call stack -# in order to ensure we don't perform infinite recursion. -# -# For instance, if an instance contains a dict which contains that instance, -# we need to know that we're already repr'ing the outside instance from within -# the dict's repr() call. -# -# This lives here rather than in _make.py so that the functions in _make.py -# don't have a direct reference to the thread-local in their globals dict. -# If they have such a reference, it breaks cloudpickle. -repr_context = threading.local() - - -def get_generic_base(cl): - """If this is a generic class (A[str]), return the generic base for it.""" - if cl.__class__ is _GenericAlias: - return cl.__origin__ - return None diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/gradio/templates/frontend/assets/index-aa084753.js b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/gradio/templates/frontend/assets/index-aa084753.js deleted file mode 100644 index 6d8bb7bd4d54b9a4541e38ea7bd8a2197f51883a..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/gradio/templates/frontend/assets/index-aa084753.js +++ /dev/null @@ -1,13 +0,0 @@ -import{S as si,i as ri,s as oi,B as io,C as se,g as Ce,E as Yt,F as vi,q as Ae,_ as Pe,G as dt,r as Xl,u as Xc,b as xr,e as fe,H as pt,M as yn,m as ue,J as Zl,p as H,l as _n,t as j,o as Vn,n as de,a5 as Ql,aa as ea,ab as bn,ac as wn,f as ta,a8 as Zc,x as ia,$ as na,a as sa,h as ra,j as oa,k as la}from"./index-8c3da1d9.js";import"./Blocks-6ad6f005.js";import{B as aa}from"./Button-62634b34.js";import{B as ha}from"./BlockLabel-98ef75ee.js";import{E as Qc}from"./Empty-5d52e655.js";/* empty css */import{C as ef,a as ca}from"./Copy-fd383441.js";import{D as tf}from"./Download-dfb06e25.js";function nf(n){let e,t;return{c(){e=io("svg"),t=io("path"),se(t,"fill","currentColor"),se(t,"d","m31 16l-7 7l-1.41-1.41L28.17 16l-5.58-5.59L24 9l7 7zM1 16l7-7l1.41 1.41L3.83 16l5.58 5.59L8 23l-7-7zm11.42 9.484L17.64 6l1.932.517L14.352 26z"),se(e,"width","100%"),se(e,"height","100%"),se(e,"viewBox","0 0 32 32")},m(i,s){Ce(i,e,s),Yt(e,t)},p:vi,i:vi,o:vi,d(i){i&&Ae(e)}}}let Sr=class extends si{constructor(e){super(),ri(this,e,null,nf,oi,{})}};class _{constructor(){}lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){let s=[];return this.decompose(0,e,s,2),i.length&&i.decompose(0,i.length,s,3),this.decompose(t,this.length,s,1),$e.from(s,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){let i=[];return this.decompose(e,t,i,0),$e.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),s=new xi(this),r=new xi(e);for(let o=t,l=t;;){if(s.next(o),r.next(o),o=0,s.lineBreak!=r.lineBreak||s.done!=r.done||s.value!=r.value)return!1;if(l+=s.value.length,s.done||l>=i)return!0}}iter(e=1){return new xi(this,e)}iterRange(e,t=this.length){return new fa(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let s=this.line(e).from;i=this.iterRange(s,Math.max(s,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new ua(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new te(e):$e.from(te.split(e,[]))}}class te extends _{constructor(e,t=sf(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.text[r],l=s+o.length;if((t?i:l)>=e)return new rf(s,l,i,o);s=l+1,i++}}decompose(e,t,i,s){let r=e<=0&&t>=this.length?this:new te(no(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(s&1){let o=i.pop(),l=fn(r.text,o.text.slice(),0,r.length);if(l.length<=32)i.push(new te(l,o.length+r.length));else{let a=l.length>>1;i.push(new te(l.slice(0,a)),new te(l.slice(a)))}}else i.push(r)}replace(e,t,i){if(!(i instanceof te))return super.replace(e,t,i);let s=fn(this.text,fn(i.text,no(this.text,0,e)),t),r=this.length+i.length-(t-e);return s.length<=32?new te(s,r):$e.from(te.split(s,[]),r)}sliceString(e,t=this.length,i=` -`){let s="";for(let r=0,o=0;r<=t&&oe&&o&&(s+=i),er&&(s+=l.slice(Math.max(0,e-r),t-r)),r=a+1}return s}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],s=-1;for(let r of e)i.push(r),s+=r.length+1,i.length==32&&(t.push(new te(i,s)),i=[],s=-1);return s>-1&&t.push(new te(i,s)),t}}class $e extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.children[r],l=s+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,s);s=l+1,i=a+1}}decompose(e,t,i,s){for(let r=0,o=0;o<=t&&r=o){let h=s&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if(i.lines=r&&t<=l){let a=o.replace(e-r,t-r,i),h=this.lines-o.lines+a.lines;if(a.lines>5-1&&a.lines>h>>5+1){let c=this.children.slice();return c[s]=a,new $e(c,this.length-(t-e)+i.length)}return super.replace(r,l,a)}r=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` -`){let s="";for(let r=0,o=0;re&&r&&(s+=i),eo&&(s+=l.sliceString(e-o,t-o,i)),o=a+1}return s}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof $e))return 0;let i=0,[s,r,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;s+=t,r+=t){if(s==o||r==l)return i;let a=this.children[s],h=e.children[r];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,s)=>i+s.length+1,-1)){let i=0;for(let d of e)i+=d.lines;if(i<32){let d=[];for(let p of e)p.flatten(d);return new te(d,t)}let s=Math.max(32,i>>5),r=s<<1,o=s>>1,l=[],a=0,h=-1,c=[];function f(d){let p;if(d.lines>r&&d instanceof $e)for(let g of d.children)f(g);else d.lines>o&&(a>o||!a)?(u(),l.push(d)):d instanceof te&&a&&(p=c[c.length-1])instanceof te&&d.lines+p.lines<=32?(a+=d.lines,h+=d.length+1,c[c.length-1]=new te(p.text.concat(d.text),p.length+1+d.length)):(a+d.lines>s&&u(),a+=d.lines,h+=d.length+1,c.push(d))}function u(){a!=0&&(l.push(c.length==1?c[0]:$e.from(c,h)),h=-1,a=c.length=0)}for(let d of e)f(d);return u(),l.length==1?l[0]:new $e(l,t)}}_.empty=new te([""],0);function sf(n){let e=-1;for(let t of n)e+=t.length+1;return e}function fn(n,e,t=0,i=1e9){for(let s=0,r=0,o=!0;r=t&&(a>i&&(l=l.slice(0,i-s)),s0?1:(e instanceof te?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,s=this.nodes[i],r=this.offsets[i],o=r>>1,l=s instanceof te?s.text.length:s.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((r&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` -`,this;e--}else if(s instanceof te){let a=s.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=s.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof te?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class fa{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new xi(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:s}=this.cursor.next(e);return this.pos+=(s.length+e)*t,this.value=s.length<=i?s:t<0?s.slice(s.length-i):s.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class ua{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:s}=this.inner.next(e);return t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=s,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},xi.prototype[Symbol.iterator]=fa.prototype[Symbol.iterator]=ua.prototype[Symbol.iterator]=function(){return this});class rf{constructor(e,t,i,s){this.from=e,this.to=t,this.number=i,this.text=s}get length(){return this.to-this.from}}let Ut="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(n=>n?parseInt(n,36):1);for(let n=1;nn)return Ut[e-1]<=n;return!1}function so(n){return n>=127462&&n<=127487}const ro=8205;function Oe(n,e,t=!0,i=!0){return(t?da:lf)(n,e,i)}function da(n,e,t){if(e==n.length)return e;e&&pa(n.charCodeAt(e))&&ma(n.charCodeAt(e-1))&&e--;let i=ge(n,e);for(e+=Ee(i);e=0&&so(ge(n,o));)r++,o-=2;if(r%2==0)break;e+=2}else break}return e}function lf(n,e,t){for(;e>0;){let i=da(n,e-2,t);if(i=56320&&n<57344}function ma(n){return n>=55296&&n<56320}function ge(n,e){let t=n.charCodeAt(e);if(!ma(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return pa(i)?(t-55296<<10)+(i-56320)+65536:t}function ga(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ee(n){return n<65536?1:2}const Bs=/\r\n?|\n/;var ce=function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n}(ce||(ce={}));class Ze{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return r+(e-s);r+=l}else{if(i!=ce.Simple&&h>=e&&(i==ce.TrackDel&&se||i==ce.TrackBefore&&se))return null;if(h>e||h==e&&t<0&&!l)return e==s||t<0?r:r+a;r+=a}s=h}if(e>s)throw new RangeError(`Position ${e} is out of range for changeset of length ${s}`);return r}touchesRange(e,t=e){for(let i=0,s=0;i=0&&s<=t&&l>=e)return st?"cover":!0;s=l}return!1}toString(){let e="";for(let t=0;t=0?":"+s:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new Ze(e)}static create(e){return new Ze(e)}}class ne extends Ze{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ps(this,(t,i,s,r,o)=>e=e.replace(s,s+(i-t),o),!1),e}mapDesc(e,t=!1){return Es(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let s=0,r=0;s=0){t[s]=l,t[s+1]=o;let a=s>>1;for(;i.length0&&ht(i,t,r.text),r.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let s=[],r=[],o=0,l=null;function a(c=!1){if(!c&&!s.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let p=d?typeof d=="string"?_.of(d.split(i||Bs)):d:_.empty,g=p.length;if(f==u&&g==0)return;fo&&me(s,f-o,-1),me(s,u-f,g),ht(r,s,p),o=u}}return h(e),a(!l),l}static empty(e){return new ne(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let s=0;sl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(r.length==1)t.push(r[0],0);else{for(;i.length=0&&t<=0&&t==n[s+1]?n[s]+=e:e==0&&n[s]==0?n[s+1]+=t:i?(n[s]+=e,n[s+1]+=t):n.push(e,t)}function ht(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(s,h,r,c,f),s=h,r=c}}}function Es(n,e,t,i=!1){let s=[],r=i?[]:null,o=new Di(n),l=new Di(e);for(let a=-1;;)if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);me(s,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),r.forward2(a),o.forward(a)}}}}class Di{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class Mt{constructor(e,t,i){this.from=e,this.to=t,this.flags=i}get anchor(){return this.flags&16?this.to:this.from}get head(){return this.flags&16?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&4?-1:this.flags&8?1:0}get bidiLevel(){let e=this.flags&3;return e==3?null:e}get goalColumn(){let e=this.flags>>5;return e==33554431?void 0:e}map(e,t=-1){let i,s;return this.empty?i=s=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),s=e.mapPos(this.to,-1)),i==this.from&&s==this.to?this:new Mt(i,s,this.flags)}extend(e,t=e){if(e<=this.anchor&&t>=this.anchor)return w.range(e,t);let i=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return w.range(this.anchor,i)}eq(e){return this.anchor==e.anchor&&this.head==e.head}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return w.range(e.anchor,e.head)}static create(e,t,i){return new Mt(e,t,i)}}class w{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:w.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let t=0;te.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new w(e.ranges.map(t=>Mt.fromJSON(t)),e.main)}static single(e,t=e){return new w([w.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,s=0;se?4:0))}static normalized(e,t=0){let i=e[t];e.sort((s,r)=>s.from-r.from),t=e.indexOf(i);for(let s=1;sr.head?w.range(a,l):w.range(l,a))}}return new w(e,t)}}function ba(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Cr=0;class D{constructor(e,t,i,s,r){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=s,this.id=Cr++,this.default=e([]),this.extensions=typeof r=="function"?r(this):r}static define(e={}){return new D(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ar),!!e.static,e.enables)}of(e){return new un([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new un(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new un(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ar(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class un{constructor(e,t,i,s){this.dependencies=e,this.facet=t,this.type=i,this.value=s,this.id=Cr++}dynamicSlot(e){var t;let i=this.value,s=this.facet.compareInput,r=this.id,o=e[r]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:((t=e[f.id])!==null&&t!==void 0?t:1)&1||c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Rs(f,c)){let d=i(f);if(l?!oo(d,f.values[o],s):!s(d,f.values[o]))return f.values[o]=d,1}return 0},reconfigure:(f,u)=>{let d=i(f),p=u.config.address[r];if(p!=null){let g=vn(u,p);if(this.dependencies.every(y=>y instanceof D?u.facet(y)===f.facet(y):y instanceof Me?u.field(y,!1)==f.field(y,!1):!0)||(l?oo(d,g,s):s(d,g)))return f.values[o]=g,0}return f.values[o]=d,1}}}}function oo(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),s=t.map(a=>a.type),r=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===s),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(lo).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,s)=>{let r=i.values[t],o=this.updateF(r,s);return this.compareF(r,o)?0:(i.values[t]=o,1)},reconfigure:(i,s)=>s.config.address[this.id]!=null?(i.values[t]=s.field(this),0):(i.values[t]=this.create(i),1)}}init(e){return[this,lo.of({field:this,create:e})]}get extension(){return this}}const Ct={lowest:4,low:3,default:2,high:1,highest:0};function ci(n){return e=>new wa(e,n)}const Vi={highest:ci(Ct.highest),high:ci(Ct.high),default:ci(Ct.default),low:ci(Ct.low),lowest:ci(Ct.lowest)};class wa{constructor(e,t){this.inner=e,this.prec=t}}class Fn{of(e){return new Ls(this,e)}reconfigure(e){return Fn.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class Ls{constructor(e,t){this.compartment=e,this.inner=t}}class kn{constructor(e,t,i,s,r,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=s,this.staticValues=r,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let s=[],r=Object.create(null),o=new Map;for(let u of hf(e,t,o))u instanceof Me?s.push(u):(r[u.facet.id]||(r[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of s)l[u.id]=h.length<<1,h.push(d=>u.slot(d));let c=i?.config.facets;for(let u in r){let d=r[u],p=d[0].facet,g=c&&c[u]||[];if(d.every(y=>y.type==0))if(l[p.id]=a.length<<1|1,Ar(g,d))a.push(i.facet(p));else{let y=p.combine(d.map(b=>b.value));a.push(i&&p.compare(y,i.facet(p))?i.facet(p):y)}else{for(let y of d)y.type==0?(l[y.id]=a.length<<1|1,a.push(y.value)):(l[y.id]=h.length<<1,h.push(b=>y.dynamicSlot(b)));l[p.id]=h.length<<1,h.push(y=>af(y,p,d))}}let f=h.map(u=>u(l));return new kn(e,o,f,l,a,r)}}function hf(n,e,t){let i=[[],[],[],[],[]],s=new Map;function r(o,l){let a=s.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof Ls&&t.delete(o.compartment)}if(s.set(o,l),Array.isArray(o))for(let h of o)r(h,l);else if(o instanceof Ls){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),r(h,l)}else if(o instanceof wa)r(o.inner,o.prec);else if(o instanceof Me)i[l].push(o),o.provides&&r(o.provides,l);else if(o instanceof un)i[l].push(o),o.facet.extensions&&r(o.facet.extensions,Ct.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);r(h,l)}}return r(n,Ct.default),i.reduce((o,l)=>o.concat(l))}function Si(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let s=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|s}function vn(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const ka=D.define(),va=D.define({combine:n=>n.some(e=>e),static:!0}),xa=D.define({combine:n=>n.length?n[0]:void 0,static:!0}),Sa=D.define(),Ca=D.define(),Aa=D.define(),Ma=D.define({combine:n=>n.length?n[0]:!1});class Nt{constructor(e,t){this.type=e,this.value=t}static define(){return new cf}}class cf{of(e){return new Nt(this,e)}}class ff{constructor(e){this.map=e}of(e){return new R(this,e)}}class R{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new R(this.type,t)}is(e){return this.type==e}static define(e={}){return new ff(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let s of e){let r=s.map(t);r&&i.push(r)}return i}}R.reconfigure=R.define();R.appendConfig=R.define();class re{constructor(e,t,i,s,r,o){this.startState=e,this.changes=t,this.selection=i,this.effects=s,this.annotations=r,this.scrollIntoView=o,this._doc=null,this._state=null,i&&ba(i,t.newLength),r.some(l=>l.type==re.time)||(this.annotations=r.concat(re.time.of(Date.now())))}static create(e,t,i,s,r,o){return new re(e,t,i,s,r,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(re.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}re.time=Nt.define();re.userEvent=Nt.define();re.addToHistory=Nt.define();re.remote=Nt.define();function uf(n,e){let t=[];for(let i=0,s=0;;){let r,o;if(i=n[i]))r=n[i++],o=n[i++];else if(s=0;s--){let r=i[s](n);r instanceof re?n=r:Array.isArray(r)&&r.length==1&&r[0]instanceof re?n=r[0]:n=Ta(e,Gt(r),!1)}return n}function pf(n){let e=n.startState,t=e.facet(Aa),i=n;for(let s=t.length-1;s>=0;s--){let r=t[s](n);r&&Object.keys(r).length&&(i=Da(i,Is(e,r,n.changes.newLength),!0))}return i==n?n:re.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const mf=[];function Gt(n){return n==null?mf:Array.isArray(n)?n:[n]}var Re=function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n}(Re||(Re={}));const gf=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Ns;try{Ns=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function yf(n){if(Ns)return Ns.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||gf.test(t)))return!0}return!1}function bf(n){return e=>{if(!/\S/.test(e))return Re.Space;if(yf(e))return Re.Word;for(let t=0;t-1)return Re.Word;return Re.Other}}class N{constructor(e,t,i,s,r,o){this.config=e,this.doc=t,this.selection=i,this.values=s,this.status=e.statusTemplate.slice(),this.computeSlot=r,o&&(o._state=this);for(let l=0;ls.set(a,l)),t=null),s.set(o.value.compartment,o.value.extension)):o.is(R.reconfigure)?(t=null,i=o.value):o.is(R.appendConfig)&&(t=null,i=Gt(i).concat(o.value));let r;t?r=e.startState.values.slice():(t=kn.resolve(i,s,this),r=new N(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(l,a)=>a.reconfigure(l,this),null).values),new N(t,e.newDoc,e.newSelection,r,(o,l)=>l.update(o,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:w.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),s=this.changes(i.changes),r=[i.range],o=Gt(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return N.create({doc:e.doc,selection:w.fromJSON(e.selection),extensions:t.extensions?s.concat([t.extensions]):s})}static create(e={}){let t=kn.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(N.lineSeparator)||Bs)),s=e.selection?e.selection instanceof w?e.selection:w.single(e.selection.anchor,e.selection.head):w.single(0);return ba(s,i.length),t.staticFacet(va)||(s=s.asSingle()),new N(t,i,s,t.dynamicSlots.map(()=>null),(r,o)=>o.create(r),null)}get tabSize(){return this.facet(N.tabSize)}get lineBreak(){return this.facet(N.lineSeparator)||` -`}get readOnly(){return this.facet(Ma)}phrase(e,...t){for(let i of this.facet(N.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,s)=>{if(s=="$")return"$";let r=+(s||1);return!r||r>t.length?i:t[r-1]})),e}languageDataAt(e,t,i=-1){let s=[];for(let r of this.facet(ka))for(let o of r(this,t,i))Object.prototype.hasOwnProperty.call(o,e)&&s.push(o[e]);return s}charCategorizer(e){return bf(this.languageDataAt("wordChars",e).join(""))}wordAt(e){let{text:t,from:i,length:s}=this.doc.lineAt(e),r=this.charCategorizer(e),o=e-i,l=e-i;for(;o>0;){let a=Oe(t,o,!1);if(r(t.slice(a,o))!=Re.Word)break;o=a}for(;ln.length?n[0]:4});N.lineSeparator=xa;N.readOnly=Ma;N.phrases=D.define({compare(n,e){let t=Object.keys(n),i=Object.keys(e);return t.length==i.length&&t.every(s=>n[s]==e[s])}});N.languageData=ka;N.changeFilter=Sa;N.transactionFilter=Ca;N.transactionExtender=Aa;Fn.reconfigure=R.define();function _t(n,e,t={}){let i={};for(let s of n)for(let r of Object.keys(s)){let o=s[r],l=i[r];if(l===void 0)i[r]=o;else if(!(l===o||o===void 0))if(Object.hasOwnProperty.call(t,r))i[r]=t[r](l,o);else throw new Error("Config merge conflict for field "+r)}for(let s in e)i[s]===void 0&&(i[s]=e[s]);return i}class Bt{eq(e){return this==e}range(e,t=e){return _s.create(e,t,this)}}Bt.prototype.startSide=Bt.prototype.endSide=0;Bt.prototype.point=!1;Bt.prototype.mapMode=ce.TrackDel;let _s=class Oa{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new Oa(e,t,i)}};function Vs(n,e){return n.from-e.from||n.value.startSide-e.value.startSide}class Mr{constructor(e,t,i,s){this.from=e,this.to=t,this.value=i,this.maxPoint=s}get length(){return this.to[this.to.length-1]}findIndex(e,t,i,s=0){let r=i?this.to:this.from;for(let o=s,l=r.length;;){if(o==l)return o;let a=o+l>>1,h=r[a]-e||(i?this.value[a].endSide:this.value[a].startSide)-t;if(a==o)return h>=0?o:l;h>=0?l=a:o=a+1}}between(e,t,i,s){for(let r=this.findIndex(t,-1e9,!0),o=this.findIndex(i,1e9,!1,r);rd||u==d&&h.startSide>0&&h.endSide<=0)continue;(d-u||h.endSide-h.startSide)<0||(o<0&&(o=u),h.point&&(l=Math.max(l,d-u)),i.push(h),s.push(u-o),r.push(d-o))}return{mapped:i.length?new Mr(s,r,i,l):null,pos:o}}}class F{constructor(e,t,i,s){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=s}static create(e,t,i,s){return new F(e,t,i,s)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:i=!1,filterFrom:s=0,filterTo:r=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(i&&(t=t.slice().sort(Vs)),this.isEmpty)return t.length?F.of(t):this;let l=new Ba(this,null,-1).goto(0),a=0,h=[],c=new Pt;for(;l.value||a=0){let f=t[a++];c.addInner(f.from,f.to,f.value)||h.push(f)}else l.rangeIndex==1&&l.chunkIndexthis.chunkEnd(l.chunkIndex)||rl.to||r=r&&e<=r+o.length&&o.between(r,e-r,t-r,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return Ti.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return Ti.from(e).goto(t)}static compare(e,t,i,s,r=-1){let o=e.filter(f=>f.maxPoint>0||!f.isEmpty&&f.maxPoint>=r),l=t.filter(f=>f.maxPoint>0||!f.isEmpty&&f.maxPoint>=r),a=ao(o,l,i),h=new fi(o,a,r),c=new fi(l,a,r);i.iterGaps((f,u,d)=>ho(h,f,c,u,d,s)),i.empty&&i.length==0&&ho(h,0,c,0,0,s)}static eq(e,t,i=0,s){s==null&&(s=1e9);let r=e.filter(c=>!c.isEmpty&&t.indexOf(c)<0),o=t.filter(c=>!c.isEmpty&&e.indexOf(c)<0);if(r.length!=o.length)return!1;if(!r.length)return!0;let l=ao(r,o),a=new fi(r,l,0).goto(i),h=new fi(o,l,0).goto(i);for(;;){if(a.to!=h.to||!Fs(a.active,h.active)||a.point&&(!h.point||!a.point.eq(h.point)))return!1;if(a.to>s)return!0;a.next(),h.next()}}static spans(e,t,i,s,r=-1){let o=new fi(e,null,r).goto(t),l=t,a=o.openStart;for(;;){let h=Math.min(o.to,i);if(o.point?(s.point(l,h,o.point,o.activeForPoint(o.to),a,o.pointRank),a=o.openEnd(h)+(o.to>h?1:0)):h>l&&(s.span(l,h,o.active,a),a=o.openEnd(h)),o.to>i)break;l=o.to,o.next()}return a}static of(e,t=!1){let i=new Pt;for(let s of e instanceof _s?[e]:t?wf(e):e)i.add(s.from,s.to,s.value);return i.finish()}}F.empty=new F([],[],null,-1);function wf(n){if(n.length>1)for(let e=n[0],t=1;t0)return n.slice().sort(Vs);e=i}return n}F.empty.nextLayer=F.empty;class Pt{constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}finishChunk(e){this.chunks.push(new Mr(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}add(e,t,i){this.addInner(e,t,i)||(this.nextLayer||(this.nextLayer=new Pt)).add(e,t,i)}addInner(e,t,i){let s=e-this.lastTo||i.startSide-this.last.endSide;if(s<=0&&(e-this.lastFrom||i.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return s<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=i,this.lastFrom=e,this.lastTo=t,this.value.push(i),i.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let i=t.value.length-1;return this.last=t.value[i],this.lastFrom=t.from[i]+e,this.lastTo=t.to[i]+e,!0}finish(){return this.finishInner(F.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=F.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}}function ao(n,e,t){let i=new Map;for(let r of n)for(let o=0;o=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex=i&&s.push(new Ba(o,t,i,r));return s.length==1?s[0]:new Ti(s)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let i of this.heap)i.goto(e,t);for(let i=this.heap.length>>1;i>=0;i--)es(this.heap,i);return this.next(),this}forward(e,t){for(let i of this.heap)i.forward(e,t);for(let i=this.heap.length>>1;i>=0;i--)es(this.heap,i);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),es(this.heap,0)}}}function es(n,e){for(let t=n[e];;){let i=(e<<1)+1;if(i>=n.length)break;let s=n[i];if(i+1=0&&(s=n[i+1],i++),t.compare(s)<0)break;n[i]=t,n[e]=s,e=i}}class fi{constructor(e,t,i){this.minPoint=i,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=Ti.from(e,t,i)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){Ki(this.active,e),Ki(this.activeTo,e),Ki(this.activeRank,e),this.minActive=co(this.active,this.activeTo)}addActive(e){let t=0,{value:i,to:s,rank:r}=this.cursor;for(;t-1&&(this.activeTo[r]-this.cursor.from||this.active[r].endSide-this.cursor.startSide)<0){if(this.activeTo[r]>e){this.to=this.activeTo[r],this.endSide=this.active[r].endSide;break}this.removeActive(r),i&&Ki(i,r)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let o=this.cursor.value;if(!o.point)this.addActive(i),this.cursor.frome&&s++,this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from=0&&!(this.activeRank[i]e||this.activeTo[i]==e&&this.active[i].endSide>=this.point.endSide)&&t.push(this.active[i]);return t.reverse()}openEnd(e){let t=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>e;i--)t++;return t}}function ho(n,e,t,i,s,r){n.goto(e),t.goto(i);let o=i+s,l=i,a=i-e;for(;;){let h=n.to+a-t.to||n.endSide-t.endSide,c=h<0?n.to+a:t.to,f=Math.min(c,o);if(n.point||t.point?n.point&&t.point&&(n.point==t.point||n.point.eq(t.point))&&Fs(n.activeForPoint(n.to+a),t.activeForPoint(t.to))||r.comparePoint(l,f,n.point,t.point):f>l&&!Fs(n.active,t.active)&&r.compareRange(l,f,n.active,t.active),c>o)break;l=c,h<=0&&n.next(),h>=0&&t.next()}}function Fs(n,e){if(n.length!=e.length)return!1;for(let t=0;t=e;i--)n[i+1]=n[i];n[e]=t}function co(n,e){let t=-1,i=1e9;for(let s=0;s=e)return s;if(s==n.length)break;r+=n.charCodeAt(s)==9?t-r%t:1,s=Oe(n,s)}return i===!0?-1:n.length}const Ws="ͼ",fo=typeof Symbol>"u"?"__"+Ws:Symbol.for(Ws),zs=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),uo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{};class mt{constructor(e,t){this.rules=[];let{finish:i}=t||{};function s(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function r(o,l,a,h){let c=[],f=/^@(\w+)\b/.exec(o[0]),u=f&&f[1]=="keyframes";if(f&&l==null)return a.push(o[0]+";");for(let d in l){let p=l[d];if(/&/.test(d))r(d.split(/,\s*/).map(g=>o.map(y=>g.replace(/&/,y))).reduce((g,y)=>g.concat(y)),p,a);else if(p&&typeof p=="object"){if(!f)throw new RangeError("The value of a property ("+d+") should be a primitive value.");r(s(d),p,c,u)}else p!=null&&c.push(d.replace(/_.*/,"").replace(/[A-Z]/g,g=>"-"+g.toLowerCase())+": "+p+";")}(c.length||u)&&a.push((i&&!f&&!h?o.map(i):o).join(", ")+" {"+c.join(" ")+"}")}for(let o in e)r(s(o),e[o],this.rules)}getRules(){return this.rules.join(` -`)}static newName(){let e=uo[fo]||1;return uo[fo]=e+1,Ws+e.toString(36)}static mount(e,t){(e[zs]||new kf(e)).mount(Array.isArray(t)?t:[t])}}let Gi=null;class kf{constructor(e){if(!e.head&&e.adoptedStyleSheets&&typeof CSSStyleSheet<"u"){if(Gi)return e.adoptedStyleSheets=[Gi.sheet].concat(e.adoptedStyleSheets),e[zs]=Gi;this.sheet=new CSSStyleSheet,e.adoptedStyleSheets=[this.sheet].concat(e.adoptedStyleSheets),Gi=this}else{this.styleTag=(e.ownerDocument||e).createElement("style");let t=e.head||e;t.insertBefore(this.styleTag,t.firstChild)}this.modules=[],e[zs]=this}mount(e){let t=this.sheet,i=0,s=0;for(let r=0;r-1&&(this.modules.splice(l,1),s--,l=-1),l==-1){if(this.modules.splice(s++,0,o),t)for(let a=0;a",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},po=typeof navigator<"u"&&/Chrome\/(\d+)/.exec(navigator.userAgent),vf=typeof navigator<"u"&&/Mac/.test(navigator.platform),xf=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),Sf=vf||po&&+po[1]<57;for(var he=0;he<10;he++)gt[48+he]=gt[96+he]=String(he);for(var he=1;he<=24;he++)gt[he+111]="F"+he;for(var he=65;he<=90;he++)gt[he]=String.fromCharCode(he+32),Oi[he]=String.fromCharCode(he);for(var ts in gt)Oi.hasOwnProperty(ts)||(Oi[ts]=gt[ts]);function Cf(n){var e=Sf&&(n.ctrlKey||n.altKey||n.metaKey)||xf&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?Oi:gt)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}function xn(n){let e;return n.nodeType==11?e=n.getSelection?n:n.ownerDocument:e=n,e.getSelection()}function Xt(n,e){return e?n==e||n.contains(e.nodeType!=1?e.parentNode:e):!1}function Af(n){let e=n.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function dn(n,e){if(!e.anchorNode)return!1;try{return Xt(n,e.anchorNode)}catch{return!1}}function Bi(n){return n.nodeType==3?Zt(n,0,n.nodeValue.length).getClientRects():n.nodeType==1?n.getClientRects():[]}function Sn(n,e,t,i){return t?mo(n,e,t,i,-1)||mo(n,e,t,i,1):!1}function Cn(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e}function mo(n,e,t,i,s){for(;;){if(n==t&&e==i)return!0;if(e==(s<0?0:Pi(n))){if(n.nodeName=="DIV")return!1;let r=n.parentNode;if(!r||r.nodeType!=1)return!1;e=Cn(n)+(s<0?0:1),n=r}else if(n.nodeType==1){if(n=n.childNodes[e+(s<0?-1:0)],n.nodeType==1&&n.contentEditable=="false")return!1;e=s<0?Pi(n):0}else return!1}}function Pi(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}const Pa={left:0,right:0,top:0,bottom:0};function Dr(n,e){let t=e?n.left:n.right;return{left:t,right:t,top:n.top,bottom:n.bottom}}function Mf(n){return{left:0,right:n.innerWidth,top:0,bottom:n.innerHeight}}function Df(n,e,t,i,s,r,o,l){let a=n.ownerDocument,h=a.defaultView||window;for(let c=n;c;)if(c.nodeType==1){let f,u=c==a.body;if(u)f=Mf(h);else{if(c.scrollHeight<=c.clientHeight&&c.scrollWidth<=c.clientWidth){c=c.assignedSlot||c.parentNode;continue}let g=c.getBoundingClientRect();f={left:g.left,right:g.left+c.clientWidth,top:g.top,bottom:g.top+c.clientHeight}}let d=0,p=0;if(s=="nearest")e.top0&&e.bottom>f.bottom+p&&(p=e.bottom-f.bottom+p+o)):e.bottom>f.bottom&&(p=e.bottom-f.bottom+o,t<0&&e.top-p0&&e.right>f.right+d&&(d=e.right-f.right+d+r)):e.right>f.right&&(d=e.right-f.right+r,t<0&&e.leftt)return f.domBoundsAround(e,t,h);if(u>=e&&s==-1&&(s=a,r=h),h>t&&f.dom.parentNode==this.dom){o=a,l=c;break}c=u,h=u+f.breakAfter}return{from:r,to:l<0?i+this.length:l,startDOM:(s?this.children[s-1].dom.nextSibling:null)||this.dom.firstChild,endDOM:o=0?this.children[o].dom:null}}markDirty(e=!1){this.dirty|=2,this.markParentsDirty(e)}markParentsDirty(e){for(let t=this.parent;t;t=t.parent){if(e&&(t.dirty|=2),t.dirty&1)return;t.dirty|=1,e=!1}}setParent(e){this.parent!=e&&(this.parent=e,this.dirty&&this.markParentsDirty(!0))}setDOM(e){this.dom&&(this.dom.cmView=null),this.dom=e,e.cmView=this}get rootView(){for(let e=this;;){let t=e.parent;if(!t)return e;e=t}}replaceChildren(e,t,i=Tr){this.markDirty();for(let s=e;sthis.pos||e==this.pos&&(t>0||this.i==0||this.children[this.i-1].breakAfter))return this.off=e-this.pos,this;let i=this.children[--this.i];this.pos-=i.length+i.breakAfter}}}function Ia(n,e,t,i,s,r,o,l,a){let{children:h}=n,c=h.length?h[e]:null,f=r.length?r[r.length-1]:null,u=f?f.breakAfter:o;if(!(e==i&&c&&!o&&!u&&r.length<2&&c.merge(t,s,r.length?f:null,t==0,l,a))){if(i0&&(!o&&r.length&&c.merge(t,c.length,r[0],!1,l,0)?c.breakAfter=r.shift().breakAfter:(t2);var A={mac:ko||/Mac/.test(Te.platform),windows:/Win/.test(Te.platform),linux:/Linux|X11/.test(Te.platform),ie:Hn,ie_version:_a?qs.documentMode||6:Ks?+Ks[1]:js?+js[1]:0,gecko:bo,gecko_version:bo?+(/Firefox\/(\d+)/.exec(Te.userAgent)||[0,0])[1]:0,chrome:!!is,chrome_version:is?+is[1]:0,ios:ko,android:/Android\b/.test(Te.userAgent),webkit:wo,safari:Va,webkit_version:wo?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0,tabSize:qs.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};const Pf=256;class yt extends K{constructor(e){super(),this.text=e}get length(){return this.text.length}createDOM(e){this.setDOM(e||document.createTextNode(this.text))}sync(e){this.dom||this.createDOM(),this.dom.nodeValue!=this.text&&(e&&e.node==this.dom&&(e.written=!0),this.dom.nodeValue=this.text)}reuseDOM(e){e.nodeType==3&&this.createDOM(e)}merge(e,t,i){return i&&(!(i instanceof yt)||this.length-(t-e)+i.length>Pf)?!1:(this.text=this.text.slice(0,e)+(i?i.text:"")+this.text.slice(t),this.markDirty(),!0)}split(e){let t=new yt(this.text.slice(e));return this.text=this.text.slice(0,e),this.markDirty(),t}localPosFromDOM(e,t){return e==this.dom?t:t?this.text.length:0}domAtPos(e){return new ye(this.dom,e)}domBoundsAround(e,t,i){return{from:i,to:i+this.length,startDOM:this.dom,endDOM:this.dom.nextSibling}}coordsAt(e,t){return Us(this.dom,e,t)}}class et extends K{constructor(e,t=[],i=0){super(),this.mark=e,this.children=t,this.length=i;for(let s of t)s.setParent(this)}setAttrs(e){if(Ra(e),this.mark.class&&(e.className=this.mark.class),this.mark.attrs)for(let t in this.mark.attrs)e.setAttribute(t,this.mark.attrs[t]);return e}reuseDOM(e){e.nodeName==this.mark.tagName.toUpperCase()&&(this.setDOM(e),this.dirty|=6)}sync(e){this.dom?this.dirty&4&&this.setAttrs(this.dom):this.setDOM(this.setAttrs(document.createElement(this.mark.tagName))),super.sync(e)}merge(e,t,i,s,r,o){return i&&(!(i instanceof et&&i.mark.eq(this.mark))||e&&r<=0||te&&t.push(i=e&&(s=r),i=a,r++}let o=this.length-e;return this.length=e,s>-1&&(this.children.length=s,this.markDirty()),new et(this.mark,t,o)}domAtPos(e){return Wa(this,e)}coordsAt(e,t){return qa(this,e,t)}}function Us(n,e,t){let i=n.nodeValue.length;e>i&&(e=i);let s=e,r=e,o=0;e==0&&t<0||e==i&&t>=0?A.chrome||A.gecko||(e?(s--,o=1):r=0)?0:l.length-1];return A.safari&&!o&&a.width==0&&(a=Array.prototype.find.call(l,h=>h.width)||a),o?Dr(a,o<0):a||null}class ct extends K{constructor(e,t,i){super(),this.widget=e,this.length=t,this.side=i,this.prevWidget=null}static create(e,t,i){return new(e.customView||ct)(e,t,i)}split(e){let t=ct.create(this.widget,this.length-e,this.side);return this.length-=e,t}sync(){(!this.dom||!this.widget.updateDOM(this.dom))&&(this.dom&&this.prevWidget&&this.prevWidget.destroy(this.dom),this.prevWidget=null,this.setDOM(this.widget.toDOM(this.editorView)),this.dom.contentEditable="false")}getSide(){return this.side}merge(e,t,i,s,r,o){return i&&(!(i instanceof ct)||!this.widget.compare(i.widget)||e>0&&r<=0||t0?i.length-1:0;s=i[r],!(e>0?r==0:r==i.length-1||s.top0?-1:1);return this.length?s:Dr(s,this.side>0)}get isEditable(){return!1}destroy(){super.destroy(),this.dom&&this.widget.destroy(this.dom)}}class Fa extends ct{domAtPos(e){let{topView:t,text:i}=this.widget;return t?Gs(e,0,t,i,(s,r)=>s.domAtPos(r),s=>new ye(i,Math.min(s,i.nodeValue.length))):new ye(i,Math.min(e,i.nodeValue.length))}sync(){this.setDOM(this.widget.toDOM())}localPosFromDOM(e,t){let{topView:i,text:s}=this.widget;return i?Ha(e,t,i,s):Math.min(t,this.length)}ignoreMutation(){return!1}get overrideDOMText(){return null}coordsAt(e,t){let{topView:i,text:s}=this.widget;return i?Gs(e,t,i,s,(r,o,l)=>r.coordsAt(o,l),(r,o)=>Us(s,r,o)):Us(s,e,t)}destroy(){var e;super.destroy(),(e=this.widget.topView)===null||e===void 0||e.destroy()}get isEditable(){return!0}canReuseDOM(){return!0}}function Gs(n,e,t,i,s,r){if(t instanceof et){for(let o=t.dom.firstChild;o;o=o.nextSibling){let l=K.get(o);if(!l)return r(n,e);let a=Xt(o,i),h=l.length+(a?i.nodeValue.length:0);if(n0?-1:1);return i&&i.topt.top?{left:t.left,right:t.right,top:i.top,bottom:i.bottom}:t}get overrideDOMText(){return _.empty}}yt.prototype.children=ct.prototype.children=Qt.prototype.children=Tr;function Ef(n,e){let t=n.parent,i=t?t.children.indexOf(n):-1;for(;t&&i>=0;)if(e<0?i>0:ir&&e0;r--){let o=i[r-1];if(o.dom.parentNode==t)return o.domAtPos(o.length)}for(let r=s;r0&&e instanceof et&&s.length&&(i=s[s.length-1])instanceof et&&i.mark.eq(e.mark)?za(i,e.children[0],t-1):(s.push(e),e.setParent(n)),n.length+=e.length}function qa(n,e,t){let i=null,s=-1,r=null,o=-1;function l(h,c){for(let f=0,u=0;f=c&&(d.children.length?l(d,c-u):!r&&(p>c||u==p&&d.getSide()>0)?(r=d,o=c-u):(u0?3e8:-4e8:t>0?1e8:-1e8,new Et(e,t,t,i,e.widget||null,!1)}static replace(e){let t=!!e.block,i,s;if(e.isBlockGap)i=-5e8,s=4e8;else{let{start:r,end:o}=ja(e,t);i=(r?t?-3e8:-1:5e8)-1,s=(o?t?2e8:1:-6e8)+1}return new Et(e,i,s,t,e.widget||null,!0)}static line(e){return new Hi(e)}static set(e,t=!1){return F.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}}E.none=F.empty;class Wn extends E{constructor(e){let{start:t,end:i}=ja(e);super(t?-1:5e8,i?1:-6e8,null,e),this.tagName=e.tagName||"span",this.class=e.class||"",this.attrs=e.attributes||null}eq(e){return this==e||e instanceof Wn&&this.tagName==e.tagName&&this.class==e.class&&Or(this.attrs,e.attrs)}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}}Wn.prototype.point=!1;class Hi extends E{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof Hi&&Or(this.spec.attributes,e.spec.attributes)}range(e,t=e){if(t!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,t)}}Hi.prototype.mapMode=ce.TrackBefore;Hi.prototype.point=!0;class Et extends E{constructor(e,t,i,s,r,o){super(t,i,r,e),this.block=s,this.isReplace=o,this.mapMode=s?t<=0?ce.TrackBefore:ce.TrackAfter:ce.TrackDel}get type(){return this.startSide=5}eq(e){return e instanceof Et&&Lf(this.widget,e.widget)&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide}range(e,t=e){if(this.isReplace&&(e>t||e==t&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&t!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,t)}}Et.prototype.point=!0;function ja(n,e=!1){let{inclusiveStart:t,inclusiveEnd:i}=n;return t==null&&(t=n.inclusive),i==null&&(i=n.inclusive),{start:t??e,end:i??e}}function Lf(n,e){return n==e||!!(n&&e&&n.compare(e))}function Ys(n,e,t,i=0){let s=t.length-1;s>=0&&t[s]+i>=n?t[s]=Math.max(t[s],e):t.push(n,e)}class ke extends K{constructor(){super(...arguments),this.children=[],this.length=0,this.prevAttrs=void 0,this.attrs=null,this.breakAfter=0}merge(e,t,i,s,r,o){if(i){if(!(i instanceof ke))return!1;this.dom||i.transferDOM(this)}return s&&this.setDeco(i?i.attrs:null),Na(this,e,t,i?i.children:[],r,o),!0}split(e){let t=new ke;if(t.breakAfter=this.breakAfter,this.length==0)return t;let{i,off:s}=this.childPos(e);s&&(t.append(this.children[i].split(s),0),this.children[i].merge(s,this.children[i].length,null,!1,0,0),i++);for(let r=i;r0&&this.children[i-1].length==0;)this.children[--i].destroy();return this.children.length=i,this.markDirty(),this.length=e,t}transferDOM(e){this.dom&&(this.markDirty(),e.setDOM(this.dom),e.prevAttrs=this.prevAttrs===void 0?this.attrs:this.prevAttrs,this.prevAttrs=void 0,this.dom=null)}setDeco(e){Or(this.attrs,e)||(this.dom&&(this.prevAttrs=this.attrs,this.markDirty()),this.attrs=e)}append(e,t){za(this,e,t)}addLineDeco(e){let t=e.spec.attributes,i=e.spec.class;t&&(this.attrs=$s(t,this.attrs||{})),i&&(this.attrs=$s({class:i},this.attrs||{}))}domAtPos(e){return Wa(this,e)}reuseDOM(e){e.nodeName=="DIV"&&(this.setDOM(e),this.dirty|=6)}sync(e){var t;this.dom?this.dirty&4&&(Ra(this.dom),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0):(this.setDOM(document.createElement("div")),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0),this.prevAttrs!==void 0&&(Js(this.dom,this.prevAttrs,this.attrs),this.dom.classList.add("cm-line"),this.prevAttrs=void 0),super.sync(e);let i=this.dom.lastChild;for(;i&&K.get(i)instanceof et;)i=i.lastChild;if(!i||!this.length||i.nodeName!="BR"&&((t=K.get(i))===null||t===void 0?void 0:t.isEditable)==!1&&(!A.ios||!this.children.some(s=>s instanceof yt))){let s=document.createElement("BR");s.cmIgnore=!0,this.dom.appendChild(s)}}measureTextSize(){if(this.children.length==0||this.length>20)return null;let e=0;for(let t of this.children){if(!(t instanceof yt)||/[^ -~]/.test(t.text))return null;let i=Bi(t.dom);if(i.length!=1)return null;e+=i[0].width}return e?{lineHeight:this.dom.getBoundingClientRect().height,charWidth:e/this.length}:null}coordsAt(e,t){return qa(this,e,t)}become(e){return!1}get type(){return W.Text}static find(e,t){for(let i=0,s=0;i=t){if(r instanceof ke)return r;if(o>t)break}s=o+r.breakAfter}return null}}class Ot extends K{constructor(e,t,i){super(),this.widget=e,this.length=t,this.type=i,this.breakAfter=0,this.prevWidget=null}merge(e,t,i,s,r,o){return i&&(!(i instanceof Ot)||!this.widget.compare(i.widget)||e>0&&r<=0||t0;){if(this.textOff==this.text.length){let{value:r,lineBreak:o,done:l}=this.cursor.next(this.skip);if(this.skip=0,l)throw new Error("Ran out of text content when drawing inline views");if(o){this.posCovered()||this.getLine(),this.content.length?this.content[this.content.length-1].breakAfter=1:this.breakAtStart=1,this.flushBuffer([]),this.curLine=null,e--;continue}else this.text=r,this.textOff=0}let s=Math.min(this.text.length-this.textOff,e,512);this.flushBuffer(t.slice(0,i)),this.getLine().append($i(new yt(this.text.slice(this.textOff,this.textOff+s)),t),i),this.atCursorPos=!0,this.textOff+=s,e-=s,i=0}}span(e,t,i,s){this.buildText(t-e,i,s),this.pos=t,this.openStart<0&&(this.openStart=s)}point(e,t,i,s,r,o){if(this.disallowBlockEffectsFor[o]&&i instanceof Et){if(i.block)throw new RangeError("Block decorations may not be specified via plugins");if(t>this.doc.lineAt(this.pos).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}let l=t-e;if(i instanceof Et)if(i.block){let{type:a}=i;a==W.WidgetAfter&&!this.posCovered()&&this.getLine(),this.addBlockWidget(new Ot(i.widget||new vo("div"),l,a))}else{let a=ct.create(i.widget||new vo("span"),l,l?0:i.startSide),h=this.atCursorPos&&!a.isEditable&&r<=s.length&&(e0),c=!a.isEditable&&(en.some(e=>e)}),Xa=D.define({combine:n=>n.some(e=>e)});class An{constructor(e,t="nearest",i="nearest",s=5,r=5){this.range=e,this.y=t,this.x=i,this.yMargin=s,this.xMargin=r}map(e){return e.empty?this:new An(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin)}}const xo=R.define({map:(n,e)=>n.map(e)});function He(n,e,t){let i=n.facet($a);i.length?i[0](e):window.onerror?window.onerror(String(e),t,void 0,void 0,e):t?console.error(t+":",e):console.error(e)}const zn=D.define({combine:n=>n.length?n[0]:!0});let If=0;const yi=D.define();class be{constructor(e,t,i,s){this.id=e,this.create=t,this.domEventHandlers=i,this.extension=s(this)}static define(e,t){const{eventHandlers:i,provide:s,decorations:r}=t||{};return new be(If++,e,i,o=>{let l=[yi.of(o)];return r&&l.push(Ei.of(a=>{let h=a.plugin(o);return h?r(h):E.none})),s&&l.push(s(o)),l})}static fromClass(e,t){return be.define(i=>new e(i),t)}}class ns{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}update(e){if(this.value){if(this.mustUpdate){let t=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(t)}catch(i){if(He(t.state,i,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.create(e)}catch(t){He(e.state,t,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var t;if(!((t=this.value)===null||t===void 0)&&t.destroy)try{this.value.destroy()}catch(i){He(e.state,i,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}}const Za=D.define(),Qa=D.define(),Ei=D.define(),eh=D.define(),th=D.define(),bi=D.define();class Qe{constructor(e,t,i,s){this.fromA=e,this.toA=t,this.fromB=i,this.toB=s}join(e){return new Qe(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let t=e.length,i=this;for(;t>0;t--){let s=e[t-1];if(!(s.fromA>i.toA)){if(s.toAc)break;r+=2}if(!a)return i;new Qe(a.fromA,a.toA,a.fromB,a.toB).addToSet(i),o=a.toA,l=a.toB}}}class Mn{constructor(e,t,i){this.view=e,this.state=t,this.transactions=i,this.flags=0,this.startState=e.state,this.changes=ne.empty(this.startState.doc.length);for(let o of i)this.changes=this.changes.compose(o.changes);let s=[];this.changes.iterChangedRanges((o,l,a,h)=>s.push(new Qe(o,l,a,h))),this.changedRanges=s;let r=e.hasFocus;r!=e.inputState.notifiedFocused&&(e.inputState.notifiedFocused=r,this.flags|=1)}static create(e,t,i){return new Mn(e,t,i)}get viewportChanged(){return(this.flags&4)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&10)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}}var Z=function(n){return n[n.LTR=0]="LTR",n[n.RTL=1]="RTL",n}(Z||(Z={}));const Zs=Z.LTR,Nf=Z.RTL;function ih(n){let e=[];for(let t=0;t=t){if(l.level==i)return o;(r<0||(s!=0?s<0?l.fromt:e[r].level>l.level))&&(r=o)}}if(r<0)throw new RangeError("Index out of range");return r}}const X=[];function Wf(n,e){let t=n.length,i=e==Zs?1:2,s=e==Zs?2:1;if(!n||i==1&&!Hf.test(n))return nh(t);for(let o=0,l=i,a=i;o=0;u-=3)if(ze[u+1]==-c){let d=ze[u+2],p=d&2?i:d&4?d&1?s:i:0;p&&(X[o]=X[ze[u]]=p),l=u;break}}else{if(ze.length==189)break;ze[l++]=o,ze[l++]=h,ze[l++]=a}else if((f=X[o])==2||f==1){let u=f==i;a=u?0:1;for(let d=l-3;d>=0;d-=3){let p=ze[d+2];if(p&2)break;if(u)ze[d+2]|=2;else{if(p&4)break;ze[d+2]|=4}}}for(let o=0;ol;){let c=h,f=X[--h]!=2;for(;h>l&&f==(X[h-1]!=2);)h--;r.push(new Jt(h,c,f?2:1))}else r.push(new Jt(l,o,0))}else for(let o=0;o1)for(let a of this.points)a.node==e&&a.pos>this.text.length&&(a.pos-=o-1);i=r+o}}readNode(e){if(e.cmIgnore)return;let t=K.get(e),i=t&&t.overrideDOMText;if(i!=null){this.findPointInside(e,i.length);for(let s=i.iter();!s.next().done;)s.lineBreak?this.lineBreak():this.append(s.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let i of this.points)i.node==e&&e.childNodes[i.offset]==t&&(i.pos=this.text.length)}findPointInside(e,t){for(let i of this.points)(e.nodeType==3?i.node==e:e.contains(i.node))&&(i.pos=this.text.length+Math.min(t,i.offset))}}function So(n){return n.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(n.nodeName)}class Co{constructor(e,t){this.node=e,this.offset=t,this.pos=-1}}class Ao extends K{constructor(e){super(),this.view=e,this.compositionDeco=E.none,this.decorations=[],this.dynamicDecorationMap=[],this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.setDOM(e.contentDOM),this.children=[new ke],this.children[0].setParent(this),this.updateDeco(),this.updateInner([new Qe(0,0,0,e.state.doc.length)],0)}get editorView(){return this.view}get length(){return this.view.state.doc.length}update(e){let t=e.changedRanges;this.minWidth>0&&t.length&&(t.every(({fromA:o,toA:l})=>lthis.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.view.inputState.composing<0?this.compositionDeco=E.none:(e.transactions.length||this.dirty)&&(this.compositionDeco=jf(this.view,e.changes)),(A.ie||A.chrome)&&!this.compositionDeco.size&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let i=this.decorations,s=this.updateDeco(),r=$f(i,s,e.changes);return t=Qe.extendWithRanges(t,r),this.dirty==0&&t.length==0?!1:(this.updateInner(t,e.startState.doc.length),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t){this.view.viewState.mustMeasureContent=!0,this.updateChildren(e,t);let{observer:i}=this.view;i.ignore(()=>{this.dom.style.height=this.view.viewState.contentHeight+"px",this.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let r=A.chrome||A.ios?{node:i.selectionRange.focusNode,written:!1}:void 0;this.sync(r),this.dirty=0,r&&(r.written||i.selectionRange.focusNode!=r.node)&&(this.forceSelection=!0),this.dom.style.height=""});let s=[];if(this.view.viewport.from||this.view.viewport.to=0?e[s]:null;if(!r)break;let{fromA:o,toA:l,fromB:a,toB:h}=r,{content:c,breakAtStart:f,openStart:u,openEnd:d}=Br.build(this.view.state.doc,a,h,this.decorations,this.dynamicDecorationMap),{i:p,off:g}=i.findPos(l,1),{i:y,off:b}=i.findPos(o,-1);Ia(this,y,b,p,g,c,f,u,d)}}updateSelection(e=!1,t=!1){if((e||!this.view.observer.selectionRange.focusNode)&&this.view.observer.readSelectionRange(),!(t||this.mayControlSelection()))return;let i=this.forceSelection;this.forceSelection=!1;let s=this.view.state.selection.main,r=this.domAtPos(s.anchor),o=s.empty?r:this.domAtPos(s.head);if(A.gecko&&s.empty&&qf(r)){let a=document.createTextNode("");this.view.observer.ignore(()=>r.node.insertBefore(a,r.node.childNodes[r.offset]||null)),r=o=new ye(a,0),i=!0}let l=this.view.observer.selectionRange;(i||!l.focusNode||!Sn(r.node,r.offset,l.anchorNode,l.anchorOffset)||!Sn(o.node,o.offset,l.focusNode,l.focusOffset))&&(this.view.observer.ignore(()=>{A.android&&A.chrome&&this.dom.contains(l.focusNode)&&Jf(l.focusNode,this.dom)&&(this.dom.blur(),this.dom.focus({preventScroll:!0}));let a=xn(this.view.root);if(a)if(s.empty){if(A.gecko){let h=Uf(r.node,r.offset);if(h&&h!=3){let c=lh(r.node,r.offset,h==1?1:-1);c&&(r=new ye(c,h==1?0:c.nodeValue.length))}}a.collapse(r.node,r.offset),s.bidiLevel!=null&&l.cursorBidiLevel!=null&&(l.cursorBidiLevel=s.bidiLevel)}else if(a.extend){a.collapse(r.node,r.offset);try{a.extend(o.node,o.offset)}catch{}}else{let h=document.createRange();s.anchor>s.head&&([r,o]=[o,r]),h.setEnd(o.node,o.offset),h.setStart(r.node,r.offset),a.removeAllRanges(),a.addRange(h)}}),this.view.observer.setSelectionRange(r,o)),this.impreciseAnchor=r.precise?null:new ye(l.anchorNode,l.anchorOffset),this.impreciseHead=o.precise?null:new ye(l.focusNode,l.focusOffset)}enforceCursorAssoc(){if(this.compositionDeco.size)return;let{view:e}=this,t=e.state.selection.main,i=xn(e.root),{anchorNode:s,anchorOffset:r}=e.observer.selectionRange;if(!i||!t.empty||!t.assoc||!i.modify)return;let o=ke.find(this,t.head);if(!o)return;let l=o.posAtStart;if(t.head==l||t.head==l+o.length)return;let a=this.coordsAt(t.head,-1),h=this.coordsAt(t.head,1);if(!a||!h||a.bottom>h.top)return;let c=this.domAtPos(t.head+t.assoc);i.collapse(c.node,c.offset),i.modify("move",t.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let f=e.observer.selectionRange;e.docView.posFromDOM(f.anchorNode,f.anchorOffset)!=t.from&&i.collapse(s,r)}mayControlSelection(){let e=this.view.root.activeElement;return e==this.dom||dn(this.dom,this.view.observer.selectionRange)&&!(e&&this.dom.contains(e))}nearest(e){for(let t=e;t;){let i=K.get(t);if(i&&i.rootView==this)return i;t=t.parentNode}return null}posFromDOM(e,t){let i=this.nearest(e);if(!i)throw new RangeError("Trying to find position for a DOM position outside of the document");return i.localPosFromDOM(e,t)+i.posAtStart}domAtPos(e){let{i:t,off:i}=this.childCursor().findPos(e,-1);for(;to||e==o&&r.type!=W.WidgetBefore&&r.type!=W.WidgetAfter&&(!s||t==2||this.children[s-1].breakAfter||this.children[s-1].type==W.WidgetBefore&&t>-2))return r.coordsAt(e-o,t);i=o}}measureVisibleLineHeights(e){let t=[],{from:i,to:s}=e,r=this.view.contentDOM.clientWidth,o=r>Math.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,l=-1,a=this.view.textDirection==Z.LTR;for(let h=0,c=0;cs)break;if(h>=i){let d=f.dom.getBoundingClientRect();if(t.push(d.height),o){let p=f.dom.lastChild,g=p?Bi(p):[];if(g.length){let y=g[g.length-1],b=a?y.right-d.left:d.right-y.left;b>l&&(l=b,this.minWidth=r,this.minWidthFrom=h,this.minWidthTo=u)}}}h=u+f.breakAfter}return t}textDirectionAt(e){let{i:t}=this.childPos(e,1);return getComputedStyle(this.children[t].dom).direction=="rtl"?Z.RTL:Z.LTR}measureTextSize(){for(let s of this.children)if(s instanceof ke){let r=s.measureTextSize();if(r)return r}let e=document.createElement("div"),t,i;return e.className="cm-line",e.style.width="99999px",e.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.dom.appendChild(e);let s=Bi(e.firstChild)[0];t=e.getBoundingClientRect().height,i=s?s.width/27:7,e.remove()}),{lineHeight:t,charWidth:i}}childCursor(e=this.length){let t=this.children.length;return t&&(e-=this.children[--t].length),new La(this.children,e,t)}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let i=0,s=0;;s++){let r=s==t.viewports.length?null:t.viewports[s],o=r?r.from-1:this.length;if(o>i){let l=t.lineBlockAt(o).bottom-t.lineBlockAt(i).top;e.push(E.replace({widget:new Mo(l),block:!0,inclusive:!0,isBlockGap:!0}).range(i,o))}if(!r)break;i=r.to+1}return E.set(e)}updateDeco(){let e=this.view.state.facet(Ei).map((t,i)=>(this.dynamicDecorationMap[i]=typeof t=="function")?t(this.view):t);for(let t=e.length;tt.anchor?-1:1),s;if(!i)return;!t.empty&&(s=this.coordsAt(t.anchor,t.anchor>t.head?-1:1))&&(i={left:Math.min(i.left,s.left),top:Math.min(i.top,s.top),right:Math.max(i.right,s.right),bottom:Math.max(i.bottom,s.bottom)});let r=0,o=0,l=0,a=0;for(let c of this.view.state.facet(th).map(f=>f(this.view)))if(c){let{left:f,right:u,top:d,bottom:p}=c;f!=null&&(r=Math.max(r,f)),u!=null&&(o=Math.max(o,u)),d!=null&&(l=Math.max(l,d)),p!=null&&(a=Math.max(a,p))}let h={left:i.left-r,top:i.top-l,right:i.right+o,bottom:i.bottom+a};Df(this.view.scrollDOM,h,t.head0&&t<=0)n=n.childNodes[e-1],e=Pi(n);else if(n.nodeType==1&&e=0)n=n.childNodes[e],e=0;else return null}}function Uf(n,e){return n.nodeType!=1?0:(e&&n.childNodes[e-1].contentEditable=="false"?1:0)|(e0;){let h=Oe(s.text,o,!1);if(i(s.text.slice(h,o))!=a)break;o=h}for(;ln?e.left-n:Math.max(0,n-e.right)}function Zf(n,e){return e.top>n?e.top-n:Math.max(0,n-e.bottom)}function ss(n,e){return n.tope.top+1}function Do(n,e){return en.bottom?{top:n.top,left:n.left,right:n.right,bottom:e}:n}function er(n,e,t){let i,s,r,o,l=!1,a,h,c,f;for(let p=n.firstChild;p;p=p.nextSibling){let g=Bi(p);for(let y=0;yS||o==S&&r>v)&&(i=p,s=b,r=v,o=S,l=!v||(v>0?y0)),v==0?t>b.bottom&&(!c||c.bottomb.top)&&(h=p,f=b):c&&ss(c,b)?c=To(c,b.bottom):f&&ss(f,b)&&(f=Do(f,b.top))}}if(c&&c.bottom>=t?(i=a,s=c):f&&f.top<=t&&(i=h,s=f),!i)return{node:n,offset:0};let u=Math.max(s.left,Math.min(s.right,e));if(i.nodeType==3)return Oo(i,u,t);if(l&&i.contentEditable!="false")return er(i,u,t);let d=Array.prototype.indexOf.call(n.childNodes,i)+(e>=(s.left+s.right)/2?1:0);return{node:n,offset:d}}function Oo(n,e,t){let i=n.nodeValue.length,s=-1,r=1e9,o=0;for(let l=0;lt?c.top-t:t-c.bottom)-1;if(c.left-1<=e&&c.right+1>=e&&f=(c.left+c.right)/2,d=u;if((A.chrome||A.gecko)&&Zt(n,l).getBoundingClientRect().left==c.right&&(d=!u),f<=0)return{node:n,offset:l+(d?1:0)};s=l+(d?1:0),r=f}}}return{node:n,offset:s>-1?s:o>0?n.nodeValue.length:0}}function ah(n,{x:e,y:t},i,s=-1){var r;let o=n.contentDOM.getBoundingClientRect(),l=o.top+n.viewState.paddingTop,a,{docHeight:h}=n.viewState,c=t-l;if(c<0)return 0;if(c>h)return n.state.doc.length;for(let b=n.defaultLineHeight/2,v=!1;a=n.elementAtHeight(c),a.type!=W.Text;)for(;c=s>0?a.bottom+b:a.top-b,!(c>=0&&c<=h);){if(v)return i?null:0;v=!0,s=-s}t=l+c;let f=a.from;if(fn.viewport.to)return n.viewport.to==n.state.doc.length?n.state.doc.length:i?null:Bo(n,o,a,e,t);let u=n.dom.ownerDocument,d=n.root.elementFromPoint?n.root:u,p=d.elementFromPoint(e,t);p&&!n.contentDOM.contains(p)&&(p=null),p||(e=Math.max(o.left+1,Math.min(o.right-1,e)),p=d.elementFromPoint(e,t),p&&!n.contentDOM.contains(p)&&(p=null));let g,y=-1;if(p&&((r=n.docView.nearest(p))===null||r===void 0?void 0:r.isEditable)!=!1){if(u.caretPositionFromPoint){let b=u.caretPositionFromPoint(e,t);b&&({offsetNode:g,offset:y}=b)}else if(u.caretRangeFromPoint){let b=u.caretRangeFromPoint(e,t);b&&({startContainer:g,startOffset:y}=b,(!n.contentDOM.contains(g)||A.safari&&Qf(g,y,e)||A.chrome&&eu(g,y,e))&&(g=void 0))}}if(!g||!n.docView.dom.contains(g)){let b=ke.find(n.docView,f);if(!b)return c>a.top+a.height/2?a.to:a.from;({node:g,offset:y}=er(b.dom,e,t))}return n.docView.posFromDOM(g,y)}function Bo(n,e,t,i,s){let r=Math.round((i-e.left)*n.defaultCharacterWidth);if(n.lineWrapping&&t.height>n.defaultLineHeight*1.5){let l=Math.floor((s-t.top)/n.defaultLineHeight);r+=l*n.viewState.heightOracle.lineLength}let o=n.state.sliceDoc(t.from,t.to);return t.from+Hs(o,r,n.state.tabSize)}function Qf(n,e,t){let i;if(n.nodeType!=3||e!=(i=n.nodeValue.length))return!1;for(let s=n.nextSibling;s;s=s.nextSibling)if(s.nodeType!=1||s.nodeName!="BR")return!1;return Zt(n,i-1,i).getBoundingClientRect().left>t}function eu(n,e,t){if(e!=0)return!1;for(let s=n;;){let r=s.parentNode;if(!r||r.nodeType!=1||r.firstChild!=s)return!1;if(r.classList.contains("cm-line"))break;s=r}let i=n.nodeType==1?n.getBoundingClientRect():Zt(n,0,Math.max(n.nodeValue.length,1)).getBoundingClientRect();return t-i.left>5}function tu(n,e,t,i){let s=n.state.doc.lineAt(e.head),r=!i||!n.lineWrapping?null:n.coordsAtPos(e.assoc<0&&e.head>s.from?e.head-1:e.head);if(r){let a=n.dom.getBoundingClientRect(),h=n.textDirectionAt(s.from),c=n.posAtCoords({x:t==(h==Z.LTR)?a.right-1:a.left+1,y:(r.top+r.bottom)/2});if(c!=null)return w.cursor(c,t?-1:1)}let o=ke.find(n.docView,e.head),l=o?t?o.posAtEnd:o.posAtStart:t?s.to:s.from;return w.cursor(l,t?-1:1)}function Po(n,e,t,i){let s=n.state.doc.lineAt(e.head),r=n.bidiSpans(s),o=n.textDirectionAt(s.from);for(let l=e,a=null;;){let h=zf(s,r,o,l,t),c=sh;if(!h){if(s.number==(t?n.state.doc.lines:1))return l;c=` -`,s=n.state.doc.line(s.number+(t?1:-1)),r=n.bidiSpans(s),h=w.cursor(t?s.from:s.to)}if(a){if(!a(c))return l}else{if(!i)return h;a=i(c)}l=h}}function iu(n,e,t){let i=n.state.charCategorizer(e),s=i(t);return r=>{let o=i(r);return s==Re.Space&&(s=o),s==o}}function nu(n,e,t,i){let s=e.head,r=t?1:-1;if(s==(t?n.state.doc.length:0))return w.cursor(s,e.assoc);let o=e.goalColumn,l,a=n.contentDOM.getBoundingClientRect(),h=n.coordsAtPos(s),c=n.documentTop;if(h)o==null&&(o=h.left-a.left),l=r<0?h.top:h.bottom;else{let d=n.viewState.lineBlockAt(s);o==null&&(o=Math.min(a.right-a.left,n.defaultCharacterWidth*(s-d.from))),l=(r<0?d.top:d.bottom)+c}let f=a.left+o,u=i??n.defaultLineHeight>>1;for(let d=0;;d+=10){let p=l+(u+d)*r,g=ah(n,{x:f,y:p},!1,r);if(pa.bottom||(r<0?gs))return w.cursor(g,e.assoc,void 0,o)}}function rs(n,e,t){let i=n.state.facet(eh).map(s=>s(n));for(;;){let s=!1;for(let r of i)r.between(t.from-1,t.from+1,(o,l,a)=>{t.from>o&&t.fromt.from?w.cursor(o,1):w.cursor(l,-1),s=!0)});if(!s)return t}}class su{constructor(e){this.lastKeyCode=0,this.lastKeyTime=0,this.lastTouchTime=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.chromeScrollHack=-1,this.pendingIOSKey=void 0,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastEscPress=0,this.lastContextMenu=0,this.scrollHandlers=[],this.registeredEvents=[],this.customHandlers=[],this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.mouseSelection=null;for(let t in oe){let i=oe[t];e.contentDOM.addEventListener(t,s=>{!Eo(e,s)||this.ignoreDuringComposition(s)||t=="keydown"&&this.keydown(e,s)||(this.mustFlushObserver(s)&&e.observer.forceFlush(),this.runCustomHandlers(t,e,s)?s.preventDefault():i(e,s))},tr[t]),this.registeredEvents.push(t)}A.chrome&&A.chrome_version==102&&e.scrollDOM.addEventListener("wheel",()=>{this.chromeScrollHack<0?e.contentDOM.style.pointerEvents="none":window.clearTimeout(this.chromeScrollHack),this.chromeScrollHack=setTimeout(()=>{this.chromeScrollHack=-1,e.contentDOM.style.pointerEvents=""},100)},{passive:!0}),this.notifiedFocused=e.hasFocus,A.safari&&e.contentDOM.addEventListener("input",()=>null)}setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}ensureHandlers(e,t){var i;let s;this.customHandlers=[];for(let r of t)if(s=(i=r.update(e).spec)===null||i===void 0?void 0:i.domEventHandlers){this.customHandlers.push({plugin:r.value,handlers:s});for(let o in s)this.registeredEvents.indexOf(o)<0&&o!="scroll"&&(this.registeredEvents.push(o),e.contentDOM.addEventListener(o,l=>{Eo(e,l)&&this.runCustomHandlers(o,e,l)&&l.preventDefault()}))}}runCustomHandlers(e,t,i){for(let s of this.customHandlers){let r=s.handlers[e];if(r)try{if(r.call(s.plugin,i,t)||i.defaultPrevented)return!0}catch(o){He(t.state,o)}}return!1}runScrollHandlers(e,t){this.lastScrollTop=e.scrollDOM.scrollTop,this.lastScrollLeft=e.scrollDOM.scrollLeft;for(let i of this.customHandlers){let s=i.handlers.scroll;if(s)try{s.call(i.plugin,t,e)}catch(r){He(e.state,r)}}}keydown(e,t){if(this.lastKeyCode=t.keyCode,this.lastKeyTime=Date.now(),t.keyCode==9&&Date.now()s.keyCode==t.keyCode))&&!t.ctrlKey||ru.indexOf(t.key)>-1&&t.ctrlKey&&!t.shiftKey)?(this.pendingIOSKey=i||t,setTimeout(()=>this.flushIOSKey(e),250),!0):!1}flushIOSKey(e){let t=this.pendingIOSKey;return t?(this.pendingIOSKey=void 0,$t(e.contentDOM,t.key,t.keyCode)):!1}ignoreDuringComposition(e){return/^key/.test(e.type)?this.composing>0?!0:A.safari&&!A.ios&&Date.now()-this.compositionEndedAt<100?(this.compositionEndedAt=0,!0):!1:!1}mustFlushObserver(e){return e.type=="keydown"&&e.keyCode!=229}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.mouseSelection&&this.mouseSelection.update(e),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}}const hh=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],ru="dthko",ch=[16,17,18,20,91,92,224,225];class ou{constructor(e,t,i,s){this.view=e,this.style=i,this.mustSelect=s,this.lastEvent=t;let r=e.contentDOM.ownerDocument;r.addEventListener("mousemove",this.move=this.move.bind(this)),r.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(N.allowMultipleSelections)&&lu(e,t),this.dragMove=au(e,t),this.dragging=hu(e,t)&&ph(t)==1?null:!1,this.dragging===!1&&(t.preventDefault(),this.select(t))}move(e){if(e.buttons==0)return this.destroy();this.dragging===!1&&this.select(this.lastEvent=e)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=null}select(e){let t=this.style.get(e,this.extend,this.multiple);(this.mustSelect||!t.eq(this.view.state.selection)||t.main.assoc!=this.view.state.selection.main.assoc)&&this.view.dispatch({selection:t,userEvent:"select.pointer",scrollIntoView:!0}),this.mustSelect=!1}update(e){e.docChanged&&this.dragging&&(this.dragging=this.dragging.map(e.changes)),this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}}function lu(n,e){let t=n.state.facet(Ka);return t.length?t[0](e):A.mac?e.metaKey:e.ctrlKey}function au(n,e){let t=n.state.facet(Ua);return t.length?t[0](e):A.mac?!e.altKey:!e.ctrlKey}function hu(n,e){let{main:t}=n.state.selection;if(t.empty)return!1;let i=xn(n.root);if(!i||i.rangeCount==0)return!0;let s=i.getRangeAt(0).getClientRects();for(let r=0;r=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function Eo(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,i;t!=n.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(i=K.get(t))&&i.ignoreEvent(e))return!1;return!0}const oe=Object.create(null),tr=Object.create(null),fh=A.ie&&A.ie_version<15||A.ios&&A.webkit_version<604;function cu(n){let e=n.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{n.focus(),t.remove(),uh(n,t.value)},50)}function uh(n,e){let{state:t}=n,i,s=1,r=t.toText(e),o=r.lines==t.selection.ranges.length;if(ir!=null&&t.selection.ranges.every(a=>a.empty)&&ir==r.toString()){let a=-1;i=t.changeByRange(h=>{let c=t.doc.lineAt(h.from);if(c.from==a)return{range:h};a=c.from;let f=t.toText((o?r.line(s++).text:e)+t.lineBreak);return{changes:{from:c.from,insert:f},range:w.cursor(h.from+f.length)}})}else o?i=t.changeByRange(a=>{let h=r.line(s++);return{changes:{from:a.from,to:a.to,insert:h.text},range:w.cursor(a.from+h.length)}}):i=t.replaceSelection(r);n.dispatch(i,{userEvent:"input.paste",scrollIntoView:!0})}oe.keydown=(n,e)=>{n.inputState.setSelectionOrigin("select"),e.keyCode==27?n.inputState.lastEscPress=Date.now():ch.indexOf(e.keyCode)<0&&(n.inputState.lastEscPress=0)};oe.touchstart=(n,e)=>{n.inputState.lastTouchTime=Date.now(),n.inputState.setSelectionOrigin("select.pointer")};oe.touchmove=n=>{n.inputState.setSelectionOrigin("select.pointer")};tr.touchstart=tr.touchmove={passive:!0};oe.mousedown=(n,e)=>{if(n.observer.flush(),n.inputState.lastTouchTime>Date.now()-2e3)return;let t=null;for(let i of n.state.facet(Ga))if(t=i(n,e),t)break;if(!t&&e.button==0&&(t=du(n,e)),t){let i=n.root.activeElement!=n.contentDOM;i&&n.observer.ignore(()=>Ea(n.contentDOM)),n.inputState.startMouseSelection(new ou(n,e,t,i))}};function Ro(n,e,t,i){if(i==1)return w.cursor(e,t);if(i==2)return Yf(n.state,e,t);{let s=ke.find(n.docView,e),r=n.state.doc.lineAt(s?s.posAtEnd:e),o=s?s.posAtStart:r.from,l=s?s.posAtEnd:r.to;return ln>=e.top&&n<=e.bottom,Lo=(n,e,t)=>dh(e,t)&&n>=t.left&&n<=t.right;function fu(n,e,t,i){let s=ke.find(n.docView,e);if(!s)return 1;let r=e-s.posAtStart;if(r==0)return 1;if(r==s.length)return-1;let o=s.coordsAt(r,-1);if(o&&Lo(t,i,o))return-1;let l=s.coordsAt(r,1);return l&&Lo(t,i,l)?1:o&&dh(i,o)?-1:1}function Io(n,e){let t=n.posAtCoords({x:e.clientX,y:e.clientY},!1);return{pos:t,bias:fu(n,t,e.clientX,e.clientY)}}const uu=A.ie&&A.ie_version<=11;let No=null,_o=0,Vo=0;function ph(n){if(!uu)return n.detail;let e=No,t=Vo;return No=n,Vo=Date.now(),_o=!e||t>Date.now()-400&&Math.abs(e.clientX-n.clientX)<2&&Math.abs(e.clientY-n.clientY)<2?(_o+1)%3:1}function du(n,e){let t=Io(n,e),i=ph(e),s=n.state.selection,r=t,o=e;return{update(l){l.docChanged&&(t.pos=l.changes.mapPos(t.pos),s=s.map(l.changes),o=null)},get(l,a,h){let c;o&&l.clientX==o.clientX&&l.clientY==o.clientY?c=r:(c=r=Io(n,l),o=l);let f=Ro(n,c.pos,c.bias,i);if(t.pos!=c.pos&&!a){let u=Ro(n,t.pos,t.bias,i),d=Math.min(u.from,f.from),p=Math.max(u.to,f.to);f=d1&&s.ranges.some(u=>u.eq(f))?pu(s,f):h?s.addRange(f):w.create([f])}}}function pu(n,e){for(let t=0;;t++)if(n.ranges[t].eq(e))return w.create(n.ranges.slice(0,t).concat(n.ranges.slice(t+1)),n.mainIndex==t?0:n.mainIndex-(n.mainIndex>t?1:0))}oe.dragstart=(n,e)=>{let{selection:{main:t}}=n.state,{mouseSelection:i}=n.inputState;i&&(i.dragging=t),e.dataTransfer&&(e.dataTransfer.setData("Text",n.state.sliceDoc(t.from,t.to)),e.dataTransfer.effectAllowed="copyMove")};function Fo(n,e,t,i){if(!t)return;let s=n.posAtCoords({x:e.clientX,y:e.clientY},!1);e.preventDefault();let{mouseSelection:r}=n.inputState,o=i&&r&&r.dragging&&r.dragMove?{from:r.dragging.from,to:r.dragging.to}:null,l={from:s,insert:t},a=n.state.changes(o?[o,l]:l);n.focus(),n.dispatch({changes:a,selection:{anchor:a.mapPos(s,-1),head:a.mapPos(s,1)},userEvent:o?"move.drop":"input.drop"})}oe.drop=(n,e)=>{if(!e.dataTransfer)return;if(n.state.readOnly)return e.preventDefault();let t=e.dataTransfer.files;if(t&&t.length){e.preventDefault();let i=Array(t.length),s=0,r=()=>{++s==t.length&&Fo(n,e,i.filter(o=>o!=null).join(n.state.lineBreak),!1)};for(let o=0;o{/[\x00-\x08\x0e-\x1f]{2}/.test(l.result)||(i[o]=l.result),r()},l.readAsText(t[o])}}else Fo(n,e,e.dataTransfer.getData("Text"),!0)};oe.paste=(n,e)=>{if(n.state.readOnly)return e.preventDefault();n.observer.flush();let t=fh?null:e.clipboardData;t?(uh(n,t.getData("text/plain")),e.preventDefault()):cu(n)};function mu(n,e){let t=n.dom.parentNode;if(!t)return;let i=t.appendChild(document.createElement("textarea"));i.style.cssText="position: fixed; left: -10000px; top: 10px",i.value=e,i.focus(),i.selectionEnd=e.length,i.selectionStart=0,setTimeout(()=>{i.remove(),n.focus()},50)}function gu(n){let e=[],t=[],i=!1;for(let s of n.selection.ranges)s.empty||(e.push(n.sliceDoc(s.from,s.to)),t.push(s));if(!e.length){let s=-1;for(let{from:r}of n.selection.ranges){let o=n.doc.lineAt(r);o.number>s&&(e.push(o.text),t.push({from:o.from,to:Math.min(n.doc.length,o.to+1)})),s=o.number}i=!0}return{text:e.join(n.lineBreak),ranges:t,linewise:i}}let ir=null;oe.copy=oe.cut=(n,e)=>{let{text:t,ranges:i,linewise:s}=gu(n.state);if(!t&&!s)return;ir=s?t:null;let r=fh?null:e.clipboardData;r?(e.preventDefault(),r.clearData(),r.setData("text/plain",t)):mu(n,t),e.type=="cut"&&!n.state.readOnly&&n.dispatch({changes:i,scrollIntoView:!0,userEvent:"delete.cut"})};function mh(n){setTimeout(()=>{n.hasFocus!=n.inputState.notifiedFocused&&n.update([])},10)}oe.focus=n=>{n.inputState.lastFocusTime=Date.now(),!n.scrollDOM.scrollTop&&(n.inputState.lastScrollTop||n.inputState.lastScrollLeft)&&(n.scrollDOM.scrollTop=n.inputState.lastScrollTop,n.scrollDOM.scrollLeft=n.inputState.lastScrollLeft),mh(n)};oe.blur=n=>{n.observer.clearSelectionRange(),mh(n)};oe.compositionstart=oe.compositionupdate=n=>{n.inputState.compositionFirstChange==null&&(n.inputState.compositionFirstChange=!0),n.inputState.composing<0&&(n.inputState.composing=0)};oe.compositionend=n=>{n.inputState.composing=-1,n.inputState.compositionEndedAt=Date.now(),n.inputState.compositionFirstChange=null,A.chrome&&A.android&&n.observer.flushSoon(),setTimeout(()=>{n.inputState.composing<0&&n.docView.compositionDeco.size&&n.update([])},50)};oe.contextmenu=n=>{n.inputState.lastContextMenu=Date.now()};oe.beforeinput=(n,e)=>{var t;let i;if(A.chrome&&A.android&&(i=hh.find(s=>s.inputType==e.inputType))&&(n.observer.delayAndroidKey(i.key,i.keyCode),i.key=="Backspace"||i.key=="Delete")){let s=((t=window.visualViewport)===null||t===void 0?void 0:t.height)||0;setTimeout(()=>{var r;(((r=window.visualViewport)===null||r===void 0?void 0:r.height)||0)>s+10&&n.hasFocus&&(n.contentDOM.blur(),n.focus())},100)}};const Ho=["pre-wrap","normal","pre-line","break-spaces"];class yu{constructor(){this.doc=_.empty,this.lineWrapping=!1,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.lineLength=30,this.heightChanged=!1}heightForGap(e,t){let i=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(i+=Math.ceil((t-e-i*this.lineLength*.5)/this.lineLength)),this.lineHeight*i}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/(this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return Ho.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let i=0;i-1,l=Math.round(t)!=Math.round(this.lineHeight)||this.lineWrapping!=o;if(this.lineWrapping=o,this.lineHeight=t,this.charWidth=i,this.lineLength=s,l){this.heightSamples={};for(let a=0;a0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e,t){this.height!=t&&(Math.abs(this.height-t)>pn&&(e.heightChanged=!0),this.height=t)}replace(e,t,i){return ve.of(i)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,i,s){let r=this;for(let o=s.length-1;o>=0;o--){let{fromA:l,toA:a,fromB:h,toB:c}=s[o],f=r.lineAt(l,q.ByPosNoHeight,t,0,0),u=f.to>=a?f:r.lineAt(a,q.ByPosNoHeight,t,0,0);for(c+=u.to-a,a=u.to;o>0&&f.from<=s[o-1].toA;)l=s[o-1].fromA,h=s[o-1].fromB,o--,lr*2){let l=e[t-1];l.break?e.splice(--t,1,l.left,null,l.right):e.splice(--t,1,l.left,l.right),i+=1+l.break,s-=l.size}else if(r>s*2){let l=e[i];l.break?e.splice(i,1,l.left,null,l.right):e.splice(i,1,l.left,l.right),i+=2+l.break,r-=l.size}else break;else if(s=r&&o(this.blockAt(0,i,s,r))}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more&&this.setHeight(e,s.heights[s.index++]),this.outdated=!1,this}toString(){return`block(${this.length})`}}class De extends gh{constructor(e,t){super(e,t,W.Text),this.collapsed=0,this.widgetHeight=0}replace(e,t,i){let s=i[0];return i.length==1&&(s instanceof De||s instanceof ae&&s.flags&4)&&Math.abs(this.length-s.length)<10?(s instanceof ae?s=new De(s.length,this.height):s.height=this.height,this.outdated||(s.outdated=!1),s):ve.of(i)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more?this.setHeight(e,s.heights[s.index++]):(i||this.outdated)&&this.setHeight(e,Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}}class ae extends ve{constructor(e){super(e,0)}lines(e,t){let i=e.lineAt(t).number,s=e.lineAt(t+this.length).number;return{firstLine:i,lastLine:s,lineHeight:this.height/(s-i+1)}}blockAt(e,t,i,s){let{firstLine:r,lastLine:o,lineHeight:l}=this.lines(t,s),a=Math.max(0,Math.min(o-r,Math.floor((e-i)/l))),{from:h,length:c}=t.line(r+a);return new ut(h,c,i+l*a,l,W.Text)}lineAt(e,t,i,s,r){if(t==q.ByHeight)return this.blockAt(e,i,s,r);if(t==q.ByPosNoHeight){let{from:f,to:u}=i.lineAt(e);return new ut(f,u-f,0,0,W.Text)}let{firstLine:o,lineHeight:l}=this.lines(i,r),{from:a,length:h,number:c}=i.lineAt(e);return new ut(a,h,s+l*(c-o),l,W.Text)}forEachLine(e,t,i,s,r,o){let{firstLine:l,lineHeight:a}=this.lines(i,r);for(let h=Math.max(e,r),c=Math.min(r+this.length,t);h<=c;){let f=i.lineAt(h);h==e&&(s+=a*(f.number-l)),o(new ut(f.from,f.length,s,a,W.Text)),s+=a,h=f.to+1}}replace(e,t,i){let s=this.length-t;if(s>0){let r=i[i.length-1];r instanceof ae?i[i.length-1]=new ae(r.length+s):i.push(null,new ae(s-1))}if(e>0){let r=i[0];r instanceof ae?i[0]=new ae(e+r.length):i.unshift(new ae(e-1),null)}return ve.of(i)}decomposeLeft(e,t){t.push(new ae(e-1),null)}decomposeRight(e,t){t.push(null,new ae(this.length-e-1))}updateHeight(e,t=0,i=!1,s){let r=t+this.length;if(s&&s.from<=t+this.length&&s.more){let o=[],l=Math.max(t,s.from),a=-1,h=e.heightChanged;for(s.from>t&&o.push(new ae(s.from-t-1).updateHeight(e,t));l<=r&&s.more;){let f=e.doc.lineAt(l).length;o.length&&o.push(null);let u=s.heights[s.index++];a==-1?a=u:Math.abs(u-a)>=pn&&(a=-2);let d=new De(f,u);d.outdated=!1,o.push(d),l+=f+1}l<=r&&o.push(null,new ae(r-l).updateHeight(e,l));let c=ve.of(o);return e.heightChanged=h||a<0||Math.abs(c.height-this.height)>=pn||Math.abs(a-this.lines(e.doc,t).lineHeight)>=pn,c}else(i||this.outdated)&&(this.setHeight(e,e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}}class wu extends ve{constructor(e,t,i){super(e.length+t+i.length,e.height+i.height,t|(e.outdated||i.outdated?2:0)),this.left=e,this.right=i,this.size=e.size+i.size}get break(){return this.flags&1}blockAt(e,t,i,s){let r=i+this.left.height;return el))return h;let c=t==q.ByPosNoHeight?q.ByPosNoHeight:q.ByPos;return a?h.join(this.right.lineAt(l,c,i,o,l)):this.left.lineAt(l,c,i,s,r).join(h)}forEachLine(e,t,i,s,r,o){let l=s+this.left.height,a=r+this.left.length+this.break;if(this.break)e=a&&this.right.forEachLine(e,t,i,l,a,o);else{let h=this.lineAt(a,q.ByPos,i,s,r);e=e&&h.from<=t&&o(h),t>h.to&&this.right.forEachLine(h.to+1,t,i,l,a,o)}}replace(e,t,i){let s=this.left.length+this.break;if(tthis.left.length)return this.balanced(this.left,this.right.replace(e-s,t-s,i));let r=[];e>0&&this.decomposeLeft(e,r);let o=r.length;for(let l of i)r.push(l);if(e>0&&Wo(r,o-1),t=i&&t.push(null)),e>i&&this.right.decomposeLeft(e-i,t)}decomposeRight(e,t){let i=this.left.length,s=i+this.break;if(e>=s)return this.right.decomposeRight(e-s,t);e2*t.size||t.size>2*e.size?ve.of(this.break?[e,null,t]:[e,t]):(this.left=e,this.right=t,this.height=e.height+t.height,this.outdated=e.outdated||t.outdated,this.size=e.size+t.size,this.length=e.length+this.break+t.length,this)}updateHeight(e,t=0,i=!1,s){let{left:r,right:o}=this,l=t+r.length+this.break,a=null;return s&&s.from<=t+r.length&&s.more?a=r=r.updateHeight(e,t,i,s):r.updateHeight(e,t,i),s&&s.from<=l+o.length&&s.more?a=o=o.updateHeight(e,l,i,s):o.updateHeight(e,l,i),a?this.balanced(r,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}}function Wo(n,e){let t,i;n[e]==null&&(t=n[e-1])instanceof ae&&(i=n[e+1])instanceof ae&&n.splice(e-1,3,new ae(t.length+1+i.length))}const ku=5;class Pr{constructor(e,t){this.pos=e,this.oracle=t,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let i=Math.min(t,this.lineEnd),s=this.nodes[this.nodes.length-1];s instanceof De?s.length+=i-this.pos:(i>this.pos||!this.isCovered)&&this.nodes.push(new De(i-this.pos,-1)),this.writtenTo=i,t>i&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,i){if(e=ku)&&this.addLineDeco(s,r)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenToe&&this.nodes.push(new De(this.pos-e,-1)),this.writtenTo=this.pos}blankContent(e,t){let i=new ae(t-e);return this.oracle.doc.lineAt(e).to==t&&(i.flags|=4),i}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof De)return e;let t=new De(0,-1);return this.nodes.push(t),t}addBlock(e){this.enterLine(),e.type==W.WidgetAfter&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,e.type!=W.WidgetBefore&&(this.covering=e)}addLineDeco(e,t){let i=this.ensureLine();i.length+=t,i.collapsed+=t,i.widgetHeight=Math.max(i.widgetHeight,e),this.writtenTo=this.pos=this.pos+t}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof De)&&!this.isCovered?this.nodes.push(new De(0,-1)):(this.writtenToc.clientHeight||c.scrollWidth>c.clientWidth)&&f.overflow!="visible"){let u=c.getBoundingClientRect();r=Math.max(r,u.left),o=Math.min(o,u.right),l=Math.max(l,u.top),a=h==n.parentNode?u.bottom:Math.min(a,u.bottom)}h=f.position=="absolute"||f.position=="fixed"?c.offsetParent:c.parentNode}else if(h.nodeType==11)h=h.host;else break;return{left:r-t.left,right:Math.max(r,o)-t.left,top:l-(t.top+e),bottom:Math.max(l,a)-(t.top+e)}}function Cu(n,e){let t=n.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}class os{constructor(e,t,i){this.from=e,this.to=t,this.size=i}static same(e,t){if(e.length!=t.length)return!1;for(let i=0;itypeof t!="function"),this.heightMap=ve.empty().applyChanges(this.stateDeco,_.empty,this.heightOracle.setDoc(e.doc),[new Qe(0,0,0,e.doc.length)]),this.viewport=this.getViewport(0,null),this.updateViewportLines(),this.updateForViewport(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=E.set(this.lineGaps.map(t=>t.draw(!1))),this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let i=0;i<=1;i++){let s=i?t.head:t.anchor;if(!e.some(({from:r,to:o})=>s>=r&&s<=o)){let{from:r,to:o}=this.lineBlockAt(s);e.push(new Ji(r,o))}}this.viewports=e.sort((i,s)=>i.from-s.from),this.scaler=this.heightMap.height<=7e6?qo:new Tu(this.heightOracle.doc,this.heightMap,this.viewports)}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.state.doc,0,0,e=>{this.viewportLines.push(this.scaler.scale==1?e:wi(e,this.scaler))})}update(e,t=null){this.state=e.state;let i=this.stateDeco;this.stateDeco=this.state.facet(Ei).filter(h=>typeof h!="function");let s=e.changedRanges,r=Qe.extendWithRanges(s,vu(i,this.stateDeco,e?e.changes:ne.empty(this.state.doc.length))),o=this.heightMap.height;this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),r),this.heightMap.height!=o&&(e.flags|=2);let l=r.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.headl.to)||!this.viewportIsAppropriate(l))&&(l=this.getViewport(0,t));let a=!e.changes.empty||e.flags&2||l.from!=this.viewport.from||l.to!=this.viewport.to;this.viewport=l,this.updateForViewport(),a&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>2e3<<1)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&e.selectionSet&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(Xa)&&(this.mustEnforceCursorAssoc=!0)}measure(e){let t=e.contentDOM,i=window.getComputedStyle(t),s=this.heightOracle,r=i.whiteSpace;this.defaultTextDirection=i.direction=="rtl"?Z.RTL:Z.LTR;let o=this.heightOracle.mustRefreshForWrapping(r),l=o||this.mustMeasureContent||this.contentDOMHeight!=t.clientHeight;this.contentDOMHeight=t.clientHeight,this.mustMeasureContent=!1;let a=0,h=0,c=parseInt(i.paddingTop)||0,f=parseInt(i.paddingBottom)||0;(this.paddingTop!=c||this.paddingBottom!=f)&&(this.paddingTop=c,this.paddingBottom=f,a|=10),this.editorWidth!=e.scrollDOM.clientWidth&&(s.lineWrapping&&(l=!0),this.editorWidth=e.scrollDOM.clientWidth,a|=8);let u=(this.printing?Cu:Su)(t,this.paddingTop),d=u.top-this.pixelViewport.top,p=u.bottom-this.pixelViewport.bottom;this.pixelViewport=u;let g=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(g!=this.inView&&(this.inView=g,g&&(l=!0)),!this.inView&&!this.scrollTarget)return 0;let y=t.clientWidth;if((this.contentDOMWidth!=y||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=y,this.editorHeight=e.scrollDOM.clientHeight,a|=8),l){let v=e.docView.measureVisibleLineHeights(this.viewport);if(s.mustRefreshForHeights(v)&&(o=!0),o||s.lineWrapping&&Math.abs(y-this.contentDOMWidth)>s.charWidth){let{lineHeight:S,charWidth:k}=e.docView.measureTextSize();o=S>0&&s.refresh(r,S,k,y/k,v),o&&(e.docView.minWidth=0,a|=8)}d>0&&p>0?h=Math.max(d,p):d<0&&p<0&&(h=Math.min(d,p)),s.heightChanged=!1;for(let S of this.viewports){let k=S.from==this.viewport.from?v:e.docView.measureVisibleLineHeights(S);this.heightMap=o?ve.empty().applyChanges(this.stateDeco,_.empty,this.heightOracle,[new Qe(0,0,0,e.state.doc.length)]):this.heightMap.updateHeight(s,0,o,new bu(S.from,k))}s.heightChanged&&(a|=2)}let b=!this.viewportIsAppropriate(this.viewport,h)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return b&&(this.viewport=this.getViewport(h,this.scrollTarget)),this.updateForViewport(),(a&2||b)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>2e3<<1)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,e)),a|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),a}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let i=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),s=this.heightMap,r=this.state.doc,{visibleTop:o,visibleBottom:l}=this,a=new Ji(s.lineAt(o-i*1e3,q.ByHeight,r,0,0).from,s.lineAt(l+(1-i)*1e3,q.ByHeight,r,0,0).to);if(t){let{head:h}=t.range;if(ha.to){let c=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),f=s.lineAt(h,q.ByPos,r,0,0),u;t.y=="center"?u=(f.top+f.bottom)/2-c/2:t.y=="start"||t.y=="nearest"&&h=l+Math.max(10,Math.min(i,250)))&&s>o-2*1e3&&r>1,o=s<<1;if(this.defaultTextDirection!=Z.LTR&&!i)return[];let l=[],a=(h,c,f,u)=>{if(c-hh&&yy.from>=f.from&&y.to<=f.to&&Math.abs(y.from-h)y.fromb));if(!g){if(cy.from<=c&&y.to>=c)){let y=t.moveToLineBoundary(w.cursor(c),!1,!0).head;y>h&&(c=y)}g=new os(h,c,this.gapSize(f,h,c,u))}l.push(g)};for(let h of this.viewportLines){if(h.lengthh.from&&a(h.from,u,h,c),dt.draw(this.heightOracle.lineWrapping))))}computeVisibleRanges(){let e=this.stateDeco;this.lineGaps.length&&(e=e.concat(this.lineGapDeco));let t=[];F.spans(e,this.viewport.from,this.viewport.to,{span(s,r){t.push({from:s,to:r})},point(){}},20);let i=t.length!=this.visibleRanges.length||this.visibleRanges.some((s,r)=>s.from!=t[r].from||s.to!=t[r].to);return this.visibleRanges=t,i?4:0}lineBlockAt(e){return e>=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||wi(this.heightMap.lineAt(e,q.ByPos,this.state.doc,0,0),this.scaler)}lineBlockAtHeight(e){return wi(this.heightMap.lineAt(this.scaler.fromDOM(e),q.ByHeight,this.state.doc,0,0),this.scaler)}elementAtHeight(e){return wi(this.heightMap.blockAt(this.scaler.fromDOM(e),this.state.doc,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}}class Ji{constructor(e,t){this.from=e,this.to=t}}function Mu(n,e,t){let i=[],s=n,r=0;return F.spans(t,n,e,{span(){},point(o,l){o>s&&(i.push({from:s,to:o}),r+=o-s),s=l}},20),s=1)return e[e.length-1].to;let i=Math.floor(n*t);for(let s=0;;s++){let{from:r,to:o}=e[s],l=o-r;if(i<=l)return r+i;i-=l}}function Xi(n,e){let t=0;for(let{from:i,to:s}of n.ranges){if(e<=s){t+=e-i;break}t+=s-i}return t/n.total}function Du(n,e){for(let t of n)if(e(t))return t}const qo={toDOM(n){return n},fromDOM(n){return n},scale:1};class Tu{constructor(e,t,i){let s=0,r=0,o=0;this.viewports=i.map(({from:l,to:a})=>{let h=t.lineAt(l,q.ByPos,e,0,0).top,c=t.lineAt(a,q.ByPos,e,0,0).bottom;return s+=c-h,{from:l,to:a,top:h,bottom:c,domTop:0,domBottom:0}}),this.scale=(7e6-s)/(t.height-s);for(let l of this.viewports)l.domTop=o+(l.top-r)*this.scale,o=l.domBottom=l.domTop+(l.bottom-l.top),r=l.bottom}toDOM(e){for(let t=0,i=0,s=0;;t++){let r=twi(s,e)):n.type)}const Zi=D.define({combine:n=>n.join(" ")}),nr=D.define({combine:n=>n.indexOf(!0)>-1}),sr=mt.newName(),yh=mt.newName(),bh=mt.newName(),wh={"&light":"."+yh,"&dark":"."+bh};function rr(n,e,t){return new mt(e,{finish(i){return/&/.test(i)?i.replace(/&\w*/,s=>{if(s=="&")return n;if(!t||!t[s])throw new RangeError(`Unsupported selector: ${s}`);return t[s]}):n+" "+i}})}const Ou=rr("."+sr,{"&.cm-editor":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0},".cm-content":{margin:0,flexGrow:2,flexShrink:0,minHeight:"100%",display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 4px"},".cm-selectionLayer":{zIndex:-1,contain:"size style"},".cm-selectionBackground":{position:"absolute"},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{zIndex:100,contain:"size style",pointerEvents:"none"},"&.cm-focused .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{position:"absolute",borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#444"},"&.cm-focused .cm-cursor":{display:"block"},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",left:0,zIndex:200},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",borderRight:"1px solid #ddd"},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},wh);class Bu{constructor(e,t,i,s){this.typeOver=s,this.bounds=null,this.text="";let{impreciseHead:r,impreciseAnchor:o}=e.docView;if(t>-1&&!e.state.readOnly&&(this.bounds=e.docView.domBoundsAround(t,i,0))){let l=r||o?[]:Eu(e),a=new rh(l,e.state);a.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=a.text,this.newSel=Ru(l,this.bounds.from)}else{let l=e.observer.selectionRange,a=r&&r.node==l.focusNode&&r.offset==l.focusOffset||!Xt(e.contentDOM,l.focusNode)?e.state.selection.main.head:e.docView.posFromDOM(l.focusNode,l.focusOffset),h=o&&o.node==l.anchorNode&&o.offset==l.anchorOffset||!Xt(e.contentDOM,l.anchorNode)?e.state.selection.main.anchor:e.docView.posFromDOM(l.anchorNode,l.anchorOffset);this.newSel=w.single(h,a)}}}function kh(n,e){let t,{newSel:i}=e,s=n.state.selection.main;if(e.bounds){let{from:r,to:o}=e.bounds,l=s.from,a=null;(n.inputState.lastKeyCode===8&&n.inputState.lastKeyTime>Date.now()-100||A.android&&e.text.length=s.from&&t.to<=s.to&&(t.from!=s.from||t.to!=s.to)&&s.to-s.from-(t.to-t.from)<=4?t={from:s.from,to:s.to,insert:n.state.doc.slice(s.from,t.from).append(t.insert).append(n.state.doc.slice(t.to,s.to))}:(A.mac||A.android)&&t&&t.from==t.to&&t.from==s.head-1&&/^\. ?$/.test(t.insert.toString())?(i&&t.insert.length==2&&(i=w.single(i.main.anchor-1,i.main.head-1)),t={from:s.from,to:s.to,insert:_.of([" "])}):A.chrome&&t&&t.from==t.to&&t.from==s.head&&t.insert.toString()==` - `&&n.lineWrapping&&(i&&(i=w.single(i.main.anchor-1,i.main.head-1)),t={from:s.from,to:s.to,insert:_.of([" "])}),t){let r=n.state;if(A.ios&&n.inputState.flushIOSKey(n)||A.android&&(t.from==s.from&&t.to==s.to&&t.insert.length==1&&t.insert.lines==2&&$t(n.contentDOM,"Enter",13)||t.from==s.from-1&&t.to==s.to&&t.insert.length==0&&$t(n.contentDOM,"Backspace",8)||t.from==s.from&&t.to==s.to+1&&t.insert.length==0&&$t(n.contentDOM,"Delete",46)))return!0;let o=t.insert.toString();if(n.state.facet(Ja).some(h=>h(n,t.from,t.to,o)))return!0;n.inputState.composing>=0&&n.inputState.composing++;let l;if(t.from>=s.from&&t.to<=s.to&&t.to-t.from>=(s.to-s.from)/3&&(!i||i.main.empty&&i.main.from==t.from+t.insert.length)&&n.inputState.composing<0){let h=s.fromt.to?r.sliceDoc(t.to,s.to):"";l=r.replaceSelection(n.state.toText(h+t.insert.sliceString(0,void 0,n.state.lineBreak)+c))}else{let h=r.changes(t),c=i&&!r.selection.main.eq(i.main)&&i.main.to<=h.newLength?i.main:void 0;if(r.selection.ranges.length>1&&n.inputState.composing>=0&&t.to<=s.to&&t.to>=s.to-10){let f=n.state.sliceDoc(t.from,t.to),u=oh(n)||n.state.doc.lineAt(s.head),d=s.to-t.to,p=s.to-s.from;l=r.changeByRange(g=>{if(g.from==s.from&&g.to==s.to)return{changes:h,range:c||g.map(h)};let y=g.to-d,b=y-f.length;if(g.to-g.from!=p||n.state.sliceDoc(b,y)!=f||u&&g.to>=u.from&&g.from<=u.to)return{range:g};let v=r.changes({from:b,to:y,insert:t.insert}),S=g.to-s.to;return{changes:v,range:c?w.range(Math.max(0,c.anchor+S),Math.max(0,c.head+S)):g.map(v)}})}else l={changes:h,selection:c&&r.selection.replaceRange(c)}}let a="input.type";return n.composing&&(a+=".compose",n.inputState.compositionFirstChange&&(a+=".start",n.inputState.compositionFirstChange=!1)),n.dispatch(l,{scrollIntoView:!0,userEvent:a}),!0}else if(i&&!i.main.eq(s)){let r=!1,o="select";return n.inputState.lastSelectionTime>Date.now()-50&&(n.inputState.lastSelectionOrigin=="select"&&(r=!0),o=n.inputState.lastSelectionOrigin),n.dispatch({selection:i,scrollIntoView:r,userEvent:o}),!0}else return!1}function Pu(n,e,t,i){let s=Math.min(n.length,e.length),r=0;for(;r0&&l>0&&n.charCodeAt(o-1)==e.charCodeAt(l-1);)o--,l--;if(i=="end"){let a=Math.max(0,r-Math.min(o,l));t-=o+a-r}if(o=o?r-t:0;r-=a,l=r+(l-o),o=r}else if(l=l?r-t:0;r-=a,o=r+(o-l),l=r}return{from:r,toA:o,toB:l}}function Eu(n){let e=[];if(n.root.activeElement!=n.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}=n.observer.selectionRange;return t&&(e.push(new Co(t,i)),(s!=t||r!=i)&&e.push(new Co(s,r))),e}function Ru(n,e){if(n.length==0)return null;let t=n[0].pos,i=n.length==2?n[1].pos:t;return t>-1&&i>-1?w.single(t+e,i+e):null}const Lu={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},ls=A.ie&&A.ie_version<=11;class Iu{constructor(e){this.view=e,this.active=!1,this.selectionRange=new Tf,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resize=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let i of t)this.queue.push(i);(A.ie&&A.ie_version<=11||A.ios&&e.composing)&&t.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),ls&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),typeof ResizeObserver=="function"&&(this.resize=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate){this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(t=>{t.length>0&&t[t.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runScrollHandlers(this.view,e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(){this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500)}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((t,i)=>t!=e[i]))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:i}=this,s=this.selectionRange;if(i.state.facet(zn)?i.root.activeElement!=this.dom:!dn(i.dom,s))return;let r=s.anchorNode&&i.docView.nearest(s.anchorNode);if(r&&r.ignoreEvent(e)){t||(this.selectionChanged=!1);return}(A.ie&&A.ie_version<=11||A.android&&A.chrome)&&!i.state.selection.main.empty&&s.focusNode&&Sn(s.focusNode,s.focusOffset,s.anchorNode,s.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=A.safari&&e.root.nodeType==11&&Af(this.dom.ownerDocument)==this.dom&&Nu(this.view)||xn(e.root);if(!t||this.selectionRange.eq(t))return!1;let i=dn(this.dom,t);return i&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime{let r=this.delayedAndroidKey;r&&(this.clearDelayedAndroidKey(),!this.flush()&&r.force&&$t(this.dom,r.key,r.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(s)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}processRecords(){let e=this.queue;for(let r of this.observer.takeRecords())e.push(r);e.length&&(this.queue=[]);let t=-1,i=-1,s=!1;for(let r of e){let o=this.readMutation(r);o&&(o.typeOver&&(s=!0),t==-1?{from:t,to:i}=o:(t=Math.min(o.from,t),i=Math.max(o.to,i)))}return{from:t,to:i,typeOver:s}}readChange(){let{from:e,to:t,typeOver:i}=this.processRecords(),s=this.selectionChanged&&dn(this.dom,this.selectionRange);return e<0&&!s?null:(e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1,new Bu(this.view,e,t,i))}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return!1;let i=this.view.state,s=kh(this.view,t);return this.view.state==i&&this.view.update([]),s}readMutation(e){let t=this.view.docView.nearest(e.target);if(!t||t.ignoreMutation(e))return null;if(t.markDirty(e.type=="attributes"),e.type=="attributes"&&(t.dirty|=4),e.type=="childList"){let i=jo(t,e.previousSibling||e.target.previousSibling,-1),s=jo(t,e.nextSibling||e.target.nextSibling,1);return{from:i?t.posAfter(i):t.posAtStart,to:s?t.posBefore(s):t.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}destroy(){var e,t,i;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(t=this.gapIntersection)===null||t===void 0||t.disconnect(),(i=this.resize)===null||i===void 0||i.disconnect();for(let s of this.scrollTargets)s.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey)}}function jo(n,e,t){for(;e;){let i=K.get(e);if(i&&i.parent==n)return i;let s=e.parentNode;e=s!=n.dom?s:t>0?e.nextSibling:e.previousSibling}return null}function Nu(n){let e=null;function t(a){a.preventDefault(),a.stopImmediatePropagation(),e=a.getTargetRanges()[0]}if(n.contentDOM.addEventListener("beforeinput",t,!0),n.dom.ownerDocument.execCommand("indent"),n.contentDOM.removeEventListener("beforeinput",t,!0),!e)return null;let i=e.startContainer,s=e.startOffset,r=e.endContainer,o=e.endOffset,l=n.docView.domAtPos(n.state.selection.main.anchor);return Sn(l.node,l.offset,r,o)&&([i,s,r,o]=[r,o,i,s]),{anchorNode:i,anchorOffset:s,focusNode:r,focusOffset:o}}class O{constructor(e={}){this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.style.cssText="position: absolute; top: -10000px",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),this._dispatch=e.dispatch||(t=>this.update([t])),this.dispatch=this.dispatch.bind(this),this._root=e.root||Of(e.parent)||document,this.viewState=new zo(e.state||N.create(e)),this.plugins=this.state.facet(yi).map(t=>new ns(t));for(let t of this.plugins)t.update(this);this.observer=new Iu(this),this.inputState=new su(this),this.inputState.ensureHandlers(this,this.plugins),this.docView=new Ao(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),e.parent&&e.parent.appendChild(this.dom)}get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return this.inputState.composing>0}get compositionStarted(){return this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}dispatch(...e){this._dispatch(e.length==1&&e[0]instanceof re?e[0]:this.state.update(...e))}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let t=!1,i=!1,s,r=this.state;for(let h of e){if(h.startState!=r)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");r=h.state}if(this.destroyed){this.viewState.state=r;return}let o=this.observer.delayedAndroidKey,l=null;if(o?(this.observer.clearDelayedAndroidKey(),l=this.observer.readChange(),(l&&!this.state.doc.eq(r.doc)||!this.state.selection.eq(r.selection))&&(l=null)):this.observer.clear(),r.facet(N.phrases)!=this.state.facet(N.phrases))return this.setState(r);s=Mn.create(this,r,e);let a=this.viewState.scrollTarget;try{this.updateState=2;for(let h of e){if(a&&(a=a.map(h.changes)),h.scrollIntoView){let{main:c}=h.state.selection;a=new An(c.empty?c:w.cursor(c.head,c.head>c.anchor?-1:1))}for(let c of h.effects)c.is(xo)&&(a=c.value)}this.viewState.update(s,a),this.bidiCache=Dn.update(this.bidiCache,s.changes),s.empty||(this.updatePlugins(s),this.inputState.update(s)),t=this.docView.update(s),this.state.facet(bi)!=this.styleModules&&this.mountStyles(),i=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(h=>h.isUserEvent("select.pointer")))}finally{this.updateState=0}if(s.startState.facet(Zi)!=s.state.facet(Zi)&&(this.viewState.mustMeasureContent=!0),(t||i||a||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),!s.empty)for(let h of this.state.facet(Xs))h(s);l&&!kh(this,l)&&o.force&&$t(this.contentDOM,o.key,o.keyCode)}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let i of this.plugins)i.destroy(this);this.viewState=new zo(e),this.plugins=e.facet(yi).map(i=>new ns(i)),this.pluginMap.clear();for(let i of this.plugins)i.update(this);this.docView=new Ao(this),this.inputState.ensureHandlers(this,this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(yi),i=e.state.facet(yi);if(t!=i){let s=[];for(let r of i){let o=t.indexOf(r);if(o<0)s.push(new ns(r));else{let l=this.plugins[o];l.mustUpdate=e,s.push(l)}}for(let r of this.plugins)r.mustUpdate!=e&&r.destroy(this);this.plugins=s,this.pluginMap.clear(),this.inputState.ensureHandlers(this,this.plugins)}else for(let s of this.plugins)s.mustUpdate=e;for(let s=0;s-1&&cancelAnimationFrame(this.measureScheduled),this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,{scrollHeight:i,scrollTop:s,clientHeight:r}=this.scrollDOM,o=s>i-r-4?i:s;try{for(let l=0;;l++){this.updateState=1;let a=this.viewport,h=this.viewState.lineBlockAtHeight(o),c=this.viewState.measure(this);if(!c&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(l>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let f=[];c&4||([this.measureRequests,f]=[f,this.measureRequests]);let u=f.map(y=>{try{return y.read(this)}catch(b){return He(this.state,b),Ko}}),d=Mn.create(this,this.state,[]),p=!1,g=!1;d.flags|=c,t?t.flags|=c:t=d,this.updateState=2,d.empty||(this.updatePlugins(d),this.inputState.update(d),this.updateAttrs(),p=this.docView.update(d));for(let y=0;y1||y<-1)&&(this.scrollDOM.scrollTop+=y,g=!0)}if(p&&this.docView.updateSelection(!0),this.viewport.from==a.from&&this.viewport.to==a.to&&!g&&this.measureRequests.length==0)break}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let l of this.state.facet(Xs))l(t)}get themeClasses(){return sr+" "+(this.state.facet(nr)?bh:yh)+" "+this.state.facet(Zi)}updateAttrs(){let e=Uo(this,Za,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",translate:"no",contenteditable:this.state.facet(zn)?"true":"false",class:"cm-content",style:`${A.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),Uo(this,Qa,t);let i=this.observer.ignore(()=>{let s=Js(this.contentDOM,this.contentAttrs,t),r=Js(this.dom,this.editorAttrs,e);return s||r});return this.editorAttrs=e,this.contentAttrs=t,i}showAnnouncements(e){let t=!0;for(let i of e)for(let s of i.effects)if(s.is(O.announce)){t&&(this.announceDOM.textContent=""),t=!1;let r=this.announceDOM.appendChild(document.createElement("div"));r.textContent=s.value}}mountStyles(){this.styleModules=this.state.facet(bi),mt.mount(this.root,this.styleModules.concat(Ou).reverse())}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(e.key!=null){for(let t=0;ti.spec==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,i){return rs(this,e,Po(this,e,t,i))}moveByGroup(e,t){return rs(this,e,Po(this,e,t,i=>iu(this,e.head,i)))}moveToLineBoundary(e,t,i=!0){return tu(this,e,t,i)}moveVertically(e,t,i){return rs(this,e,nu(this,e,t,i))}domAtPos(e){return this.docView.domAtPos(e)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){return this.readMeasured(),ah(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let i=this.docView.coordsAt(e,t);if(!i||i.left==i.right)return i;let s=this.state.doc.lineAt(e),r=this.bidiSpans(s),o=r[Jt.find(r,e-s.from,-1,t)];return Dr(i,o.dir==Z.LTR==t>0)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(Ya)||ethis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>_u)return nh(e.length);let t=this.textDirectionAt(e.from);for(let s of this.bidiCache)if(s.from==e.from&&s.dir==t)return s.order;let i=Wf(e.text,t);return this.bidiCache.push(new Dn(e.from,e.to,t,i)),i}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||A.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{Ea(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){return xo.of(new An(typeof e=="number"?w.cursor(e):e,t.y,t.x,t.yMargin,t.xMargin))}static domEventHandlers(e){return be.define(()=>({}),{eventHandlers:e})}static theme(e,t){let i=mt.newName(),s=[Zi.of(i),bi.of(rr(`.${i}`,e))];return t&&t.dark&&s.push(nr.of(!0)),s}static baseTheme(e){return Vi.lowest(bi.of(rr("."+sr,e,wh)))}static findFromDOM(e){var t;let i=e.querySelector(".cm-content"),s=i&&K.get(i)||K.get(e);return((t=s?.rootView)===null||t===void 0?void 0:t.view)||null}}O.styleModule=bi;O.inputHandler=Ja;O.perLineTextDirection=Ya;O.exceptionSink=$a;O.updateListener=Xs;O.editable=zn;O.mouseSelectionStyle=Ga;O.dragMovesSelection=Ua;O.clickAddsSelectionRange=Ka;O.decorations=Ei;O.atomicRanges=eh;O.scrollMargins=th;O.darkTheme=nr;O.contentAttributes=Qa;O.editorAttributes=Za;O.lineWrapping=O.contentAttributes.of({class:"cm-lineWrapping"});O.announce=R.define();const _u=4096,Ko={};class Dn{constructor(e,t,i,s){this.from=e,this.to=t,this.dir=i,this.order=s}static update(e,t){if(t.empty)return e;let i=[],s=e.length?e[e.length-1].dir:Z.LTR;for(let r=Math.max(0,e.length-10);r=0;s--){let r=i[s],o=typeof r=="function"?r(n):r;o&&$s(o,t)}return t}const Vu=A.mac?"mac":A.windows?"win":A.linux?"linux":"key";function Fu(n,e){const t=n.split(/-(?!$)/);let i=t[t.length-1];i=="Space"&&(i=" ");let s,r,o,l;for(let a=0;ai.concat(s),[]))),t}let at=null;const zu=4e3;function qu(n,e=Vu){let t=Object.create(null),i=Object.create(null),s=(o,l)=>{let a=i[o];if(a==null)i[o]=l;else if(a!=l)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},r=(o,l,a,h)=>{var c,f;let u=t[o]||(t[o]=Object.create(null)),d=l.split(/ (?!$)/).map(y=>Fu(y,e));for(let y=1;y{let S=at={view:v,prefix:b,scope:o};return setTimeout(()=>{at==S&&(at=null)},zu),!0}]})}let p=d.join(" ");s(p,!1);let g=u[p]||(u[p]={preventDefault:!1,run:((f=(c=u._any)===null||c===void 0?void 0:c.run)===null||f===void 0?void 0:f.slice())||[]});a&&g.run.push(a),h&&(g.preventDefault=!0)};for(let o of n){let l=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let h of l){let c=t[h]||(t[h]=Object.create(null));c._any||(c._any={preventDefault:!1,run:[]});for(let f in c)c[f].run.push(o.any)}let a=o[e]||o.key;if(a)for(let h of l)r(h,a,o.run,o.preventDefault),o.shift&&r(h,"Shift-"+a,o.shift,o.preventDefault)}return t}function ju(n,e,t,i){let s=Cf(e),r=ge(s,0),o=Ee(r)==s.length&&s!=" ",l="",a=!1;at&&at.view==t&&at.scope==i&&(l=at.prefix+" ",(a=ch.indexOf(e.keyCode)<0)&&(at=null));let h=new Set,c=p=>{if(p){for(let g of p.run)if(!h.has(g)&&(h.add(g),g(t,e)))return!0;p.preventDefault&&(a=!0)}return!1},f=n[i],u,d;if(f){if(c(f[l+Qi(s,e,!o)]))return!0;if(o&&(e.shiftKey||e.altKey||e.metaKey||r>127)&&(u=gt[e.keyCode])&&u!=s){if(c(f[l+Qi(u,e,!0)]))return!0;if(e.shiftKey&&(d=Oi[e.keyCode])!=s&&d!=u&&c(f[l+Qi(d,e,!1)]))return!0}else if(o&&e.shiftKey&&c(f[l+Qi(s,e,!0)]))return!0;if(c(f._any))return!0}return a}const vh=!A.ios,ki=D.define({combine(n){return _t(n,{cursorBlinkRate:1200,drawRangeCursor:!0},{cursorBlinkRate:(e,t)=>Math.min(e,t),drawRangeCursor:(e,t)=>e||t})}});function Ku(n={}){return[ki.of(n),Uu,Gu,Xa.of(!0)]}class xh{constructor(e,t,i,s,r){this.left=e,this.top=t,this.width=i,this.height=s,this.className=r}draw(){let e=document.createElement("div");return e.className=this.className,this.adjust(e),e}adjust(e){e.style.left=this.left+"px",e.style.top=this.top+"px",this.width>=0&&(e.style.width=this.width+"px"),e.style.height=this.height+"px"}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}}const Uu=be.fromClass(class{constructor(n){this.view=n,this.rangePieces=[],this.cursors=[],this.measureReq={read:this.readPos.bind(this),write:this.drawSel.bind(this)},this.selectionLayer=n.scrollDOM.appendChild(document.createElement("div")),this.selectionLayer.className="cm-selectionLayer",this.selectionLayer.setAttribute("aria-hidden","true"),this.cursorLayer=n.scrollDOM.appendChild(document.createElement("div")),this.cursorLayer.className="cm-cursorLayer",this.cursorLayer.setAttribute("aria-hidden","true"),n.requestMeasure(this.measureReq),this.setBlinkRate()}setBlinkRate(){this.cursorLayer.style.animationDuration=this.view.state.facet(ki).cursorBlinkRate+"ms"}update(n){let e=n.startState.facet(ki)!=n.state.facet(ki);(e||n.selectionSet||n.geometryChanged||n.viewportChanged)&&this.view.requestMeasure(this.measureReq),n.transactions.some(t=>t.scrollIntoView)&&(this.cursorLayer.style.animationName=this.cursorLayer.style.animationName=="cm-blink"?"cm-blink2":"cm-blink"),e&&this.setBlinkRate()}readPos(){let{state:n}=this.view,e=n.facet(ki),t=n.selection.ranges.map(s=>s.empty?[]:$u(this.view,s)).reduce((s,r)=>s.concat(r)),i=[];for(let s of n.selection.ranges){let r=s==n.selection.main;if(s.empty?!r||vh:e.drawRangeCursor){let o=Ju(this.view,s,r);o&&i.push(o)}}return{rangePieces:t,cursors:i}}drawSel({rangePieces:n,cursors:e}){if(n.length!=this.rangePieces.length||n.some((t,i)=>!t.eq(this.rangePieces[i]))){this.selectionLayer.textContent="";for(let t of n)this.selectionLayer.appendChild(t.draw());this.rangePieces=n}if(e.length!=this.cursors.length||e.some((t,i)=>!t.eq(this.cursors[i]))){let t=this.cursorLayer.children;if(t.length!==e.length){this.cursorLayer.textContent="";for(const i of e)this.cursorLayer.appendChild(i.draw())}else e.forEach((i,s)=>i.adjust(t[s]));this.cursors=e}}destroy(){this.selectionLayer.remove(),this.cursorLayer.remove()}}),Sh={".cm-line":{"& ::selection":{backgroundColor:"transparent !important"},"&::selection":{backgroundColor:"transparent !important"}}};vh&&(Sh[".cm-line"].caretColor="transparent !important");const Gu=Vi.highest(O.theme(Sh));function Ch(n){let e=n.scrollDOM.getBoundingClientRect();return{left:(n.textDirection==Z.LTR?e.left:e.right-n.scrollDOM.clientWidth)-n.scrollDOM.scrollLeft,top:e.top-n.scrollDOM.scrollTop}}function $o(n,e,t){let i=w.cursor(e);return{from:Math.max(t.from,n.moveToLineBoundary(i,!1,!0).from),to:Math.min(t.to,n.moveToLineBoundary(i,!0,!0).from),type:W.Text}}function Jo(n,e){let t=n.lineBlockAt(e);if(Array.isArray(t.type)){for(let i of t.type)if(i.to>e||i.to==e&&(i.to==t.to||i.type==W.Text))return i}return t}function $u(n,e){if(e.to<=n.viewport.from||e.from>=n.viewport.to)return[];let t=Math.max(e.from,n.viewport.from),i=Math.min(e.to,n.viewport.to),s=n.textDirection==Z.LTR,r=n.contentDOM,o=r.getBoundingClientRect(),l=Ch(n),a=window.getComputedStyle(r.firstChild),h=o.left+parseInt(a.paddingLeft)+Math.min(0,parseInt(a.textIndent)),c=o.right-parseInt(a.paddingRight),f=Jo(n,t),u=Jo(n,i),d=f.type==W.Text?f:null,p=u.type==W.Text?u:null;if(n.lineWrapping&&(d&&(d=$o(n,t,d)),p&&(p=$o(n,i,p))),d&&p&&d.from==p.from)return y(b(e.from,e.to,d));{let S=d?b(e.from,null,d):v(f,!1),k=p?b(null,e.to,p):v(u,!0),C=[];return(d||f).to<(p||u).from-1?C.push(g(h,S.bottom,c,k.top)):S.bottomP&&G.from=M)break;J>Q&&I(Math.max(le,Q),S==null&&le<=P,Math.min(J,M),k==null&&J>=V,Y.dir)}if(Q=$.to+1,Q>=M)break}return U.length==0&&I(P,S==null,V,k==null,n.textDirection),{top:T,bottom:B,horizontal:U}}function v(S,k){let C=o.top+(k?S.top:S.bottom);return{top:C,bottom:C,horizontal:[]}}}function Ju(n,e,t){let i=n.coordsAtPos(e.head,e.assoc||1);if(!i)return null;let s=Ch(n);return new xh(i.left-s.left,i.top-s.top,-1,i.bottom-i.top,t?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary")}function Yo(n,e,t,i,s){e.lastIndex=0;for(let r=n.iterRange(t,i),o=t,l;!r.next().done;o+=r.value.length)if(!r.lineBreak)for(;l=e.exec(r.value);)s(o+l.index,l)}function Yu(n,e){let t=n.visibleRanges;if(t.length==1&&t[0].from==n.viewport.from&&t[0].to==n.viewport.to)return t;let i=[];for(let{from:s,to:r}of t)s=Math.max(n.state.doc.lineAt(s).from,s-e),r=Math.min(n.state.doc.lineAt(r).to,r+e),i.length&&i[i.length-1].to>=s?i[i.length-1].to=r:i.push({from:s,to:r});return i}class Xu{constructor(e){const{regexp:t,decoration:i,decorate:s,boundary:r,maxLength:o=1e3}=e;if(!t.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=t,s)this.addMatch=(l,a,h,c)=>s(c,h,h+l[0].length,l,a);else if(typeof i=="function")this.addMatch=(l,a,h,c)=>{let f=i(l,a,h);f&&c(h,h+l[0].length,f)};else if(i)this.addMatch=(l,a,h,c)=>c(h,h+l[0].length,i);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=r,this.maxLength=o}createDeco(e){let t=new Pt,i=t.add.bind(t);for(let{from:s,to:r}of Yu(e,this.maxLength))Yo(e.state.doc,this.regexp,s,r,(o,l)=>this.addMatch(l,e,o,i));return t.finish()}updateDeco(e,t){let i=1e9,s=-1;return e.docChanged&&e.changes.iterChanges((r,o,l,a)=>{a>e.view.viewport.from&&l1e3?this.createDeco(e.view):s>-1?this.updateRange(e.view,t.map(e.changes),i,s):t}updateRange(e,t,i,s){for(let r of e.visibleRanges){let o=Math.max(r.from,i),l=Math.min(r.to,s);if(l>o){let a=e.state.doc.lineAt(o),h=a.toa.from;o--)if(this.boundary.test(a.text[o-1-a.from])){c=o;break}for(;lu.push(b.range(g,y));if(a==h)for(this.regexp.lastIndex=c-a.from;(d=this.regexp.exec(a.text))&&d.indexthis.addMatch(y,e,g,p));t=t.update({filterFrom:c,filterTo:f,filter:(g,y)=>gf,add:u})}}return t}}const or=/x/.unicode!=null?"gu":"g",Zu=new RegExp(`[\0-\b ---Ÿ­؜​‎‏\u2028\u2029‭‮⁦⁧⁩\uFEFF-]`,or),Qu={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"};let as=null;function ed(){var n;if(as==null&&typeof document<"u"&&document.body){let e=document.body.style;as=((n=e.tabSize)!==null&&n!==void 0?n:e.MozTabSize)!=null}return as||!1}const mn=D.define({combine(n){let e=_t(n,{render:null,specialChars:Zu,addSpecialChars:null});return(e.replaceTabs=!ed())&&(e.specialChars=new RegExp(" |"+e.specialChars.source,or)),e.addSpecialChars&&(e.specialChars=new RegExp(e.specialChars.source+"|"+e.addSpecialChars.source,or)),e}});function td(n={}){return[mn.of(n),id()]}let Xo=null;function id(){return Xo||(Xo=be.fromClass(class{constructor(n){this.view=n,this.decorations=E.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(n.state.facet(mn)),this.decorations=this.decorator.createDeco(n)}makeDecorator(n){return new Xu({regexp:n.specialChars,decoration:(e,t,i)=>{let{doc:s}=t.state,r=ge(e[0],0);if(r==9){let o=s.lineAt(i),l=t.state.tabSize,a=Fi(o.text,l,i-o.from);return E.replace({widget:new od((l-a%l)*this.view.defaultCharacterWidth)})}return this.decorationCache[r]||(this.decorationCache[r]=E.replace({widget:new rd(n,r)}))},boundary:n.replaceTabs?void 0:/[^]/})}update(n){let e=n.state.facet(mn);n.startState.facet(mn)!=e?(this.decorator=this.makeDecorator(e),this.decorations=this.decorator.createDeco(n.view)):this.decorations=this.decorator.updateDeco(n,this.decorations)}},{decorations:n=>n.decorations}))}const nd="•";function sd(n){return n>=32?nd:n==10?"␤":String.fromCharCode(9216+n)}class rd extends tt{constructor(e,t){super(),this.options=e,this.code=t}eq(e){return e.code==this.code}toDOM(e){let t=sd(this.code),i=e.state.phrase("Control character")+" "+(Qu[this.code]||"0x"+this.code.toString(16)),s=this.options.render&&this.options.render(this.code,i,t);if(s)return s;let r=document.createElement("span");return r.textContent=t,r.title=i,r.setAttribute("aria-label",i),r.className="cm-specialChar",r}ignoreEvent(){return!1}}class od extends tt{constructor(e){super(),this.width=e}eq(e){return e.width==this.width}toDOM(){let e=document.createElement("span");return e.textContent=" ",e.className="cm-tab",e.style.width=this.width+"px",e}ignoreEvent(){return!1}}class ld extends tt{constructor(e){super(),this.content=e}toDOM(){let e=document.createElement("span");return e.className="cm-placeholder",e.style.pointerEvents="none",e.appendChild(typeof this.content=="string"?document.createTextNode(this.content):this.content),typeof this.content=="string"?e.setAttribute("aria-label","placeholder "+this.content):e.setAttribute("aria-hidden","true"),e}ignoreEvent(){return!1}}function ad(n){return be.fromClass(class{constructor(e){this.view=e,this.placeholder=E.set([E.widget({widget:new ld(n),side:1}).range(0)])}get decorations(){return this.view.state.doc.length?E.none:this.placeholder}},{decorations:e=>e.decorations})}const lr=2e3;function hd(n,e,t){let i=Math.min(e.line,t.line),s=Math.max(e.line,t.line),r=[];if(e.off>lr||t.off>lr||e.col<0||t.col<0){let o=Math.min(e.off,t.off),l=Math.max(e.off,t.off);for(let a=i;a<=s;a++){let h=n.doc.line(a);h.length<=l&&r.push(w.range(h.from+o,h.to+l))}}else{let o=Math.min(e.col,t.col),l=Math.max(e.col,t.col);for(let a=i;a<=s;a++){let h=n.doc.line(a),c=Hs(h.text,o,n.tabSize,!0);if(c<0)r.push(w.cursor(h.to));else{let f=Hs(h.text,l,n.tabSize);r.push(w.range(h.from+c,h.from+f))}}}return r}function cd(n,e){let t=n.coordsAtPos(n.viewport.from);return t?Math.round(Math.abs((t.left-e)/n.defaultCharacterWidth)):-1}function Zo(n,e){let t=n.posAtCoords({x:e.clientX,y:e.clientY},!1),i=n.state.doc.lineAt(t),s=t-i.from,r=s>lr?-1:s==i.length?cd(n,e.clientX):Fi(i.text,n.state.tabSize,t-i.from);return{line:i.number,col:r,off:s}}function fd(n,e){let t=Zo(n,e),i=n.state.selection;return t?{update(s){if(s.docChanged){let r=s.changes.mapPos(s.startState.doc.line(t.line).from),o=s.state.doc.lineAt(r);t={line:o.number,col:t.col,off:Math.min(t.off,o.length)},i=i.map(s.changes)}},get(s,r,o){let l=Zo(n,s);if(!l)return i;let a=hd(n.state,t,l);return a.length?o?w.create(a.concat(i.ranges)):w.create(a):i}}:null}function ud(n){let e=n?.eventFilter||(t=>t.altKey&&t.button==0);return O.mouseSelectionStyle.of((t,i)=>e(i)?fd(t,i):null)}const dd={Alt:[18,n=>n.altKey],Control:[17,n=>n.ctrlKey],Shift:[16,n=>n.shiftKey],Meta:[91,n=>n.metaKey]},pd={style:"cursor: crosshair"};function md(n={}){let[e,t]=dd[n.key||"Alt"],i=be.fromClass(class{constructor(s){this.view=s,this.isDown=!1}set(s){this.isDown!=s&&(this.isDown=s,this.view.update([]))}},{eventHandlers:{keydown(s){this.set(s.keyCode==e||t(s))},keyup(s){(s.keyCode==e||!t(s))&&this.set(!1)},mousemove(s){this.set(t(s))}}});return[i,O.contentAttributes.of(s=>{var r;return!((r=s.plugin(i))===null||r===void 0)&&r.isDown?pd:null})]}const hs="-10000px";class Ah{constructor(e,t,i){this.facet=t,this.createTooltipView=i,this.input=e.state.facet(t),this.tooltips=this.input.filter(s=>s),this.tooltipViews=this.tooltips.map(i)}update(e){var t;let i=e.state.facet(this.facet),s=i.filter(o=>o);if(i===this.input){for(let o of this.tooltipViews)o.update&&o.update(e);return!1}let r=[];for(let o=0;o{var e,t,i;return{position:A.ios?"absolute":((e=n.find(s=>s.position))===null||e===void 0?void 0:e.position)||"fixed",parent:((t=n.find(s=>s.parent))===null||t===void 0?void 0:t.parent)||null,tooltipSpace:((i=n.find(s=>s.tooltipSpace))===null||i===void 0?void 0:i.tooltipSpace)||gd}}}),Mh=be.fromClass(class{constructor(n){this.view=n,this.inView=!0,this.lastTransaction=0,this.measureTimeout=-1;let e=n.state.facet(cs);this.position=e.position,this.parent=e.parent,this.classes=n.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.manager=new Ah(n,Er,t=>this.createTooltip(t)),this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(t=>{Date.now()>this.lastTransaction-50&&t.length>0&&t[t.length-1].intersectionRatio<1&&this.measureSoon()},{threshold:[1]}):null,this.observeIntersection(),n.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let n of this.manager.tooltipViews)this.intersectionObserver.observe(n.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(n){n.transactions.length&&(this.lastTransaction=Date.now());let e=this.manager.update(n);e&&this.observeIntersection();let t=e||n.geometryChanged,i=n.state.facet(cs);if(i.position!=this.position){this.position=i.position;for(let s of this.manager.tooltipViews)s.dom.style.position=this.position;t=!0}if(i.parent!=this.parent){this.parent&&this.container.remove(),this.parent=i.parent,this.createContainer();for(let s of this.manager.tooltipViews)this.container.appendChild(s.dom);t=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);t&&this.maybeMeasure()}createTooltip(n){let e=n.create(this.view);if(e.dom.classList.add("cm-tooltip"),n.arrow&&!e.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let t=document.createElement("div");t.className="cm-tooltip-arrow",e.dom.appendChild(t)}return e.dom.style.position=this.position,e.dom.style.top=hs,this.container.appendChild(e.dom),e.mount&&e.mount(this.view),e}destroy(){var n,e;this.view.win.removeEventListener("resize",this.measureSoon);for(let t of this.manager.tooltipViews)t.dom.remove(),(n=t.destroy)===null||n===void 0||n.call(t);(e=this.intersectionObserver)===null||e===void 0||e.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let n=this.view.dom.getBoundingClientRect();return{editor:n,parent:this.parent?this.container.getBoundingClientRect():n,pos:this.manager.tooltips.map((e,t)=>{let i=this.manager.tooltipViews[t];return i.getCoords?i.getCoords(e.pos):this.view.coordsAtPos(e.pos)}),size:this.manager.tooltipViews.map(({dom:e})=>e.getBoundingClientRect()),space:this.view.state.facet(cs).tooltipSpace(this.view)}}writeMeasure(n){let{editor:e,space:t}=n,i=[];for(let s=0;s=Math.min(e.bottom,t.bottom)||a.rightMath.min(e.right,t.right)+.1){l.style.top=hs;continue}let c=r.arrow?o.dom.querySelector(".cm-tooltip-arrow"):null,f=c?7:0,u=h.right-h.left,d=h.bottom-h.top,p=o.offset||bd,g=this.view.textDirection==Z.LTR,y=h.width>t.right-t.left?g?t.left:t.right-h.width:g?Math.min(a.left-(c?14:0)+p.x,t.right-u):Math.max(t.left,a.left-u+(c?14:0)-p.x),b=!!r.above;!r.strictSide&&(b?a.top-(h.bottom-h.top)-p.yt.bottom)&&b==t.bottom-a.bottom>a.top-t.top&&(b=!b);let v=b?a.top-d-f-p.y:a.bottom+f+p.y,S=y+u;if(o.overlap!==!0)for(let k of i)k.lefty&&k.topv&&(v=b?k.top-d-2-f:k.bottom+f+2);this.position=="absolute"?(l.style.top=v-n.parent.top+"px",l.style.left=y-n.parent.left+"px"):(l.style.top=v+"px",l.style.left=y+"px"),c&&(c.style.left=`${a.left+(g?p.x:-p.x)-(y+14-7)}px`),o.overlap!==!0&&i.push({left:y,top:v,right:S,bottom:v+d}),l.classList.toggle("cm-tooltip-above",b),l.classList.toggle("cm-tooltip-below",!b),o.positioned&&o.positioned()}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let n of this.manager.tooltipViews)n.dom.style.top=hs}},{eventHandlers:{scroll(){this.maybeMeasure()}}}),yd=O.baseTheme({".cm-tooltip":{zIndex:100},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:`${7*2}px`,position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),bd={x:0,y:0},Er=D.define({enables:[Mh,yd]}),Tn=D.define();class Rr{constructor(e){this.view=e,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new Ah(e,Tn,t=>this.createHostedView(t))}static create(e){return new Rr(e)}createHostedView(e){let t=e.create(this.view);return t.dom.classList.add("cm-tooltip-section"),this.dom.appendChild(t.dom),this.mounted&&t.mount&&t.mount(this.view),t}mount(e){for(let t of this.manager.tooltipViews)t.mount&&t.mount(e);this.mounted=!0}positioned(){for(let e of this.manager.tooltipViews)e.positioned&&e.positioned()}update(e){this.manager.update(e)}}const wd=Er.compute([Tn],n=>{let e=n.facet(Tn).filter(t=>t);return e.length===0?null:{pos:Math.min(...e.map(t=>t.pos)),end:Math.max(...e.filter(t=>t.end!=null).map(t=>t.end)),create:Rr.create,above:e[0].above,arrow:e.some(t=>t.arrow)}});class kd{constructor(e,t,i,s,r){this.view=e,this.source=t,this.field=i,this.setHover=s,this.hoverTime=r,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:e.dom,time:0},this.checkHover=this.checkHover.bind(this),e.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),e.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout(()=>this.startHover(),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active)return;let e=Date.now()-this.lastMove.time;ei.bottom||e.xi.right+this.view.defaultCharacterWidth)return;let s=this.view.bidiSpans(this.view.state.doc.lineAt(t)).find(l=>l.from<=t&&l.to>=t),r=s&&s.dir==Z.RTL?-1:1,o=this.source(this.view,t,e.x{this.pending==l&&(this.pending=null,a&&this.view.dispatch({effects:this.setHover.of(a)}))},a=>He(this.view.state,a,"hover tooltip"))}else o&&this.view.dispatch({effects:this.setHover.of(o)})}mousemove(e){var t;this.lastMove={x:e.clientX,y:e.clientY,target:e.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let i=this.active;if(i&&!vd(this.lastMove.target)||this.pending){let{pos:s}=i||this.pending,r=(t=i?.end)!==null&&t!==void 0?t:s;(s==r?this.view.posAtCoords(this.lastMove)!=s:!xd(this.view,s,r,e.clientX,e.clientY,6))&&(this.view.dispatch({effects:this.setHover.of(null)}),this.pending=null)}}mouseleave(){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1,this.active&&this.view.dispatch({effects:this.setHover.of(null)})}destroy(){clearTimeout(this.hoverTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}}function vd(n){for(let e=n;e;e=e.parentNode)if(e.nodeType==1&&e.classList.contains("cm-tooltip"))return!0;return!1}function xd(n,e,t,i,s,r){let o=document.createRange(),l=n.domAtPos(e),a=n.domAtPos(t);o.setEnd(a.node,a.offset),o.setStart(l.node,l.offset);let h=o.getClientRects();o.detach();for(let c=0;cTn.from(s)});return[i,be.define(s=>new kd(s,n,i,t,e.hoverTime||300)),wd]}function Cd(n,e){let t=n.plugin(Mh);if(!t)return null;let i=t.manager.tooltips.indexOf(e);return i<0?null:t.manager.tooltipViews[i]}const Ad=R.define(),Qo=D.define({combine(n){let e,t;for(let i of n)e=e||i.topContainer,t=t||i.bottomContainer;return{topContainer:e,bottomContainer:t}}});function Md(n,e){let t=n.plugin(Dh),i=t?t.specs.indexOf(e):-1;return i>-1?t.panels[i]:null}const Dh=be.fromClass(class{constructor(n){this.input=n.state.facet(ar),this.specs=this.input.filter(t=>t),this.panels=this.specs.map(t=>t(n));let e=n.state.facet(Qo);this.top=new en(n,!0,e.topContainer),this.bottom=new en(n,!1,e.bottomContainer),this.top.sync(this.panels.filter(t=>t.top)),this.bottom.sync(this.panels.filter(t=>!t.top));for(let t of this.panels)t.dom.classList.add("cm-panel"),t.mount&&t.mount()}update(n){let e=n.state.facet(Qo);this.top.container!=e.topContainer&&(this.top.sync([]),this.top=new en(n.view,!0,e.topContainer)),this.bottom.container!=e.bottomContainer&&(this.bottom.sync([]),this.bottom=new en(n.view,!1,e.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let t=n.state.facet(ar);if(t!=this.input){let i=t.filter(a=>a),s=[],r=[],o=[],l=[];for(let a of i){let h=this.specs.indexOf(a),c;h<0?(c=a(n.view),l.push(c)):(c=this.panels[h],c.update&&c.update(n)),s.push(c),(c.top?r:o).push(c)}this.specs=i,this.panels=s,this.top.sync(r),this.bottom.sync(o);for(let a of l)a.dom.classList.add("cm-panel"),a.mount&&a.mount()}else for(let i of this.panels)i.update&&i.update(n)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:n=>O.scrollMargins.of(e=>{let t=e.plugin(n);return t&&{top:t.top.scrollMargin(),bottom:t.bottom.scrollMargin()}})});class en{constructor(e,t,i){this.view=e,this.top=t,this.container=i,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(e){for(let t of this.panels)t.destroy&&e.indexOf(t)<0&&t.destroy();this.panels=e,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);return}if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom",this.dom.style[this.top?"top":"bottom"]="0";let t=this.container||this.view.dom;t.insertBefore(this.dom,this.top?t.firstChild:null)}let e=this.dom.firstChild;for(let t of this.panels)if(t.dom.parentNode==this.dom){for(;e!=t.dom;)e=el(e);e=e.nextSibling}else this.dom.insertBefore(t.dom,e);for(;e;)e=el(e)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let e of this.classes.split(" "))e&&this.container.classList.remove(e);for(let e of(this.classes=this.view.themeClasses).split(" "))e&&this.container.classList.add(e)}}}function el(n){let e=n.nextSibling;return n.remove(),e}const ar=D.define({enables:Dh});class bt extends Bt{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}}bt.prototype.elementClass="";bt.prototype.toDOM=void 0;bt.prototype.mapMode=ce.TrackBefore;bt.prototype.startSide=bt.prototype.endSide=-1;bt.prototype.point=!0;const fs=D.define(),Dd={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>F.empty,lineMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{}},Ci=D.define();function Td(n){return[Th(),Ci.of(Object.assign(Object.assign({},Dd),n))]}const hr=D.define({combine:n=>n.some(e=>e)});function Th(n){let e=[Od];return n&&n.fixed===!1&&e.push(hr.of(!0)),e}const Od=be.fromClass(class{constructor(n){this.view=n,this.prevViewport=n.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight+"px",this.gutters=n.state.facet(Ci).map(e=>new il(n,e));for(let e of this.gutters)this.dom.appendChild(e.dom);this.fixed=!n.state.facet(hr),this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),n.scrollDOM.insertBefore(this.dom,n.contentDOM)}update(n){if(this.updateGutters(n)){let e=this.prevViewport,t=n.view.viewport,i=Math.min(e.to,t.to)-Math.max(e.from,t.from);this.syncGutters(i<(t.to-t.from)*.8)}n.geometryChanged&&(this.dom.style.minHeight=this.view.contentHeight+"px"),this.view.state.facet(hr)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":""),this.prevViewport=n.view.viewport}syncGutters(n){let e=this.dom.nextSibling;n&&this.dom.remove();let t=F.iter(this.view.state.facet(fs),this.view.viewport.from),i=[],s=this.gutters.map(r=>new Bd(r,this.view.viewport,-this.view.documentPadding.top));for(let r of this.view.viewportLineBlocks){let o;if(Array.isArray(r.type)){for(let l of r.type)if(l.type==W.Text){o=l;break}}else o=r.type==W.Text?r:void 0;if(o){i.length&&(i=[]),Oh(t,i,r.from);for(let l of s)l.line(this.view,o,i)}}for(let r of s)r.finish();n&&this.view.scrollDOM.insertBefore(this.dom,e)}updateGutters(n){let e=n.startState.facet(Ci),t=n.state.facet(Ci),i=n.docChanged||n.heightChanged||n.viewportChanged||!F.eq(n.startState.facet(fs),n.state.facet(fs),n.view.viewport.from,n.view.viewport.to);if(e==t)for(let s of this.gutters)s.update(n)&&(i=!0);else{i=!0;let s=[];for(let r of t){let o=e.indexOf(r);o<0?s.push(new il(this.view,r)):(this.gutters[o].update(n),s.push(this.gutters[o]))}for(let r of this.gutters)r.dom.remove(),s.indexOf(r)<0&&r.destroy();for(let r of s)this.dom.appendChild(r.dom);this.gutters=s}return i}destroy(){for(let n of this.gutters)n.destroy();this.dom.remove()}},{provide:n=>O.scrollMargins.of(e=>{let t=e.plugin(n);return!t||t.gutters.length==0||!t.fixed?null:e.textDirection==Z.LTR?{left:t.dom.offsetWidth}:{right:t.dom.offsetWidth}})});function tl(n){return Array.isArray(n)?n:[n]}function Oh(n,e,t){for(;n.value&&n.from<=t;)n.from==t&&e.push(n.value),n.next()}class Bd{constructor(e,t,i){this.gutter=e,this.height=i,this.localMarkers=[],this.i=0,this.cursor=F.iter(e.markers,t.from)}line(e,t,i){this.localMarkers.length&&(this.localMarkers=[]),Oh(this.cursor,this.localMarkers,t.from);let s=i.length?this.localMarkers.concat(i):this.localMarkers,r=this.gutter.config.lineMarker(e,t,s);r&&s.unshift(r);let o=this.gutter;if(s.length==0&&!o.config.renderEmptyElements)return;let l=t.top-this.height;if(this.i==o.elements.length){let a=new Bh(e,t.height,l,s);o.elements.push(a),o.dom.appendChild(a.dom)}else o.elements[this.i].update(e,t.height,l,s);this.height=t.bottom,this.i++}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}}class il{constructor(e,t){this.view=e,this.config=t,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let i in t.domEventHandlers)this.dom.addEventListener(i,s=>{let r=e.lineBlockAtHeight(s.clientY-e.documentTop);t.domEventHandlers[i](e,r,s)&&s.preventDefault()});this.markers=tl(t.markers(e)),t.initialSpacer&&(this.spacer=new Bh(e,0,0,[t.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let t=this.markers;if(this.markers=tl(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let s=this.config.updateSpacer(this.spacer.markers[0],e);s!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[s])}let i=e.view.viewport;return!F.eq(this.markers,t,i.from,i.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}}class Bh{constructor(e,t,i,s){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,t,i,s)}update(e,t,i,s){this.height!=t&&(this.dom.style.height=(this.height=t)+"px"),this.above!=i&&(this.dom.style.marginTop=(this.above=i)?i+"px":""),Pd(this.markers,s)||this.setMarkers(e,s)}setMarkers(e,t){let i="cm-gutterElement",s=this.dom.firstChild;for(let r=0,o=0;;){let l=o,a=rr(l,a,h)||o(l,a,h):o}return i}})}});class us extends bt{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}}function ds(n,e){return n.state.facet(zt).formatNumber(e,n.state)}const Rd=Ci.compute([zt],n=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(Ed)},lineMarker(e,t,i){return i.some(s=>s.toDOM)?null:new us(ds(e,e.state.doc.lineAt(t.from).number))},lineMarkerChange:e=>e.startState.facet(zt)!=e.state.facet(zt),initialSpacer(e){return new us(ds(e,nl(e.state.doc.lines)))},updateSpacer(e,t){let i=ds(t.view,nl(t.view.state.doc.lines));return i==e.number?e:new us(i)},domEventHandlers:n.facet(zt).domEventHandlers}));function Ld(n={}){return[zt.of(n),Th(),Rd]}function nl(n){let e=9;for(;e{throw new Error("This node type doesn't define a deserialize function")})}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=xe.match(e)),t=>{let i=e(t);return i===void 0?null:[this,i]}}}L.closedBy=new L({deserialize:n=>n.split(" ")});L.openedBy=new L({deserialize:n=>n.split(" ")});L.group=new L({deserialize:n=>n.split(" ")});L.contextHash=new L({perNode:!0});L.lookAhead=new L({perNode:!0});L.mounted=new L({perNode:!0});class _d{constructor(e,t,i){this.tree=e,this.overlay=t,this.parser=i}}const Vd=Object.create(null);class xe{constructor(e,t,i,s=0){this.name=e,this.props=t,this.id=i,this.flags=s}static define(e){let t=e.props&&e.props.length?Object.create(null):Vd,i=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),s=new xe(e.name||"",t,e.id,i);if(e.props){for(let r of e.props)if(Array.isArray(r)||(r=r(s)),r){if(r[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[r[0].id]=r[1]}}return s}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop(L.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let i in e)for(let s of i.split(" "))t[s]=e[i];return i=>{for(let s=i.prop(L.group),r=-1;r<(s?s.length:0);r++){let o=t[r<0?i.name:s[r]];if(o)return o}}}}xe.none=new xe("",Object.create(null),0,8);class Lr{constructor(e){this.types=e;for(let t=0;t=s&&(o.type.isAnonymous||t(o)!==!1)){if(o.firstChild())continue;l=!0}for(;l&&i&&!o.type.isAnonymous&&i(o),!o.nextSibling();){if(!o.parent())return;l=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:_r(xe.none,this.children,this.positions,0,this.children.length,0,this.length,(t,i,s)=>new z(this.type,t,i,s,this.propValues),e.makeTree||((t,i,s)=>new z(xe.none,t,i,s)))}static build(e){return Hd(e)}}z.empty=new z(xe.none,[],[],0);class Ir{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new Ir(this.buffer,this.index)}}class Vt{constructor(e,t,i){this.buffer=e,this.length=t,this.set=i}get type(){return xe.none}toString(){let e=[];for(let t=0;t0));a=o[a+3]);return l}slice(e,t,i){let s=this.buffer,r=new Uint16Array(t-e),o=0;for(let l=e,a=0;l=e&&te;case 1:return t<=e&&i>e;case 2:return i>e;case 4:return!0}}function Eh(n,e){let t=n.childBefore(e);for(;t;){let i=t.lastChild;if(!i||i.to!=t.to)break;i.type.isError&&i.from==i.to?(n=t,t=i.prevSibling):t=i}return n}function ei(n,e,t,i){for(var s;n.from==n.to||(t<1?n.from>=e:n.from>e)||(t>-1?n.to<=e:n.to0?l.length:-1;e!=h;e+=t){let c=l[e],f=a[e]+o.from;if(Ph(s,i,f,f+c.length)){if(c instanceof Vt){if(r&ee.ExcludeBuffers)continue;let u=c.findChild(0,c.buffer.length,t,i-f,s);if(u>-1)return new Ye(new Fd(o,c,e,f),null,u)}else if(r&ee.IncludeAnonymous||!c.type.isAnonymous||Nr(c)){let u;if(!(r&ee.IgnoreMounts)&&c.props&&(u=c.prop(L.mounted))&&!u.overlay)return new _e(u.tree,f,e,o);let d=new _e(c,f,e,o);return r&ee.IncludeAnonymous||!d.type.isAnonymous?d:d.nextChild(t<0?c.children.length-1:0,t,i,s)}}}if(r&ee.IncludeAnonymous||!o.type.isAnonymous||(o.index>=0?e=o.index+t:e=t<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}enter(e,t,i=0){let s;if(!(i&ee.IgnoreOverlays)&&(s=this._tree.prop(L.mounted))&&s.overlay){let r=e-this.from;for(let{from:o,to:l}of s.overlay)if((t>0?o<=r:o=r:l>r))return new _e(s.tree,s.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,i)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}cursor(e=0){return new Ri(this,e)}get tree(){return this._tree}toTree(){return this._tree}resolve(e,t=0){return ei(this,e,t,!1)}resolveInner(e,t=0){return ei(this,e,t,!0)}enterUnfinishedNodesBefore(e){return Eh(this,e)}getChild(e,t=null,i=null){let s=On(this,e,t,i);return s.length?s[0]:null}getChildren(e,t=null,i=null){return On(this,e,t,i)}toString(){return this._tree.toString()}get node(){return this}matchContext(e){return Bn(this,e)}}function On(n,e,t,i){let s=n.cursor(),r=[];if(!s.firstChild())return r;if(t!=null){for(;!s.type.is(t);)if(!s.nextSibling())return r}for(;;){if(i!=null&&s.type.is(i))return r;if(s.type.is(e)&&r.push(s.node),!s.nextSibling())return i==null?r:[]}}function Bn(n,e,t=e.length-1){for(let i=n.parent;t>=0;i=i.parent){if(!i)return!1;if(!i.type.isAnonymous){if(e[t]&&e[t]!=i.name)return!1;t--}}return!0}class Fd{constructor(e,t,i,s){this.parent=e,this.buffer=t,this.index=i,this.start=s}}class Ye{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,i){this.context=e,this._parent=t,this.index=i,this.type=e.buffer.set.types[e.buffer.buffer[i]]}child(e,t,i){let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.context.start,i);return r<0?null:new Ye(this.context,this,r)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}enter(e,t,i=0){if(i&ee.ExcludeBuffers)return null;let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return r<0?null:new Ye(this.context,this,r)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new Ye(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new Ye(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}cursor(e=0){return new Ri(this,e)}get tree(){return null}toTree(){let e=[],t=[],{buffer:i}=this.context,s=this.index+4,r=i.buffer[this.index+3];if(r>s){let o=i.buffer[this.index+1];e.push(i.slice(s,r,o)),t.push(0)}return new z(this.type,e,t,this.to-this.from)}resolve(e,t=0){return ei(this,e,t,!1)}resolveInner(e,t=0){return ei(this,e,t,!0)}enterUnfinishedNodesBefore(e){return Eh(this,e)}toString(){return this.context.buffer.childString(this.index)}getChild(e,t=null,i=null){let s=On(this,e,t,i);return s.length?s[0]:null}getChildren(e,t=null,i=null){return On(this,e,t,i)}get node(){return this}matchContext(e){return Bn(this,e)}}class Ri{get name(){return this.type.name}constructor(e,t=0){if(this.mode=t,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,e instanceof _e)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let i=e._parent;i;i=i._parent)this.stack.unshift(i.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:i,buffer:s}=this.buffer;return this.type=t||s.set.types[s.buffer[e]],this.from=i+s.buffer[e+1],this.to=i+s.buffer[e+2],!0}yield(e){return e?e instanceof _e?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,i){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,i,this.mode));let{buffer:s}=this.buffer,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.buffer.start,i);return r<0?!1:(this.stack.push(this.index),this.yieldBuf(r))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,i=this.mode){return this.buffer?i&ee.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,i))}parent(){if(!this.buffer)return this.yieldNode(this.mode&ee.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&ee.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,i=this.stack.length-1;if(e<0){let s=i<0?0:this.stack[i]+4;if(this.index!=s)return this.yieldBuf(t.findChild(s,this.index,-1,0,4))}else{let s=t.buffer[this.index+3];if(s<(i<0?t.buffer.length:t.buffer[this.stack[i]+3]))return this.yieldBuf(s)}return i<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,i,{buffer:s}=this;if(s){if(e>0){if(this.index-1)for(let r=t+e,o=e<0?-1:i._tree.children.length;r!=o;r+=e){let l=i._tree.children[r];if(this.mode&ee.IncludeAnonymous||l instanceof Vt||!l.type.isAnonymous||Nr(l))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let o=e;o;o=o._parent)if(o.index==s){if(s==this.index)return o;t=o,i=r+1;break e}s=this.stack[--r]}for(let s=i;s=0;r--){if(r<0)return Bn(this.node,e,s);let o=i[t.buffer[this.stack[r]]];if(!o.isAnonymous){if(e[s]&&e[s]!=o.name)return!1;s--}}return!0}}function Nr(n){return n.children.some(e=>e instanceof Vt||!e.type.isAnonymous||Nr(e))}function Hd(n){var e;let{buffer:t,nodeSet:i,maxBufferLength:s=Id,reused:r=[],minRepeatType:o=i.types.length}=n,l=Array.isArray(t)?new Ir(t,t.length):t,a=i.types,h=0,c=0;function f(k,C,T,B,U){let{id:I,start:P,end:V,size:G}=l,Q=c;for(;G<0;)if(l.next(),G==-1){let J=r[I];T.push(J),B.push(P-k);return}else if(G==-3){h=I;return}else if(G==-4){c=I;return}else throw new RangeError(`Unrecognized record size: ${G}`);let M=a[I],$,Y,le=P-k;if(V-P<=s&&(Y=g(l.pos-C,U))){let J=new Uint16Array(Y.size-Y.skip),ie=l.pos-Y.size,nt=J.length;for(;l.pos>ie;)nt=y(Y.start,J,nt);$=new Vt(J,V-Y.start,i),le=Y.start-k}else{let J=l.pos-G;l.next();let ie=[],nt=[],vt=I>=o?I:-1,Ft=0,ji=V;for(;l.pos>J;)vt>=0&&l.id==vt&&l.size>=0?(l.end<=ji-s&&(d(ie,nt,P,Ft,l.end,ji,vt,Q),Ft=ie.length,ji=l.end),l.next()):f(P,J,ie,nt,vt);if(vt>=0&&Ft>0&&Ft-1&&Ft>0){let to=u(M);$=_r(M,ie,nt,0,ie.length,0,V-P,to,to)}else $=p(M,ie,nt,V-P,Q-V)}T.push($),B.push(le)}function u(k){return(C,T,B)=>{let U=0,I=C.length-1,P,V;if(I>=0&&(P=C[I])instanceof z){if(!I&&P.type==k&&P.length==B)return P;(V=P.prop(L.lookAhead))&&(U=T[I]+P.length+V)}return p(k,C,T,B,U)}}function d(k,C,T,B,U,I,P,V){let G=[],Q=[];for(;k.length>B;)G.push(k.pop()),Q.push(C.pop()+T-U);k.push(p(i.types[P],G,Q,I-U,V-I)),C.push(U-T)}function p(k,C,T,B,U=0,I){if(h){let P=[L.contextHash,h];I=I?[P].concat(I):[P]}if(U>25){let P=[L.lookAhead,U];I=I?[P].concat(I):[P]}return new z(k,C,T,B,I)}function g(k,C){let T=l.fork(),B=0,U=0,I=0,P=T.end-s,V={size:0,start:0,skip:0};e:for(let G=T.pos-k;T.pos>G;){let Q=T.size;if(T.id==C&&Q>=0){V.size=B,V.start=U,V.skip=I,I+=4,B+=4,T.next();continue}let M=T.pos-Q;if(Q<0||M=o?4:0,Y=T.start;for(T.next();T.pos>M;){if(T.size<0)if(T.size==-3)$+=4;else break e;else T.id>=o&&($+=4);T.next()}U=Y,B+=Q,I+=$}return(C<0||B==k)&&(V.size=B,V.start=U,V.skip=I),V.size>4?V:void 0}function y(k,C,T){let{id:B,start:U,end:I,size:P}=l;if(l.next(),P>=0&&B4){let G=l.pos-(P-4);for(;l.pos>G;)T=y(k,C,T)}C[--T]=V,C[--T]=I-k,C[--T]=U-k,C[--T]=B}else P==-3?h=B:P==-4&&(c=B);return T}let b=[],v=[];for(;l.pos>0;)f(n.start||0,n.bufferStart||0,b,v,-1);let S=(e=n.length)!==null&&e!==void 0?e:b.length?v[0]+b[0].length:0;return new z(a[n.topID],b.reverse(),v.reverse(),S)}const rl=new WeakMap;function gn(n,e){if(!n.isAnonymous||e instanceof Vt||e.type!=n)return 1;let t=rl.get(e);if(t==null){t=1;for(let i of e.children){if(i.type!=n||!(i instanceof z)){t=1;break}t+=gn(n,i)}rl.set(e,t)}return t}function _r(n,e,t,i,s,r,o,l,a){let h=0;for(let p=i;p=c)break;T+=B}if(S==k+1){if(T>c){let B=p[k];d(B.children,B.positions,0,B.children.length,g[k]+v);continue}f.push(p[k])}else{let B=g[S-1]+p[S-1].length-C;f.push(_r(n,p,g,k,S,C,B,null,a))}u.push(C+v-r)}}return d(e,t,i,s,0),(l||a)(f,u,o)}class iy{constructor(){this.map=new WeakMap}setBuffer(e,t,i){let s=this.map.get(e);s||this.map.set(e,s=new Map),s.set(t,i)}getBuffer(e,t){let i=this.map.get(e);return i&&i.get(t)}set(e,t){e instanceof Ye?this.setBuffer(e.context.buffer,e.index,t):e instanceof _e&&this.map.set(e.tree,t)}get(e){return e instanceof Ye?this.getBuffer(e.context.buffer,e.index):e instanceof _e?this.map.get(e.tree):void 0}cursorSet(e,t){e.buffer?this.setBuffer(e.buffer.buffer,e.index,t):this.map.set(e.tree,t)}cursorGet(e){return e.buffer?this.getBuffer(e.buffer.buffer,e.index):this.map.get(e.tree)}}class rt{constructor(e,t,i,s,r=!1,o=!1){this.from=e,this.to=t,this.tree=i,this.offset=s,this.open=(r?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],i=!1){let s=[new rt(0,e.length,e,0,!1,i)];for(let r of t)r.to>e.length&&s.push(r);return s}static applyChanges(e,t,i=128){if(!t.length)return e;let s=[],r=1,o=e.length?e[0]:null;for(let l=0,a=0,h=0;;l++){let c=l=i)for(;o&&o.from=u.from||f<=u.to||h){let d=Math.max(u.from,a)-h,p=Math.min(u.to,f)-h;u=d>=p?null:new rt(d,p,u.tree,u.offset+h,l>0,!!c)}if(u&&s.push(u),o.to>f)break;o=rnew Le(s.from,s.to)):[new Le(0,0)]:[new Le(0,e.length)],this.createParse(e,t||[],i)}parse(e,t,i){let s=this.startParse(e,t,i);for(;;){let r=s.advance();if(r)return r}}}class Wd{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}function ny(n){return(e,t,i,s)=>new qd(e,n,t,i,s)}class ol{constructor(e,t,i,s,r){this.parser=e,this.parse=t,this.overlay=i,this.target=s,this.ranges=r}}class zd{constructor(e,t,i,s,r,o,l){this.parser=e,this.predicate=t,this.mounts=i,this.index=s,this.start=r,this.target=o,this.prev=l,this.depth=0,this.ranges=[]}}const cr=new L({perNode:!0});class qd{constructor(e,t,i,s,r){this.nest=t,this.input=i,this.fragments=s,this.ranges=r,this.inner=[],this.innerDone=0,this.baseTree=null,this.stoppedAt=null,this.baseParse=e}advance(){if(this.baseParse){let i=this.baseParse.advance();if(!i)return null;if(this.baseParse=null,this.baseTree=i,this.startInner(),this.stoppedAt!=null)for(let s of this.inner)s.parse.stopAt(this.stoppedAt)}if(this.innerDone==this.inner.length){let i=this.baseTree;return this.stoppedAt!=null&&(i=new z(i.type,i.children,i.positions,i.length,i.propValues.concat([[cr,this.stoppedAt]]))),i}let e=this.inner[this.innerDone],t=e.parse.advance();if(t){this.innerDone++;let i=Object.assign(Object.create(null),e.target.props);i[L.mounted.id]=new _d(t,e.overlay,e.parser),e.target.props=i}return null}get parsedPos(){if(this.baseParse)return 0;let e=this.input.length;for(let t=this.innerDone;tc.frag.from<=s.from&&c.frag.to>=s.to&&c.mount.overlay);if(h)for(let c of h.mount.overlay){let f=c.from+h.pos,u=c.to+h.pos;f>=s.from&&u<=s.to&&!t.ranges.some(d=>d.fromf)&&t.ranges.push({from:f,to:u})}}l=!1}else if(i&&(o=jd(i.ranges,s.from,s.to)))l=o!=2;else if(!s.type.isAnonymous&&s.fromnew Le(f.from-s.from,f.to-s.from)):null,s.tree,c)),r.overlay?c.length&&(i={ranges:c,depth:0,prev:i}):l=!1}}else t&&(a=t.predicate(s))&&(a===!0&&(a=new Le(s.from,s.to)),a.fromnew Le(c.from-t.start,c.to-t.start)),t.target,h)),t=t.prev}i&&!--i.depth&&(i=i.prev)}}}}function jd(n,e,t){for(let i of n){if(i.from>=t)break;if(i.to>e)return i.from<=e&&i.to>=t?2:1}return 0}function ll(n,e,t,i,s,r){if(e=e.to);i++);let o=s.children[i],l=o.buffer;function a(h,c,f,u,d){let p=h;for(;l[p+2]+r<=e.from;)p=l[p+3];let g=[],y=[];ll(o,h,p,g,y,u);let b=l[p+1],v=l[p+2],S=b+r==e.from&&v+r==e.to&&l[p]==e.type.id;return g.push(S?e.toTree():a(p+4,l[p+3],o.set.types[l[p]],b,v-b)),y.push(b-u),ll(o,l[p+3],c,g,y,u),new z(f,g,y,d)}s.children[i]=a(0,l.length,xe.none,0,o.length);for(let h=0;h<=t;h++)n.childAfter(e.from)}class al{constructor(e,t){this.offset=t,this.done=!1,this.cursor=e.cursor(ee.IncludeAnonymous|ee.IgnoreMounts)}moveTo(e){let{cursor:t}=this,i=e-this.offset;for(;!this.done&&t.from=e&&t.enter(i,1,ee.IgnoreOverlays|ee.ExcludeBuffers)||t.next(!1)||(this.done=!0)}hasNode(e){if(this.moveTo(e.from),!this.done&&this.cursor.from+this.offset==e.from&&this.cursor.tree)for(let t=this.cursor.tree;;){if(t==e.tree)return!0;if(t.children.length&&t.positions[0]==0&&t.children[0]instanceof z)t=t.children[0];else break}return!1}}class Ud{constructor(e){var t;if(this.fragments=e,this.curTo=0,this.fragI=0,e.length){let i=this.curFrag=e[0];this.curTo=(t=i.tree.prop(cr))!==null&&t!==void 0?t:i.to,this.inner=new al(i.tree,-i.offset)}else this.curFrag=this.inner=null}hasNode(e){for(;this.curFrag&&e.from>=this.curTo;)this.nextFrag();return this.curFrag&&this.curFrag.from<=e.from&&this.curTo>=e.to&&this.inner.hasNode(e)}nextFrag(){var e;if(this.fragI++,this.fragI==this.fragments.length)this.curFrag=this.inner=null;else{let t=this.curFrag=this.fragments[this.fragI];this.curTo=(e=t.tree.prop(cr))!==null&&e!==void 0?e:t.to,this.inner=new al(t.tree,-t.offset)}}findMounts(e,t){var i;let s=[];if(this.inner){this.inner.cursor.moveTo(e,1);for(let r=this.inner.cursor.node;r;r=r.parent){let o=(i=r.tree)===null||i===void 0?void 0:i.prop(L.mounted);if(o&&o.parser==t)for(let l=this.fragI;l=r.to)break;a.tree==this.curFrag.tree&&s.push({frag:a,pos:r.from-a.offset,mount:o})}}}return s}}function hl(n,e){let t=null,i=e;for(let s=1,r=0;s=l)break;a.to<=o||(t||(i=t=e.slice()),a.froml&&t.splice(r+1,0,new Le(l,a.to))):a.to>l?t[r--]=new Le(l,a.to):t.splice(r--,1))}}return i}function Gd(n,e,t,i){let s=0,r=0,o=!1,l=!1,a=-1e9,h=[];for(;;){let c=s==n.length?1e9:o?n[s].to:n[s].from,f=r==e.length?1e9:l?e[r].to:e[r].from;if(o!=l){let u=Math.max(a,t),d=Math.min(c,f,i);unew Le(u.from+i,u.to+i)),f=Gd(e,c,a,h);for(let u=0,d=a;;u++){let p=u==f.length,g=p?h:f[u].from;if(g>d&&t.push(new rt(d,g,s.tree,-o,r.from>=d||r.openStart,r.to<=g||r.openEnd)),p)break;d=f[u].to}}else t.push(new rt(a,h,s.tree,-o,r.from>=o||r.openStart,r.to<=l||r.openEnd))}return t}let $d=0;class Ge{constructor(e,t,i){this.set=e,this.base=t,this.modified=i,this.id=$d++}static define(e){if(e?.base)throw new Error("Can not derive from a modified tag");let t=new Ge([],null,[]);if(t.set.push(t),e)for(let i of e.set)t.set.push(i);return t}static defineModifier(){let e=new Pn;return t=>t.modified.indexOf(e)>-1?t:Pn.get(t.base||t,t.modified.concat(e).sort((i,s)=>i.id-s.id))}}let Jd=0;class Pn{constructor(){this.instances=[],this.id=Jd++}static get(e,t){if(!t.length)return e;let i=t[0].instances.find(l=>l.base==e&&Yd(t,l.modified));if(i)return i;let s=[],r=new Ge(s,e,t);for(let l of t)l.instances.push(r);let o=Xd(t);for(let l of e.set)if(!l.modified.length)for(let a of o)s.push(Pn.get(l,a));return r}}function Yd(n,e){return n.length==e.length&&n.every((t,i)=>t==e[i])}function Xd(n){let e=[[]];for(let t=0;ti.length-t.length)}function Zd(n){let e=Object.create(null);for(let t in n){let i=n[t];Array.isArray(i)||(i=[i]);for(let s of t.split(" "))if(s){let r=[],o=2,l=s;for(let f=0;;){if(l=="..."&&f>0&&f+3==s.length){o=1;break}let u=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(l);if(!u)throw new RangeError("Invalid path: "+s);if(r.push(u[0]=="*"?"":u[0][0]=='"'?JSON.parse(u[0]):u[0]),f+=u[0].length,f==s.length)break;let d=s[f++];if(f==s.length&&d=="!"){o=0;break}if(d!="/")throw new RangeError("Invalid path: "+s);l=s.slice(f)}let a=r.length-1,h=r[a];if(!h)throw new RangeError("Invalid path: "+s);let c=new En(i,o,a>0?r.slice(0,a):null);e[h]=c.sort(e[h])}}return Lh.add(e)}const Lh=new L;class En{constructor(e,t,i,s){this.tags=e,this.mode=t,this.context=i,this.next=s}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth{let o=s;for(let l of r)for(let a of l.set){let h=t[a.id];if(h){o=o?o+" "+h:h;break}}return o},scope:i}}function Qd(n,e){let t=null;for(let i of n){let s=i.style(e);s&&(t=t?t+" "+s:s)}return t}function ep(n,e,t,i=0,s=n.length){let r=new tp(i,Array.isArray(e)?e:[e],t);r.highlightRange(n.cursor(),i,s,"",r.highlighters),r.flush(s)}class tp{constructor(e,t,i){this.at=e,this.highlighters=t,this.span=i,this.class=""}startSpan(e,t){t!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=t)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,t,i,s,r){let{type:o,from:l,to:a}=e;if(l>=i||a<=t)return;o.isTop&&(r=this.highlighters.filter(d=>!d.scope||d.scope(o)));let h=s,c=ip(e)||En.empty,f=Qd(r,c.tags);if(f&&(h&&(h+=" "),h+=f,c.mode==1&&(s+=(s?" ":"")+f)),this.startSpan(e.from,h),c.opaque)return;let u=e.tree&&e.tree.prop(L.mounted);if(u&&u.overlay){let d=e.node.enter(u.overlay[0].from+l,1),p=this.highlighters.filter(y=>!y.scope||y.scope(u.tree.type)),g=e.firstChild();for(let y=0,b=l;;y++){let v=y=S||!e.nextSibling())););if(!v||S>i)break;b=v.to+l,b>t&&(this.highlightRange(d.cursor(),Math.max(t,v.from+l),Math.min(i,b),s,p),this.startSpan(b,h))}g&&e.parent()}else if(e.firstChild()){do if(!(e.to<=t)){if(e.from>=i)break;this.highlightRange(e,t,i,s,r),this.startSpan(Math.min(i,e.to),h)}while(e.nextSibling());e.parent()}}}function ip(n){let e=n.type.prop(Lh);for(;e&&e.context&&!n.matchContext(e.context);)e=e.next;return e||null}const x=Ge.define,nn=x(),ot=x(),fl=x(ot),ul=x(ot),lt=x(),sn=x(lt),ps=x(lt),Ke=x(),xt=x(Ke),qe=x(),je=x(),fr=x(),ui=x(fr),rn=x(),m={comment:nn,lineComment:x(nn),blockComment:x(nn),docComment:x(nn),name:ot,variableName:x(ot),typeName:fl,tagName:x(fl),propertyName:ul,attributeName:x(ul),className:x(ot),labelName:x(ot),namespace:x(ot),macroName:x(ot),literal:lt,string:sn,docString:x(sn),character:x(sn),attributeValue:x(sn),number:ps,integer:x(ps),float:x(ps),bool:x(lt),regexp:x(lt),escape:x(lt),color:x(lt),url:x(lt),keyword:qe,self:x(qe),null:x(qe),atom:x(qe),unit:x(qe),modifier:x(qe),operatorKeyword:x(qe),controlKeyword:x(qe),definitionKeyword:x(qe),moduleKeyword:x(qe),operator:je,derefOperator:x(je),arithmeticOperator:x(je),logicOperator:x(je),bitwiseOperator:x(je),compareOperator:x(je),updateOperator:x(je),definitionOperator:x(je),typeOperator:x(je),controlOperator:x(je),punctuation:fr,separator:x(fr),bracket:ui,angleBracket:x(ui),squareBracket:x(ui),paren:x(ui),brace:x(ui),content:Ke,heading:xt,heading1:x(xt),heading2:x(xt),heading3:x(xt),heading4:x(xt),heading5:x(xt),heading6:x(xt),contentSeparator:x(Ke),list:x(Ke),quote:x(Ke),emphasis:x(Ke),strong:x(Ke),link:x(Ke),monospace:x(Ke),strikethrough:x(Ke),inserted:x(),deleted:x(),changed:x(),invalid:x(),meta:rn,documentMeta:x(rn),annotation:x(rn),processingInstruction:x(rn),definition:Ge.defineModifier(),constant:Ge.defineModifier(),function:Ge.defineModifier(),standard:Ge.defineModifier(),local:Ge.defineModifier(),special:Ge.defineModifier()};Ih([{tag:m.link,class:"tok-link"},{tag:m.heading,class:"tok-heading"},{tag:m.emphasis,class:"tok-emphasis"},{tag:m.strong,class:"tok-strong"},{tag:m.keyword,class:"tok-keyword"},{tag:m.atom,class:"tok-atom"},{tag:m.bool,class:"tok-bool"},{tag:m.url,class:"tok-url"},{tag:m.labelName,class:"tok-labelName"},{tag:m.inserted,class:"tok-inserted"},{tag:m.deleted,class:"tok-deleted"},{tag:m.literal,class:"tok-literal"},{tag:m.string,class:"tok-string"},{tag:m.number,class:"tok-number"},{tag:[m.regexp,m.escape,m.special(m.string)],class:"tok-string2"},{tag:m.variableName,class:"tok-variableName"},{tag:m.local(m.variableName),class:"tok-variableName tok-local"},{tag:m.definition(m.variableName),class:"tok-variableName tok-definition"},{tag:m.special(m.variableName),class:"tok-variableName2"},{tag:m.definition(m.propertyName),class:"tok-propertyName tok-definition"},{tag:m.typeName,class:"tok-typeName"},{tag:m.namespace,class:"tok-namespace"},{tag:m.className,class:"tok-className"},{tag:m.macroName,class:"tok-macroName"},{tag:m.propertyName,class:"tok-propertyName"},{tag:m.operator,class:"tok-operator"},{tag:m.comment,class:"tok-comment"},{tag:m.meta,class:"tok-meta"},{tag:m.invalid,class:"tok-invalid"},{tag:m.punctuation,class:"tok-punctuation"}]);var ms;const Dt=new L;function Nh(n){return D.define({combine:n?e=>e.concat(n):void 0})}const np=new L;class Ie{constructor(e,t,i=[],s=""){this.data=e,this.name=s,N.prototype.hasOwnProperty("tree")||Object.defineProperty(N.prototype,"tree",{get(){return pe(this)}}),this.parser=t,this.extension=[wt.of(this),N.languageData.of((r,o,l)=>{let a=dl(r,o,l),h=a.type.prop(Dt);if(!h)return[];let c=r.facet(h),f=a.type.prop(np);if(f){let u=a.resolve(o-a.from,l);for(let d of f)if(d.test(u,r)){let p=r.facet(d.facet);return d.type=="replace"?p:p.concat(c)}}return c})].concat(i)}isActiveAt(e,t,i=-1){return dl(e,t,i).type.prop(Dt)==this.data}findRegions(e){let t=e.facet(wt);if(t?.data==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let i=[],s=(r,o)=>{if(r.prop(Dt)==this.data){i.push({from:o,to:o+r.length});return}let l=r.prop(L.mounted);if(l){if(l.tree.prop(Dt)==this.data){if(l.overlay)for(let a of l.overlay)i.push({from:a.from+o,to:a.to+o});else i.push({from:o,to:o+r.length});return}else if(l.overlay){let a=i.length;if(s(l.tree,l.overlay[0].from+o),i.length>a)return}}for(let a=0;ai.isTop?t:void 0)]}),e.name)}configure(e,t){return new ur(this.data,this.parser.configure(e),t||this.name)}get allowsNesting(){return this.parser.hasWrappers()}}function pe(n){let e=n.field(Ie.state,!1);return e?e.tree:z.empty}class sp{constructor(e){this.doc=e,this.cursorPos=0,this.string="",this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,t){let i=this.cursorPos-this.string.length;return e=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-i,t-i)}}let di=null;class ti{constructor(e,t,i=[],s,r,o,l,a){this.parser=e,this.state=t,this.fragments=i,this.tree=s,this.treeLen=r,this.viewport=o,this.skipped=l,this.scheduleOn=a,this.parse=null,this.tempSkipped=[]}static create(e,t,i){return new ti(e,t,[],z.empty,0,i,[],null)}startParse(){return this.parser.startParse(new sp(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=z.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var i;if(typeof e=="number"){let s=Date.now()+e;e=()=>Date.now()>s}for(this.parse||(this.parse=this.startParse()),t!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&t=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(t=this.parse.advance()););}),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped(rt.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=di;di=this;try{return e()}finally{di=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=pl(e,t.from,t.to);return e}changes(e,t){let{fragments:i,tree:s,treeLen:r,viewport:o,skipped:l}=this;if(this.takeTree(),!e.empty){let a=[];if(e.iterChangedRanges((h,c,f,u)=>a.push({fromA:h,toA:c,fromB:f,toB:u})),i=rt.applyChanges(i,a),s=z.empty,r=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){l=[];for(let h of this.skipped){let c=e.mapPos(h.from,1),f=e.mapPos(h.to,-1);ce.from&&(this.fragments=pl(this.fragments,s,r),this.skipped.splice(i--,1))}return this.skipped.length>=t?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends Rh{createParse(t,i,s){let r=s[0].from,o=s[s.length-1].to;return{parsedPos:r,advance(){let a=di;if(a){for(let h of s)a.tempSkipped.push(h);e&&(a.scheduleOn=a.scheduleOn?Promise.all([a.scheduleOn,e]):e)}return this.parsedPos=o,new z(xe.none,[],[],o-r)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&t[0].from==0&&t[0].to>=e}static get(){return di}}function pl(n,e,t){return rt.applyChanges(n,[{fromA:e,toA:t,fromB:e,toB:t}])}class ii{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let t=this.context.changes(e.changes,e.state),i=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,i)||t.takeTree(),new ii(t)}static init(e){let t=Math.min(3e3,e.doc.length),i=ti.create(e.facet(wt).parser,e,{from:0,to:t});return i.work(20,t)||i.takeTree(),new ii(i)}}Ie.state=Me.define({create:ii.init,update(n,e){for(let t of e.effects)if(t.is(Ie.setState))return t.value;return e.startState.facet(wt)!=e.state.facet(wt)?ii.init(e.state):n.apply(e)}});let _h=n=>{let e=setTimeout(()=>n(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(_h=n=>{let e=-1,t=setTimeout(()=>{e=requestIdleCallback(n,{timeout:500-100})},100);return()=>e<0?clearTimeout(t):cancelIdleCallback(e)});const gs=typeof navigator<"u"&&(!((ms=navigator.scheduling)===null||ms===void 0)&&ms.isInputPending)?()=>navigator.scheduling.isInputPending():null,rp=be.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(Ie.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),e.docChanged&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(Ie.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=_h(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEnds+1e3,a=r.context.work(()=>gs&&gs()||Date.now()>o,s+(l?0:1e5));this.chunkBudget-=Date.now()-t,(a||this.chunkBudget<=0)&&(r.context.takeTree(),this.view.dispatch({effects:Ie.setState.of(new ii(r.context))})),this.chunkBudget>0&&!(a&&!l)&&this.scheduleWork(),this.checkAsyncSchedule(r.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(t=>He(this.view.state,t)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),wt=D.define({combine(n){return n.length?n[0]:null},enables:n=>[Ie.state,rp,O.contentAttributes.compute([n],e=>{let t=e.facet(n);return t&&t.name?{"data-language":t.name}:{}})]});class ry{constructor(e,t=[]){this.language=e,this.support=t,this.extension=[e,t]}}class Vh{constructor(e,t,i,s,r,o=void 0){this.name=e,this.alias=t,this.extensions=i,this.filename=s,this.loadFunc=r,this.support=o,this.loading=null}load(){return this.loading||(this.loading=this.loadFunc().then(e=>this.support=e,e=>{throw this.loading=null,e}))}static of(e){let{load:t,support:i}=e;if(!t){if(!i)throw new RangeError("Must pass either 'load' or 'support' to LanguageDescription.of");t=()=>Promise.resolve(i)}return new Vh(e.name,(e.alias||[]).concat(e.name).map(s=>s.toLowerCase()),e.extensions||[],e.filename,t,i)}static matchFilename(e,t){for(let s of e)if(s.filename&&s.filename.test(t))return s;let i=/\.([^.]+)$/.exec(t);if(i){for(let s of e)if(s.extensions.indexOf(i[1])>-1)return s}return null}static matchLanguageName(e,t,i=!0){t=t.toLowerCase();for(let s of e)if(s.alias.some(r=>r==t))return s;if(i)for(let s of e)for(let r of s.alias){let o=t.indexOf(r);if(o>-1&&(r.length>2||!/\w/.test(t[o-1])&&!/\w/.test(t[o+r.length])))return s}return null}}const Fh=D.define(),jn=D.define({combine:n=>{if(!n.length)return" ";let e=n[0];if(!e||/\S/.test(e)||Array.from(e).some(t=>t!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(n[0]));return e}});function Rt(n){let e=n.facet(jn);return e.charCodeAt(0)==9?n.tabSize*e.length:e.length}function Li(n,e){let t="",i=n.tabSize,s=n.facet(jn)[0];if(s==" "){for(;e>=i;)t+=" ",e-=i;s=" "}for(let r=0;r=i.from&&s<=i.to?r&&s==e?{text:"",from:e}:(t<0?s-1&&(r+=o-this.countColumn(i,i.search(/\S|$/))),r}countColumn(e,t=e.length){return Fi(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:i,from:s}=this.lineAt(e,t),r=this.options.overrideIndentation;if(r){let o=r(s);if(o>-1)return o}return this.countColumn(i,i.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}}const op=new L;function lp(n,e,t){return Hh(e.resolveInner(t).enterUnfinishedNodesBefore(t),t,n)}function ap(n){return n.pos==n.options.simulateBreak&&n.options.simulateDoubleBreak}function hp(n){let e=n.type.prop(op);if(e)return e;let t=n.firstChild,i;if(t&&(i=t.type.prop(L.closedBy))){let s=n.lastChild,r=s&&i.indexOf(s.name)>-1;return o=>Wh(o,!0,1,void 0,r&&!ap(o)?s.from:void 0)}return n.parent==null?cp:null}function Hh(n,e,t){for(;n;n=n.parent){let i=hp(n);if(i)return i(Fr.create(t,e,n))}return null}function cp(){return 0}class Fr extends Kn{constructor(e,t,i){super(e.state,e.options),this.base=e,this.pos=t,this.node=i}static create(e,t,i){return new Fr(e,t,i)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){let e=this.state.doc.lineAt(this.node.from);for(;;){let t=this.node.resolve(e.from);for(;t.parent&&t.parent.from==t.from;)t=t.parent;if(fp(t,this.node))break;e=this.state.doc.lineAt(t.from)}return this.lineIndent(e.from)}continue(){let e=this.node.parent;return e?Hh(e,this.pos,this.base):0}}function fp(n,e){for(let t=e;t;t=t.parent)if(n==t)return!0;return!1}function up(n){let e=n.node,t=e.childAfter(e.from),i=e.lastChild;if(!t)return null;let s=n.options.simulateBreak,r=n.state.doc.lineAt(t.from),o=s==null||s<=r.from?r.to:Math.min(r.to,s);for(let l=t.to;;){let a=e.childAfter(l);if(!a||a==i)return null;if(!a.type.isSkipped)return a.fromWh(i,e,t,n)}function Wh(n,e,t,i,s){let r=n.textAfter,o=r.match(/^\s*/)[0].length,l=i&&r.slice(o,o+i.length)==i||s==n.pos+o,a=e?up(n):null;return a?l?n.column(a.from):n.column(a.to):n.baseIndent+(l?0:n.unit*t)}const ly=n=>n.baseIndent;function ay({except:n,units:e=1}={}){return t=>{let i=n&&n.test(t.textAfter);return t.baseIndent+(i?0:e*t.unit)}}const dp=200;function pp(){return N.transactionFilter.of(n=>{if(!n.docChanged||!n.isUserEvent("input.type")&&!n.isUserEvent("input.complete"))return n;let e=n.startState.languageDataAt("indentOnInput",n.startState.selection.main.head);if(!e.length)return n;let t=n.newDoc,{head:i}=n.newSelection.main,s=t.lineAt(i);if(i>s.from+dp)return n;let r=t.sliceString(s.from,i);if(!e.some(h=>h.test(r)))return n;let{state:o}=n,l=-1,a=[];for(let{head:h}of o.selection.ranges){let c=o.doc.lineAt(h);if(c.from==l)continue;l=c.from;let f=Vr(o,c.from);if(f==null)continue;let u=/^\s*/.exec(c.text)[0],d=Li(o,f);u!=d&&a.push({from:c.from,to:c.from+u.length,insert:d})}return a.length?[n,{changes:a,sequential:!0}]:n})}const mp=D.define(),gp=new L;function hy(n){let e=n.firstChild,t=n.lastChild;return e&&e.tot)continue;if(r&&o.from=e&&a.to>t&&(r=a)}}return r}function bp(n){let e=n.lastChild;return e&&e.to==n.to&&e.type.isError}function Rn(n,e,t){for(let i of n.facet(mp)){let s=i(n,e,t);if(s)return s}return yp(n,e,t)}function zh(n,e){let t=e.mapPos(n.from,1),i=e.mapPos(n.to,-1);return t>=i?void 0:{from:t,to:i}}const Un=R.define({map:zh}),Wi=R.define({map:zh});function qh(n){let e=[];for(let{head:t}of n.state.selection.ranges)e.some(i=>i.from<=t&&i.to>=t)||e.push(n.lineBlockAt(t));return e}const Lt=Me.define({create(){return E.none},update(n,e){n=n.map(e.changes);for(let t of e.effects)t.is(Un)&&!wp(n,t.value.from,t.value.to)?n=n.update({add:[ml.range(t.value.from,t.value.to)]}):t.is(Wi)&&(n=n.update({filter:(i,s)=>t.value.from!=i||t.value.to!=s,filterFrom:t.value.from,filterTo:t.value.to}));if(e.selection){let t=!1,{head:i}=e.selection.main;n.between(i,i,(s,r)=>{si&&(t=!0)}),t&&(n=n.update({filterFrom:i,filterTo:i,filter:(s,r)=>r<=i||s>=i}))}return n},provide:n=>O.decorations.from(n),toJSON(n,e){let t=[];return n.between(0,e.doc.length,(i,s)=>{t.push(i,s)}),t},fromJSON(n){if(!Array.isArray(n)||n.length%2)throw new RangeError("Invalid JSON for fold state");let e=[];for(let t=0;t{(!s||s.from>r)&&(s={from:r,to:o})}),s}function wp(n,e,t){let i=!1;return n.between(e,e,(s,r)=>{s==e&&r==t&&(i=!0)}),i}function jh(n,e){return n.field(Lt,!1)?e:e.concat(R.appendConfig.of(Gh()))}const kp=n=>{for(let e of qh(n)){let t=Rn(n.state,e.from,e.to);if(t)return n.dispatch({effects:jh(n.state,[Un.of(t),Kh(n,t)])}),!0}return!1},vp=n=>{if(!n.state.field(Lt,!1))return!1;let e=[];for(let t of qh(n)){let i=Ln(n.state,t.from,t.to);i&&e.push(Wi.of(i),Kh(n,i,!1))}return e.length&&n.dispatch({effects:e}),e.length>0};function Kh(n,e,t=!0){let i=n.state.doc.lineAt(e.from).number,s=n.state.doc.lineAt(e.to).number;return O.announce.of(`${n.state.phrase(t?"Folded lines":"Unfolded lines")} ${i} ${n.state.phrase("to")} ${s}.`)}const xp=n=>{let{state:e}=n,t=[];for(let i=0;i{let e=n.state.field(Lt,!1);if(!e||!e.size)return!1;let t=[];return e.between(0,n.state.doc.length,(i,s)=>{t.push(Wi.of({from:i,to:s}))}),n.dispatch({effects:t}),!0},Cp=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:kp},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:vp},{key:"Ctrl-Alt-[",run:xp},{key:"Ctrl-Alt-]",run:Sp}],Ap={placeholderDOM:null,placeholderText:"…"},Uh=D.define({combine(n){return _t(n,Ap)}});function Gh(n){let e=[Lt,Tp];return n&&e.push(Uh.of(n)),e}const ml=E.replace({widget:new class extends tt{toDOM(n){let{state:e}=n,t=e.facet(Uh),i=r=>{let o=n.lineBlockAt(n.posAtDOM(r.target)),l=Ln(n.state,o.from,o.to);l&&n.dispatch({effects:Wi.of(l)}),r.preventDefault()};if(t.placeholderDOM)return t.placeholderDOM(n,i);let s=document.createElement("span");return s.textContent=t.placeholderText,s.setAttribute("aria-label",e.phrase("folded code")),s.title=e.phrase("unfold"),s.className="cm-foldPlaceholder",s.onclick=i,s}}}),Mp={openText:"⌄",closedText:"›",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1};class ys extends bt{constructor(e,t){super(),this.config=e,this.open=t}eq(e){return this.config==e.config&&this.open==e.open}toDOM(e){if(this.config.markerDOM)return this.config.markerDOM(this.open);let t=document.createElement("span");return t.textContent=this.open?this.config.openText:this.config.closedText,t.title=e.state.phrase(this.open?"Fold line":"Unfold line"),t}}function Dp(n={}){let e=Object.assign(Object.assign({},Mp),n),t=new ys(e,!0),i=new ys(e,!1),s=be.fromClass(class{constructor(o){this.from=o.viewport.from,this.markers=this.buildMarkers(o)}update(o){(o.docChanged||o.viewportChanged||o.startState.facet(wt)!=o.state.facet(wt)||o.startState.field(Lt,!1)!=o.state.field(Lt,!1)||pe(o.startState)!=pe(o.state)||e.foldingChanged(o))&&(this.markers=this.buildMarkers(o.view))}buildMarkers(o){let l=new Pt;for(let a of o.viewportLineBlocks){let h=Ln(o.state,a.from,a.to)?i:Rn(o.state,a.from,a.to)?t:null;h&&l.add(a.from,a.from,h)}return l.finish()}}),{domEventHandlers:r}=e;return[s,Td({class:"cm-foldGutter",markers(o){var l;return((l=o.plugin(s))===null||l===void 0?void 0:l.markers)||F.empty},initialSpacer(){return new ys(e,!1)},domEventHandlers:Object.assign(Object.assign({},r),{click:(o,l,a)=>{if(r.click&&r.click(o,l,a))return!0;let h=Ln(o.state,l.from,l.to);if(h)return o.dispatch({effects:Wi.of(h)}),!0;let c=Rn(o.state,l.from,l.to);return c?(o.dispatch({effects:Un.of(c)}),!0):!1}})}),Gh()]}const Tp=O.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}});class li{constructor(e,t){this.specs=e;let i;function s(l){let a=mt.newName();return(i||(i=Object.create(null)))["."+a]=l,a}const r=typeof t.all=="string"?t.all:t.all?s(t.all):void 0,o=t.scope;this.scope=o instanceof Ie?l=>l.prop(Dt)==o.data:o?l=>l==o:void 0,this.style=Ih(e.map(l=>({tag:l.tag,class:l.class||s(Object.assign({},l,{tag:null}))})),{all:r}).style,this.module=i?new mt(i):null,this.themeType=t.themeType}static define(e,t){return new li(e,t||{})}}const dr=D.define(),$h=D.define({combine(n){return n.length?[n[0]]:null}});function bs(n){let e=n.facet(dr);return e.length?e:n.facet($h)}function Hr(n,e){let t=[Bp],i;return n instanceof li&&(n.module&&t.push(O.styleModule.of(n.module)),i=n.themeType),e?.fallback?t.push($h.of(n)):i?t.push(dr.computeN([O.darkTheme],s=>s.facet(O.darkTheme)==(i=="dark")?[n]:[])):t.push(dr.of(n)),t}class Op{constructor(e){this.markCache=Object.create(null),this.tree=pe(e.state),this.decorations=this.buildDeco(e,bs(e.state))}update(e){let t=pe(e.state),i=bs(e.state),s=i!=bs(e.startState);t.length{i.add(o,l,this.markCache[a]||(this.markCache[a]=E.mark({class:a})))},s,r);return i.finish()}}const Bp=Vi.high(be.fromClass(Op,{decorations:n=>n.decorations})),Pp=li.define([{tag:m.meta,color:"#404740"},{tag:m.link,textDecoration:"underline"},{tag:m.heading,textDecoration:"underline",fontWeight:"bold"},{tag:m.emphasis,fontStyle:"italic"},{tag:m.strong,fontWeight:"bold"},{tag:m.strikethrough,textDecoration:"line-through"},{tag:m.keyword,color:"#708"},{tag:[m.atom,m.bool,m.url,m.contentSeparator,m.labelName],color:"#219"},{tag:[m.literal,m.inserted],color:"#164"},{tag:[m.string,m.deleted],color:"#a11"},{tag:[m.regexp,m.escape,m.special(m.string)],color:"#e40"},{tag:m.definition(m.variableName),color:"#00f"},{tag:m.local(m.variableName),color:"#30a"},{tag:[m.typeName,m.namespace],color:"#085"},{tag:m.className,color:"#167"},{tag:[m.special(m.variableName),m.macroName],color:"#256"},{tag:m.definition(m.propertyName),color:"#00c"},{tag:m.comment,color:"#940"},{tag:m.invalid,color:"#f00"}]),Ep=1e4,Rp="()[]{}",Lp=new L;function pr(n,e,t){let i=n.prop(e<0?L.openedBy:L.closedBy);if(i)return i;if(n.name.length==1){let s=t.indexOf(n.name);if(s>-1&&s%2==(e<0?1:0))return[t[s+e]]}return null}function mr(n){let e=n.type.prop(Lp);return e?e(n.node):n}function qt(n,e,t,i={}){let s=i.maxScanDistance||Ep,r=i.brackets||Rp,o=pe(n),l=o.resolveInner(e,t);for(let a=l;a;a=a.parent){let h=pr(a.type,t,r);if(h&&a.from0?e>=c.from&&ec.from&&e<=c.to))return Ip(n,e,t,a,c,h,r)}}return Np(n,e,t,o,l.type,s,r)}function Ip(n,e,t,i,s,r,o){let l=i.parent,a={from:s.from,to:s.to},h=0,c=l?.cursor();if(c&&(t<0?c.childBefore(i.from):c.childAfter(i.to)))do if(t<0?c.to<=i.from:c.from>=i.to){if(h==0&&r.indexOf(c.type.name)>-1&&c.from0)return null;let h={from:t<0?e-1:e,to:t>0?e+1:e},c=n.doc.iterRange(e,t>0?n.doc.length:0),f=0;for(let u=0;!c.next().done&&u<=r;){let d=c.value;t<0&&(u+=d.length);let p=e+u*t;for(let g=t>0?0:d.length-1,y=t>0?d.length:-1;g!=y;g+=t){let b=o.indexOf(d[g]);if(!(b<0||i.resolveInner(p+g,1).type!=s))if(b%2==0==t>0)f++;else{if(f==1)return{start:h,end:{from:p+g,to:p+g+1},matched:b>>1==a>>1};f--}}t>0&&(u+=d.length)}return c.done?{start:h,matched:!1}:null}function gl(n,e,t,i=0,s=0){e==null&&(e=n.search(/[^\s\u00a0]/),e==-1&&(e=n.length));let r=s;for(let o=i;o=this.string.length}sol(){return this.pos==0}peek(){return this.string.charAt(this.pos)||void 0}next(){if(this.post}eatSpace(){let e=this.pos;for(;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e}skipToEnd(){this.pos=this.string.length}skipTo(e){let t=this.string.indexOf(e,this.pos);if(t>-1)return this.pos=t,!0}backUp(e){this.pos-=e}column(){return this.lastColumnPosi?o.toLowerCase():o,r=this.string.substr(this.pos,e.length);return s(r)==s(e)?(t!==!1&&(this.pos+=e.length),!0):null}else{let s=this.string.slice(this.pos).match(e);return s&&s.index>0?null:(s&&t!==!1&&(this.pos+=s[0].length),s)}}current(){return this.string.slice(this.start,this.pos)}}function _p(n){return{name:n.name||"",token:n.token,blankLine:n.blankLine||(()=>{}),startState:n.startState||(()=>!0),copyState:n.copyState||Vp,indent:n.indent||(()=>null),languageData:n.languageData||{},tokenTable:n.tokenTable||zr}}function Vp(n){if(typeof n!="object")return n;let e={};for(let t in n){let i=n[t];e[t]=i instanceof Array?i.slice():i}return e}const yl=new WeakMap;class jt extends Ie{constructor(e){let t=Nh(e.languageData),i=_p(e),s,r=new class extends Rh{createParse(o,l,a){return new Hp(s,o,l,a)}};super(t,r,[Fh.of((o,l)=>this.getIndent(o,l))],e.name),this.topNode=qp(t),s=this,this.streamParser=i,this.stateAfter=new L({perNode:!0}),this.tokenTable=e.tokenTable?new Qh(i.tokenTable):zp}static define(e){return new jt(e)}getIndent(e,t){let i=pe(e.state),s=i.resolve(t);for(;s&&s.type!=this.topNode;)s=s.parent;if(!s)return null;let r,{overrideIndentation:o}=e.options;o&&(r=yl.get(e.state),r!=null&&r1e4)return null;for(;a=i&&t+e.length<=s&&e.prop(n.stateAfter);if(r)return{state:n.streamParser.copyState(r),pos:t+e.length};for(let o=e.children.length-1;o>=0;o--){let l=e.children[o],a=t+e.positions[o],h=l instanceof z&&a=e.length)return e;!s&&e.type==n.topNode&&(s=!0);for(let r=e.children.length-1;r>=0;r--){let o=e.positions[r],l=e.children[r],a;if(ot&&Wr(n,s.tree,0-s.offset,t,o),a;if(l&&(a=Yh(n,s.tree,t+s.offset,l.pos+s.offset,!1)))return{state:l.state,tree:a}}return{state:n.streamParser.startState(i?Rt(i):4),tree:z.empty}}class Hp{constructor(e,t,i,s){this.lang=e,this.input=t,this.fragments=i,this.ranges=s,this.stoppedAt=null,this.chunks=[],this.chunkPos=[],this.chunk=[],this.chunkReused=void 0,this.rangeIndex=0,this.to=s[s.length-1].to;let r=ti.get(),o=s[0].from,{state:l,tree:a}=Fp(e,i,o,r?.state);this.state=l,this.parsedPos=this.chunkStart=o+a.length;for(let h=0;h=t?this.finish():e&&this.parsedPos>=e.viewport.to?(e.skipUntilInView(this.parsedPos,t),this.finish()):null}stopAt(e){this.stoppedAt=e}lineAfter(e){let t=this.input.chunk(e);if(this.input.lineChunks)t==` -`&&(t="");else{let i=t.indexOf(` -`);i>-1&&(t=t.slice(0,i))}return e+t.length<=this.to?t:t.slice(0,this.to-e)}nextLine(){let e=this.parsedPos,t=this.lineAfter(e),i=e+t.length;for(let s=this.rangeIndex;;){let r=this.ranges[s].to;if(r>=i||(t=t.slice(0,r-(i-t.length)),s++,s==this.ranges.length))break;let o=this.ranges[s].from,l=this.lineAfter(o);t+=l,i=o+l.length}return{line:t,end:i}}skipGapsTo(e,t,i){for(;;){let s=this.ranges[this.rangeIndex].to,r=e+t;if(i>0?s>r:s>=r)break;let o=this.ranges[++this.rangeIndex].from;t+=o-s}return t}moveRangeIndex(){for(;this.ranges[this.rangeIndex].to1){r=this.skipGapsTo(t,r,1),t+=r;let o=this.chunk.length;r=this.skipGapsTo(i,r,-1),i+=r,s+=this.chunk.length-o}return this.chunk.push(e,t,i,s),r}parseLine(e){let{line:t,end:i}=this.nextLine(),s=0,{streamParser:r}=this.lang,o=new Jh(t,e?e.state.tabSize:4,e?Rt(e.state):2);if(o.eol())r.blankLine(this.state,o.indentUnit);else for(;!o.eol();){let l=Xh(r.token,o,this.state);if(l&&(s=this.emitToken(this.lang.tokenTable.resolve(l),this.parsedPos+o.start,this.parsedPos+o.pos,4,s)),o.start>1e4)break}this.parsedPos=i,this.moveRangeIndex(),this.parsedPose.start)return s}throw new Error("Stream parser failed to advance stream.")}const zr=Object.create(null),Ii=[xe.none],Wp=new Lr(Ii),bl=[],Zh=Object.create(null);for(let[n,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])Zh[n]=ec(zr,e);class Qh{constructor(e){this.extra=e,this.table=Object.assign(Object.create(null),Zh)}resolve(e){return e?this.table[e]||(this.table[e]=ec(this.extra,e)):0}}const zp=new Qh(zr);function ws(n,e){bl.indexOf(n)>-1||(bl.push(n),console.warn(e))}function ec(n,e){let t=null;for(let r of e.split(".")){let o=n[r]||m[r];o?typeof o=="function"?t?t=o(t):ws(r,`Modifier ${r} used at start of tag`):t?ws(r,`Tag ${r} used as modifier`):t=o:ws(r,`Unknown highlighting tag ${r}`)}if(!t)return 0;let i=e.replace(/ /g,"_"),s=xe.define({id:Ii.length,name:i,props:[Zd({[i]:t})]});return Ii.push(s),s.id}function qp(n){let e=xe.define({id:Ii.length,name:"Document",props:[Dt.add(()=>n)]});return Ii.push(e),e}const jp=n=>{let e=jr(n.state);return e.line?Kp(n):e.block?Gp(n):!1};function qr(n,e){return({state:t,dispatch:i})=>{if(t.readOnly)return!1;let s=n(e,t);return s?(i(t.update(s)),!0):!1}}const Kp=qr(Yp,0),Up=qr(tc,0),Gp=qr((n,e)=>tc(n,e,Jp(e)),0);function jr(n,e=n.selection.main.head){let t=n.languageDataAt("commentTokens",e);return t.length?t[0]:{}}const pi=50;function $p(n,{open:e,close:t},i,s){let r=n.sliceDoc(i-pi,i),o=n.sliceDoc(s,s+pi),l=/\s*$/.exec(r)[0].length,a=/^\s*/.exec(o)[0].length,h=r.length-l;if(r.slice(h-e.length,h)==e&&o.slice(a,a+t.length)==t)return{open:{pos:i-l,margin:l&&1},close:{pos:s+a,margin:a&&1}};let c,f;s-i<=2*pi?c=f=n.sliceDoc(i,s):(c=n.sliceDoc(i,i+pi),f=n.sliceDoc(s-pi,s));let u=/^\s*/.exec(c)[0].length,d=/\s*$/.exec(f)[0].length,p=f.length-d-t.length;return c.slice(u,u+e.length)==e&&f.slice(p,p+t.length)==t?{open:{pos:i+u+e.length,margin:/\s/.test(c.charAt(u+e.length))?1:0},close:{pos:s-d-t.length,margin:/\s/.test(f.charAt(p-1))?1:0}}:null}function Jp(n){let e=[];for(let t of n.selection.ranges){let i=n.doc.lineAt(t.from),s=t.to<=i.to?i:n.doc.lineAt(t.to),r=e.length-1;r>=0&&e[r].to>i.from?e[r].to=s.to:e.push({from:i.from,to:s.to})}return e}function tc(n,e,t=e.selection.ranges){let i=t.map(r=>jr(e,r.from).block);if(!i.every(r=>r))return null;let s=t.map((r,o)=>$p(e,i[o],r.from,r.to));if(n!=2&&!s.every(r=>r))return{changes:e.changes(t.map((r,o)=>s[o]?[]:[{from:r.from,insert:i[o].open+" "},{from:r.to,insert:" "+i[o].close}]))};if(n!=1&&s.some(r=>r)){let r=[];for(let o=0,l;os&&(r==o||o>c.from)){s=c.from;let f=jr(e,h).line;if(!f)continue;let u=/^\s*/.exec(c.text)[0].length,d=u==c.length,p=c.text.slice(u,u+f.length)==f?u:-1;ur.comment<0&&(!r.empty||r.single))){let r=[];for(let{line:l,token:a,indent:h,empty:c,single:f}of i)(f||!c)&&r.push({from:l.from+h,insert:a+" "});let o=e.changes(r);return{changes:o,selection:e.selection.map(o,1)}}else if(n!=1&&i.some(r=>r.comment>=0)){let r=[];for(let{line:o,comment:l,token:a}of i)if(l>=0){let h=o.from+l,c=h+a.length;o.text[c-o.from]==" "&&c++,r.push({from:h,to:c})}return{changes:r}}return null}const gr=Nt.define(),Xp=Nt.define(),Zp=D.define(),ic=D.define({combine(n){return _t(n,{minDepth:100,newGroupDelay:500},{minDepth:Math.max,newGroupDelay:Math.min})}});function Qp(n){let e=0;return n.iterChangedRanges((t,i)=>e=i),e}const nc=Me.define({create(){return Xe.empty},update(n,e){let t=e.state.facet(ic),i=e.annotation(gr);if(i){let a=e.docChanged?w.single(Qp(e.changes)):void 0,h=Se.fromTransaction(e,a),c=i.side,f=c==0?n.undone:n.done;return h?f=In(f,f.length,t.minDepth,h):f=oc(f,e.startState.selection),new Xe(c==0?i.rest:f,c==0?f:i.rest)}let s=e.annotation(Xp);if((s=="full"||s=="before")&&(n=n.isolate()),e.annotation(re.addToHistory)===!1)return e.changes.empty?n:n.addMapping(e.changes.desc);let r=Se.fromTransaction(e),o=e.annotation(re.time),l=e.annotation(re.userEvent);return r?n=n.addChanges(r,o,l,t.newGroupDelay,t.minDepth):e.selection&&(n=n.addSelection(e.startState.selection,o,l,t.newGroupDelay)),(s=="full"||s=="after")&&(n=n.isolate()),n},toJSON(n){return{done:n.done.map(e=>e.toJSON()),undone:n.undone.map(e=>e.toJSON())}},fromJSON(n){return new Xe(n.done.map(Se.fromJSON),n.undone.map(Se.fromJSON))}});function em(n={}){return[nc,ic.of(n),O.domEventHandlers({beforeinput(e,t){let i=e.inputType=="historyUndo"?sc:e.inputType=="historyRedo"?yr:null;return i?(e.preventDefault(),i(t)):!1}})]}function Gn(n,e){return function({state:t,dispatch:i}){if(!e&&t.readOnly)return!1;let s=t.field(nc,!1);if(!s)return!1;let r=s.pop(n,t,e);return r?(i(r),!0):!1}}const sc=Gn(0,!1),yr=Gn(1,!1),tm=Gn(0,!0),im=Gn(1,!0);class Se{constructor(e,t,i,s,r){this.changes=e,this.effects=t,this.mapped=i,this.startSelection=s,this.selectionsAfter=r}setSelAfter(e){return new Se(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,i;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(t=this.mapped)===null||t===void 0?void 0:t.toJSON(),startSelection:(i=this.startSelection)===null||i===void 0?void 0:i.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(e){return new Se(e.changes&&ne.fromJSON(e.changes),[],e.mapped&&Ze.fromJSON(e.mapped),e.startSelection&&w.fromJSON(e.startSelection),e.selectionsAfter.map(w.fromJSON))}static fromTransaction(e,t){let i=Ne;for(let s of e.startState.facet(Zp)){let r=s(e);r.length&&(i=i.concat(r))}return!i.length&&e.changes.empty?null:new Se(e.changes.invert(e.startState.doc),i,void 0,t||e.startState.selection,Ne)}static selection(e){return new Se(void 0,Ne,void 0,void 0,e)}}function In(n,e,t,i){let s=e+1>t+20?e-t-1:0,r=n.slice(s,e);return r.push(i),r}function nm(n,e){let t=[],i=!1;return n.iterChangedRanges((s,r)=>t.push(s,r)),e.iterChangedRanges((s,r,o,l)=>{for(let a=0;a=h&&o<=c&&(i=!0)}}),i}function sm(n,e){return n.ranges.length==e.ranges.length&&n.ranges.filter((t,i)=>t.empty!=e.ranges[i].empty).length===0}function rc(n,e){return n.length?e.length?n.concat(e):n:e}const Ne=[],rm=200;function oc(n,e){if(n.length){let t=n[n.length-1],i=t.selectionsAfter.slice(Math.max(0,t.selectionsAfter.length-rm));return i.length&&i[i.length-1].eq(e)?n:(i.push(e),In(n,n.length-1,1e9,t.setSelAfter(i)))}else return[Se.selection([e])]}function om(n){let e=n[n.length-1],t=n.slice();return t[n.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),t}function ks(n,e){if(!n.length)return n;let t=n.length,i=Ne;for(;t;){let s=lm(n[t-1],e,i);if(s.changes&&!s.changes.empty||s.effects.length){let r=n.slice(0,t);return r[t-1]=s,r}else e=s.mapped,t--,i=s.selectionsAfter}return i.length?[Se.selection(i)]:Ne}function lm(n,e,t){let i=rc(n.selectionsAfter.length?n.selectionsAfter.map(l=>l.map(e)):Ne,t);if(!n.changes)return Se.selection(i);let s=n.changes.map(e),r=e.mapDesc(n.changes,!0),o=n.mapped?n.mapped.composeDesc(r):r;return new Se(s,R.mapEffects(n.effects,e),o,n.startSelection.map(r),i)}const am=/^(input\.type|delete)($|\.)/;class Xe{constructor(e,t,i=0,s=void 0){this.done=e,this.undone=t,this.prevTime=i,this.prevUserEvent=s}isolate(){return this.prevTime?new Xe(this.done,this.undone):this}addChanges(e,t,i,s,r){let o=this.done,l=o[o.length-1];return l&&l.changes&&!l.changes.empty&&e.changes&&(!i||am.test(i))&&(!l.selectionsAfter.length&&t-this.prevTime0&&t-this.prevTimet.empty?n.moveByChar(t,e):$n(t,e))}function we(n){return n.textDirectionAt(n.state.selection.main.head)==Z.LTR}const ac=n=>lc(n,!we(n)),hc=n=>lc(n,we(n));function cc(n,e){return We(n,t=>t.empty?n.moveByGroup(t,e):$n(t,e))}const cm=n=>cc(n,!we(n)),fm=n=>cc(n,we(n));function um(n,e,t){if(e.type.prop(t))return!0;let i=e.to-e.from;return i&&(i>2||/[^\s,.;:]/.test(n.sliceDoc(e.from,e.to)))||e.firstChild}function Jn(n,e,t){let i=pe(n).resolveInner(e.head),s=t?L.closedBy:L.openedBy;for(let a=e.head;;){let h=t?i.childAfter(a):i.childBefore(a);if(!h)break;um(n,h,s)?i=h:a=t?h.to:h.from}let r=i.type.prop(s),o,l;return r&&(o=t?qt(n,i.from,1):qt(n,i.to,-1))&&o.matched?l=t?o.end.to:o.end.from:l=t?i.to:i.from,w.cursor(l,t?-1:1)}const dm=n=>We(n,e=>Jn(n.state,e,!we(n))),pm=n=>We(n,e=>Jn(n.state,e,we(n)));function fc(n,e){return We(n,t=>{if(!t.empty)return $n(t,e);let i=n.moveVertically(t,e);return i.head!=t.head?i:n.moveToLineBoundary(t,e)})}const uc=n=>fc(n,!1),dc=n=>fc(n,!0);function pc(n){return Math.max(n.defaultLineHeight,Math.min(n.dom.clientHeight,innerHeight)-5)}function mc(n,e){let{state:t}=n,i=ai(t.selection,l=>l.empty?n.moveVertically(l,e,pc(n)):$n(l,e));if(i.eq(t.selection))return!1;let s=n.coordsAtPos(t.selection.main.head),r=n.scrollDOM.getBoundingClientRect(),o;return s&&s.top>r.top&&s.bottommc(n,!1),br=n=>mc(n,!0);function kt(n,e,t){let i=n.lineBlockAt(e.head),s=n.moveToLineBoundary(e,t);if(s.head==e.head&&s.head!=(t?i.to:i.from)&&(s=n.moveToLineBoundary(e,t,!1)),!t&&s.head==i.from&&i.length){let r=/^\s*/.exec(n.state.sliceDoc(i.from,Math.min(i.from+100,i.to)))[0].length;r&&e.head!=i.from+r&&(s=w.cursor(i.from+r))}return s}const mm=n=>We(n,e=>kt(n,e,!0)),gm=n=>We(n,e=>kt(n,e,!1)),ym=n=>We(n,e=>kt(n,e,!we(n))),bm=n=>We(n,e=>kt(n,e,we(n))),wm=n=>We(n,e=>w.cursor(n.lineBlockAt(e.head).from,1)),km=n=>We(n,e=>w.cursor(n.lineBlockAt(e.head).to,-1));function vm(n,e,t){let i=!1,s=ai(n.selection,r=>{let o=qt(n,r.head,-1)||qt(n,r.head,1)||r.head>0&&qt(n,r.head-1,1)||r.headvm(n,e,!1);function Ve(n,e){let t=ai(n.state.selection,i=>{let s=e(i);return w.range(i.anchor,s.head,s.goalColumn)});return t.eq(n.state.selection)?!1:(n.dispatch(it(n.state,t)),!0)}function gc(n,e){return Ve(n,t=>n.moveByChar(t,e))}const yc=n=>gc(n,!we(n)),bc=n=>gc(n,we(n));function wc(n,e){return Ve(n,t=>n.moveByGroup(t,e))}const Sm=n=>wc(n,!we(n)),Cm=n=>wc(n,we(n)),Am=n=>Ve(n,e=>Jn(n.state,e,!we(n))),Mm=n=>Ve(n,e=>Jn(n.state,e,we(n)));function kc(n,e){return Ve(n,t=>n.moveVertically(t,e))}const vc=n=>kc(n,!1),xc=n=>kc(n,!0);function Sc(n,e){return Ve(n,t=>n.moveVertically(t,e,pc(n)))}const kl=n=>Sc(n,!1),vl=n=>Sc(n,!0),Dm=n=>Ve(n,e=>kt(n,e,!0)),Tm=n=>Ve(n,e=>kt(n,e,!1)),Om=n=>Ve(n,e=>kt(n,e,!we(n))),Bm=n=>Ve(n,e=>kt(n,e,we(n))),Pm=n=>Ve(n,e=>w.cursor(n.lineBlockAt(e.head).from)),Em=n=>Ve(n,e=>w.cursor(n.lineBlockAt(e.head).to)),xl=({state:n,dispatch:e})=>(e(it(n,{anchor:0})),!0),Sl=({state:n,dispatch:e})=>(e(it(n,{anchor:n.doc.length})),!0),Cl=({state:n,dispatch:e})=>(e(it(n,{anchor:n.selection.main.anchor,head:0})),!0),Al=({state:n,dispatch:e})=>(e(it(n,{anchor:n.selection.main.anchor,head:n.doc.length})),!0),Rm=({state:n,dispatch:e})=>(e(n.update({selection:{anchor:0,head:n.doc.length},userEvent:"select"})),!0),Lm=({state:n,dispatch:e})=>{let t=Xn(n).map(({from:i,to:s})=>w.range(i,Math.min(s+1,n.doc.length)));return e(n.update({selection:w.create(t),userEvent:"select"})),!0},Im=({state:n,dispatch:e})=>{let t=ai(n.selection,i=>{var s;let r=pe(n).resolveInner(i.head,1);for(;!(r.from=i.to||r.to>i.to&&r.from<=i.from||!(!((s=r.parent)===null||s===void 0)&&s.parent));)r=r.parent;return w.range(r.to,r.from)});return e(it(n,t)),!0},Nm=({state:n,dispatch:e})=>{let t=n.selection,i=null;return t.ranges.length>1?i=w.create([t.main]):t.main.empty||(i=w.create([w.cursor(t.main.head)])),i?(e(it(n,i)),!0):!1};function Yn(n,e){if(n.state.readOnly)return!1;let t="delete.selection",{state:i}=n,s=i.changeByRange(r=>{let{from:o,to:l}=r;if(o==l){let a=e(o);ao&&(t="delete.forward",a=on(n,a,!0)),o=Math.min(o,a),l=Math.max(l,a)}else o=on(n,o,!1),l=on(n,l,!0);return o==l?{range:r}:{changes:{from:o,to:l},range:w.cursor(o)}});return s.changes.empty?!1:(n.dispatch(i.update(s,{scrollIntoView:!0,userEvent:t,effects:t=="delete.selection"?O.announce.of(i.phrase("Selection deleted")):void 0})),!0)}function on(n,e,t){if(n instanceof O)for(let i of n.state.facet(O.atomicRanges).map(s=>s(n)))i.between(e,e,(s,r)=>{se&&(e=t?r:s)});return e}const Cc=(n,e)=>Yn(n,t=>{let{state:i}=n,s=i.doc.lineAt(t),r,o;if(!e&&t>s.from&&tCc(n,!1),Ac=n=>Cc(n,!0),Mc=(n,e)=>Yn(n,t=>{let i=t,{state:s}=n,r=s.doc.lineAt(i),o=s.charCategorizer(i);for(let l=null;;){if(i==(e?r.to:r.from)){i==t&&r.number!=(e?s.doc.lines:1)&&(i+=e?1:-1);break}let a=Oe(r.text,i-r.from,e)+r.from,h=r.text.slice(Math.min(i,a)-r.from,Math.max(i,a)-r.from),c=o(h);if(l!=null&&c!=l)break;(h!=" "||i!=t)&&(l=c),i=a}return i}),Dc=n=>Mc(n,!1),_m=n=>Mc(n,!0),Tc=n=>Yn(n,e=>{let t=n.lineBlockAt(e).to;return eYn(n,e=>{let t=n.lineBlockAt(e).from;return e>t?t:Math.max(0,e-1)}),Fm=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(i=>({changes:{from:i.from,to:i.to,insert:_.of(["",""])},range:w.cursor(i.from)}));return e(n.update(t,{scrollIntoView:!0,userEvent:"input"})),!0},Hm=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(i=>{if(!i.empty||i.from==0||i.from==n.doc.length)return{range:i};let s=i.from,r=n.doc.lineAt(s),o=s==r.from?s-1:Oe(r.text,s-r.from,!1)+r.from,l=s==r.to?s+1:Oe(r.text,s-r.from,!0)+r.from;return{changes:{from:o,to:l,insert:n.doc.slice(s,l).append(n.doc.slice(o,s))},range:w.cursor(l)}});return t.changes.empty?!1:(e(n.update(t,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function Xn(n){let e=[],t=-1;for(let i of n.selection.ranges){let s=n.doc.lineAt(i.from),r=n.doc.lineAt(i.to);if(!i.empty&&i.to==r.from&&(r=n.doc.lineAt(i.to-1)),t>=s.number){let o=e[e.length-1];o.to=r.to,o.ranges.push(i)}else e.push({from:s.from,to:r.to,ranges:[i]});t=r.number+1}return e}function Oc(n,e,t){if(n.readOnly)return!1;let i=[],s=[];for(let r of Xn(n)){if(t?r.to==n.doc.length:r.from==0)continue;let o=n.doc.lineAt(t?r.to+1:r.from-1),l=o.length+1;if(t){i.push({from:r.to,to:o.to},{from:r.from,insert:o.text+n.lineBreak});for(let a of r.ranges)s.push(w.range(Math.min(n.doc.length,a.anchor+l),Math.min(n.doc.length,a.head+l)))}else{i.push({from:o.from,to:r.from},{from:r.to,insert:n.lineBreak+o.text});for(let a of r.ranges)s.push(w.range(a.anchor-l,a.head-l))}}return i.length?(e(n.update({changes:i,scrollIntoView:!0,selection:w.create(s,n.selection.mainIndex),userEvent:"move.line"})),!0):!1}const Wm=({state:n,dispatch:e})=>Oc(n,e,!1),zm=({state:n,dispatch:e})=>Oc(n,e,!0);function Bc(n,e,t){if(n.readOnly)return!1;let i=[];for(let s of Xn(n))t?i.push({from:s.from,insert:n.doc.slice(s.from,s.to)+n.lineBreak}):i.push({from:s.to,insert:n.lineBreak+n.doc.slice(s.from,s.to)});return e(n.update({changes:i,scrollIntoView:!0,userEvent:"input.copyline"})),!0}const qm=({state:n,dispatch:e})=>Bc(n,e,!1),jm=({state:n,dispatch:e})=>Bc(n,e,!0),Km=n=>{if(n.state.readOnly)return!1;let{state:e}=n,t=e.changes(Xn(e).map(({from:s,to:r})=>(s>0?s--:rn.moveVertically(s,!0)).map(t);return n.dispatch({changes:t,selection:i,scrollIntoView:!0,userEvent:"delete.line"}),!0};function Um(n,e){if(/\(\)|\[\]|\{\}/.test(n.sliceDoc(e-1,e+1)))return{from:e,to:e};let t=pe(n).resolveInner(e),i=t.childBefore(e),s=t.childAfter(e),r;return i&&s&&i.to<=e&&s.from>=e&&(r=i.type.prop(L.closedBy))&&r.indexOf(s.name)>-1&&n.doc.lineAt(i.to).from==n.doc.lineAt(s.from).from?{from:i.to,to:s.from}:null}const Gm=Pc(!1),$m=Pc(!0);function Pc(n){return({state:e,dispatch:t})=>{if(e.readOnly)return!1;let i=e.changeByRange(s=>{let{from:r,to:o}=s,l=e.doc.lineAt(r),a=!n&&r==o&&Um(e,r);n&&(r=o=(o<=l.to?l:e.doc.lineAt(o)).to);let h=new Kn(e,{simulateBreak:r,simulateDoubleBreak:!!a}),c=Vr(h,r);for(c==null&&(c=/^\s*/.exec(e.doc.lineAt(r).text)[0].length);ol.from&&r{let s=[];for(let o=i.from;o<=i.to;){let l=n.doc.lineAt(o);l.number>t&&(i.empty||i.to>l.from)&&(e(l,s,i),t=l.number),o=l.to+1}let r=n.changes(s);return{changes:s,range:w.range(r.mapPos(i.anchor,1),r.mapPos(i.head,1))}})}const Jm=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=Object.create(null),i=new Kn(n,{overrideIndentation:r=>{let o=t[r];return o??-1}}),s=Kr(n,(r,o,l)=>{let a=Vr(i,r.from);if(a==null)return;/\S/.test(r.text)||(a=0);let h=/^\s*/.exec(r.text)[0],c=Li(n,a);(h!=c||l.fromn.readOnly?!1:(e(n.update(Kr(n,(t,i)=>{i.push({from:t.from,insert:n.facet(jn)})}),{userEvent:"input.indent"})),!0),Rc=({state:n,dispatch:e})=>n.readOnly?!1:(e(n.update(Kr(n,(t,i)=>{let s=/^\s*/.exec(t.text)[0];if(!s)return;let r=Fi(s,n.tabSize),o=0,l=Li(n,Math.max(0,r-Rt(n)));for(;o({mac:n.key,run:n.run,shift:n.shift}))),Zm=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:dm,shift:Am},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:pm,shift:Mm},{key:"Alt-ArrowUp",run:Wm},{key:"Shift-Alt-ArrowUp",run:qm},{key:"Alt-ArrowDown",run:zm},{key:"Shift-Alt-ArrowDown",run:jm},{key:"Escape",run:Nm},{key:"Mod-Enter",run:$m},{key:"Alt-l",mac:"Ctrl-l",run:Lm},{key:"Mod-i",run:Im,preventDefault:!0},{key:"Mod-[",run:Rc},{key:"Mod-]",run:Ec},{key:"Mod-Alt-\\",run:Jm},{key:"Shift-Mod-k",run:Km},{key:"Shift-Mod-\\",run:xm},{key:"Mod-/",run:jp},{key:"Alt-A",run:Up}].concat(Xm),Qm={key:"Tab",run:Ec,shift:Rc},eg="#2E3235",Ue="#DDDDDD",Ai="#B9D2FF",ln="#b0b0b0",tg="#e0e0e0",Lc="#808080",vs="#000000",ig="#A54543",Ic="#fc6d24",St="#fda331",xs="#8abeb7",Ml="#b5bd68",mi="#6fb3d2",gi="#cc99cc",ng="#6987AF",Dl=Ic,Tl="#292d30",an=Ai+"30",sg=eg,Ss=Ue,rg="#202325",Ol=Ue,og=O.theme({"&":{color:Ue,backgroundColor:sg},".cm-content":{caretColor:Ol},".cm-cursor, .cm-dropCursor":{borderLeftColor:Ol},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:rg},".cm-panels":{backgroundColor:Tl,color:ln},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:Ai,outline:`1px solid ${ln}`,color:vs},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:tg,color:vs},".cm-activeLine":{backgroundColor:an},".cm-selectionMatch":{backgroundColor:an},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{outline:`1px solid ${ln}`},"&.cm-focused .cm-matchingBracket":{backgroundColor:Ai,color:vs},".cm-gutters":{borderRight:"1px solid #ffffff10",color:Lc,backgroundColor:Tl},".cm-activeLineGutter":{backgroundColor:an},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:Ai},".cm-tooltip":{border:"none",backgroundColor:Ss},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:Ss,borderBottomColor:Ss},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:an,color:ln}}},{dark:!0}),lg=li.define([{tag:m.keyword,color:St},{tag:[m.name,m.deleted,m.character,m.propertyName,m.macroName],color:Ml},{tag:[m.variableName],color:mi},{tag:[m.function(m.variableName)],color:St},{tag:[m.labelName],color:Ic},{tag:[m.color,m.constant(m.name),m.standard(m.name)],color:St},{tag:[m.definition(m.name),m.separator],color:gi},{tag:[m.brace],color:gi},{tag:[m.annotation],color:Dl},{tag:[m.number,m.changed,m.annotation,m.modifier,m.self,m.namespace],color:St},{tag:[m.typeName,m.className],color:mi},{tag:[m.operator,m.operatorKeyword],color:gi},{tag:[m.tagName],color:St},{tag:[m.squareBracket],color:gi},{tag:[m.angleBracket],color:gi},{tag:[m.attributeName],color:mi},{tag:[m.regexp],color:St},{tag:[m.quote],color:Ue},{tag:[m.string],color:Ml},{tag:m.link,color:ng,textDecoration:"underline",textUnderlinePosition:"under"},{tag:[m.url,m.escape,m.special(m.string)],color:xs},{tag:[m.meta],color:ig},{tag:[m.comment],color:Lc,fontStyle:"italic"},{tag:m.monospace,color:Ue},{tag:m.strong,fontWeight:"bold",color:St},{tag:m.emphasis,fontStyle:"italic",color:mi},{tag:m.strikethrough,textDecoration:"line-through"},{tag:m.heading,fontWeight:"bold",color:Ue},{tag:m.special(m.heading1),fontWeight:"bold",color:Ue},{tag:m.heading1,fontWeight:"bold",color:Ue},{tag:[m.heading2,m.heading3,m.heading4],fontWeight:"bold",color:Ue},{tag:[m.heading5,m.heading6],color:Ue},{tag:[m.atom,m.bool,m.special(m.variableName)],color:xs},{tag:[m.processingInstruction,m.inserted],color:xs},{tag:[m.contentSeparator],color:mi},{tag:m.invalid,color:Ai,borderBottom:`1px dotted ${Dl}`}]),ag=[og,Hr(lg)],Bl="#2e3440",Ur="#3b4252",Pl="#434c5e",hn="#4c566a",El="#e5e9f0",kr="#eceff4",Cs="#8fbcbb",Rl="#88c0d0",hg="#81a1c1",Fe="#5e81ac",cg="#bf616a",Wt="#d08770",As="#ebcb8b",Ll="#a3be8c",fg="#b48ead",Il="#d30102",Gr=kr,Ms=Gr,ug="#ffffff",Ds=Ur,dg=Gr,Nl=Ur,pg=O.theme({"&":{color:Bl,backgroundColor:ug},".cm-content":{caretColor:Nl},".cm-cursor, .cm-dropCursor":{borderLeftColor:Nl},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:dg},".cm-panels":{backgroundColor:Gr,color:hn},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:`1px solid ${hn}`},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:El},".cm-activeLine":{backgroundColor:Ms},".cm-selectionMatch":{backgroundColor:El},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{outline:`1px solid ${hn}`},"&.cm-focused .cm-matchingBracket":{backgroundColor:kr},".cm-gutters":{backgroundColor:kr,color:Bl,border:"none"},".cm-activeLineGutter":{backgroundColor:Ms},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:Ds},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:Ds,borderBottomColor:Ds},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:Ms,color:hn}}},{dark:!1}),mg=li.define([{tag:m.keyword,color:Fe},{tag:[m.name,m.deleted,m.character,m.propertyName,m.macroName],color:Wt},{tag:[m.variableName],color:Wt},{tag:[m.function(m.variableName)],color:Fe},{tag:[m.labelName],color:hg},{tag:[m.color,m.constant(m.name),m.standard(m.name)],color:Fe},{tag:[m.definition(m.name),m.separator],color:Ll},{tag:[m.brace],color:Cs},{tag:[m.annotation],color:Il},{tag:[m.number,m.changed,m.annotation,m.modifier,m.self,m.namespace],color:Rl},{tag:[m.typeName,m.className],color:As},{tag:[m.operator,m.operatorKeyword],color:Ll},{tag:[m.tagName],color:fg},{tag:[m.squareBracket],color:cg},{tag:[m.angleBracket],color:Wt},{tag:[m.attributeName],color:As},{tag:[m.regexp],color:Fe},{tag:[m.quote],color:Ur},{tag:[m.string],color:Wt},{tag:m.link,color:Cs,textDecoration:"underline",textUnderlinePosition:"under"},{tag:[m.url,m.escape,m.special(m.string)],color:Wt},{tag:[m.meta],color:Rl},{tag:[m.comment],color:Pl,fontStyle:"italic"},{tag:m.strong,fontWeight:"bold",color:Fe},{tag:m.emphasis,fontStyle:"italic",color:Fe},{tag:m.strikethrough,textDecoration:"line-through"},{tag:m.heading,fontWeight:"bold",color:Fe},{tag:m.special(m.heading1),fontWeight:"bold",color:Fe},{tag:m.heading1,fontWeight:"bold",color:Fe},{tag:[m.heading2,m.heading3,m.heading4],fontWeight:"bold",color:Fe},{tag:[m.heading5,m.heading6],color:Fe},{tag:[m.atom,m.bool,m.special(m.variableName)],color:Wt},{tag:[m.processingInstruction,m.inserted],color:Cs},{tag:[m.contentSeparator],color:As},{tag:m.invalid,color:Pl,borderBottom:`1px dotted ${Il}`}]),gg=[pg,Hr(mg)];function _l(n){let e=Object.keys(n).join(""),t=/\w/.test(e);return t&&(e=e.replace(/\w/g,"")),`[${t?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function yg(n){let e=Object.create(null),t=Object.create(null);for(let{label:s}of n){e[s[0]]=!0;for(let r=1;rtypeof s=="string"?{label:s}:s),[t,i]=e.every(s=>/^\w+$/.test(s.label))?[/\w*$/,/\w+$/]:yg(e);return s=>{let r=s.matchBefore(i);return r||s.explicit?{from:r?r.from:s.pos,options:e,validFor:t}:null}}function cy(n,e){return t=>{for(let i=pe(t.state).resolveInner(t.pos,-1);i;i=i.parent)if(n.indexOf(i.name)>-1)return null;return e(t)}}class Vl{constructor(e,t,i){this.completion=e,this.source=t,this.match=i}}function vr(n){return n.selection.main.head}function wg(n,e,t,i){return Object.assign(Object.assign({},n.changeByRange(s=>{if(s==n.selection.main)return{changes:{from:t,to:i,insert:e},range:w.cursor(t+e.length)};let r=i-t;return!s.empty||r&&n.sliceDoc(s.from-r,s.from)!=n.sliceDoc(t,i)?{range:s}:{changes:{from:s.from-r,to:s.from,insert:e},range:w.cursor(s.from-r+e.length)}})),{userEvent:"input.complete"})}function Nc(n,e){const t=e.completion.apply||e.completion.label;let i=e.source;typeof t=="string"?n.dispatch(wg(n.state,t,i.from,i.to)):t(n,e.completion,i.from,i.to)}const Fl=new WeakMap;function kg(n){if(!Array.isArray(n))return n;let e=Fl.get(n);return e||Fl.set(n,e=bg(n)),e}class vg{constructor(e){this.pattern=e,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[];for(let t=0;t=48&&C<=57||C>=97&&C<=122?2:C>=65&&C<=90?1:0:(T=ga(C))!=T.toLowerCase()?1:T!=T.toUpperCase()?2:0;(!v||B==1&&y||k==0&&B!=0)&&(t[f]==C||i[f]==C&&(u=!0)?o[f++]=v:o.length&&(b=!1)),k=B,v+=Ee(C)}return f==a&&o[0]==0&&b?this.result(-100+(u?-200:0),o,e):d==a&&p==0?[-200-e.length,0,g]:l>-1?[-700-e.length,l,l+this.pattern.length]:d==a?[-200+-700-e.length,p,g]:f==a?this.result(-100+(u?-200:0)+-700+(b?0:-1100),o,e):t.length==2?null:this.result((s[0]?-700:0)+-200+-1100,s,e)}result(e,t,i){let s=[e-i.length],r=1;for(let o of t){let l=o+(this.astral?Ee(ge(i,o)):1);r>1&&s[r-1]==o?s[r-1]=l:(s[r++]=o,s[r++]=l)}return s}}const It=D.define({combine(n){return _t(n,{activateOnTyping:!0,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],compareCompletions:(e,t)=>e.label.localeCompare(t.label),interactionDelay:75},{defaultKeymap:(e,t)=>e&&t,closeOnBlur:(e,t)=>e&&t,icons:(e,t)=>e&&t,optionClass:(e,t)=>i=>xg(e(i),t(i)),addToOptions:(e,t)=>e.concat(t)})}});function xg(n,e){return n?e?n+" "+e:n:e}function Sg(n){let e=n.addToOptions.slice();return n.icons&&e.push({render(t){let i=document.createElement("div");return i.classList.add("cm-completionIcon"),t.type&&i.classList.add(...t.type.split(/\s+/g).map(s=>"cm-completionIcon-"+s)),i.setAttribute("aria-hidden","true"),i},position:20}),e.push({render(t,i,s){let r=document.createElement("span");r.className="cm-completionLabel";let{label:o}=t,l=0;for(let a=1;al&&r.appendChild(document.createTextNode(o.slice(l,h)));let f=r.appendChild(document.createElement("span"));f.appendChild(document.createTextNode(o.slice(h,c))),f.className="cm-completionMatchedText",l=c}return lt.position-i.position).map(t=>t.render)}function Hl(n,e,t){if(n<=t)return{from:0,to:n};if(e<0&&(e=0),e<=n>>1){let s=Math.floor(e/t);return{from:s*t,to:(s+1)*t}}let i=Math.floor((n-e)/t);return{from:n-(i+1)*t,to:n-i*t}}class Cg{constructor(e,t){this.view=e,this.stateField=t,this.info=null,this.placeInfo={read:()=>this.measureInfo(),write:l=>this.positionInfo(l),key:this};let i=e.state.field(t),{options:s,selected:r}=i.open,o=e.state.facet(It);this.optionContent=Sg(o),this.optionClass=o.optionClass,this.range=Hl(s.length,r,o.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.dom.addEventListener("mousedown",l=>{for(let a=l.target,h;a&&a!=this.dom;a=a.parentNode)if(a.nodeName=="LI"&&(h=/-(\d+)$/.exec(a.id))&&+h[1]{this.info&&this.view.requestMeasure(this.placeInfo)})}mount(){this.updateSel()}update(e){e.state.field(this.stateField)!=e.startState.field(this.stateField)&&this.updateSel()}positioned(){this.info&&this.view.requestMeasure(this.placeInfo)}updateSel(){let e=this.view.state.field(this.stateField),t=e.open;if((t.selected>-1&&t.selected=this.range.to)&&(this.range=Hl(t.options.length,t.selected,this.view.state.facet(It).maxRenderedOptions),this.list.remove(),this.list=this.dom.appendChild(this.createListBox(t.options,e.id,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfo)})),this.updateSelectedOption(t.selected)){this.info&&(this.info.remove(),this.info=null);let{completion:i}=t.options[t.selected],{info:s}=i;if(!s)return;let r=typeof s=="string"?document.createTextNode(s):s(i);if(!r)return;"then"in r?r.then(o=>{o&&this.view.state.field(this.stateField,!1)==e&&this.addInfoPane(o)}).catch(o=>He(this.view.state,o,"completion info")):this.addInfoPane(r)}}addInfoPane(e){let t=this.info=document.createElement("div");t.className="cm-tooltip cm-completionInfo",t.appendChild(e),this.dom.appendChild(t),this.view.requestMeasure(this.placeInfo)}updateSelectedOption(e){let t=null;for(let i=this.list.firstChild,s=this.range.from;i;i=i.nextSibling,s++)s==e?i.hasAttribute("aria-selected")||(i.setAttribute("aria-selected","true"),t=i):i.hasAttribute("aria-selected")&&i.removeAttribute("aria-selected");return t&&Mg(this.list,t),t}measureInfo(){let e=this.dom.querySelector("[aria-selected]");if(!e||!this.info)return null;let t=this.dom.ownerDocument.defaultView||window,i=this.dom.getBoundingClientRect(),s=this.info.getBoundingClientRect(),r=e.getBoundingClientRect();if(r.top>Math.min(t.innerHeight,i.bottom)-10||r.bottom=s.height||p>i.top?c=r.bottom-i.top+"px":f=i.bottom-r.top+"px"}return{top:c,bottom:f,maxWidth:h,class:a?o?"left-narrow":"right-narrow":l?"left":"right"}}positionInfo(e){this.info&&(e?(this.info.style.top=e.top,this.info.style.bottom=e.bottom,this.info.style.maxWidth=e.maxWidth,this.info.className="cm-tooltip cm-completionInfo cm-completionInfo-"+e.class):this.info.style.top="-1e6px")}createListBox(e,t,i){const s=document.createElement("ul");s.id=t,s.setAttribute("role","listbox"),s.setAttribute("aria-expanded","true"),s.setAttribute("aria-label",this.view.state.phrase("Completions"));for(let r=i.from;rnew Cg(e,n)}function Mg(n,e){let t=n.getBoundingClientRect(),i=e.getBoundingClientRect();i.topt.bottom&&(n.scrollTop+=i.bottom-t.bottom)}function Wl(n){return(n.boost||0)*100+(n.apply?10:0)+(n.info?5:0)+(n.type?1:0)}function Dg(n,e){let t=[],i=0;for(let l of n)if(l.hasResult())if(l.result.filter===!1){let a=l.result.getMatch;for(let h of l.result.options){let c=[1e9-i++];if(a)for(let f of a(h))c.push(f);t.push(new Vl(h,l,c))}}else{let a=new vg(e.sliceDoc(l.from,l.to)),h;for(let c of l.result.options)(h=a.match(c.label))&&(c.boost!=null&&(h[0]+=c.boost),t.push(new Vl(c,l,h)))}let s=[],r=null,o=e.facet(It).compareCompletions;for(let l of t.sort((a,h)=>h.match[0]-a.match[0]||o(a.completion,h.completion)))!r||r.label!=l.completion.label||r.detail!=l.completion.detail||r.type!=null&&l.completion.type!=null&&r.type!=l.completion.type||r.apply!=l.completion.apply?s.push(l):Wl(l.completion)>Wl(r)&&(s[s.length-1]=l),r=l.completion;return s}class Mi{constructor(e,t,i,s,r){this.options=e,this.attrs=t,this.tooltip=i,this.timestamp=s,this.selected=r}setSelected(e,t){return e==this.selected||e>=this.options.length?this:new Mi(this.options,zl(t,e),this.tooltip,this.timestamp,e)}static build(e,t,i,s,r){let o=Dg(e,t);if(!o.length)return null;let l=t.facet(It).selectOnOpen?0:-1;if(s&&s.selected!=l&&s.selected!=-1){let a=s.options[s.selected].completion;for(let h=0;hh.hasResult()?Math.min(a,h.from):a,1e8),create:Ag(zi),above:r.aboveCursor},s?s.timestamp:Date.now(),l)}map(e){return new Mi(this.options,this.attrs,Object.assign(Object.assign({},this.tooltip),{pos:e.mapPos(this.tooltip.pos)}),this.timestamp,this.selected)}}class Nn{constructor(e,t,i){this.active=e,this.id=t,this.open=i}static start(){return new Nn(Bg,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(e){let{state:t}=e,i=t.facet(It),r=(i.override||t.languageDataAt("autocomplete",vr(t)).map(kg)).map(l=>(this.active.find(h=>h.source==l)||new st(l,this.active.some(h=>h.state!=0)?1:0)).update(e,i));r.length==this.active.length&&r.every((l,a)=>l==this.active[a])&&(r=this.active);let o=e.selection||r.some(l=>l.hasResult()&&e.changes.touchesRange(l.from,l.to))||!Tg(r,this.active)?Mi.build(r,t,this.id,this.open,i):this.open&&e.docChanged?this.open.map(e.changes):this.open;!o&&r.every(l=>l.state!=1)&&r.some(l=>l.hasResult())&&(r=r.map(l=>l.hasResult()?new st(l.source,0):l));for(let l of e.effects)l.is(Fc)&&(o=o&&o.setSelected(l.value,this.id));return r==this.active&&o==this.open?this:new Nn(r,this.id,o)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:Og}}function Tg(n,e){if(n==e)return!0;for(let t=0,i=0;;){for(;t-1&&(t["aria-activedescendant"]=n+"-"+e),t}const Bg=[];function Pg(n){return n.isUserEvent("input.type")?"input":n.isUserEvent("delete.backward")?"delete":null}class st{constructor(e,t,i=-1){this.source=e,this.state=t,this.explicitPos=i}hasResult(){return!1}update(e,t){let i=Pg(e),s=this;i?s=s.handleUserEvent(e,i,t):e.docChanged?s=s.handleChange(e):e.selection&&s.state!=0&&(s=new st(s.source,0));for(let r of e.effects)if(r.is(_c))s=new st(s.source,1,r.value?vr(e.state):-1);else if(r.is(Vc))s=new st(s.source,0);else if(r.is(Eg))for(let o of r.value)o.source==s.source&&(s=o);return s}handleUserEvent(e,t,i){return t=="delete"||!i.activateOnTyping?this.map(e.changes):new st(this.source,1)}handleChange(e){return e.changes.touchesRange(vr(e.startState))?new st(this.source,0):this.map(e.changes)}map(e){return e.empty||this.explicitPos<0?this:new st(this.source,this.state,e.mapPos(this.explicitPos))}}const _c=R.define(),Vc=R.define(),Eg=R.define({map(n,e){return n.map(t=>t.map(e))}}),Fc=R.define(),zi=Me.define({create(){return Nn.start()},update(n,e){return n.update(e)},provide:n=>[Er.from(n,e=>e.tooltip),O.contentAttributes.from(n,e=>e.attrs)]});function cn(n,e="option"){return t=>{let i=t.state.field(zi,!1);if(!i||!i.open||Date.now()-i.open.timestamp-1?i.open.selected+s*(n?1:-1):n?0:o-1;return l<0?l=e=="page"?0:o-1:l>=o&&(l=e=="page"?o-1:0),t.dispatch({effects:Fc.of(l)}),!0}}const Rg=n=>{let e=n.state.field(zi,!1);return n.state.readOnly||!e||!e.open||e.open.selected<0||Date.now()-e.open.timestampn.state.field(zi,!1)?(n.dispatch({effects:_c.of(!0)}),!0):!1,Ig=n=>{let e=n.state.field(zi,!1);return!e||!e.active.some(t=>t.state!=0)?!1:(n.dispatch({effects:Vc.of(null)}),!0)},Ng=O.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",listStyle:"none",margin:0,padding:0,"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer",padding:"1px 3px",lineHeight:1.2}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑︎'"}},".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});class _g{constructor(e,t,i,s){this.field=e,this.line=t,this.from=i,this.to=s}}class $r{constructor(e,t,i){this.field=e,this.from=t,this.to=i}map(e){let t=e.mapPos(this.from,-1,ce.TrackDel),i=e.mapPos(this.to,1,ce.TrackDel);return t==null||i==null?null:new $r(this.field,t,i)}}class Jr{constructor(e,t){this.lines=e,this.fieldPositions=t}instantiate(e,t){let i=[],s=[t],r=e.doc.lineAt(t),o=/^\s*/.exec(r.text)[0];for(let a of this.lines){if(i.length){let h=o,c=/^\t*/.exec(a)[0].length;for(let f=0;fnew $r(a.field,s[a.line]+a.from,s[a.line]+a.to));return{text:i,ranges:l}}static parse(e){let t=[],i=[],s=[],r;for(let o of e.split(/\r\n?|\n/)){for(;r=/[#$]\{(?:(\d+)(?::([^}]*))?|([^}]*))\}/.exec(o);){let l=r[1]?+r[1]:null,a=r[2]||r[3]||"",h=-1;for(let c=0;c=h&&f.field++}s.push(new _g(h,i.length,r.index,r.index+a.length)),o=o.slice(0,r.index)+a+o.slice(r.index+r[0].length)}for(let l;l=/([$#])\\{/.exec(o);){o=o.slice(0,l.index)+l[1]+"{"+o.slice(l.index+l[0].length);for(let a of s)a.line==i.length&&a.from>l.index&&(a.from--,a.to--)}i.push(o)}return new Jr(i,s)}}let Vg=E.widget({widget:new class extends tt{toDOM(){let n=document.createElement("span");return n.className="cm-snippetFieldPosition",n}ignoreEvent(){return!1}}}),Fg=E.mark({class:"cm-snippetField"});class hi{constructor(e,t){this.ranges=e,this.active=t,this.deco=E.set(e.map(i=>(i.from==i.to?Vg:Fg).range(i.from,i.to)))}map(e){let t=[];for(let i of this.ranges){let s=i.map(e);if(!s)return null;t.push(s)}return new hi(t,this.active)}selectionInsideField(e){return e.ranges.every(t=>this.ranges.some(i=>i.field==this.active&&i.from<=t.from&&i.to>=t.to))}}const qi=R.define({map(n,e){return n&&n.map(e)}}),Hg=R.define(),Ni=Me.define({create(){return null},update(n,e){for(let t of e.effects){if(t.is(qi))return t.value;if(t.is(Hg)&&n)return new hi(n.ranges,t.value)}return n&&e.docChanged&&(n=n.map(e.changes)),n&&e.selection&&!n.selectionInsideField(e.selection)&&(n=null),n},provide:n=>O.decorations.from(n,e=>e?e.deco:E.none)});function Yr(n,e){return w.create(n.filter(t=>t.field==e).map(t=>w.range(t.from,t.to)))}function Wg(n){let e=Jr.parse(n);return(t,i,s,r)=>{let{text:o,ranges:l}=e.instantiate(t.state,s),a={changes:{from:s,to:r,insert:_.of(o)},scrollIntoView:!0};if(l.length&&(a.selection=Yr(l,0)),l.length>1){let h=new hi(l,0),c=a.effects=[qi.of(h)];t.state.field(Ni,!1)===void 0&&c.push(R.appendConfig.of([Ni,Ug,Gg,Ng]))}t.dispatch(t.state.update(a))}}function Hc(n){return({state:e,dispatch:t})=>{let i=e.field(Ni,!1);if(!i||n<0&&i.active==0)return!1;let s=i.active+n,r=n>0&&!i.ranges.some(o=>o.field==s+n);return t(e.update({selection:Yr(i.ranges,s),effects:qi.of(r?null:new hi(i.ranges,s))})),!0}}const zg=({state:n,dispatch:e})=>n.field(Ni,!1)?(e(n.update({effects:qi.of(null)})),!0):!1,qg=Hc(1),jg=Hc(-1),Kg=[{key:"Tab",run:qg,shift:jg},{key:"Escape",run:zg}],ql=D.define({combine(n){return n.length?n[0]:Kg}}),Ug=Vi.highest(qn.compute([ql],n=>n.facet(ql)));function fy(n,e){return Object.assign(Object.assign({},e),{apply:Wg(n)})}const Gg=O.domEventHandlers({mousedown(n,e){let t=e.state.field(Ni,!1),i;if(!t||(i=e.posAtCoords({x:n.clientX,y:n.clientY}))==null)return!1;let s=t.ranges.find(r=>r.from<=i&&r.to>=i);return!s||s.field==t.active?!1:(e.dispatch({selection:Yr(t.ranges,s.field),effects:qi.of(t.ranges.some(r=>r.field>s.field)?new hi(t.ranges,s.field):null)}),!0)}}),_i={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},Tt=R.define({map(n,e){let t=e.mapPos(n,-1,ce.TrackAfter);return t??void 0}}),Xr=R.define({map(n,e){return e.mapPos(n)}}),Zr=new class extends Bt{};Zr.startSide=1;Zr.endSide=-1;const Wc=Me.define({create(){return F.empty},update(n,e){if(e.selection){let t=e.state.doc.lineAt(e.selection.main.head).from,i=e.startState.doc.lineAt(e.startState.selection.main.head).from;t!=e.changes.mapPos(i,-1)&&(n=F.empty)}n=n.map(e.changes);for(let t of e.effects)t.is(Tt)?n=n.update({add:[Zr.range(t.value,t.value+1)]}):t.is(Xr)&&(n=n.update({filter:i=>i!=t.value}));return n}});function $g(){return[Yg,Wc]}const Ts="()[]{}<>";function zc(n){for(let e=0;e{if((Jg?n.composing:n.compositionStarted)||n.state.readOnly)return!1;let s=n.state.selection.main;if(i.length>2||i.length==2&&Ee(ge(i,0))==1||e!=s.from||t!=s.to)return!1;let r=Qg(n.state,i);return r?(n.dispatch(r),!0):!1}),Xg=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let i=qc(n,n.selection.main.head).brackets||_i.brackets,s=null,r=n.changeByRange(o=>{if(o.empty){let l=e0(n.doc,o.head);for(let a of i)if(a==l&&Zn(n.doc,o.head)==zc(ge(a,0)))return{changes:{from:o.head-a.length,to:o.head+a.length},range:w.cursor(o.head-a.length)}}return{range:s=o}});return s||e(n.update(r,{scrollIntoView:!0,userEvent:"delete.backward"})),!s},Zg=[{key:"Backspace",run:Xg}];function Qg(n,e){let t=qc(n,n.selection.main.head),i=t.brackets||_i.brackets;for(let s of i){let r=zc(ge(s,0));if(e==s)return r==s?n0(n,s,i.indexOf(s+s+s)>-1,t):t0(n,s,r,t.before||_i.before);if(e==r&&jc(n,n.selection.main.from))return i0(n,s,r)}return null}function jc(n,e){let t=!1;return n.field(Wc).between(0,n.doc.length,i=>{i==e&&(t=!0)}),t}function Zn(n,e){let t=n.sliceString(e,e+2);return t.slice(0,Ee(ge(t,0)))}function e0(n,e){let t=n.sliceString(e-2,e);return Ee(ge(t,0))==t.length?t:t.slice(1)}function t0(n,e,t,i){let s=null,r=n.changeByRange(o=>{if(!o.empty)return{changes:[{insert:e,from:o.from},{insert:t,from:o.to}],effects:Tt.of(o.to+e.length),range:w.range(o.anchor+e.length,o.head+e.length)};let l=Zn(n.doc,o.head);return!l||/\s/.test(l)||i.indexOf(l)>-1?{changes:{insert:e+t,from:o.head},effects:Tt.of(o.head+e.length),range:w.cursor(o.head+e.length)}:{range:s=o}});return s?null:n.update(r,{scrollIntoView:!0,userEvent:"input.type"})}function i0(n,e,t){let i=null,s=n.selection.ranges.map(r=>r.empty&&Zn(n.doc,r.head)==t?w.cursor(r.head+t.length):i=r);return i?null:n.update({selection:w.create(s,n.selection.mainIndex),scrollIntoView:!0,effects:n.selection.ranges.map(({from:r})=>Xr.of(r))})}function n0(n,e,t,i){let s=i.stringPrefixes||_i.stringPrefixes,r=null,o=n.changeByRange(l=>{if(!l.empty)return{changes:[{insert:e,from:l.from},{insert:e,from:l.to}],effects:Tt.of(l.to+e.length),range:w.range(l.anchor+e.length,l.head+e.length)};let a=l.head,h=Zn(n.doc,a),c;if(h==e){if(jl(n,a))return{changes:{insert:e+e,from:a},effects:Tt.of(a+e.length),range:w.cursor(a+e.length)};if(jc(n,a)){let f=t&&n.sliceDoc(a,a+e.length*3)==e+e+e;return{range:w.cursor(a+e.length*(f?3:1)),effects:Xr.of(a)}}}else{if(t&&n.sliceDoc(a-2*e.length,a)==e+e&&(c=Kl(n,a-2*e.length,s))>-1&&jl(n,c))return{changes:{insert:e+e+e+e,from:a},effects:Tt.of(a+e.length),range:w.cursor(a+e.length)};if(n.charCategorizer(a)(h)!=Re.Word&&Kl(n,a,s)>-1&&!s0(n,a,e,s))return{changes:{insert:e+e,from:a},effects:Tt.of(a+e.length),range:w.cursor(a+e.length)}}return{range:r=l}});return r?null:n.update(o,{scrollIntoView:!0,userEvent:"input.type"})}function jl(n,e){let t=pe(n).resolveInner(e+1);return t.parent&&t.from==e}function s0(n,e,t,i){let s=pe(n).resolveInner(e,-1),r=i.reduce((o,l)=>Math.max(o,l.length),0);for(let o=0;o<5;o++){let l=n.sliceDoc(s.from,Math.min(s.to,s.from+t.length+r)),a=l.indexOf(t);if(!a||a>-1&&i.indexOf(l.slice(0,a))>-1){let c=s.firstChild;for(;c&&c.from==s.from&&c.to-c.from>t.length+a;){if(n.sliceDoc(c.to-t.length,c.to)==t)return!1;c=c.firstChild}return!0}let h=s.to==e&&s.parent;if(!h)break;s=h}return!1}function Kl(n,e,t){let i=n.charCategorizer(e);if(i(n.sliceDoc(e-1,e))!=Re.Word)return e;for(let s of t){let r=e-s.length;if(n.sliceDoc(r,e)==s&&i(n.sliceDoc(r-1,r))!=Re.Word)return r}return-1}const r0=[{key:"Ctrl-Space",run:Lg},{key:"Escape",run:Ig},{key:"ArrowDown",run:cn(!0)},{key:"ArrowUp",run:cn(!1)},{key:"PageDown",run:cn(!0,"page")},{key:"PageUp",run:cn(!1,"page")},{key:"Enter",run:Rg}];function Je(){var n=arguments[0];typeof n=="string"&&(n=document.createElement(n));var e=1,t=arguments[1];if(t&&typeof t=="object"&&t.nodeType==null&&!Array.isArray(t)){for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)){var s=t[i];typeof s=="string"?n.setAttribute(i,s):s!=null&&(n[i]=s)}e++}for(;el.from==l.to||l.from==l.to-1&&i.doc.lineAt(l.from).to==l.from?E.widget({widget:new g0(l),diagnostic:l}).range(l.from):E.mark({attributes:{class:"cm-lintRange cm-lintRange-"+l.severity},diagnostic:l}).range(l.from,l.to)),!0);return new At(o,t,ni(o))}}function ni(n,e=null,t=0){let i=null;return n.between(t,1e9,(s,r,{spec:o})=>{if(!(e&&o.diagnostic!=e))return i=new o0(s,r,o.diagnostic),!1}),i}function l0(n,e){return!!(n.effects.some(t=>t.is(Qr))||n.changes.touchesRange(e.pos))}function Uc(n,e){return n.field(Be,!1)?e:e.concat(R.appendConfig.of([Be,O.decorations.compute([Be],t=>{let{selected:i,panel:s}=t.field(Be);return!i||!s||i.from==i.to?E.none:E.set([h0.range(i.from,i.to)])}),Sd(c0,{hideOn:l0}),b0]))}function a0(n,e){return{effects:Uc(n,[Qr.of(e)])}}const Qr=R.define(),eo=R.define(),Gc=R.define(),Be=Me.define({create(){return new At(E.none,null,null)},update(n,e){if(e.docChanged){let t=n.diagnostics.map(e.changes),i=null;if(n.selected){let s=e.changes.mapPos(n.selected.from,1);i=ni(t,n.selected.diagnostic,s)||ni(t,null,s)}n=new At(t,n.panel,i)}for(let t of e.effects)t.is(Qr)?n=At.init(t.value,n.panel,e.state):t.is(eo)?n=new At(n.diagnostics,t.value?Qn.open:null,n.selected):t.is(Gc)&&(n=new At(n.diagnostics,n.panel,t.value));return n},provide:n=>[ar.from(n,e=>e.panel),O.decorations.from(n,e=>e.diagnostics)]}),h0=E.mark({class:"cm-lintRange cm-lintRange-active"});function c0(n,e,t){let{diagnostics:i}=n.state.field(Be),s=[],r=2e8,o=0;i.between(e-(t<0?1:0),e+(t>0?1:0),(a,h,{spec:c})=>{e>=a&&e<=h&&(a==h||(e>a||t>0)&&(eJc(n,t,!1)))}const u0=n=>{let e=n.state.field(Be,!1);(!e||!e.panel)&&n.dispatch({effects:Uc(n.state,[eo.of(!0)])});let t=Md(n,Qn.open);return t&&t.dom.querySelector(".cm-panel-lint ul").focus(),!0},Ul=n=>{let e=n.state.field(Be,!1);return!e||!e.panel?!1:(n.dispatch({effects:eo.of(!1)}),!0)},d0=n=>{let e=n.state.field(Be,!1);if(!e)return!1;let t=n.state.selection.main,i=e.diagnostics.iter(t.to+1);return!i.value&&(i=e.diagnostics.iter(0),!i.value||i.from==t.from&&i.to==t.to)?!1:(n.dispatch({selection:{anchor:i.from,head:i.to},scrollIntoView:!0}),!0)},p0=[{key:"Mod-Shift-m",run:u0},{key:"F8",run:d0}],m0=be.fromClass(class{constructor(n){this.view=n,this.timeout=-1,this.set=!0;let{delay:e}=n.state.facet(Kt);this.lintTime=Date.now()+e,this.run=this.run.bind(this),this.timeout=setTimeout(this.run,e)}run(){let n=Date.now();if(nPromise.resolve(i(this.view)))).then(i=>{let s=i.reduce((r,o)=>r.concat(o));this.view.state.doc==e.doc&&this.view.dispatch(a0(this.view.state,s))},i=>{He(this.view.state,i)})}}update(n){let e=n.state.facet(Kt);(n.docChanged||e!=n.startState.facet(Kt))&&(this.lintTime=Date.now()+e.delay,this.set||(this.set=!0,this.timeout=setTimeout(this.run,e.delay)))}force(){this.set&&(this.lintTime=Date.now(),this.run())}destroy(){clearTimeout(this.timeout)}}),Kt=D.define({combine(n){return Object.assign({sources:n.map(e=>e.source)},_t(n.map(e=>e.config),{delay:750,markerFilter:null,tooltipFilter:null}))},enables:m0});function $c(n){let e=[];if(n)e:for(let{name:t}of n){for(let i=0;ir.toLowerCase()==s.toLowerCase())){e.push(s);continue e}}e.push("")}return e}function Jc(n,e,t){var i;let s=t?$c(e.actions):[];return Je("li",{class:"cm-diagnostic cm-diagnostic-"+e.severity},Je("span",{class:"cm-diagnosticText"},e.renderMessage?e.renderMessage():e.message),(i=e.actions)===null||i===void 0?void 0:i.map((r,o)=>{let l=f=>{f.preventDefault();let u=ni(n.state.field(Be).diagnostics,e);u&&r.apply(n,u.from,u.to)},{name:a}=r,h=s[o]?a.indexOf(s[o]):-1,c=h<0?a:[a.slice(0,h),Je("u",a.slice(h,h+1)),a.slice(h+1)];return Je("button",{type:"button",class:"cm-diagnosticAction",onclick:l,onmousedown:l,"aria-label":` Action: ${a}${h<0?"":` (access key "${s[o]})"`}.`},c)}),e.source&&Je("div",{class:"cm-diagnosticSource"},e.source))}class g0 extends tt{constructor(e){super(),this.diagnostic=e}eq(e){return e.diagnostic==this.diagnostic}toDOM(){return Je("span",{class:"cm-lintPoint cm-lintPoint-"+this.diagnostic.severity})}}class Gl{constructor(e,t){this.diagnostic=t,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=Jc(e,t,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class Qn{constructor(e){this.view=e,this.items=[];let t=s=>{if(s.keyCode==27)Ul(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:r}=this.items[this.selectedIndex],o=$c(r.actions);for(let l=0;l{for(let r=0;rUl(this.view)},"×")),this.update()}get selectedIndex(){let e=this.view.state.field(Be).selected;if(!e)return-1;for(let t=0;t{let h=-1,c;for(let f=i;fi&&(this.items.splice(i,h-i),s=!0)),t&&c.diagnostic==t.diagnostic?c.dom.hasAttribute("aria-selected")||(c.dom.setAttribute("aria-selected","true"),r=c):c.dom.hasAttribute("aria-selected")&&c.dom.removeAttribute("aria-selected"),i++});i({sel:r.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:o,panel:l})=>{o.topl.bottom&&(this.list.scrollTop+=o.bottom-l.bottom)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let e=this.list.firstChild;function t(){let i=e;e=i.nextSibling,i.remove()}for(let i of this.items)if(i.dom.parentNode==this.list){for(;e!=i.dom;)t();e=i.dom.nextSibling}else this.list.insertBefore(i.dom,e);for(;e;)t()}moveSelection(e){if(this.selectedIndex<0)return;let t=this.view.state.field(Be),i=ni(t.diagnostics,this.items[e].diagnostic);i&&this.view.dispatch({selection:{anchor:i.from,head:i.to},scrollIntoView:!0,effects:Gc.of(i)})}static open(e){return new Qn(e)}}function y0(n,e='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,${encodeURIComponent(n)}')`}function Os(n){return y0(``,'width="6" height="3"')}const b0=O.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:Os("#d11")},".cm-lintRange-warning":{backgroundImage:Os("orange")},".cm-lintRange-info":{backgroundImage:Os("#999")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}}),w0=(()=>[Ld(),td(),em(),Dp(),Ku(),N.allowMultipleSelections.of(!0),pp(),Hr(Pp,{fallback:!0}),$g(),ud(),md(),qn.of([...Zg,...Zm,...hm,...Cp,...r0,...p0])])(),$l={python:()=>Pe(()=>import("./index-79ad4076.js"),["./index-79ad4076.js","./index-767254b1.js","./index-8c3da1d9.js","./index-4e8912f3.css","./Blocks-6ad6f005.js","./Button-62634b34.js","./Button-4cd12e76.css","./Blocks-005a10ea.css","./BlockLabel-98ef75ee.js","./Empty-5d52e655.js","./Copy-fd383441.js","./Download-dfb06e25.js","./DropdownArrow-5fa4dd09.css"],import.meta.url).then(n=>n.python()),markdown:async()=>{const[n,e]=await Promise.all([Pe(()=>import("./index-6d2143a6.js"),["./index-6d2143a6.js","./index-cfae41de.js","./index-767254b1.js","./index-26c6ce60.js","./index-8c3da1d9.js","./index-4e8912f3.css","./Blocks-6ad6f005.js","./Button-62634b34.js","./Button-4cd12e76.css","./Blocks-005a10ea.css","./BlockLabel-98ef75ee.js","./Empty-5d52e655.js","./Copy-fd383441.js","./Download-dfb06e25.js","./DropdownArrow-5fa4dd09.css","./index-0f59eac9.js"],import.meta.url),Pe(()=>import("./frontmatter-1b6984ab.js"),["./frontmatter-1b6984ab.js","./yaml-95012b83.js","./index-8c3da1d9.js","./index-4e8912f3.css","./Blocks-6ad6f005.js","./Button-62634b34.js","./Button-4cd12e76.css","./Blocks-005a10ea.css","./BlockLabel-98ef75ee.js","./Empty-5d52e655.js","./Copy-fd383441.js","./Download-dfb06e25.js","./DropdownArrow-5fa4dd09.css"],import.meta.url)]);return n.markdown({extensions:[e.frontmatter]})},json:()=>Pe(()=>import("./index-b4cdeff1.js"),["./index-b4cdeff1.js","./index-767254b1.js","./index-8c3da1d9.js","./index-4e8912f3.css","./Blocks-6ad6f005.js","./Button-62634b34.js","./Button-4cd12e76.css","./Blocks-005a10ea.css","./BlockLabel-98ef75ee.js","./Empty-5d52e655.js","./Copy-fd383441.js","./Download-dfb06e25.js","./DropdownArrow-5fa4dd09.css"],import.meta.url).then(n=>n.json()),html:()=>Pe(()=>import("./index-cfae41de.js"),["./index-cfae41de.js","./index-767254b1.js","./index-26c6ce60.js","./index-8c3da1d9.js","./index-4e8912f3.css","./Blocks-6ad6f005.js","./Button-62634b34.js","./Button-4cd12e76.css","./Blocks-005a10ea.css","./BlockLabel-98ef75ee.js","./Empty-5d52e655.js","./Copy-fd383441.js","./Download-dfb06e25.js","./DropdownArrow-5fa4dd09.css","./index-0f59eac9.js"],import.meta.url).then(n=>n.html()),css:()=>Pe(()=>import("./index-26c6ce60.js"),["./index-26c6ce60.js","./index-767254b1.js","./index-8c3da1d9.js","./index-4e8912f3.css","./Blocks-6ad6f005.js","./Button-62634b34.js","./Button-4cd12e76.css","./Blocks-005a10ea.css","./BlockLabel-98ef75ee.js","./Empty-5d52e655.js","./Copy-fd383441.js","./Download-dfb06e25.js","./DropdownArrow-5fa4dd09.css"],import.meta.url).then(n=>n.css()),javascript:()=>Pe(()=>import("./index-0f59eac9.js"),["./index-0f59eac9.js","./index-767254b1.js","./index-8c3da1d9.js","./index-4e8912f3.css","./Blocks-6ad6f005.js","./Button-62634b34.js","./Button-4cd12e76.css","./Blocks-005a10ea.css","./BlockLabel-98ef75ee.js","./Empty-5d52e655.js","./Copy-fd383441.js","./Download-dfb06e25.js","./DropdownArrow-5fa4dd09.css"],import.meta.url).then(n=>n.javascript()),typescript:()=>Pe(()=>import("./index-0f59eac9.js"),["./index-0f59eac9.js","./index-767254b1.js","./index-8c3da1d9.js","./index-4e8912f3.css","./Blocks-6ad6f005.js","./Button-62634b34.js","./Button-4cd12e76.css","./Blocks-005a10ea.css","./BlockLabel-98ef75ee.js","./Empty-5d52e655.js","./Copy-fd383441.js","./Download-dfb06e25.js","./DropdownArrow-5fa4dd09.css"],import.meta.url).then(n=>n.javascript({typescript:!0})),yaml:()=>Pe(()=>import("./yaml-95012b83.js"),[],import.meta.url).then(n=>jt.define(n.yaml)),dockerfile:()=>Pe(()=>import("./dockerfile-d67bbd50.js"),[],import.meta.url).then(n=>jt.define(n.dockerFile)),shell:()=>Pe(()=>import("./shell-86dd1d99.js"),[],import.meta.url).then(n=>jt.define(n.shell)),r:()=>Pe(()=>import("./r-3ca97919.js"),[],import.meta.url).then(n=>jt.define(n.r))},k0={py:"python",md:"markdown",js:"javascript",ts:"typescript",sh:"shell"};async function v0(n){const e=$l[n]||$l[k0[n]]||void 0;if(e)return e()}function x0(n){let e,t,i;return{c(){e=dt("div"),t=dt("div"),se(t,"class",i="codemirror-wrapper "+n[0]+" svelte-1sc8eck"),se(e,"class","wrap svelte-1sc8eck")},m(s,r){Ce(s,e,r),Yt(e,t),n[12](t)},p(s,[r]){r&1&&i!==(i="codemirror-wrapper "+s[0]+" svelte-1sc8eck")&&se(t,"class",i)},i:vi,o:vi,d(s){s&&Ae(e),n[12](null)}}}function S0(n){let e=n.dom.querySelectorAll(".cm-gutterElement");if(e.length===0)return null;for(var t=0;t(y=k(),()=>y?.destroy()));function Q(M){xr[M?"unshift":"push"](()=>{g=M,t(1,g)})}return n.$$set=M=>{"classNames"in M&&t(0,i=M.classNames),"value"in M&&t(2,s=M.value),"dark_mode"in M&&t(3,r=M.dark_mode),"basic"in M&&t(4,o=M.basic),"language"in M&&t(5,l=M.language),"lines"in M&&t(6,a=M.lines),"extensions"in M&&t(7,h=M.extensions),"useTab"in M&&t(8,c=M.useTab),"readonly"in M&&t(9,f=M.readonly),"placeholder"in M&&t(10,u=M.placeholder)},n.$$.update=()=>{n.$$.dirty&32&&b(l),n.$$.dirty&2048&&G(),n.$$.dirty&4&&v(s),n.$$.dirty&64&&S()},[i,g,s,r,o,l,a,h,c,f,u,p,Q]}class Yc extends si{constructor(e){super(),ri(this,e,C0,x0,oi,{classNames:0,value:2,dark_mode:3,basic:4,language:5,lines:6,extensions:7,useTab:8,readonly:9,placeholder:10})}}function Jl(n){let e,t,i,s;return t=new ca({}),{c(){e=dt("span"),fe(t.$$.fragment),se(e,"class","check svelte-qi7jcw")},m(r,o){Ce(r,e,o),ue(t,e,null),s=!0},i(r){s||(H(t.$$.fragment,r),ea(()=>{s&&(i||(i=bn(e,wn,{},!0)),i.run(1))}),s=!0)},o(r){j(t.$$.fragment,r),i||(i=bn(e,wn,{},!1)),i.run(0),s=!1},d(r){r&&Ae(e),de(t),r&&i&&i.end()}}}function A0(n){let e,t,i,s,r,o,l;i=new ef({});let a=n[0]&&Jl();return{c(){e=dt("button"),t=dt("span"),fe(i.$$.fragment),s=pt(),a&&a.c(),se(t,"class","copy-text"),yn(t,"copied",n[0]),se(e,"title","copy"),se(e,"class","svelte-qi7jcw")},m(h,c){Ce(h,e,c),Yt(e,t),ue(i,t,null),Yt(e,s),a&&a.m(e,null),r=!0,o||(l=Zl(e,"click",n[1]),o=!0)},p(h,[c]){(!r||c&1)&&yn(t,"copied",h[0]),h[0]?a?c&1&&H(a,1):(a=Jl(),a.c(),H(a,1),a.m(e,null)):a&&(_n(),j(a,1,1,()=>{a=null}),Vn())},i(h){r||(H(i.$$.fragment,h),H(a),r=!0)},o(h){j(i.$$.fragment,h),j(a),r=!1},d(h){h&&Ae(e),de(i),a&&a.d(),o=!1,l()}}}function M0(n,e,t){let i=!1,{value:s}=e,r;function o(){t(0,i=!0),r&&clearTimeout(r),r=setTimeout(()=>{t(0,i=!1)},2e3)}async function l(){"clipboard"in navigator&&(await navigator.clipboard.writeText(s),o())}return Ql(()=>{r&&clearTimeout(r)}),n.$$set=a=>{"value"in a&&t(2,s=a.value)},[i,l,s]}class D0 extends si{constructor(e){super(),ri(this,e,M0,A0,oi,{value:2})}}function Yl(n){let e,t,i,s;return t=new ca({}),{c(){e=dt("span"),fe(t.$$.fragment),se(e,"class","check svelte-14d303a")},m(r,o){Ce(r,e,o),ue(t,e,null),s=!0},i(r){s||(H(t.$$.fragment,r),ea(()=>{s&&(i||(i=bn(e,wn,{},!0)),i.run(1))}),s=!0)},o(r){j(t.$$.fragment,r),i||(i=bn(e,wn,{},!1)),i.run(0),s=!1},d(r){r&&Ae(e),de(t),r&&i&&i.end()}}}function T0(n){let e,t,i,s,r,o,l;t=new tf({});let a=n[0]&&Yl();return{c(){e=dt("a"),fe(t.$$.fragment),i=pt(),a&&a.c(),se(e,"download",s="file."+n[2]),se(e,"href",n[1]),se(e,"class","svelte-14d303a"),yn(e,"copied",n[0])},m(h,c){Ce(h,e,c),ue(t,e,null),Yt(e,i),a&&a.m(e,null),r=!0,o||(l=Zl(e,"click",n[3]),o=!0)},p(h,[c]){h[0]?a?c&1&&H(a,1):(a=Yl(),a.c(),H(a,1),a.m(e,null)):a&&(_n(),j(a,1,1,()=>{a=null}),Vn()),(!r||c&4&&s!==(s="file."+h[2]))&&se(e,"download",s),(!r||c&2)&&se(e,"href",h[1]),(!r||c&1)&&yn(e,"copied",h[0])},i(h){r||(H(t.$$.fragment,h),H(a),r=!0)},o(h){j(t.$$.fragment,h),j(a),r=!1},d(h){h&&Ae(e),de(t),a&&a.d(),o=!1,l()}}}function O0(n){return{py:"py",python:"py",md:"md",markdown:"md",json:"json",html:"html",css:"css",js:"js",javascript:"js",ts:"ts",typescript:"ts",yaml:"yaml",yml:"yml",dockerfile:"dockerfile",sh:"sh",shell:"sh",r:"r"}[n]||"txt"}function B0(n,e,t){let i,s,{value:r}=e,{language:o}=e,l=!1,a;function h(){t(0,l=!0),a&&clearTimeout(a),a=setTimeout(()=>{t(0,l=!1)},2e3)}return Ql(()=>{a&&clearTimeout(a)}),n.$$set=c=>{"value"in c&&t(4,r=c.value),"language"in c&&t(5,o=c.language)},n.$$.update=()=>{n.$$.dirty&32&&t(2,i=O0(o)),n.$$.dirty&16&&t(1,s=URL.createObjectURL(new Blob([r])))},[l,s,i,h,r,o]}class P0 extends si{constructor(e){super(),ri(this,e,B0,T0,oi,{value:4,language:5})}}function E0(n){let e,t,i,s,r;return t=new P0({props:{value:n[0],language:n[1]}}),s=new D0({props:{value:n[0]}}),{c(){e=dt("div"),fe(t.$$.fragment),i=pt(),fe(s.$$.fragment),se(e,"class","svelte-1yin446")},m(o,l){Ce(o,e,l),ue(t,e,null),Yt(e,i),ue(s,e,null),r=!0},p(o,[l]){const a={};l&1&&(a.value=o[0]),l&2&&(a.language=o[1]),t.$set(a);const h={};l&1&&(h.value=o[0]),s.$set(h)},i(o){r||(H(t.$$.fragment,o),H(s.$$.fragment,o),r=!0)},o(o){j(t.$$.fragment,o),j(s.$$.fragment,o),r=!1},d(o){o&&Ae(e),de(t),de(s)}}}function R0(n,e,t){let{value:i}=e,{language:s}=e;return n.$$set=r=>{"value"in r&&t(0,i=r.value),"language"in r&&t(1,s=r.language)},[i,s]}class L0 extends si{constructor(e){super(),ri(this,e,R0,E0,oi,{value:0,language:1})}}function I0(n){let e,t;return e=new aa({props:{variant:"solid",padding:!1,elem_id:n[3],elem_classes:n[4],visible:n[5],$$slots:{default:[_0]},$$scope:{ctx:n}}}),{c(){fe(e.$$.fragment)},m(i,s){ue(e,i,s),t=!0},p(i,s){const r={};s&8&&(r.elem_id=i[3]),s&16&&(r.elem_classes=i[4]),s&32&&(r.visible=i[5]),s&131975&&(r.$$scope={dirty:s,ctx:i}),e.$set(r)},i(i){t||(H(e.$$.fragment,i),t=!0)},o(i){j(e.$$.fragment,i),t=!1},d(i){de(e,i)}}}function N0(n){let e,t;return e=new aa({props:{variant:"solid",padding:!1,elem_id:n[3],elem_classes:n[4],visible:n[5],$$slots:{default:[W0]},$$scope:{ctx:n}}}),{c(){fe(e.$$.fragment)},m(i,s){ue(e,i,s),t=!0},p(i,s){const r={};s&8&&(r.elem_id=i[3]),s&16&&(r.elem_classes=i[4]),s&32&&(r.visible=i[5]),s&131975&&(r.$$scope={dirty:s,ctx:i}),e.$set(r)},i(i){t||(H(e.$$.fragment,i),t=!0)},o(i){j(e.$$.fragment,i),t=!1},d(i){de(e,i)}}}function _0(n){let e,t,i,s,r,o,l;const a=[n[9]];let h={};for(let u=0;usa(r,"value",c)),{c(){fe(e.$$.fragment),t=pt(),fe(i.$$.fragment),s=pt(),fe(r.$$.fragment)},m(u,d){ue(e,u,d),Ce(u,t,d),ue(i,u,d),Ce(u,s,d),ue(r,u,d),l=!0},p(u,d){const p=d&512?ra(a,[oa(u[9])]):{};e.$set(p);const g={};d&256&&(g.show_label=u[8]),d&128&&(g.label=u[7]),i.$set(g);const y={};d&2&&(y.language=u[1]),d&4&&(y.lines=u[2]),!o&&d&1&&(o=!0,y.value=u[0],la(()=>o=!1)),r.$set(y)},i(u){l||(H(e.$$.fragment,u),H(i.$$.fragment,u),H(r.$$.fragment,u),l=!0)},o(u){j(e.$$.fragment,u),j(i.$$.fragment,u),j(r.$$.fragment,u),l=!1},d(u){de(e,u),u&&Ae(t),de(i,u),u&&Ae(s),de(r,u)}}}function V0(n){let e,t,i,s,r;e=new L0({props:{language:n[1],value:n[0]}});function o(a){n[13](a)}let l={language:n[1],lines:n[2],dark_mode:n[10],readonly:!0};return n[0]!==void 0&&(l.value=n[0]),i=new Yc({props:l}),xr.push(()=>sa(i,"value",o)),{c(){fe(e.$$.fragment),t=pt(),fe(i.$$.fragment)},m(a,h){ue(e,a,h),Ce(a,t,h),ue(i,a,h),r=!0},p(a,h){const c={};h&2&&(c.language=a[1]),h&1&&(c.value=a[0]),e.$set(c);const f={};h&2&&(f.language=a[1]),h&4&&(f.lines=a[2]),!s&&h&1&&(s=!0,f.value=a[0],la(()=>s=!1)),i.$set(f)},i(a){r||(H(e.$$.fragment,a),H(i.$$.fragment,a),r=!0)},o(a){j(e.$$.fragment,a),j(i.$$.fragment,a),r=!1},d(a){de(e,a),a&&Ae(t),de(i,a)}}}function F0(n){let e,t;return e=new Qc({props:{size:"large",unpadded_box:!0,$$slots:{default:[H0]},$$scope:{ctx:n}}}),{c(){fe(e.$$.fragment)},m(i,s){ue(e,i,s),t=!0},p(i,s){const r={};s&131072&&(r.$$scope={dirty:s,ctx:i}),e.$set(r)},i(i){t||(H(e.$$.fragment,i),t=!0)},o(i){j(e.$$.fragment,i),t=!1},d(i){de(e,i)}}}function H0(n){let e,t;return e=new Sr({}),{c(){fe(e.$$.fragment)},m(i,s){ue(e,i,s),t=!0},i(i){t||(H(e.$$.fragment,i),t=!0)},o(i){j(e.$$.fragment,i),t=!1},d(i){de(e,i)}}}function W0(n){let e,t,i,s,r,o,l,a;const h=[n[9]];let c={};for(let p=0;p{u[v]=null}),Vn(),o=u[r],o?o.p(p,g):(o=u[r]=f[r](p),o.c()),H(o,1),o.m(l.parentNode,l))},i(p){a||(H(e.$$.fragment,p),H(i.$$.fragment,p),H(o),a=!0)},o(p){j(e.$$.fragment,p),j(i.$$.fragment,p),j(o),a=!1},d(p){de(e,p),p&&Ae(t),de(i,p),p&&Ae(s),u[r].d(p),p&&Ae(l)}}}function z0(n){let e,t,i,s;const r=[N0,I0],o=[];function l(a,h){return a[6]==="static"?0:1}return e=l(n),t=o[e]=r[e](n),{c(){t.c(),i=ta()},m(a,h){o[e].m(a,h),Ce(a,i,h),s=!0},p(a,[h]){let c=e;e=l(a),e===c?o[e].p(a,h):(_n(),j(o[c],1,1,()=>{o[c]=null}),Vn(),t=o[e],t?t.p(a,h):(t=o[e]=r[e](a),t.c()),H(t,1),t.m(i.parentNode,i))},i(a){s||(H(t),s=!0)},o(a){j(t),s=!1},d(a){o[e].d(a),a&&Ae(i)}}}function q0(n,e,t){const i=Xl();let{value:s=""}=e,{value_is_output:r=!1}=e,{language:o=""}=e,{lines:l=5}=e,{target:a}=e,{elem_id:h=""}=e,{elem_classes:c=[]}=e,{visible:f=!0}=e,{mode:u}=e,{label:d="Code"}=e,{show_label:p=!0}=e,{loading_status:g}=e,y=a.classList.contains("dark");function b(){i("change",s),r||i("input")}Zc(()=>{t(11,r=!1)});function v(k){s=k,t(0,s)}function S(k){s=k,t(0,s)}return n.$$set=k=>{"value"in k&&t(0,s=k.value),"value_is_output"in k&&t(11,r=k.value_is_output),"language"in k&&t(1,o=k.language),"lines"in k&&t(2,l=k.lines),"target"in k&&t(12,a=k.target),"elem_id"in k&&t(3,h=k.elem_id),"elem_classes"in k&&t(4,c=k.elem_classes),"visible"in k&&t(5,f=k.visible),"mode"in k&&t(6,u=k.mode),"label"in k&&t(7,d=k.label),"show_label"in k&&t(8,p=k.show_label),"loading_status"in k&&t(9,g=k.loading_status)},n.$$.update=()=>{n.$$.dirty&1&&b()},[s,o,l,h,c,f,u,d,p,g,y,r,a,v,S]}class j0 extends si{constructor(e){super(),ri(this,e,q0,z0,oi,{value:0,value_is_output:11,language:1,lines:2,target:12,elem_id:3,elem_classes:4,visible:5,mode:6,label:7,show_label:8,loading_status:9})}}const K0=j0,U0=["static","dynamic"],uy=Object.freeze(Object.defineProperty({__proto__:null,Component:K0,modes:U0},Symbol.toStringTag,{value:"Module"}));export{np as A,cy as B,bg as C,Id as D,w as E,uy as F,ee as I,ur as L,Lr as N,Rh as P,jt as S,z as T,hy as a,ry as b,xe as c,oy as d,L as e,gp as f,Ge as g,pe as h,op as i,Vi as j,qn as k,Ie as l,Nh as m,Dt as n,mp as o,ny as p,Vh as q,ti as r,Zd as s,m as t,Lp as u,O as v,ay as w,iy as x,fy as y,ly as z}; -//# sourceMappingURL=index-aa084753.js.map diff --git a/spaces/lambdalabs/LambdaSuperRes/KAIR/retinaface/retinaface_detection.py b/spaces/lambdalabs/LambdaSuperRes/KAIR/retinaface/retinaface_detection.py deleted file mode 100644 index 24e9919bb3f9656cc2601f868a85276ad852c00f..0000000000000000000000000000000000000000 --- a/spaces/lambdalabs/LambdaSuperRes/KAIR/retinaface/retinaface_detection.py +++ /dev/null @@ -1,124 +0,0 @@ -''' -@paper: GAN Prior Embedded Network for Blind Face Restoration in the Wild (CVPR2021) -@author: yangxy (yangtao9009@gmail.com) -''' - - -import sys -path_retinaface = 'retinaface' -if path_retinaface not in sys.path: - sys.path.insert(0, path_retinaface) - -import os -import torch -import torch.backends.cudnn as cudnn -import numpy as np -from data_faces import cfg_re50 -from layers.functions.prior_box import PriorBox -from utils_faces.nms.py_cpu_nms import py_cpu_nms -import cv2 -from facemodels.retinaface import RetinaFace -from utils_faces.box_utils import decode, decode_landm -import time - - -class RetinaFaceDetection(object): - def __init__(self, model_path): - torch.set_grad_enabled(False) - cudnn.benchmark = True - self.pretrained_path = model_path - self.device = torch.cuda.current_device() - self.cfg = cfg_re50 - self.net = RetinaFace(cfg=self.cfg, phase='test') - self.load_model() - self.net = self.net.cuda() - - def check_keys(self, pretrained_state_dict): - ckpt_keys = set(pretrained_state_dict.keys()) - model_keys = set(self.net.state_dict().keys()) - used_pretrained_keys = model_keys & ckpt_keys - unused_pretrained_keys = ckpt_keys - model_keys - missing_keys = model_keys - ckpt_keys - assert len(used_pretrained_keys) > 0, 'load NONE from pretrained checkpoint' - return True - - def remove_prefix(self, state_dict, prefix): - ''' Old style model is stored with all names of parameters sharing common prefix 'module.' ''' - f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x - return {f(key): value for key, value in state_dict.items()} - - def load_model(self, load_to_cpu=False): - if load_to_cpu: - pretrained_dict = torch.load(self.pretrained_path, map_location=lambda storage, loc: storage) - else: - pretrained_dict = torch.load(self.pretrained_path, map_location=lambda storage, loc: storage.cuda()) - if "state_dict" in pretrained_dict.keys(): - pretrained_dict = self.remove_prefix(pretrained_dict['state_dict'], 'module.') - else: - pretrained_dict = self.remove_prefix(pretrained_dict, 'module.') - self.check_keys(pretrained_dict) - self.net.load_state_dict(pretrained_dict, strict=False) - self.net.eval() - - def detect(self, img_raw, resize=1, confidence_threshold=0.9, nms_threshold=0.4, top_k=5000, keep_top_k=750, save_image=False): - img = np.float32(img_raw) - - im_height, im_width = img.shape[:2] - scale = torch.Tensor([img.shape[1], img.shape[0], img.shape[1], img.shape[0]]) - img -= (104, 117, 123) - img = img.transpose(2, 0, 1) - img = torch.from_numpy(img).unsqueeze(0) - img = img.cuda() - scale = scale.cuda() - - loc, conf, landms = self.net(img) # forward pass - - priorbox = PriorBox(self.cfg, image_size=(im_height, im_width)) - priors = priorbox.forward() - priors = priors.cuda() - prior_data = priors.data - boxes = decode(loc.data.squeeze(0), prior_data, self.cfg['variance']) - boxes = boxes * scale / resize - boxes = boxes.cpu().numpy() - scores = conf.squeeze(0).data.cpu().numpy()[:, 1] - landms = decode_landm(landms.data.squeeze(0), prior_data, self.cfg['variance']) - scale1 = torch.Tensor([img.shape[3], img.shape[2], img.shape[3], img.shape[2], - img.shape[3], img.shape[2], img.shape[3], img.shape[2], - img.shape[3], img.shape[2]]) - scale1 = scale1.cuda() - landms = landms * scale1 / resize - landms = landms.cpu().numpy() - - # ignore low scores - inds = np.where(scores > confidence_threshold)[0] - boxes = boxes[inds] - landms = landms[inds] - scores = scores[inds] - - # keep top-K before NMS - order = scores.argsort()[::-1][:top_k] - boxes = boxes[order] - landms = landms[order] - scores = scores[order] - - # do NMS - dets = np.hstack((boxes, scores[:, np.newaxis])).astype(np.float32, copy=False) - keep = py_cpu_nms(dets, nms_threshold) - # keep = nms(dets, nms_threshold,force_cpu=args.cpu) - dets = dets[keep, :] - landms = landms[keep] - - # keep top-K faster NMS - dets = dets[:keep_top_k, :] - landms = landms[:keep_top_k, :] - - # sort faces(delete) - fscores = [det[4] for det in dets] - sorted_idx = sorted(range(len(fscores)), key=lambda k:fscores[k], reverse=False) # sort index - tmp = [landms[idx] for idx in sorted_idx] - landms = np.asarray(tmp) - - landms = landms.reshape((-1, 5, 2)) - landms = landms.transpose((0, 2, 1)) - landms = landms.reshape(-1, 10, ) - return dets, landms diff --git a/spaces/lewiswu1209/MockingBird/mkgui/train_vc.py b/spaces/lewiswu1209/MockingBird/mkgui/train_vc.py deleted file mode 100644 index 8c233724b6b5572903069a1a2c2a9d41dd3f2167..0000000000000000000000000000000000000000 --- a/spaces/lewiswu1209/MockingBird/mkgui/train_vc.py +++ /dev/null @@ -1,155 +0,0 @@ -from pydantic import BaseModel, Field -import os -from pathlib import Path -from enum import Enum -from typing import Any, Tuple -import numpy as np -from utils.load_yaml import HpsYaml -from utils.util import AttrDict -import torch - -# Constants -EXT_MODELS_DIRT = f"ppg_extractor{os.sep}saved_models" -CONV_MODELS_DIRT = f"ppg2mel{os.sep}saved_models" -ENC_MODELS_DIRT = f"encoder{os.sep}saved_models" - - -if os.path.isdir(EXT_MODELS_DIRT): - extractors = Enum('extractors', list((file.name, file) for file in Path(EXT_MODELS_DIRT).glob("**/*.pt"))) - print("Loaded extractor models: " + str(len(extractors))) -else: - raise Exception(f"Model folder {EXT_MODELS_DIRT} doesn't exist.") - -if os.path.isdir(CONV_MODELS_DIRT): - convertors = Enum('convertors', list((file.name, file) for file in Path(CONV_MODELS_DIRT).glob("**/*.pth"))) - print("Loaded convertor models: " + str(len(convertors))) -else: - raise Exception(f"Model folder {CONV_MODELS_DIRT} doesn't exist.") - -if os.path.isdir(ENC_MODELS_DIRT): - encoders = Enum('encoders', list((file.name, file) for file in Path(ENC_MODELS_DIRT).glob("**/*.pt"))) - print("Loaded encoders models: " + str(len(encoders))) -else: - raise Exception(f"Model folder {ENC_MODELS_DIRT} doesn't exist.") - -class Model(str, Enum): - VC_PPG2MEL = "ppg2mel" - -class Dataset(str, Enum): - AIDATATANG_200ZH = "aidatatang_200zh" - AIDATATANG_200ZH_S = "aidatatang_200zh_s" - -class Input(BaseModel): - # def render_input_ui(st, input) -> Dict: - # input["selected_dataset"] = st.selectbox( - # '选择数据集', - # ("aidatatang_200zh", "aidatatang_200zh_s") - # ) - # return input - model: Model = Field( - Model.VC_PPG2MEL, title="模型类型", - ) - # datasets_root: str = Field( - # ..., alias="预处理数据根目录", description="输入目录(相对/绝对),不适用于ppg2mel模型", - # format=True, - # example="..\\trainning_data\\" - # ) - output_root: str = Field( - ..., alias="输出目录(可选)", description="建议不填,保持默认", - format=True, - example="" - ) - continue_mode: bool = Field( - True, alias="继续训练模式", description="选择“是”,则从下面选择的模型中继续训练", - ) - gpu: bool = Field( - True, alias="GPU训练", description="选择“是”,则使用GPU训练", - ) - verbose: bool = Field( - True, alias="打印详情", description="选择“是”,输出更多详情", - ) - # TODO: Move to hiden fields by default - convertor: convertors = Field( - ..., alias="转换模型", - description="选择语音转换模型文件." - ) - extractor: extractors = Field( - ..., alias="特征提取模型", - description="选择PPG特征提取模型文件." - ) - encoder: encoders = Field( - ..., alias="语音编码模型", - description="选择语音编码模型文件." - ) - njobs: int = Field( - 8, alias="进程数", description="适用于ppg2mel", - ) - seed: int = Field( - default=0, alias="初始随机数", description="适用于ppg2mel", - ) - model_name: str = Field( - ..., alias="新模型名", description="仅在重新训练时生效,选中继续训练时无效", - example="test" - ) - model_config: str = Field( - ..., alias="新模型配置", description="仅在重新训练时生效,选中继续训练时无效", - example=".\\ppg2mel\\saved_models\\seq2seq_mol_ppg2mel_vctk_libri_oneshotvc_r4_normMel_v2" - ) - -class AudioEntity(BaseModel): - content: bytes - mel: Any - -class Output(BaseModel): - __root__: Tuple[str, int] - - def render_output_ui(self, streamlit_app, input) -> None: # type: ignore - """Custom output UI. - If this method is implmeneted, it will be used instead of the default Output UI renderer. - """ - sr, count = self.__root__ - streamlit_app.subheader(f"Dataset {sr} done processed total of {count}") - -def train_vc(input: Input) -> Output: - """Train VC(训练 VC)""" - - print(">>> OneShot VC training ...") - params = AttrDict() - params.update({ - "gpu": input.gpu, - "cpu": not input.gpu, - "njobs": input.njobs, - "seed": input.seed, - "verbose": input.verbose, - "load": input.convertor.value, - "warm_start": False, - }) - if input.continue_mode: - # trace old model and config - p = Path(input.convertor.value) - params.name = p.parent.name - # search a config file - model_config_fpaths = list(p.parent.rglob("*.yaml")) - if len(model_config_fpaths) == 0: - raise "No model yaml config found for convertor" - config = HpsYaml(model_config_fpaths[0]) - params.ckpdir = p.parent.parent - params.config = model_config_fpaths[0] - params.logdir = os.path.join(p.parent, "log") - else: - # Make the config dict dot visitable - config = HpsYaml(input.config) - np.random.seed(input.seed) - torch.manual_seed(input.seed) - if torch.cuda.is_available(): - torch.cuda.manual_seed_all(input.seed) - mode = "train" - from ppg2mel.train.train_linglf02mel_seq2seq_oneshotvc import Solver - solver = Solver(config, params, mode) - solver.load_data() - solver.set_model() - solver.exec() - print(">>> Oneshot VC train finished!") - - # TODO: pass useful return code - return Output(__root__=(input.dataset, 0)) \ No newline at end of file diff --git a/spaces/lixq/bingo61/src/pages/api/kblob.ts b/spaces/lixq/bingo61/src/pages/api/kblob.ts deleted file mode 100644 index 0ce7e6063cdc06838e76f1cff1d5982d34ef52de..0000000000000000000000000000000000000000 --- a/spaces/lixq/bingo61/src/pages/api/kblob.ts +++ /dev/null @@ -1,56 +0,0 @@ -'use server' - -import { NextApiRequest, NextApiResponse } from 'next' -import FormData from 'form-data' -import { fetch } from '@/lib/isomorphic' -import { KBlobRequest } from '@/lib/bots/bing/types' - -const API_DOMAIN = 'https://bing.vcanbb.top' - -export const config = { - api: { - bodyParser: { - sizeLimit: '10mb' // Set desired value here - } - } -} - -export default async function handler(req: NextApiRequest, res: NextApiResponse) { - try { - const { knowledgeRequest, imageBase64 } = req.body as KBlobRequest - - const formData = new FormData() - formData.append('knowledgeRequest', JSON.stringify(knowledgeRequest)) - if (imageBase64) { - formData.append('imageBase64', imageBase64) - } - - const response = await fetch(`${API_DOMAIN}/images/kblob`, - { - method: 'POST', - body: formData.getBuffer(), - headers: { - "sec-ch-ua": "\"Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"115\", \"Chromium\";v=\"115\"", - "sec-ch-ua-mobile": "?0", - "sec-ch-ua-platform": "\"Windows\"", - "Referer": `${API_DOMAIN}/web/index.html`, - "Referrer-Policy": "origin-when-cross-origin", - 'x-ms-useragent': 'azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/Win32', - ...formData.getHeaders() - } - } - ).then(res => res.text()) - - res.writeHead(200, { - 'Content-Type': 'application/json', - }) - res.end(response || JSON.stringify({ result: { value: 'UploadFailed', message: '请更换 IP 或代理后重试' } })) - } catch (e) { - return res.json({ - result: { - value: 'UploadFailed', - message: `${e}` - } - }) - } -} diff --git a/spaces/ljjggr/bingo/src/app/page.tsx b/spaces/ljjggr/bingo/src/app/page.tsx deleted file mode 100644 index 0dff3431b098ce4fe282cc83fc87a93a28a43090..0000000000000000000000000000000000000000 --- a/spaces/ljjggr/bingo/src/app/page.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import dynamic from 'next/dynamic' - -const DynamicComponentWithNoSSR = dynamic( - () => import('../components/chat'), - { ssr: false } -) - -export default function IndexPage() { - return ( - <> -
        - - - ) -} diff --git a/spaces/lubin1997/removebackground/README.md b/spaces/lubin1997/removebackground/README.md deleted file mode 100644 index 465a95850cc0062a60e78a7b2873068bbac1df7a..0000000000000000000000000000000000000000 --- a/spaces/lubin1997/removebackground/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Removebackground -emoji: 😻 -colorFrom: indigo -colorTo: indigo -sdk: gradio -sdk_version: 3.5 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/ma-xu/LIVE/thrust/dependencies/cub/test/link_main.cpp b/spaces/ma-xu/LIVE/thrust/dependencies/cub/test/link_main.cpp deleted file mode 100644 index ef677ee03b4febf543deed0867dd46e73b42e37d..0000000000000000000000000000000000000000 --- a/spaces/ma-xu/LIVE/thrust/dependencies/cub/test/link_main.cpp +++ /dev/null @@ -1,10 +0,0 @@ -#include - -extern void a(); -extern void b(); - -int main() -{ - printf("hello world\n"); - return 0; -} diff --git a/spaces/magicr/BuboGPT/bubogpt/datasets/builders/audio_base_dataset_builder.py b/spaces/magicr/BuboGPT/bubogpt/datasets/builders/audio_base_dataset_builder.py deleted file mode 100644 index 584fd7c2995305b2bfecdc4250cadebdd7fe020c..0000000000000000000000000000000000000000 --- a/spaces/magicr/BuboGPT/bubogpt/datasets/builders/audio_base_dataset_builder.py +++ /dev/null @@ -1,142 +0,0 @@ -import logging -import os -import shutil -import warnings - -from omegaconf import OmegaConf -import torch.distributed as dist -from torchvision.datasets.utils import download_url - -import bubogpt.common.utils as utils -from bubogpt.common.dist_utils import is_dist_avail_and_initialized, is_main_process -from bubogpt.common.registry import registry -from bubogpt.datasets.builders import load_dataset_config -from bubogpt.processors.base_processor import BaseProcessor - - -class AudioBaseDatasetBuilder: - train_dataset_cls, eval_dataset_cls = None, None - - def __init__(self, cfg=None): - super().__init__() - - if cfg is None: - # help to create datasets from default config. - self.config = load_dataset_config(self.default_config_path()) - elif isinstance(cfg, str): - self.config = load_dataset_config(cfg) - else: - # when called from task.build_dataset() - self.config = cfg - - self.data_type = self.config.data_type - - self.audio_processors = {"train": BaseProcessor(), "eval": BaseProcessor()} - self.text_processors = {"train": BaseProcessor(), "eval": BaseProcessor()} - - def build_datasets(self): - # download, split, etc... - # only called on 1 GPU/TPU in distributed - - if is_main_process(): - self._download_data() - - if is_dist_avail_and_initialized(): - dist.barrier() - - # at this point, all the annotations and image/videos should be all downloaded to the specified locations. - logging.info("Building datasets...") - datasets = self.build() # dataset['train'/'val'/'test'] - - return datasets - - def build_processors(self): - aud_proc_cfg = self.config.get("audio_processor") - txt_proc_cfg = self.config.get("text_processor") - - if aud_proc_cfg is not None: - aud_train_cfg = aud_proc_cfg.get("train") - aud_eval_cfg = aud_proc_cfg.get("eval") - - self.audio_processors["train"] = self._build_proc_from_cfg(aud_train_cfg) - self.audio_processors["eval"] = self._build_proc_from_cfg(aud_eval_cfg) - - if txt_proc_cfg is not None: - txt_train_cfg = txt_proc_cfg.get("train") - txt_eval_cfg = txt_proc_cfg.get("eval") - - self.text_processors["train"] = self._build_proc_from_cfg(txt_train_cfg) - self.text_processors["eval"] = self._build_proc_from_cfg(txt_eval_cfg) - - @staticmethod - def _build_proc_from_cfg(cfg): - return ( - registry.get_processor_class(cfg.name).from_config(cfg) - if cfg is not None - else None - ) - - @classmethod - def default_config_path(cls, type="default"): - return utils.get_abs_path(cls.DATASET_CONFIG_DICT[type]) - - def _download_data(self): - self._download_ann() - self._download_aud() - - def _download_ann(self): - """ - Download annotation files if necessary. - All the audio-language datasets should have annotations of unified format. - - storage_path can be: - (1) relative/absolute: will be prefixed with env.cache_root to make full path if relative. - (2) basename/dirname: will be suffixed with base name of URL if dirname is provided. - - Local annotation paths should be relative. - """ - anns = self.config.build_info.annotations - - splits = anns.keys() - - cache_root = registry.get_path("cache_root") - - for split in splits: - info = anns[split] - - urls, storage_paths = info.get("url", None), info.storage - - if isinstance(urls, str): - urls = [urls] - if isinstance(storage_paths, str): - storage_paths = [storage_paths] - - assert len(urls) == len(storage_paths) - - for url_or_filename, storage_path in zip(urls, storage_paths): - # if storage_path is relative, make it full by prefixing with cache_root. - if not os.path.isabs(storage_path): - storage_path = os.path.join(cache_root, storage_path) - - dirname = os.path.dirname(storage_path) - if not os.path.exists(dirname): - os.makedirs(dirname) - - if os.path.isfile(url_or_filename): - src, dst = url_or_filename, storage_path - if not os.path.exists(dst): - shutil.copyfile(src=src, dst=dst) - else: - logging.info("Using existing file {}.".format(dst)) - else: - if os.path.isdir(storage_path): - # if only dirname is provided, suffix with basename of URL. - raise ValueError( - "Expecting storage_path to be a file path, got directory {}".format( - storage_path - ) - ) - else: - filename = os.path.basename(storage_path) - - download_url(url=url_or_filename, root=dirname, filename=filename) diff --git a/spaces/matthoffner/falcon-mini/README.md b/spaces/matthoffner/falcon-mini/README.md deleted file mode 100644 index 57127e8c406095ce610b0bc814cc033e722e2195..0000000000000000000000000000000000000000 --- a/spaces/matthoffner/falcon-mini/README.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -title: falcon-mini -emoji: 🦅💸 -colorFrom: red -colorTo: blue -sdk: docker -pinned: false -app_port: 7860 -license: apache-2.0 ---- - -# falcon-7b-instruct - -## ggllm.cpp -## ctransformers \ No newline at end of file diff --git a/spaces/merle/PROTEIN_GENERATOR/utils/examples/secondary_structure_from_pdb.sh b/spaces/merle/PROTEIN_GENERATOR/utils/examples/secondary_structure_from_pdb.sh deleted file mode 100644 index b548870e8eade138a4c59ebada89fb4ab2a9ec68..0000000000000000000000000000000000000000 --- a/spaces/merle/PROTEIN_GENERATOR/utils/examples/secondary_structure_from_pdb.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash -#SBATCH -J seq_diff -#SBATCH -p gpu -#SBATCH --mem=8g -#SBATCH --gres=gpu:a6000:1 -#SBATCH -o ./out/slurm/slurm_%j.out - -source activate /software/conda/envs/SE3nv - -srun python ../inference.py \ - --num_designs 10 \ - --out out/design \ - --contigs 110 \ - --T 25 --save_best_plddt \ - --dssp_pdb ./pdbs/cd86.pdb - -# FOR SECONDARY STRUCTURE: -# X - mask -# H - helix -# E - strand -# L - loop diff --git a/spaces/merve/Grounding_DINO_demo/groundingdino/__init__.py b/spaces/merve/Grounding_DINO_demo/groundingdino/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/merve/chatgpt-prompt-generator-v12/README.md b/spaces/merve/chatgpt-prompt-generator-v12/README.md deleted file mode 100644 index 34189f2b6e3acfd620ffe3b1e7d0a70972f6f45f..0000000000000000000000000000000000000000 --- a/spaces/merve/chatgpt-prompt-generator-v12/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Chatgpt Prompt Generator V12 -emoji: 🐨 -colorFrom: blue -colorTo: blue -sdk: gradio -sdk_version: 3.20.1 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/merve/fill-in-the-blank/source/anonymization/init.js b/spaces/merve/fill-in-the-blank/source/anonymization/init.js deleted file mode 100644 index 5e181d580ff878e75ebbd508b052866e42c2ac1a..0000000000000000000000000000000000000000 --- a/spaces/merve/fill-in-the-blank/source/anonymization/init.js +++ /dev/null @@ -1,77 +0,0 @@ -d3.select('body').selectAppend('div.tooltip.tooltip-hidden') - -window.ages = '18 19 20 21 22'.split(' ') -window.states = 'RI NH NY CT VT'.split(' ') - -window.init = function(){ - // console.clear() - var graphSel = d3.select('#graph').html('').append('div') - window.c = d3.conventions({ - sel: graphSel, - width: 460, - height: 460, - }) - - function sizeGraphSel(){ - var clientWidth = d3.select('body').node().clientWidth - - window.scale = d3.clamp(1, (c.totalWidth + 35)/(clientWidth - 10), 2) // off by one, s is 35 - - graphSel.st({ - transform: `scale(${1/scale})`, - transformOrigin: `0px 0px`, - }) - - d3.select('#graph').st({height: scale == 1 ? 500 : 710}) - } - sizeGraphSel() - d3.select(window).on('resize', sizeGraphSel) - - - c.svg = c.svg.append('g').translate([.5, .5]) - - window.axii = makeAxii() - window.sliders = makeSliders() - window.students = makeStudents() - window.sel = makeSel() - window.slides = makeSlides() - window.estimates = makeEstimates() - - - - - var error = 0 - while (error < .02 || error > .05){ - estimates.flipCoin() - error = Math.abs(estimates.active.val - .5) - } - - makeGS() -} - -init() - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spaces/merve/uncertainty-calibration/public/fill-in-the-blank/style.css b/spaces/merve/uncertainty-calibration/public/fill-in-the-blank/style.css deleted file mode 100644 index 726984190483443c3da0905eae281514eccc7487..0000000000000000000000000000000000000000 --- a/spaces/merve/uncertainty-calibration/public/fill-in-the-blank/style.css +++ /dev/null @@ -1,737 +0,0 @@ -@media (max-width: 1100px){ - body{ - /*overflow-x: hidden;*/ - } -} - - -.tooltip { - top: -1000px; - position: absolute; - padding: 10px; - background: rgba(255, 255, 255, .8); - border: 0px solid lightgray; - - width: 300px; - font-size: 14px; - line-height: 1.4em; - background: rgba(0, 0, 0, .8); - color: #fff; - pointer-events: all !important; -} -.tooltip a{ - color: #fff !important; -} -.tooltip:hover{ -/* opacity: 1; - pointer-events: all !important; -*/} - -.tooltip-hidden{ - opacity: 0; - transition: all .3s; - transition-delay: .2s; - pointer-events: none !important; -} - -@media (max-width: 590px){ - .footend{ - margin-left: 0px; - width: 10px; - } - - - div.tooltip{ - transition: all 0s !important; - transition-delay: 0s !important; - - display: none; - position: fixed; - bottom: -1px; - width: calc(100%); - left: -1px !important; - right: -1px !important; - top: auto !important; - width: auto !important; - } -} - -svg{ - overflow: visible; -} - -.domain{ - display: none; -} - -.tick{ - display: none; -} - -.bg-tick{ - stroke: #eee; -} - -text{ - pointer-events: none; - /*fill: #fff;*/ - text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, 0 -1px 0 #fff, -1px 0 0 #fff; -} - -.pair{ - width: 820px; - /*height: 550px;*/ - margin: 0px auto; - margin-top: 25px !important -} - -.nurse-name-zari-cda{ - margin-bottom: 35px; -} - -.pair > div{ - display: inline-block; - vertical-align: top; -} - -.pair .graph{ - width: 500px; -} - -.pair .options{ - width: 250px; - padding-right: 20px; -} - -.pair .warning{ - width: 250px; - /*border: 1px solid orange;*/ - /*background: #fff9e4;*/ - /*padding: 10px;*/ - margin-top: 15px; - padding-left: 0px; - font-size: 14px; - line-height: 1.25em; - opacity: 0; - transition: all .2s; -} - -.pair .reset{ - width: 58px; - /*border: 1px solid orange;*/ - /*background: #fff9e4;*/ - /*padding: 10px;*/ - margin-top: 15px; - font-size: 14px; - line-height: 1.25em; - opacity: 0; - transition: opacity .2s; - cursor: pointer; - user-select: none; - outline: 1px solid #ccc; - padding: 5px; - -} -.pair .reset span{ - position: relative; - top: -1px; - padding-right: 4px; - padding-left: 1px; - /*font-size: ;*/ -} - -.pair .reset:hover{ - background: #eee; - color: #000; - outline: 1px solid #000; -} - -.options > *{ - margin-right: 10px; -} - -.options b{ - display: block; - margin-bottom: 5px; - margin-top: 10px; -} - - - - -.flex-row{ - width: 100%; - display: flex; - justify-content: space-between; - column-gap: 10px -} - -.flex-row > *{ - flex-grow: 1; - margin-right: 0px !important; -} - -.options > *{ - margin-right: 0px; -} - -.pair textarea{ - width: 100%; -} - -.flex-row-textarea{ - display: block; -} - -@media (max-width: 820px){ - .pair{ - width: 100%; - height: auto; - max-width: 500px; - margin: 0px auto; - } - - .flex-row{ - margin-bottom: -10px; - } - - .flex-row-textarea{ - display: flex; - margin-bottom: 10px; - } - - - .pair .options{ - width: auto; - padding-right: 0px; - } - - .warning{ - display: none !important; - } - - .reset{ - display: none !important; - } - - .pair .graph{ - width: 100%; - } - - .annotations{ - display: none; - } -} - - - -.pair.difference{ - width: 1000px; - margin-left: 0px; -} - -.pair.difference .pair-container{ -} - -.pair .options.wide{ - width: 100%; - margin-bottom: 20px; -} -.pair .options.wide > div{ - display: inline-block; -} - -.options.wide .option-type .button{ - width: 78px !important; -} - -.options.wide .option-model .button{ - width: 40px !important; -} - -.options.wide .update.button{ - width: 80px !important; -} - -textarea{ - font-family: 'Roboto', Helvetica, sans-serif; - font-weight: 300; - line-height: 1.55em; - font-size: 16px; - font-weight: bold; - border: 1px #ccc solid; - resize: none; -} - -.button.update{ - /*height: 20px;*/ - /*position: relative;*/ - /*top: -30px;*/ - /*margin-bottom: -10px;*/ - /*vertical-align: center;*/ - margin-top: 25px; - width: 252px; - text-align: center; - font-weight: 500; -} -.button{ - display: inline-block; - outline: 1px solid #ccc; - padding: 5px; - margin-top: 10px; - margin-right: 10px; - position: relative; - top: -12px; - cursor: pointer; - user-select: none; -} - -@media (hover: hover) and (pointer: fine) { - .button:hover{ - outline-color: #000; - } -} - -@media screen and (-webkit-min-device-pixel-ratio:0) and @media (max-width: 900px) { - select, - textarea, - input { - font-size: 16px !important; - } - - textarea{ - height: 80px !important; - } -} - - -.button.active{ - background: #eee; - color: #000; - /*font-weight: 500;*/ -} - - -.button.loading i{ - opacity: 1; -} - -.button.loading{ - pointer-events: none; - /*opacity: .6;*/ -} -.p-button{ - /*position: relative;*/ - /*top: -3px;*/ - /*line-height: 10px;*/ - /*line-height: */ - display: inline-block; - margin-right: 15px; -} -.p-button-link{ - text-decoration: underline; - cursor: pointer; - padding-right: 10px; -} -.interesting-pair-alts .p-button-link{ - display: block; - text-decoration: none; -} -.interesting-pair-alts .p-button-link div{ - padding-left: 10px; - padding-right: 10px; - padding-top: 5px; - padding-bottom: 5px; - outline: 1px solid #ccc; - margin-top: 5px; - margin-bottom: 5px; - margin-left: 10px; - -} -.difference-difference-alts .p-button-link:hover div{ - outline: 1px solid #000; -} - -.difference-difference-alts .p-button-link{ - display: block; - text-decoration: none; -} -.difference-difference-alts .p-button-link div{ - padding-left: 10px; - padding-right: 10px; - padding-top: 5px; - padding-bottom: 5px; - outline: 1px solid #ccc; - margin-top: 5px; - margin-bottom: 5px; - margin-left: 10px; - -} -.difference-difference-alts .p-button-link:hover div{ - outline: 1px solid #000; -} - - -.wide .flex-row{ - width: 220px; -} - -.wide > *{ - margin-right: 40px; -} - -.wide textarea{ - position: relative; - top: 12px; -} - - -@media (max-width: 1100px){ - .pair-container-overflow{ - overflow-x: scroll; - width: 100% !important; - } - - .pair.difference{ - width: auto; - max-width: 2000px; - } - - .pair.difference .options{ - margin: 0px auto; - margin-left: max(50vh - 500px, 0px); - width: min(500px, 100%); - } - -} - -.pair-container{ - width: 1000px; -} - - - - - -.checkbox{ - display: inline-block; - position: relative; - top: -10px; - margin-left: 10px; - -} - -circle:hover{ - stroke: blue; -} - - - -.hover text{ - fill: #000; - font-weight: 300; - /*stroke-width: 2px;*/ - /*text-shadow: 0 2px 0 #000, 2px 0 0 #000, 0 -2px 0 #000, -2px 0 0 #000;*/ -} - -#graph > div{ - display: inline-block; -} - -text.tiny{ - font-size: 9px; - font-family: monospace; - /*fill: #555;*/ -} - - - - - -svg{ - overflow: visible; -} - - -input{ - font-family: monospace; - width: 900px; - overflow: hidden; - background-color: rgba(0,0,0,0); - border: 0px; -} - -textarea{ - font-family: monospace; - font-size: 14px; -} - -/* Hide scrollbar for Chrome, Safari and Opera */ -.top-sents::-webkit-scrollbar { - /*display: none;*/ -} - -/* Hide scrollbar for IE, Edge and Firefox */ -.top-sents { - -ms-overflow-style: none; /* IE and Edge */ - scrollbar-width: none; /* Firefox */ -} - -.sent{ - margin-top: -15px; -} - - - -.post-summary{ - display: none; -} - - -.token-container{ - text-align: center; - line-height: 2em; -} - -.token{ - display: inline-block; - padding: 5px; - margin: 10px; - margin-top: 0px; - margin-bottom: 0px; - font-size: 20px; - font-family: monospace; - outline: 1px solid #ccc; - color: #000; - cursor: pointer; - background: #fff; - border: 0px; -} - -.token:hover, .token.active{ - outline: 1px solid #000; -} - - -.xy-only, .rotate-only{ - opacity: 0; - transition: all .2s; -} - -.annotations{ - transition: opacity .2s; -} - -.is-xy .xy-only{ - opacity: 1 !important; -} -.is-rotate .rotate-only{ - opacity: 1 !important; -} - -.hamlet{ - min-height: 304px; - margin-bottom: 20px; -} - -.hamlet-edit .button{ - color: #ccc; - pointer-events: none; -} -.hamlet-edit.changed .button{ - color: #000; - pointer-events: all; -} - -@media (max-width: 500px){ - .hamlet-edit .button{ - display: block; - text-align: center; - top: 0px !important; - margin: 0px auto !important; - margin-top: 5px !important; - width: 100%; - } -} - - - -.pair .update{ - color: #ccc; - pointer-events: none; -} -.pair.changed .update{ - color: #000; - pointer-events: all; -} - - - - -.difference-difference-list{ - display: none; -} - -.pair-container{ - width: 900px; -} -.pair-container > div{ - display: inline-block; -} - - -.difference-difference textarea{ - height: 52px; -} - -.not-is-color-by .y-axis-label text, .not-is-color-by .sent-1 text, .not-is-color-by .x-axis-label{ - fill: #444 !important; -} - -.is-color-by .y-axis-label text, .is-color-by .sent-1 text, .is-color-by .x-axis-label{ - font-weight: 400; - /*text-decoration: underline;*/ -} - - - -.time-token.active path{ - stroke: #f0f; - opacity: 1; -} -.time-token.active text{ - fill: #f0f !important; - opacity: 1 !important; - font-size: 14px; -} - - -.token{ - -} - -.gender-over-time{ - width: 1100px; - margin: 0px auto; - font-size: 14px; - margin-left: -91px; -} - -.gender-over-time .tick{ - display: block; -} - -.gender-over-time .axis{ - opacity: .7; -} - -.gender-over-time .sentence{ - /*position: relative;*/ - width: 32%; -} - -.gender-over-time .sentence .sentence-title{ - right: 42px; - position: relative; - text-align: right; - font-family: monospace; - -} -.gender-over-time .sentence.is-bear .sentence-title{ - /*text-align: center;*/ - right: 115px; -} - -.gender-over-time .g-caption{ - line-height: 18px; - margin-bottom: 30px; - margin-top: 5px; - width: 290px; - font-size: 13px; - left: 365px; - position: relative; -} - -@media (max-width: 1100px){ - .gender-over-time{ - width: 100%; - margin-left: 0px; - max-width: 500px; - margin: 0px auto; - } - - .gender-over-time .sentence{ - width: 100% !important; - margin-bottom: 20px; - } - - .gender-over-time .g-caption{ - left: 0px; - width: 100%; - } -} - -.time-token text{ - font-family: monospace; - pointer-events: all !important; - cursor: default; -} - - - -img[src*="img/wiki-years.png"] { - width: 300px; -} - - -#more-explorables{ - margin-top: 100px; -} - - - - -/*html{ - font-smooth: never; - -webkit-font-smoothing: none; - background: transparent; -} - -path{ - display: none; -}*/ - - -button { - display: inline-block; - border: none; - margin: 0; - text-decoration: none; - background: #fff; - color: #ffffff; - font-size: 1em; - cursor: pointer; - text-align: center; - -webkit-appearance: none; - -moz-appearance: none; - font-family : inherit; - -} - -button:active { - transform: scale(0.99); -} - - -info{ - font-weight: 300; - font-size: 12px; - line-height: 0em; - position: relative; - left: 7px; - top: -1px; - cursor: default; -} -info:hover{ - font-weight: 600; -} \ No newline at end of file diff --git a/spaces/merve/uncertainty-calibration/source/_posts/2019-10-01-anonymization.html b/spaces/merve/uncertainty-calibration/source/_posts/2019-10-01-anonymization.html deleted file mode 100644 index b2cedac240d8f4c3dfbbd820f4057a92074f090e..0000000000000000000000000000000000000000 --- a/spaces/merve/uncertainty-calibration/source/_posts/2019-10-01-anonymization.html +++ /dev/null @@ -1,188 +0,0 @@ - ---- -template: post.html -title: How randomized response can help collect sensitive information responsibly -shorttitle: Collecting Sensitive Information -summary: Giant datasets are revealing new patterns in cancer, income inequality and other important areas. However, the widespread availability of fast computers that can cross reference public data is making it harder to collect private information without inadvertently violating people's privacy. Modern randomization techniques can help preserve anonymity. -socialsummary: The availability of giant datasets and faster computers is making it harder to collect and study private information without inadvertently violating people's privacy. -shareimg: https://pair.withgoogle.com/explorables/images/anonymization.png -permalink: /anonymization/ -date: 2020-09-01 ---- - - - -
        -
        -
        -
        - -

        Anonymous Data

        - -

        Let's pretend we're analysts at a small college, looking at anonymous survey data about plagiarism. - -

        We've gotten responses from the entire student body, reporting if they've ever plagiarized or not. To encourage them to respond honestly, names were not collected. -

        - -

        The data here has been randomly generated

        -
        - - -
        -

        On the survey students also report several bits of information about themselves, like their age... -

        - - -
        -

        ...and what state they're from. - -

        This additional information is critical to finding potential patterns in the data—why have so many first-years from New Hampshire plagiarized? -

        - - -
        -

        Revealed Information

        -

        But granular information comes with a cost. - -

        One student has a unique age/home state combination. By searching another student database for a 19-year old from Vermont we can identify one of the plagiarists from supposedly anonymous survey data. -

        - - -
        -

        Increasing granularity exacerbates the problem. If the students reported slightly more about their ages by including what season they were born in, we'd be able to identify about a sixth of them. - -

        This isn't just a hypothetical: A birthday / gender / zip code combination uniquely identifies 83% of the people in the United States. - -

        With the spread of large datasets, it is increasingly difficult to release detailed information without inadvertently revealing someone's identity. A week of a person's location data could reveal a home and work address—possibly enough to find a name using public records. -

        - - -
        -

        Randomization

        -

        One solution is to randomize responses so each student has plausible deniability. This lets us buy privacy at the cost of some uncertainty in our estimation of plagiarism rates. - -

        Step 1: Each student flips a coin and looks at it without showing anyone. -

        - - -
        -

        Step 2: Students who flip heads report plagiarism, even if they haven't plagiarized. - -

        Students that flipped tails report the truth, secure with the knowledge that even if their response is linked back to their name, they can claim they flipped heads. -

        - - -
        -

        With a little bit of math, we can approximate the rate of plagiarism from these randomized responses. We'll skip the algebra, but doubling the reported non-plagiarism rate gives a good estimate of the actual non-plagiarism rate. - -

        - -
        -
        -Flip coins -
        -
        - -
        - - -
        -

        How far off can we be?

        - -

        If we simulate this coin flipping lots of times, we can see the distribution of errors. - -

        The estimates are close most of the time, but errors can be quite large. - -

        -
        -Flip coins 200 times -
        -
        - -
        - - -
        -

        Reducing the random noise (by reducing the number of students who flip heads) increases the accuracy of our estimate, but risks leaking information about students. - -

        If the coin is heavily weighted towards tails, identified students can't credibly claim they reported plagiarizing because they flipped heads. - -

        -
        -
        -
        - -
        - - -
        -

        One surprising way out of this accuracy-privacy tradeoff: carefully collect information from even more people. - -

        If we got students from other schools to fill out this survey, we could accurately measure plagiarism while protecting everyone's privacy. With enough students, we could even start comparing plagiarism across different age groups again—safely this time. - -

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

        Conclusion

        - -

        Aggregate statistics about private information are valuable, but can be risky to collect. We want researchers to be able to study things like the connection between demographics and health outcomes without revealing our entire medical history to our neighbors. The coin flipping technique in this article, called randomized response, makes it possible to safely study private information. - -

        You might wonder if coin flipping is the only way to do this. It's not—differential privacy can add targeted bits of random noise to a dataset and guarantee privacy. More flexible than randomized response, the 2020 Census will use it to protect respondents' privacy. In addition to randomizing responses, differential privacy also limits the impact any one response can have on the released data. - - -

        Credits

        - -

        Adam Pearce and Ellen Jiang // September 2020 - -

        Thanks to Carey Radebaugh, Fernanda Viégas, Emily Reif, Hal Abelson, Jess Holbrook, Kristen Olson, Mahima Pushkarna, Martin Wattenberg, Michael Terry, Miguel Guevara, Rebecca Salois, Yannick Assogba, Zan Armstrong and our other colleagues at Google for their help with this piece. - -

        - - -

        More Explorables

        - -

        - -
        - - - - - - - - - - - - - - - - - - diff --git a/spaces/merve/uncertainty-calibration/source/_posts/2021-10-31-uncertainty-calibration.md b/spaces/merve/uncertainty-calibration/source/_posts/2021-10-31-uncertainty-calibration.md deleted file mode 100644 index 0e097d412fff555af6b338ffa6d704d4ba05a454..0000000000000000000000000000000000000000 --- a/spaces/merve/uncertainty-calibration/source/_posts/2021-10-31-uncertainty-calibration.md +++ /dev/null @@ -1,131 +0,0 @@ ---- -template: post.html -title: Are Model Predictions Probabilities? -socialsummary: Machine learning models express their uncertainty as model scores, but through calibration we can transform these scores into probabilities for more effective decision making. -shareimg: https://pair.withgoogle.com/explorables/images/uncertainty-calibration.png -shareimgabstract: https://pair.withgoogle.com/explorables/images/uncertainty-calibration-abstract.png -permalink: /uncertainty-calibration/ ---- - -
        -
        -
        - -
        - -If a machine learning model tells you that it’s going to rain tomorrow with a score of 0.60, should you buy an umbrella?1 - -

        In the diagram, we have a hypothetical machine learning classifier for predicting rainy days. For each date, the classifier reads in relevant signals like temperature and humidity and spits out a number between 0 and 1. Each data point represents a different day, with the position representing the model’s prediction for rain that day and the symbol (🌧️ or ☀️) representing the true weather that occurred that day. - -

        Do the model’s predictions tell us the probability of rain?
        - -

        In general, machine learning classifiers don’t just give binary predictions, but instead provide some numerical value between 0 and 1 for their predictions. This number, sometimes called the *model score* or *confidence*, is a way for the model to express their certainty about what class the input data belongs to. In most applications, the exact score is ignored and we use a threshold to round the score to a binary answer, yes or no, rain or not. However, by using *calibration* we can transform these scores into probabilities and use them more effectively in decision making. - -

        - -

        Thresholding

        - -

        One traditional approach to using a model’s score is through *thresholding*. In this setting, you choose a threshold *t* and then declare that the model thinks it’s going to rain if the score is above *t* and it’s not if the score is below, thereby converting the score to a binary outcome. When you observe the actual weather, you know how often it was wrong and can compute key aggregate statistics like *accuracy*. - -

        We can sometimes treat these aggregate statistics themselves as probabilities. For example, accuracy is the probability that the binary prediction of your model (rain or not) is equal to the ground truth (🌧️ or ☀️). -

        - -

        Adjustable Thresholding

        - -

        The threshold can easily be changed after the model is trained. - -

        Thresholding uses the model’s score to make a decision, but fails to consider the model’s confidence. The model score is only used to decide whether you are above or below the threshold, but the magnitude of the difference isn’t considered. For example, if you threshold at 0.4, the model’s predictions of 0.6 and 0.9 are treated the same, even though the model is much more confident in the latter. - -

        Can we do a better job of incorporating the model score into our understanding of the model?
        - -
        - -

        Calibration

        - -

        *Calibration* lets us compare our model scores directly to probabilities. - -

        For this technique, instead of one threshold, we have many, which we use to split the predictions into buckets. Again, once we observe the ground truth, we can see what proportion of the predictions in each bucket were rainy days (🌧️). This proportion is the *empirical probability* of rain for that bucket. - -

        Ideally, we want this proportion to be higher for higher buckets, so that the probability is roughly in line with the average prediction for that bucket. We call the difference between the proportion and the predicted rates the calibration error, and by averaging over all of the buckets, we can calculate the Expected Calibration Error. If the proportions and the predictions line up for our use case, meaning the error is low, then we say the model is “well-calibrated” and we can consider treating the model score as the probability that it will actually rain. -

        - -

        Adjusting Calibration

        - -

        We saw above that a well-calibrated model allows us to treat our model score as a kind of probability. But if we start with a poorly calibrated model, one which is over or under-confident. Is there anything we can do to improve it? - -

        It turns out that, in many settings, we can adjust the model score without really changing the model’s decisions, as long as our adjustment preserves the order of the scores2. For example, if we map all of the scores from our original model to their squares, we don’t change the order of the data with respect to the model score. Thus, quantities like accuracy will stay the same as long as we appropriately map the threshold to its square as well. However, these adjustments *do* change the calibration of a model by changing which data points lie in which buckets. - -

        **Try** **tweaking the thresholds** to *calibrate* the model scores for our data3 – how much can you improve the model's calibration?
        - -

        In general, we don’t have to rely on tweaking the model scores by hand to improve calibration. If we are trying to calibrate the model for a particular data distribution, we can use mathematical techniques like Isotonic Regression or Platt Scaling to generate the correct remapping for model scores. -

        - -

        Shifting Data

        - -

        While good calibration is an important property for a model’s scores to be interpreted as probabilities, it alone does not capture all aspects of model uncertainty. - -

        What happens if it starts to rain less frequently after we've trained and calibrated our model? Notice how the calibration drops, even if we use the same calibrated model scores as before. - -

        Models are usually only well calibrated with respect to certain data distributions. If the data changes significantly between training and serving time, our models might cease to be well calibrated and we can’t rely on using our model scores as probabilities. -

        - -

        Beyond Calibration

        - -

        Calibration can sometimes be easy to game. For example, if we knew that it rains 50% of the time over the course of the year, then we could create a model with a constant prediction of 0.5 every day. This would have perfect calibration, despite not being a very useful model for distinguishing day-to-day differences in the probability of rain. This highlights an important issue: - -

        Better calibration doesn’t mean more accurate predictions.
        - -

        It turns out that statisticians identified the issue with focusing solely on calibration in meteorology when comparing weather forecasts, and came up with a solution. Proper scoring rules provide an alternative approach to measuring the quality of probabilistic forecasts, by using a formula to measure the distance between the model’s predictions and the true event probabilities. These rules guarantee that a better value must mean a better prediction in terms of accuracy and calibration. Such rules incentivize models to be both better calibrated and more accurate. - -

        -
        -
        - - -

        More Reading

        - -

        This post is only the beginning of the discussion on the connections between machine learning models, probability, and uncertainty. In practice, when developing machine learning models with uncertainty in mind, we may need to go beyond calibration. - -

        In some settings, errors are not all equal. For example, if we are training a classifier to predict if a patient needs to be tested for a disease, then a false negative (missing a case of the disease) may be more detrimental than a false positive (accidentally having a patient tested). In such cases, we may not want a perfectly calibrated model, but may want to skew the model scores towards one class or another. The field of Statistical Decision Theory provides us with tools to determine how to better use model scores in this more general setting. Calibration may also lead to tension with other important goals like model fairness in some applications. - -

        Beyond this, so far we’ve only considered the case of using a single model score, i.e. a point estimate. If we trained the model a thousand times with different random seeds, or resampled the training data, we would almost certainly generate a collection of different model scores for a given input. To truly unpack the different sources of uncertainty that we might encounter, we might want to look towards *distributional* approaches to measuring uncertainty, using techniques like Deep Ensembles or Bayesian modeling. We will dig deeper into these in future posts. - -

        Credits

        - -

        Nithum Thain, Adam Pearce, Jasper Snoek & Mahima Pushkarna // March 2022 - -

        Thanks to Balaji Lakshminarayanan, Emily Reif, Lucas Dixon, Martin Wattenberg, Fernanda Viégas, Ian Kivlichan, Nicole Mitchell, and Meredith Morris for their help with this piece. - -

        Footnotes

        - -

        Your decision might depend both on the probability of rain and its severity (i.e. how much rain there is going to be). We’ll focus just on the probability for now. - -

        Applying a strictly monotonic function to the model always keeps the order of scores the same. - -

        In this example, we adjust the model scores by changing the model scores of elements within a bucket to the mean of the bucket. -

        More Explorables

        - -

        - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spaces/mikeee/falcon-7b-ggml/app.py b/spaces/mikeee/falcon-7b-ggml/app.py deleted file mode 100644 index 5c7833615c6a6e7a63d1d7e17330717e0b5dccd0..0000000000000000000000000000000000000000 --- a/spaces/mikeee/falcon-7b-ggml/app.py +++ /dev/null @@ -1,262 +0,0 @@ -from pathlib import Path -from urllib.parse import urlparse - -import gradio as gr -import psutil -from ctransformers import AutoModelForCausalLM -from huggingface_hub import hf_hub_download - -_ = """ -snapshot_download( - repo_id="TheBloke/falcon-7b-instruct-GGML", - allow_patterns="falcon7b-instruct.ggmlv3.q4_0.bin", - revision="ggmlv3", - local_dir="models", - local_dir_use_symlinks=False, # default "auto" -) - -hf_hub_download( - repo_id=repo_id, - filename=model_filename, - local_dir=local_path, - local_dir_use_symlinks=True, -) -# """ -# 4.06G - -_ = """ -llm = AutoModelForCausalLM.from_pretrained( - "TheBloke/falcon-7b-instruct-GGML", - model_file="falcon7b-instruct.ggmlv3.q4_0.bin", - model_type="falcon", gpu_layers=32, threads=2, -) -# """ -# _ = Path("models", "falcon7b-instruct.ggmlv3.q4_0.bin").absolute().as_posix() -# assert Path(_).exists(), f"{_} does not exist, perhaps snapshot_download failed?" - -URL = "https://huggingface.co/TheBloke/falcon-7b-instruct-GGML/blob/main/falcon-7b-instruct.ggccv1.q4_1.bin" -URL = "https://huggingface.co/TheBloke/falcon-7b-instruct-GGML/blob/ggmlv3/falcon7b-instruct.ggmlv3.q4_1.bin" -repo_id = "/".join(urlparse(URL).path.strip("/").split("/")[:2]) - - -model_file = Path(URL).name - -_ = hf_hub_download( - repo_id=repo_id, - revision="ggmlv3", - filename=model_file, - local_dir="models", - # local_dir_use_symlinks=True, -) - -llm = AutoModelForCausalLM.from_pretrained( - # repo_id, # "TheBloke/falcon-7b-instruct-GGML", - # model_file=model_file, - # model_file=_, - _, - model_type="falcon", - threads=psutil.cpu_count(logical=False), -) - -TITLE = f"""

        🦅 Falcon-Chat ggml ({model_file}) 🦅""" -USER_NAME = "User" -BOT_NAME = "Falcon" -DEFAULT_INSTRUCTIONS = """The following is a conversation between a highly knowledgeable and intelligent AI assistant, called Falcon, and a human user, called User. In the following interactions, User and Falcon will converse in natural language, and Falcon will answer User's questions. Falcon was built to be respectful, polite and inclusive. Falcon was built by the Technology Innovation Institute in Abu Dhabi. Falcon will never decline to answer a question, and always attempts to give an answer that User would be satisfied with. It knows a lot, and always tells the truth. The conversation begins. -""" -RETRY_COMMAND = "/retry" -STOP_STR = f"\n{USER_NAME}:" -STOP_SUSPECT_LIST = [":", "\n", "User"] - - -def chat_accordion(): - with gr.Accordion("Parameters", open=False): - temperature = gr.Slider( - minimum=0.1, - maximum=2.0, - value=0.8, - step=0.1, - interactive=True, - label="Temperature", - ) - top_p = gr.Slider( - minimum=0.1, - maximum=0.99, - value=0.9, - step=0.01, - interactive=True, - label="p (nucleus sampling)", - ) - return temperature, top_p - - -def format_chat_prompt(message: str, chat_history, instructions: str) -> str: - instructions = instructions.strip(" ").strip("\n") - prompt = instructions - for turn in chat_history: - user_message, bot_message = turn - prompt = f"{prompt}\n{USER_NAME}: {user_message}\n{BOT_NAME}: {bot_message}" - prompt = f"{prompt}\n{USER_NAME}: {message}\n{BOT_NAME}:" - return prompt - - -def chat(): - with gr.Column(elem_id="chat_container"): - with gr.Row(): - chatbot = gr.Chatbot(elem_id="chatbot") - with gr.Row(): - inputs = gr.Textbox( - placeholder=f"Hello {BOT_NAME} !!", - label="Type an input and press Enter", - max_lines=3, - ) - - with gr.Row(elem_id="button_container"): - with gr.Column(): - retry_button = gr.Button("♻️ Retry last turn") - with gr.Column(): - delete_turn_button = gr.Button("🧽 Delete last turn") - with gr.Column(): - clear_chat_button = gr.Button("✨ Delete all history") - - gr.Examples( - [ - ["Hey Falcon! Any recommendations for my holidays in Abu Dhabi?"], - ["What's the Everett interpretation of quantum mechanics?"], - [ - "Give me a list of the top 10 dive sites you would recommend around the world." - ], - ["Can you tell me more about deep-water soloing?"], - [ - "Can you write a short tweet about the Apache 2.0 release of our latest AI model, Falcon LLM?" - ], - ], - inputs=inputs, - label="Click on any example and press Enter in the input textbox!", - ) - - with gr.Row(elem_id="param_container"): - with gr.Column(): - temperature, top_p = chat_accordion() - with gr.Column(): - with gr.Accordion("Instructions", open=False): - instructions = gr.Textbox( - placeholder="LLM instructions", - value=DEFAULT_INSTRUCTIONS, - lines=10, - interactive=True, - label="Instructions", - max_lines=16, - show_label=False, - ) - - def run_chat( - message: str, chat_history, instructions: str, temperature: float, top_p: float - ): - if not message or (message == RETRY_COMMAND and len(chat_history) == 0): - yield chat_history - return - - if message == RETRY_COMMAND and chat_history: - prev_turn = chat_history.pop(-1) - user_message, _ = prev_turn - message = user_message - - prompt = format_chat_prompt(message, chat_history, instructions) - chat_history = chat_history + [[message, ""]] - stream = llm( - prompt, - max_new_tokens=1024, - stop=[STOP_STR, "<|endoftext|>"], - temperature=temperature, - top_p=top_p, - stream=True, - ) - acc_text = "" - for idx, response in enumerate(stream): - text_token = response - - if text_token in STOP_SUSPECT_LIST: - acc_text += text_token - continue - - if idx == 0 and text_token.startswith(" "): - text_token = text_token[1:] - - acc_text += text_token - last_turn = list(chat_history.pop(-1)) - last_turn[-1] += acc_text - chat_history = chat_history + [last_turn] - yield chat_history - acc_text = "" - - def delete_last_turn(chat_history): - if chat_history: - chat_history.pop(-1) - return {chatbot: gr.update(value=chat_history)} - - def run_retry( - message: str, chat_history, instructions: str, temperature: float, top_p: float - ): - yield from run_chat( - RETRY_COMMAND, chat_history, instructions, temperature, top_p - ) - - def clear_chat(): - return [] - - inputs.submit( - run_chat, - [inputs, chatbot, instructions, temperature, top_p], - outputs=[chatbot], - show_progress="minimal", - ) - inputs.submit(lambda: "", inputs=None, outputs=inputs) - delete_turn_button.click(delete_last_turn, inputs=[chatbot], outputs=[chatbot]) - retry_button.click( - run_retry, - [inputs, chatbot, instructions, temperature, top_p], - outputs=[chatbot], - show_progress="minimal", - ) - clear_chat_button.click(clear_chat, [], chatbot) - - -def get_demo(): - with gr.Blocks( - # css=None - # css="""#chat_container {width: 700px; margin-left: auto; margin-right: auto;} - # #button_container {width: 700px; margin-left: auto; margin-right: auto;} - # #param_container {width: 700px; margin-left: auto; margin-right: auto;}""" - css="""#chatbot { - font-size: 14px; - min-height: 300px; -}""" - ) as demo: - gr.HTML(TITLE) - - with gr.Row(): - with gr.Column(): - gr.Markdown( - """**Chat with [Falcon-7b-Instruct](https://huggingface.co/tiiuae/falcon-7b-instruct), brainstorm ideas, discuss your holiday plans, and more!** - - ✨ This demo is powered by [Falcon-7B](https://huggingface.co/tiiuae/falcon-7b), finetuned on the [Baize](https://github.com/project-baize/baize-chatbot) dataset, and running with [Text Generation Inference](https://github.com/huggingface/text-generation-inference). [Falcon-7B](https://huggingface.co/tiiuae/falcon-7b) is a state-of-the-art large language model built by the [Technology Innovation Institute](https://www.tii.ae) in Abu Dhabi. It is trained on 1 trillion tokens (including [RefinedWeb](https://huggingface.co/datasets/tiiuae/falcon-refinedweb)) and available under the Apache 2.0 license. It currently holds the 🥇 1st place on the [🤗 Open LLM leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard). This demo is made available by the [HuggingFace H4 team](https://huggingface.co/HuggingFaceH4). - - 🧪 This is only a **first experimental preview**: the [H4 team](https://huggingface.co/HuggingFaceH4) intends to provide increasingly capable versions of Falcon Chat in the future, based on improved datasets and RLHF/RLAIF. - - 👀 **Learn more about Falcon LLM:** [falconllm.tii.ae](https://falconllm.tii.ae/) - - ➡️️ **Intended Use**: this demo is intended to showcase an early finetuning of [Falcon-7B](https://huggingface.co/tiiuae/falcon-7b), to illustrate the impact (and limitations) of finetuning on a dataset of conversations and instructions. We encourage the community to further build upon the base model, and to create even better instruct/chat versions! - - ⚠️ **Limitations**: the model can and will produce factually incorrect information, hallucinating facts and actions. As it has not undergone any advanced tuning/alignment, it can produce problematic outputs, especially if prompted to do so. Finally, this demo is limited to a session length of about 1,000 words. - """ - ) - - chat() - - return demo - - -if __name__ == "__main__": - demo = get_demo() - demo.queue(max_size=64, concurrency_count=8) - demo.launch(server_name="0.0.0.0", server_port=7860) diff --git a/spaces/mikeee/radiobee-dev/tests/test_lists2cmat.py b/spaces/mikeee/radiobee-dev/tests/test_lists2cmat.py deleted file mode 100644 index 4fe791efbca269bd65b991e946fea97d9da2789d..0000000000000000000000000000000000000000 --- a/spaces/mikeee/radiobee-dev/tests/test_lists2cmat.py +++ /dev/null @@ -1,42 +0,0 @@ -"""Test lists2cmat.""" -# pylint: disable=invalid-name -from itertools import zip_longest -from fastlid import fastlid -from radiobee.loadtext import loadtext -from radiobee.lists2cmat import lists2cmat - -file1 = "data/test_en.txt" -file2 = "data/test_zh.txt" - -# assume English or Chinese -fastlid.set_languages = ["en", "zh", ] - -text1 = loadtext(file1) -text2 = loadtext(file2) - -lang1, _ = fastlid(text1) -lang2, _ = fastlid(text2) - - -def test_lists2cmat(): - """Test lists2cmat.""" - - lst1, lst2 = [], [] - - if text1: - lst1 = [_.strip() for _ in text1.splitlines() if _.strip()] - if text2: - lst2 = [_.strip() for _ in text2.splitlines() if _.strip()] - - # en zh - len(lst1) == 33, len(lst2) == 36 - - # cmat = texts2cmat(lst1, lst2, lang1, lang2) - cmat = lists2cmat(lst1, lst2, lang1, lang2) - - assert cmat.shape == (36, 33) - - cmat21 = lists2cmat(lst2, lst1, lang2, lang1) - - assert cmat21.shape == (33, 36) - assert lists2cmat(lst2, lst1).mean() > 0.05 # 0.09 diff --git a/spaces/mikeion/research_guru/app.py b/spaces/mikeion/research_guru/app.py deleted file mode 100644 index 00e6912566e07113b65560c8a54a2935240103d4..0000000000000000000000000000000000000000 --- a/spaces/mikeion/research_guru/app.py +++ /dev/null @@ -1,263 +0,0 @@ -import os -import requests -from io import BytesIO -from PyPDF2 import PdfReader -import pandas as pd -from openai.embeddings_utils import get_embedding, cosine_similarity -import openai -import streamlit as st -import numpy as np -import base64 -import faiss - - - -messages = [ - {"role": "system", "content": "You are SummarizeGPT, a large language model whose expertise is reading and summarizing scientific papers."} -] - -class Chatbot(): - - def parse_paper(self, pdf): - # This function parses the PDF and returns a list of dictionaries with the text, - # font size, and x and y coordinates of each text element in the PDF - print("Parsing paper") - number_of_pages = len(pdf.pages) - print(f"Total number of pages: {number_of_pages}") - # This is the list that will contain all the text elements in the PDF and will be returned by the function - paper_text = [] - - for i in range(number_of_pages): - # Iterate through each page in the PDF, and extract the text elements. pdf.pages is a list of Page objects. - page = pdf.pages[i] - # This is the list that will contain all the text elements in the current page - page_text = [] - - def visitor_body(text, cm, tm, fontDict, fontSize): - # tm is a 6-element tuple of floats that represent a 2x3 matrix, which is the text matrix for the text. - # The first two elements are the horizontal and vertical scaling factors, the third and fourth elements - # are the horizontal and vertical shear factors, and the fifth and sixth elements are the horizontal and vertical translation factors. - - # x and y are the coordinates of the text element - x = tm[4] - y = tm[5] - - # ignore header/footer, and empty text. - # The y coordinate is used to filter out the header and footer of the paper - # The length of the text is used to filter out empty text - if (y > 50 and y < 720) and (len(text.strip()) > 1): - page_text.append({ - # The fontsize is used to separate paragraphs into different elements in the paper_text list - 'fontsize': fontSize, - # The text is stripped of whitespace and the \x03 character - 'text': text.strip().replace('\x03', ''), - # The x and y coordinates are used to separate paragraphs into different elements in the paper_text list - 'x': x, - 'y': y - }) - - # Extract the text elements from the page - _ = page.extract_text(visitor_text=visitor_body) - print(f'Page {i} text", {page_text}') - - - blob_font_size = None - blob_text = '' - processed_text = [] - - for t in page_text: - if t['fontsize'] == blob_font_size: - blob_text += f" {t['text']}" - if len(blob_text) >= 2000: - processed_text.append({ - 'fontsize': blob_font_size, - 'text': blob_text, - 'page': i - }) - blob_font_size = None - blob_text = '' - else: - if blob_font_size is not None and len(blob_text) >= 1: - processed_text.append({ - 'fontsize': blob_font_size, - 'text': blob_text, - 'page': i - }) - blob_font_size = t['fontsize'] - blob_text = t['text'] - paper_text += processed_text - print("Done parsing paper") - print(paper_text) - - return paper_text - - def paper_df(self, pdf): - print('Creating dataframe') - filtered_pdf= [] - for row in pdf: - # This will use the get method to safely access the 'text' key in the row dictionary, - # and if the key is not present, it will use an empty string as a default value. This - # should prevent a KeyError from occurring. - if len(row.get('text', '')) < 30: - continue - filtered_pdf.append(row) - print("Filtered paper_text", filtered_pdf) - df = pd.DataFrame(filtered_pdf) - print(df.shape) - print(df.head) - # remove elements with identical df[text] and df[page] values - df = df.drop_duplicates(subset=['text', 'page'], keep='first') - df['length'] = df['text'].apply(lambda x: len(x)) - print('Done creating dataframe') - return df - - def calculate_embeddings(self, df): - print('Calculating embeddings') - openai.api_key = os.getenv('OPENAI_API_KEY') - embedding_model = "text-embedding-ada-002" - # Get the embeddings for each text element in the dataframe - embeddings = df.text.apply(lambda x: get_embedding(x, engine=embedding_model)) - embeddings = np.vstack(embeddings, dtype=np.float32) - return embeddings - - def search_embeddings(self, embeddings, df, query, n=3, pprint=True): - - # Step 1. Get an embedding for the question being asked to the PDF - query_embedding = get_embedding(query, engine="text-embedding-ada-002") - query_embedding = np.array(query_embedding, dtype=np.float32) - # Step 2. Create a FAISS index and add the embeddings - d = embeddings.shape[1] - # Use the L2 distance metric - index = faiss.IndexFlatL2(d) - print("Embeddings shape:", embeddings.shape) - print("Embeddings data type:", type(embeddings)) - index.add(embeddings) - - - # Step 3. Search the index for the embedding of the question - - D, I = index.search(query_embedding.reshape(1,d), n) - - # Step 4. Get the top n results from the dataframe - results = df.iloc[I[0]] - results['similarity'] = D[0] - results = results.reset_index(drop=True) - - # Make a dictionary of the first n results with the page number as the key and the text as the value - - global sources - sources = [] - for i in range(n): - # append the page number and the text as a dict to the sources list - sources.append({'Page '+str(results.iloc[i]['page']): results.iloc[i]['text'][:150]+'...'}) - print(sources) - return results.head(n) - - def create_prompt(self, embeddings, df, user_input): - result = self.search_embeddings(embeddings, df, user_input, n=3) - print(result) - prompt = """ - You are Research Paper Guru - The user is going to ask you a question about a research paper after uploading a PDF of the paper. - You are a large language model whose expertise is reading and and providing answers to their queries, based on what you know about the subject as well as what you know about the text given to you. - - The user asks: """+ user_input + """ - - And the information about the paper that is relevant to the question is: - - 1.""" + str(result.iloc[0]['text']) + """ - 2.""" + str(result.iloc[1]['text']) + """ - 3.""" + str(result.iloc[2]['text']) + """ - - Knowing what you know about this answer, as well as being able to navigate this knowledge in conjuction with what is being said in the paper, provide an answer to the user. If the person asks you to summarize what is in the paper, do your best to provide a summary of the paper. - The goal here is to keep the user happy and satisfied that you have given them the best answer to the question to the best of your knowledge. If necessary, you can also point them to outside resources for more information.:""" - - print('Done creating prompt') - return prompt - - def gpt(self, prompt): - openai.api_key = os.getenv('OPENAI_API_KEY') - print('got API key') - messages.append({"role": "user", "content": prompt}) - r = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages) - answer = r['choices'][0]['message']['content'] - response = {'answer': answer, 'sources': sources} - return response - - def reply(self, embeddings, user_input): - print(user_input) - prompt = self.create_prompt(embeddings, df, user_input) - return self.gpt(prompt) - -def process_pdf(file): - print("Processing pdf") - pdf = PdfReader(BytesIO(file)) - chatbot = Chatbot() - paper_text = chatbot.parse_paper(pdf) - global df - df = chatbot.paper_df(paper_text) - embeddings = chatbot.calculate_embeddings(df) - print("Done processing pdf") - return embeddings - -def download_pdf(url): - chatbot = Chatbot() - r = requests.get(str(url)) - print(r.headers) - pdf = PdfReader(BytesIO(r.content)) - paper_text = chatbot.parse_paper(pdf) - global df - df = chatbot.paper_df(paper_text) - embeddings = chatbot.calculate_embeddings(df) - print("Done processing pdf") - return embeddings - -def show_pdf(file_content): - base64_pdf = base64.b64encode(file_content).decode('utf-8') - pdf_display = f'' - st.markdown(pdf_display, unsafe_allow_html=True) - - -def main(): - st.title("Research Paper Guru") - st.subheader("Upload PDF or Enter URL") - embeddings = None - pdf_option = st.selectbox("Choose an option:", ["Upload PDF", "Enter URL"]) - chatbot = Chatbot() - - if pdf_option == "Upload PDF": - uploaded_file = st.file_uploader("Choose a PDF file", type="pdf") - if uploaded_file is not None: - file_content = uploaded_file.read() - embeddings = process_pdf(file_content) - st.success("PDF uploaded and processed successfully!") - show_pdf(file_content) - - elif pdf_option == "Enter URL": - url = st.text_input("Enter the URL of the PDF:") - if url: - if st.button("Download and process PDF"): - try: - r = requests.get(str(url)) - content = r.content - embeddings = download_pdf(url) - st.success("PDF downloaded and processed successfully!") - show_pdf(content) - except Exception as e: - st.error(f"An error occurred while processing the PDF: {e}") - st.subheader("Ask a question about a research paper and get an answer with sources!") - query = st.text_input("Enter your query:") - if query: - if st.button("Get answer"): - if embeddings is not None: - response = chatbot.reply(embeddings, query) - else: - st.warning("Please upload a PDF or enter a URL first.") - st.write(response['answer']) - st.write("Sources:") - for source in response['sources']: - st.write(source) - -if __name__ == "__main__": - main() - \ No newline at end of file diff --git a/spaces/milyiyo/reimagine-it/retrieval/text_utils.py b/spaces/milyiyo/reimagine-it/retrieval/text_utils.py deleted file mode 100644 index 51f981054b41a945656f9e619c722e09de198bf7..0000000000000000000000000000000000000000 --- a/spaces/milyiyo/reimagine-it/retrieval/text_utils.py +++ /dev/null @@ -1,74 +0,0 @@ -import random - -def repeat(text, n_max_gram=3, n_max_repeat=3): - """repeat n-grams""" - tokens = text.split() - - n_gram = random.randint(1, n_max_gram) - - repeat_token_idx = random.randint(0, len(tokens) - n_gram) - - repeated_tokens = tokens[repeat_token_idx:repeat_token_idx+n_gram] - - n_repeat = random.randint(1, n_max_repeat) - for _ in range(n_repeat): - insert_idx = random.randint(0, len(tokens)) - tokens = tokens[:insert_idx] + \ - repeated_tokens + tokens[insert_idx:] - - new_text = " ".join(tokens) - return new_text - -def remove(text, n_max_gram=3): - """remove n-grams""" - tokens = text.split() - - n_gram = random.randint(1, n_max_gram) - - remove_token_idx = random.randint(0, len(tokens) - n_gram) - - tokens = tokens[:remove_token_idx] + tokens[remove_token_idx + n_gram:] - - new_text = " ".join(tokens) - return new_text - -def insert(text, vocab, n_max_tokens=3): - """Insert tokens""" - tokens = text.split() - - n_insert_token = random.randint(1, n_max_tokens) - - for _ in range(n_insert_token): - insert_token_idx = random.randint(0, len(tokens) - 1) - insert_token = random.choice(vocab) - tokens = tokens[:insert_token_idx] + [insert_token] + tokens[insert_token_idx:] - - new_text = " ".join(tokens) - return new_text - -def swap(text, vocab, n_max_tokens=3): - """Swap tokens""" - tokens = text.split() - - n_swap_tokens = random.randint(1, n_max_tokens) - - for _ in range(n_swap_tokens): - swap_token_idx = random.randint(0, len(tokens) - 1) - - swap_token = random.choice(vocab) - while swap_token == tokens[swap_token_idx]: - swap_token = random.choice(vocab) - - tokens[swap_token_idx] = swap_token - - new_text = " ".join(tokens) - return new_text - -def shuffle(text): - """shuffle tokens""" - tokens = text.split() - - random.shuffle(tokens) - - new_text = " ".join(tokens) - return new_text diff --git a/spaces/ml-energy/leaderboard/scripts/aggregate_nlp_metrics.py b/spaces/ml-energy/leaderboard/scripts/aggregate_nlp_metrics.py deleted file mode 100644 index a92ca4693f2eb2a377f6b478a871f9f606aeaf55..0000000000000000000000000000000000000000 --- a/spaces/ml-energy/leaderboard/scripts/aggregate_nlp_metrics.py +++ /dev/null @@ -1,44 +0,0 @@ -import os -import json - -import tyro -import pandas as pd - -TASK_METRICS = { - "arc_challenge": "acc_norm", - "hellaswag": "acc_norm", - "truthfulqa_mc": "mc2", -} - -TASK_SHORT_NAMES = { - "arc_challenge": "arc", - "hellaswag": "hellaswag", - "truthfulqa_mc": "truthfulqa", -} - - -def main(data_dir: str, out_file: str = "score.csv") -> None: - """Aggregate results from lm-evaluation-harness into a CSV file. - - Args: - data_dir: The directory containing the results. Model names are - expected to be the immediate subdirectories of `data_dir`. - out_file: The path to the output CSV file. (Default: `score.csv`) - """ - models = list(filter(lambda x: os.path.isdir(f"{data_dir}/{x}"), os.listdir(data_dir))) - - df = pd.DataFrame(columns=TASK_SHORT_NAMES.values()) - for model_dir in models: - for task, metric in TASK_METRICS.items(): - model_name = "/".join(model_dir.split("--")[-2:]) - results = json.load(open(f"{data_dir}/{model_dir}/{task}.json")) - df.loc[model_name, TASK_SHORT_NAMES[task]] = float(results["results"][task][metric]) * 100.0 - df = df.reset_index().rename(columns={"index": "model"}) - - # Write the CSV file. - if dirname := os.path.dirname(out_file): - os.makedirs(dirname, exist_ok=True) - df.to_csv(out_file, index=False) - -if __name__ == "__main__": - tyro.cli(main) diff --git a/spaces/mmlab-ntu/Segment-Any-RGBD/open_vocab_seg/modeling/clip_adapter/__init__.py b/spaces/mmlab-ntu/Segment-Any-RGBD/open_vocab_seg/modeling/clip_adapter/__init__.py deleted file mode 100644 index 5c880f121e329e0fc2bb31de5aa8240b44b4a25a..0000000000000000000000000000000000000000 --- a/spaces/mmlab-ntu/Segment-Any-RGBD/open_vocab_seg/modeling/clip_adapter/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# Copyright (c) Meta Platforms, Inc. All Rights Reserved - -from .text_template import ( - PredefinedPromptExtractor, - ImageNetPromptExtractor, - VILDPromptExtractor, -) -from .adapter import ClipAdapter, MaskFormerClipAdapter - - -def build_text_prompt(cfg): - if cfg.TEXT_TEMPLATES == "predefined": - text_templates = PredefinedPromptExtractor(cfg.PREDEFINED_PROMPT_TEMPLATES) - elif cfg.TEXT_TEMPLATES == "imagenet": - text_templates = ImageNetPromptExtractor() - elif cfg.TEXT_TEMPLATES == "vild": - text_templates = VILDPromptExtractor() - else: - raise NotImplementedError( - "Prompt learner {} is not supported".format(cfg.TEXT_TEMPLATES) - ) - return text_templates diff --git a/spaces/mshukor/UnIVAL/fairseq/examples/speech_recognition/kaldi/kaldi_initializer.py b/spaces/mshukor/UnIVAL/fairseq/examples/speech_recognition/kaldi/kaldi_initializer.py deleted file mode 100644 index 6d2a2a4b6b809ba1106f9a57cb6f241dc083e670..0000000000000000000000000000000000000000 --- a/spaces/mshukor/UnIVAL/fairseq/examples/speech_recognition/kaldi/kaldi_initializer.py +++ /dev/null @@ -1,698 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -from dataclasses import dataclass -import hydra -from hydra.core.config_store import ConfigStore -import logging -from omegaconf import MISSING, OmegaConf -import os -import os.path as osp -from pathlib import Path -import subprocess -from typing import Optional - -from fairseq.data.dictionary import Dictionary -from fairseq.dataclass import FairseqDataclass - -script_dir = Path(__file__).resolve().parent -config_path = script_dir / "config" - - -logger = logging.getLogger(__name__) - - -@dataclass -class KaldiInitializerConfig(FairseqDataclass): - data_dir: str = MISSING - fst_dir: Optional[str] = None - in_labels: str = MISSING - out_labels: Optional[str] = None - wav2letter_lexicon: Optional[str] = None - lm_arpa: str = MISSING - kaldi_root: str = MISSING - blank_symbol: str = "" - silence_symbol: Optional[str] = None - - -def create_units(fst_dir: Path, in_labels: str, vocab: Dictionary) -> Path: - in_units_file = fst_dir / f"kaldi_dict.{in_labels}.txt" - if not in_units_file.exists(): - - logger.info(f"Creating {in_units_file}") - - with open(in_units_file, "w") as f: - print(" 0", file=f) - i = 1 - for symb in vocab.symbols[vocab.nspecial :]: - if not symb.startswith("madeupword"): - print(f"{symb} {i}", file=f) - i += 1 - return in_units_file - - -def create_lexicon( - cfg: KaldiInitializerConfig, - fst_dir: Path, - unique_label: str, - in_units_file: Path, - out_words_file: Path, -) -> (Path, Path): - - disambig_in_units_file = fst_dir / f"kaldi_dict.{cfg.in_labels}_disambig.txt" - lexicon_file = fst_dir / f"kaldi_lexicon.{unique_label}.txt" - disambig_lexicon_file = fst_dir / f"kaldi_lexicon.{unique_label}_disambig.txt" - if ( - not lexicon_file.exists() - or not disambig_lexicon_file.exists() - or not disambig_in_units_file.exists() - ): - logger.info(f"Creating {lexicon_file} (in units file: {in_units_file})") - - assert cfg.wav2letter_lexicon is not None or cfg.in_labels == cfg.out_labels - - if cfg.wav2letter_lexicon is not None: - lm_words = set() - with open(out_words_file, "r") as lm_dict_f: - for line in lm_dict_f: - lm_words.add(line.split()[0]) - - num_skipped = 0 - total = 0 - with open(cfg.wav2letter_lexicon, "r") as w2l_lex_f, open( - lexicon_file, "w" - ) as out_f: - for line in w2l_lex_f: - items = line.rstrip().split("\t") - assert len(items) == 2, items - if items[0] in lm_words: - print(items[0], items[1], file=out_f) - else: - num_skipped += 1 - logger.debug( - f"Skipping word {items[0]} as it was not found in LM" - ) - total += 1 - if num_skipped > 0: - logger.warning( - f"Skipped {num_skipped} out of {total} words as they were not found in LM" - ) - else: - with open(in_units_file, "r") as in_f, open(lexicon_file, "w") as out_f: - for line in in_f: - symb = line.split()[0] - if symb != "" and symb != "" and symb != "": - print(symb, symb, file=out_f) - - lex_disambig_path = ( - Path(cfg.kaldi_root) / "egs/wsj/s5/utils/add_lex_disambig.pl" - ) - res = subprocess.run( - [lex_disambig_path, lexicon_file, disambig_lexicon_file], - check=True, - capture_output=True, - ) - ndisambig = int(res.stdout) - disamib_path = Path(cfg.kaldi_root) / "egs/wsj/s5/utils/add_disambig.pl" - res = subprocess.run( - [disamib_path, "--include-zero", in_units_file, str(ndisambig)], - check=True, - capture_output=True, - ) - with open(disambig_in_units_file, "wb") as f: - f.write(res.stdout) - - return disambig_lexicon_file, disambig_in_units_file - - -def create_G( - kaldi_root: Path, fst_dir: Path, lm_arpa: Path, arpa_base: str -) -> (Path, Path): - - out_words_file = fst_dir / f"kaldi_dict.{arpa_base}.txt" - grammar_graph = fst_dir / f"G_{arpa_base}.fst" - if not grammar_graph.exists() or not out_words_file.exists(): - logger.info(f"Creating {grammar_graph}") - arpa2fst = kaldi_root / "src/lmbin/arpa2fst" - subprocess.run( - [ - arpa2fst, - "--disambig-symbol=#0", - f"--write-symbol-table={out_words_file}", - lm_arpa, - grammar_graph, - ], - check=True, - ) - return grammar_graph, out_words_file - - -def create_L( - kaldi_root: Path, - fst_dir: Path, - unique_label: str, - lexicon_file: Path, - in_units_file: Path, - out_words_file: Path, -) -> Path: - lexicon_graph = fst_dir / f"L.{unique_label}.fst" - - if not lexicon_graph.exists(): - logger.info(f"Creating {lexicon_graph} (in units: {in_units_file})") - make_lex = kaldi_root / "egs/wsj/s5/utils/make_lexicon_fst.pl" - fstcompile = kaldi_root / "tools/openfst-1.6.7/bin/fstcompile" - fstaddselfloops = kaldi_root / "src/fstbin/fstaddselfloops" - fstarcsort = kaldi_root / "tools/openfst-1.6.7/bin/fstarcsort" - - def write_disambig_symbol(file): - with open(file, "r") as f: - for line in f: - items = line.rstrip().split() - if items[0] == "#0": - out_path = str(file) + "_disamig" - with open(out_path, "w") as out_f: - print(items[1], file=out_f) - return out_path - - return None - - in_disambig_sym = write_disambig_symbol(in_units_file) - assert in_disambig_sym is not None - out_disambig_sym = write_disambig_symbol(out_words_file) - assert out_disambig_sym is not None - - try: - with open(lexicon_graph, "wb") as out_f: - res = subprocess.run( - [make_lex, lexicon_file], capture_output=True, check=True - ) - assert len(res.stderr) == 0, res.stderr.decode("utf-8") - res = subprocess.run( - [ - fstcompile, - f"--isymbols={in_units_file}", - f"--osymbols={out_words_file}", - "--keep_isymbols=false", - "--keep_osymbols=false", - ], - input=res.stdout, - capture_output=True, - ) - assert len(res.stderr) == 0, res.stderr.decode("utf-8") - res = subprocess.run( - [fstaddselfloops, in_disambig_sym, out_disambig_sym], - input=res.stdout, - capture_output=True, - check=True, - ) - res = subprocess.run( - [fstarcsort, "--sort_type=olabel"], - input=res.stdout, - capture_output=True, - check=True, - ) - out_f.write(res.stdout) - except subprocess.CalledProcessError as e: - logger.error(f"cmd: {e.cmd}, err: {e.stderr.decode('utf-8')}") - os.remove(lexicon_graph) - raise - except AssertionError: - os.remove(lexicon_graph) - raise - - return lexicon_graph - - -def create_LG( - kaldi_root: Path, - fst_dir: Path, - unique_label: str, - lexicon_graph: Path, - grammar_graph: Path, -) -> Path: - lg_graph = fst_dir / f"LG.{unique_label}.fst" - - if not lg_graph.exists(): - logger.info(f"Creating {lg_graph}") - - fsttablecompose = kaldi_root / "src/fstbin/fsttablecompose" - fstdeterminizestar = kaldi_root / "src/fstbin/fstdeterminizestar" - fstminimizeencoded = kaldi_root / "src/fstbin/fstminimizeencoded" - fstpushspecial = kaldi_root / "src/fstbin/fstpushspecial" - fstarcsort = kaldi_root / "tools/openfst-1.6.7/bin/fstarcsort" - - try: - with open(lg_graph, "wb") as out_f: - res = subprocess.run( - [fsttablecompose, lexicon_graph, grammar_graph], - capture_output=True, - check=True, - ) - res = subprocess.run( - [ - fstdeterminizestar, - "--use-log=true", - ], - input=res.stdout, - capture_output=True, - ) - res = subprocess.run( - [fstminimizeencoded], - input=res.stdout, - capture_output=True, - check=True, - ) - res = subprocess.run( - [fstpushspecial], - input=res.stdout, - capture_output=True, - check=True, - ) - res = subprocess.run( - [fstarcsort, "--sort_type=ilabel"], - input=res.stdout, - capture_output=True, - check=True, - ) - out_f.write(res.stdout) - except subprocess.CalledProcessError as e: - logger.error(f"cmd: {e.cmd}, err: {e.stderr.decode('utf-8')}") - os.remove(lg_graph) - raise - - return lg_graph - - -def create_H( - kaldi_root: Path, - fst_dir: Path, - disambig_out_units_file: Path, - in_labels: str, - vocab: Dictionary, - blk_sym: str, - silence_symbol: Optional[str], -) -> (Path, Path, Path): - h_graph = ( - fst_dir / f"H.{in_labels}{'_' + silence_symbol if silence_symbol else ''}.fst" - ) - h_out_units_file = fst_dir / f"kaldi_dict.h_out.{in_labels}.txt" - disambig_in_units_file_int = Path(str(h_graph) + "isym_disambig.int") - disambig_out_units_file_int = Path(str(disambig_out_units_file) + ".int") - if ( - not h_graph.exists() - or not h_out_units_file.exists() - or not disambig_in_units_file_int.exists() - ): - logger.info(f"Creating {h_graph}") - eps_sym = "" - - num_disambig = 0 - osymbols = [] - - with open(disambig_out_units_file, "r") as f, open( - disambig_out_units_file_int, "w" - ) as out_f: - for line in f: - symb, id = line.rstrip().split() - if line.startswith("#"): - num_disambig += 1 - print(id, file=out_f) - else: - if len(osymbols) == 0: - assert symb == eps_sym, symb - osymbols.append((symb, id)) - - i_idx = 0 - isymbols = [(eps_sym, 0)] - - imap = {} - - for i, s in enumerate(vocab.symbols): - i_idx += 1 - isymbols.append((s, i_idx)) - imap[s] = i_idx - - fst_str = [] - - node_idx = 0 - root_node = node_idx - - special_symbols = [blk_sym] - if silence_symbol is not None: - special_symbols.append(silence_symbol) - - for ss in special_symbols: - fst_str.append("{} {} {} {}".format(root_node, root_node, ss, eps_sym)) - - for symbol, _ in osymbols: - if symbol == eps_sym or symbol.startswith("#"): - continue - - node_idx += 1 - # 1. from root to emitting state - fst_str.append("{} {} {} {}".format(root_node, node_idx, symbol, symbol)) - # 2. from emitting state back to root - fst_str.append("{} {} {} {}".format(node_idx, root_node, eps_sym, eps_sym)) - # 3. from emitting state to optional blank state - pre_node = node_idx - node_idx += 1 - for ss in special_symbols: - fst_str.append("{} {} {} {}".format(pre_node, node_idx, ss, eps_sym)) - # 4. from blank state back to root - fst_str.append("{} {} {} {}".format(node_idx, root_node, eps_sym, eps_sym)) - - fst_str.append("{}".format(root_node)) - - fst_str = "\n".join(fst_str) - h_str = str(h_graph) - isym_file = h_str + ".isym" - - with open(isym_file, "w") as f: - for sym, id in isymbols: - f.write("{} {}\n".format(sym, id)) - - with open(h_out_units_file, "w") as f: - for sym, id in osymbols: - f.write("{} {}\n".format(sym, id)) - - with open(disambig_in_units_file_int, "w") as f: - disam_sym_id = len(isymbols) - for _ in range(num_disambig): - f.write("{}\n".format(disam_sym_id)) - disam_sym_id += 1 - - fstcompile = kaldi_root / "tools/openfst-1.6.7/bin/fstcompile" - fstaddselfloops = kaldi_root / "src/fstbin/fstaddselfloops" - fstarcsort = kaldi_root / "tools/openfst-1.6.7/bin/fstarcsort" - - try: - with open(h_graph, "wb") as out_f: - res = subprocess.run( - [ - fstcompile, - f"--isymbols={isym_file}", - f"--osymbols={h_out_units_file}", - "--keep_isymbols=false", - "--keep_osymbols=false", - ], - input=str.encode(fst_str), - capture_output=True, - check=True, - ) - res = subprocess.run( - [ - fstaddselfloops, - disambig_in_units_file_int, - disambig_out_units_file_int, - ], - input=res.stdout, - capture_output=True, - check=True, - ) - res = subprocess.run( - [fstarcsort, "--sort_type=olabel"], - input=res.stdout, - capture_output=True, - check=True, - ) - out_f.write(res.stdout) - except subprocess.CalledProcessError as e: - logger.error(f"cmd: {e.cmd}, err: {e.stderr.decode('utf-8')}") - os.remove(h_graph) - raise - return h_graph, h_out_units_file, disambig_in_units_file_int - - -def create_HLGa( - kaldi_root: Path, - fst_dir: Path, - unique_label: str, - h_graph: Path, - lg_graph: Path, - disambig_in_words_file_int: Path, -) -> Path: - hlga_graph = fst_dir / f"HLGa.{unique_label}.fst" - - if not hlga_graph.exists(): - logger.info(f"Creating {hlga_graph}") - - fsttablecompose = kaldi_root / "src/fstbin/fsttablecompose" - fstdeterminizestar = kaldi_root / "src/fstbin/fstdeterminizestar" - fstrmsymbols = kaldi_root / "src/fstbin/fstrmsymbols" - fstrmepslocal = kaldi_root / "src/fstbin/fstrmepslocal" - fstminimizeencoded = kaldi_root / "src/fstbin/fstminimizeencoded" - - try: - with open(hlga_graph, "wb") as out_f: - res = subprocess.run( - [ - fsttablecompose, - h_graph, - lg_graph, - ], - capture_output=True, - check=True, - ) - res = subprocess.run( - [fstdeterminizestar, "--use-log=true"], - input=res.stdout, - capture_output=True, - check=True, - ) - res = subprocess.run( - [fstrmsymbols, disambig_in_words_file_int], - input=res.stdout, - capture_output=True, - check=True, - ) - res = subprocess.run( - [fstrmepslocal], - input=res.stdout, - capture_output=True, - check=True, - ) - res = subprocess.run( - [fstminimizeencoded], - input=res.stdout, - capture_output=True, - check=True, - ) - out_f.write(res.stdout) - except subprocess.CalledProcessError as e: - logger.error(f"cmd: {e.cmd}, err: {e.stderr.decode('utf-8')}") - os.remove(hlga_graph) - raise - - return hlga_graph - - -def create_HLa( - kaldi_root: Path, - fst_dir: Path, - unique_label: str, - h_graph: Path, - l_graph: Path, - disambig_in_words_file_int: Path, -) -> Path: - hla_graph = fst_dir / f"HLa.{unique_label}.fst" - - if not hla_graph.exists(): - logger.info(f"Creating {hla_graph}") - - fsttablecompose = kaldi_root / "src/fstbin/fsttablecompose" - fstdeterminizestar = kaldi_root / "src/fstbin/fstdeterminizestar" - fstrmsymbols = kaldi_root / "src/fstbin/fstrmsymbols" - fstrmepslocal = kaldi_root / "src/fstbin/fstrmepslocal" - fstminimizeencoded = kaldi_root / "src/fstbin/fstminimizeencoded" - - try: - with open(hla_graph, "wb") as out_f: - res = subprocess.run( - [ - fsttablecompose, - h_graph, - l_graph, - ], - capture_output=True, - check=True, - ) - res = subprocess.run( - [fstdeterminizestar, "--use-log=true"], - input=res.stdout, - capture_output=True, - check=True, - ) - res = subprocess.run( - [fstrmsymbols, disambig_in_words_file_int], - input=res.stdout, - capture_output=True, - check=True, - ) - res = subprocess.run( - [fstrmepslocal], - input=res.stdout, - capture_output=True, - check=True, - ) - res = subprocess.run( - [fstminimizeencoded], - input=res.stdout, - capture_output=True, - check=True, - ) - out_f.write(res.stdout) - except subprocess.CalledProcessError as e: - logger.error(f"cmd: {e.cmd}, err: {e.stderr.decode('utf-8')}") - os.remove(hla_graph) - raise - - return hla_graph - - -def create_HLG( - kaldi_root: Path, - fst_dir: Path, - unique_label: str, - hlga_graph: Path, - prefix: str = "HLG", -) -> Path: - hlg_graph = fst_dir / f"{prefix}.{unique_label}.fst" - - if not hlg_graph.exists(): - logger.info(f"Creating {hlg_graph}") - - add_self_loop = script_dir / "add-self-loop-simple" - kaldi_src = kaldi_root / "src" - kaldi_lib = kaldi_src / "lib" - - try: - if not add_self_loop.exists(): - fst_include = kaldi_root / "tools/openfst-1.6.7/include" - add_self_loop_src = script_dir / "add-self-loop-simple.cc" - - subprocess.run( - [ - "c++", - f"-I{kaldi_src}", - f"-I{fst_include}", - f"-L{kaldi_lib}", - add_self_loop_src, - "-lkaldi-base", - "-lkaldi-fstext", - "-o", - add_self_loop, - ], - check=True, - ) - - my_env = os.environ.copy() - my_env["LD_LIBRARY_PATH"] = f"{kaldi_lib}:{my_env['LD_LIBRARY_PATH']}" - - subprocess.run( - [ - add_self_loop, - hlga_graph, - hlg_graph, - ], - check=True, - capture_output=True, - env=my_env, - ) - except subprocess.CalledProcessError as e: - logger.error(f"cmd: {e.cmd}, err: {e.stderr.decode('utf-8')}") - raise - - return hlg_graph - - -def initalize_kaldi(cfg: KaldiInitializerConfig) -> Path: - if cfg.fst_dir is None: - cfg.fst_dir = osp.join(cfg.data_dir, "kaldi") - if cfg.out_labels is None: - cfg.out_labels = cfg.in_labels - - kaldi_root = Path(cfg.kaldi_root) - data_dir = Path(cfg.data_dir) - fst_dir = Path(cfg.fst_dir) - fst_dir.mkdir(parents=True, exist_ok=True) - - arpa_base = osp.splitext(osp.basename(cfg.lm_arpa))[0] - unique_label = f"{cfg.in_labels}.{arpa_base}" - - with open(data_dir / f"dict.{cfg.in_labels}.txt", "r") as f: - vocab = Dictionary.load(f) - - in_units_file = create_units(fst_dir, cfg.in_labels, vocab) - - grammar_graph, out_words_file = create_G( - kaldi_root, fst_dir, Path(cfg.lm_arpa), arpa_base - ) - - disambig_lexicon_file, disambig_L_in_units_file = create_lexicon( - cfg, fst_dir, unique_label, in_units_file, out_words_file - ) - - h_graph, h_out_units_file, disambig_in_units_file_int = create_H( - kaldi_root, - fst_dir, - disambig_L_in_units_file, - cfg.in_labels, - vocab, - cfg.blank_symbol, - cfg.silence_symbol, - ) - lexicon_graph = create_L( - kaldi_root, - fst_dir, - unique_label, - disambig_lexicon_file, - disambig_L_in_units_file, - out_words_file, - ) - lg_graph = create_LG( - kaldi_root, fst_dir, unique_label, lexicon_graph, grammar_graph - ) - hlga_graph = create_HLGa( - kaldi_root, fst_dir, unique_label, h_graph, lg_graph, disambig_in_units_file_int - ) - hlg_graph = create_HLG(kaldi_root, fst_dir, unique_label, hlga_graph) - - # for debugging - # hla_graph = create_HLa(kaldi_root, fst_dir, unique_label, h_graph, lexicon_graph, disambig_in_units_file_int) - # hl_graph = create_HLG(kaldi_root, fst_dir, unique_label, hla_graph, prefix="HL_looped") - # create_HLG(kaldi_root, fst_dir, "phnc", h_graph, prefix="H_looped") - - return hlg_graph - - -@hydra.main(config_path=config_path, config_name="kaldi_initializer") -def cli_main(cfg: KaldiInitializerConfig) -> None: - container = OmegaConf.to_container(cfg, resolve=True, enum_to_str=True) - cfg = OmegaConf.create(container) - OmegaConf.set_struct(cfg, True) - initalize_kaldi(cfg) - - -if __name__ == "__main__": - - logging.root.setLevel(logging.INFO) - logging.basicConfig(level=logging.INFO) - - try: - from hydra._internal.utils import ( - get_args, - ) # pylint: disable=import-outside-toplevel - - cfg_name = get_args().config_name or "kaldi_initializer" - except ImportError: - logger.warning("Failed to get config name from hydra args") - cfg_name = "kaldi_initializer" - - cs = ConfigStore.instance() - cs.store(name=cfg_name, node=KaldiInitializerConfig) - - cli_main() diff --git a/spaces/mshukor/UnIVAL/fairseq/examples/speech_text_joint_to_text/tasks/__init__.py b/spaces/mshukor/UnIVAL/fairseq/examples/speech_text_joint_to_text/tasks/__init__.py deleted file mode 100644 index d878278475fb24cf6b97d66d784e657567f5aa80..0000000000000000000000000000000000000000 --- a/spaces/mshukor/UnIVAL/fairseq/examples/speech_text_joint_to_text/tasks/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import importlib -import os - -for file in os.listdir(os.path.dirname(__file__)): - if file.endswith(".py") and not file.startswith("_"): - task_name = file[: file.find(".py")] - importlib.import_module("examples.speech_text_joint_to_text.tasks." + task_name) diff --git a/spaces/mshukor/UnIVAL/fairseq/fairseq/tasks/language_modeling.py b/spaces/mshukor/UnIVAL/fairseq/fairseq/tasks/language_modeling.py deleted file mode 100644 index 4b76a51c61d71c4358de07bdd4eb3f93894737a8..0000000000000000000000000000000000000000 --- a/spaces/mshukor/UnIVAL/fairseq/fairseq/tasks/language_modeling.py +++ /dev/null @@ -1,379 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import logging -import os -from dataclasses import dataclass, field -from typing import Optional - -import numpy as np -import torch -from fairseq import utils -from fairseq.data import ( - AppendTokenDataset, - Dictionary, - IdDataset, - LMContextWindowDataset, - MonolingualDataset, - NestedDictionaryDataset, - NumelDataset, - PadDataset, - PrependTokenDataset, - StripTokenDataset, - TokenBlockDataset, - TruncatedDictionary, - data_utils, -) -from fairseq.data.indexed_dataset import get_available_dataset_impl -from fairseq.data.shorten_dataset import maybe_shorten_dataset -from fairseq.dataclass import ChoiceEnum, FairseqDataclass -from fairseq.tasks import LegacyFairseqTask, register_task -from omegaconf import II - - -SAMPLE_BREAK_MODE_CHOICES = ChoiceEnum(["none", "complete", "complete_doc", "eos"]) -SHORTEN_METHOD_CHOICES = ChoiceEnum(["none", "truncate", "random_crop"]) -logger = logging.getLogger(__name__) - - -@dataclass -class LanguageModelingConfig(FairseqDataclass): - data: Optional[str] = field( - default=None, metadata={"help": "path to data directory"} - ) - sample_break_mode: SAMPLE_BREAK_MODE_CHOICES = field( - default="none", - metadata={ - "help": 'If omitted or "none", fills each sample with tokens-per-sample ' - 'tokens. If set to "complete", splits samples only at the end ' - "of sentence, but may include multiple sentences per sample. " - '"complete_doc" is similar but respects doc boundaries. ' - 'If set to "eos", includes only one sentence per sample.' - }, - ) - tokens_per_sample: int = field( - default=1024, - metadata={"help": "max number of tokens per sample for LM dataset"}, - ) - output_dictionary_size: int = field( - default=-1, metadata={"help": "limit the size of output dictionary"} - ) - self_target: bool = field(default=False, metadata={"help": "include self target"}) - future_target: bool = field( - default=False, metadata={"help": "include future target"} - ) - past_target: bool = field(default=False, metadata={"help": "include past target"}) - add_bos_token: bool = field( - default=False, metadata={"help": "prepend beginning of sentence token ()"} - ) - max_target_positions: Optional[int] = field( - default=None, metadata={"help": "max number of tokens in the target sequence"} - ) - shorten_method: SHORTEN_METHOD_CHOICES = field( - default="none", - metadata={ - "help": "if not none, shorten sequences that exceed --tokens-per-sample" - }, - ) - shorten_data_split_list: str = field( - default="", - metadata={ - "help": "comma-separated list of dataset splits to apply shortening to, " - 'e.g., "train,valid" (default: all dataset splits)' - }, - ) - pad_to_fixed_length: Optional[bool] = field( - default=False, metadata={"help": "pad to fixed length"}, - ) - pad_to_fixed_bsz: Optional[bool] = field( - default=False, metadata={"help": "boolean to pad to fixed batch size"}, - ) - - # TODO common vars below add to parent - seed: int = II("common.seed") - batch_size: Optional[int] = II("dataset.batch_size") - batch_size_valid: Optional[int] = II("dataset.batch_size_valid") - dataset_impl: Optional[ChoiceEnum(get_available_dataset_impl())] = II( - "dataset.dataset_impl" - ) - data_buffer_size: int = II("dataset.data_buffer_size") - tpu: bool = II("common.tpu") - use_plasma_view: bool = II("common.use_plasma_view") - plasma_path: str = II("common.plasma_path") - - -@register_task("language_modeling", dataclass=LanguageModelingConfig) -class LanguageModelingTask(LegacyFairseqTask): - """ - Train a language model. - - Args: - dictionary (~fairseq.data.Dictionary): the dictionary for the input of - the language model - output_dictionary (~fairseq.data.Dictionary): the dictionary for the - output of the language model. In most cases it will be the same as - *dictionary*, but could possibly be a more limited version of the - dictionary (if ``--output-dictionary-size`` is used). - targets (List[str]): list of the target types that the language model - should predict. Can be one of "self", "future", and "past". - Defaults to "future". - - .. note:: - - The language modeling task is compatible with :mod:`fairseq-train`, - :mod:`fairseq-generate`, :mod:`fairseq-interactive` and - :mod:`fairseq-eval-lm`. - - The language modeling task provides the following additional command-line - arguments: - - .. argparse:: - :ref: fairseq.tasks.language_modeling_parser - :prog: - """ - - def __init__(self, args, dictionary, output_dictionary=None, targets=None): - super().__init__(args) - self.dictionary = dictionary - self.output_dictionary = output_dictionary or dictionary - - if targets is None: - targets = ["future"] - self.targets = targets - - @classmethod - def setup_dictionary(cls, args, **kwargs): - dictionary = None - output_dictionary = None - if args.data: - paths = utils.split_paths(args.data) - assert len(paths) > 0 - dictionary = Dictionary.load(os.path.join(paths[0], "dict.txt")) - logger.info("dictionary: {} types".format(len(dictionary))) - output_dictionary = dictionary - if args.output_dictionary_size >= 0: - output_dictionary = TruncatedDictionary( - dictionary, args.output_dictionary_size - ) - return (dictionary, output_dictionary) - - @classmethod - def setup_task(cls, args, **kwargs): - """Setup the task (e.g., load dictionaries). - - Args: - args (argparse.Namespace): parsed command-line arguments - """ - dictionary, output_dictionary = cls.setup_dictionary(args, **kwargs) - - # upgrade old checkpoints - if getattr(args, "exclude_self_target", False): - args.self_target = False - - targets = [] - if getattr(args, "self_target", False): - targets.append("self") - if getattr(args, "future_target", False): - targets.append("future") - if getattr(args, "past_target", False): - targets.append("past") - if len(targets) == 0: - # standard language modeling - targets = ["future"] - - return cls(args, dictionary, output_dictionary, targets=targets) - - def build_model(self, args): - model = super().build_model(args) - for target in self.targets: - if target not in model.supported_targets: - raise ValueError( - "Unsupported language modeling target: {}".format(target) - ) - - return model - - def load_dataset( - self, split: str, epoch=1, combine=False, **kwargs - ) -> MonolingualDataset: - """Load a given dataset split. - - Args: - split (str): name of the split (e.g., train, valid, valid1, test) - """ - paths = utils.split_paths(self.args.data) - assert len(paths) > 0 - - data_path = paths[(epoch - 1) % len(paths)] - split_path = os.path.join(data_path, split) - - # each process has its own copy of the raw data (likely to be an np.memmap) - dataset = data_utils.load_indexed_dataset( - split_path, self.dictionary, self.args.dataset_impl, combine=combine - ) - if dataset is None: - raise FileNotFoundError(f"Dataset not found: {split} ({split_path})") - - dataset = maybe_shorten_dataset( - dataset, - split, - self.args.shorten_data_split_list, - self.args.shorten_method, - self.args.tokens_per_sample, - self.args.seed, - ) - dataset = TokenBlockDataset( - dataset, - dataset.sizes, - self.args.tokens_per_sample, - pad=self.dictionary.pad(), - eos=self.dictionary.eos(), - break_mode=self.args.sample_break_mode, - include_targets=True, - use_plasma_view=self.args.use_plasma_view, - split_path=split_path, - plasma_path=self.args.plasma_path, - ) - - add_eos_for_other_targets = ( - self.args.sample_break_mode is not None - and self.args.sample_break_mode != "none" - ) - fixed_pad_length = None - if self.args.pad_to_fixed_length: - fixed_pad_length = self.args.tokens_per_sample - - pad_to_bsz = None - if self.args.pad_to_fixed_bsz: - pad_to_bsz = self.args.batch_size_valid if 'valid' in split else self.args.batch_size - - self.datasets[split] = MonolingualDataset( - dataset=dataset, - sizes=dataset.sizes, - src_vocab=self.dictionary, - tgt_vocab=self.output_dictionary, - add_eos_for_other_targets=add_eos_for_other_targets, - shuffle=True, - targets=self.targets, - add_bos_token=self.args.add_bos_token, - fixed_pad_length=fixed_pad_length, - pad_to_bsz=pad_to_bsz, - ) - - def build_dataset_for_inference(self, src_tokens, src_lengths, **kwargs): - """ - Generate batches for inference. We prepend an eos token to src_tokens - (or bos if `--add-bos-token` is set) and we append a to target. - This is convenient both for generation with a prefix and LM scoring. - """ - dataset = StripTokenDataset( - TokenBlockDataset( - src_tokens, - src_lengths, - block_size=None, # ignored for "eos" break mode - pad=self.source_dictionary.pad(), - eos=self.source_dictionary.eos(), - break_mode="eos", - ), - # remove eos from (end of) target sequence - self.source_dictionary.eos(), - ) - src_dataset = PrependTokenDataset( - dataset, - token=( - self.source_dictionary.bos() - if getattr(self.args, "add_bos_token", False) - else self.source_dictionary.eos() - ), - ) - tgt_dataset = AppendTokenDataset(dataset, token=self.source_dictionary.pad()) - return NestedDictionaryDataset( - { - "id": IdDataset(), - "net_input": { - "src_tokens": PadDataset( - src_dataset, - pad_idx=self.source_dictionary.pad(), - left_pad=False, - ), - "src_lengths": NumelDataset(src_dataset, reduce=False), - }, - "target": PadDataset( - tgt_dataset, pad_idx=self.source_dictionary.pad(), left_pad=False - ), - }, - sizes=[np.array(src_lengths)], - ) - - def inference_step( - self, generator, models, sample, prefix_tokens=None, constraints=None - ): - with torch.no_grad(): - # Generation will always be conditioned on bos_token - if getattr(self.args, "add_bos_token", False): - bos_token = self.source_dictionary.bos() - else: - bos_token = self.source_dictionary.eos() - - if constraints is not None: - raise NotImplementedError( - "Constrained decoding with the language_modeling task is not supported" - ) - - # SequenceGenerator doesn't use src_tokens directly, we need to - # pass the `prefix_tokens` argument instead - if prefix_tokens is None and sample["net_input"]["src_tokens"].nelement(): - prefix_tokens = sample["net_input"]["src_tokens"] - if prefix_tokens[:, 0].eq(bos_token).all(): - prefix_tokens = prefix_tokens[:, 1:] - - return generator.generate( - models, sample, prefix_tokens=prefix_tokens, bos_token=bos_token - ) - - def eval_lm_dataloader( - self, - dataset, - max_tokens: Optional[int] = 36000, - batch_size: Optional[int] = None, - max_positions: Optional[int] = None, - num_shards: int = 1, - shard_id: int = 0, - num_workers: int = 1, - data_buffer_size: int = 10, - # ensures that every evaluated token has access to a context of at least - # this size, if possible - context_window: int = 0, - ): - if context_window > 0: - dataset = LMContextWindowDataset( - dataset=dataset, - tokens_per_sample=self.args.tokens_per_sample, - context_window=context_window, - pad_idx=self.source_dictionary.pad(), - ) - return self.get_batch_iterator( - dataset=dataset, - max_tokens=max_tokens, - max_sentences=batch_size, - max_positions=max_positions, - ignore_invalid_inputs=True, - num_shards=num_shards, - shard_id=shard_id, - num_workers=num_workers, - data_buffer_size=data_buffer_size, - ).next_epoch_itr(shuffle=False) - - @property - def source_dictionary(self): - """Return the :class:`~fairseq.data.Dictionary` for the language - model.""" - return self.dictionary - - @property - def target_dictionary(self): - """Return the :class:`~fairseq.data.Dictionary` for the language - model.""" - return self.output_dictionary diff --git a/spaces/myrad01/Inpaint-Anything/third_party/lama/bin/gen_mask_dataset.py b/spaces/myrad01/Inpaint-Anything/third_party/lama/bin/gen_mask_dataset.py deleted file mode 100644 index 6e2ce3a9bc9708fd46641cab815113508af32d02..0000000000000000000000000000000000000000 --- a/spaces/myrad01/Inpaint-Anything/third_party/lama/bin/gen_mask_dataset.py +++ /dev/null @@ -1,130 +0,0 @@ -#!/usr/bin/env python3 - -import glob -import os -import shutil -import traceback - -import PIL.Image as Image -import numpy as np -from joblib import Parallel, delayed - -from saicinpainting.evaluation.masks.mask import SegmentationMask, propose_random_square_crop -from saicinpainting.evaluation.utils import load_yaml, SmallMode -from saicinpainting.training.data.masks import MixedMaskGenerator - - -class MakeManyMasksWrapper: - def __init__(self, impl, variants_n=2): - self.impl = impl - self.variants_n = variants_n - - def get_masks(self, img): - img = np.transpose(np.array(img), (2, 0, 1)) - return [self.impl(img)[0] for _ in range(self.variants_n)] - - -def process_images(src_images, indir, outdir, config): - if config.generator_kind == 'segmentation': - mask_generator = SegmentationMask(**config.mask_generator_kwargs) - elif config.generator_kind == 'random': - variants_n = config.mask_generator_kwargs.pop('variants_n', 2) - mask_generator = MakeManyMasksWrapper(MixedMaskGenerator(**config.mask_generator_kwargs), - variants_n=variants_n) - else: - raise ValueError(f'Unexpected generator kind: {config.generator_kind}') - - max_tamper_area = config.get('max_tamper_area', 1) - - for infile in src_images: - try: - file_relpath = infile[len(indir):] - img_outpath = os.path.join(outdir, file_relpath) - os.makedirs(os.path.dirname(img_outpath), exist_ok=True) - - image = Image.open(infile).convert('RGB') - - # scale input image to output resolution and filter smaller images - if min(image.size) < config.cropping.out_min_size: - handle_small_mode = SmallMode(config.cropping.handle_small_mode) - if handle_small_mode == SmallMode.DROP: - continue - elif handle_small_mode == SmallMode.UPSCALE: - factor = config.cropping.out_min_size / min(image.size) - out_size = (np.array(image.size) * factor).round().astype('uint32') - image = image.resize(out_size, resample=Image.BICUBIC) - else: - factor = config.cropping.out_min_size / min(image.size) - out_size = (np.array(image.size) * factor).round().astype('uint32') - image = image.resize(out_size, resample=Image.BICUBIC) - - # generate and select masks - src_masks = mask_generator.get_masks(image) - - filtered_image_mask_pairs = [] - for cur_mask in src_masks: - if config.cropping.out_square_crop: - (crop_left, - crop_top, - crop_right, - crop_bottom) = propose_random_square_crop(cur_mask, - min_overlap=config.cropping.crop_min_overlap) - cur_mask = cur_mask[crop_top:crop_bottom, crop_left:crop_right] - cur_image = image.copy().crop((crop_left, crop_top, crop_right, crop_bottom)) - else: - cur_image = image - - if len(np.unique(cur_mask)) == 0 or cur_mask.mean() > max_tamper_area: - continue - - filtered_image_mask_pairs.append((cur_image, cur_mask)) - - mask_indices = np.random.choice(len(filtered_image_mask_pairs), - size=min(len(filtered_image_mask_pairs), config.max_masks_per_image), - replace=False) - - # crop masks; save masks together with input image - mask_basename = os.path.join(outdir, os.path.splitext(file_relpath)[0]) - for i, idx in enumerate(mask_indices): - cur_image, cur_mask = filtered_image_mask_pairs[idx] - cur_basename = mask_basename + f'_crop{i:03d}' - Image.fromarray(np.clip(cur_mask * 255, 0, 255).astype('uint8'), - mode='L').save(cur_basename + f'_mask{i:03d}.png') - cur_image.save(cur_basename + '.png') - except KeyboardInterrupt: - return - except Exception as ex: - print(f'Could not make masks for {infile} due to {ex}:\n{traceback.format_exc()}') - - -def main(args): - if not args.indir.endswith('/'): - args.indir += '/' - - os.makedirs(args.outdir, exist_ok=True) - - config = load_yaml(args.config) - - in_files = list(glob.glob(os.path.join(args.indir, '**', f'*.{args.ext}'), recursive=True)) - if args.n_jobs == 0: - process_images(in_files, args.indir, args.outdir, config) - else: - in_files_n = len(in_files) - chunk_size = in_files_n // args.n_jobs + (1 if in_files_n % args.n_jobs > 0 else 0) - Parallel(n_jobs=args.n_jobs)( - delayed(process_images)(in_files[start:start+chunk_size], args.indir, args.outdir, config) - for start in range(0, len(in_files), chunk_size) - ) - - -if __name__ == '__main__': - import argparse - - aparser = argparse.ArgumentParser() - aparser.add_argument('config', type=str, help='Path to config for dataset generation') - aparser.add_argument('indir', type=str, help='Path to folder with images') - aparser.add_argument('outdir', type=str, help='Path to folder to store aligned images and masks to') - aparser.add_argument('--n-jobs', type=int, default=0, help='How many processes to use') - aparser.add_argument('--ext', type=str, default='jpg', help='Input image extension') - - main(aparser.parse_args()) diff --git a/spaces/nateraw/deepafx-st/deepafx_st/data/dataset.py b/spaces/nateraw/deepafx-st/deepafx_st/data/dataset.py deleted file mode 100644 index 41ebff6b7ae382b9f741e582e5f5864448980cf5..0000000000000000000000000000000000000000 --- a/spaces/nateraw/deepafx-st/deepafx_st/data/dataset.py +++ /dev/null @@ -1,344 +0,0 @@ -import os -import sys -import csv -import glob -import torch -import random -from tqdm import tqdm -from typing import List, Any - -from deepafx_st.data.audio import AudioFile -import deepafx_st.utils as utils -import deepafx_st.data.augmentations as augmentations - - -class AudioDataset(torch.utils.data.Dataset): - """Audio dataset which returns an input and target file. - - Args: - audio_dir (str): Path to the top level of the audio dataset. - input_dir (List[str], optional): List of paths to the directories containing input audio files. Default: ["clean"] - subset (str, optional): Dataset subset. One of ["train", "val", "test"]. Default: "train" - length (int, optional): Number of samples to load for each example. Default: 65536 - train_frac (float, optional): Fraction of the files to use for training subset. Default: 0.8 - val_frac (float, optional): Fraction of the files to use for validation subset. Default: 0.1 - buffer_size_gb (float, optional): Size of audio to read into RAM in GB at any given time. Default: 10.0 - Note: This is the buffer size PER DataLoader worker. So total RAM = buffer_size_gb * num_workers - buffer_reload_rate (int, optional): Number of items to generate before loading next chunk of dataset. Default: 10000 - half (bool, optional): Sotre audio samples as float 16. Default: False - num_examples_per_epoch (int, optional): Define an epoch as certain number of audio examples. Default: 10000 - random_scale_input (bool, optional): Apply random gain scaling to input utterances. Default: False - random_scale_target (bool, optional): Apply same random gain scaling to target utterances. Default: False - augmentations (dict, optional): List of augmentation types to apply to inputs. Default: [] - freq_corrupt (bool, optional): Apply bad EQ filters. Default: False - drc_corrupt (bool, optional): Apply an expander to corrupt dynamic range. Default: False - ext (str, optional): Expected audio file extension. Default: "wav" - """ - - def __init__( - self, - audio_dir, - input_dirs: List[str] = ["cleanraw"], - subset: str = "train", - length: int = 65536, - train_frac: float = 0.8, - val_per: float = 0.1, - buffer_size_gb: float = 1.0, - buffer_reload_rate: float = 1000, - half: bool = False, - num_examples_per_epoch: int = 10000, - random_scale_input: bool = False, - random_scale_target: bool = False, - augmentations: dict = {}, - freq_corrupt: bool = False, - drc_corrupt: bool = False, - ext: str = "wav", - ): - super().__init__() - self.audio_dir = audio_dir - self.dataset_name = os.path.basename(audio_dir) - self.input_dirs = input_dirs - self.subset = subset - self.length = length - self.train_frac = train_frac - self.val_per = val_per - self.buffer_size_gb = buffer_size_gb - self.buffer_reload_rate = buffer_reload_rate - self.half = half - self.num_examples_per_epoch = num_examples_per_epoch - self.random_scale_input = random_scale_input - self.random_scale_target = random_scale_target - self.augmentations = augmentations - self.freq_corrupt = freq_corrupt - self.drc_corrupt = drc_corrupt - self.ext = ext - - self.input_filepaths = [] - for input_dir in input_dirs: - search_path = os.path.join(audio_dir, input_dir, f"*.{ext}") - self.input_filepaths += glob.glob(search_path) - self.input_filepaths = sorted(self.input_filepaths) - - # create dataset split based on subset - self.input_filepaths = utils.split_dataset( - self.input_filepaths, - subset, - train_frac, - ) - - # get details about input audio files - input_files = {} - input_dur_frames = 0 - for input_filepath in tqdm(self.input_filepaths, ncols=80): - file_id = os.path.basename(input_filepath) - audio_file = AudioFile( - input_filepath, - preload=False, - half=half, - ) - if audio_file.num_frames < (self.length * 2): - continue - input_files[file_id] = audio_file - input_dur_frames += input_files[file_id].num_frames - - if len(list(input_files.items())) < 1: - raise RuntimeError(f"No files found in {search_path}.") - - input_dur_hr = (input_dur_frames / input_files[file_id].sample_rate) / 3600 - print( - f"\nLoaded {len(input_files)} files for {subset} = {input_dur_hr:0.2f} hours." - ) - - self.sample_rate = input_files[file_id].sample_rate - - # save a csv file with details about the train and test split - splits_dir = os.path.join("configs", "splits") - if not os.path.isdir(splits_dir): - os.makedirs(splits_dir) - csv_filepath = os.path.join(splits_dir, f"{self.dataset_name}_{self.subset}_set.csv") - - with open(csv_filepath, "w") as fp: - dw = csv.DictWriter(fp, ["file_id", "filepath", "type", "subset"]) - dw.writeheader() - for input_filepath in self.input_filepaths: - dw.writerow( - { - "file_id": self.get_file_id(input_filepath), - "filepath": input_filepath, - "type": "input", - "subset": self.subset, - } - ) - - # some setup for iteratble loading of the dataset into RAM - self.items_since_load = self.buffer_reload_rate - - def __len__(self): - return self.num_examples_per_epoch - - def load_audio_buffer(self): - self.input_files_loaded = {} # clear audio buffer - self.items_since_load = 0 # reset iteration counter - nbytes_loaded = 0 # counter for data in RAM - - # different subset in each - random.shuffle(self.input_filepaths) - - # load files into RAM - for input_filepath in self.input_filepaths: - file_id = os.path.basename(input_filepath) - audio_file = AudioFile( - input_filepath, - preload=True, - half=self.half, - ) - - if audio_file.num_frames < (self.length * 2): - continue - - self.input_files_loaded[file_id] = audio_file - - nbytes = audio_file.audio.element_size() * audio_file.audio.nelement() - nbytes_loaded += nbytes - - # check the size of loaded data - if nbytes_loaded > self.buffer_size_gb * 1e9: - break - - def generate_pair(self): - # ------------------------ Input audio ---------------------- - rand_input_file_id = None - input_file = None - start_idx = None - stop_idx = None - while True: - rand_input_file_id = self.get_random_file_id(self.input_files_loaded.keys()) - - # use this random key to retrieve an input file - input_file = self.input_files_loaded[rand_input_file_id] - - # load the audio data if needed - if not input_file.loaded: - raise RuntimeError("Audio not loaded.") - - # get a random patch of size `self.length` x 2 - start_idx, stop_idx = self.get_random_patch( - input_file, int(self.length * 2) - ) - if start_idx >= 0: - break - - input_audio = input_file.audio[:, start_idx:stop_idx].clone().detach() - input_audio = input_audio.view(1, -1) - - if self.half: - input_audio = input_audio.float() - - # peak normalize to -12 dBFS - input_audio /= input_audio.abs().max() - input_audio *= 10 ** (-12.0 / 20) # with min 3 dBFS headroom - - if len(list(self.augmentations.items())) > 0: - if torch.rand(1).sum() < 0.5: - input_audio_aug = augmentations.apply( - [input_audio], - self.sample_rate, - self.augmentations, - )[0] - else: - input_audio_aug = input_audio.clone() - else: - input_audio_aug = input_audio.clone() - - input_audio_corrupt = input_audio_aug.clone() - # apply frequency and dynamic range corrpution (expander) - if self.freq_corrupt and torch.rand(1).sum() < 0.75: - input_audio_corrupt = augmentations.frequency_corruption( - [input_audio_corrupt], self.sample_rate - )[0] - - # peak normalize again before passing through dynamic range expander - input_audio_corrupt /= input_audio_corrupt.abs().max() - input_audio_corrupt *= 10 ** (-12.0 / 20) # with min 3 dBFS headroom - - if self.drc_corrupt and torch.rand(1).sum() < 0.10: - input_audio_corrupt = augmentations.dynamic_range_corruption( - [input_audio_corrupt], self.sample_rate - )[0] - - # ------------------------ Target audio ---------------------- - # use the same augmented audio clip, add different random EQ and compressor - - target_audio_corrupt = input_audio_aug.clone() - # apply frequency and dynamic range corrpution (expander) - if self.freq_corrupt and torch.rand(1).sum() < 0.75: - target_audio_corrupt = augmentations.frequency_corruption( - [target_audio_corrupt], self.sample_rate - )[0] - - # peak normalize again before passing through dynamic range compressor - input_audio_corrupt /= input_audio_corrupt.abs().max() - input_audio_corrupt *= 10 ** (-12.0 / 20) # with min 3 dBFS headroom - - if self.drc_corrupt and torch.rand(1).sum() < 0.75: - target_audio_corrupt = augmentations.dynamic_range_compression( - [target_audio_corrupt], self.sample_rate - )[0] - - return input_audio_corrupt, target_audio_corrupt - - def __getitem__(self, _): - """ """ - - # increment counter - self.items_since_load += 1 - - # load next chunk into buffer if needed - if self.items_since_load > self.buffer_reload_rate: - self.load_audio_buffer() - - # generate pairs for style training - input_audio, target_audio = self.generate_pair() - - # ------------------------ Conform length of files ------------------- - input_audio = utils.conform_length(input_audio, int(self.length * 2)) - target_audio = utils.conform_length(target_audio, int(self.length * 2)) - - # ------------------------ Apply fade in and fade out ------------------- - input_audio = utils.linear_fade(input_audio, sample_rate=self.sample_rate) - target_audio = utils.linear_fade(target_audio, sample_rate=self.sample_rate) - - # ------------------------ Final normalizeation ---------------------- - # always peak normalize final input to -12 dBFS - input_audio /= input_audio.abs().max() - input_audio *= 10 ** (-12.0 / 20.0) - - # always peak normalize the target to -12 dBFS - target_audio /= target_audio.abs().max() - target_audio *= 10 ** (-12.0 / 20.0) - - return input_audio, target_audio - - @staticmethod - def get_random_file_id(keys): - # generate a random index into the keys of the input files - rand_input_idx = torch.randint(0, len(keys) - 1, [1])[0] - # find the key (file_id) correponding to the random index - rand_input_file_id = list(keys)[rand_input_idx] - - return rand_input_file_id - - @staticmethod - def get_random_patch(audio_file, length, check_silence=True): - silent = True - count = 0 - while silent: - count += 1 - start_idx = torch.randint(0, audio_file.num_frames - length - 1, [1])[0] - # int(torch.rand(1) * (audio_file.num_frames - length)) - stop_idx = start_idx + length - patch = audio_file.audio[:, start_idx:stop_idx].clone().detach() - - length = patch.shape[-1] - first_patch = patch[..., : length // 2] - second_patch = patch[..., length // 2 :] - - if ( - (first_patch**2).mean() > 1e-5 and (second_patch**2).mean() > 1e-5 - ) or not check_silence: - silent = False - - if count > 100: - print("get_random_patch count", count) - return -1, -1 - # break - - return start_idx, stop_idx - - def get_file_id(self, filepath): - """Given a filepath extract the DAPS file id. - - Args: - filepath (str): Path to an audio files in the DAPS dataset. - - Returns: - file_id (str): DAPS file id of the form _ - file_set (str): The DAPS set to which the file belongs. - """ - file_id = os.path.basename(filepath).split("_")[:2] - file_id = "_".join(file_id) - return file_id - - def get_file_set(self, filepath): - """Given a filepath extract the DAPS file set name. - - Args: - filepath (str): Path to an audio files in the DAPS dataset. - - Returns: - file_set (str): The DAPS set to which the file belongs. - """ - file_set = os.path.basename(filepath).split("_")[2:] - file_set = "_".join(file_set) - file_set = file_set.replace(f".{self.ext}", "") - return file_set diff --git a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/2011 Gta Vice City Extreme Tuning Mod 2005 211.md b/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/2011 Gta Vice City Extreme Tuning Mod 2005 211.md deleted file mode 100644 index 7064c1a990db964fb10e7be6168ca5b2801e0988..0000000000000000000000000000000000000000 --- a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/2011 Gta Vice City Extreme Tuning Mod 2005 211.md +++ /dev/null @@ -1,35 +0,0 @@ -
        -

        How to Install and Play GTA Vice City Extreme Tuning Mod 2005 211

        -

        GTA Vice City is one of the most popular and iconic games in the Grand Theft Auto series. It features a vibrant and colorful open world set in the 1980s, with a variety of missions, characters, vehicles, and weapons. But did you know that you can also customize and enhance your GTA Vice City experience with mods?

        -

        Mods are modifications that add new features, content, or changes to the game. They can range from simple tweaks to complete overhauls. One of the most impressive and comprehensive mods for GTA Vice City is the Extreme Tuning Mod 2005 211, created by HBSumon[^1^]. This mod adds a lot of new elements to the game, such as:

        -

        2011 Gta Vice City Extreme Tuning Mod 2005 211


        Download Zip ○○○ https://urlcod.com/2uIbrV



        -
          -
        • All missions unlocked
        • -
        • Super bike 1000x faster
        • -
        • All vehicles speed meter mod
        • -
        • All city unlocked
        • -
        • Added new mission
        • -
        • Super running mod
        • -
        • Super bike control
        • -
        -

        If you want to try out this mod and see how it transforms your GTA Vice City gameplay, here are the steps you need to follow:

        -
          -
        1. Download the mod file from here [^1^] or here [^2^]. The file size is about 1 GB.
        2. -
        3. Extract the zip file with any extractor program.
        4. -
        5. Copy the data folder and paste it into your GTA Vice City directory folder, replacing all files.
        6. -
        7. Launch the game and enjoy!
        8. -
        -

        Note: Do not use any other cleo mods or scripts with this mod, as they may cause the game to crash or not work properly. If you encounter any problems, please contact the mod author at habiburbasarsumon123@gmail.com [^1^].

        -

        GTA Vice City Extreme Tuning Mod 2005 211 is a great way to spice up your GTA Vice City experience and have some fun with new features and challenges. It is one of the many mods available for GTA Vice City that show how creative and passionate the modding community is. If you are looking for more mods to try out, you can check out some of these websites:

        - -

        Have fun and happy gaming!

        - -

        If you are wondering how this mod affects the gameplay and the graphics of GTA Vice City, you can watch some videos on YouTube that showcase the mod in action. For example, you can check out this video by GTA Gaming1 [^3^] or this video by Penta BroZ . You will see how the mod changes the look and feel of the game, making it more dynamic and exciting.

        -

        Some of the features that stand out in this mod are the super bike and the super running mod. The super bike is a motorcycle that can reach incredible speeds and perform amazing stunts. You can use it to explore the city, escape from the police, or just have fun. The super running mod allows you to run faster than any car or pedestrian, making you feel like a superhero. You can use it to complete missions faster, avoid enemies, or just enjoy the scenery.

        -

        Of course, this mod also has some drawbacks and limitations. For one thing, it is not compatible with any other cleo mods or scripts, so you have to choose between this mod and others. For another thing, it may cause some glitches or bugs in the game, such as crashes or freezes. If you encounter any problems, you can try to contact the mod author or look for solutions online. You can also backup your original game files before installing this mod, in case you want to revert to the vanilla version.

        81aa517590
        -
        -
        \ No newline at end of file diff --git a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Agatha Christies Poirot S13E01 HDTV X264-TLA [eztv] Free.md b/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Agatha Christies Poirot S13E01 HDTV X264-TLA [eztv] Free.md deleted file mode 100644 index 7e58ccb893fbdbf6a922e7cb4dc4db0c077d9b6d..0000000000000000000000000000000000000000 --- a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Agatha Christies Poirot S13E01 HDTV X264-TLA [eztv] Free.md +++ /dev/null @@ -1,18 +0,0 @@ -
        -

        Review: Agatha Christies Poirot S13E01 HDTV x264-TLA [eztv]

        -

        Agatha Christie's Poirot is a British television series that adapts the novels and short stories of the famous detective writer. The series stars David Suchet as Hercule Poirot, a Belgian sleuth who solves mysteries with his keen observation and logical reasoning. The series has been running since 1989 and has covered most of the original stories by Christie.

        -

        Agatha Christies Poirot S13E01 HDTV x264-TLA [eztv]


        Download 🆓 https://urlcod.com/2uIatI



        -

        The thirteenth and final season of Agatha Christie's Poirot premiered on June 9, 2013 with the episode "Elephants Can Remember". The episode is based on the novel of the same name, published in 1972. It follows Poirot and his friend Ariadne Oliver, a crime novelist, as they investigate a double murder that happened twenty years ago. The only clue they have is the word "elephants", which was uttered by one of the victims before dying.

        -

        The episode is a fitting start for the last season of the show, as it showcases Poirot's skills and personality. Suchet delivers a brilliant performance as the aging detective, who still has his charm and wit. The episode also pays homage to Christie's own career as a writer, as Oliver is a fictionalized version of herself. The plot is intriguing and complex, with twists and turns that keep the viewers guessing until the end.

        -

        The episode is available for download on eztv, a popular torrent site that provides high-quality video files of various shows. The file name is Agatha Christies Poirot S13E01 HDTV x264-TLA [eztv], which indicates that it is a high-definition television rip encoded with x264 codec and released by TLA group. The file size is 435 MB and the runtime is 88 minutes.

        -

        -

        If you are a fan of Agatha Christie's Poirot or mystery genre in general, you should definitely watch this episode. It is a well-crafted adaptation of a classic story that will keep you entertained and engaged. You can download it from eztv using the link below:

        - - -

        The episode "Elephants Can Remember" is one of the four feature-length episodes that make up the final season of Agatha Christie's Poirot. The other three are "The Big Four", "The Labours of Hercules" and "Curtain: Poirot's Last Case". These episodes are based on some of the most acclaimed and challenging novels by Christie, and they showcase Poirot's final cases before his retirement and death.

        -

        The episode features a stellar cast of supporting actors, including Zoë Wanamaker as Ariadne Oliver, Greta Scacchi as Celia Ravenscroft, Iain Glen as Dr. Willoughby, Vanessa Kirby as Alexandra Ravenscroft and Ferdinand Kingsley as Zelie Ledbetter. The episode also features some references to previous cases and characters from the series, such as Countess Vera Rossakoff, Major Hastings and Miss Lemon.

        -

        The episode received positive reviews from critics and fans alike, who praised the adaptation, the direction, the cinematography and the performances. The episode was nominated for a BAFTA TV Award for Best Photography and Lighting (Fiction/Entertainment) in 2014. The episode also marked the end of an era for David Suchet, who had played Poirot for 25 years and had become synonymous with the character.

        7b8c122e87
        -
        -
        \ No newline at end of file diff --git a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Alarm Cobra 11 Free Download Full [PORTABLE] Versionl.md b/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Alarm Cobra 11 Free Download Full [PORTABLE] Versionl.md deleted file mode 100644 index 10fe0e336f8c25164d9348776cbe5ad2779b1dd3..0000000000000000000000000000000000000000 --- a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Alarm Cobra 11 Free Download Full [PORTABLE] Versionl.md +++ /dev/null @@ -1,22 +0,0 @@ -
        -

        How to Download and Play Alarm Cobra 11 Games on Your PC

        -

        Alarm Cobra 11 is a series of action-packed racing games based on the German TV show of the same name. The games feature high-speed chases, explosions, and stunts as you play as a member of the highway police. If you are a fan of Alarm Cobra 11 and want to play the games on your PC, here are some steps you can follow:

        -

        Alarm Cobra 11 Free Download Full Versionl


        DOWNLOADhttps://urlcod.com/2uIa3A



        -
          -
        1. Choose which game you want to download. There are several Alarm Cobra 11 games available for PC, such as Alarm for Cobra 11: Nitro[^2^], Alarm for Cobra 11: Crash Time[^1^], and Alarm for Cobra 11 Vol. 2: Hot Pursuit[^2^]. You can find more information about each game on their respective websites or online reviews.
        2. -
        3. Find a reliable source to download the game. You can either buy the game from an online store or download it for free from a website that offers old games. Some examples of such websites are Old Games Download[^1^] [^2^] and Internet Archive[^3^] [^4^] [^5^]. Make sure to check the file size, compatibility, and language of the game before downloading it.
        4. -
        5. Install and run the game on your PC. Depending on the game you downloaded, you may need to extract the files, mount the image, copy a no-cd patch, or use a compatibility tool like dgVoodoo 2. You can find more instructions on how to install and run each game on their download pages or readme files.
        6. -
        7. Enjoy playing Alarm Cobra 11 games on your PC. You can adjust the settings, controls, and graphics according to your preferences. You can also play with friends online or offline using multiplayer modes or split-screen options.
        8. -
        -

        Alarm Cobra 11 games are fun and thrilling racing games that will keep you on the edge of your seat. If you want to experience the adrenaline rush of chasing criminals and causing mayhem on the highway, download and play Alarm Cobra 11 games on your PC today!

        - -

        If you are wondering what makes Alarm Cobra 11 games so exciting and unique, here are some of the features that set them apart from other racing games:

        -
          -
        • Realistic and diverse scenarios. The games are based on the TV show, which means they feature realistic locations, vehicles, and situations. You can drive on highways, cities, airports, bridges, tunnels, and more. You can also encounter different types of criminals, such as terrorists, smugglers, kidnappers, and robbers.
        • -
        • Dynamic and interactive environment. The games allow you to interact with the environment in various ways. You can use objects like ramps, barrels, crates, and signs to perform stunts or create obstacles. You can also cause damage to the environment and trigger explosions or fires.
        • -
        • Challenging and varied missions. The games offer a variety of missions that test your skills and reflexes. You can choose from different modes, such as story mode, arcade mode, or free mode. You can also customize your difficulty level and objectives.
        • -
        • Fun and engaging gameplay. The games are designed to provide you with a thrilling and satisfying gameplay experience. You can use different weapons and gadgets to stop the criminals or escape the police. You can also enjoy the realistic physics and graphics that make the game more immersive.
        • -
        -

        Alarm Cobra 11 games are not for the faint of heart. They are for those who love speed, action, and adventure. If you are one of them, don't hesitate to download and play Alarm Cobra 11 games on your PC now!

        81aa517590
        -
        -
        \ No newline at end of file diff --git a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Bus Driver Simulator 2018 Crack CD Key Download Free For PC LINK.md b/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Bus Driver Simulator 2018 Crack CD Key Download Free For PC LINK.md deleted file mode 100644 index 669c6f6298815085ec1c9a1bb0a31d1061e24c37..0000000000000000000000000000000000000000 --- a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Bus Driver Simulator 2018 Crack CD Key Download Free For PC LINK.md +++ /dev/null @@ -1,19 +0,0 @@ -
        -

        Bus Driver Simulator 2018 Crack CD Key Download Free For PC

        -

        If you are looking for a realistic and immersive bus driving experience, you might want to check out Bus Driver Simulator 2018. This game lets you take the role of a bus driver in a vast and freely drivable urban area. You can drive original licensed city buses from the great brands: Mercedes-Benz, Setra, MAN, and IVECO BUS. You can transport your passengers safely and punctually, either solo in single player mode, or in multiplayer mode with your friends.

        -

        Bus driver simulator 2018 Crack CD Key Download Free For PC


        DOWNLOADhttps://urlcod.com/2uIcm1



        -

        Bus Driver Simulator 2018 is a simulation video game developed by KishMish Games and published by KishMish Games. It was released on January 31, 2018 for PC. The game features realistic traffic and weather conditions, day and night cycles, different bus models and routes, and a career mode with achievements and rewards.

        -

        However, if you want to play Bus Driver Simulator 2018 on your PC, you might need to pay for it on Steam or other platforms. But don't worry, there is a way to get Bus Driver Simulator 2018 Crack CD Key Download Free For PC. All you need to do is follow these simple steps:

        -
          -
        1. Go to this website and click on the download button.
        2. -
        3. Extract the zip file and run the setup.exe file.
        4. -
        5. Follow the installation instructions and choose your preferred language and destination folder.
        6. -
        7. Copy the crack files from the crack folder and paste them into the game folder.
        8. -
        9. Launch the game and enjoy Bus Driver Simulator 2018 for free.
        10. -
        -

        That's it! You have successfully downloaded and installed Bus Driver Simulator 2018 Crack CD Key Download Free For PC. Now you can enjoy driving buses in a realistic environment without spending any money. Have fun!

        Bus Driver Simulator 2018 is not only a game, but also a learning experience. You can improve your driving skills, learn the traffic rules, and get familiar with the city layout. You can also customize your bus with different skins and decals, and adjust the settings to your liking. You can choose between different camera angles, steering modes, and difficulty levels.

        -

        Bus Driver Simulator 2018 has received mixed or average reviews from critics and users. Some praised the game for its realism, variety, and modding support. Others criticized the game for its bugs, glitches, and lack of polish. The game has a Metascore of 67 and a User Score of 6.3 on Metacritic[^2^]. One reviewer said: "Bus Simulator 18, at its core, is a good simulator game with a whole lot of soul. It brings a lot of playability options to the table, whether you want to just drive a bus or manage the whole company. The driving is complex enough to keep the player involved, and the economic systems provide a respite for players tired of being behind the wheel."[^2^]

        -

        If you are interested in Bus Driver Simulator 2018, you can buy it on Steam for $24.99[^1^] or watch some gameplay videos on YouTube[^3^]. You can also download Bus Driver Simulator 2018 Crack CD Key Download Free For PC from this website and enjoy the game without paying anything. However, this might be illegal or unsafe, so do it at your own risk.

        -

        7b8c122e87
        -
        -
        \ No newline at end of file diff --git a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Download Kyun! Ho Gaya Na Movie Subtitle Indonesia Download.md b/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Download Kyun! Ho Gaya Na Movie Subtitle Indonesia Download.md deleted file mode 100644 index 4948d0fac9fa7b4e66ebd0fc5a92d4a16aecad92..0000000000000000000000000000000000000000 --- a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Download Kyun! Ho Gaya Na Movie Subtitle Indonesia Download.md +++ /dev/null @@ -1,23 +0,0 @@ -
        -

        How to Download Kyun! Ho Gaya Na Movie Subtitle Indonesia Download

        -

        If you are looking for a romantic comedy movie to watch, you might want to check out Kyun! Ho Gaya Na, a 2004 Bollywood film starring Aishwarya Rai and Vivek Oberoi. The movie tells the story of Diya and Arjun, two opposites who fall in love despite their differences. But can they overcome the obstacles that come their way?

        -

        One of the challenges that you might face if you want to watch this movie is finding the subtitles in Indonesian. The movie is in Hindi, and you might not understand everything that is happening on the screen. Fortunately, there are some websites that offer Kyun! Ho Gaya Na movie subtitle indonesia download for free. Here are some of them:

        -

        download Kyun! Ho Gaya Na movie subtitle indonesia download


        Download Ziphttps://urlcod.com/2uI9vP



        -
          -
        • Subscene: This is one of the most popular websites for downloading subtitles for movies and TV shows. You can find subtitles in various languages, including Indonesian. Just search for Kyun! Ho Gaya Na and choose the subtitle file that matches your video quality and format.
        • -
        • iSubtitles: This is another website that offers subtitles for Kyun! Ho Gaya Na in Indonesian. You can download the subtitle file in SRT or ZIP format. You can also preview the subtitles before downloading them.
        • -
        • OpenSubtitles: This is a website that has a large database of subtitles for movies and TV shows. You can find subtitles for Kyun! Ho Gaya Na in Indonesian and other languages. You can also rate and comment on the subtitles.
        • -
        -

        Once you have downloaded the subtitle file, you need to add it to your video player. Depending on the video player you use, you might need to rename the subtitle file to match the video file name, or select the subtitle file from the menu. You can also adjust the timing and font size of the subtitles if needed.

        -

        Now you are ready to enjoy Kyun! Ho Gaya Na movie with subtitle indonesia download. We hope you have a great time watching this romantic comedy film.

        - -

        If you are wondering what makes Kyun! Ho Gaya Na movie worth watching, here are some of the reasons why you might like it:

        -
          -
        1. The chemistry between the leads: Aishwarya Rai and Vivek Oberoi are not only beautiful actors, but also real life lovers. They bring a natural charm and charisma to their roles as Diya and Arjun, who have a love-hate relationship. You can feel their attraction and tension as they bicker and flirt throughout the movie.
        2. -
        3. The humor and romance: Kyun! Ho Gaya Na movie is a romantic comedy that will make you laugh and swoon. The movie has many funny scenes and dialogues that will keep you entertained. The movie also has some sweet and romantic moments that will melt your heart. The movie has a good balance of comedy and romance that will appeal to different audiences.
        4. -
        5. The music and dance: Kyun! Ho Gaya Na movie has a catchy and melodious soundtrack that will make you want to sing along. The movie also has some impressive dance numbers that showcase the talent and grace of the actors. The movie has a colorful and vibrant style that matches the mood and tone of the story.
        6. -
        -

        These are some of the reasons why Kyun! Ho Gaya Na movie is a fun and enjoyable watch. If you are looking for a light-hearted and entertaining movie, you should give Kyun! Ho Gaya Na movie subtitle indonesia download a try.

        -

        e93f5a0c3f
        -
        -
        \ No newline at end of file diff --git a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Free Copy Of Iso 2859 Pdf EXCLUSIVE.md b/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Free Copy Of Iso 2859 Pdf EXCLUSIVE.md deleted file mode 100644 index 8d9c1ce93bc85d10201c0bdab55e5f0ed74de9e3..0000000000000000000000000000000000000000 --- a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Free Copy Of Iso 2859 Pdf EXCLUSIVE.md +++ /dev/null @@ -1,29 +0,0 @@ -
        -

        How to Get a Free Copy of ISO 2859 PDF

        -

        ISO 2859 is a standard that specifies the sampling procedures and tables for inspection by attributes. It is widely used in quality control and assurance, especially for products that have to meet certain specifications and criteria. If you are looking for a free copy of ISO 2859 PDF, you may be wondering where to find it and how to download it legally.

        -

        Free Copy Of Iso 2859 Pdf


        DOWNLOAD ::: https://urlcod.com/2uIbQg



        -

        In this article, we will show you some of the best sources to get a free copy of ISO 2859 PDF, as well as some tips on how to use it effectively.

        - -

        Why Do You Need ISO 2859 PDF?

        -

        ISO 2859 PDF is a useful document for anyone who is involved in quality management, inspection, testing, or auditing. It provides a systematic and statistical approach to determine the acceptance or rejection of a lot or batch of products based on the number of defects or nonconformities found in a sample.

        -

        By using ISO 2859 PDF, you can save time and money by avoiding unnecessary inspections and rework. You can also ensure that your products meet the expectations and requirements of your customers and stakeholders. ISO 2859 PDF can help you improve your quality performance and reputation.

        - -

        Where to Find a Free Copy of ISO 2859 PDF?

        -

        ISO 2859 PDF is not a free document that you can download from any website. It is a copyrighted document that belongs to the International Organization for Standardization (ISO), which is the world's largest developer and publisher of international standards. You have to pay a fee to access the official version of ISO 2859 PDF from the ISO website or its authorized distributors.

        -

        However, there are some ways to get a free copy of ISO 2859 PDF legally and ethically. Here are some of them:

        -
          -
        • Borrow it from a library. Many libraries have subscriptions to online databases that contain ISO standards and other technical documents. You can check if your local library has access to ISO 2859 PDF and borrow it for a limited period of time. You may need to register as a library member and follow the library's rules and policies.
        • -
        • Request it from your organization. If you work for an organization that has purchased ISO 2859 PDF or has a membership with ISO, you can ask your manager or supervisor if you can use it for your work purposes. You may need to sign a confidentiality agreement and respect the intellectual property rights of ISO.
        • -
        • Search for it on the internet. Some websites may offer free copies of ISO 2859 PDF for educational or informational purposes. However, you have to be careful about the quality and validity of these copies, as they may be outdated, incomplete, or inaccurate. You also have to respect the copyright laws and avoid downloading or sharing any illegal or pirated copies.
        • -
        - -

        How to Use ISO 2859 PDF Effectively?

        -

        Once you have obtained a free copy of ISO 2859 PDF, you need to know how to use it properly and efficiently. Here are some tips on how to do that:

        -
          -
        • Read the introduction and scope. The introduction and scope sections of ISO 2859 PDF give you an overview of the purpose, objectives, principles, and limitations of the standard. They also explain the terms and definitions used in the standard and provide references to other related standards.
        • -
        • Select the appropriate sampling plan. ISO 2859 PDF contains several sampling plans that vary in terms of the sample size, acceptance number, rejection number, inspection level, and acceptance quality limit (AQL). You need to choose the sampling plan that suits your product type, quality characteristics, inspection criteria, and risk level.
        • -
        • Follow the sampling procedures. ISO 2859 PDF provides detailed instructions on how to select, inspect, classify, record, and report the samples according to the chosen sampling plan. You need to follow these procedures carefully and consistently to ensure the validity and reliability of your results.
        • -
        • Analyze and interpret the results. Based on the number of defects or nonconformities found in the sample, you can decide whether to accept or reject the lot or batch of products. You can also calculate the estimated percentage of defective units in the lot or batch using the formulas given in ISO 2859 PDF.

          -

          cec2833e83
          -
          -
          \ No newline at end of file diff --git a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Free Web App To Automatically Add Chord Progression Chord Master.md b/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Free Web App To Automatically Add Chord Progression Chord Master.md deleted file mode 100644 index 81d909eef8e083f749ae063bc722fbe3bc2b899a..0000000000000000000000000000000000000000 --- a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Free Web App To Automatically Add Chord Progression Chord Master.md +++ /dev/null @@ -1,38 +0,0 @@ - -

          How to Use Chord Master: A Free Web App to Automatically Add Chord Progression to Your Songs

          - -

          Do you want to create amazing songs with catchy chord progressions? Do you struggle with finding the right chords for your melodies? Do you wish there was a tool that could help you generate chords in seconds?

          -

          Free Web App to Automatically Add Chord Progression: Chord Master


          Download Zip ►►► https://urlcod.com/2uI9RF



          - -

          If you answered yes to any of these questions, then you need to check out Chord Master, a free web app that can automatically add chord progression to your songs. Chord Master is a simple and powerful tool that can help you create professional-sounding music in minutes. Here's how it works:

          - -
            -
          1. Go to chordmaster.com and sign up for a free account.
          2. -
          3. Upload your melody file or record it directly on the website.
          4. -
          5. Select your preferred genre, mood, key, and tempo.
          6. -
          7. Click on the "Generate Chords" button and wait for a few seconds.
          8. -
          9. Voila! You will see a list of possible chord progressions that match your melody. You can listen to them, edit them, or download them as MIDI files.
          10. -
          - -

          Chord Master uses artificial intelligence and music theory to analyze your melody and generate chords that fit it perfectly. You can choose from different genres, such as pop, rock, jazz, blues, R&B, hip hop, and more. You can also adjust the mood, key, and tempo of your song to suit your style and preference.

          - -

          Chord Master is not only a great tool for beginners who want to learn how to write songs with chords, but also for advanced musicians who want to experiment with different chord progressions and harmonies. You can use Chord Master to create original songs, remix existing songs, or add some spice to your covers.

          - -

          Chord Master is free to use and does not require any installation or registration. You can access it from any device with an internet connection and a browser. You can also share your creations with other users and get feedback and inspiration from the community.

          - -

          So what are you waiting for? Try Chord Master today and unleash your musical creativity!

          -

          - -

          If you want to learn more about how Chord Master works and how to use it effectively, you can check out the following resources:

          - -
            -
          • The FAQ page, where you can find answers to common questions and issues.
          • -
          • The Blog page, where you can read articles and tips on songwriting, chord progression, music theory, and more.
          • -
          • The Contact page, where you can send your feedback, suggestions, or inquiries to the Chord Master team.
          • -
          - -

          You can also follow Chord Master on social media platforms, such as Facebook, Twitter, Instagram, and YouTube, to stay updated on the latest news and features. You can also join the Chord Master community and interact with other users who share your passion for music.

          - -

          Chord Master is more than just a web app. It's a platform that empowers you to create amazing songs with chords. Whether you are a beginner or a pro, Chord Master can help you take your music to the next level. Don't miss this opportunity to make your musical dreams come true. Start using Chord Master today and see the difference for yourself!

          cec2833e83
          -
          -
          \ No newline at end of file diff --git a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Sonic Generations Graphics Confi.md b/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Sonic Generations Graphics Confi.md deleted file mode 100644 index e7aa7ab11b949b5dc4282dc4dcd8be265754eaaf..0000000000000000000000000000000000000000 --- a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Sonic Generations Graphics Confi.md +++ /dev/null @@ -1,27 +0,0 @@ -
          -

          How to Optimize Your Sonic Generations Graphics Configuration

          -

          Sonic Generations is a popular game that celebrates the 20th anniversary of the Sonic the Hedgehog franchise. It features two versions of Sonic, classic and modern, as they travel through various stages from past games. The game has received critical acclaim for its gameplay, graphics, and music.

          -

          However, some players may encounter issues with the game's graphics configuration, such as the game not launching, displaying an error message, or having poor performance. In this article, we will show you how to fix these problems and optimize your Sonic Generations graphics configuration for the best gaming experience.

          -

          Sonic Generations Graphics Confi


          Download Ziphttps://urlcod.com/2uIbDa



          -

          What is Sonic Generations Graphics Confi?

          -

          Sonic Generations Graphics Confi is a file that stores the settings for the game's graphics options, such as resolution, anti-aliasing, shadow quality, and more. The file is located in the game's installation folder, usually under C:\Program Files (x86)\Steam\steamapps\common\Sonic Generations.

          -

          The game also comes with a configuration tool that allows you to change these settings and save them to the file. The tool can be accessed by right-clicking on the game in your Steam library, selecting Properties, then clicking on Set Launch Options. Alternatively, you can run the tool directly from the game's folder by double-clicking on ConfigurationTool.exe.

          -

          How to Fix No Valid Graphics Configuration File Found Error

          -

          One of the most common issues that players face with Sonic Generations is the error message that says "No valid Graphics Configuration File found, please run the Configuration Tool and Save." This usually happens when the game cannot find or read the graphics configuration file properly.

          -

          There are several possible solutions to this problem:

          -

          -
            -
          • Run the configuration tool as an administrator. This will ensure that the tool has enough permissions to create and modify the graphics configuration file. To do this, right-click on ConfigurationTool.exe, select Run as administrator, then click on Yes when prompted.
          • -
          • Verify the integrity of the game files through Steam. This will check if any of the game files are missing or corrupted, and download them again if necessary. To do this, right-click on the game in your Steam library, select Properties, then click on Local Files tab. Then click on Verify Integrity of Game Files and wait for the process to finish.
          • -
          • Use a modified version of the configuration tool that fixes some issues and design inconsistencies. For example, you can try Better Sonic Generations Config Tool, which is a tweaked version of the original tool that uses Sajid's decompilation as a base. This tool has some improvements such as aligning text, adding taskbar icon, changing antialiasing setting name, simplifying resolution list, fixing scaling and transparency issues, and more.
          • -
          -

          How to Optimize Your Sonic Generations Graphics Configuration

          -

          Once you have fixed the error message and can run the configuration tool successfully, you can optimize your Sonic Generations graphics configuration for better performance and quality. Here are some tips on how to do that:

          -
            -
          • Choose a resolution that matches your monitor's native resolution. This will ensure that the game looks sharp and clear on your screen. You can also choose a lower resolution if your computer cannot handle higher ones.
          • -
          • Enable antialiasing (FXAA) if you want to smooth out jagged edges in the game. However, this may also reduce your frame rate slightly, so you can disable it if you prefer faster performance.
          • -
          • Adjust shadow quality according to your preference. Higher shadow quality will make the game look more realistic and immersive, but it will also consume more resources and lower your frame rate. Lower shadow quality will have the opposite effect.
          • -
          • Enable VSync if you want to prevent screen tearing, which is when parts of the image appear out of sync with each other. However, this may also introduce input lag and limit your frame rate to your monitor's refresh rate. Disable VSync if you prefer smoother and more responsive gameplay.
          • -
          • Save your settings by clicking on OK

            e93f5a0c3f
            -
            -
            \ No newline at end of file diff --git a/spaces/nsaintsever/music-generation/README.md b/spaces/nsaintsever/music-generation/README.md deleted file mode 100644 index 00de220a2ac33a42115072125561bbc79b9bc75d..0000000000000000000000000000000000000000 --- a/spaces/nsaintsever/music-generation/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Music Generation -emoji: 🐠 -colorFrom: blue -colorTo: gray -sdk: streamlit -sdk_version: 1.27.2 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/nt3awnou/Nt3awnou-rescue-map/src/text_content.py b/spaces/nt3awnou/Nt3awnou-rescue-map/src/text_content.py deleted file mode 100644 index 6ab91e73f3d77ec1f104293446403701a2d84a0e..0000000000000000000000000000000000000000 --- a/spaces/nt3awnou/Nt3awnou-rescue-map/src/text_content.py +++ /dev/null @@ -1,104 +0,0 @@ -INTRO_TEXT_EN = """ -
            - Nt3awnou نتعاونو is a non-profit organization and a collaborative platform dedicated to aiding individuals impacted by the recent earthquake in Morocco. Our core mission is to streamline and coordinate timely assistance for everyone affected. How do we achieve this? We assist those in need by allowing them to communicate their location and the specific aid they require, either by completing a form or sending a voice message via WhatsApp to the number 0602838166. Once we receive and process this information, it can be viewed in our dashboard, which allows NGOs to organize and precisely target their interventions, ensuring swift assistance reaches those in need. Any organization that has taken initiative in a particular area can notify us by completing a dedicated form. This data is also incorporated into the dashboard so that other NGOs can help affected areas that still haven't received help. -
            ⚠️ Warning : There are still rocks falling down the mountains, making the roads to the affected areas very dangerous. We advise volunteers to donate directly to specialized NGOs.
            -
            - ✉️ You can contact us via email at nt3awnoumorocco@gmail.com or via Instagram @nt3awnou_morocco
            - 📝 Help us report more people in need by filling this form https://forms.gle/nZNCUVog9ka2Vdqu6
            - 📝 NGOs can report their interventions by filling this form https://forms.gle/PsNSuHHjTTgwQMmVA
            - ❗️ Our team is working day and night to verify the data. Please reach out to us if you can help us verify the data. -
            -
            - """ - -INTRO_TEXT_AR = """ -
            - - نتعاونو هي منصة تعاونية غير ربحية لمساعدة الأفراد المتضررين من الزلزال الأخير في المغرب. مهمتنا هي تسهيل تقديم المساعدة في الوقت المناسب و بفاعلية و تنظيم لجميع المتضررين. كيفاش؟ كنعاونو الناس لي محتاجين للمساعدة إعلمونا بمكانهم و نوع المساعدة لي محتاجين ليها سواء عن طريق ملأ الاستمارة أو عن طريق إرسال تسجيل صوتي عبر واتساب إلى رقم مخصص0602838166. بعد معالجة هاد المعلومات، كنجمعوهم فخريطة كتمكن الجمعيات من تنظيم و استهداف تدخلاتهم بدقة باش توصل المساعدة للناس لي محتاجين في وقت أسرع. و كل جمعية قامت باللازم في منطقة معينة تقدر تعلمنا عن طريق ملأ استمارة مخصصة لهاد الأمر. هاد المعلومات كذلك كتضاف للخريطة باش باقي الجمعيات يتاجهو لمناطق أخرى مازال ماوصلاتهم مساعدة. -
            تحذير : نظرا لخطورة الطرقان بسبب الحجر اللي كيطيح من الجبال، ننصح المتطوعين اللي بغاو يساعدو المناطق المتضررة يتبرعو عن طريق الجمعيات المختصة⚠️ -
            -
            - nt3awnoumorocco@gmail.com المتطوعين ليبغاو يعاونوا يقدرو يتصلوا معنا عبر البريد ✉️ -
            - @nt3awnou_morocco أو عبر الانستغرام - https://forms.gle/nZNCUVog9ka2Vdqu6 : ساعدونا نبلغو الناس ليمحتاجين فهاد الاستمارة 📝
            - https://forms.gle/PsNSuHHjTTgwQMmVA : الجمعيات لي عندهم تدخلات يقدرو يبلغونا عبر هاد الاستمار ة📝
            - فريقنا يعمل ليلا نهارا للتحقق من البيانات. يرجى التواصل معنا إذا كنت تستطيع مساعدتنا في التحقق من البيانات❗️ -
            -
            - """ - -INTRO_TEXT_FR = """ -
            - Nt3awnou نتعاونو est une plateforme collaborative à but non-lucratif dédiée à l'aide aux personnes touchées par le récent tremblement de terre au Maroc. Notre mission principale est de rationaliser et de coordonner une assistance rapide pour toutes les personnes touchées. Comment y parvenons-nous ? Nous aidons les personnes dans le besoin en leur permettant de communiquer leur localisation et l'aide spécifique dont elles ont besoin, soit en remplissant un formulaire, soit en envoyant un message vocal via WhatsApp à un numéro 0602838166. Une fois reçues et traitées, ces informations peuvent être consultées dans notre tableau de bord, qui permet aux associations d'organiser et de cibler précisément leurs interventions, afin que l'aide parvienne rapidement à ceux qui en ont besoin. Toute organisation ayant pris une initiative dans une zone particulière peut nous en informer en remplissant un formulaire prévu à cet effet. Ces données sont également intégrées au tableau de bord afin que d'autres associations puissent aider les zones touchées qui n'ont pas encore reçu d'aide. -
            ⚠️ Avertissement : Il y a encore des chutes de pierres dans les montagnes, ce qui rend les routes vers les zones touchées très dangereuses. Nous conseillons aux volontaires de faire des dons directement aux associations spécialisées. -
            -
            - ✉️ Vous pouvez nous contacter par courrier électronique à l'adresse suivante nt3awnoumorocco@gmail.com ou via Instagram @nt3awnou_morocco
            - 📝 Aidez-nous à signaler plus de personnes dans le besoin en remplissant ce formulaire : https://forms.gle/nZNCUVog9ka2Vdqu6
            - 📝 Les associations peuvent signaler leurs interventions en remplissant ce formulaire : https://forms.gle/PsNSuHHjTTgwQMmVA
            - ❗️Notre équipe travaille jour et nuit pour vérifier les données. Veuillez nous contacter si vous pouvez nous aider à vérifier les données. -
            -
            - """ - -SLOGAN = """ -
            -

            وَمَنْ أَحْيَاهَا فَكَأَنَّمَا أَحْيَا النَّاسَ جَمِيعاً

            -
            - """ - - -CREDITS_TEXT = """ -
            -
            -

            By Moroccans for Moroccans 🤝

            -

            Reach out to us at nt3awnoumorocco@gmail.com

            - """ - -LOGO = """ - -
            -
            - Nt3awnou logo -
            - -
            - - # """ - -REVIEW_TEXT = """**If a request should be reviewed or dropped submit its id here/ إذا كان يجب مراجعة أو حذف طلب، أدخل رقمه هنا:**""" diff --git a/spaces/omkar001/gradiolangchainchatbot/README.md b/spaces/omkar001/gradiolangchainchatbot/README.md deleted file mode 100644 index 26a2293fe2aa5a417e186fd0e7d70ccbf6ea3301..0000000000000000000000000000000000000000 --- a/spaces/omkar001/gradiolangchainchatbot/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Gradiolangchainchatbot -emoji: 🐠 -colorFrom: green -colorTo: purple -sdk: gradio -sdk_version: 3.39.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/onnx/ArcFace/README.md b/spaces/onnx/ArcFace/README.md deleted file mode 100644 index 265d03e1dfc0df3e34d108ed5d70ea8c3861ba78..0000000000000000000000000000000000000000 --- a/spaces/onnx/ArcFace/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: ArcFace -emoji: 😻 -colorFrom: green -colorTo: yellow -sdk: gradio -sdk_version: 2.8.10 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference diff --git a/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/docs/source/en/tutorials/basic_training.md b/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/docs/source/en/tutorials/basic_training.md deleted file mode 100644 index c97447e54bc1252d59af0d11ff58288590937dd1..0000000000000000000000000000000000000000 --- a/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/docs/source/en/tutorials/basic_training.md +++ /dev/null @@ -1,409 +0,0 @@ - - -[[open-in-colab]] - -# Train a diffusion model - -Unconditional image generation is a popular application of diffusion models that generates images that look like those in the dataset used for training. Typically, the best results are obtained from finetuning a pretrained model on a specific dataset. You can find many of these checkpoints on the [Hub](https://huggingface.co/search/full-text?q=unconditional-image-generation&type=model), but if you can't find one you like, you can always train your own! - -This tutorial will teach you how to train a [`UNet2DModel`] from scratch on a subset of the [Smithsonian Butterflies](https://huggingface.co/datasets/huggan/smithsonian_butterflies_subset) dataset to generate your own 🦋 butterflies 🦋. - - - -💡 This training tutorial is based on the [Training with 🧨 Diffusers](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/training_example.ipynb) notebook. For additional details and context about diffusion models like how they work, check out the notebook! - - - -Before you begin, make sure you have 🤗 Datasets installed to load and preprocess image datasets, and 🤗 Accelerate, to simplify training on any number of GPUs. The following command will also install [TensorBoard](https://www.tensorflow.org/tensorboard) to visualize training metrics (you can also use [Weights & Biases](https://docs.wandb.ai/) to track your training). - -```py -# uncomment to install the necessary libraries in Colab -#!pip install diffusers[training] -``` - -We encourage you to share your model with the community, and in order to do that, you'll need to login to your Hugging Face account (create one [here](https://hf.co/join) if you don't already have one!). You can login from a notebook and enter your token when prompted: - -```py ->>> from huggingface_hub import notebook_login - ->>> notebook_login() -``` - -Or login in from the terminal: - -```bash -huggingface-cli login -``` - -Since the model checkpoints are quite large, install [Git-LFS](https://git-lfs.com/) to version these large files: - -```bash -!sudo apt -qq install git-lfs -!git config --global credential.helper store -``` - -## Training configuration - -For convenience, create a `TrainingConfig` class containing the training hyperparameters (feel free to adjust them): - -```py ->>> from dataclasses import dataclass - - ->>> @dataclass -... class TrainingConfig: -... image_size = 128 # the generated image resolution -... train_batch_size = 16 -... eval_batch_size = 16 # how many images to sample during evaluation -... num_epochs = 50 -... gradient_accumulation_steps = 1 -... learning_rate = 1e-4 -... lr_warmup_steps = 500 -... save_image_epochs = 10 -... save_model_epochs = 30 -... mixed_precision = "fp16" # `no` for float32, `fp16` for automatic mixed precision -... output_dir = "ddpm-butterflies-128" # the model name locally and on the HF Hub - -... push_to_hub = True # whether to upload the saved model to the HF Hub -... hub_private_repo = False -... overwrite_output_dir = True # overwrite the old model when re-running the notebook -... seed = 0 - - ->>> config = TrainingConfig() -``` - -## Load the dataset - -You can easily load the [Smithsonian Butterflies](https://huggingface.co/datasets/huggan/smithsonian_butterflies_subset) dataset with the 🤗 Datasets library: - -```py ->>> from datasets import load_dataset - ->>> config.dataset_name = "huggan/smithsonian_butterflies_subset" ->>> dataset = load_dataset(config.dataset_name, split="train") -``` - - - -💡 You can find additional datasets from the [HugGan Community Event](https://huggingface.co/huggan) or you can use your own dataset by creating a local [`ImageFolder`](https://huggingface.co/docs/datasets/image_dataset#imagefolder). Set `config.dataset_name` to the repository id of the dataset if it is from the HugGan Community Event, or `imagefolder` if you're using your own images. - - - -🤗 Datasets uses the [`~datasets.Image`] feature to automatically decode the image data and load it as a [`PIL.Image`](https://pillow.readthedocs.io/en/stable/reference/Image.html) which we can visualize: - -```py ->>> import matplotlib.pyplot as plt - ->>> fig, axs = plt.subplots(1, 4, figsize=(16, 4)) ->>> for i, image in enumerate(dataset[:4]["image"]): -... axs[i].imshow(image) -... axs[i].set_axis_off() ->>> fig.show() -``` - -
            - -
            - -The images are all different sizes though, so you'll need to preprocess them first: - -* `Resize` changes the image size to the one defined in `config.image_size`. -* `RandomHorizontalFlip` augments the dataset by randomly mirroring the images. -* `Normalize` is important to rescale the pixel values into a [-1, 1] range, which is what the model expects. - -```py ->>> from torchvision import transforms - ->>> preprocess = transforms.Compose( -... [ -... transforms.Resize((config.image_size, config.image_size)), -... transforms.RandomHorizontalFlip(), -... transforms.ToTensor(), -... transforms.Normalize([0.5], [0.5]), -... ] -... ) -``` - -Use 🤗 Datasets' [`~datasets.Dataset.set_transform`] method to apply the `preprocess` function on the fly during training: - -```py ->>> def transform(examples): -... images = [preprocess(image.convert("RGB")) for image in examples["image"]] -... return {"images": images} - - ->>> dataset.set_transform(transform) -``` - -Feel free to visualize the images again to confirm that they've been resized. Now you're ready to wrap the dataset in a [DataLoader](https://pytorch.org/docs/stable/data#torch.utils.data.DataLoader) for training! - -```py ->>> import torch - ->>> train_dataloader = torch.utils.data.DataLoader(dataset, batch_size=config.train_batch_size, shuffle=True) -``` - -## Create a UNet2DModel - -Pretrained models in 🧨 Diffusers are easily created from their model class with the parameters you want. For example, to create a [`UNet2DModel`]: - -```py ->>> from diffusers import UNet2DModel - ->>> model = UNet2DModel( -... sample_size=config.image_size, # the target image resolution -... in_channels=3, # the number of input channels, 3 for RGB images -... out_channels=3, # the number of output channels -... layers_per_block=2, # how many ResNet layers to use per UNet block -... block_out_channels=(128, 128, 256, 256, 512, 512), # the number of output channels for each UNet block -... down_block_types=( -... "DownBlock2D", # a regular ResNet downsampling block -... "DownBlock2D", -... "DownBlock2D", -... "DownBlock2D", -... "AttnDownBlock2D", # a ResNet downsampling block with spatial self-attention -... "DownBlock2D", -... ), -... up_block_types=( -... "UpBlock2D", # a regular ResNet upsampling block -... "AttnUpBlock2D", # a ResNet upsampling block with spatial self-attention -... "UpBlock2D", -... "UpBlock2D", -... "UpBlock2D", -... "UpBlock2D", -... ), -... ) -``` - -It is often a good idea to quickly check the sample image shape matches the model output shape: - -```py ->>> sample_image = dataset[0]["images"].unsqueeze(0) ->>> print("Input shape:", sample_image.shape) -Input shape: torch.Size([1, 3, 128, 128]) - ->>> print("Output shape:", model(sample_image, timestep=0).sample.shape) -Output shape: torch.Size([1, 3, 128, 128]) -``` - -Great! Next, you'll need a scheduler to add some noise to the image. - -## Create a scheduler - -The scheduler behaves differently depending on whether you're using the model for training or inference. During inference, the scheduler generates image from the noise. During training, the scheduler takes a model output - or a sample - from a specific point in the diffusion process and applies noise to the image according to a *noise schedule* and an *update rule*. - -Let's take a look at the [`DDPMScheduler`] and use the `add_noise` method to add some random noise to the `sample_image` from before: - -```py ->>> import torch ->>> from PIL import Image ->>> from diffusers import DDPMScheduler - ->>> noise_scheduler = DDPMScheduler(num_train_timesteps=1000) ->>> noise = torch.randn(sample_image.shape) ->>> timesteps = torch.LongTensor([50]) ->>> noisy_image = noise_scheduler.add_noise(sample_image, noise, timesteps) - ->>> Image.fromarray(((noisy_image.permute(0, 2, 3, 1) + 1.0) * 127.5).type(torch.uint8).numpy()[0]) -``` - -
            - -
            - -The training objective of the model is to predict the noise added to the image. The loss at this step can be calculated by: - -```py ->>> import torch.nn.functional as F - ->>> noise_pred = model(noisy_image, timesteps).sample ->>> loss = F.mse_loss(noise_pred, noise) -``` - -## Train the model - -By now, you have most of the pieces to start training the model and all that's left is putting everything together. - -First, you'll need an optimizer and a learning rate scheduler: - -```py ->>> from diffusers.optimization import get_cosine_schedule_with_warmup - ->>> optimizer = torch.optim.AdamW(model.parameters(), lr=config.learning_rate) ->>> lr_scheduler = get_cosine_schedule_with_warmup( -... optimizer=optimizer, -... num_warmup_steps=config.lr_warmup_steps, -... num_training_steps=(len(train_dataloader) * config.num_epochs), -... ) -``` - -Then, you'll need a way to evaluate the model. For evaluation, you can use the [`DDPMPipeline`] to generate a batch of sample images and save it as a grid: - -```py ->>> from diffusers import DDPMPipeline ->>> from diffusers.utils import make_image_grid ->>> import math ->>> import os - - ->>> def evaluate(config, epoch, pipeline): -... # Sample some images from random noise (this is the backward diffusion process). -... # The default pipeline output type is `List[PIL.Image]` -... images = pipeline( -... batch_size=config.eval_batch_size, -... generator=torch.manual_seed(config.seed), -... ).images - -... # Make a grid out of the images -... image_grid = make_image_grid(images, rows=4, cols=4) - -... # Save the images -... test_dir = os.path.join(config.output_dir, "samples") -... os.makedirs(test_dir, exist_ok=True) -... image_grid.save(f"{test_dir}/{epoch:04d}.png") -``` - -Now you can wrap all these components together in a training loop with 🤗 Accelerate for easy TensorBoard logging, gradient accumulation, and mixed precision training. To upload the model to the Hub, write a function to get your repository name and information and then push it to the Hub. - - - -💡 The training loop below may look intimidating and long, but it'll be worth it later when you launch your training in just one line of code! If you can't wait and want to start generating images, feel free to copy and run the code below. You can always come back and examine the training loop more closely later, like when you're waiting for your model to finish training. 🤗 - - - -```py ->>> from accelerate import Accelerator ->>> from huggingface_hub import HfFolder, Repository, whoami ->>> from tqdm.auto import tqdm ->>> from pathlib import Path ->>> import os - - ->>> def get_full_repo_name(model_id: str, organization: str = None, token: str = None): -... if token is None: -... token = HfFolder.get_token() -... if organization is None: -... username = whoami(token)["name"] -... return f"{username}/{model_id}" -... else: -... return f"{organization}/{model_id}" - - ->>> def train_loop(config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler): -... # Initialize accelerator and tensorboard logging -... accelerator = Accelerator( -... mixed_precision=config.mixed_precision, -... gradient_accumulation_steps=config.gradient_accumulation_steps, -... log_with="tensorboard", -... project_dir=os.path.join(config.output_dir, "logs"), -... ) -... if accelerator.is_main_process: -... if config.push_to_hub: -... repo_name = get_full_repo_name(Path(config.output_dir).name) -... repo = Repository(config.output_dir, clone_from=repo_name) -... elif config.output_dir is not None: -... os.makedirs(config.output_dir, exist_ok=True) -... accelerator.init_trackers("train_example") - -... # Prepare everything -... # There is no specific order to remember, you just need to unpack the -... # objects in the same order you gave them to the prepare method. -... model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare( -... model, optimizer, train_dataloader, lr_scheduler -... ) - -... global_step = 0 - -... # Now you train the model -... for epoch in range(config.num_epochs): -... progress_bar = tqdm(total=len(train_dataloader), disable=not accelerator.is_local_main_process) -... progress_bar.set_description(f"Epoch {epoch}") - -... for step, batch in enumerate(train_dataloader): -... clean_images = batch["images"] -... # Sample noise to add to the images -... noise = torch.randn(clean_images.shape).to(clean_images.device) -... bs = clean_images.shape[0] - -... # Sample a random timestep for each image -... timesteps = torch.randint( -... 0, noise_scheduler.config.num_train_timesteps, (bs,), device=clean_images.device -... ).long() - -... # Add noise to the clean images according to the noise magnitude at each timestep -... # (this is the forward diffusion process) -... noisy_images = noise_scheduler.add_noise(clean_images, noise, timesteps) - -... with accelerator.accumulate(model): -... # Predict the noise residual -... noise_pred = model(noisy_images, timesteps, return_dict=False)[0] -... loss = F.mse_loss(noise_pred, noise) -... accelerator.backward(loss) - -... accelerator.clip_grad_norm_(model.parameters(), 1.0) -... optimizer.step() -... lr_scheduler.step() -... optimizer.zero_grad() - -... progress_bar.update(1) -... logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0], "step": global_step} -... progress_bar.set_postfix(**logs) -... accelerator.log(logs, step=global_step) -... global_step += 1 - -... # After each epoch you optionally sample some demo images with evaluate() and save the model -... if accelerator.is_main_process: -... pipeline = DDPMPipeline(unet=accelerator.unwrap_model(model), scheduler=noise_scheduler) - -... if (epoch + 1) % config.save_image_epochs == 0 or epoch == config.num_epochs - 1: -... evaluate(config, epoch, pipeline) - -... if (epoch + 1) % config.save_model_epochs == 0 or epoch == config.num_epochs - 1: -... if config.push_to_hub: -... repo.push_to_hub(commit_message=f"Epoch {epoch}", blocking=True) -... else: -... pipeline.save_pretrained(config.output_dir) -``` - -Phew, that was quite a bit of code! But you're finally ready to launch the training with 🤗 Accelerate's [`~accelerate.notebook_launcher`] function. Pass the function the training loop, all the training arguments, and the number of processes (you can change this value to the number of GPUs available to you) to use for training: - -```py ->>> from accelerate import notebook_launcher - ->>> args = (config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler) - ->>> notebook_launcher(train_loop, args, num_processes=1) -``` - -Once training is complete, take a look at the final 🦋 images 🦋 generated by your diffusion model! - -```py ->>> import glob - ->>> sample_images = sorted(glob.glob(f"{config.output_dir}/samples/*.png")) ->>> Image.open(sample_images[-1]) -``` - -
            - -
            - -## Next steps - -Unconditional image generation is one example of a task that can be trained. You can explore other tasks and training techniques by visiting the [🧨 Diffusers Training Examples](../training/overview) page. Here are some examples of what you can learn: - -* [Textual Inversion](../training/text_inversion), an algorithm that teaches a model a specific visual concept and integrates it into the generated image. -* [DreamBooth](../training/dreambooth), a technique for generating personalized images of a subject given several input images of the subject. -* [Guide](../training/text2image) to finetuning a Stable Diffusion model on your own dataset. -* [Guide](../training/lora) to using LoRA, a memory-efficient technique for finetuning really large models faster. diff --git a/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/src/diffusers/commands/__init__.py b/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/src/diffusers/commands/__init__.py deleted file mode 100644 index 4ad4af9199bbe297dbc6679fd9ecb46baa976053..0000000000000000000000000000000000000000 --- a/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/src/diffusers/commands/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright 2023 The HuggingFace Team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from abc import ABC, abstractmethod -from argparse import ArgumentParser - - -class BaseDiffusersCLICommand(ABC): - @staticmethod - @abstractmethod - def register_subcommand(parser: ArgumentParser): - raise NotImplementedError() - - @abstractmethod - def run(self): - raise NotImplementedError() diff --git a/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/src/diffusers/pipelines/README.md b/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/src/diffusers/pipelines/README.md deleted file mode 100644 index 7562040596e9028ed56431817f42f4379ecf3435..0000000000000000000000000000000000000000 --- a/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/src/diffusers/pipelines/README.md +++ /dev/null @@ -1,171 +0,0 @@ -# 🧨 Diffusers Pipelines - -Pipelines provide a simple way to run state-of-the-art diffusion models in inference. -Most diffusion systems consist of multiple independently-trained models and highly adaptable scheduler -components - all of which are needed to have a functioning end-to-end diffusion system. - -As an example, [Stable Diffusion](https://huggingface.co/blog/stable_diffusion) has three independently trained models: -- [Autoencoder](https://github.com/huggingface/diffusers/blob/5cbed8e0d157f65d3ddc2420dfd09f2df630e978/src/diffusers/models/vae.py#L392) -- [Conditional Unet](https://github.com/huggingface/diffusers/blob/5cbed8e0d157f65d3ddc2420dfd09f2df630e978/src/diffusers/models/unet_2d_condition.py#L12) -- [CLIP text encoder](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTextModel) -- a scheduler component, [scheduler](https://github.com/huggingface/diffusers/blob/main/src/diffusers/schedulers/scheduling_pndm.py), -- a [CLIPImageProcessor](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPImageProcessor), -- as well as a [safety checker](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/safety_checker.py). -All of these components are necessary to run stable diffusion in inference even though they were trained -or created independently from each other. - -To that end, we strive to offer all open-sourced, state-of-the-art diffusion system under a unified API. -More specifically, we strive to provide pipelines that -- 1. can load the officially published weights and yield 1-to-1 the same outputs as the original implementation according to the corresponding paper (*e.g.* [LDMTextToImagePipeline](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines/latent_diffusion), uses the officially released weights of [High-Resolution Image Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752)), -- 2. have a simple user interface to run the model in inference (see the [Pipelines API](#pipelines-api) section), -- 3. are easy to understand with code that is self-explanatory and can be read along-side the official paper (see [Pipelines summary](#pipelines-summary)), -- 4. can easily be contributed by the community (see the [Contribution](#contribution) section). - -**Note** that pipelines do not (and should not) offer any training functionality. -If you are looking for *official* training examples, please have a look at [examples](https://github.com/huggingface/diffusers/tree/main/examples). - - -## Pipelines Summary - -The following table summarizes all officially supported pipelines, their corresponding paper, and if -available a colab notebook to directly try them out. - -| Pipeline | Source | Tasks | Colab -|-------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------|:---:|:---:| -| [dance diffusion](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/dance_diffusion) | [**Dance Diffusion**](https://github.com/Harmonai-org/sample-generator) | *Unconditional Audio Generation* | -| [ddpm](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ddpm) | [**Denoising Diffusion Probabilistic Models**](https://arxiv.org/abs/2006.11239) | *Unconditional Image Generation* | -| [ddim](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ddim) | [**Denoising Diffusion Implicit Models**](https://arxiv.org/abs/2010.02502) | *Unconditional Image Generation* | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/training_example.ipynb) -| [latent_diffusion](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/latent_diffusion) | [**High-Resolution Image Synthesis with Latent Diffusion Models**](https://arxiv.org/abs/2112.10752) | *Text-to-Image Generation* | -| [latent_diffusion_uncond](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/latent_diffusion_uncond) | [**High-Resolution Image Synthesis with Latent Diffusion Models**](https://arxiv.org/abs/2112.10752) | *Unconditional Image Generation* | -| [pndm](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pndm) | [**Pseudo Numerical Methods for Diffusion Models on Manifolds**](https://arxiv.org/abs/2202.09778) | *Unconditional Image Generation* | -| [score_sde_ve](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/score_sde_ve) | [**Score-Based Generative Modeling through Stochastic Differential Equations**](https://openreview.net/forum?id=PxTIG12RRHS) | *Unconditional Image Generation* | -| [score_sde_vp](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/score_sde_vp) | [**Score-Based Generative Modeling through Stochastic Differential Equations**](https://openreview.net/forum?id=PxTIG12RRHS) | *Unconditional Image Generation* | -| [stable_diffusion](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion) | [**Stable Diffusion**](https://stability.ai/blog/stable-diffusion-public-release) | *Text-to-Image Generation* | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/stable_diffusion.ipynb) -| [stable_diffusion](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion) | [**Stable Diffusion**](https://stability.ai/blog/stable-diffusion-public-release) | *Image-to-Image Text-Guided Generation* | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/image_2_image_using_diffusers.ipynb) -| [stable_diffusion](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion) | [**Stable Diffusion**](https://stability.ai/blog/stable-diffusion-public-release) | *Text-Guided Image Inpainting* | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/in_painting_with_stable_diffusion_using_diffusers.ipynb) -| [stochastic_karras_ve](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stochastic_karras_ve) | [**Elucidating the Design Space of Diffusion-Based Generative Models**](https://arxiv.org/abs/2206.00364) | *Unconditional Image Generation* | - -**Note**: Pipelines are simple examples of how to play around with the diffusion systems as described in the corresponding papers. -However, most of them can be adapted to use different scheduler components or even different model components. Some pipeline examples are shown in the [Examples](#examples) below. - -## Pipelines API - -Diffusion models often consist of multiple independently-trained models or other previously existing components. - - -Each model has been trained independently on a different task and the scheduler can easily be swapped out and replaced with a different one. -During inference, we however want to be able to easily load all components and use them in inference - even if one component, *e.g.* CLIP's text encoder, originates from a different library, such as [Transformers](https://github.com/huggingface/transformers). To that end, all pipelines provide the following functionality: - -- [`from_pretrained` method](https://github.com/huggingface/diffusers/blob/5cbed8e0d157f65d3ddc2420dfd09f2df630e978/src/diffusers/pipeline_utils.py#L139) that accepts a Hugging Face Hub repository id, *e.g.* [runwayml/stable-diffusion-v1-5](https://huggingface.co/runwayml/stable-diffusion-v1-5) or a path to a local directory, *e.g.* -"./stable-diffusion". To correctly retrieve which models and components should be loaded, one has to provide a `model_index.json` file, *e.g.* [runwayml/stable-diffusion-v1-5/model_index.json](https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/model_index.json), which defines all components that should be -loaded into the pipelines. More specifically, for each model/component one needs to define the format `: ["", ""]`. `` is the attribute name given to the loaded instance of `` which can be found in the library or pipeline folder called `""`. -- [`save_pretrained`](https://github.com/huggingface/diffusers/blob/5cbed8e0d157f65d3ddc2420dfd09f2df630e978/src/diffusers/pipeline_utils.py#L90) that accepts a local path, *e.g.* `./stable-diffusion` under which all models/components of the pipeline will be saved. For each component/model a folder is created inside the local path that is named after the given attribute name, *e.g.* `./stable_diffusion/unet`. -In addition, a `model_index.json` file is created at the root of the local path, *e.g.* `./stable_diffusion/model_index.json` so that the complete pipeline can again be instantiated -from the local path. -- [`to`](https://github.com/huggingface/diffusers/blob/5cbed8e0d157f65d3ddc2420dfd09f2df630e978/src/diffusers/pipeline_utils.py#L118) which accepts a `string` or `torch.device` to move all models that are of type `torch.nn.Module` to the passed device. The behavior is fully analogous to [PyTorch's `to` method](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.to). -- [`__call__`] method to use the pipeline in inference. `__call__` defines inference logic of the pipeline and should ideally encompass all aspects of it, from pre-processing to forwarding tensors to the different models and schedulers, as well as post-processing. The API of the `__call__` method can strongly vary from pipeline to pipeline. *E.g.* a text-to-image pipeline, such as [`StableDiffusionPipeline`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py) should accept among other things the text prompt to generate the image. A pure image generation pipeline, such as [DDPMPipeline](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines/ddpm) on the other hand can be run without providing any inputs. To better understand what inputs can be adapted for -each pipeline, one should look directly into the respective pipeline. - -**Note**: All pipelines have PyTorch's autograd disabled by decorating the `__call__` method with a [`torch.no_grad`](https://pytorch.org/docs/stable/generated/torch.no_grad.html) decorator because pipelines should -not be used for training. If you want to store the gradients during the forward pass, we recommend writing your own pipeline, see also our [community-examples](https://github.com/huggingface/diffusers/tree/main/examples/community) - -## Contribution - -We are more than happy about any contribution to the officially supported pipelines 🤗. We aspire -all of our pipelines to be **self-contained**, **easy-to-tweak**, **beginner-friendly** and for **one-purpose-only**. - -- **Self-contained**: A pipeline shall be as self-contained as possible. More specifically, this means that all functionality should be either directly defined in the pipeline file itself, should be inherited from (and only from) the [`DiffusionPipeline` class](https://github.com/huggingface/diffusers/blob/5cbed8e0d157f65d3ddc2420dfd09f2df630e978/src/diffusers/pipeline_utils.py#L56) or be directly attached to the model and scheduler components of the pipeline. -- **Easy-to-use**: Pipelines should be extremely easy to use - one should be able to load the pipeline and -use it for its designated task, *e.g.* text-to-image generation, in just a couple of lines of code. Most -logic including pre-processing, an unrolled diffusion loop, and post-processing should all happen inside the `__call__` method. -- **Easy-to-tweak**: Certain pipelines will not be able to handle all use cases and tasks that you might like them to. If you want to use a certain pipeline for a specific use case that is not yet supported, you might have to copy the pipeline file and tweak the code to your needs. We try to make the pipeline code as readable as possible so that each part –from pre-processing to diffusing to post-processing– can easily be adapted. If you would like the community to benefit from your customized pipeline, we would love to see a contribution to our [community-examples](https://github.com/huggingface/diffusers/tree/main/examples/community). If you feel that an important pipeline should be part of the official pipelines but isn't, a contribution to the [official pipelines](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines) would be even better. -- **One-purpose-only**: Pipelines should be used for one task and one task only. Even if two tasks are very similar from a modeling point of view, *e.g.* image2image translation and in-painting, pipelines shall be used for one task only to keep them *easy-to-tweak* and *readable*. - -## Examples - -### Text-to-Image generation with Stable Diffusion - -```python -# make sure you're logged in with `huggingface-cli login` -from diffusers import StableDiffusionPipeline, LMSDiscreteScheduler - -pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") -pipe = pipe.to("cuda") - -prompt = "a photo of an astronaut riding a horse on mars" -image = pipe(prompt).images[0] - -image.save("astronaut_rides_horse.png") -``` - -### Image-to-Image text-guided generation with Stable Diffusion - -The `StableDiffusionImg2ImgPipeline` lets you pass a text prompt and an initial image to condition the generation of new images. - -```python -import requests -from PIL import Image -from io import BytesIO - -from diffusers import StableDiffusionImg2ImgPipeline - -# load the pipeline -device = "cuda" -pipe = StableDiffusionImg2ImgPipeline.from_pretrained( - "runwayml/stable-diffusion-v1-5", - torch_dtype=torch.float16, -).to(device) - -# let's download an initial image -url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg" - -response = requests.get(url) -init_image = Image.open(BytesIO(response.content)).convert("RGB") -init_image = init_image.resize((768, 512)) - -prompt = "A fantasy landscape, trending on artstation" - -images = pipe(prompt=prompt, image=init_image, strength=0.75, guidance_scale=7.5).images - -images[0].save("fantasy_landscape.png") -``` -You can also run this example on colab [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/image_2_image_using_diffusers.ipynb) - -### Tweak prompts reusing seeds and latents - -You can generate your own latents to reproduce results, or tweak your prompt on a specific result you liked. [This notebook](https://github.com/pcuenca/diffusers-examples/blob/main/notebooks/stable-diffusion-seeds.ipynb) shows how to do it step by step. You can also run it in Google Colab [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pcuenca/diffusers-examples/blob/main/notebooks/stable-diffusion-seeds.ipynb). - - -### In-painting using Stable Diffusion - -The `StableDiffusionInpaintPipeline` lets you edit specific parts of an image by providing a mask and text prompt. - -```python -import PIL -import requests -import torch -from io import BytesIO - -from diffusers import StableDiffusionInpaintPipeline - -def download_image(url): - response = requests.get(url) - return PIL.Image.open(BytesIO(response.content)).convert("RGB") - -img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png" -mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png" - -init_image = download_image(img_url).resize((512, 512)) -mask_image = download_image(mask_url).resize((512, 512)) - -pipe = StableDiffusionInpaintPipeline.from_pretrained( - "runwayml/stable-diffusion-inpainting", - torch_dtype=torch.float16, -) -pipe = pipe.to("cuda") - -prompt = "Face of a yellow cat, high resolution, sitting on a park bench" -image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0] -``` - -You can also run this example on colab [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/in_painting_with_stable_diffusion_using_diffusers.ipynb) diff --git a/spaces/passaglia/yomikata-demo/app.py b/spaces/passaglia/yomikata-demo/app.py deleted file mode 100644 index 31512b2166b0a937a05f98fa6ab9335cba8cb13a..0000000000000000000000000000000000000000 --- a/spaces/passaglia/yomikata-demo/app.py +++ /dev/null @@ -1,209 +0,0 @@ -"""app.py -streamlit demo of yomikata""" -from pathlib import Path - -import pandas as pd -import spacy -import streamlit as st -from speach import ttlig - -from yomikata import utils -from yomikata.dictionary import Dictionary -from yomikata.utils import parse_furigana - - -@st.cache -def add_border(html: str): - WRAPPER = """
            {}
            """ - html = html.replace("\n", " ") - return WRAPPER.format(html) - - -def get_random_sentence(): - from config.config import TEST_DATA_DIR - - df = pd.read_csv(Path(TEST_DATA_DIR, "test_optimized_strict_heteronyms.csv")) - return df.sample(1).iloc[0].sentence - - -@st.cache -def get_dbert_prediction_and_heteronym_list(text): - from yomikata.dbert import dBert - - reader = dBert() - return reader.furigana(text), reader.heteronyms - - -@st.cache -def get_stats(): - from config import config - from yomikata.utils import load_dict - - stats = load_dict(Path(config.STORES_DIR, "dbert/training_performance.json")) - - global_accuracy = stats["test"]["accuracy"] - - stats = stats["test"]["heteronym_performance"] - heteronyms = stats.keys() - - accuracy = [stats[heteronym]["accuracy"] for heteronym in heteronyms] - - readings = [ - "、".join( - [ - "{reading} ({correct}/{n})".format( - reading=reading, - correct=stats[heteronym]["readings"][reading]["found"][reading], - n=stats[heteronym]["readings"][reading]["n"], - ) - for reading in stats[heteronym]["readings"].keys() - if ( - stats[heteronym]["readings"][reading]["found"][reading] != 0 - or reading != "" - ) - ] - ) - for heteronym in heteronyms - ] - - # if reading != '' - - df = pd.DataFrame( - {"heteronym": heteronyms, "accuracy": accuracy, "readings": readings} - ) - - df = df[df["readings"].str.contains("、")] - - df["readings"] = df["readings"].str.replace("", "Other") - - df = df.rename(columns={"readings": "readings (correct/total)"}) - - df = df.sort_values("accuracy", ascending=False, ignore_index=True) - - df.index += 1 - - return global_accuracy, df - - -@st.cache -def furigana_to_spacy(text_with_furigana): - tokens = parse_furigana(text_with_furigana) - ents = [] - output_text = "" - heteronym_count = 0 - for token in tokens.groups: - if isinstance(token, ttlig.RubyFrag): - if heteronym_count != 0: - output_text += ", " - - ents.append( - { - "start": len(output_text), - "end": len(output_text) + len(token.text), - "label": token.furi, - } - ) - - output_text += token.text - heteronym_count += 1 - else: - pass - return { - "text": output_text, - "ents": ents, - "title": None, - } - - -st.title("Yomikata: Disambiguate Japanese Heteronyms") - -# Input text box -st.markdown("Input a Japanese sentence:") - -if "default_sentence" not in st.session_state: - st.session_state.default_sentence = "え、{人間/にんげん}というものかい? {人間/にんげん}というものは{角/つの}の{生/は}えない、{生白/なまじろ}い{顔/かお}や{手足/てあし}をした、{何/なん}ともいわれず{気味/きみ}の{悪/わる}いものだよ。" - -input_text = st.text_area( - "Input a Japanese sentence:", - utils.remove_furigana(st.session_state.default_sentence), - label_visibility="collapsed", -) - -# Yomikata prediction -dbert_prediction, heteronyms = get_dbert_prediction_and_heteronym_list(input_text) - -# spacy-style output for the predictions -colors = ["#85DCDF", "#DF85DC", "#DCDF85", "#85ABDF"] -spacy_dict = furigana_to_spacy(dbert_prediction) -label_colors = { - reading: colors[i % len(colors)] - for i, reading in enumerate(set([item["label"] for item in spacy_dict["ents"]])) -} -html = spacy.displacy.render( - spacy_dict, style="ent", manual=True, options={"colors": label_colors} -) - -if len(spacy_dict["ents"]) > 0: - st.markdown( - "**Yomikata** disambiguated the following words with multiple readings:" - ) - st.write( - f"{add_border(html)}", - unsafe_allow_html=True, - ) -else: - st.markdown("**Yomikata** found no heteronyms in the input text.") - -# Dictionary + Yomikata prediction -st.markdown("**Yomikata** can be coupled with a dictionary to get full furigana:") -dictionary = st.radio( - "It can be coupled with a dictionary", - ("sudachi", "unidic", "ipadic", "juman"), - horizontal=True, - label_visibility="collapsed", -) - -dictreader = Dictionary(dictionary) -dictionary_prediction = dictreader.furigana(dbert_prediction) -html = parse_furigana(dictionary_prediction).to_html() -st.write( - f"{add_border(html)}", - unsafe_allow_html=True, -) - -# Dictionary alone prediction -if len(spacy_dict["ents"]) > 0: - dictionary_prediction = dictreader.furigana(utils.remove_furigana(input_text)) - html = parse_furigana(dictionary_prediction).to_html() - st.markdown("Without **Yomikata** disambiguation, the dictionary would yield:") - st.write( - f"{add_border(html)}", - unsafe_allow_html=True, - ) - -# Randomize button -if st.button("🎲 Randomize the input sentence"): - st.session_state.default_sentence = get_random_sentence() - st.experimental_rerun() - -# Stats section -global_accuracy, stats_df = get_stats() - -st.subheader( - f"**Yomikata** supports {len(stats_df)} heteronyms, with a global accuracy of {global_accuracy:.0%}!" -) - -st.dataframe(stats_df) - -st.subheader( - "Check out **Yomikata** on [GitHub](https://github.com/passaglia/yomikata) today!" -) - -# Hide the footer -hide_streamlit_style = """ - - """ -st.markdown(hide_streamlit_style, unsafe_allow_html=True) diff --git a/spaces/philipalden/InvisibleCities/config.py b/spaces/philipalden/InvisibleCities/config.py deleted file mode 100644 index 481e2cb236a8033de0f07790465b2bf4789817c4..0000000000000000000000000000000000000000 --- a/spaces/philipalden/InvisibleCities/config.py +++ /dev/null @@ -1,11 +0,0 @@ -import os -from dotenv import load_dotenv - -# Load environment variables from .env file -load_dotenv() - -class SimpleConfig: - def __init__(self): - self.openai_api_key = os.getenv("OPENAI_API_KEY") - self.pinecone_api_key = os.getenv("PINECONE_API_KEY") - self.pinecone_region = os.getenv("PINECONE_ENV") diff --git a/spaces/phyloforfun/VoucherVision/vouchervision/component_detector/hubconf.py b/spaces/phyloforfun/VoucherVision/vouchervision/component_detector/hubconf.py deleted file mode 100644 index 4e05149026b33192fbd745e1406226827be8c38a..0000000000000000000000000000000000000000 --- a/spaces/phyloforfun/VoucherVision/vouchervision/component_detector/hubconf.py +++ /dev/null @@ -1,146 +0,0 @@ -# YOLOv5 🚀 by Ultralytics, GPL-3.0 license -""" -PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5/ - -Usage: - import torch - model = torch.hub.load('ultralytics/yolov5', 'yolov5s') - model = torch.hub.load('ultralytics/yolov5:master', 'custom', 'path/to/yolov5s.onnx') # file from branch -""" - -import torch - - -def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): - """Creates or loads a YOLOv5 model - - Arguments: - name (str): model name 'yolov5s' or path 'path/to/best.pt' - pretrained (bool): load pretrained weights into the model - channels (int): number of input channels - classes (int): number of model classes - autoshape (bool): apply YOLOv5 .autoshape() wrapper to model - verbose (bool): print all information to screen - device (str, torch.device, None): device to use for model parameters - - Returns: - YOLOv5 model - """ - from pathlib import Path - - from models.common import AutoShape, DetectMultiBackend - from models.yolo import Model - from utils.downloads import attempt_download - from utils.general import LOGGER, check_requirements, intersect_dicts, logging - from utils.torch_utils import select_device - - if not verbose: - LOGGER.setLevel(logging.WARNING) - - check_requirements(exclude=('tensorboard', 'thop', 'opencv-python')) - name = Path(name) - path = name.with_suffix('.pt') if name.suffix == '' else name # checkpoint path - try: - device = select_device(('0' if torch.cuda.is_available() else 'cpu') if device is None else device) - - if pretrained and channels == 3 and classes == 80: - model = DetectMultiBackend(path, device=device) # download/load FP32 model - # model = models.experimental.attempt_load(path, map_location=device) # download/load FP32 model - else: - cfg = list((Path(__file__).parent / 'models').rglob(f'{path.stem}.yaml'))[0] # model.yaml path - model = Model(cfg, channels, classes) # create model - if pretrained: - ckpt = torch.load(attempt_download(path), map_location=device) # load - csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32 - csd = intersect_dicts(csd, model.state_dict(), exclude=['anchors']) # intersect - model.load_state_dict(csd, strict=False) # load - if len(ckpt['model'].names) == classes: - model.names = ckpt['model'].names # set class names attribute - if autoshape: - model = AutoShape(model) # for file/URI/PIL/cv2/np inputs and NMS - return model.to(device) - - except Exception as e: - help_url = 'https://github.com/ultralytics/yolov5/issues/36' - s = f'{e}. Cache may be out of date, try `force_reload=True` or see {help_url} for help.' - raise Exception(s) from e - - -def custom(path='path/to/model.pt', autoshape=True, _verbose=True, device=None): - # YOLOv5 custom or local model - return _create(path, autoshape=autoshape, verbose=_verbose, device=device) - - -def yolov5n(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None): - # YOLOv5-nano model https://github.com/ultralytics/yolov5 - return _create('yolov5n', pretrained, channels, classes, autoshape, _verbose, device) - - -def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None): - # YOLOv5-small model https://github.com/ultralytics/yolov5 - return _create('yolov5s', pretrained, channels, classes, autoshape, _verbose, device) - - -def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None): - # YOLOv5-medium model https://github.com/ultralytics/yolov5 - return _create('yolov5m', pretrained, channels, classes, autoshape, _verbose, device) - - -def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None): - # YOLOv5-large model https://github.com/ultralytics/yolov5 - return _create('yolov5l', pretrained, channels, classes, autoshape, _verbose, device) - - -def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None): - # YOLOv5-xlarge model https://github.com/ultralytics/yolov5 - return _create('yolov5x', pretrained, channels, classes, autoshape, _verbose, device) - - -def yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None): - # YOLOv5-nano-P6 model https://github.com/ultralytics/yolov5 - return _create('yolov5n6', pretrained, channels, classes, autoshape, _verbose, device) - - -def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None): - # YOLOv5-small-P6 model https://github.com/ultralytics/yolov5 - return _create('yolov5s6', pretrained, channels, classes, autoshape, _verbose, device) - - -def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None): - # YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5 - return _create('yolov5m6', pretrained, channels, classes, autoshape, _verbose, device) - - -def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None): - # YOLOv5-large-P6 model https://github.com/ultralytics/yolov5 - return _create('yolov5l6', pretrained, channels, classes, autoshape, _verbose, device) - - -def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None): - # YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5 - return _create('yolov5x6', pretrained, channels, classes, autoshape, _verbose, device) - - -if __name__ == '__main__': - model = _create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True, verbose=True) - # model = custom(path='path/to/model.pt') # custom - - # Verify inference - from pathlib import Path - - import numpy as np - from PIL import Image - - from utils.general import cv2 - - imgs = [ - 'data/images/zidane.jpg', # filename - Path('data/images/zidane.jpg'), # Path - 'https://ultralytics.com/images/zidane.jpg', # URI - cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV - Image.open('data/images/bus.jpg'), # PIL - np.zeros((320, 640, 3))] # numpy - - results = model(imgs, size=320) # batched inference - results.print() - results.save() diff --git a/spaces/pikaduck/DungeonMaster/assets/__init__.py b/spaces/pikaduck/DungeonMaster/assets/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/pknez/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_internal/models/direct_url.py b/spaces/pknez/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_internal/models/direct_url.py deleted file mode 100644 index e219d73849bbbfc556be108fac2ae619042bce1a..0000000000000000000000000000000000000000 --- a/spaces/pknez/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_internal/models/direct_url.py +++ /dev/null @@ -1,237 +0,0 @@ -""" PEP 610 """ -import json -import re -import urllib.parse -from typing import Any, Dict, Iterable, Optional, Type, TypeVar, Union - -__all__ = [ - "DirectUrl", - "DirectUrlValidationError", - "DirInfo", - "ArchiveInfo", - "VcsInfo", -] - -T = TypeVar("T") - -DIRECT_URL_METADATA_NAME = "direct_url.json" -ENV_VAR_RE = re.compile(r"^\$\{[A-Za-z0-9-_]+\}(:\$\{[A-Za-z0-9-_]+\})?$") - - -class DirectUrlValidationError(Exception): - pass - - -def _get( - d: Dict[str, Any], expected_type: Type[T], key: str, default: Optional[T] = None -) -> Optional[T]: - """Get value from dictionary and verify expected type.""" - if key not in d: - return default - value = d[key] - if not isinstance(value, expected_type): - raise DirectUrlValidationError( - "{!r} has unexpected type for {} (expected {})".format( - value, key, expected_type - ) - ) - return value - - -def _get_required( - d: Dict[str, Any], expected_type: Type[T], key: str, default: Optional[T] = None -) -> T: - value = _get(d, expected_type, key, default) - if value is None: - raise DirectUrlValidationError(f"{key} must have a value") - return value - - -def _exactly_one_of(infos: Iterable[Optional["InfoType"]]) -> "InfoType": - infos = [info for info in infos if info is not None] - if not infos: - raise DirectUrlValidationError( - "missing one of archive_info, dir_info, vcs_info" - ) - if len(infos) > 1: - raise DirectUrlValidationError( - "more than one of archive_info, dir_info, vcs_info" - ) - assert infos[0] is not None - return infos[0] - - -def _filter_none(**kwargs: Any) -> Dict[str, Any]: - """Make dict excluding None values.""" - return {k: v for k, v in kwargs.items() if v is not None} - - -class VcsInfo: - name = "vcs_info" - - def __init__( - self, - vcs: str, - commit_id: str, - requested_revision: Optional[str] = None, - ) -> None: - self.vcs = vcs - self.requested_revision = requested_revision - self.commit_id = commit_id - - @classmethod - def _from_dict(cls, d: Optional[Dict[str, Any]]) -> Optional["VcsInfo"]: - if d is None: - return None - return cls( - vcs=_get_required(d, str, "vcs"), - commit_id=_get_required(d, str, "commit_id"), - requested_revision=_get(d, str, "requested_revision"), - ) - - def _to_dict(self) -> Dict[str, Any]: - return _filter_none( - vcs=self.vcs, - requested_revision=self.requested_revision, - commit_id=self.commit_id, - ) - - -class ArchiveInfo: - name = "archive_info" - - def __init__( - self, - hash: Optional[str] = None, - hashes: Optional[Dict[str, str]] = None, - ) -> None: - # set hashes before hash, since the hash setter will further populate hashes - self.hashes = hashes - self.hash = hash - - @property - def hash(self) -> Optional[str]: - return self._hash - - @hash.setter - def hash(self, value: Optional[str]) -> None: - if value is not None: - # Auto-populate the hashes key to upgrade to the new format automatically. - # We don't back-populate the legacy hash key from hashes. - try: - hash_name, hash_value = value.split("=", 1) - except ValueError: - raise DirectUrlValidationError( - f"invalid archive_info.hash format: {value!r}" - ) - if self.hashes is None: - self.hashes = {hash_name: hash_value} - elif hash_name not in self.hashes: - self.hashes = self.hashes.copy() - self.hashes[hash_name] = hash_value - self._hash = value - - @classmethod - def _from_dict(cls, d: Optional[Dict[str, Any]]) -> Optional["ArchiveInfo"]: - if d is None: - return None - return cls(hash=_get(d, str, "hash"), hashes=_get(d, dict, "hashes")) - - def _to_dict(self) -> Dict[str, Any]: - return _filter_none(hash=self.hash, hashes=self.hashes) - - -class DirInfo: - name = "dir_info" - - def __init__( - self, - editable: bool = False, - ) -> None: - self.editable = editable - - @classmethod - def _from_dict(cls, d: Optional[Dict[str, Any]]) -> Optional["DirInfo"]: - if d is None: - return None - return cls(editable=_get_required(d, bool, "editable", default=False)) - - def _to_dict(self) -> Dict[str, Any]: - return _filter_none(editable=self.editable or None) - - -InfoType = Union[ArchiveInfo, DirInfo, VcsInfo] - - -class DirectUrl: - def __init__( - self, - url: str, - info: InfoType, - subdirectory: Optional[str] = None, - ) -> None: - self.url = url - self.info = info - self.subdirectory = subdirectory - - def _remove_auth_from_netloc(self, netloc: str) -> str: - if "@" not in netloc: - return netloc - user_pass, netloc_no_user_pass = netloc.split("@", 1) - if ( - isinstance(self.info, VcsInfo) - and self.info.vcs == "git" - and user_pass == "git" - ): - return netloc - if ENV_VAR_RE.match(user_pass): - return netloc - return netloc_no_user_pass - - @property - def redacted_url(self) -> str: - """url with user:password part removed unless it is formed with - environment variables as specified in PEP 610, or it is ``git`` - in the case of a git URL. - """ - purl = urllib.parse.urlsplit(self.url) - netloc = self._remove_auth_from_netloc(purl.netloc) - surl = urllib.parse.urlunsplit( - (purl.scheme, netloc, purl.path, purl.query, purl.fragment) - ) - return surl - - def validate(self) -> None: - self.from_dict(self.to_dict()) - - @classmethod - def from_dict(cls, d: Dict[str, Any]) -> "DirectUrl": - return DirectUrl( - url=_get_required(d, str, "url"), - subdirectory=_get(d, str, "subdirectory"), - info=_exactly_one_of( - [ - ArchiveInfo._from_dict(_get(d, dict, "archive_info")), - DirInfo._from_dict(_get(d, dict, "dir_info")), - VcsInfo._from_dict(_get(d, dict, "vcs_info")), - ] - ), - ) - - def to_dict(self) -> Dict[str, Any]: - res = _filter_none( - url=self.redacted_url, - subdirectory=self.subdirectory, - ) - res[self.info.name] = self.info._to_dict() - return res - - @classmethod - def from_json(cls, s: str) -> "DirectUrl": - return cls.from_dict(json.loads(s)) - - def to_json(self) -> str: - return json.dumps(self.to_dict(), sort_keys=True) - - def is_local_editable(self) -> bool: - return isinstance(self.info, DirInfo) and self.info.editable diff --git a/spaces/plzdontcry/dakubettergpt/src/components/PopupModal/index.ts b/spaces/plzdontcry/dakubettergpt/src/components/PopupModal/index.ts deleted file mode 100644 index 2f71a63426cc74217da3ba3863fe503d9756cfdc..0000000000000000000000000000000000000000 --- a/spaces/plzdontcry/dakubettergpt/src/components/PopupModal/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { default } from './PopupModal'; diff --git a/spaces/prasanna2003/ChatOPT/app.py b/spaces/prasanna2003/ChatOPT/app.py deleted file mode 100644 index dd2e695e5ad35cd670bf90e20af26eb2ac9f3ad7..0000000000000000000000000000000000000000 --- a/spaces/prasanna2003/ChatOPT/app.py +++ /dev/null @@ -1,73 +0,0 @@ -import gradio as gr -import torch -from transformers import AutoTokenizer - -class Pipline: - def __init__(self, model, tokenizer, device='cpu'): - self.device = device - self.model = model.to(self.device) - self.tokenizer = tokenizer - self.pre_prompt = "\n\nYou are a AI assistant who helps the user to solve their issue\n\n" - - @torch.no_grad() - def respond(self, Instruction=None, input=None, temperature=0.8, max_length=200, do_sample=True, top_k=0, top_p=0.9, repetition_penalty=1.0, num_return_sequences=1, num_beams=1, early_stopping=False, use_cache=True, **generate_kwargs): - if not Instruction and not input: - raise ValueError("Either Instruction or input must be passed.") - query = f"""{self.pre_prompt} -Instruction: {Instruction if Instruction else ""} -Input: {input if input else ""} -Output:""" - inp_tokens_l = self.tokenizer(query, return_tensors='pt').input_ids - inp_tokens = inp_tokens_l.to(self.device) - out_tokens = self.model.generate(inp_tokens, max_length=max_length, temperature=temperature, do_sample=do_sample, top_k=top_k, top_p=top_p, repetition_penalty=repetition_penalty, num_return_sequences=num_return_sequences, num_beams=num_beams, early_stopping=early_stopping, use_cache=use_cache, **generate_kwargs) - out_text = self.tokenizer.batch_decode(out_tokens, skip_special_tokens=True) - # self.pre_prompt = out_text[0].split("<|endoftext|>")[0] - return out_text - -tokenizer = AutoTokenizer.from_pretrained("facebook/opt-125M") -model = torch.load('./model-cpu.pkl') - -pipe = Pipline(model=model, tokenizer=tokenizer, device='cpu') - -input_components = [ - gr.inputs.Textbox(label='Instruction', placeholder='Enter instruction...'), - gr.inputs.Textbox(label='Input', placeholder='Enter input...'), -] - -output_components = [ - gr.outputs.Textbox(label='Output'), -] - -def chatbot_response(Instruction, input, max_length, temperature): - output = pipe.respond( - Instruction=Instruction, - input=input, - max_length=int(max_length), - temperature=float(temperature), - ) - return output[0] - -interface = gr.Interface( - fn=chatbot_response, - inputs=input_components + [ - gr.inputs.Slider( - label='Max Length', - minimum=10, - maximum=500, - step=10, - default=200, - ), - gr.inputs.Slider( - label='Temperature', - minimum=0.1, - maximum=1.0, - step=0.1, - default=0.8, - ), - ], - outputs=output_components, - title='ChatOPT', - description='Type in an instruction and input, and get a response from the model', -) - -interface.launch() diff --git a/spaces/prerna9811/Chord/portaudio/src/common/pa_dither.c b/spaces/prerna9811/Chord/portaudio/src/common/pa_dither.c deleted file mode 100644 index 0d1666a774137169fdca6cc8705e773a27d3c3d1..0000000000000000000000000000000000000000 --- a/spaces/prerna9811/Chord/portaudio/src/common/pa_dither.c +++ /dev/null @@ -1,218 +0,0 @@ -/* - * $Id$ - * Portable Audio I/O Library triangular dither generator - * - * Based on the Open Source API proposed by Ross Bencina - * Copyright (c) 1999-2002 Phil Burk, Ross Bencina - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files - * (the "Software"), to deal in the Software without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -/* - * The text above constitutes the entire PortAudio license; however, - * the PortAudio community also makes the following non-binding requests: - * - * Any person wishing to distribute modifications to the Software is - * requested to send the modifications to the original developer so that - * they can be incorporated into the canonical version. It is also - * requested that these non-binding requests be included along with the - * license above. - */ - -/** @file - @ingroup common_src - - @brief Functions for generating dither noise -*/ - -#include "pa_types.h" -#include "pa_dither.h" - - -/* Note that the linear congruential algorithm requires 32 bit integers - * because it uses arithmetic overflow. So use PaUint32 instead of - * unsigned long so it will work on 64 bit systems. - */ - -#define PA_DITHER_BITS_ (15) - - -void PaUtil_InitializeTriangularDitherState( PaUtilTriangularDitherGenerator *state ) -{ - state->previous = 0; - state->randSeed1 = 22222; - state->randSeed2 = 5555555; -} - - -PaInt32 PaUtil_Generate16BitTriangularDither( PaUtilTriangularDitherGenerator *state ) -{ - PaInt32 current, highPass; - - /* Generate two random numbers. */ - state->randSeed1 = (state->randSeed1 * 196314165) + 907633515; - state->randSeed2 = (state->randSeed2 * 196314165) + 907633515; - - /* Generate triangular distribution about 0. - * Shift before adding to prevent overflow which would skew the distribution. - * Also shift an extra bit for the high pass filter. - */ -#define DITHER_SHIFT_ ((sizeof(PaInt32)*8 - PA_DITHER_BITS_) + 1) - - current = (((PaInt32)state->randSeed1)>>DITHER_SHIFT_) + - (((PaInt32)state->randSeed2)>>DITHER_SHIFT_); - - /* High pass filter to reduce audibility. */ - highPass = current - state->previous; - state->previous = current; - return highPass; -} - - -/* Multiply by PA_FLOAT_DITHER_SCALE_ to get a float between -2.0 and +1.99999 */ -#define PA_FLOAT_DITHER_SCALE_ (1.0f / ((1<randSeed1 = (state->randSeed1 * 196314165) + 907633515; - state->randSeed2 = (state->randSeed2 * 196314165) + 907633515; - - /* Generate triangular distribution about 0. - * Shift before adding to prevent overflow which would skew the distribution. - * Also shift an extra bit for the high pass filter. - */ - current = (((PaInt32)state->randSeed1)>>DITHER_SHIFT_) + - (((PaInt32)state->randSeed2)>>DITHER_SHIFT_); - - /* High pass filter to reduce audibility. */ - highPass = current - state->previous; - state->previous = current; - return ((float)highPass) * const_float_dither_scale_; -} - - -/* -The following alternate dither algorithms (from musicdsp.org) could be -considered -*/ - -/*Noise shaped dither (March 2000) -------------------- - -This is a simple implementation of highpass triangular-PDF dither with -2nd-order noise shaping, for use when truncating floating point audio -data to fixed point. - -The noise shaping lowers the noise floor by 11dB below 5kHz (@ 44100Hz -sample rate) compared to triangular-PDF dither. The code below assumes -input data is in the range +1 to -1 and doesn't check for overloads! - -To save time when generating dither for multiple channels you can do -things like this: r3=(r1 & 0x7F)<<8; instead of calling rand() again. - - - - int r1, r2; //rectangular-PDF random numbers - float s1, s2; //error feedback buffers - float s = 0.5f; //set to 0.0f for no noise shaping - float w = pow(2.0,bits-1); //word length (usually bits=16) - float wi= 1.0f/w; - float d = wi / RAND_MAX; //dither amplitude (2 lsb) - float o = wi * 0.5f; //remove dc offset - float in, tmp; - int out; - - -//for each sample... - - r2=r1; //can make HP-TRI dither by - r1=rand(); //subtracting previous rand() - - in += s * (s1 + s1 - s2); //error feedback - tmp = in + o + d * (float)(r1 - r2); //dc offset and dither - - out = (int)(w * tmp); //truncate downwards - if(tmp<0.0f) out--; //this is faster than floor() - - s2 = s1; - s1 = in - wi * (float)out; //error - - - --- -paul.kellett@maxim.abel.co.uk -http://www.maxim.abel.co.uk -*/ - - -/* -16-to-8-bit first-order dither - -Type : First order error feedforward dithering code -References : Posted by Jon Watte - -Notes : -This is about as simple a dithering algorithm as you can implement, but it's -likely to sound better than just truncating to N bits. - -Note that you might not want to carry forward the full difference for infinity. -It's probably likely that the worst performance hit comes from the saturation -conditionals, which can be avoided with appropriate instructions on many DSPs -and integer SIMD type instructions, or CMOV. - -Last, if sound quality is paramount (such as when going from > 16 bits to 16 -bits) you probably want to use a higher-order dither function found elsewhere -on this site. - - -Code : -// This code will down-convert and dither a 16-bit signed short -// mono signal into an 8-bit unsigned char signal, using a first -// order forward-feeding error term dither. - -#define uchar unsigned char - -void dither_one_channel_16_to_8( short * input, uchar * output, int count, int * memory ) -{ - int m = *memory; - while( count-- > 0 ) { - int i = *input++; - i += m; - int j = i + 32768 - 128; - uchar o; - if( j < 0 ) { - o = 0; - } - else if( j > 65535 ) { - o = 255; - } - else { - o = (uchar)((j>>8)&0xff); - } - m = ((j-32768+128)-i); - *output++ = o; - } - *memory = m; -} -*/ diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/gradio/_frontend_code/wasm/svelte/index.ts b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/gradio/_frontend_code/wasm/svelte/index.ts deleted file mode 100644 index aadb8ee883b6c9f2aad87b3b5349603415d5173b..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/gradio/_frontend_code/wasm/svelte/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./context"; -export * from "./file-url"; diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/gradio/templates/frontend/assets/Example-f75cba10.css b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/gradio/templates/frontend/assets/Example-f75cba10.css deleted file mode 100644 index 5407a69e2bcc27d96b2a0ba576fc2ac67b8ee414..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/gradio/templates/frontend/assets/Example-f75cba10.css +++ /dev/null @@ -1 +0,0 @@ -pre.svelte-agpzo2{text-align:left}.gallery.svelte-agpzo2{padding:var(--size-1) var(--size-2)} diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/httpcore/_backends/sync.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/httpcore/_backends/sync.py deleted file mode 100644 index f2dbd32afa4990835e6be87f20f7c2a11b9ebbda..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/httpcore/_backends/sync.py +++ /dev/null @@ -1,245 +0,0 @@ -import socket -import ssl -import sys -import typing -from functools import partial - -from .._exceptions import ( - ConnectError, - ConnectTimeout, - ExceptionMapping, - ReadError, - ReadTimeout, - WriteError, - WriteTimeout, - map_exceptions, -) -from .._utils import is_socket_readable -from .base import SOCKET_OPTION, NetworkBackend, NetworkStream - - -class TLSinTLSStream(NetworkStream): # pragma: no cover - """ - Because the standard `SSLContext.wrap_socket` method does - not work for `SSLSocket` objects, we need this class - to implement TLS stream using an underlying `SSLObject` - instance in order to support TLS on top of TLS. - """ - - # Defined in RFC 8449 - TLS_RECORD_SIZE = 16384 - - def __init__( - self, - sock: socket.socket, - ssl_context: ssl.SSLContext, - server_hostname: typing.Optional[str] = None, - timeout: typing.Optional[float] = None, - ): - self._sock = sock - self._incoming = ssl.MemoryBIO() - self._outgoing = ssl.MemoryBIO() - - self.ssl_obj = ssl_context.wrap_bio( - incoming=self._incoming, - outgoing=self._outgoing, - server_hostname=server_hostname, - ) - - self._sock.settimeout(timeout) - self._perform_io(self.ssl_obj.do_handshake) - - def _perform_io( - self, - func: typing.Callable[..., typing.Any], - ) -> typing.Any: - ret = None - - while True: - errno = None - try: - ret = func() - except (ssl.SSLWantReadError, ssl.SSLWantWriteError) as e: - errno = e.errno - - self._sock.sendall(self._outgoing.read()) - - if errno == ssl.SSL_ERROR_WANT_READ: - buf = self._sock.recv(self.TLS_RECORD_SIZE) - - if buf: - self._incoming.write(buf) - else: - self._incoming.write_eof() - if errno is None: - return ret - - def read(self, max_bytes: int, timeout: typing.Optional[float] = None) -> bytes: - exc_map: ExceptionMapping = {socket.timeout: ReadTimeout, OSError: ReadError} - with map_exceptions(exc_map): - self._sock.settimeout(timeout) - return typing.cast( - bytes, self._perform_io(partial(self.ssl_obj.read, max_bytes)) - ) - - def write(self, buffer: bytes, timeout: typing.Optional[float] = None) -> None: - exc_map: ExceptionMapping = {socket.timeout: WriteTimeout, OSError: WriteError} - with map_exceptions(exc_map): - self._sock.settimeout(timeout) - while buffer: - nsent = self._perform_io(partial(self.ssl_obj.write, buffer)) - buffer = buffer[nsent:] - - def close(self) -> None: - self._sock.close() - - def start_tls( - self, - ssl_context: ssl.SSLContext, - server_hostname: typing.Optional[str] = None, - timeout: typing.Optional[float] = None, - ) -> "NetworkStream": - raise NotImplementedError() - - def get_extra_info(self, info: str) -> typing.Any: - if info == "ssl_object": - return self.ssl_obj - if info == "client_addr": - return self._sock.getsockname() - if info == "server_addr": - return self._sock.getpeername() - if info == "socket": - return self._sock - if info == "is_readable": - return is_socket_readable(self._sock) - return None - - -class SyncStream(NetworkStream): - def __init__(self, sock: socket.socket) -> None: - self._sock = sock - - def read(self, max_bytes: int, timeout: typing.Optional[float] = None) -> bytes: - exc_map: ExceptionMapping = {socket.timeout: ReadTimeout, OSError: ReadError} - with map_exceptions(exc_map): - self._sock.settimeout(timeout) - return self._sock.recv(max_bytes) - - def write(self, buffer: bytes, timeout: typing.Optional[float] = None) -> None: - if not buffer: - return - - exc_map: ExceptionMapping = {socket.timeout: WriteTimeout, OSError: WriteError} - with map_exceptions(exc_map): - while buffer: - self._sock.settimeout(timeout) - n = self._sock.send(buffer) - buffer = buffer[n:] - - def close(self) -> None: - self._sock.close() - - def start_tls( - self, - ssl_context: ssl.SSLContext, - server_hostname: typing.Optional[str] = None, - timeout: typing.Optional[float] = None, - ) -> NetworkStream: - if isinstance(self._sock, ssl.SSLSocket): # pragma: no cover - raise RuntimeError( - "Attempted to add a TLS layer on top of the existing " - "TLS stream, which is not supported by httpcore package" - ) - - exc_map: ExceptionMapping = { - socket.timeout: ConnectTimeout, - OSError: ConnectError, - } - with map_exceptions(exc_map): - try: - if isinstance(self._sock, ssl.SSLSocket): # pragma: no cover - # If the underlying socket has already been upgraded - # to the TLS layer (i.e. is an instance of SSLSocket), - # we need some additional smarts to support TLS-in-TLS. - return TLSinTLSStream( - self._sock, ssl_context, server_hostname, timeout - ) - else: - self._sock.settimeout(timeout) - sock = ssl_context.wrap_socket( - self._sock, server_hostname=server_hostname - ) - except Exception as exc: # pragma: nocover - self.close() - raise exc - return SyncStream(sock) - - def get_extra_info(self, info: str) -> typing.Any: - if info == "ssl_object" and isinstance(self._sock, ssl.SSLSocket): - return self._sock._sslobj # type: ignore - if info == "client_addr": - return self._sock.getsockname() - if info == "server_addr": - return self._sock.getpeername() - if info == "socket": - return self._sock - if info == "is_readable": - return is_socket_readable(self._sock) - return None - - -class SyncBackend(NetworkBackend): - def connect_tcp( - self, - host: str, - port: int, - timeout: typing.Optional[float] = None, - local_address: typing.Optional[str] = None, - socket_options: typing.Optional[typing.Iterable[SOCKET_OPTION]] = None, - ) -> NetworkStream: - # Note that we automatically include `TCP_NODELAY` - # in addition to any other custom socket options. - if socket_options is None: - socket_options = [] # pragma: no cover - address = (host, port) - source_address = None if local_address is None else (local_address, 0) - exc_map: ExceptionMapping = { - socket.timeout: ConnectTimeout, - OSError: ConnectError, - } - - with map_exceptions(exc_map): - sock = socket.create_connection( - address, - timeout, - source_address=source_address, - ) - for option in socket_options: - sock.setsockopt(*option) # pragma: no cover - sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) - return SyncStream(sock) - - def connect_unix_socket( - self, - path: str, - timeout: typing.Optional[float] = None, - socket_options: typing.Optional[typing.Iterable[SOCKET_OPTION]] = None, - ) -> NetworkStream: # pragma: nocover - if sys.platform == "win32": - raise RuntimeError( - "Attempted to connect to a UNIX socket on a Windows system." - ) - if socket_options is None: - socket_options = [] - - exc_map: ExceptionMapping = { - socket.timeout: ConnectTimeout, - OSError: ConnectError, - } - with map_exceptions(exc_map): - sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - for option in socket_options: - sock.setsockopt(*option) - sock.settimeout(timeout) - sock.connect(path) - return SyncStream(sock) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/core/include/numpy/random/libdivide.h b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/core/include/numpy/random/libdivide.h deleted file mode 100644 index f4eb8039b50c21c0977a38ee5f47c8f89307d482..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/core/include/numpy/random/libdivide.h +++ /dev/null @@ -1,2079 +0,0 @@ -// libdivide.h - Optimized integer division -// https://libdivide.com -// -// Copyright (C) 2010 - 2019 ridiculous_fish, -// Copyright (C) 2016 - 2019 Kim Walisch, -// -// libdivide is dual-licensed under the Boost or zlib licenses. -// You may use libdivide under the terms of either of these. -// See LICENSE.txt for more details. - -#ifndef NUMPY_CORE_INCLUDE_NUMPY_LIBDIVIDE_LIBDIVIDE_H_ -#define NUMPY_CORE_INCLUDE_NUMPY_LIBDIVIDE_LIBDIVIDE_H_ - -#define LIBDIVIDE_VERSION "3.0" -#define LIBDIVIDE_VERSION_MAJOR 3 -#define LIBDIVIDE_VERSION_MINOR 0 - -#include - -#if defined(__cplusplus) - #include - #include - #include -#else - #include - #include -#endif - -#if defined(LIBDIVIDE_AVX512) - #include -#elif defined(LIBDIVIDE_AVX2) - #include -#elif defined(LIBDIVIDE_SSE2) - #include -#endif - -#if defined(_MSC_VER) - #include - // disable warning C4146: unary minus operator applied - // to unsigned type, result still unsigned - #pragma warning(disable: 4146) - #define LIBDIVIDE_VC -#endif - -#if !defined(__has_builtin) - #define __has_builtin(x) 0 -#endif - -#if defined(__SIZEOF_INT128__) - #define HAS_INT128_T - // clang-cl on Windows does not yet support 128-bit division - #if !(defined(__clang__) && defined(LIBDIVIDE_VC)) - #define HAS_INT128_DIV - #endif -#endif - -#if defined(__x86_64__) || defined(_M_X64) - #define LIBDIVIDE_X86_64 -#endif - -#if defined(__i386__) - #define LIBDIVIDE_i386 -#endif - -#if defined(__GNUC__) || defined(__clang__) - #define LIBDIVIDE_GCC_STYLE_ASM -#endif - -#if defined(__cplusplus) || defined(LIBDIVIDE_VC) - #define LIBDIVIDE_FUNCTION __FUNCTION__ -#else - #define LIBDIVIDE_FUNCTION __func__ -#endif - -#define LIBDIVIDE_ERROR(msg) \ - do { \ - fprintf(stderr, "libdivide.h:%d: %s(): Error: %s\n", \ - __LINE__, LIBDIVIDE_FUNCTION, msg); \ - abort(); \ - } while (0) - -#if defined(LIBDIVIDE_ASSERTIONS_ON) - #define LIBDIVIDE_ASSERT(x) \ - do { \ - if (!(x)) { \ - fprintf(stderr, "libdivide.h:%d: %s(): Assertion failed: %s\n", \ - __LINE__, LIBDIVIDE_FUNCTION, #x); \ - abort(); \ - } \ - } while (0) -#else - #define LIBDIVIDE_ASSERT(x) -#endif - -#ifdef __cplusplus -namespace libdivide { -#endif - -// pack divider structs to prevent compilers from padding. -// This reduces memory usage by up to 43% when using a large -// array of libdivide dividers and improves performance -// by up to 10% because of reduced memory bandwidth. -#pragma pack(push, 1) - -struct libdivide_u32_t { - uint32_t magic; - uint8_t more; -}; - -struct libdivide_s32_t { - int32_t magic; - uint8_t more; -}; - -struct libdivide_u64_t { - uint64_t magic; - uint8_t more; -}; - -struct libdivide_s64_t { - int64_t magic; - uint8_t more; -}; - -struct libdivide_u32_branchfree_t { - uint32_t magic; - uint8_t more; -}; - -struct libdivide_s32_branchfree_t { - int32_t magic; - uint8_t more; -}; - -struct libdivide_u64_branchfree_t { - uint64_t magic; - uint8_t more; -}; - -struct libdivide_s64_branchfree_t { - int64_t magic; - uint8_t more; -}; - -#pragma pack(pop) - -// Explanation of the "more" field: -// -// * Bits 0-5 is the shift value (for shift path or mult path). -// * Bit 6 is the add indicator for mult path. -// * Bit 7 is set if the divisor is negative. We use bit 7 as the negative -// divisor indicator so that we can efficiently use sign extension to -// create a bitmask with all bits set to 1 (if the divisor is negative) -// or 0 (if the divisor is positive). -// -// u32: [0-4] shift value -// [5] ignored -// [6] add indicator -// magic number of 0 indicates shift path -// -// s32: [0-4] shift value -// [5] ignored -// [6] add indicator -// [7] indicates negative divisor -// magic number of 0 indicates shift path -// -// u64: [0-5] shift value -// [6] add indicator -// magic number of 0 indicates shift path -// -// s64: [0-5] shift value -// [6] add indicator -// [7] indicates negative divisor -// magic number of 0 indicates shift path -// -// In s32 and s64 branchfree modes, the magic number is negated according to -// whether the divisor is negated. In branchfree strategy, it is not negated. - -enum { - LIBDIVIDE_32_SHIFT_MASK = 0x1F, - LIBDIVIDE_64_SHIFT_MASK = 0x3F, - LIBDIVIDE_ADD_MARKER = 0x40, - LIBDIVIDE_NEGATIVE_DIVISOR = 0x80 -}; - -static inline struct libdivide_s32_t libdivide_s32_gen(int32_t d); -static inline struct libdivide_u32_t libdivide_u32_gen(uint32_t d); -static inline struct libdivide_s64_t libdivide_s64_gen(int64_t d); -static inline struct libdivide_u64_t libdivide_u64_gen(uint64_t d); - -static inline struct libdivide_s32_branchfree_t libdivide_s32_branchfree_gen(int32_t d); -static inline struct libdivide_u32_branchfree_t libdivide_u32_branchfree_gen(uint32_t d); -static inline struct libdivide_s64_branchfree_t libdivide_s64_branchfree_gen(int64_t d); -static inline struct libdivide_u64_branchfree_t libdivide_u64_branchfree_gen(uint64_t d); - -static inline int32_t libdivide_s32_do(int32_t numer, const struct libdivide_s32_t *denom); -static inline uint32_t libdivide_u32_do(uint32_t numer, const struct libdivide_u32_t *denom); -static inline int64_t libdivide_s64_do(int64_t numer, const struct libdivide_s64_t *denom); -static inline uint64_t libdivide_u64_do(uint64_t numer, const struct libdivide_u64_t *denom); - -static inline int32_t libdivide_s32_branchfree_do(int32_t numer, const struct libdivide_s32_branchfree_t *denom); -static inline uint32_t libdivide_u32_branchfree_do(uint32_t numer, const struct libdivide_u32_branchfree_t *denom); -static inline int64_t libdivide_s64_branchfree_do(int64_t numer, const struct libdivide_s64_branchfree_t *denom); -static inline uint64_t libdivide_u64_branchfree_do(uint64_t numer, const struct libdivide_u64_branchfree_t *denom); - -static inline int32_t libdivide_s32_recover(const struct libdivide_s32_t *denom); -static inline uint32_t libdivide_u32_recover(const struct libdivide_u32_t *denom); -static inline int64_t libdivide_s64_recover(const struct libdivide_s64_t *denom); -static inline uint64_t libdivide_u64_recover(const struct libdivide_u64_t *denom); - -static inline int32_t libdivide_s32_branchfree_recover(const struct libdivide_s32_branchfree_t *denom); -static inline uint32_t libdivide_u32_branchfree_recover(const struct libdivide_u32_branchfree_t *denom); -static inline int64_t libdivide_s64_branchfree_recover(const struct libdivide_s64_branchfree_t *denom); -static inline uint64_t libdivide_u64_branchfree_recover(const struct libdivide_u64_branchfree_t *denom); - -//////// Internal Utility Functions - -static inline uint32_t libdivide_mullhi_u32(uint32_t x, uint32_t y) { - uint64_t xl = x, yl = y; - uint64_t rl = xl * yl; - return (uint32_t)(rl >> 32); -} - -static inline int32_t libdivide_mullhi_s32(int32_t x, int32_t y) { - int64_t xl = x, yl = y; - int64_t rl = xl * yl; - // needs to be arithmetic shift - return (int32_t)(rl >> 32); -} - -static inline uint64_t libdivide_mullhi_u64(uint64_t x, uint64_t y) { -#if defined(LIBDIVIDE_VC) && \ - defined(LIBDIVIDE_X86_64) - return __umulh(x, y); -#elif defined(HAS_INT128_T) - __uint128_t xl = x, yl = y; - __uint128_t rl = xl * yl; - return (uint64_t)(rl >> 64); -#else - // full 128 bits are x0 * y0 + (x0 * y1 << 32) + (x1 * y0 << 32) + (x1 * y1 << 64) - uint32_t mask = 0xFFFFFFFF; - uint32_t x0 = (uint32_t)(x & mask); - uint32_t x1 = (uint32_t)(x >> 32); - uint32_t y0 = (uint32_t)(y & mask); - uint32_t y1 = (uint32_t)(y >> 32); - uint32_t x0y0_hi = libdivide_mullhi_u32(x0, y0); - uint64_t x0y1 = x0 * (uint64_t)y1; - uint64_t x1y0 = x1 * (uint64_t)y0; - uint64_t x1y1 = x1 * (uint64_t)y1; - uint64_t temp = x1y0 + x0y0_hi; - uint64_t temp_lo = temp & mask; - uint64_t temp_hi = temp >> 32; - - return x1y1 + temp_hi + ((temp_lo + x0y1) >> 32); -#endif -} - -static inline int64_t libdivide_mullhi_s64(int64_t x, int64_t y) { -#if defined(LIBDIVIDE_VC) && \ - defined(LIBDIVIDE_X86_64) - return __mulh(x, y); -#elif defined(HAS_INT128_T) - __int128_t xl = x, yl = y; - __int128_t rl = xl * yl; - return (int64_t)(rl >> 64); -#else - // full 128 bits are x0 * y0 + (x0 * y1 << 32) + (x1 * y0 << 32) + (x1 * y1 << 64) - uint32_t mask = 0xFFFFFFFF; - uint32_t x0 = (uint32_t)(x & mask); - uint32_t y0 = (uint32_t)(y & mask); - int32_t x1 = (int32_t)(x >> 32); - int32_t y1 = (int32_t)(y >> 32); - uint32_t x0y0_hi = libdivide_mullhi_u32(x0, y0); - int64_t t = x1 * (int64_t)y0 + x0y0_hi; - int64_t w1 = x0 * (int64_t)y1 + (t & mask); - - return x1 * (int64_t)y1 + (t >> 32) + (w1 >> 32); -#endif -} - -static inline int32_t libdivide_count_leading_zeros32(uint32_t val) { -#if defined(__GNUC__) || \ - __has_builtin(__builtin_clz) - // Fast way to count leading zeros - return __builtin_clz(val); -#elif defined(LIBDIVIDE_VC) - unsigned long result; - if (_BitScanReverse(&result, val)) { - return 31 - result; - } - return 0; -#else - if (val == 0) - return 32; - int32_t result = 8; - uint32_t hi = 0xFFU << 24; - while ((val & hi) == 0) { - hi >>= 8; - result += 8; - } - while (val & hi) { - result -= 1; - hi <<= 1; - } - return result; -#endif -} - -static inline int32_t libdivide_count_leading_zeros64(uint64_t val) { -#if defined(__GNUC__) || \ - __has_builtin(__builtin_clzll) - // Fast way to count leading zeros - return __builtin_clzll(val); -#elif defined(LIBDIVIDE_VC) && defined(_WIN64) - unsigned long result; - if (_BitScanReverse64(&result, val)) { - return 63 - result; - } - return 0; -#else - uint32_t hi = val >> 32; - uint32_t lo = val & 0xFFFFFFFF; - if (hi != 0) return libdivide_count_leading_zeros32(hi); - return 32 + libdivide_count_leading_zeros32(lo); -#endif -} - -// libdivide_64_div_32_to_32: divides a 64-bit uint {u1, u0} by a 32-bit -// uint {v}. The result must fit in 32 bits. -// Returns the quotient directly and the remainder in *r -static inline uint32_t libdivide_64_div_32_to_32(uint32_t u1, uint32_t u0, uint32_t v, uint32_t *r) { -#if (defined(LIBDIVIDE_i386) || defined(LIBDIVIDE_X86_64)) && \ - defined(LIBDIVIDE_GCC_STYLE_ASM) - uint32_t result; - __asm__("divl %[v]" - : "=a"(result), "=d"(*r) - : [v] "r"(v), "a"(u0), "d"(u1) - ); - return result; -#else - uint64_t n = ((uint64_t)u1 << 32) | u0; - uint32_t result = (uint32_t)(n / v); - *r = (uint32_t)(n - result * (uint64_t)v); - return result; -#endif -} - -// libdivide_128_div_64_to_64: divides a 128-bit uint {u1, u0} by a 64-bit -// uint {v}. The result must fit in 64 bits. -// Returns the quotient directly and the remainder in *r -static uint64_t libdivide_128_div_64_to_64(uint64_t u1, uint64_t u0, uint64_t v, uint64_t *r) { -#if defined(LIBDIVIDE_X86_64) && \ - defined(LIBDIVIDE_GCC_STYLE_ASM) - uint64_t result; - __asm__("divq %[v]" - : "=a"(result), "=d"(*r) - : [v] "r"(v), "a"(u0), "d"(u1) - ); - return result; -#elif defined(HAS_INT128_T) && \ - defined(HAS_INT128_DIV) - __uint128_t n = ((__uint128_t)u1 << 64) | u0; - uint64_t result = (uint64_t)(n / v); - *r = (uint64_t)(n - result * (__uint128_t)v); - return result; -#else - // Code taken from Hacker's Delight: - // http://www.hackersdelight.org/HDcode/divlu.c. - // License permits inclusion here per: - // http://www.hackersdelight.org/permissions.htm - - const uint64_t b = (1ULL << 32); // Number base (32 bits) - uint64_t un1, un0; // Norm. dividend LSD's - uint64_t vn1, vn0; // Norm. divisor digits - uint64_t q1, q0; // Quotient digits - uint64_t un64, un21, un10; // Dividend digit pairs - uint64_t rhat; // A remainder - int32_t s; // Shift amount for norm - - // If overflow, set rem. to an impossible value, - // and return the largest possible quotient - if (u1 >= v) { - *r = (uint64_t) -1; - return (uint64_t) -1; - } - - // count leading zeros - s = libdivide_count_leading_zeros64(v); - if (s > 0) { - // Normalize divisor - v = v << s; - un64 = (u1 << s) | (u0 >> (64 - s)); - un10 = u0 << s; // Shift dividend left - } else { - // Avoid undefined behavior of (u0 >> 64). - // The behavior is undefined if the right operand is - // negative, or greater than or equal to the length - // in bits of the promoted left operand. - un64 = u1; - un10 = u0; - } - - // Break divisor up into two 32-bit digits - vn1 = v >> 32; - vn0 = v & 0xFFFFFFFF; - - // Break right half of dividend into two digits - un1 = un10 >> 32; - un0 = un10 & 0xFFFFFFFF; - - // Compute the first quotient digit, q1 - q1 = un64 / vn1; - rhat = un64 - q1 * vn1; - - while (q1 >= b || q1 * vn0 > b * rhat + un1) { - q1 = q1 - 1; - rhat = rhat + vn1; - if (rhat >= b) - break; - } - - // Multiply and subtract - un21 = un64 * b + un1 - q1 * v; - - // Compute the second quotient digit - q0 = un21 / vn1; - rhat = un21 - q0 * vn1; - - while (q0 >= b || q0 * vn0 > b * rhat + un0) { - q0 = q0 - 1; - rhat = rhat + vn1; - if (rhat >= b) - break; - } - - *r = (un21 * b + un0 - q0 * v) >> s; - return q1 * b + q0; -#endif -} - -// Bitshift a u128 in place, left (signed_shift > 0) or right (signed_shift < 0) -static inline void libdivide_u128_shift(uint64_t *u1, uint64_t *u0, int32_t signed_shift) { - if (signed_shift > 0) { - uint32_t shift = signed_shift; - *u1 <<= shift; - *u1 |= *u0 >> (64 - shift); - *u0 <<= shift; - } - else if (signed_shift < 0) { - uint32_t shift = -signed_shift; - *u0 >>= shift; - *u0 |= *u1 << (64 - shift); - *u1 >>= shift; - } -} - -// Computes a 128 / 128 -> 64 bit division, with a 128 bit remainder. -static uint64_t libdivide_128_div_128_to_64(uint64_t u_hi, uint64_t u_lo, uint64_t v_hi, uint64_t v_lo, uint64_t *r_hi, uint64_t *r_lo) { -#if defined(HAS_INT128_T) && \ - defined(HAS_INT128_DIV) - __uint128_t ufull = u_hi; - __uint128_t vfull = v_hi; - ufull = (ufull << 64) | u_lo; - vfull = (vfull << 64) | v_lo; - uint64_t res = (uint64_t)(ufull / vfull); - __uint128_t remainder = ufull - (vfull * res); - *r_lo = (uint64_t)remainder; - *r_hi = (uint64_t)(remainder >> 64); - return res; -#else - // Adapted from "Unsigned Doubleword Division" in Hacker's Delight - // We want to compute u / v - typedef struct { uint64_t hi; uint64_t lo; } u128_t; - u128_t u = {u_hi, u_lo}; - u128_t v = {v_hi, v_lo}; - - if (v.hi == 0) { - // divisor v is a 64 bit value, so we just need one 128/64 division - // Note that we are simpler than Hacker's Delight here, because we know - // the quotient fits in 64 bits whereas Hacker's Delight demands a full - // 128 bit quotient - *r_hi = 0; - return libdivide_128_div_64_to_64(u.hi, u.lo, v.lo, r_lo); - } - // Here v >= 2**64 - // We know that v.hi != 0, so count leading zeros is OK - // We have 0 <= n <= 63 - uint32_t n = libdivide_count_leading_zeros64(v.hi); - - // Normalize the divisor so its MSB is 1 - u128_t v1t = v; - libdivide_u128_shift(&v1t.hi, &v1t.lo, n); - uint64_t v1 = v1t.hi; // i.e. v1 = v1t >> 64 - - // To ensure no overflow - u128_t u1 = u; - libdivide_u128_shift(&u1.hi, &u1.lo, -1); - - // Get quotient from divide unsigned insn. - uint64_t rem_ignored; - uint64_t q1 = libdivide_128_div_64_to_64(u1.hi, u1.lo, v1, &rem_ignored); - - // Undo normalization and division of u by 2. - u128_t q0 = {0, q1}; - libdivide_u128_shift(&q0.hi, &q0.lo, n); - libdivide_u128_shift(&q0.hi, &q0.lo, -63); - - // Make q0 correct or too small by 1 - // Equivalent to `if (q0 != 0) q0 = q0 - 1;` - if (q0.hi != 0 || q0.lo != 0) { - q0.hi -= (q0.lo == 0); // borrow - q0.lo -= 1; - } - - // Now q0 is correct. - // Compute q0 * v as q0v - // = (q0.hi << 64 + q0.lo) * (v.hi << 64 + v.lo) - // = (q0.hi * v.hi << 128) + (q0.hi * v.lo << 64) + - // (q0.lo * v.hi << 64) + q0.lo * v.lo) - // Each term is 128 bit - // High half of full product (upper 128 bits!) are dropped - u128_t q0v = {0, 0}; - q0v.hi = q0.hi*v.lo + q0.lo*v.hi + libdivide_mullhi_u64(q0.lo, v.lo); - q0v.lo = q0.lo*v.lo; - - // Compute u - q0v as u_q0v - // This is the remainder - u128_t u_q0v = u; - u_q0v.hi -= q0v.hi + (u.lo < q0v.lo); // second term is borrow - u_q0v.lo -= q0v.lo; - - // Check if u_q0v >= v - // This checks if our remainder is larger than the divisor - if ((u_q0v.hi > v.hi) || - (u_q0v.hi == v.hi && u_q0v.lo >= v.lo)) { - // Increment q0 - q0.lo += 1; - q0.hi += (q0.lo == 0); // carry - - // Subtract v from remainder - u_q0v.hi -= v.hi + (u_q0v.lo < v.lo); - u_q0v.lo -= v.lo; - } - - *r_hi = u_q0v.hi; - *r_lo = u_q0v.lo; - - LIBDIVIDE_ASSERT(q0.hi == 0); - return q0.lo; -#endif -} - -////////// UINT32 - -static inline struct libdivide_u32_t libdivide_internal_u32_gen(uint32_t d, int branchfree) { - if (d == 0) { - LIBDIVIDE_ERROR("divider must be != 0"); - } - - struct libdivide_u32_t result; - uint32_t floor_log_2_d = 31 - libdivide_count_leading_zeros32(d); - - // Power of 2 - if ((d & (d - 1)) == 0) { - // We need to subtract 1 from the shift value in case of an unsigned - // branchfree divider because there is a hardcoded right shift by 1 - // in its division algorithm. Because of this we also need to add back - // 1 in its recovery algorithm. - result.magic = 0; - result.more = (uint8_t)(floor_log_2_d - (branchfree != 0)); - } else { - uint8_t more; - uint32_t rem, proposed_m; - proposed_m = libdivide_64_div_32_to_32(1U << floor_log_2_d, 0, d, &rem); - - LIBDIVIDE_ASSERT(rem > 0 && rem < d); - const uint32_t e = d - rem; - - // This power works if e < 2**floor_log_2_d. - if (!branchfree && (e < (1U << floor_log_2_d))) { - // This power works - more = floor_log_2_d; - } else { - // We have to use the general 33-bit algorithm. We need to compute - // (2**power) / d. However, we already have (2**(power-1))/d and - // its remainder. By doubling both, and then correcting the - // remainder, we can compute the larger division. - // don't care about overflow here - in fact, we expect it - proposed_m += proposed_m; - const uint32_t twice_rem = rem + rem; - if (twice_rem >= d || twice_rem < rem) proposed_m += 1; - more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; - } - result.magic = 1 + proposed_m; - result.more = more; - // result.more's shift should in general be ceil_log_2_d. But if we - // used the smaller power, we subtract one from the shift because we're - // using the smaller power. If we're using the larger power, we - // subtract one from the shift because it's taken care of by the add - // indicator. So floor_log_2_d happens to be correct in both cases. - } - return result; -} - -struct libdivide_u32_t libdivide_u32_gen(uint32_t d) { - return libdivide_internal_u32_gen(d, 0); -} - -struct libdivide_u32_branchfree_t libdivide_u32_branchfree_gen(uint32_t d) { - if (d == 1) { - LIBDIVIDE_ERROR("branchfree divider must be != 1"); - } - struct libdivide_u32_t tmp = libdivide_internal_u32_gen(d, 1); - struct libdivide_u32_branchfree_t ret = {tmp.magic, (uint8_t)(tmp.more & LIBDIVIDE_32_SHIFT_MASK)}; - return ret; -} - -uint32_t libdivide_u32_do(uint32_t numer, const struct libdivide_u32_t *denom) { - uint8_t more = denom->more; - if (!denom->magic) { - return numer >> more; - } - else { - uint32_t q = libdivide_mullhi_u32(denom->magic, numer); - if (more & LIBDIVIDE_ADD_MARKER) { - uint32_t t = ((numer - q) >> 1) + q; - return t >> (more & LIBDIVIDE_32_SHIFT_MASK); - } - else { - // All upper bits are 0, - // don't need to mask them off. - return q >> more; - } - } -} - -uint32_t libdivide_u32_branchfree_do(uint32_t numer, const struct libdivide_u32_branchfree_t *denom) { - uint32_t q = libdivide_mullhi_u32(denom->magic, numer); - uint32_t t = ((numer - q) >> 1) + q; - return t >> denom->more; -} - -uint32_t libdivide_u32_recover(const struct libdivide_u32_t *denom) { - uint8_t more = denom->more; - uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; - - if (!denom->magic) { - return 1U << shift; - } else if (!(more & LIBDIVIDE_ADD_MARKER)) { - // We compute q = n/d = n*m / 2^(32 + shift) - // Therefore we have d = 2^(32 + shift) / m - // We need to ceil it. - // We know d is not a power of 2, so m is not a power of 2, - // so we can just add 1 to the floor - uint32_t hi_dividend = 1U << shift; - uint32_t rem_ignored; - return 1 + libdivide_64_div_32_to_32(hi_dividend, 0, denom->magic, &rem_ignored); - } else { - // Here we wish to compute d = 2^(32+shift+1)/(m+2^32). - // Notice (m + 2^32) is a 33 bit number. Use 64 bit division for now - // Also note that shift may be as high as 31, so shift + 1 will - // overflow. So we have to compute it as 2^(32+shift)/(m+2^32), and - // then double the quotient and remainder. - uint64_t half_n = 1ULL << (32 + shift); - uint64_t d = (1ULL << 32) | denom->magic; - // Note that the quotient is guaranteed <= 32 bits, but the remainder - // may need 33! - uint32_t half_q = (uint32_t)(half_n / d); - uint64_t rem = half_n % d; - // We computed 2^(32+shift)/(m+2^32) - // Need to double it, and then add 1 to the quotient if doubling th - // remainder would increase the quotient. - // Note that rem<<1 cannot overflow, since rem < d and d is 33 bits - uint32_t full_q = half_q + half_q + ((rem<<1) >= d); - - // We rounded down in gen (hence +1) - return full_q + 1; - } -} - -uint32_t libdivide_u32_branchfree_recover(const struct libdivide_u32_branchfree_t *denom) { - uint8_t more = denom->more; - uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; - - if (!denom->magic) { - return 1U << (shift + 1); - } else { - // Here we wish to compute d = 2^(32+shift+1)/(m+2^32). - // Notice (m + 2^32) is a 33 bit number. Use 64 bit division for now - // Also note that shift may be as high as 31, so shift + 1 will - // overflow. So we have to compute it as 2^(32+shift)/(m+2^32), and - // then double the quotient and remainder. - uint64_t half_n = 1ULL << (32 + shift); - uint64_t d = (1ULL << 32) | denom->magic; - // Note that the quotient is guaranteed <= 32 bits, but the remainder - // may need 33! - uint32_t half_q = (uint32_t)(half_n / d); - uint64_t rem = half_n % d; - // We computed 2^(32+shift)/(m+2^32) - // Need to double it, and then add 1 to the quotient if doubling th - // remainder would increase the quotient. - // Note that rem<<1 cannot overflow, since rem < d and d is 33 bits - uint32_t full_q = half_q + half_q + ((rem<<1) >= d); - - // We rounded down in gen (hence +1) - return full_q + 1; - } -} - -/////////// UINT64 - -static inline struct libdivide_u64_t libdivide_internal_u64_gen(uint64_t d, int branchfree) { - if (d == 0) { - LIBDIVIDE_ERROR("divider must be != 0"); - } - - struct libdivide_u64_t result; - uint32_t floor_log_2_d = 63 - libdivide_count_leading_zeros64(d); - - // Power of 2 - if ((d & (d - 1)) == 0) { - // We need to subtract 1 from the shift value in case of an unsigned - // branchfree divider because there is a hardcoded right shift by 1 - // in its division algorithm. Because of this we also need to add back - // 1 in its recovery algorithm. - result.magic = 0; - result.more = (uint8_t)(floor_log_2_d - (branchfree != 0)); - } else { - uint64_t proposed_m, rem; - uint8_t more; - // (1 << (64 + floor_log_2_d)) / d - proposed_m = libdivide_128_div_64_to_64(1ULL << floor_log_2_d, 0, d, &rem); - - LIBDIVIDE_ASSERT(rem > 0 && rem < d); - const uint64_t e = d - rem; - - // This power works if e < 2**floor_log_2_d. - if (!branchfree && e < (1ULL << floor_log_2_d)) { - // This power works - more = floor_log_2_d; - } else { - // We have to use the general 65-bit algorithm. We need to compute - // (2**power) / d. However, we already have (2**(power-1))/d and - // its remainder. By doubling both, and then correcting the - // remainder, we can compute the larger division. - // don't care about overflow here - in fact, we expect it - proposed_m += proposed_m; - const uint64_t twice_rem = rem + rem; - if (twice_rem >= d || twice_rem < rem) proposed_m += 1; - more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; - } - result.magic = 1 + proposed_m; - result.more = more; - // result.more's shift should in general be ceil_log_2_d. But if we - // used the smaller power, we subtract one from the shift because we're - // using the smaller power. If we're using the larger power, we - // subtract one from the shift because it's taken care of by the add - // indicator. So floor_log_2_d happens to be correct in both cases, - // which is why we do it outside of the if statement. - } - return result; -} - -struct libdivide_u64_t libdivide_u64_gen(uint64_t d) { - return libdivide_internal_u64_gen(d, 0); -} - -struct libdivide_u64_branchfree_t libdivide_u64_branchfree_gen(uint64_t d) { - if (d == 1) { - LIBDIVIDE_ERROR("branchfree divider must be != 1"); - } - struct libdivide_u64_t tmp = libdivide_internal_u64_gen(d, 1); - struct libdivide_u64_branchfree_t ret = {tmp.magic, (uint8_t)(tmp.more & LIBDIVIDE_64_SHIFT_MASK)}; - return ret; -} - -uint64_t libdivide_u64_do(uint64_t numer, const struct libdivide_u64_t *denom) { - uint8_t more = denom->more; - if (!denom->magic) { - return numer >> more; - } - else { - uint64_t q = libdivide_mullhi_u64(denom->magic, numer); - if (more & LIBDIVIDE_ADD_MARKER) { - uint64_t t = ((numer - q) >> 1) + q; - return t >> (more & LIBDIVIDE_64_SHIFT_MASK); - } - else { - // All upper bits are 0, - // don't need to mask them off. - return q >> more; - } - } -} - -uint64_t libdivide_u64_branchfree_do(uint64_t numer, const struct libdivide_u64_branchfree_t *denom) { - uint64_t q = libdivide_mullhi_u64(denom->magic, numer); - uint64_t t = ((numer - q) >> 1) + q; - return t >> denom->more; -} - -uint64_t libdivide_u64_recover(const struct libdivide_u64_t *denom) { - uint8_t more = denom->more; - uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; - - if (!denom->magic) { - return 1ULL << shift; - } else if (!(more & LIBDIVIDE_ADD_MARKER)) { - // We compute q = n/d = n*m / 2^(64 + shift) - // Therefore we have d = 2^(64 + shift) / m - // We need to ceil it. - // We know d is not a power of 2, so m is not a power of 2, - // so we can just add 1 to the floor - uint64_t hi_dividend = 1ULL << shift; - uint64_t rem_ignored; - return 1 + libdivide_128_div_64_to_64(hi_dividend, 0, denom->magic, &rem_ignored); - } else { - // Here we wish to compute d = 2^(64+shift+1)/(m+2^64). - // Notice (m + 2^64) is a 65 bit number. This gets hairy. See - // libdivide_u32_recover for more on what we do here. - // TODO: do something better than 128 bit math - - // Full n is a (potentially) 129 bit value - // half_n is a 128 bit value - // Compute the hi half of half_n. Low half is 0. - uint64_t half_n_hi = 1ULL << shift, half_n_lo = 0; - // d is a 65 bit value. The high bit is always set to 1. - const uint64_t d_hi = 1, d_lo = denom->magic; - // Note that the quotient is guaranteed <= 64 bits, - // but the remainder may need 65! - uint64_t r_hi, r_lo; - uint64_t half_q = libdivide_128_div_128_to_64(half_n_hi, half_n_lo, d_hi, d_lo, &r_hi, &r_lo); - // We computed 2^(64+shift)/(m+2^64) - // Double the remainder ('dr') and check if that is larger than d - // Note that d is a 65 bit value, so r1 is small and so r1 + r1 - // cannot overflow - uint64_t dr_lo = r_lo + r_lo; - uint64_t dr_hi = r_hi + r_hi + (dr_lo < r_lo); // last term is carry - int dr_exceeds_d = (dr_hi > d_hi) || (dr_hi == d_hi && dr_lo >= d_lo); - uint64_t full_q = half_q + half_q + (dr_exceeds_d ? 1 : 0); - return full_q + 1; - } -} - -uint64_t libdivide_u64_branchfree_recover(const struct libdivide_u64_branchfree_t *denom) { - uint8_t more = denom->more; - uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; - - if (!denom->magic) { - return 1ULL << (shift + 1); - } else { - // Here we wish to compute d = 2^(64+shift+1)/(m+2^64). - // Notice (m + 2^64) is a 65 bit number. This gets hairy. See - // libdivide_u32_recover for more on what we do here. - // TODO: do something better than 128 bit math - - // Full n is a (potentially) 129 bit value - // half_n is a 128 bit value - // Compute the hi half of half_n. Low half is 0. - uint64_t half_n_hi = 1ULL << shift, half_n_lo = 0; - // d is a 65 bit value. The high bit is always set to 1. - const uint64_t d_hi = 1, d_lo = denom->magic; - // Note that the quotient is guaranteed <= 64 bits, - // but the remainder may need 65! - uint64_t r_hi, r_lo; - uint64_t half_q = libdivide_128_div_128_to_64(half_n_hi, half_n_lo, d_hi, d_lo, &r_hi, &r_lo); - // We computed 2^(64+shift)/(m+2^64) - // Double the remainder ('dr') and check if that is larger than d - // Note that d is a 65 bit value, so r1 is small and so r1 + r1 - // cannot overflow - uint64_t dr_lo = r_lo + r_lo; - uint64_t dr_hi = r_hi + r_hi + (dr_lo < r_lo); // last term is carry - int dr_exceeds_d = (dr_hi > d_hi) || (dr_hi == d_hi && dr_lo >= d_lo); - uint64_t full_q = half_q + half_q + (dr_exceeds_d ? 1 : 0); - return full_q + 1; - } -} - -/////////// SINT32 - -static inline struct libdivide_s32_t libdivide_internal_s32_gen(int32_t d, int branchfree) { - if (d == 0) { - LIBDIVIDE_ERROR("divider must be != 0"); - } - - struct libdivide_s32_t result; - - // If d is a power of 2, or negative a power of 2, we have to use a shift. - // This is especially important because the magic algorithm fails for -1. - // To check if d is a power of 2 or its inverse, it suffices to check - // whether its absolute value has exactly one bit set. This works even for - // INT_MIN, because abs(INT_MIN) == INT_MIN, and INT_MIN has one bit set - // and is a power of 2. - uint32_t ud = (uint32_t)d; - uint32_t absD = (d < 0) ? -ud : ud; - uint32_t floor_log_2_d = 31 - libdivide_count_leading_zeros32(absD); - // check if exactly one bit is set, - // don't care if absD is 0 since that's divide by zero - if ((absD & (absD - 1)) == 0) { - // Branchfree and normal paths are exactly the same - result.magic = 0; - result.more = floor_log_2_d | (d < 0 ? LIBDIVIDE_NEGATIVE_DIVISOR : 0); - } else { - LIBDIVIDE_ASSERT(floor_log_2_d >= 1); - - uint8_t more; - // the dividend here is 2**(floor_log_2_d + 31), so the low 32 bit word - // is 0 and the high word is floor_log_2_d - 1 - uint32_t rem, proposed_m; - proposed_m = libdivide_64_div_32_to_32(1U << (floor_log_2_d - 1), 0, absD, &rem); - const uint32_t e = absD - rem; - - // We are going to start with a power of floor_log_2_d - 1. - // This works if works if e < 2**floor_log_2_d. - if (!branchfree && e < (1U << floor_log_2_d)) { - // This power works - more = floor_log_2_d - 1; - } else { - // We need to go one higher. This should not make proposed_m - // overflow, but it will make it negative when interpreted as an - // int32_t. - proposed_m += proposed_m; - const uint32_t twice_rem = rem + rem; - if (twice_rem >= absD || twice_rem < rem) proposed_m += 1; - more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; - } - - proposed_m += 1; - int32_t magic = (int32_t)proposed_m; - - // Mark if we are negative. Note we only negate the magic number in the - // branchfull case. - if (d < 0) { - more |= LIBDIVIDE_NEGATIVE_DIVISOR; - if (!branchfree) { - magic = -magic; - } - } - - result.more = more; - result.magic = magic; - } - return result; -} - -struct libdivide_s32_t libdivide_s32_gen(int32_t d) { - return libdivide_internal_s32_gen(d, 0); -} - -struct libdivide_s32_branchfree_t libdivide_s32_branchfree_gen(int32_t d) { - struct libdivide_s32_t tmp = libdivide_internal_s32_gen(d, 1); - struct libdivide_s32_branchfree_t result = {tmp.magic, tmp.more}; - return result; -} - -int32_t libdivide_s32_do(int32_t numer, const struct libdivide_s32_t *denom) { - uint8_t more = denom->more; - uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; - - if (!denom->magic) { - uint32_t sign = (int8_t)more >> 7; - uint32_t mask = (1U << shift) - 1; - uint32_t uq = numer + ((numer >> 31) & mask); - int32_t q = (int32_t)uq; - q >>= shift; - q = (q ^ sign) - sign; - return q; - } else { - uint32_t uq = (uint32_t)libdivide_mullhi_s32(denom->magic, numer); - if (more & LIBDIVIDE_ADD_MARKER) { - // must be arithmetic shift and then sign extend - int32_t sign = (int8_t)more >> 7; - // q += (more < 0 ? -numer : numer) - // cast required to avoid UB - uq += ((uint32_t)numer ^ sign) - sign; - } - int32_t q = (int32_t)uq; - q >>= shift; - q += (q < 0); - return q; - } -} - -int32_t libdivide_s32_branchfree_do(int32_t numer, const struct libdivide_s32_branchfree_t *denom) { - uint8_t more = denom->more; - uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; - // must be arithmetic shift and then sign extend - int32_t sign = (int8_t)more >> 7; - int32_t magic = denom->magic; - int32_t q = libdivide_mullhi_s32(magic, numer); - q += numer; - - // If q is non-negative, we have nothing to do - // If q is negative, we want to add either (2**shift)-1 if d is a power of - // 2, or (2**shift) if it is not a power of 2 - uint32_t is_power_of_2 = (magic == 0); - uint32_t q_sign = (uint32_t)(q >> 31); - q += q_sign & ((1U << shift) - is_power_of_2); - - // Now arithmetic right shift - q >>= shift; - // Negate if needed - q = (q ^ sign) - sign; - - return q; -} - -int32_t libdivide_s32_recover(const struct libdivide_s32_t *denom) { - uint8_t more = denom->more; - uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; - if (!denom->magic) { - uint32_t absD = 1U << shift; - if (more & LIBDIVIDE_NEGATIVE_DIVISOR) { - absD = -absD; - } - return (int32_t)absD; - } else { - // Unsigned math is much easier - // We negate the magic number only in the branchfull case, and we don't - // know which case we're in. However we have enough information to - // determine the correct sign of the magic number. The divisor was - // negative if LIBDIVIDE_NEGATIVE_DIVISOR is set. If ADD_MARKER is set, - // the magic number's sign is opposite that of the divisor. - // We want to compute the positive magic number. - int negative_divisor = (more & LIBDIVIDE_NEGATIVE_DIVISOR); - int magic_was_negated = (more & LIBDIVIDE_ADD_MARKER) - ? denom->magic > 0 : denom->magic < 0; - - // Handle the power of 2 case (including branchfree) - if (denom->magic == 0) { - int32_t result = 1U << shift; - return negative_divisor ? -result : result; - } - - uint32_t d = (uint32_t)(magic_was_negated ? -denom->magic : denom->magic); - uint64_t n = 1ULL << (32 + shift); // this shift cannot exceed 30 - uint32_t q = (uint32_t)(n / d); - int32_t result = (int32_t)q; - result += 1; - return negative_divisor ? -result : result; - } -} - -int32_t libdivide_s32_branchfree_recover(const struct libdivide_s32_branchfree_t *denom) { - return libdivide_s32_recover((const struct libdivide_s32_t *)denom); -} - -///////////// SINT64 - -static inline struct libdivide_s64_t libdivide_internal_s64_gen(int64_t d, int branchfree) { - if (d == 0) { - LIBDIVIDE_ERROR("divider must be != 0"); - } - - struct libdivide_s64_t result; - - // If d is a power of 2, or negative a power of 2, we have to use a shift. - // This is especially important because the magic algorithm fails for -1. - // To check if d is a power of 2 or its inverse, it suffices to check - // whether its absolute value has exactly one bit set. This works even for - // INT_MIN, because abs(INT_MIN) == INT_MIN, and INT_MIN has one bit set - // and is a power of 2. - uint64_t ud = (uint64_t)d; - uint64_t absD = (d < 0) ? -ud : ud; - uint32_t floor_log_2_d = 63 - libdivide_count_leading_zeros64(absD); - // check if exactly one bit is set, - // don't care if absD is 0 since that's divide by zero - if ((absD & (absD - 1)) == 0) { - // Branchfree and non-branchfree cases are the same - result.magic = 0; - result.more = floor_log_2_d | (d < 0 ? LIBDIVIDE_NEGATIVE_DIVISOR : 0); - } else { - // the dividend here is 2**(floor_log_2_d + 63), so the low 64 bit word - // is 0 and the high word is floor_log_2_d - 1 - uint8_t more; - uint64_t rem, proposed_m; - proposed_m = libdivide_128_div_64_to_64(1ULL << (floor_log_2_d - 1), 0, absD, &rem); - const uint64_t e = absD - rem; - - // We are going to start with a power of floor_log_2_d - 1. - // This works if works if e < 2**floor_log_2_d. - if (!branchfree && e < (1ULL << floor_log_2_d)) { - // This power works - more = floor_log_2_d - 1; - } else { - // We need to go one higher. This should not make proposed_m - // overflow, but it will make it negative when interpreted as an - // int32_t. - proposed_m += proposed_m; - const uint64_t twice_rem = rem + rem; - if (twice_rem >= absD || twice_rem < rem) proposed_m += 1; - // note that we only set the LIBDIVIDE_NEGATIVE_DIVISOR bit if we - // also set ADD_MARKER this is an annoying optimization that - // enables algorithm #4 to avoid the mask. However we always set it - // in the branchfree case - more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; - } - proposed_m += 1; - int64_t magic = (int64_t)proposed_m; - - // Mark if we are negative - if (d < 0) { - more |= LIBDIVIDE_NEGATIVE_DIVISOR; - if (!branchfree) { - magic = -magic; - } - } - - result.more = more; - result.magic = magic; - } - return result; -} - -struct libdivide_s64_t libdivide_s64_gen(int64_t d) { - return libdivide_internal_s64_gen(d, 0); -} - -struct libdivide_s64_branchfree_t libdivide_s64_branchfree_gen(int64_t d) { - struct libdivide_s64_t tmp = libdivide_internal_s64_gen(d, 1); - struct libdivide_s64_branchfree_t ret = {tmp.magic, tmp.more}; - return ret; -} - -int64_t libdivide_s64_do(int64_t numer, const struct libdivide_s64_t *denom) { - uint8_t more = denom->more; - uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; - - if (!denom->magic) { // shift path - uint64_t mask = (1ULL << shift) - 1; - uint64_t uq = numer + ((numer >> 63) & mask); - int64_t q = (int64_t)uq; - q >>= shift; - // must be arithmetic shift and then sign-extend - int64_t sign = (int8_t)more >> 7; - q = (q ^ sign) - sign; - return q; - } else { - uint64_t uq = (uint64_t)libdivide_mullhi_s64(denom->magic, numer); - if (more & LIBDIVIDE_ADD_MARKER) { - // must be arithmetic shift and then sign extend - int64_t sign = (int8_t)more >> 7; - // q += (more < 0 ? -numer : numer) - // cast required to avoid UB - uq += ((uint64_t)numer ^ sign) - sign; - } - int64_t q = (int64_t)uq; - q >>= shift; - q += (q < 0); - return q; - } -} - -int64_t libdivide_s64_branchfree_do(int64_t numer, const struct libdivide_s64_branchfree_t *denom) { - uint8_t more = denom->more; - uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; - // must be arithmetic shift and then sign extend - int64_t sign = (int8_t)more >> 7; - int64_t magic = denom->magic; - int64_t q = libdivide_mullhi_s64(magic, numer); - q += numer; - - // If q is non-negative, we have nothing to do. - // If q is negative, we want to add either (2**shift)-1 if d is a power of - // 2, or (2**shift) if it is not a power of 2. - uint64_t is_power_of_2 = (magic == 0); - uint64_t q_sign = (uint64_t)(q >> 63); - q += q_sign & ((1ULL << shift) - is_power_of_2); - - // Arithmetic right shift - q >>= shift; - // Negate if needed - q = (q ^ sign) - sign; - - return q; -} - -int64_t libdivide_s64_recover(const struct libdivide_s64_t *denom) { - uint8_t more = denom->more; - uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; - if (denom->magic == 0) { // shift path - uint64_t absD = 1ULL << shift; - if (more & LIBDIVIDE_NEGATIVE_DIVISOR) { - absD = -absD; - } - return (int64_t)absD; - } else { - // Unsigned math is much easier - int negative_divisor = (more & LIBDIVIDE_NEGATIVE_DIVISOR); - int magic_was_negated = (more & LIBDIVIDE_ADD_MARKER) - ? denom->magic > 0 : denom->magic < 0; - - uint64_t d = (uint64_t)(magic_was_negated ? -denom->magic : denom->magic); - uint64_t n_hi = 1ULL << shift, n_lo = 0; - uint64_t rem_ignored; - uint64_t q = libdivide_128_div_64_to_64(n_hi, n_lo, d, &rem_ignored); - int64_t result = (int64_t)(q + 1); - if (negative_divisor) { - result = -result; - } - return result; - } -} - -int64_t libdivide_s64_branchfree_recover(const struct libdivide_s64_branchfree_t *denom) { - return libdivide_s64_recover((const struct libdivide_s64_t *)denom); -} - -#if defined(LIBDIVIDE_AVX512) - -static inline __m512i libdivide_u32_do_vector(__m512i numers, const struct libdivide_u32_t *denom); -static inline __m512i libdivide_s32_do_vector(__m512i numers, const struct libdivide_s32_t *denom); -static inline __m512i libdivide_u64_do_vector(__m512i numers, const struct libdivide_u64_t *denom); -static inline __m512i libdivide_s64_do_vector(__m512i numers, const struct libdivide_s64_t *denom); - -static inline __m512i libdivide_u32_branchfree_do_vector(__m512i numers, const struct libdivide_u32_branchfree_t *denom); -static inline __m512i libdivide_s32_branchfree_do_vector(__m512i numers, const struct libdivide_s32_branchfree_t *denom); -static inline __m512i libdivide_u64_branchfree_do_vector(__m512i numers, const struct libdivide_u64_branchfree_t *denom); -static inline __m512i libdivide_s64_branchfree_do_vector(__m512i numers, const struct libdivide_s64_branchfree_t *denom); - -//////// Internal Utility Functions - -static inline __m512i libdivide_s64_signbits(__m512i v) {; - return _mm512_srai_epi64(v, 63); -} - -static inline __m512i libdivide_s64_shift_right_vector(__m512i v, int amt) { - return _mm512_srai_epi64(v, amt); -} - -// Here, b is assumed to contain one 32-bit value repeated. -static inline __m512i libdivide_mullhi_u32_vector(__m512i a, __m512i b) { - __m512i hi_product_0Z2Z = _mm512_srli_epi64(_mm512_mul_epu32(a, b), 32); - __m512i a1X3X = _mm512_srli_epi64(a, 32); - __m512i mask = _mm512_set_epi32(-1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0); - __m512i hi_product_Z1Z3 = _mm512_and_si512(_mm512_mul_epu32(a1X3X, b), mask); - return _mm512_or_si512(hi_product_0Z2Z, hi_product_Z1Z3); -} - -// b is one 32-bit value repeated. -static inline __m512i libdivide_mullhi_s32_vector(__m512i a, __m512i b) { - __m512i hi_product_0Z2Z = _mm512_srli_epi64(_mm512_mul_epi32(a, b), 32); - __m512i a1X3X = _mm512_srli_epi64(a, 32); - __m512i mask = _mm512_set_epi32(-1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0); - __m512i hi_product_Z1Z3 = _mm512_and_si512(_mm512_mul_epi32(a1X3X, b), mask); - return _mm512_or_si512(hi_product_0Z2Z, hi_product_Z1Z3); -} - -// Here, y is assumed to contain one 64-bit value repeated. -// https://stackoverflow.com/a/28827013 -static inline __m512i libdivide_mullhi_u64_vector(__m512i x, __m512i y) { - __m512i lomask = _mm512_set1_epi64(0xffffffff); - __m512i xh = _mm512_shuffle_epi32(x, (_MM_PERM_ENUM) 0xB1); - __m512i yh = _mm512_shuffle_epi32(y, (_MM_PERM_ENUM) 0xB1); - __m512i w0 = _mm512_mul_epu32(x, y); - __m512i w1 = _mm512_mul_epu32(x, yh); - __m512i w2 = _mm512_mul_epu32(xh, y); - __m512i w3 = _mm512_mul_epu32(xh, yh); - __m512i w0h = _mm512_srli_epi64(w0, 32); - __m512i s1 = _mm512_add_epi64(w1, w0h); - __m512i s1l = _mm512_and_si512(s1, lomask); - __m512i s1h = _mm512_srli_epi64(s1, 32); - __m512i s2 = _mm512_add_epi64(w2, s1l); - __m512i s2h = _mm512_srli_epi64(s2, 32); - __m512i hi = _mm512_add_epi64(w3, s1h); - hi = _mm512_add_epi64(hi, s2h); - - return hi; -} - -// y is one 64-bit value repeated. -static inline __m512i libdivide_mullhi_s64_vector(__m512i x, __m512i y) { - __m512i p = libdivide_mullhi_u64_vector(x, y); - __m512i t1 = _mm512_and_si512(libdivide_s64_signbits(x), y); - __m512i t2 = _mm512_and_si512(libdivide_s64_signbits(y), x); - p = _mm512_sub_epi64(p, t1); - p = _mm512_sub_epi64(p, t2); - return p; -} - -////////// UINT32 - -__m512i libdivide_u32_do_vector(__m512i numers, const struct libdivide_u32_t *denom) { - uint8_t more = denom->more; - if (!denom->magic) { - return _mm512_srli_epi32(numers, more); - } - else { - __m512i q = libdivide_mullhi_u32_vector(numers, _mm512_set1_epi32(denom->magic)); - if (more & LIBDIVIDE_ADD_MARKER) { - // uint32_t t = ((numer - q) >> 1) + q; - // return t >> denom->shift; - uint32_t shift = more & LIBDIVIDE_32_SHIFT_MASK; - __m512i t = _mm512_add_epi32(_mm512_srli_epi32(_mm512_sub_epi32(numers, q), 1), q); - return _mm512_srli_epi32(t, shift); - } - else { - return _mm512_srli_epi32(q, more); - } - } -} - -__m512i libdivide_u32_branchfree_do_vector(__m512i numers, const struct libdivide_u32_branchfree_t *denom) { - __m512i q = libdivide_mullhi_u32_vector(numers, _mm512_set1_epi32(denom->magic)); - __m512i t = _mm512_add_epi32(_mm512_srli_epi32(_mm512_sub_epi32(numers, q), 1), q); - return _mm512_srli_epi32(t, denom->more); -} - -////////// UINT64 - -__m512i libdivide_u64_do_vector(__m512i numers, const struct libdivide_u64_t *denom) { - uint8_t more = denom->more; - if (!denom->magic) { - return _mm512_srli_epi64(numers, more); - } - else { - __m512i q = libdivide_mullhi_u64_vector(numers, _mm512_set1_epi64(denom->magic)); - if (more & LIBDIVIDE_ADD_MARKER) { - // uint32_t t = ((numer - q) >> 1) + q; - // return t >> denom->shift; - uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK; - __m512i t = _mm512_add_epi64(_mm512_srli_epi64(_mm512_sub_epi64(numers, q), 1), q); - return _mm512_srli_epi64(t, shift); - } - else { - return _mm512_srli_epi64(q, more); - } - } -} - -__m512i libdivide_u64_branchfree_do_vector(__m512i numers, const struct libdivide_u64_branchfree_t *denom) { - __m512i q = libdivide_mullhi_u64_vector(numers, _mm512_set1_epi64(denom->magic)); - __m512i t = _mm512_add_epi64(_mm512_srli_epi64(_mm512_sub_epi64(numers, q), 1), q); - return _mm512_srli_epi64(t, denom->more); -} - -////////// SINT32 - -__m512i libdivide_s32_do_vector(__m512i numers, const struct libdivide_s32_t *denom) { - uint8_t more = denom->more; - if (!denom->magic) { - uint32_t shift = more & LIBDIVIDE_32_SHIFT_MASK; - uint32_t mask = (1U << shift) - 1; - __m512i roundToZeroTweak = _mm512_set1_epi32(mask); - // q = numer + ((numer >> 31) & roundToZeroTweak); - __m512i q = _mm512_add_epi32(numers, _mm512_and_si512(_mm512_srai_epi32(numers, 31), roundToZeroTweak)); - q = _mm512_srai_epi32(q, shift); - __m512i sign = _mm512_set1_epi32((int8_t)more >> 7); - // q = (q ^ sign) - sign; - q = _mm512_sub_epi32(_mm512_xor_si512(q, sign), sign); - return q; - } - else { - __m512i q = libdivide_mullhi_s32_vector(numers, _mm512_set1_epi32(denom->magic)); - if (more & LIBDIVIDE_ADD_MARKER) { - // must be arithmetic shift - __m512i sign = _mm512_set1_epi32((int8_t)more >> 7); - // q += ((numer ^ sign) - sign); - q = _mm512_add_epi32(q, _mm512_sub_epi32(_mm512_xor_si512(numers, sign), sign)); - } - // q >>= shift - q = _mm512_srai_epi32(q, more & LIBDIVIDE_32_SHIFT_MASK); - q = _mm512_add_epi32(q, _mm512_srli_epi32(q, 31)); // q += (q < 0) - return q; - } -} - -__m512i libdivide_s32_branchfree_do_vector(__m512i numers, const struct libdivide_s32_branchfree_t *denom) { - int32_t magic = denom->magic; - uint8_t more = denom->more; - uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; - // must be arithmetic shift - __m512i sign = _mm512_set1_epi32((int8_t)more >> 7); - __m512i q = libdivide_mullhi_s32_vector(numers, _mm512_set1_epi32(magic)); - q = _mm512_add_epi32(q, numers); // q += numers - - // If q is non-negative, we have nothing to do - // If q is negative, we want to add either (2**shift)-1 if d is - // a power of 2, or (2**shift) if it is not a power of 2 - uint32_t is_power_of_2 = (magic == 0); - __m512i q_sign = _mm512_srai_epi32(q, 31); // q_sign = q >> 31 - __m512i mask = _mm512_set1_epi32((1U << shift) - is_power_of_2); - q = _mm512_add_epi32(q, _mm512_and_si512(q_sign, mask)); // q = q + (q_sign & mask) - q = _mm512_srai_epi32(q, shift); // q >>= shift - q = _mm512_sub_epi32(_mm512_xor_si512(q, sign), sign); // q = (q ^ sign) - sign - return q; -} - -////////// SINT64 - -__m512i libdivide_s64_do_vector(__m512i numers, const struct libdivide_s64_t *denom) { - uint8_t more = denom->more; - int64_t magic = denom->magic; - if (magic == 0) { // shift path - uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK; - uint64_t mask = (1ULL << shift) - 1; - __m512i roundToZeroTweak = _mm512_set1_epi64(mask); - // q = numer + ((numer >> 63) & roundToZeroTweak); - __m512i q = _mm512_add_epi64(numers, _mm512_and_si512(libdivide_s64_signbits(numers), roundToZeroTweak)); - q = libdivide_s64_shift_right_vector(q, shift); - __m512i sign = _mm512_set1_epi32((int8_t)more >> 7); - // q = (q ^ sign) - sign; - q = _mm512_sub_epi64(_mm512_xor_si512(q, sign), sign); - return q; - } - else { - __m512i q = libdivide_mullhi_s64_vector(numers, _mm512_set1_epi64(magic)); - if (more & LIBDIVIDE_ADD_MARKER) { - // must be arithmetic shift - __m512i sign = _mm512_set1_epi32((int8_t)more >> 7); - // q += ((numer ^ sign) - sign); - q = _mm512_add_epi64(q, _mm512_sub_epi64(_mm512_xor_si512(numers, sign), sign)); - } - // q >>= denom->mult_path.shift - q = libdivide_s64_shift_right_vector(q, more & LIBDIVIDE_64_SHIFT_MASK); - q = _mm512_add_epi64(q, _mm512_srli_epi64(q, 63)); // q += (q < 0) - return q; - } -} - -__m512i libdivide_s64_branchfree_do_vector(__m512i numers, const struct libdivide_s64_branchfree_t *denom) { - int64_t magic = denom->magic; - uint8_t more = denom->more; - uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; - // must be arithmetic shift - __m512i sign = _mm512_set1_epi32((int8_t)more >> 7); - - // libdivide_mullhi_s64(numers, magic); - __m512i q = libdivide_mullhi_s64_vector(numers, _mm512_set1_epi64(magic)); - q = _mm512_add_epi64(q, numers); // q += numers - - // If q is non-negative, we have nothing to do. - // If q is negative, we want to add either (2**shift)-1 if d is - // a power of 2, or (2**shift) if it is not a power of 2. - uint32_t is_power_of_2 = (magic == 0); - __m512i q_sign = libdivide_s64_signbits(q); // q_sign = q >> 63 - __m512i mask = _mm512_set1_epi64((1ULL << shift) - is_power_of_2); - q = _mm512_add_epi64(q, _mm512_and_si512(q_sign, mask)); // q = q + (q_sign & mask) - q = libdivide_s64_shift_right_vector(q, shift); // q >>= shift - q = _mm512_sub_epi64(_mm512_xor_si512(q, sign), sign); // q = (q ^ sign) - sign - return q; -} - -#elif defined(LIBDIVIDE_AVX2) - -static inline __m256i libdivide_u32_do_vector(__m256i numers, const struct libdivide_u32_t *denom); -static inline __m256i libdivide_s32_do_vector(__m256i numers, const struct libdivide_s32_t *denom); -static inline __m256i libdivide_u64_do_vector(__m256i numers, const struct libdivide_u64_t *denom); -static inline __m256i libdivide_s64_do_vector(__m256i numers, const struct libdivide_s64_t *denom); - -static inline __m256i libdivide_u32_branchfree_do_vector(__m256i numers, const struct libdivide_u32_branchfree_t *denom); -static inline __m256i libdivide_s32_branchfree_do_vector(__m256i numers, const struct libdivide_s32_branchfree_t *denom); -static inline __m256i libdivide_u64_branchfree_do_vector(__m256i numers, const struct libdivide_u64_branchfree_t *denom); -static inline __m256i libdivide_s64_branchfree_do_vector(__m256i numers, const struct libdivide_s64_branchfree_t *denom); - -//////// Internal Utility Functions - -// Implementation of _mm256_srai_epi64(v, 63) (from AVX512). -static inline __m256i libdivide_s64_signbits(__m256i v) { - __m256i hiBitsDuped = _mm256_shuffle_epi32(v, _MM_SHUFFLE(3, 3, 1, 1)); - __m256i signBits = _mm256_srai_epi32(hiBitsDuped, 31); - return signBits; -} - -// Implementation of _mm256_srai_epi64 (from AVX512). -static inline __m256i libdivide_s64_shift_right_vector(__m256i v, int amt) { - const int b = 64 - amt; - __m256i m = _mm256_set1_epi64x(1ULL << (b - 1)); - __m256i x = _mm256_srli_epi64(v, amt); - __m256i result = _mm256_sub_epi64(_mm256_xor_si256(x, m), m); - return result; -} - -// Here, b is assumed to contain one 32-bit value repeated. -static inline __m256i libdivide_mullhi_u32_vector(__m256i a, __m256i b) { - __m256i hi_product_0Z2Z = _mm256_srli_epi64(_mm256_mul_epu32(a, b), 32); - __m256i a1X3X = _mm256_srli_epi64(a, 32); - __m256i mask = _mm256_set_epi32(-1, 0, -1, 0, -1, 0, -1, 0); - __m256i hi_product_Z1Z3 = _mm256_and_si256(_mm256_mul_epu32(a1X3X, b), mask); - return _mm256_or_si256(hi_product_0Z2Z, hi_product_Z1Z3); -} - -// b is one 32-bit value repeated. -static inline __m256i libdivide_mullhi_s32_vector(__m256i a, __m256i b) { - __m256i hi_product_0Z2Z = _mm256_srli_epi64(_mm256_mul_epi32(a, b), 32); - __m256i a1X3X = _mm256_srli_epi64(a, 32); - __m256i mask = _mm256_set_epi32(-1, 0, -1, 0, -1, 0, -1, 0); - __m256i hi_product_Z1Z3 = _mm256_and_si256(_mm256_mul_epi32(a1X3X, b), mask); - return _mm256_or_si256(hi_product_0Z2Z, hi_product_Z1Z3); -} - -// Here, y is assumed to contain one 64-bit value repeated. -// https://stackoverflow.com/a/28827013 -static inline __m256i libdivide_mullhi_u64_vector(__m256i x, __m256i y) { - __m256i lomask = _mm256_set1_epi64x(0xffffffff); - __m256i xh = _mm256_shuffle_epi32(x, 0xB1); // x0l, x0h, x1l, x1h - __m256i yh = _mm256_shuffle_epi32(y, 0xB1); // y0l, y0h, y1l, y1h - __m256i w0 = _mm256_mul_epu32(x, y); // x0l*y0l, x1l*y1l - __m256i w1 = _mm256_mul_epu32(x, yh); // x0l*y0h, x1l*y1h - __m256i w2 = _mm256_mul_epu32(xh, y); // x0h*y0l, x1h*y0l - __m256i w3 = _mm256_mul_epu32(xh, yh); // x0h*y0h, x1h*y1h - __m256i w0h = _mm256_srli_epi64(w0, 32); - __m256i s1 = _mm256_add_epi64(w1, w0h); - __m256i s1l = _mm256_and_si256(s1, lomask); - __m256i s1h = _mm256_srli_epi64(s1, 32); - __m256i s2 = _mm256_add_epi64(w2, s1l); - __m256i s2h = _mm256_srli_epi64(s2, 32); - __m256i hi = _mm256_add_epi64(w3, s1h); - hi = _mm256_add_epi64(hi, s2h); - - return hi; -} - -// y is one 64-bit value repeated. -static inline __m256i libdivide_mullhi_s64_vector(__m256i x, __m256i y) { - __m256i p = libdivide_mullhi_u64_vector(x, y); - __m256i t1 = _mm256_and_si256(libdivide_s64_signbits(x), y); - __m256i t2 = _mm256_and_si256(libdivide_s64_signbits(y), x); - p = _mm256_sub_epi64(p, t1); - p = _mm256_sub_epi64(p, t2); - return p; -} - -////////// UINT32 - -__m256i libdivide_u32_do_vector(__m256i numers, const struct libdivide_u32_t *denom) { - uint8_t more = denom->more; - if (!denom->magic) { - return _mm256_srli_epi32(numers, more); - } - else { - __m256i q = libdivide_mullhi_u32_vector(numers, _mm256_set1_epi32(denom->magic)); - if (more & LIBDIVIDE_ADD_MARKER) { - // uint32_t t = ((numer - q) >> 1) + q; - // return t >> denom->shift; - uint32_t shift = more & LIBDIVIDE_32_SHIFT_MASK; - __m256i t = _mm256_add_epi32(_mm256_srli_epi32(_mm256_sub_epi32(numers, q), 1), q); - return _mm256_srli_epi32(t, shift); - } - else { - return _mm256_srli_epi32(q, more); - } - } -} - -__m256i libdivide_u32_branchfree_do_vector(__m256i numers, const struct libdivide_u32_branchfree_t *denom) { - __m256i q = libdivide_mullhi_u32_vector(numers, _mm256_set1_epi32(denom->magic)); - __m256i t = _mm256_add_epi32(_mm256_srli_epi32(_mm256_sub_epi32(numers, q), 1), q); - return _mm256_srli_epi32(t, denom->more); -} - -////////// UINT64 - -__m256i libdivide_u64_do_vector(__m256i numers, const struct libdivide_u64_t *denom) { - uint8_t more = denom->more; - if (!denom->magic) { - return _mm256_srli_epi64(numers, more); - } - else { - __m256i q = libdivide_mullhi_u64_vector(numers, _mm256_set1_epi64x(denom->magic)); - if (more & LIBDIVIDE_ADD_MARKER) { - // uint32_t t = ((numer - q) >> 1) + q; - // return t >> denom->shift; - uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK; - __m256i t = _mm256_add_epi64(_mm256_srli_epi64(_mm256_sub_epi64(numers, q), 1), q); - return _mm256_srli_epi64(t, shift); - } - else { - return _mm256_srli_epi64(q, more); - } - } -} - -__m256i libdivide_u64_branchfree_do_vector(__m256i numers, const struct libdivide_u64_branchfree_t *denom) { - __m256i q = libdivide_mullhi_u64_vector(numers, _mm256_set1_epi64x(denom->magic)); - __m256i t = _mm256_add_epi64(_mm256_srli_epi64(_mm256_sub_epi64(numers, q), 1), q); - return _mm256_srli_epi64(t, denom->more); -} - -////////// SINT32 - -__m256i libdivide_s32_do_vector(__m256i numers, const struct libdivide_s32_t *denom) { - uint8_t more = denom->more; - if (!denom->magic) { - uint32_t shift = more & LIBDIVIDE_32_SHIFT_MASK; - uint32_t mask = (1U << shift) - 1; - __m256i roundToZeroTweak = _mm256_set1_epi32(mask); - // q = numer + ((numer >> 31) & roundToZeroTweak); - __m256i q = _mm256_add_epi32(numers, _mm256_and_si256(_mm256_srai_epi32(numers, 31), roundToZeroTweak)); - q = _mm256_srai_epi32(q, shift); - __m256i sign = _mm256_set1_epi32((int8_t)more >> 7); - // q = (q ^ sign) - sign; - q = _mm256_sub_epi32(_mm256_xor_si256(q, sign), sign); - return q; - } - else { - __m256i q = libdivide_mullhi_s32_vector(numers, _mm256_set1_epi32(denom->magic)); - if (more & LIBDIVIDE_ADD_MARKER) { - // must be arithmetic shift - __m256i sign = _mm256_set1_epi32((int8_t)more >> 7); - // q += ((numer ^ sign) - sign); - q = _mm256_add_epi32(q, _mm256_sub_epi32(_mm256_xor_si256(numers, sign), sign)); - } - // q >>= shift - q = _mm256_srai_epi32(q, more & LIBDIVIDE_32_SHIFT_MASK); - q = _mm256_add_epi32(q, _mm256_srli_epi32(q, 31)); // q += (q < 0) - return q; - } -} - -__m256i libdivide_s32_branchfree_do_vector(__m256i numers, const struct libdivide_s32_branchfree_t *denom) { - int32_t magic = denom->magic; - uint8_t more = denom->more; - uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; - // must be arithmetic shift - __m256i sign = _mm256_set1_epi32((int8_t)more >> 7); - __m256i q = libdivide_mullhi_s32_vector(numers, _mm256_set1_epi32(magic)); - q = _mm256_add_epi32(q, numers); // q += numers - - // If q is non-negative, we have nothing to do - // If q is negative, we want to add either (2**shift)-1 if d is - // a power of 2, or (2**shift) if it is not a power of 2 - uint32_t is_power_of_2 = (magic == 0); - __m256i q_sign = _mm256_srai_epi32(q, 31); // q_sign = q >> 31 - __m256i mask = _mm256_set1_epi32((1U << shift) - is_power_of_2); - q = _mm256_add_epi32(q, _mm256_and_si256(q_sign, mask)); // q = q + (q_sign & mask) - q = _mm256_srai_epi32(q, shift); // q >>= shift - q = _mm256_sub_epi32(_mm256_xor_si256(q, sign), sign); // q = (q ^ sign) - sign - return q; -} - -////////// SINT64 - -__m256i libdivide_s64_do_vector(__m256i numers, const struct libdivide_s64_t *denom) { - uint8_t more = denom->more; - int64_t magic = denom->magic; - if (magic == 0) { // shift path - uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK; - uint64_t mask = (1ULL << shift) - 1; - __m256i roundToZeroTweak = _mm256_set1_epi64x(mask); - // q = numer + ((numer >> 63) & roundToZeroTweak); - __m256i q = _mm256_add_epi64(numers, _mm256_and_si256(libdivide_s64_signbits(numers), roundToZeroTweak)); - q = libdivide_s64_shift_right_vector(q, shift); - __m256i sign = _mm256_set1_epi32((int8_t)more >> 7); - // q = (q ^ sign) - sign; - q = _mm256_sub_epi64(_mm256_xor_si256(q, sign), sign); - return q; - } - else { - __m256i q = libdivide_mullhi_s64_vector(numers, _mm256_set1_epi64x(magic)); - if (more & LIBDIVIDE_ADD_MARKER) { - // must be arithmetic shift - __m256i sign = _mm256_set1_epi32((int8_t)more >> 7); - // q += ((numer ^ sign) - sign); - q = _mm256_add_epi64(q, _mm256_sub_epi64(_mm256_xor_si256(numers, sign), sign)); - } - // q >>= denom->mult_path.shift - q = libdivide_s64_shift_right_vector(q, more & LIBDIVIDE_64_SHIFT_MASK); - q = _mm256_add_epi64(q, _mm256_srli_epi64(q, 63)); // q += (q < 0) - return q; - } -} - -__m256i libdivide_s64_branchfree_do_vector(__m256i numers, const struct libdivide_s64_branchfree_t *denom) { - int64_t magic = denom->magic; - uint8_t more = denom->more; - uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; - // must be arithmetic shift - __m256i sign = _mm256_set1_epi32((int8_t)more >> 7); - - // libdivide_mullhi_s64(numers, magic); - __m256i q = libdivide_mullhi_s64_vector(numers, _mm256_set1_epi64x(magic)); - q = _mm256_add_epi64(q, numers); // q += numers - - // If q is non-negative, we have nothing to do. - // If q is negative, we want to add either (2**shift)-1 if d is - // a power of 2, or (2**shift) if it is not a power of 2. - uint32_t is_power_of_2 = (magic == 0); - __m256i q_sign = libdivide_s64_signbits(q); // q_sign = q >> 63 - __m256i mask = _mm256_set1_epi64x((1ULL << shift) - is_power_of_2); - q = _mm256_add_epi64(q, _mm256_and_si256(q_sign, mask)); // q = q + (q_sign & mask) - q = libdivide_s64_shift_right_vector(q, shift); // q >>= shift - q = _mm256_sub_epi64(_mm256_xor_si256(q, sign), sign); // q = (q ^ sign) - sign - return q; -} - -#elif defined(LIBDIVIDE_SSE2) - -static inline __m128i libdivide_u32_do_vector(__m128i numers, const struct libdivide_u32_t *denom); -static inline __m128i libdivide_s32_do_vector(__m128i numers, const struct libdivide_s32_t *denom); -static inline __m128i libdivide_u64_do_vector(__m128i numers, const struct libdivide_u64_t *denom); -static inline __m128i libdivide_s64_do_vector(__m128i numers, const struct libdivide_s64_t *denom); - -static inline __m128i libdivide_u32_branchfree_do_vector(__m128i numers, const struct libdivide_u32_branchfree_t *denom); -static inline __m128i libdivide_s32_branchfree_do_vector(__m128i numers, const struct libdivide_s32_branchfree_t *denom); -static inline __m128i libdivide_u64_branchfree_do_vector(__m128i numers, const struct libdivide_u64_branchfree_t *denom); -static inline __m128i libdivide_s64_branchfree_do_vector(__m128i numers, const struct libdivide_s64_branchfree_t *denom); - -//////// Internal Utility Functions - -// Implementation of _mm_srai_epi64(v, 63) (from AVX512). -static inline __m128i libdivide_s64_signbits(__m128i v) { - __m128i hiBitsDuped = _mm_shuffle_epi32(v, _MM_SHUFFLE(3, 3, 1, 1)); - __m128i signBits = _mm_srai_epi32(hiBitsDuped, 31); - return signBits; -} - -// Implementation of _mm_srai_epi64 (from AVX512). -static inline __m128i libdivide_s64_shift_right_vector(__m128i v, int amt) { - const int b = 64 - amt; - __m128i m = _mm_set1_epi64x(1ULL << (b - 1)); - __m128i x = _mm_srli_epi64(v, amt); - __m128i result = _mm_sub_epi64(_mm_xor_si128(x, m), m); - return result; -} - -// Here, b is assumed to contain one 32-bit value repeated. -static inline __m128i libdivide_mullhi_u32_vector(__m128i a, __m128i b) { - __m128i hi_product_0Z2Z = _mm_srli_epi64(_mm_mul_epu32(a, b), 32); - __m128i a1X3X = _mm_srli_epi64(a, 32); - __m128i mask = _mm_set_epi32(-1, 0, -1, 0); - __m128i hi_product_Z1Z3 = _mm_and_si128(_mm_mul_epu32(a1X3X, b), mask); - return _mm_or_si128(hi_product_0Z2Z, hi_product_Z1Z3); -} - -// SSE2 does not have a signed multiplication instruction, but we can convert -// unsigned to signed pretty efficiently. Again, b is just a 32 bit value -// repeated four times. -static inline __m128i libdivide_mullhi_s32_vector(__m128i a, __m128i b) { - __m128i p = libdivide_mullhi_u32_vector(a, b); - // t1 = (a >> 31) & y, arithmetic shift - __m128i t1 = _mm_and_si128(_mm_srai_epi32(a, 31), b); - __m128i t2 = _mm_and_si128(_mm_srai_epi32(b, 31), a); - p = _mm_sub_epi32(p, t1); - p = _mm_sub_epi32(p, t2); - return p; -} - -// Here, y is assumed to contain one 64-bit value repeated. -// https://stackoverflow.com/a/28827013 -static inline __m128i libdivide_mullhi_u64_vector(__m128i x, __m128i y) { - __m128i lomask = _mm_set1_epi64x(0xffffffff); - __m128i xh = _mm_shuffle_epi32(x, 0xB1); // x0l, x0h, x1l, x1h - __m128i yh = _mm_shuffle_epi32(y, 0xB1); // y0l, y0h, y1l, y1h - __m128i w0 = _mm_mul_epu32(x, y); // x0l*y0l, x1l*y1l - __m128i w1 = _mm_mul_epu32(x, yh); // x0l*y0h, x1l*y1h - __m128i w2 = _mm_mul_epu32(xh, y); // x0h*y0l, x1h*y0l - __m128i w3 = _mm_mul_epu32(xh, yh); // x0h*y0h, x1h*y1h - __m128i w0h = _mm_srli_epi64(w0, 32); - __m128i s1 = _mm_add_epi64(w1, w0h); - __m128i s1l = _mm_and_si128(s1, lomask); - __m128i s1h = _mm_srli_epi64(s1, 32); - __m128i s2 = _mm_add_epi64(w2, s1l); - __m128i s2h = _mm_srli_epi64(s2, 32); - __m128i hi = _mm_add_epi64(w3, s1h); - hi = _mm_add_epi64(hi, s2h); - - return hi; -} - -// y is one 64-bit value repeated. -static inline __m128i libdivide_mullhi_s64_vector(__m128i x, __m128i y) { - __m128i p = libdivide_mullhi_u64_vector(x, y); - __m128i t1 = _mm_and_si128(libdivide_s64_signbits(x), y); - __m128i t2 = _mm_and_si128(libdivide_s64_signbits(y), x); - p = _mm_sub_epi64(p, t1); - p = _mm_sub_epi64(p, t2); - return p; -} - -////////// UINT32 - -__m128i libdivide_u32_do_vector(__m128i numers, const struct libdivide_u32_t *denom) { - uint8_t more = denom->more; - if (!denom->magic) { - return _mm_srli_epi32(numers, more); - } - else { - __m128i q = libdivide_mullhi_u32_vector(numers, _mm_set1_epi32(denom->magic)); - if (more & LIBDIVIDE_ADD_MARKER) { - // uint32_t t = ((numer - q) >> 1) + q; - // return t >> denom->shift; - uint32_t shift = more & LIBDIVIDE_32_SHIFT_MASK; - __m128i t = _mm_add_epi32(_mm_srli_epi32(_mm_sub_epi32(numers, q), 1), q); - return _mm_srli_epi32(t, shift); - } - else { - return _mm_srli_epi32(q, more); - } - } -} - -__m128i libdivide_u32_branchfree_do_vector(__m128i numers, const struct libdivide_u32_branchfree_t *denom) { - __m128i q = libdivide_mullhi_u32_vector(numers, _mm_set1_epi32(denom->magic)); - __m128i t = _mm_add_epi32(_mm_srli_epi32(_mm_sub_epi32(numers, q), 1), q); - return _mm_srli_epi32(t, denom->more); -} - -////////// UINT64 - -__m128i libdivide_u64_do_vector(__m128i numers, const struct libdivide_u64_t *denom) { - uint8_t more = denom->more; - if (!denom->magic) { - return _mm_srli_epi64(numers, more); - } - else { - __m128i q = libdivide_mullhi_u64_vector(numers, _mm_set1_epi64x(denom->magic)); - if (more & LIBDIVIDE_ADD_MARKER) { - // uint32_t t = ((numer - q) >> 1) + q; - // return t >> denom->shift; - uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK; - __m128i t = _mm_add_epi64(_mm_srli_epi64(_mm_sub_epi64(numers, q), 1), q); - return _mm_srli_epi64(t, shift); - } - else { - return _mm_srli_epi64(q, more); - } - } -} - -__m128i libdivide_u64_branchfree_do_vector(__m128i numers, const struct libdivide_u64_branchfree_t *denom) { - __m128i q = libdivide_mullhi_u64_vector(numers, _mm_set1_epi64x(denom->magic)); - __m128i t = _mm_add_epi64(_mm_srli_epi64(_mm_sub_epi64(numers, q), 1), q); - return _mm_srli_epi64(t, denom->more); -} - -////////// SINT32 - -__m128i libdivide_s32_do_vector(__m128i numers, const struct libdivide_s32_t *denom) { - uint8_t more = denom->more; - if (!denom->magic) { - uint32_t shift = more & LIBDIVIDE_32_SHIFT_MASK; - uint32_t mask = (1U << shift) - 1; - __m128i roundToZeroTweak = _mm_set1_epi32(mask); - // q = numer + ((numer >> 31) & roundToZeroTweak); - __m128i q = _mm_add_epi32(numers, _mm_and_si128(_mm_srai_epi32(numers, 31), roundToZeroTweak)); - q = _mm_srai_epi32(q, shift); - __m128i sign = _mm_set1_epi32((int8_t)more >> 7); - // q = (q ^ sign) - sign; - q = _mm_sub_epi32(_mm_xor_si128(q, sign), sign); - return q; - } - else { - __m128i q = libdivide_mullhi_s32_vector(numers, _mm_set1_epi32(denom->magic)); - if (more & LIBDIVIDE_ADD_MARKER) { - // must be arithmetic shift - __m128i sign = _mm_set1_epi32((int8_t)more >> 7); - // q += ((numer ^ sign) - sign); - q = _mm_add_epi32(q, _mm_sub_epi32(_mm_xor_si128(numers, sign), sign)); - } - // q >>= shift - q = _mm_srai_epi32(q, more & LIBDIVIDE_32_SHIFT_MASK); - q = _mm_add_epi32(q, _mm_srli_epi32(q, 31)); // q += (q < 0) - return q; - } -} - -__m128i libdivide_s32_branchfree_do_vector(__m128i numers, const struct libdivide_s32_branchfree_t *denom) { - int32_t magic = denom->magic; - uint8_t more = denom->more; - uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; - // must be arithmetic shift - __m128i sign = _mm_set1_epi32((int8_t)more >> 7); - __m128i q = libdivide_mullhi_s32_vector(numers, _mm_set1_epi32(magic)); - q = _mm_add_epi32(q, numers); // q += numers - - // If q is non-negative, we have nothing to do - // If q is negative, we want to add either (2**shift)-1 if d is - // a power of 2, or (2**shift) if it is not a power of 2 - uint32_t is_power_of_2 = (magic == 0); - __m128i q_sign = _mm_srai_epi32(q, 31); // q_sign = q >> 31 - __m128i mask = _mm_set1_epi32((1U << shift) - is_power_of_2); - q = _mm_add_epi32(q, _mm_and_si128(q_sign, mask)); // q = q + (q_sign & mask) - q = _mm_srai_epi32(q, shift); // q >>= shift - q = _mm_sub_epi32(_mm_xor_si128(q, sign), sign); // q = (q ^ sign) - sign - return q; -} - -////////// SINT64 - -__m128i libdivide_s64_do_vector(__m128i numers, const struct libdivide_s64_t *denom) { - uint8_t more = denom->more; - int64_t magic = denom->magic; - if (magic == 0) { // shift path - uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK; - uint64_t mask = (1ULL << shift) - 1; - __m128i roundToZeroTweak = _mm_set1_epi64x(mask); - // q = numer + ((numer >> 63) & roundToZeroTweak); - __m128i q = _mm_add_epi64(numers, _mm_and_si128(libdivide_s64_signbits(numers), roundToZeroTweak)); - q = libdivide_s64_shift_right_vector(q, shift); - __m128i sign = _mm_set1_epi32((int8_t)more >> 7); - // q = (q ^ sign) - sign; - q = _mm_sub_epi64(_mm_xor_si128(q, sign), sign); - return q; - } - else { - __m128i q = libdivide_mullhi_s64_vector(numers, _mm_set1_epi64x(magic)); - if (more & LIBDIVIDE_ADD_MARKER) { - // must be arithmetic shift - __m128i sign = _mm_set1_epi32((int8_t)more >> 7); - // q += ((numer ^ sign) - sign); - q = _mm_add_epi64(q, _mm_sub_epi64(_mm_xor_si128(numers, sign), sign)); - } - // q >>= denom->mult_path.shift - q = libdivide_s64_shift_right_vector(q, more & LIBDIVIDE_64_SHIFT_MASK); - q = _mm_add_epi64(q, _mm_srli_epi64(q, 63)); // q += (q < 0) - return q; - } -} - -__m128i libdivide_s64_branchfree_do_vector(__m128i numers, const struct libdivide_s64_branchfree_t *denom) { - int64_t magic = denom->magic; - uint8_t more = denom->more; - uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; - // must be arithmetic shift - __m128i sign = _mm_set1_epi32((int8_t)more >> 7); - - // libdivide_mullhi_s64(numers, magic); - __m128i q = libdivide_mullhi_s64_vector(numers, _mm_set1_epi64x(magic)); - q = _mm_add_epi64(q, numers); // q += numers - - // If q is non-negative, we have nothing to do. - // If q is negative, we want to add either (2**shift)-1 if d is - // a power of 2, or (2**shift) if it is not a power of 2. - uint32_t is_power_of_2 = (magic == 0); - __m128i q_sign = libdivide_s64_signbits(q); // q_sign = q >> 63 - __m128i mask = _mm_set1_epi64x((1ULL << shift) - is_power_of_2); - q = _mm_add_epi64(q, _mm_and_si128(q_sign, mask)); // q = q + (q_sign & mask) - q = libdivide_s64_shift_right_vector(q, shift); // q >>= shift - q = _mm_sub_epi64(_mm_xor_si128(q, sign), sign); // q = (q ^ sign) - sign - return q; -} - -#endif - -/////////// C++ stuff - -#ifdef __cplusplus - -// The C++ divider class is templated on both an integer type -// (like uint64_t) and an algorithm type. -// * BRANCHFULL is the default algorithm type. -// * BRANCHFREE is the branchfree algorithm type. -enum { - BRANCHFULL, - BRANCHFREE -}; - -#if defined(LIBDIVIDE_AVX512) - #define LIBDIVIDE_VECTOR_TYPE __m512i -#elif defined(LIBDIVIDE_AVX2) - #define LIBDIVIDE_VECTOR_TYPE __m256i -#elif defined(LIBDIVIDE_SSE2) - #define LIBDIVIDE_VECTOR_TYPE __m128i -#endif - -#if !defined(LIBDIVIDE_VECTOR_TYPE) - #define LIBDIVIDE_DIVIDE_VECTOR(ALGO) -#else - #define LIBDIVIDE_DIVIDE_VECTOR(ALGO) \ - LIBDIVIDE_VECTOR_TYPE divide(LIBDIVIDE_VECTOR_TYPE n) const { \ - return libdivide_##ALGO##_do_vector(n, &denom); \ - } -#endif - -// The DISPATCHER_GEN() macro generates C++ methods (for the given integer -// and algorithm types) that redirect to libdivide's C API. -#define DISPATCHER_GEN(T, ALGO) \ - libdivide_##ALGO##_t denom; \ - dispatcher() { } \ - dispatcher(T d) \ - : denom(libdivide_##ALGO##_gen(d)) \ - { } \ - T divide(T n) const { \ - return libdivide_##ALGO##_do(n, &denom); \ - } \ - LIBDIVIDE_DIVIDE_VECTOR(ALGO) \ - T recover() const { \ - return libdivide_##ALGO##_recover(&denom); \ - } - -// The dispatcher selects a specific division algorithm for a given -// type and ALGO using partial template specialization. -template struct dispatcher { }; - -template<> struct dispatcher { DISPATCHER_GEN(int32_t, s32) }; -template<> struct dispatcher { DISPATCHER_GEN(int32_t, s32_branchfree) }; -template<> struct dispatcher { DISPATCHER_GEN(uint32_t, u32) }; -template<> struct dispatcher { DISPATCHER_GEN(uint32_t, u32_branchfree) }; -template<> struct dispatcher { DISPATCHER_GEN(int64_t, s64) }; -template<> struct dispatcher { DISPATCHER_GEN(int64_t, s64_branchfree) }; -template<> struct dispatcher { DISPATCHER_GEN(uint64_t, u64) }; -template<> struct dispatcher { DISPATCHER_GEN(uint64_t, u64_branchfree) }; - -// This is the main divider class for use by the user (C++ API). -// The actual division algorithm is selected using the dispatcher struct -// based on the integer and algorithm template parameters. -template -class divider { -public: - // We leave the default constructor empty so that creating - // an array of dividers and then initializing them - // later doesn't slow us down. - divider() { } - - // Constructor that takes the divisor as a parameter - divider(T d) : div(d) { } - - // Divides n by the divisor - T divide(T n) const { - return div.divide(n); - } - - // Recovers the divisor, returns the value that was - // used to initialize this divider object. - T recover() const { - return div.recover(); - } - - bool operator==(const divider& other) const { - return div.denom.magic == other.denom.magic && - div.denom.more == other.denom.more; - } - - bool operator!=(const divider& other) const { - return !(*this == other); - } - -#if defined(LIBDIVIDE_VECTOR_TYPE) - // Treats the vector as packed integer values with the same type as - // the divider (e.g. s32, u32, s64, u64) and divides each of - // them by the divider, returning the packed quotients. - LIBDIVIDE_VECTOR_TYPE divide(LIBDIVIDE_VECTOR_TYPE n) const { - return div.divide(n); - } -#endif - -private: - // Storage for the actual divisor - dispatcher::value, - std::is_signed::value, sizeof(T), ALGO> div; -}; - -// Overload of operator / for scalar division -template -T operator/(T n, const divider& div) { - return div.divide(n); -} - -// Overload of operator /= for scalar division -template -T& operator/=(T& n, const divider& div) { - n = div.divide(n); - return n; -} - -#if defined(LIBDIVIDE_VECTOR_TYPE) - // Overload of operator / for vector division - template - LIBDIVIDE_VECTOR_TYPE operator/(LIBDIVIDE_VECTOR_TYPE n, const divider& div) { - return div.divide(n); - } - // Overload of operator /= for vector division - template - LIBDIVIDE_VECTOR_TYPE& operator/=(LIBDIVIDE_VECTOR_TYPE& n, const divider& div) { - n = div.divide(n); - return n; - } -#endif - -// libdivdie::branchfree_divider -template -using branchfree_divider = divider; - -} // namespace libdivide - -#endif // __cplusplus - -#endif // NUMPY_CORE_INCLUDE_NUMPY_LIBDIVIDE_LIBDIVIDE_H_ diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/testing/tests/test_utils.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/testing/tests/test_utils.py deleted file mode 100644 index 0aaa508ee5d2e194f44c756c94ae5b3db194292e..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/testing/tests/test_utils.py +++ /dev/null @@ -1,1626 +0,0 @@ -import warnings -import sys -import os -import itertools -import pytest -import weakref - -import numpy as np -from numpy.testing import ( - assert_equal, assert_array_equal, assert_almost_equal, - assert_array_almost_equal, assert_array_less, build_err_msg, - assert_raises, assert_warns, assert_no_warnings, assert_allclose, - assert_approx_equal, assert_array_almost_equal_nulp, assert_array_max_ulp, - clear_and_catch_warnings, suppress_warnings, assert_string_equal, assert_, - tempdir, temppath, assert_no_gc_cycles, HAS_REFCOUNT - ) - - -class _GenericTest: - - def _test_equal(self, a, b): - self._assert_func(a, b) - - def _test_not_equal(self, a, b): - with assert_raises(AssertionError): - self._assert_func(a, b) - - def test_array_rank1_eq(self): - """Test two equal array of rank 1 are found equal.""" - a = np.array([1, 2]) - b = np.array([1, 2]) - - self._test_equal(a, b) - - def test_array_rank1_noteq(self): - """Test two different array of rank 1 are found not equal.""" - a = np.array([1, 2]) - b = np.array([2, 2]) - - self._test_not_equal(a, b) - - def test_array_rank2_eq(self): - """Test two equal array of rank 2 are found equal.""" - a = np.array([[1, 2], [3, 4]]) - b = np.array([[1, 2], [3, 4]]) - - self._test_equal(a, b) - - def test_array_diffshape(self): - """Test two arrays with different shapes are found not equal.""" - a = np.array([1, 2]) - b = np.array([[1, 2], [1, 2]]) - - self._test_not_equal(a, b) - - def test_objarray(self): - """Test object arrays.""" - a = np.array([1, 1], dtype=object) - self._test_equal(a, 1) - - def test_array_likes(self): - self._test_equal([1, 2, 3], (1, 2, 3)) - - -class TestArrayEqual(_GenericTest): - - def setup_method(self): - self._assert_func = assert_array_equal - - def test_generic_rank1(self): - """Test rank 1 array for all dtypes.""" - def foo(t): - a = np.empty(2, t) - a.fill(1) - b = a.copy() - c = a.copy() - c.fill(0) - self._test_equal(a, b) - self._test_not_equal(c, b) - - # Test numeric types and object - for t in '?bhilqpBHILQPfdgFDG': - foo(t) - - # Test strings - for t in ['S1', 'U1']: - foo(t) - - def test_0_ndim_array(self): - x = np.array(473963742225900817127911193656584771) - y = np.array(18535119325151578301457182298393896) - assert_raises(AssertionError, self._assert_func, x, y) - - y = x - self._assert_func(x, y) - - x = np.array(43) - y = np.array(10) - assert_raises(AssertionError, self._assert_func, x, y) - - y = x - self._assert_func(x, y) - - def test_generic_rank3(self): - """Test rank 3 array for all dtypes.""" - def foo(t): - a = np.empty((4, 2, 3), t) - a.fill(1) - b = a.copy() - c = a.copy() - c.fill(0) - self._test_equal(a, b) - self._test_not_equal(c, b) - - # Test numeric types and object - for t in '?bhilqpBHILQPfdgFDG': - foo(t) - - # Test strings - for t in ['S1', 'U1']: - foo(t) - - def test_nan_array(self): - """Test arrays with nan values in them.""" - a = np.array([1, 2, np.nan]) - b = np.array([1, 2, np.nan]) - - self._test_equal(a, b) - - c = np.array([1, 2, 3]) - self._test_not_equal(c, b) - - def test_string_arrays(self): - """Test two arrays with different shapes are found not equal.""" - a = np.array(['floupi', 'floupa']) - b = np.array(['floupi', 'floupa']) - - self._test_equal(a, b) - - c = np.array(['floupipi', 'floupa']) - - self._test_not_equal(c, b) - - def test_recarrays(self): - """Test record arrays.""" - a = np.empty(2, [('floupi', float), ('floupa', float)]) - a['floupi'] = [1, 2] - a['floupa'] = [1, 2] - b = a.copy() - - self._test_equal(a, b) - - c = np.empty(2, [('floupipi', float), - ('floupi', float), ('floupa', float)]) - c['floupipi'] = a['floupi'].copy() - c['floupa'] = a['floupa'].copy() - - with pytest.raises(TypeError): - self._test_not_equal(c, b) - - def test_masked_nan_inf(self): - # Regression test for gh-11121 - a = np.ma.MaskedArray([3., 4., 6.5], mask=[False, True, False]) - b = np.array([3., np.nan, 6.5]) - self._test_equal(a, b) - self._test_equal(b, a) - a = np.ma.MaskedArray([3., 4., 6.5], mask=[True, False, False]) - b = np.array([np.inf, 4., 6.5]) - self._test_equal(a, b) - self._test_equal(b, a) - - def test_subclass_that_overrides_eq(self): - # While we cannot guarantee testing functions will always work for - # subclasses, the tests should ideally rely only on subclasses having - # comparison operators, not on them being able to store booleans - # (which, e.g., astropy Quantity cannot usefully do). See gh-8452. - class MyArray(np.ndarray): - def __eq__(self, other): - return bool(np.equal(self, other).all()) - - def __ne__(self, other): - return not self == other - - a = np.array([1., 2.]).view(MyArray) - b = np.array([2., 3.]).view(MyArray) - assert_(type(a == a), bool) - assert_(a == a) - assert_(a != b) - self._test_equal(a, a) - self._test_not_equal(a, b) - self._test_not_equal(b, a) - - def test_subclass_that_does_not_implement_npall(self): - class MyArray(np.ndarray): - def __array_function__(self, *args, **kwargs): - return NotImplemented - - a = np.array([1., 2.]).view(MyArray) - b = np.array([2., 3.]).view(MyArray) - with assert_raises(TypeError): - np.all(a) - self._test_equal(a, a) - self._test_not_equal(a, b) - self._test_not_equal(b, a) - - def test_suppress_overflow_warnings(self): - # Based on issue #18992 - with pytest.raises(AssertionError): - with np.errstate(all="raise"): - np.testing.assert_array_equal( - np.array([1, 2, 3], np.float32), - np.array([1, 1e-40, 3], np.float32)) - - def test_array_vs_scalar_is_equal(self): - """Test comparing an array with a scalar when all values are equal.""" - a = np.array([1., 1., 1.]) - b = 1. - - self._test_equal(a, b) - - def test_array_vs_scalar_not_equal(self): - """Test comparing an array with a scalar when not all values equal.""" - a = np.array([1., 2., 3.]) - b = 1. - - self._test_not_equal(a, b) - - def test_array_vs_scalar_strict(self): - """Test comparing an array with a scalar with strict option.""" - a = np.array([1., 1., 1.]) - b = 1. - - with pytest.raises(AssertionError): - assert_array_equal(a, b, strict=True) - - def test_array_vs_array_strict(self): - """Test comparing two arrays with strict option.""" - a = np.array([1., 1., 1.]) - b = np.array([1., 1., 1.]) - - assert_array_equal(a, b, strict=True) - - def test_array_vs_float_array_strict(self): - """Test comparing two arrays with strict option.""" - a = np.array([1, 1, 1]) - b = np.array([1., 1., 1.]) - - with pytest.raises(AssertionError): - assert_array_equal(a, b, strict=True) - - -class TestBuildErrorMessage: - - def test_build_err_msg_defaults(self): - x = np.array([1.00001, 2.00002, 3.00003]) - y = np.array([1.00002, 2.00003, 3.00004]) - err_msg = 'There is a mismatch' - - a = build_err_msg([x, y], err_msg) - b = ('\nItems are not equal: There is a mismatch\n ACTUAL: array([' - '1.00001, 2.00002, 3.00003])\n DESIRED: array([1.00002, ' - '2.00003, 3.00004])') - assert_equal(a, b) - - def test_build_err_msg_no_verbose(self): - x = np.array([1.00001, 2.00002, 3.00003]) - y = np.array([1.00002, 2.00003, 3.00004]) - err_msg = 'There is a mismatch' - - a = build_err_msg([x, y], err_msg, verbose=False) - b = '\nItems are not equal: There is a mismatch' - assert_equal(a, b) - - def test_build_err_msg_custom_names(self): - x = np.array([1.00001, 2.00002, 3.00003]) - y = np.array([1.00002, 2.00003, 3.00004]) - err_msg = 'There is a mismatch' - - a = build_err_msg([x, y], err_msg, names=('FOO', 'BAR')) - b = ('\nItems are not equal: There is a mismatch\n FOO: array([' - '1.00001, 2.00002, 3.00003])\n BAR: array([1.00002, 2.00003, ' - '3.00004])') - assert_equal(a, b) - - def test_build_err_msg_custom_precision(self): - x = np.array([1.000000001, 2.00002, 3.00003]) - y = np.array([1.000000002, 2.00003, 3.00004]) - err_msg = 'There is a mismatch' - - a = build_err_msg([x, y], err_msg, precision=10) - b = ('\nItems are not equal: There is a mismatch\n ACTUAL: array([' - '1.000000001, 2.00002 , 3.00003 ])\n DESIRED: array([' - '1.000000002, 2.00003 , 3.00004 ])') - assert_equal(a, b) - - -class TestEqual(TestArrayEqual): - - def setup_method(self): - self._assert_func = assert_equal - - def test_nan_items(self): - self._assert_func(np.nan, np.nan) - self._assert_func([np.nan], [np.nan]) - self._test_not_equal(np.nan, [np.nan]) - self._test_not_equal(np.nan, 1) - - def test_inf_items(self): - self._assert_func(np.inf, np.inf) - self._assert_func([np.inf], [np.inf]) - self._test_not_equal(np.inf, [np.inf]) - - def test_datetime(self): - self._test_equal( - np.datetime64("2017-01-01", "s"), - np.datetime64("2017-01-01", "s") - ) - self._test_equal( - np.datetime64("2017-01-01", "s"), - np.datetime64("2017-01-01", "m") - ) - - # gh-10081 - self._test_not_equal( - np.datetime64("2017-01-01", "s"), - np.datetime64("2017-01-02", "s") - ) - self._test_not_equal( - np.datetime64("2017-01-01", "s"), - np.datetime64("2017-01-02", "m") - ) - - def test_nat_items(self): - # not a datetime - nadt_no_unit = np.datetime64("NaT") - nadt_s = np.datetime64("NaT", "s") - nadt_d = np.datetime64("NaT", "ns") - # not a timedelta - natd_no_unit = np.timedelta64("NaT") - natd_s = np.timedelta64("NaT", "s") - natd_d = np.timedelta64("NaT", "ns") - - dts = [nadt_no_unit, nadt_s, nadt_d] - tds = [natd_no_unit, natd_s, natd_d] - for a, b in itertools.product(dts, dts): - self._assert_func(a, b) - self._assert_func([a], [b]) - self._test_not_equal([a], b) - - for a, b in itertools.product(tds, tds): - self._assert_func(a, b) - self._assert_func([a], [b]) - self._test_not_equal([a], b) - - for a, b in itertools.product(tds, dts): - self._test_not_equal(a, b) - self._test_not_equal(a, [b]) - self._test_not_equal([a], [b]) - self._test_not_equal([a], np.datetime64("2017-01-01", "s")) - self._test_not_equal([b], np.datetime64("2017-01-01", "s")) - self._test_not_equal([a], np.timedelta64(123, "s")) - self._test_not_equal([b], np.timedelta64(123, "s")) - - def test_non_numeric(self): - self._assert_func('ab', 'ab') - self._test_not_equal('ab', 'abb') - - def test_complex_item(self): - self._assert_func(complex(1, 2), complex(1, 2)) - self._assert_func(complex(1, np.nan), complex(1, np.nan)) - self._test_not_equal(complex(1, np.nan), complex(1, 2)) - self._test_not_equal(complex(np.nan, 1), complex(1, np.nan)) - self._test_not_equal(complex(np.nan, np.inf), complex(np.nan, 2)) - - def test_negative_zero(self): - self._test_not_equal(np.PZERO, np.NZERO) - - def test_complex(self): - x = np.array([complex(1, 2), complex(1, np.nan)]) - y = np.array([complex(1, 2), complex(1, 2)]) - self._assert_func(x, x) - self._test_not_equal(x, y) - - def test_object(self): - #gh-12942 - import datetime - a = np.array([datetime.datetime(2000, 1, 1), - datetime.datetime(2000, 1, 2)]) - self._test_not_equal(a, a[::-1]) - - -class TestArrayAlmostEqual(_GenericTest): - - def setup_method(self): - self._assert_func = assert_array_almost_equal - - def test_closeness(self): - # Note that in the course of time we ended up with - # `abs(x - y) < 1.5 * 10**(-decimal)` - # instead of the previously documented - # `abs(x - y) < 0.5 * 10**(-decimal)` - # so this check serves to preserve the wrongness. - - # test scalars - self._assert_func(1.499999, 0.0, decimal=0) - assert_raises(AssertionError, - lambda: self._assert_func(1.5, 0.0, decimal=0)) - - # test arrays - self._assert_func([1.499999], [0.0], decimal=0) - assert_raises(AssertionError, - lambda: self._assert_func([1.5], [0.0], decimal=0)) - - def test_simple(self): - x = np.array([1234.2222]) - y = np.array([1234.2223]) - - self._assert_func(x, y, decimal=3) - self._assert_func(x, y, decimal=4) - assert_raises(AssertionError, - lambda: self._assert_func(x, y, decimal=5)) - - def test_nan(self): - anan = np.array([np.nan]) - aone = np.array([1]) - ainf = np.array([np.inf]) - self._assert_func(anan, anan) - assert_raises(AssertionError, - lambda: self._assert_func(anan, aone)) - assert_raises(AssertionError, - lambda: self._assert_func(anan, ainf)) - assert_raises(AssertionError, - lambda: self._assert_func(ainf, anan)) - - def test_inf(self): - a = np.array([[1., 2.], [3., 4.]]) - b = a.copy() - a[0, 0] = np.inf - assert_raises(AssertionError, - lambda: self._assert_func(a, b)) - b[0, 0] = -np.inf - assert_raises(AssertionError, - lambda: self._assert_func(a, b)) - - def test_subclass(self): - a = np.array([[1., 2.], [3., 4.]]) - b = np.ma.masked_array([[1., 2.], [0., 4.]], - [[False, False], [True, False]]) - self._assert_func(a, b) - self._assert_func(b, a) - self._assert_func(b, b) - - # Test fully masked as well (see gh-11123). - a = np.ma.MaskedArray(3.5, mask=True) - b = np.array([3., 4., 6.5]) - self._test_equal(a, b) - self._test_equal(b, a) - a = np.ma.masked - b = np.array([3., 4., 6.5]) - self._test_equal(a, b) - self._test_equal(b, a) - a = np.ma.MaskedArray([3., 4., 6.5], mask=[True, True, True]) - b = np.array([1., 2., 3.]) - self._test_equal(a, b) - self._test_equal(b, a) - a = np.ma.MaskedArray([3., 4., 6.5], mask=[True, True, True]) - b = np.array(1.) - self._test_equal(a, b) - self._test_equal(b, a) - - def test_subclass_that_cannot_be_bool(self): - # While we cannot guarantee testing functions will always work for - # subclasses, the tests should ideally rely only on subclasses having - # comparison operators, not on them being able to store booleans - # (which, e.g., astropy Quantity cannot usefully do). See gh-8452. - class MyArray(np.ndarray): - def __eq__(self, other): - return super().__eq__(other).view(np.ndarray) - - def __lt__(self, other): - return super().__lt__(other).view(np.ndarray) - - def all(self, *args, **kwargs): - raise NotImplementedError - - a = np.array([1., 2.]).view(MyArray) - self._assert_func(a, a) - - -class TestAlmostEqual(_GenericTest): - - def setup_method(self): - self._assert_func = assert_almost_equal - - def test_closeness(self): - # Note that in the course of time we ended up with - # `abs(x - y) < 1.5 * 10**(-decimal)` - # instead of the previously documented - # `abs(x - y) < 0.5 * 10**(-decimal)` - # so this check serves to preserve the wrongness. - - # test scalars - self._assert_func(1.499999, 0.0, decimal=0) - assert_raises(AssertionError, - lambda: self._assert_func(1.5, 0.0, decimal=0)) - - # test arrays - self._assert_func([1.499999], [0.0], decimal=0) - assert_raises(AssertionError, - lambda: self._assert_func([1.5], [0.0], decimal=0)) - - def test_nan_item(self): - self._assert_func(np.nan, np.nan) - assert_raises(AssertionError, - lambda: self._assert_func(np.nan, 1)) - assert_raises(AssertionError, - lambda: self._assert_func(np.nan, np.inf)) - assert_raises(AssertionError, - lambda: self._assert_func(np.inf, np.nan)) - - def test_inf_item(self): - self._assert_func(np.inf, np.inf) - self._assert_func(-np.inf, -np.inf) - assert_raises(AssertionError, - lambda: self._assert_func(np.inf, 1)) - assert_raises(AssertionError, - lambda: self._assert_func(-np.inf, np.inf)) - - def test_simple_item(self): - self._test_not_equal(1, 2) - - def test_complex_item(self): - self._assert_func(complex(1, 2), complex(1, 2)) - self._assert_func(complex(1, np.nan), complex(1, np.nan)) - self._assert_func(complex(np.inf, np.nan), complex(np.inf, np.nan)) - self._test_not_equal(complex(1, np.nan), complex(1, 2)) - self._test_not_equal(complex(np.nan, 1), complex(1, np.nan)) - self._test_not_equal(complex(np.nan, np.inf), complex(np.nan, 2)) - - def test_complex(self): - x = np.array([complex(1, 2), complex(1, np.nan)]) - z = np.array([complex(1, 2), complex(np.nan, 1)]) - y = np.array([complex(1, 2), complex(1, 2)]) - self._assert_func(x, x) - self._test_not_equal(x, y) - self._test_not_equal(x, z) - - def test_error_message(self): - """Check the message is formatted correctly for the decimal value. - Also check the message when input includes inf or nan (gh12200)""" - x = np.array([1.00000000001, 2.00000000002, 3.00003]) - y = np.array([1.00000000002, 2.00000000003, 3.00004]) - - # Test with a different amount of decimal digits - with pytest.raises(AssertionError) as exc_info: - self._assert_func(x, y, decimal=12) - msgs = str(exc_info.value).split('\n') - assert_equal(msgs[3], 'Mismatched elements: 3 / 3 (100%)') - assert_equal(msgs[4], 'Max absolute difference: 1.e-05') - assert_equal(msgs[5], 'Max relative difference: 3.33328889e-06') - assert_equal( - msgs[6], - ' x: array([1.00000000001, 2.00000000002, 3.00003 ])') - assert_equal( - msgs[7], - ' y: array([1.00000000002, 2.00000000003, 3.00004 ])') - - # With the default value of decimal digits, only the 3rd element - # differs. Note that we only check for the formatting of the arrays - # themselves. - with pytest.raises(AssertionError) as exc_info: - self._assert_func(x, y) - msgs = str(exc_info.value).split('\n') - assert_equal(msgs[3], 'Mismatched elements: 1 / 3 (33.3%)') - assert_equal(msgs[4], 'Max absolute difference: 1.e-05') - assert_equal(msgs[5], 'Max relative difference: 3.33328889e-06') - assert_equal(msgs[6], ' x: array([1. , 2. , 3.00003])') - assert_equal(msgs[7], ' y: array([1. , 2. , 3.00004])') - - # Check the error message when input includes inf - x = np.array([np.inf, 0]) - y = np.array([np.inf, 1]) - with pytest.raises(AssertionError) as exc_info: - self._assert_func(x, y) - msgs = str(exc_info.value).split('\n') - assert_equal(msgs[3], 'Mismatched elements: 1 / 2 (50%)') - assert_equal(msgs[4], 'Max absolute difference: 1.') - assert_equal(msgs[5], 'Max relative difference: 1.') - assert_equal(msgs[6], ' x: array([inf, 0.])') - assert_equal(msgs[7], ' y: array([inf, 1.])') - - # Check the error message when dividing by zero - x = np.array([1, 2]) - y = np.array([0, 0]) - with pytest.raises(AssertionError) as exc_info: - self._assert_func(x, y) - msgs = str(exc_info.value).split('\n') - assert_equal(msgs[3], 'Mismatched elements: 2 / 2 (100%)') - assert_equal(msgs[4], 'Max absolute difference: 2') - assert_equal(msgs[5], 'Max relative difference: inf') - - def test_error_message_2(self): - """Check the message is formatted correctly when either x or y is a scalar.""" - x = 2 - y = np.ones(20) - with pytest.raises(AssertionError) as exc_info: - self._assert_func(x, y) - msgs = str(exc_info.value).split('\n') - assert_equal(msgs[3], 'Mismatched elements: 20 / 20 (100%)') - assert_equal(msgs[4], 'Max absolute difference: 1.') - assert_equal(msgs[5], 'Max relative difference: 1.') - - y = 2 - x = np.ones(20) - with pytest.raises(AssertionError) as exc_info: - self._assert_func(x, y) - msgs = str(exc_info.value).split('\n') - assert_equal(msgs[3], 'Mismatched elements: 20 / 20 (100%)') - assert_equal(msgs[4], 'Max absolute difference: 1.') - assert_equal(msgs[5], 'Max relative difference: 0.5') - - def test_subclass_that_cannot_be_bool(self): - # While we cannot guarantee testing functions will always work for - # subclasses, the tests should ideally rely only on subclasses having - # comparison operators, not on them being able to store booleans - # (which, e.g., astropy Quantity cannot usefully do). See gh-8452. - class MyArray(np.ndarray): - def __eq__(self, other): - return super().__eq__(other).view(np.ndarray) - - def __lt__(self, other): - return super().__lt__(other).view(np.ndarray) - - def all(self, *args, **kwargs): - raise NotImplementedError - - a = np.array([1., 2.]).view(MyArray) - self._assert_func(a, a) - - -class TestApproxEqual: - - def setup_method(self): - self._assert_func = assert_approx_equal - - def test_simple_0d_arrays(self): - x = np.array(1234.22) - y = np.array(1234.23) - - self._assert_func(x, y, significant=5) - self._assert_func(x, y, significant=6) - assert_raises(AssertionError, - lambda: self._assert_func(x, y, significant=7)) - - def test_simple_items(self): - x = 1234.22 - y = 1234.23 - - self._assert_func(x, y, significant=4) - self._assert_func(x, y, significant=5) - self._assert_func(x, y, significant=6) - assert_raises(AssertionError, - lambda: self._assert_func(x, y, significant=7)) - - def test_nan_array(self): - anan = np.array(np.nan) - aone = np.array(1) - ainf = np.array(np.inf) - self._assert_func(anan, anan) - assert_raises(AssertionError, lambda: self._assert_func(anan, aone)) - assert_raises(AssertionError, lambda: self._assert_func(anan, ainf)) - assert_raises(AssertionError, lambda: self._assert_func(ainf, anan)) - - def test_nan_items(self): - anan = np.array(np.nan) - aone = np.array(1) - ainf = np.array(np.inf) - self._assert_func(anan, anan) - assert_raises(AssertionError, lambda: self._assert_func(anan, aone)) - assert_raises(AssertionError, lambda: self._assert_func(anan, ainf)) - assert_raises(AssertionError, lambda: self._assert_func(ainf, anan)) - - -class TestArrayAssertLess: - - def setup_method(self): - self._assert_func = assert_array_less - - def test_simple_arrays(self): - x = np.array([1.1, 2.2]) - y = np.array([1.2, 2.3]) - - self._assert_func(x, y) - assert_raises(AssertionError, lambda: self._assert_func(y, x)) - - y = np.array([1.0, 2.3]) - - assert_raises(AssertionError, lambda: self._assert_func(x, y)) - assert_raises(AssertionError, lambda: self._assert_func(y, x)) - - def test_rank2(self): - x = np.array([[1.1, 2.2], [3.3, 4.4]]) - y = np.array([[1.2, 2.3], [3.4, 4.5]]) - - self._assert_func(x, y) - assert_raises(AssertionError, lambda: self._assert_func(y, x)) - - y = np.array([[1.0, 2.3], [3.4, 4.5]]) - - assert_raises(AssertionError, lambda: self._assert_func(x, y)) - assert_raises(AssertionError, lambda: self._assert_func(y, x)) - - def test_rank3(self): - x = np.ones(shape=(2, 2, 2)) - y = np.ones(shape=(2, 2, 2))+1 - - self._assert_func(x, y) - assert_raises(AssertionError, lambda: self._assert_func(y, x)) - - y[0, 0, 0] = 0 - - assert_raises(AssertionError, lambda: self._assert_func(x, y)) - assert_raises(AssertionError, lambda: self._assert_func(y, x)) - - def test_simple_items(self): - x = 1.1 - y = 2.2 - - self._assert_func(x, y) - assert_raises(AssertionError, lambda: self._assert_func(y, x)) - - y = np.array([2.2, 3.3]) - - self._assert_func(x, y) - assert_raises(AssertionError, lambda: self._assert_func(y, x)) - - y = np.array([1.0, 3.3]) - - assert_raises(AssertionError, lambda: self._assert_func(x, y)) - - def test_nan_noncompare(self): - anan = np.array(np.nan) - aone = np.array(1) - ainf = np.array(np.inf) - self._assert_func(anan, anan) - assert_raises(AssertionError, lambda: self._assert_func(aone, anan)) - assert_raises(AssertionError, lambda: self._assert_func(anan, aone)) - assert_raises(AssertionError, lambda: self._assert_func(anan, ainf)) - assert_raises(AssertionError, lambda: self._assert_func(ainf, anan)) - - def test_nan_noncompare_array(self): - x = np.array([1.1, 2.2, 3.3]) - anan = np.array(np.nan) - - assert_raises(AssertionError, lambda: self._assert_func(x, anan)) - assert_raises(AssertionError, lambda: self._assert_func(anan, x)) - - x = np.array([1.1, 2.2, np.nan]) - - assert_raises(AssertionError, lambda: self._assert_func(x, anan)) - assert_raises(AssertionError, lambda: self._assert_func(anan, x)) - - y = np.array([1.0, 2.0, np.nan]) - - self._assert_func(y, x) - assert_raises(AssertionError, lambda: self._assert_func(x, y)) - - def test_inf_compare(self): - aone = np.array(1) - ainf = np.array(np.inf) - - self._assert_func(aone, ainf) - self._assert_func(-ainf, aone) - self._assert_func(-ainf, ainf) - assert_raises(AssertionError, lambda: self._assert_func(ainf, aone)) - assert_raises(AssertionError, lambda: self._assert_func(aone, -ainf)) - assert_raises(AssertionError, lambda: self._assert_func(ainf, ainf)) - assert_raises(AssertionError, lambda: self._assert_func(ainf, -ainf)) - assert_raises(AssertionError, lambda: self._assert_func(-ainf, -ainf)) - - def test_inf_compare_array(self): - x = np.array([1.1, 2.2, np.inf]) - ainf = np.array(np.inf) - - assert_raises(AssertionError, lambda: self._assert_func(x, ainf)) - assert_raises(AssertionError, lambda: self._assert_func(ainf, x)) - assert_raises(AssertionError, lambda: self._assert_func(x, -ainf)) - assert_raises(AssertionError, lambda: self._assert_func(-x, -ainf)) - assert_raises(AssertionError, lambda: self._assert_func(-ainf, -x)) - self._assert_func(-ainf, x) - - -class TestWarns: - - def test_warn(self): - def f(): - warnings.warn("yo") - return 3 - - before_filters = sys.modules['warnings'].filters[:] - assert_equal(assert_warns(UserWarning, f), 3) - after_filters = sys.modules['warnings'].filters - - assert_raises(AssertionError, assert_no_warnings, f) - assert_equal(assert_no_warnings(lambda x: x, 1), 1) - - # Check that the warnings state is unchanged - assert_equal(before_filters, after_filters, - "assert_warns does not preserver warnings state") - - def test_context_manager(self): - - before_filters = sys.modules['warnings'].filters[:] - with assert_warns(UserWarning): - warnings.warn("yo") - after_filters = sys.modules['warnings'].filters - - def no_warnings(): - with assert_no_warnings(): - warnings.warn("yo") - - assert_raises(AssertionError, no_warnings) - assert_equal(before_filters, after_filters, - "assert_warns does not preserver warnings state") - - def test_warn_wrong_warning(self): - def f(): - warnings.warn("yo", DeprecationWarning) - - failed = False - with warnings.catch_warnings(): - warnings.simplefilter("error", DeprecationWarning) - try: - # Should raise a DeprecationWarning - assert_warns(UserWarning, f) - failed = True - except DeprecationWarning: - pass - - if failed: - raise AssertionError("wrong warning caught by assert_warn") - - -class TestAssertAllclose: - - def test_simple(self): - x = 1e-3 - y = 1e-9 - - assert_allclose(x, y, atol=1) - assert_raises(AssertionError, assert_allclose, x, y) - - a = np.array([x, y, x, y]) - b = np.array([x, y, x, x]) - - assert_allclose(a, b, atol=1) - assert_raises(AssertionError, assert_allclose, a, b) - - b[-1] = y * (1 + 1e-8) - assert_allclose(a, b) - assert_raises(AssertionError, assert_allclose, a, b, rtol=1e-9) - - assert_allclose(6, 10, rtol=0.5) - assert_raises(AssertionError, assert_allclose, 10, 6, rtol=0.5) - - def test_min_int(self): - a = np.array([np.iinfo(np.int_).min], dtype=np.int_) - # Should not raise: - assert_allclose(a, a) - - def test_report_fail_percentage(self): - a = np.array([1, 1, 1, 1]) - b = np.array([1, 1, 1, 2]) - - with pytest.raises(AssertionError) as exc_info: - assert_allclose(a, b) - msg = str(exc_info.value) - assert_('Mismatched elements: 1 / 4 (25%)\n' - 'Max absolute difference: 1\n' - 'Max relative difference: 0.5' in msg) - - def test_equal_nan(self): - a = np.array([np.nan]) - b = np.array([np.nan]) - # Should not raise: - assert_allclose(a, b, equal_nan=True) - - def test_not_equal_nan(self): - a = np.array([np.nan]) - b = np.array([np.nan]) - assert_raises(AssertionError, assert_allclose, a, b, equal_nan=False) - - def test_equal_nan_default(self): - # Make sure equal_nan default behavior remains unchanged. (All - # of these functions use assert_array_compare under the hood.) - # None of these should raise. - a = np.array([np.nan]) - b = np.array([np.nan]) - assert_array_equal(a, b) - assert_array_almost_equal(a, b) - assert_array_less(a, b) - assert_allclose(a, b) - - def test_report_max_relative_error(self): - a = np.array([0, 1]) - b = np.array([0, 2]) - - with pytest.raises(AssertionError) as exc_info: - assert_allclose(a, b) - msg = str(exc_info.value) - assert_('Max relative difference: 0.5' in msg) - - def test_timedelta(self): - # see gh-18286 - a = np.array([[1, 2, 3, "NaT"]], dtype="m8[ns]") - assert_allclose(a, a) - - def test_error_message_unsigned(self): - """Check the the message is formatted correctly when overflow can occur - (gh21768)""" - # Ensure to test for potential overflow in the case of: - # x - y - # and - # y - x - x = np.asarray([0, 1, 8], dtype='uint8') - y = np.asarray([4, 4, 4], dtype='uint8') - with pytest.raises(AssertionError) as exc_info: - assert_allclose(x, y, atol=3) - msgs = str(exc_info.value).split('\n') - assert_equal(msgs[4], 'Max absolute difference: 4') - - -class TestArrayAlmostEqualNulp: - - def test_float64_pass(self): - # The number of units of least precision - # In this case, use a few places above the lowest level (ie nulp=1) - nulp = 5 - x = np.linspace(-20, 20, 50, dtype=np.float64) - x = 10**x - x = np.r_[-x, x] - - # Addition - eps = np.finfo(x.dtype).eps - y = x + x*eps*nulp/2. - assert_array_almost_equal_nulp(x, y, nulp) - - # Subtraction - epsneg = np.finfo(x.dtype).epsneg - y = x - x*epsneg*nulp/2. - assert_array_almost_equal_nulp(x, y, nulp) - - def test_float64_fail(self): - nulp = 5 - x = np.linspace(-20, 20, 50, dtype=np.float64) - x = 10**x - x = np.r_[-x, x] - - eps = np.finfo(x.dtype).eps - y = x + x*eps*nulp*2. - assert_raises(AssertionError, assert_array_almost_equal_nulp, - x, y, nulp) - - epsneg = np.finfo(x.dtype).epsneg - y = x - x*epsneg*nulp*2. - assert_raises(AssertionError, assert_array_almost_equal_nulp, - x, y, nulp) - - def test_float64_ignore_nan(self): - # Ignore ULP differences between various NAN's - # Note that MIPS may reverse quiet and signaling nans - # so we use the builtin version as a base. - offset = np.uint64(0xffffffff) - nan1_i64 = np.array(np.nan, dtype=np.float64).view(np.uint64) - nan2_i64 = nan1_i64 ^ offset # nan payload on MIPS is all ones. - nan1_f64 = nan1_i64.view(np.float64) - nan2_f64 = nan2_i64.view(np.float64) - assert_array_max_ulp(nan1_f64, nan2_f64, 0) - - def test_float32_pass(self): - nulp = 5 - x = np.linspace(-20, 20, 50, dtype=np.float32) - x = 10**x - x = np.r_[-x, x] - - eps = np.finfo(x.dtype).eps - y = x + x*eps*nulp/2. - assert_array_almost_equal_nulp(x, y, nulp) - - epsneg = np.finfo(x.dtype).epsneg - y = x - x*epsneg*nulp/2. - assert_array_almost_equal_nulp(x, y, nulp) - - def test_float32_fail(self): - nulp = 5 - x = np.linspace(-20, 20, 50, dtype=np.float32) - x = 10**x - x = np.r_[-x, x] - - eps = np.finfo(x.dtype).eps - y = x + x*eps*nulp*2. - assert_raises(AssertionError, assert_array_almost_equal_nulp, - x, y, nulp) - - epsneg = np.finfo(x.dtype).epsneg - y = x - x*epsneg*nulp*2. - assert_raises(AssertionError, assert_array_almost_equal_nulp, - x, y, nulp) - - def test_float32_ignore_nan(self): - # Ignore ULP differences between various NAN's - # Note that MIPS may reverse quiet and signaling nans - # so we use the builtin version as a base. - offset = np.uint32(0xffff) - nan1_i32 = np.array(np.nan, dtype=np.float32).view(np.uint32) - nan2_i32 = nan1_i32 ^ offset # nan payload on MIPS is all ones. - nan1_f32 = nan1_i32.view(np.float32) - nan2_f32 = nan2_i32.view(np.float32) - assert_array_max_ulp(nan1_f32, nan2_f32, 0) - - def test_float16_pass(self): - nulp = 5 - x = np.linspace(-4, 4, 10, dtype=np.float16) - x = 10**x - x = np.r_[-x, x] - - eps = np.finfo(x.dtype).eps - y = x + x*eps*nulp/2. - assert_array_almost_equal_nulp(x, y, nulp) - - epsneg = np.finfo(x.dtype).epsneg - y = x - x*epsneg*nulp/2. - assert_array_almost_equal_nulp(x, y, nulp) - - def test_float16_fail(self): - nulp = 5 - x = np.linspace(-4, 4, 10, dtype=np.float16) - x = 10**x - x = np.r_[-x, x] - - eps = np.finfo(x.dtype).eps - y = x + x*eps*nulp*2. - assert_raises(AssertionError, assert_array_almost_equal_nulp, - x, y, nulp) - - epsneg = np.finfo(x.dtype).epsneg - y = x - x*epsneg*nulp*2. - assert_raises(AssertionError, assert_array_almost_equal_nulp, - x, y, nulp) - - def test_float16_ignore_nan(self): - # Ignore ULP differences between various NAN's - # Note that MIPS may reverse quiet and signaling nans - # so we use the builtin version as a base. - offset = np.uint16(0xff) - nan1_i16 = np.array(np.nan, dtype=np.float16).view(np.uint16) - nan2_i16 = nan1_i16 ^ offset # nan payload on MIPS is all ones. - nan1_f16 = nan1_i16.view(np.float16) - nan2_f16 = nan2_i16.view(np.float16) - assert_array_max_ulp(nan1_f16, nan2_f16, 0) - - def test_complex128_pass(self): - nulp = 5 - x = np.linspace(-20, 20, 50, dtype=np.float64) - x = 10**x - x = np.r_[-x, x] - xi = x + x*1j - - eps = np.finfo(x.dtype).eps - y = x + x*eps*nulp/2. - assert_array_almost_equal_nulp(xi, x + y*1j, nulp) - assert_array_almost_equal_nulp(xi, y + x*1j, nulp) - # The test condition needs to be at least a factor of sqrt(2) smaller - # because the real and imaginary parts both change - y = x + x*eps*nulp/4. - assert_array_almost_equal_nulp(xi, y + y*1j, nulp) - - epsneg = np.finfo(x.dtype).epsneg - y = x - x*epsneg*nulp/2. - assert_array_almost_equal_nulp(xi, x + y*1j, nulp) - assert_array_almost_equal_nulp(xi, y + x*1j, nulp) - y = x - x*epsneg*nulp/4. - assert_array_almost_equal_nulp(xi, y + y*1j, nulp) - - def test_complex128_fail(self): - nulp = 5 - x = np.linspace(-20, 20, 50, dtype=np.float64) - x = 10**x - x = np.r_[-x, x] - xi = x + x*1j - - eps = np.finfo(x.dtype).eps - y = x + x*eps*nulp*2. - assert_raises(AssertionError, assert_array_almost_equal_nulp, - xi, x + y*1j, nulp) - assert_raises(AssertionError, assert_array_almost_equal_nulp, - xi, y + x*1j, nulp) - # The test condition needs to be at least a factor of sqrt(2) smaller - # because the real and imaginary parts both change - y = x + x*eps*nulp - assert_raises(AssertionError, assert_array_almost_equal_nulp, - xi, y + y*1j, nulp) - - epsneg = np.finfo(x.dtype).epsneg - y = x - x*epsneg*nulp*2. - assert_raises(AssertionError, assert_array_almost_equal_nulp, - xi, x + y*1j, nulp) - assert_raises(AssertionError, assert_array_almost_equal_nulp, - xi, y + x*1j, nulp) - y = x - x*epsneg*nulp - assert_raises(AssertionError, assert_array_almost_equal_nulp, - xi, y + y*1j, nulp) - - def test_complex64_pass(self): - nulp = 5 - x = np.linspace(-20, 20, 50, dtype=np.float32) - x = 10**x - x = np.r_[-x, x] - xi = x + x*1j - - eps = np.finfo(x.dtype).eps - y = x + x*eps*nulp/2. - assert_array_almost_equal_nulp(xi, x + y*1j, nulp) - assert_array_almost_equal_nulp(xi, y + x*1j, nulp) - y = x + x*eps*nulp/4. - assert_array_almost_equal_nulp(xi, y + y*1j, nulp) - - epsneg = np.finfo(x.dtype).epsneg - y = x - x*epsneg*nulp/2. - assert_array_almost_equal_nulp(xi, x + y*1j, nulp) - assert_array_almost_equal_nulp(xi, y + x*1j, nulp) - y = x - x*epsneg*nulp/4. - assert_array_almost_equal_nulp(xi, y + y*1j, nulp) - - def test_complex64_fail(self): - nulp = 5 - x = np.linspace(-20, 20, 50, dtype=np.float32) - x = 10**x - x = np.r_[-x, x] - xi = x + x*1j - - eps = np.finfo(x.dtype).eps - y = x + x*eps*nulp*2. - assert_raises(AssertionError, assert_array_almost_equal_nulp, - xi, x + y*1j, nulp) - assert_raises(AssertionError, assert_array_almost_equal_nulp, - xi, y + x*1j, nulp) - y = x + x*eps*nulp - assert_raises(AssertionError, assert_array_almost_equal_nulp, - xi, y + y*1j, nulp) - - epsneg = np.finfo(x.dtype).epsneg - y = x - x*epsneg*nulp*2. - assert_raises(AssertionError, assert_array_almost_equal_nulp, - xi, x + y*1j, nulp) - assert_raises(AssertionError, assert_array_almost_equal_nulp, - xi, y + x*1j, nulp) - y = x - x*epsneg*nulp - assert_raises(AssertionError, assert_array_almost_equal_nulp, - xi, y + y*1j, nulp) - - -class TestULP: - - def test_equal(self): - x = np.random.randn(10) - assert_array_max_ulp(x, x, maxulp=0) - - def test_single(self): - # Generate 1 + small deviation, check that adding eps gives a few UNL - x = np.ones(10).astype(np.float32) - x += 0.01 * np.random.randn(10).astype(np.float32) - eps = np.finfo(np.float32).eps - assert_array_max_ulp(x, x+eps, maxulp=20) - - def test_double(self): - # Generate 1 + small deviation, check that adding eps gives a few UNL - x = np.ones(10).astype(np.float64) - x += 0.01 * np.random.randn(10).astype(np.float64) - eps = np.finfo(np.float64).eps - assert_array_max_ulp(x, x+eps, maxulp=200) - - def test_inf(self): - for dt in [np.float32, np.float64]: - inf = np.array([np.inf]).astype(dt) - big = np.array([np.finfo(dt).max]) - assert_array_max_ulp(inf, big, maxulp=200) - - def test_nan(self): - # Test that nan is 'far' from small, tiny, inf, max and min - for dt in [np.float32, np.float64]: - if dt == np.float32: - maxulp = 1e6 - else: - maxulp = 1e12 - inf = np.array([np.inf]).astype(dt) - nan = np.array([np.nan]).astype(dt) - big = np.array([np.finfo(dt).max]) - tiny = np.array([np.finfo(dt).tiny]) - zero = np.array([np.PZERO]).astype(dt) - nzero = np.array([np.NZERO]).astype(dt) - assert_raises(AssertionError, - lambda: assert_array_max_ulp(nan, inf, - maxulp=maxulp)) - assert_raises(AssertionError, - lambda: assert_array_max_ulp(nan, big, - maxulp=maxulp)) - assert_raises(AssertionError, - lambda: assert_array_max_ulp(nan, tiny, - maxulp=maxulp)) - assert_raises(AssertionError, - lambda: assert_array_max_ulp(nan, zero, - maxulp=maxulp)) - assert_raises(AssertionError, - lambda: assert_array_max_ulp(nan, nzero, - maxulp=maxulp)) - - -class TestStringEqual: - def test_simple(self): - assert_string_equal("hello", "hello") - assert_string_equal("hello\nmultiline", "hello\nmultiline") - - with pytest.raises(AssertionError) as exc_info: - assert_string_equal("foo\nbar", "hello\nbar") - msg = str(exc_info.value) - assert_equal(msg, "Differences in strings:\n- foo\n+ hello") - - assert_raises(AssertionError, - lambda: assert_string_equal("foo", "hello")) - - def test_regex(self): - assert_string_equal("a+*b", "a+*b") - - assert_raises(AssertionError, - lambda: assert_string_equal("aaa", "a+b")) - - -def assert_warn_len_equal(mod, n_in_context): - try: - mod_warns = mod.__warningregistry__ - except AttributeError: - # the lack of a __warningregistry__ - # attribute means that no warning has - # occurred; this can be triggered in - # a parallel test scenario, while in - # a serial test scenario an initial - # warning (and therefore the attribute) - # are always created first - mod_warns = {} - - num_warns = len(mod_warns) - - if 'version' in mod_warns: - # Python 3 adds a 'version' entry to the registry, - # do not count it. - num_warns -= 1 - - assert_equal(num_warns, n_in_context) - - -def test_warn_len_equal_call_scenarios(): - # assert_warn_len_equal is called under - # varying circumstances depending on serial - # vs. parallel test scenarios; this test - # simply aims to probe both code paths and - # check that no assertion is uncaught - - # parallel scenario -- no warning issued yet - class mod: - pass - - mod_inst = mod() - - assert_warn_len_equal(mod=mod_inst, - n_in_context=0) - - # serial test scenario -- the __warningregistry__ - # attribute should be present - class mod: - def __init__(self): - self.__warningregistry__ = {'warning1':1, - 'warning2':2} - - mod_inst = mod() - assert_warn_len_equal(mod=mod_inst, - n_in_context=2) - - -def _get_fresh_mod(): - # Get this module, with warning registry empty - my_mod = sys.modules[__name__] - try: - my_mod.__warningregistry__.clear() - except AttributeError: - # will not have a __warningregistry__ unless warning has been - # raised in the module at some point - pass - return my_mod - - -def test_clear_and_catch_warnings(): - # Initial state of module, no warnings - my_mod = _get_fresh_mod() - assert_equal(getattr(my_mod, '__warningregistry__', {}), {}) - with clear_and_catch_warnings(modules=[my_mod]): - warnings.simplefilter('ignore') - warnings.warn('Some warning') - assert_equal(my_mod.__warningregistry__, {}) - # Without specified modules, don't clear warnings during context. - # catch_warnings doesn't make an entry for 'ignore'. - with clear_and_catch_warnings(): - warnings.simplefilter('ignore') - warnings.warn('Some warning') - assert_warn_len_equal(my_mod, 0) - - # Manually adding two warnings to the registry: - my_mod.__warningregistry__ = {'warning1': 1, - 'warning2': 2} - - # Confirm that specifying module keeps old warning, does not add new - with clear_and_catch_warnings(modules=[my_mod]): - warnings.simplefilter('ignore') - warnings.warn('Another warning') - assert_warn_len_equal(my_mod, 2) - - # Another warning, no module spec it clears up registry - with clear_and_catch_warnings(): - warnings.simplefilter('ignore') - warnings.warn('Another warning') - assert_warn_len_equal(my_mod, 0) - - -def test_suppress_warnings_module(): - # Initial state of module, no warnings - my_mod = _get_fresh_mod() - assert_equal(getattr(my_mod, '__warningregistry__', {}), {}) - - def warn_other_module(): - # Apply along axis is implemented in python; stacklevel=2 means - # we end up inside its module, not ours. - def warn(arr): - warnings.warn("Some warning 2", stacklevel=2) - return arr - np.apply_along_axis(warn, 0, [0]) - - # Test module based warning suppression: - assert_warn_len_equal(my_mod, 0) - with suppress_warnings() as sup: - sup.record(UserWarning) - # suppress warning from other module (may have .pyc ending), - # if apply_along_axis is moved, had to be changed. - sup.filter(module=np.lib.shape_base) - warnings.warn("Some warning") - warn_other_module() - # Check that the suppression did test the file correctly (this module - # got filtered) - assert_equal(len(sup.log), 1) - assert_equal(sup.log[0].message.args[0], "Some warning") - assert_warn_len_equal(my_mod, 0) - sup = suppress_warnings() - # Will have to be changed if apply_along_axis is moved: - sup.filter(module=my_mod) - with sup: - warnings.warn('Some warning') - assert_warn_len_equal(my_mod, 0) - # And test repeat works: - sup.filter(module=my_mod) - with sup: - warnings.warn('Some warning') - assert_warn_len_equal(my_mod, 0) - - # Without specified modules - with suppress_warnings(): - warnings.simplefilter('ignore') - warnings.warn('Some warning') - assert_warn_len_equal(my_mod, 0) - - -def test_suppress_warnings_type(): - # Initial state of module, no warnings - my_mod = _get_fresh_mod() - assert_equal(getattr(my_mod, '__warningregistry__', {}), {}) - - # Test module based warning suppression: - with suppress_warnings() as sup: - sup.filter(UserWarning) - warnings.warn('Some warning') - assert_warn_len_equal(my_mod, 0) - sup = suppress_warnings() - sup.filter(UserWarning) - with sup: - warnings.warn('Some warning') - assert_warn_len_equal(my_mod, 0) - # And test repeat works: - sup.filter(module=my_mod) - with sup: - warnings.warn('Some warning') - assert_warn_len_equal(my_mod, 0) - - # Without specified modules - with suppress_warnings(): - warnings.simplefilter('ignore') - warnings.warn('Some warning') - assert_warn_len_equal(my_mod, 0) - - -def test_suppress_warnings_decorate_no_record(): - sup = suppress_warnings() - sup.filter(UserWarning) - - @sup - def warn(category): - warnings.warn('Some warning', category) - - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter("always") - warn(UserWarning) # should be supppressed - warn(RuntimeWarning) - assert_equal(len(w), 1) - - -def test_suppress_warnings_record(): - sup = suppress_warnings() - log1 = sup.record() - - with sup: - log2 = sup.record(message='Some other warning 2') - sup.filter(message='Some warning') - warnings.warn('Some warning') - warnings.warn('Some other warning') - warnings.warn('Some other warning 2') - - assert_equal(len(sup.log), 2) - assert_equal(len(log1), 1) - assert_equal(len(log2),1) - assert_equal(log2[0].message.args[0], 'Some other warning 2') - - # Do it again, with the same context to see if some warnings survived: - with sup: - log2 = sup.record(message='Some other warning 2') - sup.filter(message='Some warning') - warnings.warn('Some warning') - warnings.warn('Some other warning') - warnings.warn('Some other warning 2') - - assert_equal(len(sup.log), 2) - assert_equal(len(log1), 1) - assert_equal(len(log2), 1) - assert_equal(log2[0].message.args[0], 'Some other warning 2') - - # Test nested: - with suppress_warnings() as sup: - sup.record() - with suppress_warnings() as sup2: - sup2.record(message='Some warning') - warnings.warn('Some warning') - warnings.warn('Some other warning') - assert_equal(len(sup2.log), 1) - assert_equal(len(sup.log), 1) - - -def test_suppress_warnings_forwarding(): - def warn_other_module(): - # Apply along axis is implemented in python; stacklevel=2 means - # we end up inside its module, not ours. - def warn(arr): - warnings.warn("Some warning", stacklevel=2) - return arr - np.apply_along_axis(warn, 0, [0]) - - with suppress_warnings() as sup: - sup.record() - with suppress_warnings("always"): - for i in range(2): - warnings.warn("Some warning") - - assert_equal(len(sup.log), 2) - - with suppress_warnings() as sup: - sup.record() - with suppress_warnings("location"): - for i in range(2): - warnings.warn("Some warning") - warnings.warn("Some warning") - - assert_equal(len(sup.log), 2) - - with suppress_warnings() as sup: - sup.record() - with suppress_warnings("module"): - for i in range(2): - warnings.warn("Some warning") - warnings.warn("Some warning") - warn_other_module() - - assert_equal(len(sup.log), 2) - - with suppress_warnings() as sup: - sup.record() - with suppress_warnings("once"): - for i in range(2): - warnings.warn("Some warning") - warnings.warn("Some other warning") - warn_other_module() - - assert_equal(len(sup.log), 2) - - -def test_tempdir(): - with tempdir() as tdir: - fpath = os.path.join(tdir, 'tmp') - with open(fpath, 'w'): - pass - assert_(not os.path.isdir(tdir)) - - raised = False - try: - with tempdir() as tdir: - raise ValueError() - except ValueError: - raised = True - assert_(raised) - assert_(not os.path.isdir(tdir)) - - -def test_temppath(): - with temppath() as fpath: - with open(fpath, 'w'): - pass - assert_(not os.path.isfile(fpath)) - - raised = False - try: - with temppath() as fpath: - raise ValueError() - except ValueError: - raised = True - assert_(raised) - assert_(not os.path.isfile(fpath)) - - -class my_cacw(clear_and_catch_warnings): - - class_modules = (sys.modules[__name__],) - - -def test_clear_and_catch_warnings_inherit(): - # Test can subclass and add default modules - my_mod = _get_fresh_mod() - with my_cacw(): - warnings.simplefilter('ignore') - warnings.warn('Some warning') - assert_equal(my_mod.__warningregistry__, {}) - - -@pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts") -class TestAssertNoGcCycles: - """ Test assert_no_gc_cycles """ - def test_passes(self): - def no_cycle(): - b = [] - b.append([]) - return b - - with assert_no_gc_cycles(): - no_cycle() - - assert_no_gc_cycles(no_cycle) - - def test_asserts(self): - def make_cycle(): - a = [] - a.append(a) - a.append(a) - return a - - with assert_raises(AssertionError): - with assert_no_gc_cycles(): - make_cycle() - - with assert_raises(AssertionError): - assert_no_gc_cycles(make_cycle) - - @pytest.mark.slow - def test_fails(self): - """ - Test that in cases where the garbage cannot be collected, we raise an - error, instead of hanging forever trying to clear it. - """ - - class ReferenceCycleInDel: - """ - An object that not only contains a reference cycle, but creates new - cycles whenever it's garbage-collected and its __del__ runs - """ - make_cycle = True - - def __init__(self): - self.cycle = self - - def __del__(self): - # break the current cycle so that `self` can be freed - self.cycle = None - - if ReferenceCycleInDel.make_cycle: - # but create a new one so that the garbage collector has more - # work to do. - ReferenceCycleInDel() - - try: - w = weakref.ref(ReferenceCycleInDel()) - try: - with assert_raises(RuntimeError): - # this will be unable to get a baseline empty garbage - assert_no_gc_cycles(lambda: None) - except AssertionError: - # the above test is only necessary if the GC actually tried to free - # our object anyway, which python 2.7 does not. - if w() is not None: - pytest.skip("GC does not call __del__ on cyclic objects") - raise - - finally: - # make sure that we stop creating reference cycles - ReferenceCycleInDel.make_cycle = False diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/typing/tests/data/pass/index_tricks.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/typing/tests/data/pass/index_tricks.py deleted file mode 100644 index 4c4c1195990accd61c3cba9c5684185038dfa17e..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/typing/tests/data/pass/index_tricks.py +++ /dev/null @@ -1,64 +0,0 @@ -from __future__ import annotations -from typing import Any -import numpy as np - -AR_LIKE_b = [[True, True], [True, True]] -AR_LIKE_i = [[1, 2], [3, 4]] -AR_LIKE_f = [[1.0, 2.0], [3.0, 4.0]] -AR_LIKE_U = [["1", "2"], ["3", "4"]] - -AR_i8: np.ndarray[Any, np.dtype[np.int64]] = np.array(AR_LIKE_i, dtype=np.int64) - -np.ndenumerate(AR_i8) -np.ndenumerate(AR_LIKE_f) -np.ndenumerate(AR_LIKE_U) - -np.ndenumerate(AR_i8).iter -np.ndenumerate(AR_LIKE_f).iter -np.ndenumerate(AR_LIKE_U).iter - -next(np.ndenumerate(AR_i8)) -next(np.ndenumerate(AR_LIKE_f)) -next(np.ndenumerate(AR_LIKE_U)) - -iter(np.ndenumerate(AR_i8)) -iter(np.ndenumerate(AR_LIKE_f)) -iter(np.ndenumerate(AR_LIKE_U)) - -iter(np.ndindex(1, 2, 3)) -next(np.ndindex(1, 2, 3)) - -np.unravel_index([22, 41, 37], (7, 6)) -np.unravel_index([31, 41, 13], (7, 6), order='F') -np.unravel_index(1621, (6, 7, 8, 9)) - -np.ravel_multi_index(AR_LIKE_i, (7, 6)) -np.ravel_multi_index(AR_LIKE_i, (7, 6), order='F') -np.ravel_multi_index(AR_LIKE_i, (4, 6), mode='clip') -np.ravel_multi_index(AR_LIKE_i, (4, 4), mode=('clip', 'wrap')) -np.ravel_multi_index((3, 1, 4, 1), (6, 7, 8, 9)) - -np.mgrid[1:1:2] -np.mgrid[1:1:2, None:10] - -np.ogrid[1:1:2] -np.ogrid[1:1:2, None:10] - -np.index_exp[0:1] -np.index_exp[0:1, None:3] -np.index_exp[0, 0:1, ..., [0, 1, 3]] - -np.s_[0:1] -np.s_[0:1, None:3] -np.s_[0, 0:1, ..., [0, 1, 3]] - -np.ix_(AR_LIKE_b[0]) -np.ix_(AR_LIKE_i[0], AR_LIKE_f[0]) -np.ix_(AR_i8[0]) - -np.fill_diagonal(AR_i8, 5) - -np.diag_indices(4) -np.diag_indices(2, 3) - -np.diag_indices_from(AR_i8) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/groupby/transform/test_numba.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/groupby/transform/test_numba.py deleted file mode 100644 index 61fcc930f116a7e9a5fefde0885f92b9b489d343..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/groupby/transform/test_numba.py +++ /dev/null @@ -1,284 +0,0 @@ -import numpy as np -import pytest - -from pandas.errors import NumbaUtilError - -from pandas import ( - DataFrame, - Series, - option_context, -) -import pandas._testing as tm - -pytestmark = pytest.mark.single_cpu - - -def test_correct_function_signature(): - pytest.importorskip("numba") - - def incorrect_function(x): - return x + 1 - - data = DataFrame( - {"key": ["a", "a", "b", "b", "a"], "data": [1.0, 2.0, 3.0, 4.0, 5.0]}, - columns=["key", "data"], - ) - with pytest.raises(NumbaUtilError, match="The first 2"): - data.groupby("key").transform(incorrect_function, engine="numba") - - with pytest.raises(NumbaUtilError, match="The first 2"): - data.groupby("key")["data"].transform(incorrect_function, engine="numba") - - -def test_check_nopython_kwargs(): - pytest.importorskip("numba") - - def incorrect_function(values, index): - return values + 1 - - data = DataFrame( - {"key": ["a", "a", "b", "b", "a"], "data": [1.0, 2.0, 3.0, 4.0, 5.0]}, - columns=["key", "data"], - ) - with pytest.raises(NumbaUtilError, match="numba does not support"): - data.groupby("key").transform(incorrect_function, engine="numba", a=1) - - with pytest.raises(NumbaUtilError, match="numba does not support"): - data.groupby("key")["data"].transform(incorrect_function, engine="numba", a=1) - - -@pytest.mark.filterwarnings("ignore") -# Filter warnings when parallel=True and the function can't be parallelized by Numba -@pytest.mark.parametrize("jit", [True, False]) -@pytest.mark.parametrize("pandas_obj", ["Series", "DataFrame"]) -@pytest.mark.parametrize("as_index", [True, False]) -def test_numba_vs_cython(jit, pandas_obj, nogil, parallel, nopython, as_index): - pytest.importorskip("numba") - - def func(values, index): - return values + 1 - - if jit: - # Test accepted jitted functions - import numba - - func = numba.jit(func) - - data = DataFrame( - {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] - ) - engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} - grouped = data.groupby(0, as_index=as_index) - if pandas_obj == "Series": - grouped = grouped[1] - - result = grouped.transform(func, engine="numba", engine_kwargs=engine_kwargs) - expected = grouped.transform(lambda x: x + 1, engine="cython") - - tm.assert_equal(result, expected) - - -@pytest.mark.filterwarnings("ignore") -# Filter warnings when parallel=True and the function can't be parallelized by Numba -@pytest.mark.parametrize("jit", [True, False]) -@pytest.mark.parametrize("pandas_obj", ["Series", "DataFrame"]) -def test_cache(jit, pandas_obj, nogil, parallel, nopython): - # Test that the functions are cached correctly if we switch functions - pytest.importorskip("numba") - - def func_1(values, index): - return values + 1 - - def func_2(values, index): - return values * 5 - - if jit: - import numba - - func_1 = numba.jit(func_1) - func_2 = numba.jit(func_2) - - data = DataFrame( - {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] - ) - engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} - grouped = data.groupby(0) - if pandas_obj == "Series": - grouped = grouped[1] - - result = grouped.transform(func_1, engine="numba", engine_kwargs=engine_kwargs) - expected = grouped.transform(lambda x: x + 1, engine="cython") - tm.assert_equal(result, expected) - - result = grouped.transform(func_2, engine="numba", engine_kwargs=engine_kwargs) - expected = grouped.transform(lambda x: x * 5, engine="cython") - tm.assert_equal(result, expected) - - # Retest func_1 which should use the cache - result = grouped.transform(func_1, engine="numba", engine_kwargs=engine_kwargs) - expected = grouped.transform(lambda x: x + 1, engine="cython") - tm.assert_equal(result, expected) - - -def test_use_global_config(): - pytest.importorskip("numba") - - def func_1(values, index): - return values + 1 - - data = DataFrame( - {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] - ) - grouped = data.groupby(0) - expected = grouped.transform(func_1, engine="numba") - with option_context("compute.use_numba", True): - result = grouped.transform(func_1, engine=None) - tm.assert_frame_equal(expected, result) - - -# TODO: Test more than just reductions (e.g. actually test transformations once we have -@pytest.mark.parametrize( - "agg_func", [["min", "max"], "min", {"B": ["min", "max"], "C": "sum"}] -) -def test_string_cython_vs_numba(agg_func, numba_supported_reductions): - pytest.importorskip("numba") - agg_func, kwargs = numba_supported_reductions - data = DataFrame( - {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] - ) - grouped = data.groupby(0) - - result = grouped.transform(agg_func, engine="numba", **kwargs) - expected = grouped.transform(agg_func, engine="cython", **kwargs) - tm.assert_frame_equal(result, expected) - - result = grouped[1].transform(agg_func, engine="numba", **kwargs) - expected = grouped[1].transform(agg_func, engine="cython", **kwargs) - tm.assert_series_equal(result, expected) - - -def test_args_not_cached(): - # GH 41647 - pytest.importorskip("numba") - - def sum_last(values, index, n): - return values[-n:].sum() - - df = DataFrame({"id": [0, 0, 1, 1], "x": [1, 1, 1, 1]}) - grouped_x = df.groupby("id")["x"] - result = grouped_x.transform(sum_last, 1, engine="numba") - expected = Series([1.0] * 4, name="x") - tm.assert_series_equal(result, expected) - - result = grouped_x.transform(sum_last, 2, engine="numba") - expected = Series([2.0] * 4, name="x") - tm.assert_series_equal(result, expected) - - -def test_index_data_correctly_passed(): - # GH 43133 - pytest.importorskip("numba") - - def f(values, index): - return index - 1 - - df = DataFrame({"group": ["A", "A", "B"], "v": [4, 5, 6]}, index=[-1, -2, -3]) - result = df.groupby("group").transform(f, engine="numba") - expected = DataFrame([-4.0, -3.0, -2.0], columns=["v"], index=[-1, -2, -3]) - tm.assert_frame_equal(result, expected) - - -def test_engine_kwargs_not_cached(): - # If the user passes a different set of engine_kwargs don't return the same - # jitted function - pytest.importorskip("numba") - nogil = True - parallel = False - nopython = True - - def func_kwargs(values, index): - return nogil + parallel + nopython - - engine_kwargs = {"nopython": nopython, "nogil": nogil, "parallel": parallel} - df = DataFrame({"value": [0, 0, 0]}) - result = df.groupby(level=0).transform( - func_kwargs, engine="numba", engine_kwargs=engine_kwargs - ) - expected = DataFrame({"value": [2.0, 2.0, 2.0]}) - tm.assert_frame_equal(result, expected) - - nogil = False - engine_kwargs = {"nopython": nopython, "nogil": nogil, "parallel": parallel} - result = df.groupby(level=0).transform( - func_kwargs, engine="numba", engine_kwargs=engine_kwargs - ) - expected = DataFrame({"value": [1.0, 1.0, 1.0]}) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.filterwarnings("ignore") -def test_multiindex_one_key(nogil, parallel, nopython): - pytest.importorskip("numba") - - def numba_func(values, index): - return 1 - - df = DataFrame([{"A": 1, "B": 2, "C": 3}]).set_index(["A", "B"]) - engine_kwargs = {"nopython": nopython, "nogil": nogil, "parallel": parallel} - result = df.groupby("A").transform( - numba_func, engine="numba", engine_kwargs=engine_kwargs - ) - expected = DataFrame([{"A": 1, "B": 2, "C": 1.0}]).set_index(["A", "B"]) - tm.assert_frame_equal(result, expected) - - -def test_multiindex_multi_key_not_supported(nogil, parallel, nopython): - pytest.importorskip("numba") - - def numba_func(values, index): - return 1 - - df = DataFrame([{"A": 1, "B": 2, "C": 3}]).set_index(["A", "B"]) - engine_kwargs = {"nopython": nopython, "nogil": nogil, "parallel": parallel} - with pytest.raises(NotImplementedError, match="more than 1 grouping labels"): - df.groupby(["A", "B"]).transform( - numba_func, engine="numba", engine_kwargs=engine_kwargs - ) - - -def test_multilabel_numba_vs_cython(numba_supported_reductions): - pytest.importorskip("numba") - reduction, kwargs = numba_supported_reductions - df = DataFrame( - { - "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], - "B": ["one", "one", "two", "three", "two", "two", "one", "three"], - "C": np.random.default_rng(2).standard_normal(8), - "D": np.random.default_rng(2).standard_normal(8), - } - ) - gb = df.groupby(["A", "B"]) - res_agg = gb.transform(reduction, engine="numba", **kwargs) - expected_agg = gb.transform(reduction, engine="cython", **kwargs) - tm.assert_frame_equal(res_agg, expected_agg) - - -def test_multilabel_udf_numba_vs_cython(): - pytest.importorskip("numba") - df = DataFrame( - { - "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], - "B": ["one", "one", "two", "three", "two", "two", "one", "three"], - "C": np.random.default_rng(2).standard_normal(8), - "D": np.random.default_rng(2).standard_normal(8), - } - ) - gb = df.groupby(["A", "B"]) - result = gb.transform( - lambda values, index: (values - values.min()) / (values.max() - values.min()), - engine="numba", - ) - expected = gb.transform( - lambda x: (x - x.min()) / (x.max() - x.min()), engine="cython" - ) - tm.assert_frame_equal(result, expected) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/series/methods/test_dropna.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/series/methods/test_dropna.py deleted file mode 100644 index 1a7c27929d405841967b60612371bf1dc5dc67a9..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/series/methods/test_dropna.py +++ /dev/null @@ -1,113 +0,0 @@ -import numpy as np -import pytest - -from pandas import ( - DatetimeIndex, - IntervalIndex, - NaT, - Period, - Series, - Timestamp, -) -import pandas._testing as tm - - -class TestDropna: - def test_dropna_empty(self): - ser = Series([], dtype=object) - - assert len(ser.dropna()) == 0 - return_value = ser.dropna(inplace=True) - assert return_value is None - assert len(ser) == 0 - - # invalid axis - msg = "No axis named 1 for object type Series" - with pytest.raises(ValueError, match=msg): - ser.dropna(axis=1) - - def test_dropna_preserve_name(self, datetime_series): - datetime_series[:5] = np.nan - result = datetime_series.dropna() - assert result.name == datetime_series.name - name = datetime_series.name - ts = datetime_series.copy() - return_value = ts.dropna(inplace=True) - assert return_value is None - assert ts.name == name - - def test_dropna_no_nan(self): - for ser in [ - Series([1, 2, 3], name="x"), - Series([False, True, False], name="x"), - ]: - result = ser.dropna() - tm.assert_series_equal(result, ser) - assert result is not ser - - s2 = ser.copy() - return_value = s2.dropna(inplace=True) - assert return_value is None - tm.assert_series_equal(s2, ser) - - def test_dropna_intervals(self): - ser = Series( - [np.nan, 1, 2, 3], - IntervalIndex.from_arrays([np.nan, 0, 1, 2], [np.nan, 1, 2, 3]), - ) - - result = ser.dropna() - expected = ser.iloc[1:] - tm.assert_series_equal(result, expected) - - def test_dropna_period_dtype(self): - # GH#13737 - ser = Series([Period("2011-01", freq="M"), Period("NaT", freq="M")]) - result = ser.dropna() - expected = Series([Period("2011-01", freq="M")]) - - tm.assert_series_equal(result, expected) - - def test_datetime64_tz_dropna(self): - # DatetimeLikeBlock - ser = Series( - [ - Timestamp("2011-01-01 10:00"), - NaT, - Timestamp("2011-01-03 10:00"), - NaT, - ] - ) - result = ser.dropna() - expected = Series( - [Timestamp("2011-01-01 10:00"), Timestamp("2011-01-03 10:00")], index=[0, 2] - ) - tm.assert_series_equal(result, expected) - - # DatetimeTZBlock - idx = DatetimeIndex( - ["2011-01-01 10:00", NaT, "2011-01-03 10:00", NaT], tz="Asia/Tokyo" - ) - ser = Series(idx) - assert ser.dtype == "datetime64[ns, Asia/Tokyo]" - result = ser.dropna() - expected = Series( - [ - Timestamp("2011-01-01 10:00", tz="Asia/Tokyo"), - Timestamp("2011-01-03 10:00", tz="Asia/Tokyo"), - ], - index=[0, 2], - ) - assert result.dtype == "datetime64[ns, Asia/Tokyo]" - tm.assert_series_equal(result, expected) - - @pytest.mark.parametrize("val", [1, 1.5]) - def test_dropna_ignore_index(self, val): - # GH#31725 - ser = Series([1, 2, val], index=[3, 2, 1]) - result = ser.dropna(ignore_index=True) - expected = Series([1, 2, val]) - tm.assert_series_equal(result, expected) - - ser.dropna(ignore_index=True, inplace=True) - tm.assert_series_equal(ser, expected) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_internal/commands/__init__.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_internal/commands/__init__.py deleted file mode 100644 index c72f24f30e2924c415cf45cdb8628c3cb6ecfd5d..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_internal/commands/__init__.py +++ /dev/null @@ -1,127 +0,0 @@ -""" -Package containing all pip commands -""" - -import importlib -from collections import namedtuple -from typing import Any, Dict, Optional - -from pip._internal.cli.base_command import Command - -CommandInfo = namedtuple("CommandInfo", "module_path, class_name, summary") - -# This dictionary does a bunch of heavy lifting for help output: -# - Enables avoiding additional (costly) imports for presenting `--help`. -# - The ordering matters for help display. -# -# Even though the module path starts with the same "pip._internal.commands" -# prefix, the full path makes testing easier (specifically when modifying -# `commands_dict` in test setup / teardown). -commands_dict: Dict[str, CommandInfo] = { - "install": CommandInfo( - "pip._internal.commands.install", - "InstallCommand", - "Install packages.", - ), - "download": CommandInfo( - "pip._internal.commands.download", - "DownloadCommand", - "Download packages.", - ), - "uninstall": CommandInfo( - "pip._internal.commands.uninstall", - "UninstallCommand", - "Uninstall packages.", - ), - "freeze": CommandInfo( - "pip._internal.commands.freeze", - "FreezeCommand", - "Output installed packages in requirements format.", - ), - "list": CommandInfo( - "pip._internal.commands.list", - "ListCommand", - "List installed packages.", - ), - "show": CommandInfo( - "pip._internal.commands.show", - "ShowCommand", - "Show information about installed packages.", - ), - "check": CommandInfo( - "pip._internal.commands.check", - "CheckCommand", - "Verify installed packages have compatible dependencies.", - ), - "config": CommandInfo( - "pip._internal.commands.configuration", - "ConfigurationCommand", - "Manage local and global configuration.", - ), - "search": CommandInfo( - "pip._internal.commands.search", - "SearchCommand", - "Search PyPI for packages.", - ), - "cache": CommandInfo( - "pip._internal.commands.cache", - "CacheCommand", - "Inspect and manage pip's wheel cache.", - ), - "index": CommandInfo( - "pip._internal.commands.index", - "IndexCommand", - "Inspect information available from package indexes.", - ), - "wheel": CommandInfo( - "pip._internal.commands.wheel", - "WheelCommand", - "Build wheels from your requirements.", - ), - "hash": CommandInfo( - "pip._internal.commands.hash", - "HashCommand", - "Compute hashes of package archives.", - ), - "completion": CommandInfo( - "pip._internal.commands.completion", - "CompletionCommand", - "A helper command used for command completion.", - ), - "debug": CommandInfo( - "pip._internal.commands.debug", - "DebugCommand", - "Show information useful for debugging.", - ), - "help": CommandInfo( - "pip._internal.commands.help", - "HelpCommand", - "Show help for commands.", - ), -} - - -def create_command(name: str, **kwargs: Any) -> Command: - """ - Create an instance of the Command class with the given name. - """ - module_path, class_name, summary = commands_dict[name] - module = importlib.import_module(module_path) - command_class = getattr(module, class_name) - command = command_class(name=name, summary=summary, **kwargs) - - return command - - -def get_similar_commands(name: str) -> Optional[str]: - """Command name auto-correct.""" - from difflib import get_close_matches - - name = name.lower() - - close_commands = get_close_matches(name, commands_dict.keys()) - - if close_commands: - return close_commands[0] - else: - return None diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_vendor/distlib/util.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_vendor/distlib/util.py deleted file mode 100644 index 80bfc864bcb4aec4e40127cf5c336432f0378f09..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_vendor/distlib/util.py +++ /dev/null @@ -1,1969 +0,0 @@ -# -# Copyright (C) 2012-2021 The Python Software Foundation. -# See LICENSE.txt and CONTRIBUTORS.txt. -# -import codecs -from collections import deque -import contextlib -import csv -from glob import iglob as std_iglob -import io -import json -import logging -import os -import py_compile -import re -import socket -try: - import ssl -except ImportError: # pragma: no cover - ssl = None -import subprocess -import sys -import tarfile -import tempfile -import textwrap - -try: - import threading -except ImportError: # pragma: no cover - import dummy_threading as threading -import time - -from . import DistlibException -from .compat import (string_types, text_type, shutil, raw_input, StringIO, - cache_from_source, urlopen, urljoin, httplib, xmlrpclib, - splittype, HTTPHandler, BaseConfigurator, valid_ident, - Container, configparser, URLError, ZipFile, fsdecode, - unquote, urlparse) - -logger = logging.getLogger(__name__) - -# -# Requirement parsing code as per PEP 508 -# - -IDENTIFIER = re.compile(r'^([\w\.-]+)\s*') -VERSION_IDENTIFIER = re.compile(r'^([\w\.*+-]+)\s*') -COMPARE_OP = re.compile(r'^(<=?|>=?|={2,3}|[~!]=)\s*') -MARKER_OP = re.compile(r'^((<=?)|(>=?)|={2,3}|[~!]=|in|not\s+in)\s*') -OR = re.compile(r'^or\b\s*') -AND = re.compile(r'^and\b\s*') -NON_SPACE = re.compile(r'(\S+)\s*') -STRING_CHUNK = re.compile(r'([\s\w\.{}()*+#:;,/?!~`@$%^&=|<>\[\]-]+)') - - -def parse_marker(marker_string): - """ - Parse a marker string and return a dictionary containing a marker expression. - - The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in - the expression grammar, or strings. A string contained in quotes is to be - interpreted as a literal string, and a string not contained in quotes is a - variable (such as os_name). - """ - def marker_var(remaining): - # either identifier, or literal string - m = IDENTIFIER.match(remaining) - if m: - result = m.groups()[0] - remaining = remaining[m.end():] - elif not remaining: - raise SyntaxError('unexpected end of input') - else: - q = remaining[0] - if q not in '\'"': - raise SyntaxError('invalid expression: %s' % remaining) - oq = '\'"'.replace(q, '') - remaining = remaining[1:] - parts = [q] - while remaining: - # either a string chunk, or oq, or q to terminate - if remaining[0] == q: - break - elif remaining[0] == oq: - parts.append(oq) - remaining = remaining[1:] - else: - m = STRING_CHUNK.match(remaining) - if not m: - raise SyntaxError('error in string literal: %s' % remaining) - parts.append(m.groups()[0]) - remaining = remaining[m.end():] - else: - s = ''.join(parts) - raise SyntaxError('unterminated string: %s' % s) - parts.append(q) - result = ''.join(parts) - remaining = remaining[1:].lstrip() # skip past closing quote - return result, remaining - - def marker_expr(remaining): - if remaining and remaining[0] == '(': - result, remaining = marker(remaining[1:].lstrip()) - if remaining[0] != ')': - raise SyntaxError('unterminated parenthesis: %s' % remaining) - remaining = remaining[1:].lstrip() - else: - lhs, remaining = marker_var(remaining) - while remaining: - m = MARKER_OP.match(remaining) - if not m: - break - op = m.groups()[0] - remaining = remaining[m.end():] - rhs, remaining = marker_var(remaining) - lhs = {'op': op, 'lhs': lhs, 'rhs': rhs} - result = lhs - return result, remaining - - def marker_and(remaining): - lhs, remaining = marker_expr(remaining) - while remaining: - m = AND.match(remaining) - if not m: - break - remaining = remaining[m.end():] - rhs, remaining = marker_expr(remaining) - lhs = {'op': 'and', 'lhs': lhs, 'rhs': rhs} - return lhs, remaining - - def marker(remaining): - lhs, remaining = marker_and(remaining) - while remaining: - m = OR.match(remaining) - if not m: - break - remaining = remaining[m.end():] - rhs, remaining = marker_and(remaining) - lhs = {'op': 'or', 'lhs': lhs, 'rhs': rhs} - return lhs, remaining - - return marker(marker_string) - - -def parse_requirement(req): - """ - Parse a requirement passed in as a string. Return a Container - whose attributes contain the various parts of the requirement. - """ - remaining = req.strip() - if not remaining or remaining.startswith('#'): - return None - m = IDENTIFIER.match(remaining) - if not m: - raise SyntaxError('name expected: %s' % remaining) - distname = m.groups()[0] - remaining = remaining[m.end():] - extras = mark_expr = versions = uri = None - if remaining and remaining[0] == '[': - i = remaining.find(']', 1) - if i < 0: - raise SyntaxError('unterminated extra: %s' % remaining) - s = remaining[1:i] - remaining = remaining[i + 1:].lstrip() - extras = [] - while s: - m = IDENTIFIER.match(s) - if not m: - raise SyntaxError('malformed extra: %s' % s) - extras.append(m.groups()[0]) - s = s[m.end():] - if not s: - break - if s[0] != ',': - raise SyntaxError('comma expected in extras: %s' % s) - s = s[1:].lstrip() - if not extras: - extras = None - if remaining: - if remaining[0] == '@': - # it's a URI - remaining = remaining[1:].lstrip() - m = NON_SPACE.match(remaining) - if not m: - raise SyntaxError('invalid URI: %s' % remaining) - uri = m.groups()[0] - t = urlparse(uri) - # there are issues with Python and URL parsing, so this test - # is a bit crude. See bpo-20271, bpo-23505. Python doesn't - # always parse invalid URLs correctly - it should raise - # exceptions for malformed URLs - if not (t.scheme and t.netloc): - raise SyntaxError('Invalid URL: %s' % uri) - remaining = remaining[m.end():].lstrip() - else: - - def get_versions(ver_remaining): - """ - Return a list of operator, version tuples if any are - specified, else None. - """ - m = COMPARE_OP.match(ver_remaining) - versions = None - if m: - versions = [] - while True: - op = m.groups()[0] - ver_remaining = ver_remaining[m.end():] - m = VERSION_IDENTIFIER.match(ver_remaining) - if not m: - raise SyntaxError('invalid version: %s' % ver_remaining) - v = m.groups()[0] - versions.append((op, v)) - ver_remaining = ver_remaining[m.end():] - if not ver_remaining or ver_remaining[0] != ',': - break - ver_remaining = ver_remaining[1:].lstrip() - # Some packages have a trailing comma which would break things - # See issue #148 - if not ver_remaining: - break - m = COMPARE_OP.match(ver_remaining) - if not m: - raise SyntaxError('invalid constraint: %s' % ver_remaining) - if not versions: - versions = None - return versions, ver_remaining - - if remaining[0] != '(': - versions, remaining = get_versions(remaining) - else: - i = remaining.find(')', 1) - if i < 0: - raise SyntaxError('unterminated parenthesis: %s' % remaining) - s = remaining[1:i] - remaining = remaining[i + 1:].lstrip() - # As a special diversion from PEP 508, allow a version number - # a.b.c in parentheses as a synonym for ~= a.b.c (because this - # is allowed in earlier PEPs) - if COMPARE_OP.match(s): - versions, _ = get_versions(s) - else: - m = VERSION_IDENTIFIER.match(s) - if not m: - raise SyntaxError('invalid constraint: %s' % s) - v = m.groups()[0] - s = s[m.end():].lstrip() - if s: - raise SyntaxError('invalid constraint: %s' % s) - versions = [('~=', v)] - - if remaining: - if remaining[0] != ';': - raise SyntaxError('invalid requirement: %s' % remaining) - remaining = remaining[1:].lstrip() - - mark_expr, remaining = parse_marker(remaining) - - if remaining and remaining[0] != '#': - raise SyntaxError('unexpected trailing data: %s' % remaining) - - if not versions: - rs = distname - else: - rs = '%s %s' % (distname, ', '.join(['%s %s' % con for con in versions])) - return Container(name=distname, extras=extras, constraints=versions, - marker=mark_expr, url=uri, requirement=rs) - - -def get_resources_dests(resources_root, rules): - """Find destinations for resources files""" - - def get_rel_path(root, path): - # normalizes and returns a lstripped-/-separated path - root = root.replace(os.path.sep, '/') - path = path.replace(os.path.sep, '/') - assert path.startswith(root) - return path[len(root):].lstrip('/') - - destinations = {} - for base, suffix, dest in rules: - prefix = os.path.join(resources_root, base) - for abs_base in iglob(prefix): - abs_glob = os.path.join(abs_base, suffix) - for abs_path in iglob(abs_glob): - resource_file = get_rel_path(resources_root, abs_path) - if dest is None: # remove the entry if it was here - destinations.pop(resource_file, None) - else: - rel_path = get_rel_path(abs_base, abs_path) - rel_dest = dest.replace(os.path.sep, '/').rstrip('/') - destinations[resource_file] = rel_dest + '/' + rel_path - return destinations - - -def in_venv(): - if hasattr(sys, 'real_prefix'): - # virtualenv venvs - result = True - else: - # PEP 405 venvs - result = sys.prefix != getattr(sys, 'base_prefix', sys.prefix) - return result - - -def get_executable(): -# The __PYVENV_LAUNCHER__ dance is apparently no longer needed, as -# changes to the stub launcher mean that sys.executable always points -# to the stub on OS X -# if sys.platform == 'darwin' and ('__PYVENV_LAUNCHER__' -# in os.environ): -# result = os.environ['__PYVENV_LAUNCHER__'] -# else: -# result = sys.executable -# return result - # Avoid normcasing: see issue #143 - # result = os.path.normcase(sys.executable) - result = sys.executable - if not isinstance(result, text_type): - result = fsdecode(result) - return result - - -def proceed(prompt, allowed_chars, error_prompt=None, default=None): - p = prompt - while True: - s = raw_input(p) - p = prompt - if not s and default: - s = default - if s: - c = s[0].lower() - if c in allowed_chars: - break - if error_prompt: - p = '%c: %s\n%s' % (c, error_prompt, prompt) - return c - - -def extract_by_key(d, keys): - if isinstance(keys, string_types): - keys = keys.split() - result = {} - for key in keys: - if key in d: - result[key] = d[key] - return result - -def read_exports(stream): - if sys.version_info[0] >= 3: - # needs to be a text stream - stream = codecs.getreader('utf-8')(stream) - # Try to load as JSON, falling back on legacy format - data = stream.read() - stream = StringIO(data) - try: - jdata = json.load(stream) - result = jdata['extensions']['python.exports']['exports'] - for group, entries in result.items(): - for k, v in entries.items(): - s = '%s = %s' % (k, v) - entry = get_export_entry(s) - assert entry is not None - entries[k] = entry - return result - except Exception: - stream.seek(0, 0) - - def read_stream(cp, stream): - if hasattr(cp, 'read_file'): - cp.read_file(stream) - else: - cp.readfp(stream) - - cp = configparser.ConfigParser() - try: - read_stream(cp, stream) - except configparser.MissingSectionHeaderError: - stream.close() - data = textwrap.dedent(data) - stream = StringIO(data) - read_stream(cp, stream) - - result = {} - for key in cp.sections(): - result[key] = entries = {} - for name, value in cp.items(key): - s = '%s = %s' % (name, value) - entry = get_export_entry(s) - assert entry is not None - #entry.dist = self - entries[name] = entry - return result - - -def write_exports(exports, stream): - if sys.version_info[0] >= 3: - # needs to be a text stream - stream = codecs.getwriter('utf-8')(stream) - cp = configparser.ConfigParser() - for k, v in exports.items(): - # TODO check k, v for valid values - cp.add_section(k) - for entry in v.values(): - if entry.suffix is None: - s = entry.prefix - else: - s = '%s:%s' % (entry.prefix, entry.suffix) - if entry.flags: - s = '%s [%s]' % (s, ', '.join(entry.flags)) - cp.set(k, entry.name, s) - cp.write(stream) - - -@contextlib.contextmanager -def tempdir(): - td = tempfile.mkdtemp() - try: - yield td - finally: - shutil.rmtree(td) - -@contextlib.contextmanager -def chdir(d): - cwd = os.getcwd() - try: - os.chdir(d) - yield - finally: - os.chdir(cwd) - - -@contextlib.contextmanager -def socket_timeout(seconds=15): - cto = socket.getdefaulttimeout() - try: - socket.setdefaulttimeout(seconds) - yield - finally: - socket.setdefaulttimeout(cto) - - -class cached_property(object): - def __init__(self, func): - self.func = func - #for attr in ('__name__', '__module__', '__doc__'): - # setattr(self, attr, getattr(func, attr, None)) - - def __get__(self, obj, cls=None): - if obj is None: - return self - value = self.func(obj) - object.__setattr__(obj, self.func.__name__, value) - #obj.__dict__[self.func.__name__] = value = self.func(obj) - return value - -def convert_path(pathname): - """Return 'pathname' as a name that will work on the native filesystem. - - The path is split on '/' and put back together again using the current - directory separator. Needed because filenames in the setup script are - always supplied in Unix style, and have to be converted to the local - convention before we can actually use them in the filesystem. Raises - ValueError on non-Unix-ish systems if 'pathname' either starts or - ends with a slash. - """ - if os.sep == '/': - return pathname - if not pathname: - return pathname - if pathname[0] == '/': - raise ValueError("path '%s' cannot be absolute" % pathname) - if pathname[-1] == '/': - raise ValueError("path '%s' cannot end with '/'" % pathname) - - paths = pathname.split('/') - while os.curdir in paths: - paths.remove(os.curdir) - if not paths: - return os.curdir - return os.path.join(*paths) - - -class FileOperator(object): - def __init__(self, dry_run=False): - self.dry_run = dry_run - self.ensured = set() - self._init_record() - - def _init_record(self): - self.record = False - self.files_written = set() - self.dirs_created = set() - - def record_as_written(self, path): - if self.record: - self.files_written.add(path) - - def newer(self, source, target): - """Tell if the target is newer than the source. - - Returns true if 'source' exists and is more recently modified than - 'target', or if 'source' exists and 'target' doesn't. - - Returns false if both exist and 'target' is the same age or younger - than 'source'. Raise PackagingFileError if 'source' does not exist. - - Note that this test is not very accurate: files created in the same - second will have the same "age". - """ - if not os.path.exists(source): - raise DistlibException("file '%r' does not exist" % - os.path.abspath(source)) - if not os.path.exists(target): - return True - - return os.stat(source).st_mtime > os.stat(target).st_mtime - - def copy_file(self, infile, outfile, check=True): - """Copy a file respecting dry-run and force flags. - """ - self.ensure_dir(os.path.dirname(outfile)) - logger.info('Copying %s to %s', infile, outfile) - if not self.dry_run: - msg = None - if check: - if os.path.islink(outfile): - msg = '%s is a symlink' % outfile - elif os.path.exists(outfile) and not os.path.isfile(outfile): - msg = '%s is a non-regular file' % outfile - if msg: - raise ValueError(msg + ' which would be overwritten') - shutil.copyfile(infile, outfile) - self.record_as_written(outfile) - - def copy_stream(self, instream, outfile, encoding=None): - assert not os.path.isdir(outfile) - self.ensure_dir(os.path.dirname(outfile)) - logger.info('Copying stream %s to %s', instream, outfile) - if not self.dry_run: - if encoding is None: - outstream = open(outfile, 'wb') - else: - outstream = codecs.open(outfile, 'w', encoding=encoding) - try: - shutil.copyfileobj(instream, outstream) - finally: - outstream.close() - self.record_as_written(outfile) - - def write_binary_file(self, path, data): - self.ensure_dir(os.path.dirname(path)) - if not self.dry_run: - if os.path.exists(path): - os.remove(path) - with open(path, 'wb') as f: - f.write(data) - self.record_as_written(path) - - def write_text_file(self, path, data, encoding): - self.write_binary_file(path, data.encode(encoding)) - - def set_mode(self, bits, mask, files): - if os.name == 'posix' or (os.name == 'java' and os._name == 'posix'): - # Set the executable bits (owner, group, and world) on - # all the files specified. - for f in files: - if self.dry_run: - logger.info("changing mode of %s", f) - else: - mode = (os.stat(f).st_mode | bits) & mask - logger.info("changing mode of %s to %o", f, mode) - os.chmod(f, mode) - - set_executable_mode = lambda s, f: s.set_mode(0o555, 0o7777, f) - - def ensure_dir(self, path): - path = os.path.abspath(path) - if path not in self.ensured and not os.path.exists(path): - self.ensured.add(path) - d, f = os.path.split(path) - self.ensure_dir(d) - logger.info('Creating %s' % path) - if not self.dry_run: - os.mkdir(path) - if self.record: - self.dirs_created.add(path) - - def byte_compile(self, path, optimize=False, force=False, prefix=None, hashed_invalidation=False): - dpath = cache_from_source(path, not optimize) - logger.info('Byte-compiling %s to %s', path, dpath) - if not self.dry_run: - if force or self.newer(path, dpath): - if not prefix: - diagpath = None - else: - assert path.startswith(prefix) - diagpath = path[len(prefix):] - compile_kwargs = {} - if hashed_invalidation and hasattr(py_compile, 'PycInvalidationMode'): - compile_kwargs['invalidation_mode'] = py_compile.PycInvalidationMode.CHECKED_HASH - py_compile.compile(path, dpath, diagpath, True, **compile_kwargs) # raise error - self.record_as_written(dpath) - return dpath - - def ensure_removed(self, path): - if os.path.exists(path): - if os.path.isdir(path) and not os.path.islink(path): - logger.debug('Removing directory tree at %s', path) - if not self.dry_run: - shutil.rmtree(path) - if self.record: - if path in self.dirs_created: - self.dirs_created.remove(path) - else: - if os.path.islink(path): - s = 'link' - else: - s = 'file' - logger.debug('Removing %s %s', s, path) - if not self.dry_run: - os.remove(path) - if self.record: - if path in self.files_written: - self.files_written.remove(path) - - def is_writable(self, path): - result = False - while not result: - if os.path.exists(path): - result = os.access(path, os.W_OK) - break - parent = os.path.dirname(path) - if parent == path: - break - path = parent - return result - - def commit(self): - """ - Commit recorded changes, turn off recording, return - changes. - """ - assert self.record - result = self.files_written, self.dirs_created - self._init_record() - return result - - def rollback(self): - if not self.dry_run: - for f in list(self.files_written): - if os.path.exists(f): - os.remove(f) - # dirs should all be empty now, except perhaps for - # __pycache__ subdirs - # reverse so that subdirs appear before their parents - dirs = sorted(self.dirs_created, reverse=True) - for d in dirs: - flist = os.listdir(d) - if flist: - assert flist == ['__pycache__'] - sd = os.path.join(d, flist[0]) - os.rmdir(sd) - os.rmdir(d) # should fail if non-empty - self._init_record() - -def resolve(module_name, dotted_path): - if module_name in sys.modules: - mod = sys.modules[module_name] - else: - mod = __import__(module_name) - if dotted_path is None: - result = mod - else: - parts = dotted_path.split('.') - result = getattr(mod, parts.pop(0)) - for p in parts: - result = getattr(result, p) - return result - - -class ExportEntry(object): - def __init__(self, name, prefix, suffix, flags): - self.name = name - self.prefix = prefix - self.suffix = suffix - self.flags = flags - - @cached_property - def value(self): - return resolve(self.prefix, self.suffix) - - def __repr__(self): # pragma: no cover - return '' % (self.name, self.prefix, - self.suffix, self.flags) - - def __eq__(self, other): - if not isinstance(other, ExportEntry): - result = False - else: - result = (self.name == other.name and - self.prefix == other.prefix and - self.suffix == other.suffix and - self.flags == other.flags) - return result - - __hash__ = object.__hash__ - - -ENTRY_RE = re.compile(r'''(?P(\w|[-.+])+) - \s*=\s*(?P(\w+)([:\.]\w+)*) - \s*(\[\s*(?P[\w-]+(=\w+)?(,\s*\w+(=\w+)?)*)\s*\])? - ''', re.VERBOSE) - -def get_export_entry(specification): - m = ENTRY_RE.search(specification) - if not m: - result = None - if '[' in specification or ']' in specification: - raise DistlibException("Invalid specification " - "'%s'" % specification) - else: - d = m.groupdict() - name = d['name'] - path = d['callable'] - colons = path.count(':') - if colons == 0: - prefix, suffix = path, None - else: - if colons != 1: - raise DistlibException("Invalid specification " - "'%s'" % specification) - prefix, suffix = path.split(':') - flags = d['flags'] - if flags is None: - if '[' in specification or ']' in specification: - raise DistlibException("Invalid specification " - "'%s'" % specification) - flags = [] - else: - flags = [f.strip() for f in flags.split(',')] - result = ExportEntry(name, prefix, suffix, flags) - return result - - -def get_cache_base(suffix=None): - """ - Return the default base location for distlib caches. If the directory does - not exist, it is created. Use the suffix provided for the base directory, - and default to '.distlib' if it isn't provided. - - On Windows, if LOCALAPPDATA is defined in the environment, then it is - assumed to be a directory, and will be the parent directory of the result. - On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home - directory - using os.expanduser('~') - will be the parent directory of - the result. - - The result is just the directory '.distlib' in the parent directory as - determined above, or with the name specified with ``suffix``. - """ - if suffix is None: - suffix = '.distlib' - if os.name == 'nt' and 'LOCALAPPDATA' in os.environ: - result = os.path.expandvars('$localappdata') - else: - # Assume posix, or old Windows - result = os.path.expanduser('~') - # we use 'isdir' instead of 'exists', because we want to - # fail if there's a file with that name - if os.path.isdir(result): - usable = os.access(result, os.W_OK) - if not usable: - logger.warning('Directory exists but is not writable: %s', result) - else: - try: - os.makedirs(result) - usable = True - except OSError: - logger.warning('Unable to create %s', result, exc_info=True) - usable = False - if not usable: - result = tempfile.mkdtemp() - logger.warning('Default location unusable, using %s', result) - return os.path.join(result, suffix) - - -def path_to_cache_dir(path): - """ - Convert an absolute path to a directory name for use in a cache. - - The algorithm used is: - - #. On Windows, any ``':'`` in the drive is replaced with ``'---'``. - #. Any occurrence of ``os.sep`` is replaced with ``'--'``. - #. ``'.cache'`` is appended. - """ - d, p = os.path.splitdrive(os.path.abspath(path)) - if d: - d = d.replace(':', '---') - p = p.replace(os.sep, '--') - return d + p + '.cache' - - -def ensure_slash(s): - if not s.endswith('/'): - return s + '/' - return s - - -def parse_credentials(netloc): - username = password = None - if '@' in netloc: - prefix, netloc = netloc.rsplit('@', 1) - if ':' not in prefix: - username = prefix - else: - username, password = prefix.split(':', 1) - if username: - username = unquote(username) - if password: - password = unquote(password) - return username, password, netloc - - -def get_process_umask(): - result = os.umask(0o22) - os.umask(result) - return result - -def is_string_sequence(seq): - result = True - i = None - for i, s in enumerate(seq): - if not isinstance(s, string_types): - result = False - break - assert i is not None - return result - -PROJECT_NAME_AND_VERSION = re.compile('([a-z0-9_]+([.-][a-z_][a-z0-9_]*)*)-' - '([a-z0-9_.+-]+)', re.I) -PYTHON_VERSION = re.compile(r'-py(\d\.?\d?)') - - -def split_filename(filename, project_name=None): - """ - Extract name, version, python version from a filename (no extension) - - Return name, version, pyver or None - """ - result = None - pyver = None - filename = unquote(filename).replace(' ', '-') - m = PYTHON_VERSION.search(filename) - if m: - pyver = m.group(1) - filename = filename[:m.start()] - if project_name and len(filename) > len(project_name) + 1: - m = re.match(re.escape(project_name) + r'\b', filename) - if m: - n = m.end() - result = filename[:n], filename[n + 1:], pyver - if result is None: - m = PROJECT_NAME_AND_VERSION.match(filename) - if m: - result = m.group(1), m.group(3), pyver - return result - -# Allow spaces in name because of legacy dists like "Twisted Core" -NAME_VERSION_RE = re.compile(r'(?P[\w .-]+)\s*' - r'\(\s*(?P[^\s)]+)\)$') - -def parse_name_and_version(p): - """ - A utility method used to get name and version from a string. - - From e.g. a Provides-Dist value. - - :param p: A value in a form 'foo (1.0)' - :return: The name and version as a tuple. - """ - m = NAME_VERSION_RE.match(p) - if not m: - raise DistlibException('Ill-formed name/version string: \'%s\'' % p) - d = m.groupdict() - return d['name'].strip().lower(), d['ver'] - -def get_extras(requested, available): - result = set() - requested = set(requested or []) - available = set(available or []) - if '*' in requested: - requested.remove('*') - result |= available - for r in requested: - if r == '-': - result.add(r) - elif r.startswith('-'): - unwanted = r[1:] - if unwanted not in available: - logger.warning('undeclared extra: %s' % unwanted) - if unwanted in result: - result.remove(unwanted) - else: - if r not in available: - logger.warning('undeclared extra: %s' % r) - result.add(r) - return result -# -# Extended metadata functionality -# - -def _get_external_data(url): - result = {} - try: - # urlopen might fail if it runs into redirections, - # because of Python issue #13696. Fixed in locators - # using a custom redirect handler. - resp = urlopen(url) - headers = resp.info() - ct = headers.get('Content-Type') - if not ct.startswith('application/json'): - logger.debug('Unexpected response for JSON request: %s', ct) - else: - reader = codecs.getreader('utf-8')(resp) - #data = reader.read().decode('utf-8') - #result = json.loads(data) - result = json.load(reader) - except Exception as e: - logger.exception('Failed to get external data for %s: %s', url, e) - return result - -_external_data_base_url = 'https://www.red-dove.com/pypi/projects/' - -def get_project_data(name): - url = '%s/%s/project.json' % (name[0].upper(), name) - url = urljoin(_external_data_base_url, url) - result = _get_external_data(url) - return result - -def get_package_data(name, version): - url = '%s/%s/package-%s.json' % (name[0].upper(), name, version) - url = urljoin(_external_data_base_url, url) - return _get_external_data(url) - - -class Cache(object): - """ - A class implementing a cache for resources that need to live in the file system - e.g. shared libraries. This class was moved from resources to here because it - could be used by other modules, e.g. the wheel module. - """ - - def __init__(self, base): - """ - Initialise an instance. - - :param base: The base directory where the cache should be located. - """ - # we use 'isdir' instead of 'exists', because we want to - # fail if there's a file with that name - if not os.path.isdir(base): # pragma: no cover - os.makedirs(base) - if (os.stat(base).st_mode & 0o77) != 0: - logger.warning('Directory \'%s\' is not private', base) - self.base = os.path.abspath(os.path.normpath(base)) - - def prefix_to_dir(self, prefix): - """ - Converts a resource prefix to a directory name in the cache. - """ - return path_to_cache_dir(prefix) - - def clear(self): - """ - Clear the cache. - """ - not_removed = [] - for fn in os.listdir(self.base): - fn = os.path.join(self.base, fn) - try: - if os.path.islink(fn) or os.path.isfile(fn): - os.remove(fn) - elif os.path.isdir(fn): - shutil.rmtree(fn) - except Exception: - not_removed.append(fn) - return not_removed - - -class EventMixin(object): - """ - A very simple publish/subscribe system. - """ - def __init__(self): - self._subscribers = {} - - def add(self, event, subscriber, append=True): - """ - Add a subscriber for an event. - - :param event: The name of an event. - :param subscriber: The subscriber to be added (and called when the - event is published). - :param append: Whether to append or prepend the subscriber to an - existing subscriber list for the event. - """ - subs = self._subscribers - if event not in subs: - subs[event] = deque([subscriber]) - else: - sq = subs[event] - if append: - sq.append(subscriber) - else: - sq.appendleft(subscriber) - - def remove(self, event, subscriber): - """ - Remove a subscriber for an event. - - :param event: The name of an event. - :param subscriber: The subscriber to be removed. - """ - subs = self._subscribers - if event not in subs: - raise ValueError('No subscribers: %r' % event) - subs[event].remove(subscriber) - - def get_subscribers(self, event): - """ - Return an iterator for the subscribers for an event. - :param event: The event to return subscribers for. - """ - return iter(self._subscribers.get(event, ())) - - def publish(self, event, *args, **kwargs): - """ - Publish a event and return a list of values returned by its - subscribers. - - :param event: The event to publish. - :param args: The positional arguments to pass to the event's - subscribers. - :param kwargs: The keyword arguments to pass to the event's - subscribers. - """ - result = [] - for subscriber in self.get_subscribers(event): - try: - value = subscriber(event, *args, **kwargs) - except Exception: - logger.exception('Exception during event publication') - value = None - result.append(value) - logger.debug('publish %s: args = %s, kwargs = %s, result = %s', - event, args, kwargs, result) - return result - -# -# Simple sequencing -# -class Sequencer(object): - def __init__(self): - self._preds = {} - self._succs = {} - self._nodes = set() # nodes with no preds/succs - - def add_node(self, node): - self._nodes.add(node) - - def remove_node(self, node, edges=False): - if node in self._nodes: - self._nodes.remove(node) - if edges: - for p in set(self._preds.get(node, ())): - self.remove(p, node) - for s in set(self._succs.get(node, ())): - self.remove(node, s) - # Remove empties - for k, v in list(self._preds.items()): - if not v: - del self._preds[k] - for k, v in list(self._succs.items()): - if not v: - del self._succs[k] - - def add(self, pred, succ): - assert pred != succ - self._preds.setdefault(succ, set()).add(pred) - self._succs.setdefault(pred, set()).add(succ) - - def remove(self, pred, succ): - assert pred != succ - try: - preds = self._preds[succ] - succs = self._succs[pred] - except KeyError: # pragma: no cover - raise ValueError('%r not a successor of anything' % succ) - try: - preds.remove(pred) - succs.remove(succ) - except KeyError: # pragma: no cover - raise ValueError('%r not a successor of %r' % (succ, pred)) - - def is_step(self, step): - return (step in self._preds or step in self._succs or - step in self._nodes) - - def get_steps(self, final): - if not self.is_step(final): - raise ValueError('Unknown: %r' % final) - result = [] - todo = [] - seen = set() - todo.append(final) - while todo: - step = todo.pop(0) - if step in seen: - # if a step was already seen, - # move it to the end (so it will appear earlier - # when reversed on return) ... but not for the - # final step, as that would be confusing for - # users - if step != final: - result.remove(step) - result.append(step) - else: - seen.add(step) - result.append(step) - preds = self._preds.get(step, ()) - todo.extend(preds) - return reversed(result) - - @property - def strong_connections(self): - #http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm - index_counter = [0] - stack = [] - lowlinks = {} - index = {} - result = [] - - graph = self._succs - - def strongconnect(node): - # set the depth index for this node to the smallest unused index - index[node] = index_counter[0] - lowlinks[node] = index_counter[0] - index_counter[0] += 1 - stack.append(node) - - # Consider successors - try: - successors = graph[node] - except Exception: - successors = [] - for successor in successors: - if successor not in lowlinks: - # Successor has not yet been visited - strongconnect(successor) - lowlinks[node] = min(lowlinks[node],lowlinks[successor]) - elif successor in stack: - # the successor is in the stack and hence in the current - # strongly connected component (SCC) - lowlinks[node] = min(lowlinks[node],index[successor]) - - # If `node` is a root node, pop the stack and generate an SCC - if lowlinks[node] == index[node]: - connected_component = [] - - while True: - successor = stack.pop() - connected_component.append(successor) - if successor == node: break - component = tuple(connected_component) - # storing the result - result.append(component) - - for node in graph: - if node not in lowlinks: - strongconnect(node) - - return result - - @property - def dot(self): - result = ['digraph G {'] - for succ in self._preds: - preds = self._preds[succ] - for pred in preds: - result.append(' %s -> %s;' % (pred, succ)) - for node in self._nodes: - result.append(' %s;' % node) - result.append('}') - return '\n'.join(result) - -# -# Unarchiving functionality for zip, tar, tgz, tbz, whl -# - -ARCHIVE_EXTENSIONS = ('.tar.gz', '.tar.bz2', '.tar', '.zip', - '.tgz', '.tbz', '.whl') - -def unarchive(archive_filename, dest_dir, format=None, check=True): - - def check_path(path): - if not isinstance(path, text_type): - path = path.decode('utf-8') - p = os.path.abspath(os.path.join(dest_dir, path)) - if not p.startswith(dest_dir) or p[plen] != os.sep: - raise ValueError('path outside destination: %r' % p) - - dest_dir = os.path.abspath(dest_dir) - plen = len(dest_dir) - archive = None - if format is None: - if archive_filename.endswith(('.zip', '.whl')): - format = 'zip' - elif archive_filename.endswith(('.tar.gz', '.tgz')): - format = 'tgz' - mode = 'r:gz' - elif archive_filename.endswith(('.tar.bz2', '.tbz')): - format = 'tbz' - mode = 'r:bz2' - elif archive_filename.endswith('.tar'): - format = 'tar' - mode = 'r' - else: # pragma: no cover - raise ValueError('Unknown format for %r' % archive_filename) - try: - if format == 'zip': - archive = ZipFile(archive_filename, 'r') - if check: - names = archive.namelist() - for name in names: - check_path(name) - else: - archive = tarfile.open(archive_filename, mode) - if check: - names = archive.getnames() - for name in names: - check_path(name) - if format != 'zip' and sys.version_info[0] < 3: - # See Python issue 17153. If the dest path contains Unicode, - # tarfile extraction fails on Python 2.x if a member path name - # contains non-ASCII characters - it leads to an implicit - # bytes -> unicode conversion using ASCII to decode. - for tarinfo in archive.getmembers(): - if not isinstance(tarinfo.name, text_type): - tarinfo.name = tarinfo.name.decode('utf-8') - archive.extractall(dest_dir) - - finally: - if archive: - archive.close() - - -def zip_dir(directory): - """zip a directory tree into a BytesIO object""" - result = io.BytesIO() - dlen = len(directory) - with ZipFile(result, "w") as zf: - for root, dirs, files in os.walk(directory): - for name in files: - full = os.path.join(root, name) - rel = root[dlen:] - dest = os.path.join(rel, name) - zf.write(full, dest) - return result - -# -# Simple progress bar -# - -UNITS = ('', 'K', 'M', 'G','T','P') - - -class Progress(object): - unknown = 'UNKNOWN' - - def __init__(self, minval=0, maxval=100): - assert maxval is None or maxval >= minval - self.min = self.cur = minval - self.max = maxval - self.started = None - self.elapsed = 0 - self.done = False - - def update(self, curval): - assert self.min <= curval - assert self.max is None or curval <= self.max - self.cur = curval - now = time.time() - if self.started is None: - self.started = now - else: - self.elapsed = now - self.started - - def increment(self, incr): - assert incr >= 0 - self.update(self.cur + incr) - - def start(self): - self.update(self.min) - return self - - def stop(self): - if self.max is not None: - self.update(self.max) - self.done = True - - @property - def maximum(self): - return self.unknown if self.max is None else self.max - - @property - def percentage(self): - if self.done: - result = '100 %' - elif self.max is None: - result = ' ?? %' - else: - v = 100.0 * (self.cur - self.min) / (self.max - self.min) - result = '%3d %%' % v - return result - - def format_duration(self, duration): - if (duration <= 0) and self.max is None or self.cur == self.min: - result = '??:??:??' - #elif duration < 1: - # result = '--:--:--' - else: - result = time.strftime('%H:%M:%S', time.gmtime(duration)) - return result - - @property - def ETA(self): - if self.done: - prefix = 'Done' - t = self.elapsed - #import pdb; pdb.set_trace() - else: - prefix = 'ETA ' - if self.max is None: - t = -1 - elif self.elapsed == 0 or (self.cur == self.min): - t = 0 - else: - #import pdb; pdb.set_trace() - t = float(self.max - self.min) - t /= self.cur - self.min - t = (t - 1) * self.elapsed - return '%s: %s' % (prefix, self.format_duration(t)) - - @property - def speed(self): - if self.elapsed == 0: - result = 0.0 - else: - result = (self.cur - self.min) / self.elapsed - for unit in UNITS: - if result < 1000: - break - result /= 1000.0 - return '%d %sB/s' % (result, unit) - -# -# Glob functionality -# - -RICH_GLOB = re.compile(r'\{([^}]*)\}') -_CHECK_RECURSIVE_GLOB = re.compile(r'[^/\\,{]\*\*|\*\*[^/\\,}]') -_CHECK_MISMATCH_SET = re.compile(r'^[^{]*\}|\{[^}]*$') - - -def iglob(path_glob): - """Extended globbing function that supports ** and {opt1,opt2,opt3}.""" - if _CHECK_RECURSIVE_GLOB.search(path_glob): - msg = """invalid glob %r: recursive glob "**" must be used alone""" - raise ValueError(msg % path_glob) - if _CHECK_MISMATCH_SET.search(path_glob): - msg = """invalid glob %r: mismatching set marker '{' or '}'""" - raise ValueError(msg % path_glob) - return _iglob(path_glob) - - -def _iglob(path_glob): - rich_path_glob = RICH_GLOB.split(path_glob, 1) - if len(rich_path_glob) > 1: - assert len(rich_path_glob) == 3, rich_path_glob - prefix, set, suffix = rich_path_glob - for item in set.split(','): - for path in _iglob(''.join((prefix, item, suffix))): - yield path - else: - if '**' not in path_glob: - for item in std_iglob(path_glob): - yield item - else: - prefix, radical = path_glob.split('**', 1) - if prefix == '': - prefix = '.' - if radical == '': - radical = '*' - else: - # we support both - radical = radical.lstrip('/') - radical = radical.lstrip('\\') - for path, dir, files in os.walk(prefix): - path = os.path.normpath(path) - for fn in _iglob(os.path.join(path, radical)): - yield fn - -if ssl: - from .compat import (HTTPSHandler as BaseHTTPSHandler, match_hostname, - CertificateError) - - -# -# HTTPSConnection which verifies certificates/matches domains -# - - class HTTPSConnection(httplib.HTTPSConnection): - ca_certs = None # set this to the path to the certs file (.pem) - check_domain = True # only used if ca_certs is not None - - # noinspection PyPropertyAccess - def connect(self): - sock = socket.create_connection((self.host, self.port), self.timeout) - if getattr(self, '_tunnel_host', False): - self.sock = sock - self._tunnel() - - if not hasattr(ssl, 'SSLContext'): - # For 2.x - if self.ca_certs: - cert_reqs = ssl.CERT_REQUIRED - else: - cert_reqs = ssl.CERT_NONE - self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, - cert_reqs=cert_reqs, - ssl_version=ssl.PROTOCOL_SSLv23, - ca_certs=self.ca_certs) - else: # pragma: no cover - context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) - if hasattr(ssl, 'OP_NO_SSLv2'): - context.options |= ssl.OP_NO_SSLv2 - if self.cert_file: - context.load_cert_chain(self.cert_file, self.key_file) - kwargs = {} - if self.ca_certs: - context.verify_mode = ssl.CERT_REQUIRED - context.load_verify_locations(cafile=self.ca_certs) - if getattr(ssl, 'HAS_SNI', False): - kwargs['server_hostname'] = self.host - self.sock = context.wrap_socket(sock, **kwargs) - if self.ca_certs and self.check_domain: - try: - match_hostname(self.sock.getpeercert(), self.host) - logger.debug('Host verified: %s', self.host) - except CertificateError: # pragma: no cover - self.sock.shutdown(socket.SHUT_RDWR) - self.sock.close() - raise - - class HTTPSHandler(BaseHTTPSHandler): - def __init__(self, ca_certs, check_domain=True): - BaseHTTPSHandler.__init__(self) - self.ca_certs = ca_certs - self.check_domain = check_domain - - def _conn_maker(self, *args, **kwargs): - """ - This is called to create a connection instance. Normally you'd - pass a connection class to do_open, but it doesn't actually check for - a class, and just expects a callable. As long as we behave just as a - constructor would have, we should be OK. If it ever changes so that - we *must* pass a class, we'll create an UnsafeHTTPSConnection class - which just sets check_domain to False in the class definition, and - choose which one to pass to do_open. - """ - result = HTTPSConnection(*args, **kwargs) - if self.ca_certs: - result.ca_certs = self.ca_certs - result.check_domain = self.check_domain - return result - - def https_open(self, req): - try: - return self.do_open(self._conn_maker, req) - except URLError as e: - if 'certificate verify failed' in str(e.reason): - raise CertificateError('Unable to verify server certificate ' - 'for %s' % req.host) - else: - raise - - # - # To prevent against mixing HTTP traffic with HTTPS (examples: A Man-In-The- - # Middle proxy using HTTP listens on port 443, or an index mistakenly serves - # HTML containing a http://xyz link when it should be https://xyz), - # you can use the following handler class, which does not allow HTTP traffic. - # - # It works by inheriting from HTTPHandler - so build_opener won't add a - # handler for HTTP itself. - # - class HTTPSOnlyHandler(HTTPSHandler, HTTPHandler): - def http_open(self, req): - raise URLError('Unexpected HTTP request on what should be a secure ' - 'connection: %s' % req) - -# -# XML-RPC with timeouts -# - -_ver_info = sys.version_info[:2] - -if _ver_info == (2, 6): - class HTTP(httplib.HTTP): - def __init__(self, host='', port=None, **kwargs): - if port == 0: # 0 means use port 0, not the default port - port = None - self._setup(self._connection_class(host, port, **kwargs)) - - - if ssl: - class HTTPS(httplib.HTTPS): - def __init__(self, host='', port=None, **kwargs): - if port == 0: # 0 means use port 0, not the default port - port = None - self._setup(self._connection_class(host, port, **kwargs)) - - -class Transport(xmlrpclib.Transport): - def __init__(self, timeout, use_datetime=0): - self.timeout = timeout - xmlrpclib.Transport.__init__(self, use_datetime) - - def make_connection(self, host): - h, eh, x509 = self.get_host_info(host) - if _ver_info == (2, 6): - result = HTTP(h, timeout=self.timeout) - else: - if not self._connection or host != self._connection[0]: - self._extra_headers = eh - self._connection = host, httplib.HTTPConnection(h) - result = self._connection[1] - return result - -if ssl: - class SafeTransport(xmlrpclib.SafeTransport): - def __init__(self, timeout, use_datetime=0): - self.timeout = timeout - xmlrpclib.SafeTransport.__init__(self, use_datetime) - - def make_connection(self, host): - h, eh, kwargs = self.get_host_info(host) - if not kwargs: - kwargs = {} - kwargs['timeout'] = self.timeout - if _ver_info == (2, 6): - result = HTTPS(host, None, **kwargs) - else: - if not self._connection or host != self._connection[0]: - self._extra_headers = eh - self._connection = host, httplib.HTTPSConnection(h, None, - **kwargs) - result = self._connection[1] - return result - - -class ServerProxy(xmlrpclib.ServerProxy): - def __init__(self, uri, **kwargs): - self.timeout = timeout = kwargs.pop('timeout', None) - # The above classes only come into play if a timeout - # is specified - if timeout is not None: - # scheme = splittype(uri) # deprecated as of Python 3.8 - scheme = urlparse(uri)[0] - use_datetime = kwargs.get('use_datetime', 0) - if scheme == 'https': - tcls = SafeTransport - else: - tcls = Transport - kwargs['transport'] = t = tcls(timeout, use_datetime=use_datetime) - self.transport = t - xmlrpclib.ServerProxy.__init__(self, uri, **kwargs) - -# -# CSV functionality. This is provided because on 2.x, the csv module can't -# handle Unicode. However, we need to deal with Unicode in e.g. RECORD files. -# - -def _csv_open(fn, mode, **kwargs): - if sys.version_info[0] < 3: - mode += 'b' - else: - kwargs['newline'] = '' - # Python 3 determines encoding from locale. Force 'utf-8' - # file encoding to match other forced utf-8 encoding - kwargs['encoding'] = 'utf-8' - return open(fn, mode, **kwargs) - - -class CSVBase(object): - defaults = { - 'delimiter': str(','), # The strs are used because we need native - 'quotechar': str('"'), # str in the csv API (2.x won't take - 'lineterminator': str('\n') # Unicode) - } - - def __enter__(self): - return self - - def __exit__(self, *exc_info): - self.stream.close() - - -class CSVReader(CSVBase): - def __init__(self, **kwargs): - if 'stream' in kwargs: - stream = kwargs['stream'] - if sys.version_info[0] >= 3: - # needs to be a text stream - stream = codecs.getreader('utf-8')(stream) - self.stream = stream - else: - self.stream = _csv_open(kwargs['path'], 'r') - self.reader = csv.reader(self.stream, **self.defaults) - - def __iter__(self): - return self - - def next(self): - result = next(self.reader) - if sys.version_info[0] < 3: - for i, item in enumerate(result): - if not isinstance(item, text_type): - result[i] = item.decode('utf-8') - return result - - __next__ = next - -class CSVWriter(CSVBase): - def __init__(self, fn, **kwargs): - self.stream = _csv_open(fn, 'w') - self.writer = csv.writer(self.stream, **self.defaults) - - def writerow(self, row): - if sys.version_info[0] < 3: - r = [] - for item in row: - if isinstance(item, text_type): - item = item.encode('utf-8') - r.append(item) - row = r - self.writer.writerow(row) - -# -# Configurator functionality -# - -class Configurator(BaseConfigurator): - - value_converters = dict(BaseConfigurator.value_converters) - value_converters['inc'] = 'inc_convert' - - def __init__(self, config, base=None): - super(Configurator, self).__init__(config) - self.base = base or os.getcwd() - - def configure_custom(self, config): - def convert(o): - if isinstance(o, (list, tuple)): - result = type(o)([convert(i) for i in o]) - elif isinstance(o, dict): - if '()' in o: - result = self.configure_custom(o) - else: - result = {} - for k in o: - result[k] = convert(o[k]) - else: - result = self.convert(o) - return result - - c = config.pop('()') - if not callable(c): - c = self.resolve(c) - props = config.pop('.', None) - # Check for valid identifiers - args = config.pop('[]', ()) - if args: - args = tuple([convert(o) for o in args]) - items = [(k, convert(config[k])) for k in config if valid_ident(k)] - kwargs = dict(items) - result = c(*args, **kwargs) - if props: - for n, v in props.items(): - setattr(result, n, convert(v)) - return result - - def __getitem__(self, key): - result = self.config[key] - if isinstance(result, dict) and '()' in result: - self.config[key] = result = self.configure_custom(result) - return result - - def inc_convert(self, value): - """Default converter for the inc:// protocol.""" - if not os.path.isabs(value): - value = os.path.join(self.base, value) - with codecs.open(value, 'r', encoding='utf-8') as f: - result = json.load(f) - return result - - -class SubprocessMixin(object): - """ - Mixin for running subprocesses and capturing their output - """ - def __init__(self, verbose=False, progress=None): - self.verbose = verbose - self.progress = progress - - def reader(self, stream, context): - """ - Read lines from a subprocess' output stream and either pass to a progress - callable (if specified) or write progress information to sys.stderr. - """ - progress = self.progress - verbose = self.verbose - while True: - s = stream.readline() - if not s: - break - if progress is not None: - progress(s, context) - else: - if not verbose: - sys.stderr.write('.') - else: - sys.stderr.write(s.decode('utf-8')) - sys.stderr.flush() - stream.close() - - def run_command(self, cmd, **kwargs): - p = subprocess.Popen(cmd, stdout=subprocess.PIPE, - stderr=subprocess.PIPE, **kwargs) - t1 = threading.Thread(target=self.reader, args=(p.stdout, 'stdout')) - t1.start() - t2 = threading.Thread(target=self.reader, args=(p.stderr, 'stderr')) - t2.start() - p.wait() - t1.join() - t2.join() - if self.progress is not None: - self.progress('done.', 'main') - elif self.verbose: - sys.stderr.write('done.\n') - return p - - -def normalize_name(name): - """Normalize a python package name a la PEP 503""" - # https://www.python.org/dev/peps/pep-0503/#normalized-names - return re.sub('[-_.]+', '-', name).lower() - -# def _get_pypirc_command(): - # """ - # Get the distutils command for interacting with PyPI configurations. - # :return: the command. - # """ - # from distutils.core import Distribution - # from distutils.config import PyPIRCCommand - # d = Distribution() - # return PyPIRCCommand(d) - -class PyPIRCFile(object): - - DEFAULT_REPOSITORY = 'https://upload.pypi.org/legacy/' - DEFAULT_REALM = 'pypi' - - def __init__(self, fn=None, url=None): - if fn is None: - fn = os.path.join(os.path.expanduser('~'), '.pypirc') - self.filename = fn - self.url = url - - def read(self): - result = {} - - if os.path.exists(self.filename): - repository = self.url or self.DEFAULT_REPOSITORY - - config = configparser.RawConfigParser() - config.read(self.filename) - sections = config.sections() - if 'distutils' in sections: - # let's get the list of servers - index_servers = config.get('distutils', 'index-servers') - _servers = [server.strip() for server in - index_servers.split('\n') - if server.strip() != ''] - if _servers == []: - # nothing set, let's try to get the default pypi - if 'pypi' in sections: - _servers = ['pypi'] - else: - for server in _servers: - result = {'server': server} - result['username'] = config.get(server, 'username') - - # optional params - for key, default in (('repository', self.DEFAULT_REPOSITORY), - ('realm', self.DEFAULT_REALM), - ('password', None)): - if config.has_option(server, key): - result[key] = config.get(server, key) - else: - result[key] = default - - # work around people having "repository" for the "pypi" - # section of their config set to the HTTP (rather than - # HTTPS) URL - if (server == 'pypi' and - repository in (self.DEFAULT_REPOSITORY, 'pypi')): - result['repository'] = self.DEFAULT_REPOSITORY - elif (result['server'] != repository and - result['repository'] != repository): - result = {} - elif 'server-login' in sections: - # old format - server = 'server-login' - if config.has_option(server, 'repository'): - repository = config.get(server, 'repository') - else: - repository = self.DEFAULT_REPOSITORY - result = { - 'username': config.get(server, 'username'), - 'password': config.get(server, 'password'), - 'repository': repository, - 'server': server, - 'realm': self.DEFAULT_REALM - } - return result - - def update(self, username, password): - # import pdb; pdb.set_trace() - config = configparser.RawConfigParser() - fn = self.filename - config.read(fn) - if not config.has_section('pypi'): - config.add_section('pypi') - config.set('pypi', 'username', username) - config.set('pypi', 'password', password) - with open(fn, 'w') as f: - config.write(f) - -def _load_pypirc(index): - """ - Read the PyPI access configuration as supported by distutils. - """ - return PyPIRCFile(url=index.url).read() - -def _store_pypirc(index): - PyPIRCFile().update(index.username, index.password) - -# -# get_platform()/get_host_platform() copied from Python 3.10.a0 source, with some minor -# tweaks -# - -def get_host_platform(): - """Return a string that identifies the current platform. This is used mainly to - distinguish platform-specific build directories and platform-specific built - distributions. Typically includes the OS name and version and the - architecture (as supplied by 'os.uname()'), although the exact information - included depends on the OS; eg. on Linux, the kernel version isn't - particularly important. - - Examples of returned values: - linux-i586 - linux-alpha (?) - solaris-2.6-sun4u - - Windows will return one of: - win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) - win32 (all others - specifically, sys.platform is returned) - - For other non-POSIX platforms, currently just returns 'sys.platform'. - - """ - if os.name == 'nt': - if 'amd64' in sys.version.lower(): - return 'win-amd64' - if '(arm)' in sys.version.lower(): - return 'win-arm32' - if '(arm64)' in sys.version.lower(): - return 'win-arm64' - return sys.platform - - # Set for cross builds explicitly - if "_PYTHON_HOST_PLATFORM" in os.environ: - return os.environ["_PYTHON_HOST_PLATFORM"] - - if os.name != 'posix' or not hasattr(os, 'uname'): - # XXX what about the architecture? NT is Intel or Alpha, - # Mac OS is M68k or PPC, etc. - return sys.platform - - # Try to distinguish various flavours of Unix - - (osname, host, release, version, machine) = os.uname() - - # Convert the OS name to lowercase, remove '/' characters, and translate - # spaces (for "Power Macintosh") - osname = osname.lower().replace('/', '') - machine = machine.replace(' ', '_').replace('/', '-') - - if osname[:5] == 'linux': - # At least on Linux/Intel, 'machine' is the processor -- - # i386, etc. - # XXX what about Alpha, SPARC, etc? - return "%s-%s" % (osname, machine) - - elif osname[:5] == 'sunos': - if release[0] >= '5': # SunOS 5 == Solaris 2 - osname = 'solaris' - release = '%d.%s' % (int(release[0]) - 3, release[2:]) - # We can't use 'platform.architecture()[0]' because a - # bootstrap problem. We use a dict to get an error - # if some suspicious happens. - bitness = {2147483647:'32bit', 9223372036854775807:'64bit'} - machine += '.%s' % bitness[sys.maxsize] - # fall through to standard osname-release-machine representation - elif osname[:3] == 'aix': - from _aix_support import aix_platform - return aix_platform() - elif osname[:6] == 'cygwin': - osname = 'cygwin' - rel_re = re.compile (r'[\d.]+', re.ASCII) - m = rel_re.match(release) - if m: - release = m.group() - elif osname[:6] == 'darwin': - import _osx_support, distutils.sysconfig - osname, release, machine = _osx_support.get_platform_osx( - distutils.sysconfig.get_config_vars(), - osname, release, machine) - - return '%s-%s-%s' % (osname, release, machine) - - -_TARGET_TO_PLAT = { - 'x86' : 'win32', - 'x64' : 'win-amd64', - 'arm' : 'win-arm32', -} - - -def get_platform(): - if os.name != 'nt': - return get_host_platform() - cross_compilation_target = os.environ.get('VSCMD_ARG_TGT_ARCH') - if cross_compilation_target not in _TARGET_TO_PLAT: - return get_host_platform() - return _TARGET_TO_PLAT[cross_compilation_target] diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_vendor/urllib3/util/ssl_.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_vendor/urllib3/util/ssl_.py deleted file mode 100644 index 2b45d391d4d7398e4769f45f9dd25eb55daef437..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_vendor/urllib3/util/ssl_.py +++ /dev/null @@ -1,495 +0,0 @@ -from __future__ import absolute_import - -import hmac -import os -import sys -import warnings -from binascii import hexlify, unhexlify -from hashlib import md5, sha1, sha256 - -from ..exceptions import ( - InsecurePlatformWarning, - ProxySchemeUnsupported, - SNIMissingWarning, - SSLError, -) -from ..packages import six -from .url import BRACELESS_IPV6_ADDRZ_RE, IPV4_RE - -SSLContext = None -SSLTransport = None -HAS_SNI = False -IS_PYOPENSSL = False -IS_SECURETRANSPORT = False -ALPN_PROTOCOLS = ["http/1.1"] - -# Maps the length of a digest to a possible hash function producing this digest -HASHFUNC_MAP = {32: md5, 40: sha1, 64: sha256} - - -def _const_compare_digest_backport(a, b): - """ - Compare two digests of equal length in constant time. - - The digests must be of type str/bytes. - Returns True if the digests match, and False otherwise. - """ - result = abs(len(a) - len(b)) - for left, right in zip(bytearray(a), bytearray(b)): - result |= left ^ right - return result == 0 - - -_const_compare_digest = getattr(hmac, "compare_digest", _const_compare_digest_backport) - -try: # Test for SSL features - import ssl - from ssl import CERT_REQUIRED, wrap_socket -except ImportError: - pass - -try: - from ssl import HAS_SNI # Has SNI? -except ImportError: - pass - -try: - from .ssltransport import SSLTransport -except ImportError: - pass - - -try: # Platform-specific: Python 3.6 - from ssl import PROTOCOL_TLS - - PROTOCOL_SSLv23 = PROTOCOL_TLS -except ImportError: - try: - from ssl import PROTOCOL_SSLv23 as PROTOCOL_TLS - - PROTOCOL_SSLv23 = PROTOCOL_TLS - except ImportError: - PROTOCOL_SSLv23 = PROTOCOL_TLS = 2 - -try: - from ssl import PROTOCOL_TLS_CLIENT -except ImportError: - PROTOCOL_TLS_CLIENT = PROTOCOL_TLS - - -try: - from ssl import OP_NO_COMPRESSION, OP_NO_SSLv2, OP_NO_SSLv3 -except ImportError: - OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x2000000 - OP_NO_COMPRESSION = 0x20000 - - -try: # OP_NO_TICKET was added in Python 3.6 - from ssl import OP_NO_TICKET -except ImportError: - OP_NO_TICKET = 0x4000 - - -# A secure default. -# Sources for more information on TLS ciphers: -# -# - https://wiki.mozilla.org/Security/Server_Side_TLS -# - https://www.ssllabs.com/projects/best-practices/index.html -# - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/ -# -# The general intent is: -# - prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE), -# - prefer ECDHE over DHE for better performance, -# - prefer any AES-GCM and ChaCha20 over any AES-CBC for better performance and -# security, -# - prefer AES-GCM over ChaCha20 because hardware-accelerated AES is common, -# - disable NULL authentication, MD5 MACs, DSS, and other -# insecure ciphers for security reasons. -# - NOTE: TLS 1.3 cipher suites are managed through a different interface -# not exposed by CPython (yet!) and are enabled by default if they're available. -DEFAULT_CIPHERS = ":".join( - [ - "ECDHE+AESGCM", - "ECDHE+CHACHA20", - "DHE+AESGCM", - "DHE+CHACHA20", - "ECDH+AESGCM", - "DH+AESGCM", - "ECDH+AES", - "DH+AES", - "RSA+AESGCM", - "RSA+AES", - "!aNULL", - "!eNULL", - "!MD5", - "!DSS", - ] -) - -try: - from ssl import SSLContext # Modern SSL? -except ImportError: - - class SSLContext(object): # Platform-specific: Python 2 - def __init__(self, protocol_version): - self.protocol = protocol_version - # Use default values from a real SSLContext - self.check_hostname = False - self.verify_mode = ssl.CERT_NONE - self.ca_certs = None - self.options = 0 - self.certfile = None - self.keyfile = None - self.ciphers = None - - def load_cert_chain(self, certfile, keyfile): - self.certfile = certfile - self.keyfile = keyfile - - def load_verify_locations(self, cafile=None, capath=None, cadata=None): - self.ca_certs = cafile - - if capath is not None: - raise SSLError("CA directories not supported in older Pythons") - - if cadata is not None: - raise SSLError("CA data not supported in older Pythons") - - def set_ciphers(self, cipher_suite): - self.ciphers = cipher_suite - - def wrap_socket(self, socket, server_hostname=None, server_side=False): - warnings.warn( - "A true SSLContext object is not available. This prevents " - "urllib3 from configuring SSL appropriately and may cause " - "certain SSL connections to fail. You can upgrade to a newer " - "version of Python to solve this. For more information, see " - "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html" - "#ssl-warnings", - InsecurePlatformWarning, - ) - kwargs = { - "keyfile": self.keyfile, - "certfile": self.certfile, - "ca_certs": self.ca_certs, - "cert_reqs": self.verify_mode, - "ssl_version": self.protocol, - "server_side": server_side, - } - return wrap_socket(socket, ciphers=self.ciphers, **kwargs) - - -def assert_fingerprint(cert, fingerprint): - """ - Checks if given fingerprint matches the supplied certificate. - - :param cert: - Certificate as bytes object. - :param fingerprint: - Fingerprint as string of hexdigits, can be interspersed by colons. - """ - - fingerprint = fingerprint.replace(":", "").lower() - digest_length = len(fingerprint) - hashfunc = HASHFUNC_MAP.get(digest_length) - if not hashfunc: - raise SSLError("Fingerprint of invalid length: {0}".format(fingerprint)) - - # We need encode() here for py32; works on py2 and p33. - fingerprint_bytes = unhexlify(fingerprint.encode()) - - cert_digest = hashfunc(cert).digest() - - if not _const_compare_digest(cert_digest, fingerprint_bytes): - raise SSLError( - 'Fingerprints did not match. Expected "{0}", got "{1}".'.format( - fingerprint, hexlify(cert_digest) - ) - ) - - -def resolve_cert_reqs(candidate): - """ - Resolves the argument to a numeric constant, which can be passed to - the wrap_socket function/method from the ssl module. - Defaults to :data:`ssl.CERT_REQUIRED`. - If given a string it is assumed to be the name of the constant in the - :mod:`ssl` module or its abbreviation. - (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. - If it's neither `None` nor a string we assume it is already the numeric - constant which can directly be passed to wrap_socket. - """ - if candidate is None: - return CERT_REQUIRED - - if isinstance(candidate, str): - res = getattr(ssl, candidate, None) - if res is None: - res = getattr(ssl, "CERT_" + candidate) - return res - - return candidate - - -def resolve_ssl_version(candidate): - """ - like resolve_cert_reqs - """ - if candidate is None: - return PROTOCOL_TLS - - if isinstance(candidate, str): - res = getattr(ssl, candidate, None) - if res is None: - res = getattr(ssl, "PROTOCOL_" + candidate) - return res - - return candidate - - -def create_urllib3_context( - ssl_version=None, cert_reqs=None, options=None, ciphers=None -): - """All arguments have the same meaning as ``ssl_wrap_socket``. - - By default, this function does a lot of the same work that - ``ssl.create_default_context`` does on Python 3.4+. It: - - - Disables SSLv2, SSLv3, and compression - - Sets a restricted set of server ciphers - - If you wish to enable SSLv3, you can do:: - - from pip._vendor.urllib3.util import ssl_ - context = ssl_.create_urllib3_context() - context.options &= ~ssl_.OP_NO_SSLv3 - - You can do the same to enable compression (substituting ``COMPRESSION`` - for ``SSLv3`` in the last line above). - - :param ssl_version: - The desired protocol version to use. This will default to - PROTOCOL_SSLv23 which will negotiate the highest protocol that both - the server and your installation of OpenSSL support. - :param cert_reqs: - Whether to require the certificate verification. This defaults to - ``ssl.CERT_REQUIRED``. - :param options: - Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, - ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``. - :param ciphers: - Which cipher suites to allow the server to select. - :returns: - Constructed SSLContext object with specified options - :rtype: SSLContext - """ - # PROTOCOL_TLS is deprecated in Python 3.10 - if not ssl_version or ssl_version == PROTOCOL_TLS: - ssl_version = PROTOCOL_TLS_CLIENT - - context = SSLContext(ssl_version) - - context.set_ciphers(ciphers or DEFAULT_CIPHERS) - - # Setting the default here, as we may have no ssl module on import - cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs - - if options is None: - options = 0 - # SSLv2 is easily broken and is considered harmful and dangerous - options |= OP_NO_SSLv2 - # SSLv3 has several problems and is now dangerous - options |= OP_NO_SSLv3 - # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ - # (issue #309) - options |= OP_NO_COMPRESSION - # TLSv1.2 only. Unless set explicitly, do not request tickets. - # This may save some bandwidth on wire, and although the ticket is encrypted, - # there is a risk associated with it being on wire, - # if the server is not rotating its ticketing keys properly. - options |= OP_NO_TICKET - - context.options |= options - - # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is - # necessary for conditional client cert authentication with TLS 1.3. - # The attribute is None for OpenSSL <= 1.1.0 or does not exist in older - # versions of Python. We only enable on Python 3.7.4+ or if certificate - # verification is enabled to work around Python issue #37428 - # See: https://bugs.python.org/issue37428 - if (cert_reqs == ssl.CERT_REQUIRED or sys.version_info >= (3, 7, 4)) and getattr( - context, "post_handshake_auth", None - ) is not None: - context.post_handshake_auth = True - - def disable_check_hostname(): - if ( - getattr(context, "check_hostname", None) is not None - ): # Platform-specific: Python 3.2 - # We do our own verification, including fingerprints and alternative - # hostnames. So disable it here - context.check_hostname = False - - # The order of the below lines setting verify_mode and check_hostname - # matter due to safe-guards SSLContext has to prevent an SSLContext with - # check_hostname=True, verify_mode=NONE/OPTIONAL. This is made even more - # complex because we don't know whether PROTOCOL_TLS_CLIENT will be used - # or not so we don't know the initial state of the freshly created SSLContext. - if cert_reqs == ssl.CERT_REQUIRED: - context.verify_mode = cert_reqs - disable_check_hostname() - else: - disable_check_hostname() - context.verify_mode = cert_reqs - - # Enable logging of TLS session keys via defacto standard environment variable - # 'SSLKEYLOGFILE', if the feature is available (Python 3.8+). Skip empty values. - if hasattr(context, "keylog_filename"): - sslkeylogfile = os.environ.get("SSLKEYLOGFILE") - if sslkeylogfile: - context.keylog_filename = sslkeylogfile - - return context - - -def ssl_wrap_socket( - sock, - keyfile=None, - certfile=None, - cert_reqs=None, - ca_certs=None, - server_hostname=None, - ssl_version=None, - ciphers=None, - ssl_context=None, - ca_cert_dir=None, - key_password=None, - ca_cert_data=None, - tls_in_tls=False, -): - """ - All arguments except for server_hostname, ssl_context, and ca_cert_dir have - the same meaning as they do when using :func:`ssl.wrap_socket`. - - :param server_hostname: - When SNI is supported, the expected hostname of the certificate - :param ssl_context: - A pre-made :class:`SSLContext` object. If none is provided, one will - be created using :func:`create_urllib3_context`. - :param ciphers: - A string of ciphers we wish the client to support. - :param ca_cert_dir: - A directory containing CA certificates in multiple separate files, as - supported by OpenSSL's -CApath flag or the capath argument to - SSLContext.load_verify_locations(). - :param key_password: - Optional password if the keyfile is encrypted. - :param ca_cert_data: - Optional string containing CA certificates in PEM format suitable for - passing as the cadata parameter to SSLContext.load_verify_locations() - :param tls_in_tls: - Use SSLTransport to wrap the existing socket. - """ - context = ssl_context - if context is None: - # Note: This branch of code and all the variables in it are no longer - # used by urllib3 itself. We should consider deprecating and removing - # this code. - context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) - - if ca_certs or ca_cert_dir or ca_cert_data: - try: - context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data) - except (IOError, OSError) as e: - raise SSLError(e) - - elif ssl_context is None and hasattr(context, "load_default_certs"): - # try to load OS default certs; works well on Windows (require Python3.4+) - context.load_default_certs() - - # Attempt to detect if we get the goofy behavior of the - # keyfile being encrypted and OpenSSL asking for the - # passphrase via the terminal and instead error out. - if keyfile and key_password is None and _is_key_file_encrypted(keyfile): - raise SSLError("Client private key is encrypted, password is required") - - if certfile: - if key_password is None: - context.load_cert_chain(certfile, keyfile) - else: - context.load_cert_chain(certfile, keyfile, key_password) - - try: - if hasattr(context, "set_alpn_protocols"): - context.set_alpn_protocols(ALPN_PROTOCOLS) - except NotImplementedError: # Defensive: in CI, we always have set_alpn_protocols - pass - - # If we detect server_hostname is an IP address then the SNI - # extension should not be used according to RFC3546 Section 3.1 - use_sni_hostname = server_hostname and not is_ipaddress(server_hostname) - # SecureTransport uses server_hostname in certificate verification. - send_sni = (use_sni_hostname and HAS_SNI) or ( - IS_SECURETRANSPORT and server_hostname - ) - # Do not warn the user if server_hostname is an invalid SNI hostname. - if not HAS_SNI and use_sni_hostname: - warnings.warn( - "An HTTPS request has been made, but the SNI (Server Name " - "Indication) extension to TLS is not available on this platform. " - "This may cause the server to present an incorrect TLS " - "certificate, which can cause validation failures. You can upgrade to " - "a newer version of Python to solve this. For more information, see " - "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html" - "#ssl-warnings", - SNIMissingWarning, - ) - - if send_sni: - ssl_sock = _ssl_wrap_socket_impl( - sock, context, tls_in_tls, server_hostname=server_hostname - ) - else: - ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls) - return ssl_sock - - -def is_ipaddress(hostname): - """Detects whether the hostname given is an IPv4 or IPv6 address. - Also detects IPv6 addresses with Zone IDs. - - :param str hostname: Hostname to examine. - :return: True if the hostname is an IP address, False otherwise. - """ - if not six.PY2 and isinstance(hostname, bytes): - # IDN A-label bytes are ASCII compatible. - hostname = hostname.decode("ascii") - return bool(IPV4_RE.match(hostname) or BRACELESS_IPV6_ADDRZ_RE.match(hostname)) - - -def _is_key_file_encrypted(key_file): - """Detects if a key file is encrypted or not.""" - with open(key_file, "r") as f: - for line in f: - # Look for Proc-Type: 4,ENCRYPTED - if "ENCRYPTED" in line: - return True - - return False - - -def _ssl_wrap_socket_impl(sock, ssl_context, tls_in_tls, server_hostname=None): - if tls_in_tls: - if not SSLTransport: - # Import error, ssl is not available. - raise ProxySchemeUnsupported( - "TLS in TLS requires support for the 'ssl' module" - ) - - SSLTransport._validate_ssl_context_for_tls_in_tls(ssl_context) - return SSLTransport(sock, ssl_context, server_hostname) - - if server_hostname: - return ssl_context.wrap_socket(sock, server_hostname=server_hostname) - else: - return ssl_context.wrap_socket(sock) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/rich/padding.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/rich/padding.py deleted file mode 100644 index 1d1f4a553c8114eb516a865f33170058197d856f..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/rich/padding.py +++ /dev/null @@ -1,141 +0,0 @@ -from typing import cast, List, Optional, Tuple, TYPE_CHECKING, Union - -if TYPE_CHECKING: - from .console import ( - Console, - ConsoleOptions, - RenderableType, - RenderResult, - ) -from .jupyter import JupyterMixin -from .measure import Measurement -from .style import Style -from .segment import Segment - - -PaddingDimensions = Union[int, Tuple[int], Tuple[int, int], Tuple[int, int, int, int]] - - -class Padding(JupyterMixin): - """Draw space around content. - - Example: - >>> print(Padding("Hello", (2, 4), style="on blue")) - - Args: - renderable (RenderableType): String or other renderable. - pad (Union[int, Tuple[int]]): Padding for top, right, bottom, and left borders. - May be specified with 1, 2, or 4 integers (CSS style). - style (Union[str, Style], optional): Style for padding characters. Defaults to "none". - expand (bool, optional): Expand padding to fit available width. Defaults to True. - """ - - def __init__( - self, - renderable: "RenderableType", - pad: "PaddingDimensions" = (0, 0, 0, 0), - *, - style: Union[str, Style] = "none", - expand: bool = True, - ): - self.renderable = renderable - self.top, self.right, self.bottom, self.left = self.unpack(pad) - self.style = style - self.expand = expand - - @classmethod - def indent(cls, renderable: "RenderableType", level: int) -> "Padding": - """Make padding instance to render an indent. - - Args: - renderable (RenderableType): String or other renderable. - level (int): Number of characters to indent. - - Returns: - Padding: A Padding instance. - """ - - return Padding(renderable, pad=(0, 0, 0, level), expand=False) - - @staticmethod - def unpack(pad: "PaddingDimensions") -> Tuple[int, int, int, int]: - """Unpack padding specified in CSS style.""" - if isinstance(pad, int): - return (pad, pad, pad, pad) - if len(pad) == 1: - _pad = pad[0] - return (_pad, _pad, _pad, _pad) - if len(pad) == 2: - pad_top, pad_right = cast(Tuple[int, int], pad) - return (pad_top, pad_right, pad_top, pad_right) - if len(pad) == 4: - top, right, bottom, left = cast(Tuple[int, int, int, int], pad) - return (top, right, bottom, left) - raise ValueError(f"1, 2 or 4 integers required for padding; {len(pad)} given") - - def __repr__(self) -> str: - return f"Padding({self.renderable!r}, ({self.top},{self.right},{self.bottom},{self.left}))" - - def __rich_console__( - self, console: "Console", options: "ConsoleOptions" - ) -> "RenderResult": - style = console.get_style(self.style) - if self.expand: - width = options.max_width - else: - width = min( - Measurement.get(console, options, self.renderable).maximum - + self.left - + self.right, - options.max_width, - ) - render_options = options.update_width(width - self.left - self.right) - if render_options.height is not None: - render_options = render_options.update_height( - height=render_options.height - self.top - self.bottom - ) - lines = console.render_lines( - self.renderable, render_options, style=style, pad=True - ) - _Segment = Segment - - left = _Segment(" " * self.left, style) if self.left else None - right = ( - [_Segment(f'{" " * self.right}', style), _Segment.line()] - if self.right - else [_Segment.line()] - ) - blank_line: Optional[List[Segment]] = None - if self.top: - blank_line = [_Segment(f'{" " * width}\n', style)] - yield from blank_line * self.top - if left: - for line in lines: - yield left - yield from line - yield from right - else: - for line in lines: - yield from line - yield from right - if self.bottom: - blank_line = blank_line or [_Segment(f'{" " * width}\n', style)] - yield from blank_line * self.bottom - - def __rich_measure__( - self, console: "Console", options: "ConsoleOptions" - ) -> "Measurement": - max_width = options.max_width - extra_width = self.left + self.right - if max_width - extra_width < 1: - return Measurement(max_width, max_width) - measure_min, measure_max = Measurement.get(console, options, self.renderable) - measurement = Measurement(measure_min + extra_width, measure_max + extra_width) - measurement = measurement.with_maximum(max_width) - return measurement - - -if __name__ == "__main__": # pragma: no cover - from rich import print - - print(Padding("Hello, World", (2, 4), style="on blue")) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/setuptools/command/__init__.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/setuptools/command/__init__.py deleted file mode 100644 index b966dcea57a2072f98b96dbba75ceb26bd26d2dd..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/setuptools/command/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -from distutils.command.bdist import bdist -import sys - -if 'egg' not in bdist.format_commands: - bdist.format_command['egg'] = ('bdist_egg', "Python .egg file") - bdist.format_commands.append('egg') - -del bdist, sys diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/starlette/schemas.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/starlette/schemas.py deleted file mode 100644 index f939cb5a31a349b758a1faf222c83d7da943e6c1..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/starlette/schemas.py +++ /dev/null @@ -1,145 +0,0 @@ -import inspect -import re -import typing - -from starlette.requests import Request -from starlette.responses import Response -from starlette.routing import BaseRoute, Mount, Route - -try: - import yaml -except ModuleNotFoundError: # pragma: nocover - yaml = None # type: ignore[assignment] - - -class OpenAPIResponse(Response): - media_type = "application/vnd.oai.openapi" - - def render(self, content: typing.Any) -> bytes: - assert yaml is not None, "`pyyaml` must be installed to use OpenAPIResponse." - assert isinstance( - content, dict - ), "The schema passed to OpenAPIResponse should be a dictionary." - return yaml.dump(content, default_flow_style=False).encode("utf-8") - - -class EndpointInfo(typing.NamedTuple): - path: str - http_method: str - func: typing.Callable - - -class BaseSchemaGenerator: - def get_schema(self, routes: typing.List[BaseRoute]) -> dict: - raise NotImplementedError() # pragma: no cover - - def get_endpoints( - self, routes: typing.List[BaseRoute] - ) -> typing.List[EndpointInfo]: - """ - Given the routes, yields the following information: - - - path - eg: /users/ - - http_method - one of 'get', 'post', 'put', 'patch', 'delete', 'options' - - func - method ready to extract the docstring - """ - endpoints_info: list = [] - - for route in routes: - if isinstance(route, Mount): - path = self._remove_converter(route.path) - routes = route.routes or [] - sub_endpoints = [ - EndpointInfo( - path="".join((path, sub_endpoint.path)), - http_method=sub_endpoint.http_method, - func=sub_endpoint.func, - ) - for sub_endpoint in self.get_endpoints(routes) - ] - endpoints_info.extend(sub_endpoints) - - elif not isinstance(route, Route) or not route.include_in_schema: - continue - - elif inspect.isfunction(route.endpoint) or inspect.ismethod(route.endpoint): - path = self._remove_converter(route.path) - for method in route.methods or ["GET"]: - if method == "HEAD": - continue - endpoints_info.append( - EndpointInfo(path, method.lower(), route.endpoint) - ) - else: - path = self._remove_converter(route.path) - for method in ["get", "post", "put", "patch", "delete", "options"]: - if not hasattr(route.endpoint, method): - continue - func = getattr(route.endpoint, method) - endpoints_info.append(EndpointInfo(path, method.lower(), func)) - - return endpoints_info - - def _remove_converter(self, path: str) -> str: - """ - Remove the converter from the path. - For example, a route like this: - Route("/users/{id:int}", endpoint=get_user, methods=["GET"]) - Should be represented as `/users/{id}` in the OpenAPI schema. - """ - return re.sub(r":\w+}", "}", path) - - def parse_docstring(self, func_or_method: typing.Callable) -> dict: - """ - Given a function, parse the docstring as YAML and return a dictionary of info. - """ - docstring = func_or_method.__doc__ - if not docstring: - return {} - - assert yaml is not None, "`pyyaml` must be installed to use parse_docstring." - - # We support having regular docstrings before the schema - # definition. Here we return just the schema part from - # the docstring. - docstring = docstring.split("---")[-1] - - parsed = yaml.safe_load(docstring) - - if not isinstance(parsed, dict): - # A regular docstring (not yaml formatted) can return - # a simple string here, which wouldn't follow the schema. - return {} - - return parsed - - def OpenAPIResponse(self, request: Request) -> Response: - routes = request.app.routes - schema = self.get_schema(routes=routes) - return OpenAPIResponse(schema) - - -class SchemaGenerator(BaseSchemaGenerator): - def __init__(self, base_schema: dict) -> None: - self.base_schema = base_schema - - def get_schema(self, routes: typing.List[BaseRoute]) -> dict: - schema = dict(self.base_schema) - schema.setdefault("paths", {}) - endpoints_info = self.get_endpoints(routes) - - for endpoint in endpoints_info: - parsed = self.parse_docstring(endpoint.func) - - if not parsed: - continue - - if endpoint.path not in schema["paths"]: - schema["paths"][endpoint.path] = {} - - schema["paths"][endpoint.path][endpoint.http_method] = parsed - - return schema diff --git a/spaces/pscpeng/ChuanhuChatGPT/modules/openai_func.py b/spaces/pscpeng/ChuanhuChatGPT/modules/openai_func.py deleted file mode 100644 index fb07b16235476360ccc48849f5f9e761630efec3..0000000000000000000000000000000000000000 --- a/spaces/pscpeng/ChuanhuChatGPT/modules/openai_func.py +++ /dev/null @@ -1,82 +0,0 @@ -import requests -import logging -from modules.presets import ( - timeout_all, - USAGE_API_URL, - BALANCE_API_URL, - standard_error_msg, - connection_timeout_prompt, - error_retrieve_prompt, - read_timeout_prompt -) - -from modules import shared -from modules.utils import get_proxies -import os, datetime - -def get_billing_data(openai_api_key, billing_url): - headers = { - "Content-Type": "application/json", - "Authorization": f"Bearer {openai_api_key}" - } - - timeout = timeout_all - proxies = get_proxies() - response = requests.get( - billing_url, - headers=headers, - timeout=timeout, - proxies=proxies, - ) - - if response.status_code == 200: - data = response.json() - return data - else: - raise Exception(f"API request failed with status code {response.status_code}: {response.text}") - - -def get_usage(openai_api_key): - try: - balance_data=get_billing_data(openai_api_key, BALANCE_API_URL) - logging.debug(balance_data) - try: - balance = balance_data["total_available"] if balance_data["total_available"] else 0 - total_used = balance_data["total_used"] if balance_data["total_used"] else 0 - usage_percent = round(total_used / (total_used+balance) * 100, 2) - except Exception as e: - logging.error(f"API使用情况解析失败:"+str(e)) - balance = 0 - total_used=0 - return f"**API使用情况解析失败**" - if balance == 0: - last_day_of_month = datetime.datetime.now().strftime("%Y-%m-%d") - first_day_of_month = datetime.datetime.now().replace(day=1).strftime("%Y-%m-%d") - usage_url = f"{USAGE_API_URL}?start_date={first_day_of_month}&end_date={last_day_of_month}" - try: - usage_data = get_billing_data(openai_api_key, usage_url) - except Exception as e: - logging.error(f"获取API使用情况失败:"+str(e)) - return f"**获取API使用情况失败**" - return f"**本月使用金额** \u3000 ${usage_data['total_usage'] / 100}" - - # return f"**免费额度**(已用/余额)\u3000${total_used} / ${balance}" - return f"""\ - 免费额度使用情况 -
            -
            - {usage_percent}% -
            -
            -
            已用 ${total_used}可用 ${balance}
            - """ - - except requests.exceptions.ConnectTimeout: - status_text = standard_error_msg + connection_timeout_prompt + error_retrieve_prompt - return status_text - except requests.exceptions.ReadTimeout: - status_text = standard_error_msg + read_timeout_prompt + error_retrieve_prompt - return status_text - except Exception as e: - logging.error(f"获取API使用情况失败:"+str(e)) - return standard_error_msg + error_retrieve_prompt diff --git a/spaces/pyodide-demo/self-hosted/pywavelets.js b/spaces/pyodide-demo/self-hosted/pywavelets.js deleted file mode 100644 index 27885c7c3cc46cef1bc3cbb0d4e7a94deeb4c770..0000000000000000000000000000000000000000 --- a/spaces/pyodide-demo/self-hosted/pywavelets.js +++ /dev/null @@ -1 +0,0 @@ -var Module=typeof globalThis.__pyodide_module!=="undefined"?globalThis.__pyodide_module:{};if(!Module.expectedDataFileDownloads){Module.expectedDataFileDownloads=0}Module.expectedDataFileDownloads++;(function(){var loadPackage=function(metadata){var PACKAGE_PATH="";if(typeof window==="object"){PACKAGE_PATH=window["encodeURIComponent"](window.location.pathname.toString().substring(0,window.location.pathname.toString().lastIndexOf("/"))+"/")}else if(typeof process==="undefined"&&typeof location!=="undefined"){PACKAGE_PATH=encodeURIComponent(location.pathname.toString().substring(0,location.pathname.toString().lastIndexOf("/"))+"/")}var PACKAGE_NAME="pywavelets.data";var REMOTE_PACKAGE_BASE="pywavelets.data";if(typeof Module["locateFilePackage"]==="function"&&!Module["locateFile"]){Module["locateFile"]=Module["locateFilePackage"];err("warning: you defined Module.locateFilePackage, that has been renamed to Module.locateFile (using your locateFilePackage for now)")}var REMOTE_PACKAGE_NAME=Module["locateFile"]?Module["locateFile"](REMOTE_PACKAGE_BASE,""):REMOTE_PACKAGE_BASE;var REMOTE_PACKAGE_SIZE=metadata["remote_package_size"];var PACKAGE_UUID=metadata["package_uuid"];function fetchRemotePackage(packageName,packageSize,callback,errback){if(typeof process==="object"){require("fs").readFile(packageName,(function(err,contents){if(err){errback(err)}else{callback(contents.buffer)}}));return}var xhr=new XMLHttpRequest;xhr.open("GET",packageName,true);xhr.responseType="arraybuffer";xhr.onprogress=function(event){var url=packageName;var size=packageSize;if(event.total)size=event.total;if(event.loaded){if(!xhr.addedTotal){xhr.addedTotal=true;if(!Module.dataFileDownloads)Module.dataFileDownloads={};Module.dataFileDownloads[url]={loaded:event.loaded,total:size}}else{Module.dataFileDownloads[url].loaded=event.loaded}var total=0;var loaded=0;var num=0;for(var download in Module.dataFileDownloads){var data=Module.dataFileDownloads[download];total+=data.total;loaded+=data.loaded;num++}total=Math.ceil(total*Module.expectedDataFileDownloads/num);if(Module["setStatus"])Module["setStatus"]("Downloading data... ("+loaded+"/"+total+")")}else if(!Module.dataFileDownloads){if(Module["setStatus"])Module["setStatus"]("Downloading data...")}};xhr.onerror=function(event){throw new Error("NetworkError for: "+packageName)};xhr.onload=function(event){if(xhr.status==200||xhr.status==304||xhr.status==206||xhr.status==0&&xhr.response){var packageData=xhr.response;callback(packageData)}else{throw new Error(xhr.statusText+" : "+xhr.responseURL)}};xhr.send(null)}function handleError(error){console.error("package error:",error)}var fetchedCallback=null;var fetched=Module["getPreloadedPackage"]?Module["getPreloadedPackage"](REMOTE_PACKAGE_NAME,REMOTE_PACKAGE_SIZE):null;if(!fetched)fetchRemotePackage(REMOTE_PACKAGE_NAME,REMOTE_PACKAGE_SIZE,(function(data){if(fetchedCallback){fetchedCallback(data);fetchedCallback=null}else{fetched=data}}),handleError);function runWithFS(){function assert(check,msg){if(!check)throw msg+(new Error).stack}Module["FS_createPath"]("/","lib",true,true);Module["FS_createPath"]("/lib","python3.9",true,true);Module["FS_createPath"]("/lib/python3.9","site-packages",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages","pywt",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/pywt","_extensions",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/pywt","data",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages","PyWavelets-1.2.0-py3.9.egg-info",true,true);function processPackageData(arrayBuffer){assert(arrayBuffer,"Loading data file failed.");assert(arrayBuffer instanceof ArrayBuffer,"bad input to processPackageData");var byteArray=new Uint8Array(arrayBuffer);var curr;var compressedData={data:null,cachedOffset:1684420,cachedIndexes:[-1,-1],cachedChunks:[null,null],offsets:[0,1371,2735,4048,5236,6482,7663,8898,10270,11358,12706,14010,15289,16583,18037,19071,20272,21349,22308,23540,25037,26389,27927,29287,30723,32181,33454,34877,36225,37597,38850,40129,41436,42844,44311,45681,47002,48351,49691,50782,52227,53302,54470,55706,56820,57945,59191,60031,61331,62609,63966,65264,66533,67586,68745,69842,70953,72323,73943,75483,76783,78064,79478,80686,82033,83497,84822,86198,87374,88544,89980,91316,92567,93191,94487,95928,97251,98573,99840,101097,101967,103270,104513,105792,107053,108345,109643,110760,111829,113074,114137,115217,116337,117449,118529,119722,120749,121971,123302,124596,125846,127150,128319,129637,130930,132197,133347,134606,135816,136969,137991,139010,140023,141038,142061,143087,144095,145252,146328,147477,148990,150261,151802,153152,154547,155833,157115,158283,159673,161112,162403,163826,164986,166441,167839,168912,170278,171727,173073,174514,175860,177255,178597,180057,181465,182788,184175,185682,187226,188633,190274,191835,193314,194513,195921,197212,198714,200253,201624,202911,204228,205570,206855,208145,209660,210903,212177,212936,214086,215466,216298,217054,217901,218867,220025,221042,222230,222911,224289,225378,226107,226794,227557,228328,229088,229776,230468,231183,231880,232591,233382,234302,235133,236604,238071,239514,240895,242327,243689,245205,246391,247589,248996,250432,252018,253441,254859,256336,257757,259188,260514,262208,263408,264957,266564,268020,269488,270693,272086,273585,274817,276311,277616,279076,280591,282023,283547,284891,286439,287853,289422,290953,292072,293130,293948,295270,296461,297554,298451,299425,300626,301846,302962,304111,305131,306102,307283,308565,309910,311213,312373,313355,314391,315668,316772,318151,319404,320768,322023,323475,324948,326402,327375,328610,330026,331408,332592,333938,335295,336403,337365,338467,339804,341165,342475,343861,345241,346481,347462,348631,349652,350650,352024,354008,356047,358098,360152,362200,364248,366296,368344,370395,372434,374482,376531,378587,380640,382688,384736,386625,387776,388873,389917,390615,391791,392915,393869,394912,395898,396967,398154,399460,399485,400101,401364,402647,403733,404992,406177,407223,408264,409366,410404,411476,412733,414325,415801,417286,418742,420108,421417,422664,424136,425557,426729,428092,429438,430627,431921,433336,434586,436003,437557,439043,440265,441789,443254,444830,446478,447990,449306,450845,452381,453931,455454,456943,457771,458568,459560,460599,462006,462682,463338,463960,464801,466158,467541,468927,470220,471542,472892,474172,475464,476807,478269,479724,481185,482606,484018,485516,486939,488185,489324,490813,492400,493912,495389,496960,498451,499799,501096,502801,504171,505673,507254,508632,510005,511349,512807,514110,515468,517044,518355,519715,521272,522566,523911,525413,526830,528221,529706,531152,531996,533072,534516,535760,537067,538336,539795,540703,541782,543262,544770,546213,547685,549062,550433,551937,553284,554705,556212,557655,559147,560380,561212,562646,564115,565287,566370,567330,568383,569670,570898,572044,573041,573872,575213,576441,577668,578737,579850,580862,582190,583340,584448,585576,586565,587530,588835,590091,591437,592828,594142,595496,596895,598303,599746,601228,602378,603679,604996,606412,607464,608980,610199,611510,612919,614065,614995,615948,617761,619806,621856,623911,625959,628007,630055,632103,634151,636189,638245,640293,642345,644396,646444,648492,650540,652030,653114,654204,655222,656050,657140,657363,658652,659992,661153,662301,663470,664512,665553,666691,667758,668833,670083,671353,672897,674241,675430,676595,678051,679472,680876,682405,683965,685481,686940,688536,690141,691798,693374,694866,696079,696774,697800,698861,700093,701430,702231,703071,704523,705979,707466,708912,710353,711839,713151,714432,715476,716847,718405,719859,721287,722840,724248,725753,727250,728604,730038,731333,733040,734420,735923,737538,739008,740351,741583,742950,744392,745365,746751,748094,749353,750711,752138,753243,754525,755878,757228,758482,759879,761033,762336,763745,765137,766389,767827,768989,770252,771634,773009,774239,775727,777142,777851,779251,780726,782267,783406,784469,785311,786657,787815,788926,789839,790823,792032,793207,794330,795454,796506,797456,798618,799891,801220,802484,803642,804699,805722,806966,808109,809464,810738,812141,813418,814814,816265,817726,818729,820016,821403,822819,823994,825578,826839,828225,829720,830791,831829,833244,835121,837168,839212,841265,843313,845361,847409,849457,851505,853534,855582,857635,859679,861727,863775,865823,867855,869105,870153,871244,872213,873180,874093,874858,876172,877459,878383,879698,880746,881787,882967,884036,885206,886389,887180,888268,889268,890696,891507,892862,893787,894993,896377,897817,899092,900470,901839,903298,904785,906169,907538,909064,909992,911193,912578,914002,915277,916666,918055,919539,921040,922440,923829,925357,926806,928259,929667,931123,932482,934101,935548,936789,937887,939366,940953,942533,943916,945372,946924,948343,949785,951299,952850,954210,955685,957152,958614,959801,961396,963019,964559,966047,967454,968745,970406,971944,973526,975038,976487,977703,979096,980603,981780,982797,983729,984830,986056,987238,988391,989318,990163,991521,992776,993963,995104,996164,997185,998509,999638,1000717,1001832,1002794,1003729,1005009,1006293,1007681,1009030,1010370,1011674,1013087,1014504,1015911,1017352,1018545,1019815,1021122,1022528,1023610,1025066,1026493,1027821,1028833,1029933,1031157,1032960,1035e3,1037050,1039105,1041153,1043201,1045249,1047297,1049345,1051380,1053436,1055490,1057541,1059589,1061637,1063685,1065733,1067203,1068248,1069336,1070279,1071511,1071887,1072810,1073878,1075440,1076685,1077813,1078918,1080141,1081636,1083031,1084976,1087024,1089072,1091120,1093168,1095216,1097264,1099312,1101360,1103408,1105456,1107504,1109552,1111600,1113648,1115696,1117744,1119792,1121840,1123888,1125936,1127984,1130032,1132080,1134128,1136176,1138224,1140272,1142320,1144368,1146416,1148464,1150512,1152560,1154608,1156656,1158704,1160752,1162800,1164848,1166896,1168944,1170992,1173040,1175088,1177136,1179184,1181232,1183280,1185328,1187376,1189424,1191472,1193520,1195568,1197616,1199664,1201712,1203760,1205808,1207856,1209904,1211952,1214e3,1216048,1218096,1220144,1222192,1224240,1226288,1228336,1230384,1232432,1234480,1236528,1238576,1240624,1242672,1244720,1246768,1248816,1250864,1252912,1254960,1257008,1259056,1261104,1263152,1265200,1267248,1269296,1271344,1273392,1275440,1277488,1279536,1281584,1283632,1285680,1287728,1289776,1291824,1293872,1295920,1297968,1300016,1302064,1304112,1306160,1308208,1310256,1312300,1314348,1316396,1318444,1320492,1322540,1324588,1326636,1328684,1330732,1332780,1334828,1336876,1338924,1340972,1343020,1345068,1347116,1349164,1351212,1353260,1355308,1357356,1359404,1361452,1363500,1365548,1367596,1369644,1371692,1373740,1375788,1377836,1379884,1381932,1383980,1386028,1388076,1390124,1392172,1394220,1396268,1398316,1400364,1402412,1404460,1406508,1408556,1410604,1412652,1414700,1416748,1418796,1420844,1422892,1424940,1426988,1429036,1431084,1433132,1435180,1437228,1439276,1441324,1443372,1445420,1447468,1449516,1451564,1453612,1455660,1457708,1459756,1461804,1463852,1465900,1467948,1469996,1472044,1474092,1476140,1478188,1480236,1482284,1484332,1486380,1488428,1490476,1492524,1494572,1496620,1498668,1500716,1502764,1504812,1506860,1508908,1510956,1513004,1515052,1517100,1519148,1521196,1523244,1525292,1527340,1529388,1531436,1533484,1535532,1537580,1539628,1541676,1543724,1545772,1547820,1549868,1551916,1553964,1556012,1558060,1560108,1562156,1564204,1566252,1568300,1570348,1572396,1574444,1576492,1578540,1580588,1582636,1584684,1586732,1588780,1590828,1592876,1594924,1596972,1599020,1601068,1603116,1605164,1607212,1609260,1611308,1613356,1615404,1617452,1619500,1621548,1623596,1625644,1627692,1629740,1631788,1633836,1635884,1637932,1639980,1642028,1644076,1646124,1648172,1650220,1651261,1651456,1651650,1651832,1651912,1651992,1652466,1653649,1654841,1656072,1657175,1658279,1659387,1660525,1661676,1662824,1663953,1665047,1666121,1667256,1668370,1669457,1670594,1671666,1672729,1673892,1675012,1676145,1677329,1678405,1679501,1680754,1681915,1682838,1683666],sizes:[1371,1364,1313,1188,1246,1181,1235,1372,1088,1348,1304,1279,1294,1454,1034,1201,1077,959,1232,1497,1352,1538,1360,1436,1458,1273,1423,1348,1372,1253,1279,1307,1408,1467,1370,1321,1349,1340,1091,1445,1075,1168,1236,1114,1125,1246,840,1300,1278,1357,1298,1269,1053,1159,1097,1111,1370,1620,1540,1300,1281,1414,1208,1347,1464,1325,1376,1176,1170,1436,1336,1251,624,1296,1441,1323,1322,1267,1257,870,1303,1243,1279,1261,1292,1298,1117,1069,1245,1063,1080,1120,1112,1080,1193,1027,1222,1331,1294,1250,1304,1169,1318,1293,1267,1150,1259,1210,1153,1022,1019,1013,1015,1023,1026,1008,1157,1076,1149,1513,1271,1541,1350,1395,1286,1282,1168,1390,1439,1291,1423,1160,1455,1398,1073,1366,1449,1346,1441,1346,1395,1342,1460,1408,1323,1387,1507,1544,1407,1641,1561,1479,1199,1408,1291,1502,1539,1371,1287,1317,1342,1285,1290,1515,1243,1274,759,1150,1380,832,756,847,966,1158,1017,1188,681,1378,1089,729,687,763,771,760,688,692,715,697,711,791,920,831,1471,1467,1443,1381,1432,1362,1516,1186,1198,1407,1436,1586,1423,1418,1477,1421,1431,1326,1694,1200,1549,1607,1456,1468,1205,1393,1499,1232,1494,1305,1460,1515,1432,1524,1344,1548,1414,1569,1531,1119,1058,818,1322,1191,1093,897,974,1201,1220,1116,1149,1020,971,1181,1282,1345,1303,1160,982,1036,1277,1104,1379,1253,1364,1255,1452,1473,1454,973,1235,1416,1382,1184,1346,1357,1108,962,1102,1337,1361,1310,1386,1380,1240,981,1169,1021,998,1374,1984,2039,2051,2054,2048,2048,2048,2048,2051,2039,2048,2049,2056,2053,2048,2048,1889,1151,1097,1044,698,1176,1124,954,1043,986,1069,1187,1306,25,616,1263,1283,1086,1259,1185,1046,1041,1102,1038,1072,1257,1592,1476,1485,1456,1366,1309,1247,1472,1421,1172,1363,1346,1189,1294,1415,1250,1417,1554,1486,1222,1524,1465,1576,1648,1512,1316,1539,1536,1550,1523,1489,828,797,992,1039,1407,676,656,622,841,1357,1383,1386,1293,1322,1350,1280,1292,1343,1462,1455,1461,1421,1412,1498,1423,1246,1139,1489,1587,1512,1477,1571,1491,1348,1297,1705,1370,1502,1581,1378,1373,1344,1458,1303,1358,1576,1311,1360,1557,1294,1345,1502,1417,1391,1485,1446,844,1076,1444,1244,1307,1269,1459,908,1079,1480,1508,1443,1472,1377,1371,1504,1347,1421,1507,1443,1492,1233,832,1434,1469,1172,1083,960,1053,1287,1228,1146,997,831,1341,1228,1227,1069,1113,1012,1328,1150,1108,1128,989,965,1305,1256,1346,1391,1314,1354,1399,1408,1443,1482,1150,1301,1317,1416,1052,1516,1219,1311,1409,1146,930,953,1813,2045,2050,2055,2048,2048,2048,2048,2048,2038,2056,2048,2052,2051,2048,2048,2048,1490,1084,1090,1018,828,1090,223,1289,1340,1161,1148,1169,1042,1041,1138,1067,1075,1250,1270,1544,1344,1189,1165,1456,1421,1404,1529,1560,1516,1459,1596,1605,1657,1576,1492,1213,695,1026,1061,1232,1337,801,840,1452,1456,1487,1446,1441,1486,1312,1281,1044,1371,1558,1454,1428,1553,1408,1505,1497,1354,1434,1295,1707,1380,1503,1615,1470,1343,1232,1367,1442,973,1386,1343,1259,1358,1427,1105,1282,1353,1350,1254,1397,1154,1303,1409,1392,1252,1438,1162,1263,1382,1375,1230,1488,1415,709,1400,1475,1541,1139,1063,842,1346,1158,1111,913,984,1209,1175,1123,1124,1052,950,1162,1273,1329,1264,1158,1057,1023,1244,1143,1355,1274,1403,1277,1396,1451,1461,1003,1287,1387,1416,1175,1584,1261,1386,1495,1071,1038,1415,1877,2047,2044,2053,2048,2048,2048,2048,2048,2029,2048,2053,2044,2048,2048,2048,2032,1250,1048,1091,969,967,913,765,1314,1287,924,1315,1048,1041,1180,1069,1170,1183,791,1088,1e3,1428,811,1355,925,1206,1384,1440,1275,1378,1369,1459,1487,1384,1369,1526,928,1201,1385,1424,1275,1389,1389,1484,1501,1400,1389,1528,1449,1453,1408,1456,1359,1619,1447,1241,1098,1479,1587,1580,1383,1456,1552,1419,1442,1514,1551,1360,1475,1467,1462,1187,1595,1623,1540,1488,1407,1291,1661,1538,1582,1512,1449,1216,1393,1507,1177,1017,932,1101,1226,1182,1153,927,845,1358,1255,1187,1141,1060,1021,1324,1129,1079,1115,962,935,1280,1284,1388,1349,1340,1304,1413,1417,1407,1441,1193,1270,1307,1406,1082,1456,1427,1328,1012,1100,1224,1803,2040,2050,2055,2048,2048,2048,2048,2048,2035,2056,2054,2051,2048,2048,2048,2048,1470,1045,1088,943,1232,376,923,1068,1562,1245,1128,1105,1223,1495,1395,1945,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2044,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,1041,195,194,182,80,80,474,1183,1192,1231,1103,1104,1108,1138,1151,1148,1129,1094,1074,1135,1114,1087,1137,1072,1063,1163,1120,1133,1184,1076,1096,1253,1161,923,828,754],successes:[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,0,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,0,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,0,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]};compressedData["data"]=byteArray;assert(typeof Module.LZ4==="object","LZ4 not present - was your app build with -s LZ4=1 ?");Module.LZ4.loadPackage({metadata:metadata,compressedData:compressedData},true);Module["removeRunDependency"]("datafile_pywavelets.data")}Module["addRunDependency"]("datafile_pywavelets.data");if(!Module.preloadResults)Module.preloadResults={};Module.preloadResults[PACKAGE_NAME]={fromCache:false};if(fetched){processPackageData(fetched);fetched=null}else{fetchedCallback=processPackageData}}if(Module["calledRun"]){runWithFS()}else{if(!Module["preRun"])Module["preRun"]=[];Module["preRun"].push(runWithFS)}};loadPackage({files:[{filename:"/lib/python3.9/site-packages/pywt/__init__.py",start:0,end:1093,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_c99_config.py",start:1093,end:1173,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_cwt.py",start:1173,end:8888,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_doc_utils.py",start:8888,end:14711,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_dwt.py",start:14711,end:31938,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_functions.py",start:31938,end:38937,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_mra.py",start:38937,end:53301,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_multidim.py",start:53301,end:64744,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_multilevel.py",start:64744,end:121908,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_pytest.py",start:121908,end:124421,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_pytesttester.py",start:124421,end:129324,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_swt.py",start:129324,end:161166,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_thresholding.py",start:161166,end:169959,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_utils.py",start:169959,end:173443,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_wavelet_packets.py",start:173443,end:210180,audio:0},{filename:"/lib/python3.9/site-packages/pywt/version.py",start:210180,end:210413,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_extensions/__init__.py",start:210413,end:210413,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_extensions/_pywt.so",start:210413,end:640188,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_extensions/_dwt.so",start:640188,end:1029854,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_extensions/_swt.so",start:1029854,end:1356701,audio:0},{filename:"/lib/python3.9/site-packages/pywt/_extensions/_cwt.so",start:1356701,end:1650238,audio:0},{filename:"/lib/python3.9/site-packages/pywt/data/__init__.py",start:1650238,end:1650334,audio:0},{filename:"/lib/python3.9/site-packages/pywt/data/_readers.py",start:1650334,end:1655251,audio:0},{filename:"/lib/python3.9/site-packages/pywt/data/_wavelab_signals.py",start:1655251,end:1664727,audio:0},{filename:"/lib/python3.9/site-packages/pywt/data/create_dat.py",start:1664727,end:1665352,audio:0},{filename:"/lib/python3.9/site-packages/pywt/data/ecg.npy",start:1665352,end:1669528,audio:0},{filename:"/lib/python3.9/site-packages/pywt/data/aero.npz",start:1669528,end:1897312,audio:0},{filename:"/lib/python3.9/site-packages/pywt/data/ascent.npz",start:1897312,end:2068195,audio:0},{filename:"/lib/python3.9/site-packages/pywt/data/camera.npz",start:2068195,end:2237229,audio:0},{filename:"/lib/python3.9/site-packages/pywt/data/sst_nino3.npz",start:2237229,end:2301429,audio:0},{filename:"/lib/python3.9/site-packages/PyWavelets-1.2.0-py3.9.egg-info/PKG-INFO",start:2301429,end:2303317,audio:0},{filename:"/lib/python3.9/site-packages/PyWavelets-1.2.0-py3.9.egg-info/SOURCES.txt",start:2303317,end:2309826,audio:0},{filename:"/lib/python3.9/site-packages/PyWavelets-1.2.0-py3.9.egg-info/dependency_links.txt",start:2309826,end:2309827,audio:0},{filename:"/lib/python3.9/site-packages/PyWavelets-1.2.0-py3.9.egg-info/requires.txt",start:2309827,end:2309841,audio:0},{filename:"/lib/python3.9/site-packages/PyWavelets-1.2.0-py3.9.egg-info/top_level.txt",start:2309841,end:2309846,audio:0}],remote_package_size:1688516,package_uuid:"1cdf0952-419e-45fb-a13a-8c7874c310a3"})})(); \ No newline at end of file diff --git a/spaces/quidiaMuxgu/Expedit-SAM/Gran Turismo 4 PS2 PAL DVD5 RIP ISO 141.md b/spaces/quidiaMuxgu/Expedit-SAM/Gran Turismo 4 PS2 PAL DVD5 RIP ISO 141.md deleted file mode 100644 index ea80fdd1ff0d20463766d9a89706356fdeb65d63..0000000000000000000000000000000000000000 --- a/spaces/quidiaMuxgu/Expedit-SAM/Gran Turismo 4 PS2 PAL DVD5 RIP ISO 141.md +++ /dev/null @@ -1,6 +0,0 @@ -

            Gran Turismo 4 PS2 PAL DVD5 RIP ISO 141


            Download ⚹⚹⚹ https://geags.com/2uCrWD



            - -... jungle book cartoon in urdu free downloadgolkes samsung s27b350 driver downloadtrmds. 3/3 Gran Turismo 4 PS2 PAL DVD5 RIP ISO 141. 4d29de3e1b
            -
            -
            -

            diff --git a/spaces/r3gm/RVC_HF/tools/calc_rvc_model_similarity.py b/spaces/r3gm/RVC_HF/tools/calc_rvc_model_similarity.py deleted file mode 100644 index 42496e088e51dc5162d0714470c2226f696e260c..0000000000000000000000000000000000000000 --- a/spaces/r3gm/RVC_HF/tools/calc_rvc_model_similarity.py +++ /dev/null @@ -1,96 +0,0 @@ -# This code references https://huggingface.co/JosephusCheung/ASimilarityCalculatior/blob/main/qwerty.py -# Fill in the path of the model to be queried and the root directory of the reference models, and this script will return the similarity between the model to be queried and all reference models. -import os -import logging - -logger = logging.getLogger(__name__) - -import torch -import torch.nn as nn -import torch.nn.functional as F - - -def cal_cross_attn(to_q, to_k, to_v, rand_input): - hidden_dim, embed_dim = to_q.shape - attn_to_q = nn.Linear(hidden_dim, embed_dim, bias=False) - attn_to_k = nn.Linear(hidden_dim, embed_dim, bias=False) - attn_to_v = nn.Linear(hidden_dim, embed_dim, bias=False) - attn_to_q.load_state_dict({"weight": to_q}) - attn_to_k.load_state_dict({"weight": to_k}) - attn_to_v.load_state_dict({"weight": to_v}) - - return torch.einsum( - "ik, jk -> ik", - F.softmax( - torch.einsum("ij, kj -> ik", attn_to_q(rand_input), attn_to_k(rand_input)), - dim=-1, - ), - attn_to_v(rand_input), - ) - - -def model_hash(filename): - try: - with open(filename, "rb") as file: - import hashlib - - m = hashlib.sha256() - - file.seek(0x100000) - m.update(file.read(0x10000)) - return m.hexdigest()[0:8] - except FileNotFoundError: - return "NOFILE" - - -def eval(model, n, input): - qk = f"enc_p.encoder.attn_layers.{n}.conv_q.weight" - uk = f"enc_p.encoder.attn_layers.{n}.conv_k.weight" - vk = f"enc_p.encoder.attn_layers.{n}.conv_v.weight" - atoq, atok, atov = model[qk][:, :, 0], model[uk][:, :, 0], model[vk][:, :, 0] - - attn = cal_cross_attn(atoq, atok, atov, input) - return attn - - -def main(path, root): - torch.manual_seed(114514) - model_a = torch.load(path, map_location="cpu")["weight"] - - logger.info("Query:\t\t%s\t%s" % (path, model_hash(path))) - - map_attn_a = {} - map_rand_input = {} - for n in range(6): - hidden_dim, embed_dim, _ = model_a[ - f"enc_p.encoder.attn_layers.{n}.conv_v.weight" - ].shape - rand_input = torch.randn([embed_dim, hidden_dim]) - - map_attn_a[n] = eval(model_a, n, rand_input) - map_rand_input[n] = rand_input - - del model_a - - for name in sorted(list(os.listdir(root))): - path = "%s/%s" % (root, name) - model_b = torch.load(path, map_location="cpu")["weight"] - - sims = [] - for n in range(6): - attn_a = map_attn_a[n] - attn_b = eval(model_b, n, map_rand_input[n]) - - sim = torch.mean(torch.cosine_similarity(attn_a, attn_b)) - sims.append(sim) - - logger.info( - "Reference:\t%s\t%s\t%s" - % (path, model_hash(path), f"{torch.mean(torch.stack(sims)) * 1e2:.2f}%") - ) - - -if __name__ == "__main__": - query_path = r"assets\weights\mi v3.pth" - reference_root = r"assets\weights" - main(query_path, reference_root) diff --git a/spaces/rachana219/MODT2/trackers/reid_export.py b/spaces/rachana219/MODT2/trackers/reid_export.py deleted file mode 100644 index 9ef8d13c148963ce2338a17c9e9c6a24a0f6d4fb..0000000000000000000000000000000000000000 --- a/spaces/rachana219/MODT2/trackers/reid_export.py +++ /dev/null @@ -1,313 +0,0 @@ -import argparse - -import os -# limit the number of cpus used by high performance libraries -os.environ["OMP_NUM_THREADS"] = "1" -os.environ["OPENBLAS_NUM_THREADS"] = "1" -os.environ["MKL_NUM_THREADS"] = "1" -os.environ["VECLIB_MAXIMUM_THREADS"] = "1" -os.environ["NUMEXPR_NUM_THREADS"] = "1" - -import sys -import numpy as np -from pathlib import Path -import torch -import time -import platform -import pandas as pd -import subprocess -import torch.backends.cudnn as cudnn -from torch.utils.mobile_optimizer import optimize_for_mobile - -FILE = Path(__file__).resolve() -ROOT = FILE.parents[0].parents[0] # yolov5 strongsort root directory -WEIGHTS = ROOT / 'weights' - - -if str(ROOT) not in sys.path: - sys.path.append(str(ROOT)) # add ROOT to PATH -if str(ROOT / 'yolov5') not in sys.path: - sys.path.append(str(ROOT / 'yolov5')) # add yolov5 ROOT to PATH - -ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative - -import logging -from ultralytics.yolo.utils.torch_utils import select_device -from ultralytics.yolo.utils import LOGGER, colorstr, ops -from ultralytics.yolo.utils.checks import check_requirements, check_version -from trackers.strongsort.deep.models import build_model -from trackers.strongsort.deep.reid_model_factory import get_model_name, load_pretrained_weights - - -def file_size(path): - # Return file/dir size (MB) - path = Path(path) - if path.is_file(): - return path.stat().st_size / 1E6 - elif path.is_dir(): - return sum(f.stat().st_size for f in path.glob('**/*') if f.is_file()) / 1E6 - else: - return 0.0 - - -def export_formats(): - # YOLOv5 export formats - x = [ - ['PyTorch', '-', '.pt', True, True], - ['TorchScript', 'torchscript', '.torchscript', True, True], - ['ONNX', 'onnx', '.onnx', True, True], - ['OpenVINO', 'openvino', '_openvino_model', True, False], - ['TensorRT', 'engine', '.engine', False, True], - ['TensorFlow Lite', 'tflite', '.tflite', True, False], - ] - return pd.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'CPU', 'GPU']) - - -def export_torchscript(model, im, file, optimize, prefix=colorstr('TorchScript:')): - # YOLOv5 TorchScript model export - try: - LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...') - f = file.with_suffix('.torchscript') - - ts = torch.jit.trace(model, im, strict=False) - if optimize: # https://pytorch.org/tutorials/recipes/mobile_interpreter.html - optimize_for_mobile(ts)._save_for_lite_interpreter(str(f)) - else: - ts.save(str(f)) - - LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') - return f - except Exception as e: - LOGGER.info(f'{prefix} export failure: {e}') - - -def export_onnx(model, im, file, opset, dynamic, simplify, prefix=colorstr('ONNX:')): - # ONNX export - try: - check_requirements(('onnx',)) - import onnx - - f = file.with_suffix('.onnx') - LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...') - - if dynamic: - dynamic = {'images': {0: 'batch'}} # shape(1,3,640,640) - dynamic['output'] = {0: 'batch'} # shape(1,25200,85) - - torch.onnx.export( - model.cpu() if dynamic else model, # --dynamic only compatible with cpu - im.cpu() if dynamic else im, - f, - verbose=False, - opset_version=opset, - do_constant_folding=True, - input_names=['images'], - output_names=['output'], - dynamic_axes=dynamic or None - ) - # Checks - model_onnx = onnx.load(f) # load onnx model - onnx.checker.check_model(model_onnx) # check onnx model - onnx.save(model_onnx, f) - - # Simplify - if simplify: - try: - cuda = torch.cuda.is_available() - check_requirements(('onnxruntime-gpu' if cuda else 'onnxruntime', 'onnx-simplifier>=0.4.1')) - import onnxsim - - LOGGER.info(f'simplifying with onnx-simplifier {onnxsim.__version__}...') - model_onnx, check = onnxsim.simplify(model_onnx) - assert check, 'assert check failed' - onnx.save(model_onnx, f) - except Exception as e: - LOGGER.info(f'simplifier failure: {e}') - LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') - return f - except Exception as e: - LOGGER.info(f'export failure: {e}') - - - -def export_openvino(file, half, prefix=colorstr('OpenVINO:')): - # YOLOv5 OpenVINO export - check_requirements(('openvino-dev',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/ - import openvino.inference_engine as ie - try: - LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...') - f = str(file).replace('.pt', f'_openvino_model{os.sep}') - - cmd = f"mo --input_model {file.with_suffix('.onnx')} --output_dir {f} --data_type {'FP16' if half else 'FP32'}" - subprocess.check_output(cmd.split()) # export - except Exception as e: - LOGGER.info(f'export failure: {e}') - LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') - return f - - -def export_tflite(file, half, prefix=colorstr('TFLite:')): - # YOLOv5 OpenVINO export - try: - check_requirements(('openvino2tensorflow', 'tensorflow', 'tensorflow_datasets')) # requires openvino-dev: https://pypi.org/project/openvino-dev/ - import openvino.inference_engine as ie - LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...') - output = Path(str(file).replace(f'_openvino_model{os.sep}', f'_tflite_model{os.sep}')) - modelxml = list(Path(file).glob('*.xml'))[0] - cmd = f"openvino2tensorflow \ - --model_path {modelxml} \ - --model_output_path {output} \ - --output_pb \ - --output_saved_model \ - --output_no_quant_float32_tflite \ - --output_dynamic_range_quant_tflite" - subprocess.check_output(cmd.split()) # export - - LOGGER.info(f'{prefix} export success, results saved in {output} ({file_size(f):.1f} MB)') - return f - except Exception as e: - LOGGER.info(f'\n{prefix} export failure: {e}') - - -def export_engine(model, im, file, half, dynamic, simplify, workspace=4, verbose=False, prefix=colorstr('TensorRT:')): - # YOLOv5 TensorRT export https://developer.nvidia.com/tensorrt - try: - assert im.device.type != 'cpu', 'export running on CPU but must be on GPU, i.e. `python export.py --device 0`' - try: - import tensorrt as trt - except Exception: - if platform.system() == 'Linux': - check_requirements(('nvidia-tensorrt',), cmds=('-U --index-url https://pypi.ngc.nvidia.com',)) - import tensorrt as trt - - if trt.__version__[0] == '7': # TensorRT 7 handling https://github.com/ultralytics/yolov5/issues/6012 - grid = model.model[-1].anchor_grid - model.model[-1].anchor_grid = [a[..., :1, :1, :] for a in grid] - export_onnx(model, im, file, 12, dynamic, simplify) # opset 12 - model.model[-1].anchor_grid = grid - else: # TensorRT >= 8 - check_version(trt.__version__, '8.0.0', hard=True) # require tensorrt>=8.0.0 - export_onnx(model, im, file, 12, dynamic, simplify) # opset 13 - onnx = file.with_suffix('.onnx') - - LOGGER.info(f'\n{prefix} starting export with TensorRT {trt.__version__}...') - assert onnx.exists(), f'failed to export ONNX file: {onnx}' - f = file.with_suffix('.engine') # TensorRT engine file - logger = trt.Logger(trt.Logger.INFO) - if verbose: - logger.min_severity = trt.Logger.Severity.VERBOSE - - builder = trt.Builder(logger) - config = builder.create_builder_config() - config.max_workspace_size = workspace * 1 << 30 - # config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace << 30) # fix TRT 8.4 deprecation notice - - flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) - network = builder.create_network(flag) - parser = trt.OnnxParser(network, logger) - if not parser.parse_from_file(str(onnx)): - raise RuntimeError(f'failed to load ONNX file: {onnx}') - - inputs = [network.get_input(i) for i in range(network.num_inputs)] - outputs = [network.get_output(i) for i in range(network.num_outputs)] - LOGGER.info(f'{prefix} Network Description:') - for inp in inputs: - LOGGER.info(f'{prefix}\tinput "{inp.name}" with shape {inp.shape} and dtype {inp.dtype}') - for out in outputs: - LOGGER.info(f'{prefix}\toutput "{out.name}" with shape {out.shape} and dtype {out.dtype}') - - if dynamic: - if im.shape[0] <= 1: - LOGGER.warning(f"{prefix}WARNING: --dynamic model requires maximum --batch-size argument") - profile = builder.create_optimization_profile() - for inp in inputs: - profile.set_shape(inp.name, (1, *im.shape[1:]), (max(1, im.shape[0] // 2), *im.shape[1:]), im.shape) - config.add_optimization_profile(profile) - - LOGGER.info(f'{prefix} building FP{16 if builder.platform_has_fast_fp16 and half else 32} engine in {f}') - if builder.platform_has_fast_fp16 and half: - config.set_flag(trt.BuilderFlag.FP16) - with builder.build_engine(network, config) as engine, open(f, 'wb') as t: - t.write(engine.serialize()) - LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') - return f - except Exception as e: - LOGGER.info(f'\n{prefix} export failure: {e}') - - -if __name__ == "__main__": - - parser = argparse.ArgumentParser(description="ReID export") - parser.add_argument('--batch-size', type=int, default=1, help='batch size') - parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[256, 128], help='image (h, w)') - parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') - parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile') - parser.add_argument('--dynamic', action='store_true', help='ONNX/TF/TensorRT: dynamic axes') - parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model') - parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version') - parser.add_argument('--workspace', type=int, default=4, help='TensorRT: workspace size (GB)') - parser.add_argument('--verbose', action='store_true', help='TensorRT: verbose log') - parser.add_argument('--weights', nargs='+', type=str, default=WEIGHTS / 'osnet_x0_25_msmt17.pt', help='model.pt path(s)') - parser.add_argument('--half', action='store_true', help='FP16 half-precision export') - parser.add_argument('--include', - nargs='+', - default=['torchscript'], - help='torchscript, onnx, openvino, engine') - args = parser.parse_args() - - t = time.time() - - include = [x.lower() for x in args.include] # to lowercase - fmts = tuple(export_formats()['Argument'][1:]) # --include arguments - flags = [x in include for x in fmts] - assert sum(flags) == len(include), f'ERROR: Invalid --include {include}, valid --include arguments are {fmts}' - jit, onnx, openvino, engine, tflite = flags # export booleans - - args.device = select_device(args.device) - if args.half: - assert args.device.type != 'cpu', '--half only compatible with GPU export, i.e. use --device 0' - assert not args.dynamic, '--half not compatible with --dynamic, i.e. use either --half or --dynamic but not both' - - if type(args.weights) is list: - args.weights = Path(args.weights[0]) - - model = build_model( - get_model_name(args.weights), - num_classes=1, - pretrained=not (args.weights and args.weights.is_file() and args.weights.suffix == '.pt'), - use_gpu=args.device - ).to(args.device) - load_pretrained_weights(model, args.weights) - model.eval() - - if args.optimize: - assert device.type == 'cpu', '--optimize not compatible with cuda devices, i.e. use --device cpu' - - im = torch.zeros(args.batch_size, 3, args.imgsz[0], args.imgsz[1]).to(args.device) # image size(1,3,640,480) BCHW iDetection - for _ in range(2): - y = model(im) # dry runs - if args.half: - im, model = im.half(), model.half() # to FP16 - shape = tuple((y[0] if isinstance(y, tuple) else y).shape) # model output shape - LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {args.weights} with output shape {shape} ({file_size(args.weights):.1f} MB)") - - # Exports - f = [''] * len(fmts) # exported filenames - if jit: - f[0] = export_torchscript(model, im, args.weights, args.optimize) # opset 12 - if engine: # TensorRT required before ONNX - f[1] = export_engine(model, im, args.weights, args.half, args.dynamic, args.simplify, args.workspace, args.verbose) - if onnx: # OpenVINO requires ONNX - f[2] = export_onnx(model, im, args.weights, args.opset, args.dynamic, args.simplify) # opset 12 - if openvino: - f[3] = export_openvino(args.weights, args.half) - if tflite: - export_tflite(f, False) - - # Finish - f = [str(x) for x in f if x] # filter out '' and None - if any(f): - LOGGER.info(f'\nExport complete ({time.time() - t:.1f}s)' - f"\nResults saved to {colorstr('bold', args.weights.parent.resolve())}" - f"\nVisualize: https://netron.app") - diff --git a/spaces/radames/Gradio-demo-video-image-webcam-upload/README.md b/spaces/radames/Gradio-demo-video-image-webcam-upload/README.md deleted file mode 100644 index 8965b158243ab53498db72633732e40edf584a45..0000000000000000000000000000000000000000 --- a/spaces/radames/Gradio-demo-video-image-webcam-upload/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Gradio Demo Video Image Webcam Upload -emoji: 🦀 -colorFrom: green -colorTo: blue -sdk: gradio -sdk_version: 3.44.4 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/radames/MusicGen-Continuation/audiocraft/data/audio.py b/spaces/radames/MusicGen-Continuation/audiocraft/data/audio.py deleted file mode 100644 index 2048df6f175d7303bcf5c7b931922fd297908ead..0000000000000000000000000000000000000000 --- a/spaces/radames/MusicGen-Continuation/audiocraft/data/audio.py +++ /dev/null @@ -1,215 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -""" -Audio IO methods are defined in this module (info, read, write), -We rely on av library for faster read when possible, otherwise on torchaudio. -""" - -from dataclasses import dataclass -from pathlib import Path -import logging -import typing as tp - -import numpy as np -import soundfile -import torch -from torch.nn import functional as F -import torchaudio as ta - -import av - -from .audio_utils import f32_pcm, i16_pcm, normalize_audio - - -_av_initialized = False - - -def _init_av(): - global _av_initialized - if _av_initialized: - return - logger = logging.getLogger('libav.mp3') - logger.setLevel(logging.ERROR) - _av_initialized = True - - -@dataclass(frozen=True) -class AudioFileInfo: - sample_rate: int - duration: float - channels: int - - -def _av_info(filepath: tp.Union[str, Path]) -> AudioFileInfo: - _init_av() - with av.open(str(filepath)) as af: - stream = af.streams.audio[0] - sample_rate = stream.codec_context.sample_rate - duration = float(stream.duration * stream.time_base) - channels = stream.channels - return AudioFileInfo(sample_rate, duration, channels) - - -def _soundfile_info(filepath: tp.Union[str, Path]) -> AudioFileInfo: - info = soundfile.info(filepath) - return AudioFileInfo(info.samplerate, info.duration, info.channels) - - -def audio_info(filepath: tp.Union[str, Path]) -> AudioFileInfo: - # torchaudio no longer returns useful duration informations for some formats like mp3s. - filepath = Path(filepath) - if filepath.suffix in ['.flac', '.ogg']: # TODO: Validate .ogg can be safely read with av_info - # ffmpeg has some weird issue with flac. - return _soundfile_info(filepath) - else: - return _av_info(filepath) - - -def _av_read(filepath: tp.Union[str, Path], seek_time: float = 0, duration: float = -1.) -> tp.Tuple[torch.Tensor, int]: - """FFMPEG-based audio file reading using PyAV bindings. - Soundfile cannot read mp3 and av_read is more efficient than torchaudio. - - Args: - filepath (str or Path): Path to audio file to read. - seek_time (float): Time at which to start reading in the file. - duration (float): Duration to read from the file. If set to -1, the whole file is read. - Returns: - Tuple[torch.Tensor, int]: Tuple containing audio data and sample rate - """ - _init_av() - with av.open(str(filepath)) as af: - stream = af.streams.audio[0] - sr = stream.codec_context.sample_rate - num_frames = int(sr * duration) if duration >= 0 else -1 - frame_offset = int(sr * seek_time) - # we need a small negative offset otherwise we get some edge artifact - # from the mp3 decoder. - af.seek(int(max(0, (seek_time - 0.1)) / stream.time_base), stream=stream) - frames = [] - length = 0 - for frame in af.decode(streams=stream.index): - current_offset = int(frame.rate * frame.pts * frame.time_base) - strip = max(0, frame_offset - current_offset) - buf = torch.from_numpy(frame.to_ndarray()) - if buf.shape[0] != stream.channels: - buf = buf.view(-1, stream.channels).t() - buf = buf[:, strip:] - frames.append(buf) - length += buf.shape[1] - if num_frames > 0 and length >= num_frames: - break - assert frames - # If the above assert fails, it is likely because we seeked past the end of file point, - # in which case ffmpeg returns a single frame with only zeros, and a weird timestamp. - # This will need proper debugging, in due time. - wav = torch.cat(frames, dim=1) - assert wav.shape[0] == stream.channels - if num_frames > 0: - wav = wav[:, :num_frames] - return f32_pcm(wav), sr - - -def audio_read(filepath: tp.Union[str, Path], seek_time: float = 0., - duration: float = -1., pad: bool = False) -> tp.Tuple[torch.Tensor, int]: - """Read audio by picking the most appropriate backend tool based on the audio format. - - Args: - filepath (str or Path): Path to audio file to read. - seek_time (float): Time at which to start reading in the file. - duration (float): Duration to read from the file. If set to -1, the whole file is read. - pad (bool): Pad output audio if not reaching expected duration. - Returns: - Tuple[torch.Tensor, int]: Tuple containing audio data and sample rate. - """ - fp = Path(filepath) - if fp.suffix in ['.flac', '.ogg']: # TODO: check if we can safely use av_read for .ogg - # There is some bug with ffmpeg and reading flac - info = _soundfile_info(filepath) - frames = -1 if duration <= 0 else int(duration * info.sample_rate) - frame_offset = int(seek_time * info.sample_rate) - wav, sr = soundfile.read(filepath, start=frame_offset, frames=frames, dtype=np.float32) - assert info.sample_rate == sr, f"Mismatch of sample rates {info.sample_rate} {sr}" - wav = torch.from_numpy(wav).t().contiguous() - if len(wav.shape) == 1: - wav = torch.unsqueeze(wav, 0) - elif ( - fp.suffix in ['.wav', '.mp3'] and fp.suffix[1:] in ta.utils.sox_utils.list_read_formats() - and duration <= 0 and seek_time == 0 - ): - # Torchaudio is faster if we load an entire file at once. - wav, sr = ta.load(fp) - else: - wav, sr = _av_read(filepath, seek_time, duration) - if pad and duration > 0: - expected_frames = int(duration * sr) - wav = F.pad(wav, (0, expected_frames - wav.shape[-1])) - return wav, sr - - -def audio_write(stem_name: tp.Union[str, Path], - wav: torch.Tensor, sample_rate: int, - format: str = 'wav', mp3_rate: int = 320, normalize: bool = True, - strategy: str = 'peak', peak_clip_headroom_db: float = 1, - rms_headroom_db: float = 18, loudness_headroom_db: float = 14, - loudness_compressor: bool = False, - log_clipping: bool = True, make_parent_dir: bool = True, - add_suffix: bool = True) -> Path: - """Convenience function for saving audio to disk. Returns the filename the audio was written to. - - Args: - stem_name (str or Path): Filename without extension which will be added automatically. - format (str): Either "wav" or "mp3". - mp3_rate (int): kbps when using mp3s. - normalize (bool): if `True` (default), normalizes according to the prescribed - strategy (see after). If `False`, the strategy is only used in case clipping - would happen. - strategy (str): Can be either 'clip', 'peak', or 'rms'. Default is 'peak', - i.e. audio is normalized by its largest value. RMS normalizes by root-mean-square - with extra headroom to avoid clipping. 'clip' just clips. - peak_clip_headroom_db (float): Headroom in dB when doing 'peak' or 'clip' strategy. - rms_headroom_db (float): Headroom in dB when doing 'rms' strategy. This must be much larger - than the `peak_clip` one to avoid further clipping. - loudness_headroom_db (float): Target loudness for loudness normalization. - loudness_compressor (bool): Uses tanh for soft clipping when strategy is 'loudness'. - when strategy is 'loudness'log_clipping (bool): If True, basic logging on stderr when clipping still - occurs despite strategy (only for 'rms'). - make_parent_dir (bool): Make parent directory if it doesn't exist. - Returns: - Path: Path of the saved audio. - """ - assert wav.dtype.is_floating_point, "wav is not floating point" - if wav.dim() == 1: - wav = wav[None] - elif wav.dim() > 2: - raise ValueError("Input wav should be at most 2 dimension.") - assert wav.isfinite().all() - wav = normalize_audio(wav, normalize, strategy, peak_clip_headroom_db, - rms_headroom_db, loudness_headroom_db, log_clipping=log_clipping, - sample_rate=sample_rate, stem_name=str(stem_name)) - kwargs: dict = {} - if format == 'mp3': - suffix = '.mp3' - kwargs.update({"compression": mp3_rate}) - elif format == 'wav': - wav = i16_pcm(wav) - suffix = '.wav' - kwargs.update({"encoding": "PCM_S", "bits_per_sample": 16}) - else: - raise RuntimeError(f"Invalid format {format}. Only wav or mp3 are supported.") - if not add_suffix: - suffix = '' - path = Path(str(stem_name) + suffix) - if make_parent_dir: - path.parent.mkdir(exist_ok=True, parents=True) - try: - ta.save(path, wav, sample_rate, **kwargs) - except Exception: - if path.exists(): - # we do not want to leave half written files around. - path.unlink() - raise - return path diff --git a/spaces/radames/stable-diffusion-depth2img/app.py b/spaces/radames/stable-diffusion-depth2img/app.py deleted file mode 100644 index 9e3283198d7c94d4a4e4e5a144188c8a1f00fc58..0000000000000000000000000000000000000000 --- a/spaces/radames/stable-diffusion-depth2img/app.py +++ /dev/null @@ -1,120 +0,0 @@ -import gradio as gr -import torch -from PIL import Image -import numpy as np -from diffusers import StableDiffusionDepth2ImgPipeline -from pathlib import Path - -device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') -dept2img = StableDiffusionDepth2ImgPipeline.from_pretrained( - "stabilityai/stable-diffusion-2-depth", - torch_dtype=torch.float16, -).to(device) - - -def pad_image(input_image): - pad_w, pad_h = np.max(((2, 2), np.ceil( - np.array(input_image.size) / 64).astype(int)), axis=0) * 64 - input_image.size - im_padded = Image.fromarray( - np.pad(np.array(input_image), ((0, pad_h), (0, pad_w), (0, 0)), mode='edge')) - w, h = im_padded.size - if w == h: - return im_padded - elif w > h: - new_image = Image.new(im_padded.mode, (w, w), (0, 0, 0)) - new_image.paste(im_padded, (0, (w - h) // 2)) - return new_image - else: - new_image = Image.new(im_padded.mode, (h, h), (0, 0, 0)) - new_image.paste(im_padded, ((h - w) // 2, 0)) - return new_image - - -def predict(input_image, prompt, negative_prompt, steps, num_samples, scale, seed, strength, depth_image=None): - depth = None - if depth_image is not None: - depth_image = pad_image(depth_image) - depth_image = depth_image.resize((512, 512)) - depth = np.array(depth_image.convert("L")) - depth = np.expand_dims(depth, 0) - depth = depth.astype(np.float32) / 255.0 - depth = torch.from_numpy(depth) - init_image = input_image.convert("RGB") - image = pad_image(init_image) # resize to integer multiple of 32 - image = image.resize((512, 512)) - generator = None - if seed is not None: - generator = torch.Generator(device=device).manual_seed(seed) - result = dept2img( - image=image, - prompt=prompt, - negative_prompt=negative_prompt, - generator=generator, - depth_map=depth, - strength=strength, - num_inference_steps=steps, - guidance_scale=scale, - num_images_per_prompt=num_samples, - ) - return result['images'] - - -block = gr.Blocks().queue() -with block: - with gr.Row(): - with gr.Column(): - gr.Markdown("## Stable Diffusion 2 Depth2Img") - gr.HTML("

            Duplicate Space

            ") - - - with gr.Row(): - with gr.Column(): - input_image = gr.Image(source='upload', type="pil") - depth_image = gr.Image( - source='upload', type="pil", label="Depth Image Optional", value=None) - prompt = gr.Textbox(label="Prompt") - negative_prompt = gr.Textbox(label="Negative Prompt") - - run_button = gr.Button(label="Run") - with gr.Accordion("Advanced Options", open=False): - num_samples = gr.Slider( - label="Images", minimum=1, maximum=4, value=1, step=1) - steps = gr.Slider(label="Steps", minimum=1, - maximum=50, value=50, step=1) - scale = gr.Slider( - label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1 - ) - strength = gr.Slider( - label="Strength", minimum=0.0, maximum=1.0, value=0.9, step=0.01 - ) - seed = gr.Slider( - label="Seed", - minimum=0, - maximum=2147483647, - step=1, - randomize=True, - ) - with gr.Column(): - gallery = gr.Gallery(label="Generated Images", show_label=False).style( - grid=[2], height="auto") - gr.Examples( - examples=[ - ["./examples/baby.jpg", "high definition photo of a baby astronaut space walking at the international space station with earth seeing from above in the background", - "", 50, 4, 9.0, 123123123, 0.8, None], - ["./examples/gol.jpg", "professional photo of a Elmo jumping between two high rises, beautiful colorful city landscape in the background", - "", 50, 4, 9.0, 1734133747, 0.9, None], - ["./examples/bag.jpg", "a photo of a bag of cookies in the bathroom", "low light, dark, blurry", 50, 4, 9.0, 1734133747, 0.9, "./examples/depth.jpg"], - ["./examples/smile_face.jpg", "a hand holding a very spherical orange", "low light, dark, blurry", 50, 4, 6.0, 961736534, 0.5, "./examples/smile_depth.jpg"] - - ], - inputs=[input_image, prompt, negative_prompt, steps, - num_samples, scale, seed, strength, depth_image], - outputs=[gallery], - fn=predict, - cache_examples=True, - ) - run_button.click(fn=predict, inputs=[input_image, prompt, negative_prompt, - steps, num_samples, scale, seed, strength, depth_image], outputs=[gallery]) - - -block.launch(show_api=False) \ No newline at end of file diff --git a/spaces/raedeXanto/academic-chatgpt-beta/Boom 3D 1.2.2 Full Version For Mac Crack With Registration Key How to Get It for Free.md b/spaces/raedeXanto/academic-chatgpt-beta/Boom 3D 1.2.2 Full Version For Mac Crack With Registration Key How to Get It for Free.md deleted file mode 100644 index 0a3c5ffa8fdf2306d65e5c2f55a2a79ba5f50f92..0000000000000000000000000000000000000000 --- a/spaces/raedeXanto/academic-chatgpt-beta/Boom 3D 1.2.2 Full Version For Mac Crack With Registration Key How to Get It for Free.md +++ /dev/null @@ -1,92 +0,0 @@ - -

            Boom 3D 1.2.2 Full Version For Mac Crack With Registration Key

            -

            If you are looking for a way to enhance your audio experience on your Mac, you might want to check out Boom 3D. Boom 3D is an all-new pro audio app that delivers rich and intense audio with 3D surround sound that makes any kind of headphone sound better. In this article, we will tell you what Boom 3D is, what features it has, how to download and install it, and how to crack and register it.

            -

            Boom 3D 1.2.2 Full Version For Mac Crack With Registration Key


            Downloadhttps://tinourl.com/2uKZ8K



            -

            What is Boom 3D?

            -

            Boom 3D is a powerful audio enhancement app that transforms your Mac's sound quality with its advanced features and stunning interface. It lets you customize your audio with handcrafted equalizer presets, audio effects, and an intensity slider that gives you full control over the sound output. You can also enjoy your favorite music and movies with its advanced audio player that supports various formats and codecs. Plus, you can access over 20,000 radio stations from around the world with its built-in radio feature. And if you have multiple devices connected to your Mac, you can easily manage them with its device manager.

            -

            Features of Boom 3D

            -

            Boom 3D has many features that make it stand out from other audio apps. Here are some of them:

            -

            Incredible 3D Surround Sound

            -

            Boom 3D uses a patented technology that creates a realistic and immersive sound field that surrounds you with sound from all directions. You can experience the true depth and clarity of your audio with any headphones, speakers, or earbuds. You can also choose from various sound modes such as cinema, music, gaming, vocals, and more.

            -

            Boom 3D Mac Crack Download Free Full Version
            -How to Get Boom 3D Registration Key for Mac
            -Boom 3D 1.2.2 Crack + License Key for Mac OS
            -Boom 3D Full Version Free Download with Crack for Mac
            -Boom 3D Crack Mac - Best 3D Audio Enhancer Software
            -Download Boom 3D 1.2.2 Full Version for Mac with Serial Key
            -Boom 3D Mac Crack - How to Install and Activate
            -Boom 3D Full Version for Mac - Features and Benefits
            -Boom 3D Registration Key Generator for Mac
            -Boom 3D Crack for Mac - Review and Comparison
            -Boom 3D 1.2.2 Full Version for Mac - System Requirements and Compatibility
            -Boom 3D Full Version for Mac Crack - Download Link and Instructions
            -How to Use Boom 3D Crack for Mac to Boost Your Audio Quality
            -Boom 3D Crack for Mac - Pros and Cons
            -Boom 3D Registration Key for Mac - How to Get it for Free
            -Boom 3D Full Version for Mac - Troubleshooting and Support
            -Boom 3D Crack for Mac - Tips and Tricks
            -Boom 3D Full Version for Mac - User Guide and Tutorial
            -Boom 3D Registration Key for Mac - Valid and Working
            -Boom 3D Crack for Mac - Frequently Asked Questions and Answers
            -Boom 3D Full Version for Mac - Latest Updates and News
            -Boom 3D Crack for Mac - Testimonials and Feedback
            -Boom 3D Registration Key for Mac - How to Renew and Extend
            -Boom 3D Full Version for Mac - Alternatives and Competitors
            -Boom 3D Crack for Mac - Discounts and Offers
            -Boom 3D Full Version for Mac - How to Uninstall and Remove
            -Boom 3D Registration Key for Mac - How to Transfer and Backup
            -Boom 3D Crack for Mac - How to Customize and Configure
            -Boom 3D Full Version for Mac - How to Optimize and Improve Performance
            -Boom 3D Registration Key for Mac - How to Recover and Restore
            -Boom 3D Crack for Mac - How to Fix Errors and Bugs
            -Boom 3D Full Version for Mac - How to Upgrade and Update
            -Boom 3D Registration Key for Mac - How to Share and Refer
            -Boom 3D Crack for Mac - How to Contact Customer Service and Support
            -Boom 3D Full Version for Mac - How to Access Premium Features and Benefits
            -Boom 3D Registration Key for Mac - How to Verify and Validate
            -Boom 3D Crack for Mac - How to Avoid Scams and Viruses
            -Boom 3D Full Version for Mac - How to Enjoy and Have Fun with It
            -Boom 3D Registration Key for Mac - How to Gift and Donate It
            -Boom 3D Crack for Mac - How to Learn More and Explore More Options

            -

            Advanced Equalizer Presets

            -

            Boom 3D comes with over 20 handcrafted equalizer presets that are designed to suit different genres and moods of music. You can also create your own custom presets or fine-tune the existing ones with the 31-band equalizer.

            -

            Audio Effects

            -

            Boom 3D lets you add some spice to your audio with its amazing audio effects such as bass boost, treble boost, spatial, fidelity, night mode, and more. You can also adjust the intensity of each effect with the slider.

            -

            Advanced Audio Player

            -

            Boom 3D has a built-in audio player that supports various formats such as MP3, WAV, FLAC, ALAC, OGG, M4A, and more. It also supports popular codecs such as Dolby Digital Plus (E-AC-3), Dolby Digital (AC-3), DTS, and DTS-HD. You can play your local files or stream online content from YouTube, Spotify, Apple Music, Netflix, and more.

            -

            Radio Stations

            -

            Boom 3D gives you access to over 20,000 radio stations from around the world. You can browse by genre, country, language, or popularity. You can also save your favorite stations for easy access.

            -

            Manage Devices

            -

            Boom 3D lets you easily manage multiple devices connected to your Mac such as headphones, speakers, earbuds, AirPods, Bluetooth devices, and more. You can switch between them with a click or assign different presets and effects to each device.

            -

            How to download and install Boom 3D?

            -

            If you want to try out Boom 3D on your Mac, you can follow these steps:

            -

            Download link

            -

            You can download Boom 3D from its official website or from any trusted third-party source such as CracksHash, Haxmac, Patronway, SoundCloud, or SoundCloud. Make sure you download the latest version (1.2.2) for Mac OS X.

            -

            Installation steps

            -
              -
            1. Open the downloaded file (Boom_1_2_2.dmg) and drag the Boom app icon to the Applications folder.
            2. -
            3. Double-click the Boom app icon in the Applications folder to launch it.
            4. -
            5. Wait for it to get installed fully.
            6. -
            7. Boom! Now you can use the program without any interruptions.
            8. -
            -

            (It's pre-cracked so you don't need to do anything else.)

            -

            How to crack and register Boom 3D?

            -

            If you want to unlock all the features of Boom 3D and use it without any limitations or ads, you need to crack and register it. Here's how:

            -

            Crack file

            -

            You can download the crack file for Boom 3D from any reliable source such as CracksHash, Haxmac, Patronway, SoundCloud, or SoundCloud. Make sure you download the crack file that matches the version of Boom 3D (1.2.2) for Mac OS X.

            -

            Registration key

            -

            You can also get a registration key for Boom 3D from any valid source such as CracksHash, Haxmac, Patronway, SoundCloud, or SoundCloud. Make sure you get a registration key that works for the version of Boom 3D (1.2.2) for Mac OS X.

            -
              -
            1. Open the crack file (Boom_1_2_2_Crack.zip) and extract its contents.
            2. -
            3. Copy the cracked file (Boom.app) and replace it with the original file in the Applications folder.
            4. -
            5. Launch Boom app from the Applications folder.
            6. -
            7. Go to Menu > Register > Enter License Key.
            8. -
            9. Paste the registration key that you got from any source.
            10. -
            11. Click on Activate.
            12. -
            13. Congratulations! You have successfully cracked and registered Boom 3D.
            14. -
            -

            Conclusion

            -

            In conclusion, Boom 3D is an awesome audio enhancement app that lets you enjoy rich and intense audio with 3D surround sound on your Mac. It has many features such as advanced equalizer presets, audio effects, audio player, radio stations, and device manager that make it a must-have app for any audiophile. You can download and install it easily from its official website or any trusted third-party source. You can also crack and register it with a crack file and a registration key from any valid source. We hope this article helped you learn more about Boom 3D and how to use it on your Mac.

            - **FAQs** Q: Is Boom 3D safe to use? A: Yes, Boom 3D is safe to use as long as you download it from its official website or any trusted third-party source. It does not contain any malware or viruses that can harm your Mac. Q: Does Boom 3D work with AirPlay and FaceTime? A: No, Boom 3D may not work when AirPlay and FaceTime are enabled or running on your Mac. Q: How much does Boom 3D cost? A: Boom 3D costs $19.99 for a single license that works on one Mac device. Q: What are the system requirements for Boom 3D? A: The system requirements for Boom 3D are: - OS X Yosemite (10.10) or later - At least Core i5 processor - At least 256 MB RAM - At least 100 MB free disk space Q: How can I contact the support team of Boom 3D? A: You can contact the support team of Boom 3D by sending an email to support@globaldelight.com or by filling out a form on their website.

            0a6ba089eb
            -
            -
            \ No newline at end of file diff --git a/spaces/raedeXanto/academic-chatgpt-beta/Download Game Iron Man 2 Pc Highly Compressed The Complete Guide to the Characters Missions and Weapons.md b/spaces/raedeXanto/academic-chatgpt-beta/Download Game Iron Man 2 Pc Highly Compressed The Complete Guide to the Characters Missions and Weapons.md deleted file mode 100644 index c7a58d92e652592a8307ccb63fef4736bc66ee11..0000000000000000000000000000000000000000 --- a/spaces/raedeXanto/academic-chatgpt-beta/Download Game Iron Man 2 Pc Highly Compressed The Complete Guide to the Characters Missions and Weapons.md +++ /dev/null @@ -1,173 +0,0 @@ - -

            Download Game Iron Man 2 Pc Highly Compressed

            -

            Are you a fan of Iron Man, the Marvel superhero who wears a high-tech suit of armor and fights evil with his amazing gadgets and weapons? If so, you might want to download Iron Man 2 game for PC highly compressed and enjoy an action-packed adventure based on the movie of the same name. In this article, we will tell you what Iron Man 2 game is, why you should download it for PC, how to download it highly compressed, and how to play it. Let's get started!

            -

            Introduction

            -

            What is Iron Man 2 game?

            -

            Iron Man 2 is an action-adventure video game loosely based on the film of the same name. It was released in 2010 for various platforms, including PlayStation 3, Xbox 360, Nintendo DS, Wii, PlayStation Portable, iOS, and BlackBerry PlayBook. However, a Microsoft Windows version was planned but cancelled.

            -

            Download Game Iron Man 2 Pc Highly Compressed


            DOWNLOADhttps://tinourl.com/2uL0Q6



            -

            The game has an original story written by The Invincible Iron Man author, Matt Fraction. This story is set after the plot of the film, although the iOS and BlackBerry versions stick roughly to the film's plot. The game features the voices of Don Cheadle and Samuel L. Jackson, reprising their roles from the film as War Machine and Nick Fury respectively.

            -

            Why download Iron Man 2 game for PC?

            -

            There are many reasons why you might want to download Iron Man 2 game for PC highly compressed. Here are some of them:

            -

            How to download Iron Man 2 game for pc in low size
            -Iron Man 2 pc game highly compressed free download
            -Download Iron Man 2 full version pc game in 500mb
            -Iron Man 2 game download for pc highly compressed rar
            -Best site to download Iron Man 2 pc game in high quality
            -Iron Man 2 pc game download highly compressed kgb
            -Download Iron Man 2 game for pc highly compressed in parts
            -Iron Man 2 pc game highly compressed 100 working download
            -Iron Man 2 game download for pc highly compressed zip
            -Download Iron Man 2 pc game highly compressed torrent
            -Iron Man 2 pc game highly compressed direct download link
            -Download Iron Man 2 game for pc highly compressed google drive
            -Iron Man 2 pc game highly compressed no survey download
            -Download Iron Man 2 full game for pc highly compressed iso
            -Iron Man 2 game download for pc highly compressed setup
            -Download Iron Man 2 pc game highly compressed online
            -Iron Man 2 pc game highly compressed crack download
            -Download Iron Man 2 game for pc highly compressed apk
            -Iron Man 2 game download for pc highly compressed obb
            -Download Iron Man 2 pc game highly compressed mod
            -Iron Man 2 pc game highly compressed patch download
            -Download Iron Man 2 game for pc highly compressed repack
            -Iron Man 2 game download for pc highly compressed skidrow
            -Download Iron Man 2 pc game highly compressed fitgirl
            -Iron Man 2 pc game highly compressed update download
            -Download Iron Man 2 game for pc highly compressed codex
            -Iron Man 2 game download for pc highly compressed cpy
            -Download Iron Man 2 pc game highly compressed reloaded
            -Iron Man 2 pc game highly compressed trainer download
            -Download Iron Man 2 game for pc highly compressed cheats
            -Iron Man 2 game download for pc highly compressed save file
            -Download Iron Man 2 pc game highly compressed windows 10
            -Iron Man 2 pc game highly compressed windows 7 download
            -Download Iron Man 2 game for pc highly compressed windows xp
            -Iron Man 2 game download for pc highly compressed mac
            -Download Iron Man 2 pc game highly compressed linux
            -Iron Man 2 pc game highly compressed android download
            -Download Iron Man 2 game for pc highly compressed ios
            -Iron Man 2 game download for pc highly compressed ps4
            -Download Iron Man 2 pc game highly compressed xbox one
            -Iron Man 2 pc game highly compressed ps3 download
            -Download Iron Man 2 game for pc highly compressed xbox 360
            -Iron Man 2 game download for pc highly compressed psp
            -Download Iron Man 2 pc game highly compressed ppsspp
            -Iron Man 2 pc game highly compressed wii download
            -Download Iron Man 2 game for pc highly compressed wii u
            -Iron Man 2 game download for pc highly compressed switch
            -Download Iron Man 2 pc game highly compressed nintendo ds
            -Iron Man 2 pc game highly compressed nintendo 3ds download

            -
              -
            • You can play as either Iron Man or War Machine, each with their own unique style and weapons. You can also customize your suit of armor with various upgrades and gadgets.
            • -
            • You can experience a thrilling and cinematic gameplay that combines flying, shooting, melee combat, and stealth. You can also use your environment to your advantage by destroying objects and enemies.
            • -
            • You can explore different locations from the movie and beyond, such as Stark Expo, Monaco, Siberia, Afghanistan, and more. You can also encounter various enemies from the Marvel universe, such as Ultimo, Firepower, Ghost, Whiplash, and more.
            • -
            • You can enjoy a high-quality graphics and sound that immerse you in the world of Iron Man. You can also listen to the original soundtrack composed by David Earl and Paul Lipson, as well as a song by Lamb of God called "Hit the Wall".
            • -
            -

            How to download Iron Man 2 game for PC highly compressed?

            -

            Requirements for Iron Man 2 game for PC

            -

            Minimum requirements

            -

            Before you download Iron Man 2 game for PC highly compressed, you need to make sure that your PC meets the minimum requirements for running the game. Here are the minimum requirements:

            -
              -
            • Operating system: Windows XP/Vista/7/8/10
            • -
            • Processor: Intel Core 2 Duo 1.8 GHz or AMD Athlon X2 64 2.4 GHz
            • -
            • Memory: 1 GB RAM
            • -
            • Graphics: NVIDIA GeForce 7600 GS or ATI Radeon X1650 Pro with 256 MB VRAM
            • -
            • DirectX: Version 9.0c
            • -
            • Storage: 6 GB available space
            • -
            • Sound card: DirectX compatible
            • -
            -

            Recommended requirements

            -

            If you want to enjoy a better performance and quality of Iron Man 2 game for PC highly compressed, you should have a PC that meets or exceeds the recommended requirements for running the game. Here are the recommended requirements:

            -
              -
            • Operating system: Windows XP/Vista/7/8/10
            • -
            • Processor: Intel Core 2 Quad Q6600 or AMD Phenom X4 9850
            • -
            • Memory: 2 GB RAM
            • -
            • Graphics: NVIDIA GeForce GTS 250 or ATI Radeon HD 4850 with 512 MB VRAM
            • -
            • DirectX: Version 9.0c
            • -
            • Storage: 6 GB available space
            • -
            • Sound card: DirectX compatible
            • -
            -

            Steps to download Iron Man 2 game for PC highly compressed

            -

            To download Iron Man 2 game for PC highly compressed, you need to follow these steps:

            -

            Step 1: Download a torrent client

            -

            A torrent client is a software that allows you to download files from other users who share them on a peer-to-peer network called torrent. You need a torrent client to download Iron Man 2 game for PC highly compressed because it is not available on any official website or platform.

            -

            There are many torrent clients that you can choose from, such as uTorrent , BitTorrent , qBittorrent , Vuze , Deluge , etc. You can download any of them from their official websites or from other trusted sources.

            -

            After downloading a torrent client, you need to install it on your PC by following the instructions on the screen.

            -

            Step 2: Find a reliable torrent site

            -

            A torrent site is a website that hosts torrent files that contain information about the files that you want to download from other users on the torrent network. You need a reliable torrent site to find and download Iron Man 2 game for PC highly compressed because it is not easy to find it on any random site.

            -

            There are many torrent sites that you can choose from, such as The Pirate Bay , RARBG , Torrentz , Kickass Torrents , etc. However, some of them may be blocked or banned in your country or region due to legal issues or copyright infringement.

            -

            To access these sites safely and anonymously, you may need to use a VPN service that masks your IP address and encrypts your online traffic.

            -

            You can also use alternative domains or proxies that bypass these blocks or bans.

            -

            After finding a reliable torrent site that works in your location, you need to open it on your web browser.

            -

            Step 3: Search for Iron Man 2 game for PC highly compressed

            -

            To search for Iron Man 2 game for PC highly compressed on the torrent site that you have chosen, you need to type in the name of the game in the search bar and hit enter.

            -

            You will see a list of results that match your query. You need to look for the one that has the most seeders and leechers.

            -

            A seeder is a user who has downloaded the file completely and is sharing it with others on the torrent network.

            -

            A leecher is a user who is downloading the file partially or completely from other users on the torrent network.

            -

            The more seeders and leechers a file has, the faster and easier it will be to download it.

            -

            You also need to check the size and quality of the file before downloading it.

            -

            The size of Iron Man 2 game for PC highly compressed should be around 1 GB, which is much smaller than its original size of 6 GB.

            -

            Man 2 game for PC highly compressed should be similar to its original quality, but with some minor loss of details and textures.

            -

            After finding the file that meets your criteria, you need to click on it and download the torrent file or magnet link.

            -

            A torrent file is a small file that contains information about the file that you want to download and the users who are sharing it on the torrent network.

            -

            A magnet link is a URL that contains the same information as a torrent file, but without requiring a separate file.

            -

            After downloading the torrent file or magnet link, you need to open it with your torrent client.

            -

            Step 4: Download and install the game

            -

            To download Iron Man 2 game for PC highly compressed with your torrent client, you need to follow these steps:

            -
              -
            • Add the torrent file or magnet link to your torrent client by clicking on it or dragging and dropping it.
            • -
            • Choose a location on your PC where you want to save the downloaded file.
            • -
            • Wait for the download to complete. The speed and time of the download will depend on your internet connection and the number of seeders and leechers available.
            • -
            • After the download is complete, you will see a folder that contains the game files. You need to extract them with a software like WinRAR or 7-Zip .
            • -
            • After extracting the game files, you will see an ISO file that contains the game image. You need to mount it with a software like Daemon Tools or PowerISO .
            • -
            • After mounting the game image, you will see a virtual drive that contains the game setup. You need to run it as administrator and follow the instructions on the screen.
            • -
            • After installing the game, you may need to copy and paste a crack file from the folder where you downloaded the game to the folder where you installed the game. This will bypass any protection or activation that may prevent you from playing the game.
            • -
            • After copying and pasting the crack file, you can launch the game from your desktop or start menu and enjoy playing Iron Man 2 game for PC highly compressed.
            • -
            -

            How to play Iron Man 2 game for PC?

            -

            Game modes and features

            -

            Iron Man 2 game for PC has two main game modes: Campaign and Challenge.

            -

            Campaign mode is where you follow the story of Iron Man 2 and complete various missions as either Iron Man or War Machine. You can switch between them at any time during gameplay. You can also choose from different suits of armor, each with their own abilities and weapons. You can upgrade your suit of armor with new parts and gadgets as you progress through the game. You can also unlock new suits of armor by completing certain tasks or finding hidden items.

            -

            Challenge mode is where you test your skills and compete against other players online or offline. You can choose from different challenges, such as survival, time attack, enemy wave, etc. You can also customize your suit of armor and weapons before each challenge. You can earn medals and trophies by achieving certain goals or beating certain scores.

            -

            Iron Man 2 game for PC also has some features that enhance your gameplay experience, such as:

            -
              -
            • A dynamic combat system that allows you to use your environment to your advantage by destroying objects and enemies.
            • -
            • A flight control system that allows you to fly freely across the levels and engage in aerial combat.
            • -
            • A melee combat system that allows you to get close and personal with your enemies and perform devastating attacks.
            • -
            • A stealth system that allows you to sneak past or surprise your enemies with stealth kills.
            • -
            • A dialogue system that allows you to interact with other characters and make choices that affect the outcome of the story.
            • -
            -

            Tips and tricks for Iron Man 2 game for PC

            -

            To play Iron Man 2 game for PC effectively and efficiently, you need to follow these tips and tricks:

            -
              -
            • Use your radar to locate enemies, objectives, items, and points of interest.
            • -
            • Use your repulsor blast to stun enemies and break their shields.
            • -
            • Use your unibeam to deal massive damage to enemies and bosses.
            • -
            • Use your missiles to take out multiple enemies at once or destroy vehicles and turrets.
            • -
            • Use your melee attacks to finish off enemies quickly or break their armor.
            • -
            • Use your flight mode to dodge enemy attacks and reach high places.
            • -
            • Use your hover mode to aim accurately and fire precisely.
            • -
            • Use your stealth mode to avoid detection and perform stealth kills.
            • -
            • Use your environment to create cover, distractions, or traps for your enemies.
            • -
            • Use your suit upgrades to enhance your performance and abilities.
            • -
            • Use different suits of armor for different situations and preferences.
            • -
            • Switch between Iron Man and War Machine depending on your play style and strategy.
            • -
            -

            Conclusion

            -

            In conclusion, Iron Man 2 game for PC is a fun and exciting game that lets you become one of the most iconic superheroes in the Marvel universe. You can download Iron Man 2 game for PC highly compressed by following our guide above. You can also play Iron Man 2 game for PC by following our tips and tricks above. We hope you enjoy playing Iron Man 2 game for PC highly compressed!

            -

            Frequently Asked Questions

            -
              -
            1. Is Iron Man 2 game for PC free?
            2. -

              No, Iron Man 2 game for PC is not free. You need to buy it from an official retailer or platform. However, you can download Iron Man 2 game for PC highly compressed from a torrent site for free, but this may be illegal or risky in some countries or regions.

              -
            3. Is Iron Man 2 game for PC safe?
            4. -

              Iron Man 2 game for PC is safe if you download it from a trusted source or platform. However, if you download Iron Man 2 game for PC highly compressed from a torrent site, you may encounter some viruses or malware that may harm your PC or data. Therefore, you should always scan any file that you download from a torrent site with an antivirus software before opening it.

              -
            5. Is Iron Man 2 game for PC compatible with Windows 10?
            6. -

              Yes, Iron Man 2 game for PC is compatible with Windows 10. However, you may need to run it in compatibility mode or as administrator if you encounter any issues or errors while playing it on Windows 10.

              -
            7. How long is Iron Man 2 game for PC?
            8. -

              The length of Iron Man 2 game for PC depends on how fast you play it and how much you explore it. However, on average, it may take you around 6 hours to complete the campaign mode of Iron Man 2 game for PC. The challenge mode of Iron Man 2 game for PC may take you longer depending on how many challenges you try and how good you are at them.

              -
            9. Can I play Iron Man 2 game for PC with a controller?
            10. -

              Yes, you can play Iron Man 2 game for PC with a controller. You can use any controller that is compatible with Windows such as Xbox One controller , PlayStation DualShock controller , Logitech controller , etc. You can also customize your controller settings in the options menu of Iron Man 2 game for PC.

              -
            -

            0a6ba089eb
            -
            -
            \ No newline at end of file diff --git a/spaces/rahul999r/Rahul_Kannada_TTS/utils/data/duration.py b/spaces/rahul999r/Rahul_Kannada_TTS/utils/data/duration.py deleted file mode 100644 index c3b5e112b72dd5a07ea2463f604d98bb8d961496..0000000000000000000000000000000000000000 --- a/spaces/rahul999r/Rahul_Kannada_TTS/utils/data/duration.py +++ /dev/null @@ -1,33 +0,0 @@ -# Usage -> python duration.py /src/folder/path - -import soundfile as sf -import sys -import os -from glob import glob -from joblib import Parallel, delayed -from tqdm import tqdm - - -def get_duration(fpath): - w = sf.SoundFile(fpath) - sr = w.samplerate - assert 22050 == sr, "Sample rate is not 22050" - return len(w) / sr - - -def main(folder, ext="wav"): - file_list = glob(folder + "/**/*." + ext, recursive=True) - print(f"\n\tTotal number of wav files {len(file_list)}") - duration_list = Parallel(n_jobs=1)( - delayed(get_duration)(i) for i in tqdm(file_list) - ) - print( - f"\n\tMin Duration {min(duration_list):.2f} Max Duration {max(duration_list):.2f} in secs" - ) - print(f"\n\tTotal Duration {sum(duration_list)/3600:.2f} in hours") - - -if __name__ == "__main__": - folder = sys.argv[1] - folder = os.path.abspath(folder) - main(folder) diff --git a/spaces/ramiin2/AutoGPT/autogpt/processing/__init__.py b/spaces/ramiin2/AutoGPT/autogpt/processing/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/AutodeskAutoCAD201564bitPreReleaseInclKeygenXFORCEMUMBAITPB.md b/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/AutodeskAutoCAD201564bitPreReleaseInclKeygenXFORCEMUMBAITPB.md deleted file mode 100644 index 862a345adabe68843f5629811ed9706d93bbe10f..0000000000000000000000000000000000000000 --- a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/AutodeskAutoCAD201564bitPreReleaseInclKeygenXFORCEMUMBAITPB.md +++ /dev/null @@ -1,5 +0,0 @@ -
            -

            Download AutodeskAutoCAD201564bitPreReleaseInclKeygenXFORCEMUMBAITPB the https://trf ez do dancercize.torrent -3dvdiso trello ; trello ; trello Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download Download -3dvdiso trello https://trf ez do dancercize.torrent -3dvdiso trello https://trf ez do dancercize.torrent -3dvdiso trello https://trf ez do dancercize.torrent -3dvdiso trello https://trf ez do dancercize.torrent -3dvdiso trello https://trf ez do dancercize.torrent -3dvdiso trello https://trf ez do dancercize.torrent -3dvdiso trello https://trf ez do dancercize.

            -

            AutodeskAutoCAD201564bitPreReleaseInclKeygenXFORCEMUMBAITPB


            DOWNLOADhttps://urlgoal.com/2uCK6i



            899543212b
            -
            -
            \ No newline at end of file diff --git a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Daossoft Excel Password Remover Serial 11 __TOP__.md b/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Daossoft Excel Password Remover Serial 11 __TOP__.md deleted file mode 100644 index a2dc36216c5ed1457a930bcf54e1e80e97a0a755..0000000000000000000000000000000000000000 --- a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Daossoft Excel Password Remover Serial 11 __TOP__.md +++ /dev/null @@ -1,74 +0,0 @@ - -

            Daossoft Excel Password Remover Serial 11: A Review

            -

            If you have ever forgotten or lost the password to your Excel file, you know how frustrating it can be. You cannot access your data, edit your workbook, or even print your spreadsheet. You may have tried various methods to recover or remove the password, but none of them worked. You may have given up hope and decided to create a new file from scratch.

            -

            Daossoft Excel Password Remover Serial 11


            Download ✑ ✑ ✑ https://urlgoal.com/2uCKmD



            -

            But what if I told you that there is a way to remove the password from your Excel file in seconds? A way that is easy, fast, and reliable? A way that works for any version of Excel from 97 to 2016? A way that is called Daossoft Excel Password Remover Serial 11?

            -

            What is Daossoft Excel Password Remover Serial 11?

            -

            Daossoft Excel Password Remover Serial 11 is a powerful password remover software that can help you quickly remove the password from your Excel file. It can remove any type of password, whether it is an open password, a workbook password, a sheet password, or an edit password. It can also remove passwords of any length and complexity, including multilingual passwords.

            -

            Daossoft Excel Password Remover Serial 11 is compatible with all versions of Excel from 97 to 2016. It supports both xls and xlsx file formats. It has a user-friendly interface that can be operated with no technique required. It has a high recovery speed and a 100% recovery rate. It also offers online password recovery service with guaranteed privacy.

            -

            How does Daossoft Excel Password Remover Serial 11 work?

            -

            Daossoft Excel Password Remover Serial 11 works by using advanced algorithms to scan your Excel file and remove the password instantly. You do not need to know anything about the password or the encryption method. You just need to follow these simple steps:

            -
              -
            1. Download and install Daossoft Excel Password Remover Serial 11 on your computer.
            2. -
            3. Launch the software and click on the "Open" button to select your Excel file.
            4. -
            5. Click on the "Remove Password" button to start the process.
            6. -
            7. Wait for a few seconds and you will see a message saying "Password has been removed successfully".
            8. -
            9. Click on the "Open File" button to open your Excel file without any password.
            10. -
            -

            That's it! You have successfully removed the password from your Excel file with Daossoft Excel Password Remover Serial 11. You can now access, edit, print, or share your file as you wish.

            -

            -

            Why choose Daossoft Excel Password Remover Serial 11?

            -

            There are many reasons why you should choose Daossoft Excel Password Remover Serial 11 over other password remover tools. Here are some of them:

            -
              -
            • It is fast and efficient. It can remove the password from your Excel file in seconds, regardless of the password length or complexity.
            • -
            • It is easy and convenient. It has a simple and intuitive interface that anyone can use without any difficulty.
            • -
            • It is safe and reliable. It does not damage or corrupt your Excel file in any way. It also protects your privacy by offering online password recovery service.
            • -
            • It is affordable and cost-effective. It has a reasonable price that is worth every penny. It also offers free update and technical support for lifetime.
            • -
            -

            Conclusion

            -

            If you are looking for a way to remove the password from your Excel file quickly and easily, you should try Daossoft Excel Password Remover Serial 11. It is a powerful and professional tool that can help you solve your problem in seconds. It is compatible with all versions of Excel and supports both xls and xlsx file formats. It has a user-friendly interface and a high recovery speed. It also offers online password recovery service with guaranteed privacy.

            -

            Daossoft Excel Password Remover Serial 11 is the best solution for your Excel password problem. You can download it from the official website and enjoy its benefits right away. You will never have to worry about forgetting or losing your Excel password again.

            -

            How to get Daossoft Excel Password Remover Serial 11?

            -

            If you are interested in trying Daossoft Excel Password Remover Serial 11, you can download it from the official website of Daossoft. You can choose between a trial version and a full version. The trial version allows you to decrypt the first 10 rows of your Excel file, while the full version can remove the password from any Excel file. The full version costs $17.95, which is a reasonable price for such a powerful tool.

            -

            To get Daossoft Excel Password Remover Serial 11, you need to follow these steps:

            -
              -
            1. Visit the official website of Daossoft and click on the "Download" button to download the software.
            2. -
            3. Install the software on your computer and launch it.
            4. -
            5. Click on the "Buy Now" button to purchase the full version and get the serial number.
            6. -
            7. Enter the serial number in the software and activate it.
            8. -
            9. Enjoy using Daossoft Excel Password Remover Serial 11 to remove any password from your Excel file.
            10. -
            -

            You can also contact Daossoft customer service if you have any questions or problems with the software. They offer professional, timely and free technical support for their customers. You can also get free updates for lifetime.

            -

            What are the benefits of Daossoft Excel Password Remover Serial 11?

            -

            Daossoft Excel Password Remover Serial 11 is a great tool for anyone who needs to remove the password from their Excel file. It has many benefits that make it stand out from other password remover tools. Here are some of them:

            -
              -
            • It saves your time and energy. You do not need to spend hours or days trying to guess or crack the password. You can remove it in seconds with Daossoft Excel Password Remover Serial 11.
            • -
            • It protects your data and privacy. You do not need to upload your Excel file to any online service or share it with anyone else. You can remove the password on your own computer with Daossoft Excel Password Remover Serial 11.
            • -
            • It works for any Excel file and any password. You do not need to worry about the file format, the password type, or the password complexity. Daossoft Excel Password Remover Serial 11 can handle them all.
            • -
            • It is easy and convenient to use. You do not need to have any technical skills or knowledge to use Daossoft Excel Password Remover Serial 11. You just need to follow a few simple steps and click a few buttons.
            • -
            -

            Conclusion

            -

            Daossoft Excel Password Remover Serial 11 is a must-have tool for anyone who needs to remove the password from their Excel file. It is fast, easy, safe, and reliable. It can remove any password from any Excel file in seconds. It is compatible with all versions of Excel and supports both xls and xlsx file formats. It has a user-friendly interface and a high recovery speed. It also offers online password recovery service with guaranteed privacy.

            -

            If you want to try Daossoft Excel Password Remover Serial 11, you can download it from the official website of Daossoft and enjoy its benefits right away. You will never have to worry about forgetting or losing your Excel password again.

            -

            What are the alternatives to Daossoft Excel Password Remover Serial 11?

            -

            Daossoft Excel Password Remover Serial 11 is not the only tool that can help you remove the password from your Excel file. There are some other alternatives that you can try if you want to compare different features, prices, or performance. Here are some of them:

            -
              -
            • PassFab for Excel: This is another popular and professional Excel password remover tool that can help you recover or remove any type of password from your Excel file. It supports all versions of Excel from 97 to 2019 and has a high recovery speed and rate. It also offers four powerful attack modes to suit different situations. It costs $19.95 for a single license.
            • -
            • Passware Kit Standard: This is a comprehensive password recovery tool that can help you recover or remove passwords from various files, including Excel, Word, PDF, ZIP, RAR, and more. It supports all versions of Excel from 6.0 to 2019 and has a fast and easy-to-use interface. It also uses GPU acceleration technology to speed up the recovery process. It costs $49 for a single license.
            • -
            • iSunshare Excel Password Genius: This is a simple and effective Excel password remover tool that can help you remove the password from your Excel file in minutes. It supports all versions of Excel from 97 to 2016 and has a user-friendly interface that anyone can use. It also offers two attack modes to recover different types of passwords. It costs $19.95 for a single license.
            • -
            -

            How to avoid forgetting or losing your Excel password?

            -

            While Daossoft Excel Password Remover Serial 11 can help you remove the password from your Excel file in seconds, it is always better to avoid forgetting or losing your password in the first place. Here are some tips that can help you prevent this problem:

            -
              -
            • Choose a strong but memorable password for your Excel file. You can use a combination of letters, numbers, symbols, and spaces to make your password hard to guess or crack. You can also use a passphrase or a sentence that you can easily remember.
            • -
            • Write down your password somewhere safe and secure. You can use a notebook, a sticky note, a flash drive, or an online service to store your password. Make sure you keep it away from prying eyes and unauthorized access.
            • -
            • Use a password manager tool to store and manage your passwords. You can use a software or an app that can help you generate, store, and autofill your passwords for various files and accounts. You just need to remember one master password to access all your passwords.
            • -
            -

            Conclusion

            -

            Daossoft Excel Password Remover Serial 11 is a great tool for anyone who needs to remove the password from their Excel file quickly and easily. It is fast, easy, safe, and reliable. It can remove any password from any Excel file in seconds. It is compatible with all versions of Excel and supports both xls and xlsx file formats. It has a user-friendly interface and a high recovery speed. It also offers online password recovery service with guaranteed privacy.

            -

            If you want to try Daossoft Excel Password Remover Serial 11, you can download it from the official website of Daossoft and enjoy its benefits right away. You will never have to worry about forgetting or losing your Excel password again.

            -

            Conclusion

            -

            Daossoft Excel Password Remover Serial 11 is a great tool for anyone who needs to remove the password from their Excel file quickly and easily. It is fast, easy, safe, and reliable. It can remove any password from any Excel file in seconds. It is compatible with all versions of Excel and supports both xls and xlsx file formats. It has a user-friendly interface and a high recovery speed. It also offers online password recovery service with guaranteed privacy.

            -

            If you want to try Daossoft Excel Password Remover Serial 11, you can download it from the official website of Daossoft and enjoy its benefits right away. You will never have to worry about forgetting or losing your Excel password again.

            3cee63e6c2
            -
            -
            \ No newline at end of file diff --git a/spaces/rg089/NewsHelper/README.md b/spaces/rg089/NewsHelper/README.md deleted file mode 100644 index 6034f960bd4851631929a5f02e03db0b5154656a..0000000000000000000000000000000000000000 --- a/spaces/rg089/NewsHelper/README.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: NewsHelper -emoji: 🐢 -colorFrom: gray -colorTo: blue -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/rgergw/White-box-Cartoonization/wbc/guided_filter.py b/spaces/rgergw/White-box-Cartoonization/wbc/guided_filter.py deleted file mode 100644 index fd019d145efc7f308cd96de90f4e7b648f6820b4..0000000000000000000000000000000000000000 --- a/spaces/rgergw/White-box-Cartoonization/wbc/guided_filter.py +++ /dev/null @@ -1,87 +0,0 @@ -import tensorflow as tf -import numpy as np - - - - -def tf_box_filter(x, r): - k_size = int(2*r+1) - ch = x.get_shape().as_list()[-1] - weight = 1/(k_size**2) - box_kernel = weight*np.ones((k_size, k_size, ch, 1)) - box_kernel = np.array(box_kernel).astype(np.float32) - output = tf.nn.depthwise_conv2d(x, box_kernel, [1, 1, 1, 1], 'SAME') - return output - - - -def guided_filter(x, y, r, eps=1e-2): - - x_shape = tf.shape(x) - #y_shape = tf.shape(y) - - N = tf_box_filter(tf.ones((1, x_shape[1], x_shape[2], 1), dtype=x.dtype), r) - - mean_x = tf_box_filter(x, r) / N - mean_y = tf_box_filter(y, r) / N - cov_xy = tf_box_filter(x * y, r) / N - mean_x * mean_y - var_x = tf_box_filter(x * x, r) / N - mean_x * mean_x - - A = cov_xy / (var_x + eps) - b = mean_y - A * mean_x - - mean_A = tf_box_filter(A, r) / N - mean_b = tf_box_filter(b, r) / N - - output = mean_A * x + mean_b - - return output - - - -def fast_guided_filter(lr_x, lr_y, hr_x, r=1, eps=1e-8): - - #assert lr_x.shape.ndims == 4 and lr_y.shape.ndims == 4 and hr_x.shape.ndims == 4 - - lr_x_shape = tf.shape(lr_x) - #lr_y_shape = tf.shape(lr_y) - hr_x_shape = tf.shape(hr_x) - - N = tf_box_filter(tf.ones((1, lr_x_shape[1], lr_x_shape[2], 1), dtype=lr_x.dtype), r) - - mean_x = tf_box_filter(lr_x, r) / N - mean_y = tf_box_filter(lr_y, r) / N - cov_xy = tf_box_filter(lr_x * lr_y, r) / N - mean_x * mean_y - var_x = tf_box_filter(lr_x * lr_x, r) / N - mean_x * mean_x - - A = cov_xy / (var_x + eps) - b = mean_y - A * mean_x - - mean_A = tf.image.resize_images(A, hr_x_shape[1: 3]) - mean_b = tf.image.resize_images(b, hr_x_shape[1: 3]) - - output = mean_A * hr_x + mean_b - - return output - - -if __name__ == '__main__': - import cv2 - from tqdm import tqdm - - input_photo = tf.placeholder(tf.float32, [1, None, None, 3]) - #input_superpixel = tf.placeholder(tf.float32, [16, 256, 256, 3]) - output = guided_filter(input_photo, input_photo, 5, eps=1) - image = cv2.imread('output_figure1/cartoon2.jpg') - image = image/127.5 - 1 - image = np.expand_dims(image, axis=0) - - config = tf.ConfigProto() - config.gpu_options.allow_growth = True - sess = tf.Session(config=config) - sess.run(tf.global_variables_initializer()) - - out = sess.run(output, feed_dict={input_photo: image}) - out = (np.squeeze(out)+1)*127.5 - out = np.clip(out, 0, 255).astype(np.uint8) - cv2.imwrite('output_figure1/cartoon2_filter.jpg', out) diff --git a/spaces/rgres/Seg2Sat/frontend/.svelte-kit/types/src/routes/__types/index.d.ts b/spaces/rgres/Seg2Sat/frontend/.svelte-kit/types/src/routes/__types/index.d.ts deleted file mode 100644 index 16e375e095573ad0fb117290b88799922456d7df..0000000000000000000000000000000000000000 --- a/spaces/rgres/Seg2Sat/frontend/.svelte-kit/types/src/routes/__types/index.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// this file is auto-generated -import type { Load as GenericLoad } from '@sveltejs/kit'; - -export type Load< - InputProps extends Record = Record, - OutputProps extends Record = InputProps -> = GenericLoad<{}, InputProps, OutputProps>; \ No newline at end of file diff --git a/spaces/rizam/literature-research-tool/lrt_instance/instances.py b/spaces/rizam/literature-research-tool/lrt_instance/instances.py deleted file mode 100644 index 7e85d3e8702c2c8e9280fa30deb6b32240b2b869..0000000000000000000000000000000000000000 --- a/spaces/rizam/literature-research-tool/lrt_instance/instances.py +++ /dev/null @@ -1,4 +0,0 @@ -from lrt import LiteratureResearchTool -from lrt.clustering.config import * - -baseline_lrt = LiteratureResearchTool() diff --git a/spaces/rockeycoss/Prompt-Segment-Anything-Demo/mmdet/datasets/pipelines/formatting.py b/spaces/rockeycoss/Prompt-Segment-Anything-Demo/mmdet/datasets/pipelines/formatting.py deleted file mode 100644 index 2e07f3894f0e7ab9703acd9b790135cd1f878672..0000000000000000000000000000000000000000 --- a/spaces/rockeycoss/Prompt-Segment-Anything-Demo/mmdet/datasets/pipelines/formatting.py +++ /dev/null @@ -1,403 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from collections.abc import Sequence - -import mmcv -import numpy as np -import torch -from mmcv.parallel import DataContainer as DC - -from ..builder import PIPELINES - - -def to_tensor(data): - """Convert objects of various python types to :obj:`torch.Tensor`. - - Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`, - :class:`Sequence`, :class:`int` and :class:`float`. - - Args: - data (torch.Tensor | numpy.ndarray | Sequence | int | float): Data to - be converted. - """ - - if isinstance(data, torch.Tensor): - return data - elif isinstance(data, np.ndarray): - return torch.from_numpy(data) - elif isinstance(data, Sequence) and not mmcv.is_str(data): - return torch.tensor(data) - elif isinstance(data, int): - return torch.LongTensor([data]) - elif isinstance(data, float): - return torch.FloatTensor([data]) - else: - raise TypeError(f'type {type(data)} cannot be converted to tensor.') - - -@PIPELINES.register_module() -class ToTensor: - """Convert some results to :obj:`torch.Tensor` by given keys. - - Args: - keys (Sequence[str]): Keys that need to be converted to Tensor. - """ - - def __init__(self, keys): - self.keys = keys - - def __call__(self, results): - """Call function to convert data in results to :obj:`torch.Tensor`. - - Args: - results (dict): Result dict contains the data to convert. - - Returns: - dict: The result dict contains the data converted - to :obj:`torch.Tensor`. - """ - for key in self.keys: - results[key] = to_tensor(results[key]) - return results - - def __repr__(self): - return self.__class__.__name__ + f'(keys={self.keys})' - - -@PIPELINES.register_module() -class ImageToTensor: - """Convert image to :obj:`torch.Tensor` by given keys. - - The dimension order of input image is (H, W, C). The pipeline will convert - it to (C, H, W). If only 2 dimension (H, W) is given, the output would be - (1, H, W). - - Args: - keys (Sequence[str]): Key of images to be converted to Tensor. - """ - - def __init__(self, keys): - self.keys = keys - - def __call__(self, results): - """Call function to convert image in results to :obj:`torch.Tensor` and - permute the channel order. - - Args: - results (dict): Result dict contains the image data to convert. - - Returns: - dict: The result dict contains the image converted - to :obj:`torch.Tensor` and permuted to (C, H, W) order. - """ - for key in self.keys: - img = results[key] - if len(img.shape) < 3: - img = np.expand_dims(img, -1) - results[key] = to_tensor(img).permute(2, 0, 1).contiguous() - return results - - def __repr__(self): - return self.__class__.__name__ + f'(keys={self.keys})' - - -@PIPELINES.register_module() -class Transpose: - """Transpose some results by given keys. - - Args: - keys (Sequence[str]): Keys of results to be transposed. - order (Sequence[int]): Order of transpose. - """ - - def __init__(self, keys, order): - self.keys = keys - self.order = order - - def __call__(self, results): - """Call function to transpose the channel order of data in results. - - Args: - results (dict): Result dict contains the data to transpose. - - Returns: - dict: The result dict contains the data transposed to \ - ``self.order``. - """ - for key in self.keys: - results[key] = results[key].transpose(self.order) - return results - - def __repr__(self): - return self.__class__.__name__ + \ - f'(keys={self.keys}, order={self.order})' - - -@PIPELINES.register_module() -class ToDataContainer: - """Convert results to :obj:`mmcv.DataContainer` by given fields. - - Args: - fields (Sequence[dict]): Each field is a dict like - ``dict(key='xxx', **kwargs)``. The ``key`` in result will - be converted to :obj:`mmcv.DataContainer` with ``**kwargs``. - Default: ``(dict(key='img', stack=True), dict(key='gt_bboxes'), - dict(key='gt_labels'))``. - """ - - def __init__(self, - fields=(dict(key='img', stack=True), dict(key='gt_bboxes'), - dict(key='gt_labels'))): - self.fields = fields - - def __call__(self, results): - """Call function to convert data in results to - :obj:`mmcv.DataContainer`. - - Args: - results (dict): Result dict contains the data to convert. - - Returns: - dict: The result dict contains the data converted to \ - :obj:`mmcv.DataContainer`. - """ - - for field in self.fields: - field = field.copy() - key = field.pop('key') - results[key] = DC(results[key], **field) - return results - - def __repr__(self): - return self.__class__.__name__ + f'(fields={self.fields})' - - -@PIPELINES.register_module() -class DefaultFormatBundle: - """Default formatting bundle. - - It simplifies the pipeline of formatting common fields, including "img", - "proposals", "gt_bboxes", "gt_labels", "gt_masks" and "gt_semantic_seg". - These fields are formatted as follows. - - - img: (1)transpose & to tensor, (2)to DataContainer (stack=True) - - proposals: (1)to tensor, (2)to DataContainer - - gt_bboxes: (1)to tensor, (2)to DataContainer - - gt_bboxes_ignore: (1)to tensor, (2)to DataContainer - - gt_labels: (1)to tensor, (2)to DataContainer - - gt_masks: (1)to tensor, (2)to DataContainer (cpu_only=True) - - gt_semantic_seg: (1)unsqueeze dim-0 (2)to tensor, \ - (3)to DataContainer (stack=True) - - Args: - img_to_float (bool): Whether to force the image to be converted to - float type. Default: True. - pad_val (dict): A dict for padding value in batch collating, - the default value is `dict(img=0, masks=0, seg=255)`. - Without this argument, the padding value of "gt_semantic_seg" - will be set to 0 by default, which should be 255. - """ - - def __init__(self, - img_to_float=True, - pad_val=dict(img=0, masks=0, seg=255)): - self.img_to_float = img_to_float - self.pad_val = pad_val - - def __call__(self, results): - """Call function to transform and format common fields in results. - - Args: - results (dict): Result dict contains the data to convert. - - Returns: - dict: The result dict contains the data that is formatted with \ - default bundle. - """ - - if 'img' in results: - img = results['img'] - if self.img_to_float is True and img.dtype == np.uint8: - # Normally, image is of uint8 type without normalization. - # At this time, it needs to be forced to be converted to - # flot32, otherwise the model training and inference - # will be wrong. Only used for YOLOX currently . - img = img.astype(np.float32) - # add default meta keys - results = self._add_default_meta_keys(results) - if len(img.shape) < 3: - img = np.expand_dims(img, -1) - # To improve the computational speed by by 3-5 times, apply: - # If image is not contiguous, use - # `numpy.transpose()` followed by `numpy.ascontiguousarray()` - # If image is already contiguous, use - # `torch.permute()` followed by `torch.contiguous()` - # Refer to https://github.com/open-mmlab/mmdetection/pull/9533 - # for more details - if not img.flags.c_contiguous: - img = np.ascontiguousarray(img.transpose(2, 0, 1)) - img = to_tensor(img) - else: - img = to_tensor(img).permute(2, 0, 1).contiguous() - results['img'] = DC( - img, padding_value=self.pad_val['img'], stack=True) - for key in ['proposals', 'gt_bboxes', 'gt_bboxes_ignore', 'gt_labels']: - if key not in results: - continue - results[key] = DC(to_tensor(results[key])) - if 'gt_masks' in results: - results['gt_masks'] = DC( - results['gt_masks'], - padding_value=self.pad_val['masks'], - cpu_only=True) - if 'gt_semantic_seg' in results: - results['gt_semantic_seg'] = DC( - to_tensor(results['gt_semantic_seg'][None, ...]), - padding_value=self.pad_val['seg'], - stack=True) - return results - - def _add_default_meta_keys(self, results): - """Add default meta keys. - - We set default meta keys including `pad_shape`, `scale_factor` and - `img_norm_cfg` to avoid the case where no `Resize`, `Normalize` and - `Pad` are implemented during the whole pipeline. - - Args: - results (dict): Result dict contains the data to convert. - - Returns: - results (dict): Updated result dict contains the data to convert. - """ - img = results['img'] - results.setdefault('pad_shape', img.shape) - results.setdefault('scale_factor', 1.0) - num_channels = 1 if len(img.shape) < 3 else img.shape[2] - results.setdefault( - 'img_norm_cfg', - dict( - mean=np.zeros(num_channels, dtype=np.float32), - std=np.ones(num_channels, dtype=np.float32), - to_rgb=False)) - return results - - def __repr__(self): - return self.__class__.__name__ + \ - f'(img_to_float={self.img_to_float})' - - -@PIPELINES.register_module() -class Collect: - """Collect data from the loader relevant to the specific task. - - This is usually the last stage of the data loader pipeline. Typically keys - is set to some subset of "img", "proposals", "gt_bboxes", - "gt_bboxes_ignore", "gt_labels", and/or "gt_masks". - - The "img_meta" item is always populated. The contents of the "img_meta" - dictionary depends on "meta_keys". By default this includes: - - - "img_shape": shape of the image input to the network as a tuple \ - (h, w, c). Note that images may be zero padded on the \ - bottom/right if the batch tensor is larger than this shape. - - - "scale_factor": a float indicating the preprocessing scale - - - "flip": a boolean indicating if image flip transform was used - - - "filename": path to the image file - - - "ori_shape": original shape of the image as a tuple (h, w, c) - - - "pad_shape": image shape after padding - - - "img_norm_cfg": a dict of normalization information: - - - mean - per channel mean subtraction - - std - per channel std divisor - - to_rgb - bool indicating if bgr was converted to rgb - - Args: - keys (Sequence[str]): Keys of results to be collected in ``data``. - meta_keys (Sequence[str], optional): Meta keys to be converted to - ``mmcv.DataContainer`` and collected in ``data[img_metas]``. - Default: ``('filename', 'ori_filename', 'ori_shape', 'img_shape', - 'pad_shape', 'scale_factor', 'flip', 'flip_direction', - 'img_norm_cfg')`` - """ - - def __init__(self, - keys, - meta_keys=('filename', 'ori_filename', 'ori_shape', - 'img_shape', 'pad_shape', 'scale_factor', 'flip', - 'flip_direction', 'img_norm_cfg')): - self.keys = keys - self.meta_keys = meta_keys - - def __call__(self, results): - """Call function to collect keys in results. The keys in ``meta_keys`` - will be converted to :obj:mmcv.DataContainer. - - Args: - results (dict): Result dict contains the data to collect. - - Returns: - dict: The result dict contains the following keys - - - keys in``self.keys`` - - ``img_metas`` - """ - - data = {} - img_meta = {} - for key in self.meta_keys: - img_meta[key] = results[key] - data['img_metas'] = DC(img_meta, cpu_only=True) - for key in self.keys: - data[key] = results[key] - return data - - def __repr__(self): - return self.__class__.__name__ + \ - f'(keys={self.keys}, meta_keys={self.meta_keys})' - - -@PIPELINES.register_module() -class WrapFieldsToLists: - """Wrap fields of the data dictionary into lists for evaluation. - - This class can be used as a last step of a test or validation - pipeline for single image evaluation or inference. - - Example: - >>> test_pipeline = [ - >>> dict(type='LoadImageFromFile'), - >>> dict(type='Normalize', - mean=[123.675, 116.28, 103.53], - std=[58.395, 57.12, 57.375], - to_rgb=True), - >>> dict(type='Pad', size_divisor=32), - >>> dict(type='ImageToTensor', keys=['img']), - >>> dict(type='Collect', keys=['img']), - >>> dict(type='WrapFieldsToLists') - >>> ] - """ - - def __call__(self, results): - """Call function to wrap fields into lists. - - Args: - results (dict): Result dict contains the data to wrap. - - Returns: - dict: The result dict where value of ``self.keys`` are wrapped \ - into list. - """ - - # Wrap dict fields into lists - for key, val in results.items(): - results[key] = [val] - return results - - def __repr__(self): - return f'{self.__class__.__name__}()' diff --git a/spaces/rockeycoss/Prompt-Segment-Anything-Demo/projects/instance_segment_anything/models/segment_anything/utils/transforms.py b/spaces/rockeycoss/Prompt-Segment-Anything-Demo/projects/instance_segment_anything/models/segment_anything/utils/transforms.py deleted file mode 100644 index 3ad346661f84b0647026e130a552c4b38b83e2ac..0000000000000000000000000000000000000000 --- a/spaces/rockeycoss/Prompt-Segment-Anything-Demo/projects/instance_segment_anything/models/segment_anything/utils/transforms.py +++ /dev/null @@ -1,102 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. - -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -import numpy as np -import torch -from torch.nn import functional as F -from torchvision.transforms.functional import resize, to_pil_image # type: ignore - -from copy import deepcopy -from typing import Tuple - - -class ResizeLongestSide: - """ - Resizes images to longest side 'target_length', as well as provides - methods for resizing coordinates and boxes. Provides methods for - transforming both numpy array and batched torch tensors. - """ - - def __init__(self, target_length: int) -> None: - self.target_length = target_length - - def apply_image(self, image: np.ndarray) -> np.ndarray: - """ - Expects a numpy array with shape HxWxC in uint8 format. - """ - target_size = self.get_preprocess_shape(image.shape[0], image.shape[1], self.target_length) - return np.array(resize(to_pil_image(image), target_size)) - - def apply_coords(self, coords: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray: - """ - Expects a numpy array of length 2 in the final dimension. Requires the - original image size in (H, W) format. - """ - old_h, old_w = original_size - new_h, new_w = self.get_preprocess_shape( - original_size[0], original_size[1], self.target_length - ) - coords = deepcopy(coords).astype(float) - coords[..., 0] = coords[..., 0] * (new_w / old_w) - coords[..., 1] = coords[..., 1] * (new_h / old_h) - return coords - - def apply_boxes(self, boxes: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray: - """ - Expects a numpy array shape Bx4. Requires the original image size - in (H, W) format. - """ - boxes = self.apply_coords(boxes.reshape(-1, 2, 2), original_size) - return boxes.reshape(-1, 4) - - def apply_image_torch(self, image: torch.Tensor) -> torch.Tensor: - """ - Expects batched images with shape BxCxHxW and float format. This - transformation may not exactly match apply_image. apply_image is - the transformation expected by the model. - """ - # Expects an image in BCHW format. May not exactly match apply_image. - target_size = self.get_preprocess_shape(image.shape[0], image.shape[1], self.target_length) - return F.interpolate( - image, target_size, mode="bilinear", align_corners=False, antialias=True - ) - - def apply_coords_torch( - self, coords: torch.Tensor, original_size: Tuple[int, ...] - ) -> torch.Tensor: - """ - Expects a torch tensor with length 2 in the last dimension. Requires the - original image size in (H, W) format. - """ - old_h, old_w = original_size - new_h, new_w = self.get_preprocess_shape( - original_size[0], original_size[1], self.target_length - ) - coords = deepcopy(coords).to(torch.float) - coords[..., 0] = coords[..., 0] * (new_w / old_w) - coords[..., 1] = coords[..., 1] * (new_h / old_h) - return coords - - def apply_boxes_torch( - self, boxes: torch.Tensor, original_size: Tuple[int, ...] - ) -> torch.Tensor: - """ - Expects a torch tensor with shape Bx4. Requires the original image - size in (H, W) format. - """ - boxes = self.apply_coords_torch(boxes.reshape(-1, 2, 2), original_size) - return boxes.reshape(-1, 4) - - @staticmethod - def get_preprocess_shape(oldh: int, oldw: int, long_side_length: int) -> Tuple[int, int]: - """ - Compute the output size given input size and target long side length. - """ - scale = long_side_length * 1.0 / max(oldh, oldw) - newh, neww = oldh * scale, oldw * scale - neww = int(neww + 0.5) - newh = int(newh + 0.5) - return (newh, neww) diff --git a/spaces/rorallitri/biomedical-language-models/logs/Get Stardock Fences 3.0.9.11 Crack and Transform Your Desktop Experience!.md b/spaces/rorallitri/biomedical-language-models/logs/Get Stardock Fences 3.0.9.11 Crack and Transform Your Desktop Experience!.md deleted file mode 100644 index fb5c82b6daa7acf4b03772ed39b9cdd13d371851..0000000000000000000000000000000000000000 --- a/spaces/rorallitri/biomedical-language-models/logs/Get Stardock Fences 3.0.9.11 Crack and Transform Your Desktop Experience!.md +++ /dev/null @@ -1,6 +0,0 @@ - -

            desktop fences,,Program download Stardock Fences, Download Stardock Fences, Download Stardock Fences, Program Stardock Fences, Stardock Fences Full activated, crack program Stardock Fences, program explanation Stardock Fences

            -

            Your computer will be at risk getting infected with spyware, adware, viruses, worms, trojan horses, dialers, etcwhile you are searching and browsing these illegal sites which distribute a so called keygen, key generator, pirate key, serial number, warez full version or crack forFences 4.7.2.0 download. These infections might corrupt your computer installation or breach your privacy.A keygen or key generator might contain a trojan horse opening a backdoor on your computer.Hackers can use this backdoor to take control of your computer, copy data from your computer or to use your computer to distribute viruses and spam to other people.

            -

            Stardock Fences 3.0.9.11 Crack Download HERE !


            DOWNLOAD >>>>> https://tinurll.com/2uznSk



            aaccfb2cb3
            -
            -
            \ No newline at end of file diff --git a/spaces/scedlatioru/img-to-music/example/Ebook Rekayasa Perangkat Lunak Roger S Pressman !!TOP!!.md b/spaces/scedlatioru/img-to-music/example/Ebook Rekayasa Perangkat Lunak Roger S Pressman !!TOP!!.md deleted file mode 100644 index d2885e40f220fc9fb287bdfccf5f1b3509acb027..0000000000000000000000000000000000000000 --- a/spaces/scedlatioru/img-to-music/example/Ebook Rekayasa Perangkat Lunak Roger S Pressman !!TOP!!.md +++ /dev/null @@ -1,10 +0,0 @@ - -

            enterprises have various needs and interests and they must be reported in a single, quantitative way. pressman, roger s. (2010). rekayasa perangkat lunak jangkau ria. l.n hamaningrum. yogyakarta: andi. [14] ari m.

            -

            digital librarian pressman, p. m pressman, 1999. industry pressman. l-r: (1) pressman, roger, (2) carvalho, john (3) andi, tutti. 1,000 practical suggestions for improving it in libraries. pressman pressman, dan harta, (2000) in the professional journal of library

            -

            ebook rekayasa perangkat lunak roger s pressman


            Download Filehttps://gohhs.com/2uEAt1



            -

            pressman, roger s. rekayasa perangkat lunak: pendekatan praktisi buku 1, doi 10.34440/jaict.v4i1.3018. the movers and the shakers! ted r. fromjan librarian, noted author of "fromalibrary" who was earlier part of codexis and state university of new york,

            -

            pdf nomor : novr. roger pressman rekayasa perangkat lunak jadi antara orang-orang. dalam. buku 1 edisi 7. santos, gires, hj. 2012. unpacking software engineering as a discipline a. among the first books on software engineering in indonesia, roger s. pressman roger s pressman rekayasa perangkat lunak, roger s pressman rekayasa perangkat lunak. pressman roger s pressman rekayasa perangkat lunak.

            -

            sobat hari lalu pengajiban writer/foreverfugue roger s pressman roger s pressman roger s pressman, dalam kapasitas jaman soal. mar 11th, 2020. rekayasa perangkat lunak rekayasa perangkat lunak, rekayasa perangkat lunak, rekayasa perangkat lunak roger s pressman, . rekayasa perangkat lunak buku 2 edisi 9. roger s. pressman, rekayasa perangkat lunak - buku satu. praktisi, buku 2 edisi 9, andi offset, yogyakarta. jom mobil, roger s. pressman, 2012. program software engineering and design pressman, roger s.

            -

            899543212b
            -
            -
            \ No newline at end of file diff --git a/spaces/scedlatioru/img-to-music/example/VERO EDGECAM 2016-R1-[MAGNiTUDE].rar.md b/spaces/scedlatioru/img-to-music/example/VERO EDGECAM 2016-R1-[MAGNiTUDE].rar.md deleted file mode 100644 index a4d7398d75ea3fc75d0e0f831944b5fcd3a873e5..0000000000000000000000000000000000000000 --- a/spaces/scedlatioru/img-to-music/example/VERO EDGECAM 2016-R1-[MAGNiTUDE].rar.md +++ /dev/null @@ -1,29 +0,0 @@ - -

            VERO EDGECAM 2016-R1-[MAGNiTUDE].rar: A Comprehensive Review

            -

            VERO EDGECAM 2016-R1-[MAGNiTUDE].rar is a file name that may not mean much to most people, but for those who are interested in CAD/CAM software, it is a treasure trove of features and benefits. VERO EDGECAM is a powerful and versatile software that allows you to design, simulate, and produce high-quality parts and products using various machining methods and tools. In this article, we will review VERO EDGECAM 2016-R1-[MAGNiTUDE].rar, the latest version of the software that was released in 2016. We will cover its main features, advantages, disadvantages, and how to download and install it on your PC.

            -

            What is VERO EDGECAM 2016-R1-[MAGNiTUDE].rar?

            -

            VERO EDGECAM 2016-R1-[MAGNiTUDE].rar is a compressed file that contains the installation files for VERO EDGECAM 2016-R1, the latest version of VERO EDGECAM as of 2016. VERO EDGECAM is a CAD/CAM software that was developed by Vero Software, a leading provider of software solutions for the manufacturing industry. VERO EDGECAM is used by thousands of engineers and machinists around the world to design, simulate, and produce parts and products using various machining methods and tools, such as milling, turning, wire EDM, multi-axis machining, additive manufacturing, etc.

            -

            VERO EDGECAM 2016-R1-[MAGNiTUDE].rar


            Download Filehttps://gohhs.com/2uEyR6



            -

            VERO EDGECAM 2016-R1-[MAGNiTUDE].rar was released by MAGNiTUDE, a group of hackers who cracked the software and made it available for free download on various websites and torrent platforms. MAGNiTUDE is known for cracking and releasing various software products from different vendors, such as Autodesk, Adobe, Microsoft, etc.

            -

            What are the main features of VERO EDGECAM 2016-R1-[MAGNiTUDE].rar?

            -

            VERO EDGECAM 2016-R1-[MAGNiTUDE].rar contains many features and improvements that make it one of the best CAD/CAM software in the market. Some of the main features are:

            -
              -
            • A user-friendly interface that allows you to easily create and edit your designs using various tools and commands.
            • -
            • A powerful geometry engine that supports various types of entities, such as lines, arcs, circles, splines, surfaces, solids, etc.
            • -
            • A comprehensive library of machining cycles that cover various operations, such as roughing, finishing, drilling, tapping, threading, grooving, etc.
            • -
            • A sophisticated simulation module that allows you to visualize and verify your machining processes in 3D before sending them to the machine.
            • -
            • A seamless integration with various CAD systems, such as SolidWorks, Inventor, Solid Edge, etc., that allows you to import and export your designs easily.
            • -
            • A flexible post-processor generator that allows you to customize your output code according to your machine specifications and preferences.
            • -
            • A new additive manufacturing module that allows you to create parts using 3D printing technology.
            • -
            • A new strategy manager module that allows you to automate your machining processes using rules-based programming.
            • -
            • A new waveform roughing module that allows you to optimize your material removal rate using a constant chip load strategy.
            • -
            • A new edgecam designer module that allows you to create and modify your designs directly in VERO EDGECAM without using any external CAD system.
            • -
            -

            What are the advantages of VERO EDGECAM 2016-R1-[MAGNiTUDE].rar?

            -

            VERO EDGECAM 2016-R1-[MAGNiTUDE].rar offers many advantages over other CAD/CAM software in terms of functionality

            -

            Conclusion

            -

            VERO EDGECAM 2016-R1-[MAGNiTUDE].rar is a file name that represents a powerful and versatile CAD/CAM software that can help you design, simulate, and produce high-quality parts and products using various machining methods and tools. VERO EDGECAM 2016-R1-[MAGNiTUDE].rar contains many features and improvements that make it one of the best CAD/CAM software in the market, such as a user-friendly interface, a comprehensive library of machining cycles, a sophisticated simulation module, a seamless integration with various CAD systems, a flexible post-processor generator, a new additive manufacturing module, a new strategy manager module, a new waveform roughing module, and a new edgecam designer module. VERO EDGECAM 2016-R1-[MAGNiTUDE].rar also offers many advantages over other CAD/CAM software in terms of functionality, performance, quality, and compatibility.

            -

            VERO EDGECAM 2016-R1-[MAGNiTUDE].rar was released by MAGNiTUDE, a group of hackers who cracked the software and made it available for free download on various websites and torrent platforms. However, downloading and installing VERO EDGECAM 2016-R1-[MAGNiTUDE].rar may not be legal or safe, as it may violate the intellectual property rights of Vero Software or contain malware or viruses. Therefore, we recommend that you buy the original software from the official Vero Software website or authorized resellers.

            -

            This article has shown you how to review VERO EDGECAM 2016-R1-[MAGNiTUDE].rar, the latest version of VERO EDGECAM as of 2016. We hope this guide has been helpful for you. If you have any questions or feedback, please feel free to leave a comment below.

            3cee63e6c2
            -
            -
            \ No newline at end of file diff --git a/spaces/schibsted/Facial_Recognition_with_Sentiment_Detector/README.md b/spaces/schibsted/Facial_Recognition_with_Sentiment_Detector/README.md deleted file mode 100644 index 845a17181a8648dcc4581f080058f24da93bc000..0000000000000000000000000000000000000000 --- a/spaces/schibsted/Facial_Recognition_with_Sentiment_Detector/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Facial Recognition With Sentiment Detector -emoji: 👀 -colorFrom: indigo -colorTo: green -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/segments-tobias/conex/espnet2/asr/frontend/__init__.py b/spaces/segments-tobias/conex/espnet2/asr/frontend/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/sh20raj/uploader/app.py b/spaces/sh20raj/uploader/app.py deleted file mode 100644 index 336f64ee2800ba923bfdde96f4e131edd0bf0989..0000000000000000000000000000000000000000 --- a/spaces/sh20raj/uploader/app.py +++ /dev/null @@ -1,53 +0,0 @@ -import gradio as gr -import torch -from PIL import Image -from torchvision import transforms -import huggingface_hub as hf - -# HuggingFace model and Spaces -model = torch.hub.load('facebookresearch/deit:main', 'deit_tiny_patch16_224') -repo = "uploader" - -# File upload component with local or remote option -file = gr.FileInput(type="file", label="Upload Image File", preview=True) - -# Display image -image = gr.Image(label="Uploaded Image") - -# Upload file to HuggingFace Spaces -def upload_to_hf(filename): - with open(filename, 'rb') as f: - data = f.read() - hf.upload_file(data, f"/{repo}/{filename}") - return f"/{repo}/{filename}" - -# Run model on image -def run(file): - if file.startswith("http"): # remote file - filename = file.split("/")[-1] - filepath = upload_to_hf(filename) - else: # local file - filepath = file - - image = Image.open(filepath).convert('RGB') - - # preprocess, run model, return output - transform = transforms.Compose([ - transforms.Resize(256), - transforms.CenterCrop(224), - transforms.ToTensor(), - transforms.Normalize([0.5,0.5,0.5],[0.5,0.5,0.5]) - ]) - - tensor = transform(image) - tensor = tensor.unsqueeze(0) - - with torch.no_grad(): - output = model(tensor) - - image.update(filepath) - return image - -# Launch app -app = gr.Interface(fn=run, inputs=[file], outputs=[image]) -app.launch() \ No newline at end of file diff --git a/spaces/shenfangqi/Retrieval-based-Voice-Conversion-WebUI/docs/README.ko.han.md b/spaces/shenfangqi/Retrieval-based-Voice-Conversion-WebUI/docs/README.ko.han.md deleted file mode 100644 index d05f1f986594bfc0f2764901cd3aa9f92db3b381..0000000000000000000000000000000000000000 --- a/spaces/shenfangqi/Retrieval-based-Voice-Conversion-WebUI/docs/README.ko.han.md +++ /dev/null @@ -1,102 +0,0 @@ -
            - -

            Retrieval-based-Voice-Conversion-WebUI

            -VITS基盤의 簡單하고使用하기 쉬운音聲變換틀

            - -[![madewithlove](https://forthebadge.com/images/badges/built-with-love.svg)](https://github.com/liujing04/Retrieval-based-Voice-Conversion-WebUI) - -
            - -[![Open In Colab](https://img.shields.io/badge/Colab-F9AB00?style=for-the-badge&logo=googlecolab&color=525252)](https://colab.research.google.com/github/liujing04/Retrieval-based-Voice-Conversion-WebUI/blob/main/Retrieval_based_Voice_Conversion_WebUI.ipynb) -[![Licence](https://img.shields.io/github/license/liujing04/Retrieval-based-Voice-Conversion-WebUI?style=for-the-badge)](https://github.com/liujing04/Retrieval-based-Voice-Conversion-WebUI/blob/main/%E4%BD%BF%E7%94%A8%E9%9C%80%E9%81%B5%E5%AE%88%E7%9A%84%E5%8D%8F%E8%AE%AE-LICENSE.txt) -[![Huggingface](https://img.shields.io/badge/🤗%20-Spaces-yellow.svg?style=for-the-badge)](https://huggingface.co/lj1995/VoiceConversionWebUI/tree/main/) - -[![Discord](https://img.shields.io/badge/RVC%20Developers-Discord-7289DA?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/HcsmBBGyVk) - -
            - ------- -[**更新日誌**](https://github.com/liujing04/Retrieval-based-Voice-Conversion-WebUI/blob/main/Changelog_CN.md) - -[**English**](./README.en.md) | [**中文简体**](../README.md) | [**日本語**](./README.ja.md) | [**한국어**](./README.ko.md) ([**韓國語**](./README.ko.han.md)) - -> [示範映像](https://www.bilibili.com/video/BV1pm4y1z7Gm/)을 確認해 보세요! - -> RVC를活用한實時間音聲變換: [w-okada/voice-changer](https://github.com/w-okada/voice-changer) - -> 基本모델은 50時間假量의 高品質 오픈 소스 VCTK 데이터셋을 使用하였으므로, 著作權上의 念慮가 없으니 安心하고 使用하시기 바랍니다. - -> 著作權問題가 없는 高品質의 노래를 以後에도 繼續해서 訓練할 豫定입니다. - -## 紹介 -本Repo는 다음과 같은 特徵을 가지고 있습니다: -+ top1檢索을利用하여 入力音色特徵을 訓練세트音色特徵으로 代替하여 音色의漏出을 防止; -+ 相對的으로 낮은性能의 GPU에서도 빠른訓練可能; -+ 적은量의 데이터로 訓練해도 좋은 結果를 얻을 수 있음 (最小10分以上의 低雜음音聲데이터를 使用하는 것을 勸獎); -+ 모델融合을通한 音色의 變調可能 (ckpt處理탭->ckpt混合選擇); -+ 使用하기 쉬운 WebUI (웹 使用者인터페이스); -+ UVR5 모델을 利用하여 목소리와 背景音樂의 빠른 分離; - -## 環境의準備 -poetry를通해 依存를設置하는 것을 勸獎합니다. - -다음命令은 Python 버전3.8以上의環境에서 實行되어야 합니다: -```bash -# PyTorch 關聯主要依存設置, 이미設置되어 있는 境遇 건너뛰기 可能 -# 參照: https://pytorch.org/get-started/locally/ -pip install torch torchvision torchaudio - -# Windows + Nvidia Ampere Architecture(RTX30xx)를 使用하고 있다面, #21 에서 명시된 것과 같이 PyTorch에 맞는 CUDA 버전을 指定해야 합니다. -#pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu117 - -# Poetry 設置, 이미設置되어 있는 境遇 건너뛰기 可能 -# Reference: https://python-poetry.org/docs/#installation -curl -sSL https://install.python-poetry.org | python3 - - -# 依存設置 -poetry install -``` -pip를 活用하여依存를 設置하여도 無妨합니다. - -**公知**: `MacOS`에서 `faiss 1.7.2`를 使用하면 Segmentation Fault: 11 誤謬가 發生할 수 있습니다. 手動으로 pip를 使用하여 設置하는境遇 `pip install faiss-cpu==1.7.0`을 使用해야 합니다. - -```bash -pip install -r requirements.txt -``` - -## 其他預備모델準備 -RVC 모델은 推論과訓練을 依하여 다른 預備모델이 必要합니다. - -[Huggingface space](https://huggingface.co/lj1995/VoiceConversionWebUI/tree/main/)를 通해서 다운로드 할 수 있습니다. - -다음은 RVC에 必要한 預備모델 및 其他 파일 目錄입니다: -```bash -hubert_base.pt - -./pretrained - -./uvr5_weights - -# Windows를 使用하는境遇 이 사전도 必要할 수 있습니다. FFmpeg가 設置되어 있으면 건너뛰어도 됩니다. -ffmpeg.exe -``` -그後 以下의 命令을 使用하여 WebUI를 始作할 수 있습니다: -```bash -python infer-web.py -``` -Windows를 使用하는境遇 `RVC-beta.7z`를 다운로드 및 壓縮解除하여 RVC를 直接使用하거나 `go-web.bat`을 使用하여 WebUi를 直接할 수 있습니다. - -## 參考 -+ [ContentVec](https://github.com/auspicious3000/contentvec/) -+ [VITS](https://github.com/jaywalnut310/vits) -+ [HIFIGAN](https://github.com/jik876/hifi-gan) -+ [Gradio](https://github.com/gradio-app/gradio) -+ [FFmpeg](https://github.com/FFmpeg/FFmpeg) -+ [Ultimate Vocal Remover](https://github.com/Anjok07/ultimatevocalremovergui) -+ [audio-slicer](https://github.com/openvpi/audio-slicer) -## 모든寄與者분들의勞力에感謝드립니다 - - - - - diff --git a/spaces/shi-labs/OneFormer/oneformer/modeling/meta_arch/oneformer_head.py b/spaces/shi-labs/OneFormer/oneformer/modeling/meta_arch/oneformer_head.py deleted file mode 100644 index cf6dbd9f5d734acd3a895a15fa67544f872e80ea..0000000000000000000000000000000000000000 --- a/spaces/shi-labs/OneFormer/oneformer/modeling/meta_arch/oneformer_head.py +++ /dev/null @@ -1,135 +0,0 @@ -# ------------------------------------------------------------------------------ -# Reference: https://github.com/facebookresearch/Mask2Former/blob/main/mask2former/modeling/meta_arch/mask_former_head.py -# Modified by Jitesh Jain (https://github.com/praeclarumjj3) -# ------------------------------------------------------------------------------ - -import logging -from copy import deepcopy -from typing import Callable, Dict, List, Optional, Tuple, Union - -import fvcore.nn.weight_init as weight_init -from torch import nn -from torch.nn import functional as F - -from detectron2.config import configurable -from detectron2.layers import Conv2d, ShapeSpec, get_norm -from detectron2.modeling import SEM_SEG_HEADS_REGISTRY -from ..pixel_decoder.fpn import build_pixel_decoder -from ..transformer_decoder.oneformer_transformer_decoder import build_transformer_decoder - -@SEM_SEG_HEADS_REGISTRY.register() -class OneFormerHead(nn.Module): - - _version = 2 - - def _load_from_state_dict( - self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs - ): - version = local_metadata.get("version", None) - if version is None or version < 2: - # Do not warn if train from scratch - scratch = True - logger = logging.getLogger(__name__) - for k in list(state_dict.keys()): - newk = k - if "sem_seg_head" in k and not k.startswith(prefix + "predictor"): - newk = k.replace(prefix, prefix + "pixel_decoder.") - # logger.debug(f"{k} ==> {newk}") - if newk != k: - state_dict[newk] = state_dict[k] - del state_dict[k] - scratch = False - - if not scratch: - logger.warning( - f"Weight format of {self.__class__.__name__} have changed! " - "Please upgrade your models. Applying automatic conversion now ..." - ) - - @configurable - def __init__( - self, - input_shape: Dict[str, ShapeSpec], - *, - num_classes: int, - pixel_decoder: nn.Module, - loss_weight: float = 1.0, - ignore_value: int = -1, - # extra parameters - transformer_predictor: nn.Module, - transformer_in_feature: str, - ): - """ - NOTE: this interface is experimental. - Args: - input_shape: shapes (channels and stride) of the input features - num_classes: number of classes to predict - pixel_decoder: the pixel decoder module - loss_weight: loss weight - ignore_value: category id to be ignored during training. - transformer_predictor: the transformer decoder that makes prediction - transformer_in_feature: input feature name to the transformer_predictor - """ - super().__init__() - input_shape = sorted(input_shape.items(), key=lambda x: x[1].stride) - self.in_features = [k for k, v in input_shape] - feature_strides = [v.stride for k, v in input_shape] - feature_channels = [v.channels for k, v in input_shape] - - self.ignore_value = ignore_value - self.common_stride = 4 - self.loss_weight = loss_weight - - self.pixel_decoder = pixel_decoder - self.predictor = transformer_predictor - self.transformer_in_feature = transformer_in_feature - - self.num_classes = num_classes - - @classmethod - def from_config(cls, cfg, input_shape: Dict[str, ShapeSpec]): - # figure out in_channels to transformer predictor - if cfg.MODEL.ONE_FORMER.TRANSFORMER_IN_FEATURE == "transformer_encoder": - transformer_predictor_in_channels = cfg.MODEL.SEM_SEG_HEAD.CONVS_DIM - elif cfg.MODEL.ONE_FORMER.TRANSFORMER_IN_FEATURE == "pixel_embedding": - transformer_predictor_in_channels = cfg.MODEL.SEM_SEG_HEAD.MASK_DIM - elif cfg.MODEL.ONE_FORMER.TRANSFORMER_IN_FEATURE == "multi_scale_pixel_decoder": - transformer_predictor_in_channels = cfg.MODEL.SEM_SEG_HEAD.CONVS_DIM - else: - transformer_predictor_in_channels = input_shape[cfg.MODEL.ONE_FORMER.TRANSFORMER_IN_FEATURE].channels - - return { - "input_shape": { - k: v for k, v in input_shape.items() if k in cfg.MODEL.SEM_SEG_HEAD.IN_FEATURES - }, - "ignore_value": cfg.MODEL.SEM_SEG_HEAD.IGNORE_VALUE, - "num_classes": cfg.MODEL.SEM_SEG_HEAD.NUM_CLASSES, - "pixel_decoder": build_pixel_decoder(cfg, input_shape), - "loss_weight": cfg.MODEL.SEM_SEG_HEAD.LOSS_WEIGHT, - "transformer_in_feature": cfg.MODEL.ONE_FORMER.TRANSFORMER_IN_FEATURE, - "transformer_predictor": build_transformer_decoder( - cfg, - transformer_predictor_in_channels, - mask_classification=True, - ), - } - - def forward(self, features, tasks, mask=None): - return self.layers(features, tasks, mask) - - def layers(self, features, tasks, mask=None): - mask_features, transformer_encoder_features, multi_scale_features, _, _ = self.pixel_decoder.forward_features(features) - - if self.transformer_in_feature == "multi_scale_pixel_decoder": - predictions = self.predictor(multi_scale_features, mask_features, tasks, mask) - else: - if self.transformer_in_feature == "transformer_encoder": - assert ( - transformer_encoder_features is not None - ), "Please use the TransformerEncoderPixelDecoder." - predictions = self.predictor(transformer_encoder_features, mask_features, mask) - elif self.transformer_in_feature == "pixel_embedding": - predictions = self.predictor(mask_features, mask_features, mask) - else: - predictions = self.predictor(features[self.transformer_in_feature], mask_features, mask) - return predictions diff --git a/spaces/shibing624/CLIP-Image-Search/README.md b/spaces/shibing624/CLIP-Image-Search/README.md deleted file mode 100644 index 68843d9b128f47e84c6675411e101991248d3bff..0000000000000000000000000000000000000000 --- a/spaces/shibing624/CLIP-Image-Search/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: CLIP Image Search -emoji: 💻 -colorFrom: red -colorTo: yellow -sdk: gradio -sdk_version: 3.47.1 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/sidharthism/fashion-eye/models/stylegan/stylegan_tf/training/networks_progan.py b/spaces/sidharthism/fashion-eye/models/stylegan/stylegan_tf/training/networks_progan.py deleted file mode 100644 index 896f500b0bfca5c292b1cba8de79e270f6a08036..0000000000000000000000000000000000000000 --- a/spaces/sidharthism/fashion-eye/models/stylegan/stylegan_tf/training/networks_progan.py +++ /dev/null @@ -1,322 +0,0 @@ -# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. -# -# This work is licensed under the Creative Commons Attribution-NonCommercial -# 4.0 International License. To view a copy of this license, visit -# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to -# Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. - -"""Network architectures used in the ProGAN paper.""" - -import numpy as np -import tensorflow as tf - -# NOTE: Do not import any application-specific modules here! -# Specify all network parameters as kwargs. - -#---------------------------------------------------------------------------- - -def lerp(a, b, t): return a + (b - a) * t -def lerp_clip(a, b, t): return a + (b - a) * tf.clip_by_value(t, 0.0, 1.0) -def cset(cur_lambda, new_cond, new_lambda): return lambda: tf.cond(new_cond, new_lambda, cur_lambda) - -#---------------------------------------------------------------------------- -# Get/create weight tensor for a convolutional or fully-connected layer. - -def get_weight(shape, gain=np.sqrt(2), use_wscale=False): - fan_in = np.prod(shape[:-1]) # [kernel, kernel, fmaps_in, fmaps_out] or [in, out] - std = gain / np.sqrt(fan_in) # He init - if use_wscale: - wscale = tf.constant(np.float32(std), name='wscale') - w = tf.get_variable('weight', shape=shape, initializer=tf.initializers.random_normal()) * wscale - else: - w = tf.get_variable('weight', shape=shape, initializer=tf.initializers.random_normal(0, std)) - return w - -#---------------------------------------------------------------------------- -# Fully-connected layer. - -def dense(x, fmaps, gain=np.sqrt(2), use_wscale=False): - if len(x.shape) > 2: - x = tf.reshape(x, [-1, np.prod([d.value for d in x.shape[1:]])]) - w = get_weight([x.shape[1].value, fmaps], gain=gain, use_wscale=use_wscale) - w = tf.cast(w, x.dtype) - return tf.matmul(x, w) - -#---------------------------------------------------------------------------- -# Convolutional layer. - -def conv2d(x, fmaps, kernel, gain=np.sqrt(2), use_wscale=False): - assert kernel >= 1 and kernel % 2 == 1 - w = get_weight([kernel, kernel, x.shape[1].value, fmaps], gain=gain, use_wscale=use_wscale) - w = tf.cast(w, x.dtype) - return tf.nn.conv2d(x, w, strides=[1,1,1,1], padding='SAME', data_format='NCHW') - -#---------------------------------------------------------------------------- -# Apply bias to the given activation tensor. - -def apply_bias(x): - b = tf.get_variable('bias', shape=[x.shape[1]], initializer=tf.initializers.zeros()) - b = tf.cast(b, x.dtype) - if len(x.shape) == 2: - return x + b - return x + tf.reshape(b, [1, -1, 1, 1]) - -#---------------------------------------------------------------------------- -# Leaky ReLU activation. Same as tf.nn.leaky_relu, but supports FP16. - -def leaky_relu(x, alpha=0.2): - with tf.name_scope('LeakyRelu'): - alpha = tf.constant(alpha, dtype=x.dtype, name='alpha') - return tf.maximum(x * alpha, x) - -#---------------------------------------------------------------------------- -# Nearest-neighbor upscaling layer. - -def upscale2d(x, factor=2): - assert isinstance(factor, int) and factor >= 1 - if factor == 1: return x - with tf.variable_scope('Upscale2D'): - s = x.shape - x = tf.reshape(x, [-1, s[1], s[2], 1, s[3], 1]) - x = tf.tile(x, [1, 1, 1, factor, 1, factor]) - x = tf.reshape(x, [-1, s[1], s[2] * factor, s[3] * factor]) - return x - -#---------------------------------------------------------------------------- -# Fused upscale2d + conv2d. -# Faster and uses less memory than performing the operations separately. - -def upscale2d_conv2d(x, fmaps, kernel, gain=np.sqrt(2), use_wscale=False): - assert kernel >= 1 and kernel % 2 == 1 - w = get_weight([kernel, kernel, x.shape[1].value, fmaps], gain=gain, use_wscale=use_wscale) - w = tf.transpose(w, [0, 1, 3, 2]) # [kernel, kernel, fmaps_out, fmaps_in] - w = tf.pad(w, [[1,1], [1,1], [0,0], [0,0]], mode='CONSTANT') - w = tf.add_n([w[1:, 1:], w[:-1, 1:], w[1:, :-1], w[:-1, :-1]]) - w = tf.cast(w, x.dtype) - os = [tf.shape(x)[0], fmaps, x.shape[2] * 2, x.shape[3] * 2] - return tf.nn.conv2d_transpose(x, w, os, strides=[1,1,2,2], padding='SAME', data_format='NCHW') - -#---------------------------------------------------------------------------- -# Box filter downscaling layer. - -def downscale2d(x, factor=2): - assert isinstance(factor, int) and factor >= 1 - if factor == 1: return x - with tf.variable_scope('Downscale2D'): - ksize = [1, 1, factor, factor] - return tf.nn.avg_pool(x, ksize=ksize, strides=ksize, padding='VALID', data_format='NCHW') # NOTE: requires tf_config['graph_options.place_pruned_graph'] = True - -#---------------------------------------------------------------------------- -# Fused conv2d + downscale2d. -# Faster and uses less memory than performing the operations separately. - -def conv2d_downscale2d(x, fmaps, kernel, gain=np.sqrt(2), use_wscale=False): - assert kernel >= 1 and kernel % 2 == 1 - w = get_weight([kernel, kernel, x.shape[1].value, fmaps], gain=gain, use_wscale=use_wscale) - w = tf.pad(w, [[1,1], [1,1], [0,0], [0,0]], mode='CONSTANT') - w = tf.add_n([w[1:, 1:], w[:-1, 1:], w[1:, :-1], w[:-1, :-1]]) * 0.25 - w = tf.cast(w, x.dtype) - return tf.nn.conv2d(x, w, strides=[1,1,2,2], padding='SAME', data_format='NCHW') - -#---------------------------------------------------------------------------- -# Pixelwise feature vector normalization. - -def pixel_norm(x, epsilon=1e-8): - with tf.variable_scope('PixelNorm'): - return x * tf.rsqrt(tf.reduce_mean(tf.square(x), axis=1, keepdims=True) + epsilon) - -#---------------------------------------------------------------------------- -# Minibatch standard deviation. - -def minibatch_stddev_layer(x, group_size=4, num_new_features=1): - with tf.variable_scope('MinibatchStddev'): - group_size = tf.minimum(group_size, tf.shape(x)[0]) # Minibatch must be divisible by (or smaller than) group_size. - s = x.shape # [NCHW] Input shape. - y = tf.reshape(x, [group_size, -1, num_new_features, s[1]//num_new_features, s[2], s[3]]) # [GMncHW] Split minibatch into M groups of size G. Split channels into n channel groups c. - y = tf.cast(y, tf.float32) # [GMncHW] Cast to FP32. - y -= tf.reduce_mean(y, axis=0, keepdims=True) # [GMncHW] Subtract mean over group. - y = tf.reduce_mean(tf.square(y), axis=0) # [MncHW] Calc variance over group. - y = tf.sqrt(y + 1e-8) # [MncHW] Calc stddev over group. - y = tf.reduce_mean(y, axis=[2,3,4], keepdims=True) # [Mn111] Take average over fmaps and pixels. - y = tf.reduce_mean(y, axis=[2]) # [Mn11] Split channels into c channel groups - y = tf.cast(y, x.dtype) # [Mn11] Cast back to original data type. - y = tf.tile(y, [group_size, 1, s[2], s[3]]) # [NnHW] Replicate over group and pixels. - return tf.concat([x, y], axis=1) # [NCHW] Append as new fmap. - -#---------------------------------------------------------------------------- -# Networks used in the ProgressiveGAN paper. - -def G_paper( - latents_in, # First input: Latent vectors [minibatch, latent_size]. - labels_in, # Second input: Labels [minibatch, label_size]. - num_channels = 1, # Number of output color channels. Overridden based on dataset. - resolution = 32, # Output resolution. Overridden based on dataset. - label_size = 0, # Dimensionality of the labels, 0 if no labels. Overridden based on dataset. - fmap_base = 8192, # Overall multiplier for the number of feature maps. - fmap_decay = 1.0, # log2 feature map reduction when doubling the resolution. - fmap_max = 512, # Maximum number of feature maps in any layer. - latent_size = None, # Dimensionality of the latent vectors. None = min(fmap_base, fmap_max). - normalize_latents = True, # Normalize latent vectors before feeding them to the network? - use_wscale = True, # Enable equalized learning rate? - use_pixelnorm = True, # Enable pixelwise feature vector normalization? - pixelnorm_epsilon = 1e-8, # Constant epsilon for pixelwise feature vector normalization. - use_leakyrelu = True, # True = leaky ReLU, False = ReLU. - dtype = 'float32', # Data type to use for activations and outputs. - fused_scale = True, # True = use fused upscale2d + conv2d, False = separate upscale2d layers. - structure = None, # 'linear' = human-readable, 'recursive' = efficient, None = select automatically. - is_template_graph = False, # True = template graph constructed by the Network class, False = actual evaluation. - **_kwargs): # Ignore unrecognized keyword args. - - resolution_log2 = int(np.log2(resolution)) - assert resolution == 2**resolution_log2 and resolution >= 4 - def nf(stage): return min(int(fmap_base / (2.0 ** (stage * fmap_decay))), fmap_max) - def PN(x): return pixel_norm(x, epsilon=pixelnorm_epsilon) if use_pixelnorm else x - if latent_size is None: latent_size = nf(0) - if structure is None: structure = 'linear' if is_template_graph else 'recursive' - act = leaky_relu if use_leakyrelu else tf.nn.relu - - latents_in.set_shape([None, latent_size]) - labels_in.set_shape([None, label_size]) - combo_in = tf.cast(tf.concat([latents_in, labels_in], axis=1), dtype) - lod_in = tf.cast(tf.get_variable('lod', initializer=np.float32(0.0), trainable=False), dtype) - images_out = None - - # Building blocks. - def block(x, res): # res = 2..resolution_log2 - with tf.variable_scope('%dx%d' % (2**res, 2**res)): - if res == 2: # 4x4 - if normalize_latents: x = pixel_norm(x, epsilon=pixelnorm_epsilon) - with tf.variable_scope('Dense'): - x = dense(x, fmaps=nf(res-1)*16, gain=np.sqrt(2)/4, use_wscale=use_wscale) # override gain to match the original Theano implementation - x = tf.reshape(x, [-1, nf(res-1), 4, 4]) - x = PN(act(apply_bias(x))) - with tf.variable_scope('Conv'): - x = PN(act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=3, use_wscale=use_wscale)))) - else: # 8x8 and up - if fused_scale: - with tf.variable_scope('Conv0_up'): - x = PN(act(apply_bias(upscale2d_conv2d(x, fmaps=nf(res-1), kernel=3, use_wscale=use_wscale)))) - else: - x = upscale2d(x) - with tf.variable_scope('Conv0'): - x = PN(act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=3, use_wscale=use_wscale)))) - with tf.variable_scope('Conv1'): - x = PN(act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=3, use_wscale=use_wscale)))) - return x - def torgb(x, res): # res = 2..resolution_log2 - lod = resolution_log2 - res - with tf.variable_scope('ToRGB_lod%d' % lod): - return apply_bias(conv2d(x, fmaps=num_channels, kernel=1, gain=1, use_wscale=use_wscale)) - - # Linear structure: simple but inefficient. - if structure == 'linear': - x = block(combo_in, 2) - images_out = torgb(x, 2) - for res in range(3, resolution_log2 + 1): - lod = resolution_log2 - res - x = block(x, res) - img = torgb(x, res) - images_out = upscale2d(images_out) - with tf.variable_scope('Grow_lod%d' % lod): - images_out = lerp_clip(img, images_out, lod_in - lod) - - # Recursive structure: complex but efficient. - if structure == 'recursive': - def grow(x, res, lod): - y = block(x, res) - img = lambda: upscale2d(torgb(y, res), 2**lod) - if res > 2: img = cset(img, (lod_in > lod), lambda: upscale2d(lerp(torgb(y, res), upscale2d(torgb(x, res - 1)), lod_in - lod), 2**lod)) - if lod > 0: img = cset(img, (lod_in < lod), lambda: grow(y, res + 1, lod - 1)) - return img() - images_out = grow(combo_in, 2, resolution_log2 - 2) - - assert images_out.dtype == tf.as_dtype(dtype) - images_out = tf.identity(images_out, name='images_out') - return images_out - - -def D_paper( - images_in, # First input: Images [minibatch, channel, height, width]. - labels_in, # Second input: Labels [minibatch, label_size]. - num_channels = 1, # Number of input color channels. Overridden based on dataset. - resolution = 32, # Input resolution. Overridden based on dataset. - label_size = 0, # Dimensionality of the labels, 0 if no labels. Overridden based on dataset. - fmap_base = 8192, # Overall multiplier for the number of feature maps. - fmap_decay = 1.0, # log2 feature map reduction when doubling the resolution. - fmap_max = 512, # Maximum number of feature maps in any layer. - use_wscale = True, # Enable equalized learning rate? - mbstd_group_size = 4, # Group size for the minibatch standard deviation layer, 0 = disable. - dtype = 'float32', # Data type to use for activations and outputs. - fused_scale = True, # True = use fused conv2d + downscale2d, False = separate downscale2d layers. - structure = None, # 'linear' = human-readable, 'recursive' = efficient, None = select automatically - is_template_graph = False, # True = template graph constructed by the Network class, False = actual evaluation. - **_kwargs): # Ignore unrecognized keyword args. - - resolution_log2 = int(np.log2(resolution)) - assert resolution == 2**resolution_log2 and resolution >= 4 - def nf(stage): return min(int(fmap_base / (2.0 ** (stage * fmap_decay))), fmap_max) - if structure is None: structure = 'linear' if is_template_graph else 'recursive' - act = leaky_relu - - images_in.set_shape([None, num_channels, resolution, resolution]) - labels_in.set_shape([None, label_size]) - images_in = tf.cast(images_in, dtype) - labels_in = tf.cast(labels_in, dtype) - lod_in = tf.cast(tf.get_variable('lod', initializer=np.float32(0.0), trainable=False), dtype) - scores_out = None - - # Building blocks. - def fromrgb(x, res): # res = 2..resolution_log2 - with tf.variable_scope('FromRGB_lod%d' % (resolution_log2 - res)): - return act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=1, use_wscale=use_wscale))) - def block(x, res): # res = 2..resolution_log2 - with tf.variable_scope('%dx%d' % (2**res, 2**res)): - if res >= 3: # 8x8 and up - with tf.variable_scope('Conv0'): - x = act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=3, use_wscale=use_wscale))) - if fused_scale: - with tf.variable_scope('Conv1_down'): - x = act(apply_bias(conv2d_downscale2d(x, fmaps=nf(res-2), kernel=3, use_wscale=use_wscale))) - else: - with tf.variable_scope('Conv1'): - x = act(apply_bias(conv2d(x, fmaps=nf(res-2), kernel=3, use_wscale=use_wscale))) - x = downscale2d(x) - else: # 4x4 - if mbstd_group_size > 1: - x = minibatch_stddev_layer(x, mbstd_group_size) - with tf.variable_scope('Conv'): - x = act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=3, use_wscale=use_wscale))) - with tf.variable_scope('Dense0'): - x = act(apply_bias(dense(x, fmaps=nf(res-2), use_wscale=use_wscale))) - with tf.variable_scope('Dense1'): - x = apply_bias(dense(x, fmaps=1, gain=1, use_wscale=use_wscale)) - return x - - # Linear structure: simple but inefficient. - if structure == 'linear': - img = images_in - x = fromrgb(img, resolution_log2) - for res in range(resolution_log2, 2, -1): - lod = resolution_log2 - res - x = block(x, res) - img = downscale2d(img) - y = fromrgb(img, res - 1) - with tf.variable_scope('Grow_lod%d' % lod): - x = lerp_clip(x, y, lod_in - lod) - scores_out = block(x, 2) - - # Recursive structure: complex but efficient. - if structure == 'recursive': - def grow(res, lod): - x = lambda: fromrgb(downscale2d(images_in, 2**lod), res) - if lod > 0: x = cset(x, (lod_in < lod), lambda: grow(res + 1, lod - 1)) - x = block(x(), res); y = lambda: x - if res > 2: y = cset(y, (lod_in > lod), lambda: lerp(x, fromrgb(downscale2d(images_in, 2**(lod+1)), res - 1), lod_in - lod)) - return y() - scores_out = grow(2, resolution_log2 - 2) - - assert scores_out.dtype == tf.as_dtype(dtype) - scores_out = tf.identity(scores_out, name='scores_out') - return scores_out - -#---------------------------------------------------------------------------- diff --git a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download Bitcoin Blocks A Fun and Educational Game that Pays You in Crypto.md b/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download Bitcoin Blocks A Fun and Educational Game that Pays You in Crypto.md deleted file mode 100644 index 1e25321b57ab8cf28a03fd8815b8045cadf31cc8..0000000000000000000000000000000000000000 --- a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download Bitcoin Blocks A Fun and Educational Game that Pays You in Crypto.md +++ /dev/null @@ -1,118 +0,0 @@ - -

            How to Download Bitcoin Blocks and Why You Might Want to Do It

            -

            Bitcoin is a decentralized digital currency that operates on a peer-to-peer network of computers. The network records and validates all transactions in blocks, which are linked together to form a chain. This chain is called the blockchain, and it is the source of truth for the state of the Bitcoin system.

            -

            download bitcoin blocks


            Download ---> https://ssurll.com/2uNWxM



            -

            But how can you access this blockchain and download the blocks that contain the transaction history of Bitcoin? And why would you want to do that in the first place? In this article, we will explain what bitcoin blocks are, how they are created, how you can download them from the network, and what benefits you can get from doing so.

            -

            What are Bitcoin Blocks and How are They Created?

            -

            Bitcoin Blocks are Records of Transactions on the Bitcoin Network

            -

            A bitcoin block is a data structure that contains a set of transactions that occurred on the bitcoin network within a certain time period. Each block has a unique identifier called a block hash, which is derived from the data in the block. Each block also references the previous block in the chain by its hash, creating a link between them.

            -

            The first block in the chain is called the genesis block, and it was created by Satoshi Nakamoto, the anonymous creator of Bitcoin, in 2009. Since then, new blocks have been added to the chain every 10 minutes on average, making it grow longer over time. As of June 2021, there are over 690,000 blocks in the bitcoin blockchain, containing over 600 million transactions.

            -

            How to download bitcoin blocks from blockchain.info
            -Download bitcoin blocks in hex format
            -Download single and specific bitcoin block for study purposes
            -Download bitcoin blocks nightlies from tcatm
            -Download bitcoin blocks with bitcoind -rescan option
            -Download bitcoin blocks faster with bootstrap.dat
            -Download bitcoin blocks as CSV files
            -Download bitcoin blocks and verify proof of work
            -Download bitcoin blocks and parse block header
            -Download bitcoin blocks and analyze block data
            -Download bitcoin blocks and extract transactions
            -Download bitcoin blocks and convert to JSON
            -Download bitcoin blocks and visualize block structure
            -Download bitcoin blocks and calculate block hash
            -Download bitcoin blocks and compare block difficulty
            -Download bitcoin blocks and measure block size
            -Download bitcoin blocks and track block reward
            -Download bitcoin blocks and monitor block time
            -Download bitcoin blocks and explore block merkle tree
            -Download bitcoin blocks and decode block version
            -Download bitcoin blocks and check block validity
            -Download bitcoin blocks and store in local database
            -Download bitcoin blocks and sync with network
            -Download bitcoin blocks and compress block data
            -Download bitcoin blocks and encrypt block files
            -Download bitcoin blocks and backup block data
            -Download bitcoin blocks and restore block data
            -Download bitcoin blocks and update block data
            -Download bitcoin blocks and index block data
            -Download bitcoin blocks and search block data
            -Download bitcoin blocks and filter block data
            -Download bitcoin blocks and sort block data
            -Download bitcoin blocks and export block data
            -Download bitcoin blocks and import block data
            -Download bitcoin blocks and stream block data
            -Download bitcoin blocks and share block data
            -Download bitcoin blocks and access block API
            -Download bitcoin blocks and use block explorer
            -Download bitcoin blocks and create block graph
            -Download bitcoin blocks and generate block statistics
            -Download bitcoin blocks and learn block theory
            -Download bitcoin blocks and understand block consensus
            -Download bitcoin blocks and modify block code
            -Download bitcoin blocks and test block functionality
            -Download bitcoin blocks and debug block errors
            -Download bitcoin blocks and optimize block performance
            -Download bitcoin blocks and enhance block security
            -Download bitcoin blocks and improve block scalability
            -Download bitcoin blocks and support block development

            -

            Bitcoin Blocks are Generated by Miners Using Proof-of-Work

            -

            But how are new blocks created and added to the chain? This is done by a process called mining, which involves solving a mathematical puzzle that requires a lot of computational power. The puzzle is based on finding a nonce, which is a random number that makes the block hash start with a certain number of zeros. The difficulty of the puzzle adjusts every 2016 blocks, or about every two weeks, to maintain an average block time of 10 minutes.

            -

            The first miner who finds a valid nonce for a new block broadcasts it to the network, along with the transactions they have chosen to include in the block. The other miners then verify that the block is valid and add it to their version of the blockchain. The miner who created the block receives a reward of newly minted bitcoins (currently 6.25 bitcoins per block) plus any transaction fees paid by the users.

            -

            How to Download Bitcoin Blocks from the Bitcoin Network

            -

            You Need a Bitcoin Node Software to Connect to the Network and Sync the Blockchain

            -

            If you want to download bitcoin blocks from the network, you need to run a software that acts as a node, or a participant, in the network. A node communicates with other nodes using a protocol called Bitcoin P2P Protocol, which allows them to exchange information about transactions and blocks. A node can also relay transactions and blocks to other nodes, as well as validate them according to the consensus rules of Bitcoin.

            -

            There are different types of nodes that perform different functions on the network, such as full nodes, light nodes, mining nodes, etc. However, for downloading bitcoin blocks, you need a full node software, which stores and validates the entire blockchain locally. Some examples of full node software are Bitcoin Core (the original implementation of Bitcoin), Bitcoin Knots, Bitcoin Unlimited, etc. You can download and install a full node software from their official websites or GitHub repositories.

            -

            You Can Choose Between Full Nodes and Pruned Nodes Depending on Your Storage Space and Bandwidth

            -

            However, running a full node requires a lot of storage space and bandwidth, as you need to download and store the entire blockchain, which is currently over 350 GB in size. This can be a problem for some users who have limited resources or want to run a node on a mobile device or a low-end computer.

            -

            Fortunately, there is a solution for this: pruning. Pruning is a feature that allows you to delete old blocks that are no longer needed for validation, while keeping the most recent blocks and the block headers of all blocks. This way, you can reduce the storage space required for running a node, while still being able to verify transactions and blocks. Pruning can be enabled by setting the prune option in the configuration file of your node software. The minimum prune size is 550 MB, which means you can run a node with less than 1 GB of storage space. However, pruning also has some drawbacks, such as not being able to serve historical blocks to other nodes or not being able to rescan your wallet for transactions that occurred before the pruning point.

            -

            You Can Use Different Sources to Download Bitcoin Blocks Faster or More Securely

            -

            Another challenge that you might face when downloading bitcoin blocks is the speed and security of the process. Depending on your network connection and the availability of peers, it can take hours or even days to sync the blockchain from scratch. Moreover, you might encounter malicious nodes that try to feed you invalid or fake blocks, which can compromise your node's functionality or security.

            -

            To overcome these issues, you can use different sources to download bitcoin blocks faster or more securely. For example, you can use a bootstrap file, which is a compressed copy of the blockchain that you can download from a trusted source and then import into your node software. This can save you some time and bandwidth, as you don't have to download the blocks from the network. However, you still have to verify the blocks after importing them, which can take some CPU power and disk space. Moreover, you have to trust the source of the bootstrap file, as it might contain invalid or malicious blocks.

            -

            Another option is to use a torrent file, which is a peer-to-peer file sharing protocol that allows you to download files from multiple sources simultaneously. This can speed up the download process, as you can leverage the bandwidth of other users who have already downloaded the blockchain. However, you still have to verify the blocks after downloading them, and you might expose your IP address to other peers, which can affect your privacy.

            -

            A third option is to use a fast sync mode, which is a feature that some node software offer to sync the blockchain faster. This mode skips the verification of most blocks and only verifies the block headers and some randomly selected blocks. This can reduce the sync time significantly, as you don't have to check every transaction and block. However, this mode also reduces the security of your node, as you rely on the majority of miners to produce valid blocks and you don't check them yourself.

            -

            Why You Might Want to Download Bitcoin Blocks for Yourself

            -

            Downloading Bitcoin Blocks Allows You to Verify Transactions and Blocks Independently

            -

            One of the main reasons why you might want to download bitcoin blocks for yourself is to verify transactions and blocks independently. By doing so, you can ensure that no one is cheating or tampering with the Bitcoin system, such as by creating fake bitcoins or spending them twice. You can also check that the transactions that you send or receive are valid and confirmed by the network.

            -

            By verifying transactions and blocks independently, you are following the principle of "don't trust, verify", which is essential for maintaining the decentralization and security of Bitcoin. You are not relying on third parties, such as exchanges, wallets, or explorers, to tell you what is happening on the network. You are using your own node as a source of truth, which gives you more confidence and peace of mind.

            -

            Downloading Bitcoin Blocks Enables You to Run Your Own Services or Applications on Top of the Bitcoin Protocol

            -

            Another reason why you might want to download bitcoin blocks for yourself is to run your own services or applications on top of the Bitcoin protocol. By having access to the blockchain data locally, you can use it for various purposes, such as:

            -
              -
            • Running a block explorer: A block explorer is a website or an application that allows you to browse and search the blockchain for transactions, addresses, balances, etc. By running your own block explorer, you can have more privacy and control over your data.
            • -
            • Running a wallet: A wallet is a software that allows you to store, send, and receive bitcoins. By running your own wallet, you can have more security and control over your funds.
            • -
            • Running a node: A node is a software that participates in the Bitcoin network and validates transactions and blocks. By running your own node, you can support the network and contribute to its decentralization and resilience.
            • -
            • Running a lightning network node: The lightning network is a layer-2 solution that enables fast and cheap transactions on top of Bitcoin. By running your own lightning network node, you can use the lightning network to send and receive payments, as well as provide liquidity and routing services to other users.
            • -
            • Running a mining node: A mining node is a software that creates new blocks and competes for the block reward. By running your own mining node, you can earn bitcoins by securing the network and processing transactions.
            • -
            -

            These are just some examples of the services or applications that you can run on top of the Bitcoin protocol. There are many more possibilities, such as running smart contracts, decentralized exchanges, peer-to-peer marketplaces, etc. By downloading bitcoin blocks for yourself, you can unleash your creativity and innovation on the Bitcoin platform.

            -

            Downloading Bitcoin Blocks Gives You More Privacy and Control Over Your Bitcoin Transactions

            -

            A third reason why you might want to download bitcoin blocks for yourself is to have more privacy and control over your bitcoin transactions. By using your own node to broadcast and receive transactions, you can avoid exposing your IP address or other personal information to third parties, such as intermediaries or spy nodes. You can also use techniques such as Tor or VPN to further anonymize your network activity.

            -

            Moreover, by using your own node to verify transactions and blocks, you can avoid trusting or relying on third parties to confirm your transactions or provide you with accurate information. You can also choose which transactions or blocks you want to accept or reject, based on your own criteria or preferences. For example, you can choose to ignore transactions that pay low fees, or blocks that violate the consensus rules of Bitcoin.

            -

            By downloading bitcoin blocks for yourself, you can have more privacy and control over your bitcoin transactions, which can enhance your user experience and satisfaction.

            -

            Conclusion

            -

            Downloading bitcoin blocks is not a trivial task, as it requires a lot of resources and time. However, it also has a lot of benefits, such as verifying transactions and blocks independently, running your own services or applications on top of the Bitcoin protocol, and having more privacy and control over your bitcoin transactions.

            -

            If you are interested in downloading bitcoin blocks for yourself, you need to run a full node software that connects to the network and syncs the blockchain. You can choose between full nodes and pruned nodes depending on your storage space and bandwidth. You can also use different sources to download bitcoin blocks faster or more securely, such as bootstrap files, torrent files, or fast sync modes.

            -

            Downloading bitcoin blocks is a way of becoming more involved and informed in the Bitcoin system. It is also a way of supporting the network and contributing to its decentralization and security. If you are passionate about Bitcoin and want to learn more about it, downloading bitcoin blocks might be a rewarding experience for you.

            -

            FAQs

            -

            How long does it take to download bitcoin blocks?

            -

            The time it takes to download bitcoin blocks depends on several factors, such as your network speed, your node software, your hardware specifications, etc. However, a rough estimate is that it can take anywhere from a few hours to a few days to sync the blockchain from scratch.

            -

            How much storage space do I need to download bitcoin blocks?

            -

            The storage space you need to download bitcoin blocks depends on whether you run a full node or a pruned node. A full node requires over 350 GB of storage space as of June 2021, while a pruned node can run with less than 1 GB of storage space.

            -

            How can I check the progress of downloading bitcoin blocks?

            -

            You can check the progress of downloading bitcoin blocks by using the graphical user interface (GUI) or the command-line interface (CLI) of your node software. For example, if you use Bitcoin Core as your node software, you can check the progress by looking at the status bar in the GUI or by typing getblockchaininfo in the CLI.

            -

            What are some alternatives to downloading bitcoin blocks?

            -

            If you don't want to download bitcoin blocks for yourself, you can use some alternatives that provide you with access to the blockchain data without requiring you to store or validate it locally. Some examples are:

            -
              -
            • Using a light node: A light node is a software that only downloads the block headers and relies on other nodes to provide the full blocks or transactions. A light node is faster and lighter than a full node, but it also has less security and privacy, as it depends on third parties for verification and data.
            • -
            • Using a block explorer: A block explorer is a website or an application that allows you to browse and search the blockchain for transactions, addresses, balances, etc. A block explorer is convenient and easy to use, but it also has less security and privacy, as it exposes your IP address and your queries to the website operator and other parties.
            • -
            • Using an API: An API is an interface that allows you to access the blockchain data from a remote server or service. An API is flexible and powerful, but it also has less security and privacy, as it requires you to trust the provider of the API and their data.
            • -
            -

            What are some risks of downloading bitcoin blocks?

            -

            Downloading bitcoin blocks is generally safe and beneficial, but it also has some risks that you should be aware of. Some of them are:

            -
              -
            • Downloading malicious blocks: You might encounter nodes that try to feed you invalid or fake blocks, which can compromise your node's functionality or security. To avoid this, you should always verify the blocks that you download and use reputable sources or peers.
            • -
            • Downloading corrupted blocks: You might encounter errors or glitches that cause your blocks to be corrupted or incomplete, which can affect your node's performance or accuracy. To avoid this, you should always backup your blocks and use reliable hardware and software.
            • -
            • Downloading illegal blocks: You might encounter blocks that contain illegal or controversial data, such as child pornography, terrorist propaganda, etc. This can expose you to legal or ethical issues, depending on your jurisdiction and your moral stance. To avoid this, you should be careful about what blocks you download and use filters or blacklists if necessary.
            • -

            197e85843d
            -
            -
            \ No newline at end of file diff --git a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download LokiCraft Mod APK 1.09 - Full Version with Unlimited Blocks.md b/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download LokiCraft Mod APK 1.09 - Full Version with Unlimited Blocks.md deleted file mode 100644 index b26af40fd1036ab4d68065f85a54f1d131751747..0000000000000000000000000000000000000000 --- a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download LokiCraft Mod APK 1.09 - Full Version with Unlimited Blocks.md +++ /dev/null @@ -1,92 +0,0 @@ -
            -

            LokiCraft APK Mod: A Fun and Creative Sandbox Game

            -

            If you are a fan of sandbox games, you might have heard of LokiCraft, a popular game that lets you create your own world and explore endless possibilities. But did you know that you can also enjoy LokiCraft with some extra features and benefits by downloading the LokiCraft APK Mod? In this article, we will tell you everything you need to know about LokiCraft and its modded version, including what it is, how to play it, and how to download and install it on your device.

            -

            lokicraft apk mod


            Download »»» https://ssurll.com/2uNTpL



            -

            What is LokiCraft?

            -

            LokiCraft is a free sandbox game that is inspired by Minecraft, one of the most successful games of all time. In LokiCraft, you can build and destroy blocks, craft items, explore infinite worlds, and survive against enemies. You can also play in different modes, such as creative mode and survival mode, depending on your preference and mood. LokiCraft is a game that is suitable for all ages and can stimulate your creativity and imagination.

            -

            Features of LokiCraft

            -

            LokiCraft has many features that make it an enjoyable and addictive game. Here are some of them:

            -

            Explore infinite worlds

            -

            LokiCraft has randomly generated worlds that are infinite in size and diversity. You can explore different biomes, such as forests, deserts, mountains, oceans, and more. You can also find various resources, animals, plants, and structures in each world. You never know what you will discover next in LokiCraft.

            -

            Build anything you can imagine

            -

            LokiCraft gives you the freedom to build anything you can imagine with blocks. You can create houses, castles, bridges, towers, statues, gardens, and more. You can also use different materials, colors, and textures to customize your creations. You can express your personality and style through your buildings in LokiCraft.

            -

            lokicraft mod apk unlimited money
            -lokicraft mod apk download latest version
            -lokicraft mod apk free craft
            -lokicraft mod apk android 1
            -lokicraft mod apk no ads
            -lokicraft mod apk 2023
            -lokicraft mod apk happymod
            -lokicraft mod apk offline
            -lokicraft mod apk unlimited resources
            -lokicraft mod apk all unlocked
            -lokicraft mod apk revdl
            -lokicraft mod apk rexdl
            -lokicraft mod apk an1
            -lokicraft mod apk full version
            -lokicraft mod apk 1.09
            -lokicraft mod apk pure
            -lokicraft mod apk unlimited everything
            -lokicraft mod apk for pc
            -lokicraft mod apk god mode
            -lokicraft mod apk unlimited blocks
            -lokicraft mod apk latest update
            -lokicraft mod apk premium
            -lokicraft mod apk pro
            -lokicraft mod apk mega
            -lokicraft mod apk mediafıre
            -lokicraft mod apk vip
            -lokicraft mod apk hack
            -lokicraft mod apk cheat
            -lokicraft mod apk 1.08
            -lokicraft mod apk 1.07
            -lokicraft mod apk 1.06
            -lokicraft mod apk 1.05
            -lokicraft mod apk 1.04
            -lokicraft mod apk 1.03
            -lokicraft mod apk 1.02
            -lokicraft mod apk 1.01
            -lokicraft mod apk 1.0
            -lokicraft pro build and destroy blocks hack cheats unlimited resources generator no human verification 2023 android ios pc mac xbox ps4 online free download install play now working real legit official website link app game store google play store apple app store windows store steam store epic games store amazon appstore samsung galaxy store huawei appgallery xiaomi getapps oppo app market vivo app store oneplus store realme app market lg smartworld asus app store acer app store lenovo app store motorola app store sony app store nokia app store blackberry app store alcatel app store zte app store tcl app store meizu app store coolpad app store micromax app store lava app store karbonn app store panasonic app store gionee app store intex app store spice app store xolo app store swipe app store videocon app store lyf app store infocus app store celkon app store iball app store leeco app store yu televentures app store obi worldphone app store blu products app store verykool app store plum mobile app store unnecto app store posh mobile app store cat phones app store doogee mobile app store cubot mobile app store elephone mobile app store homtom mobile app store leagoo mobile app store oukitel mobile app store ulefone mobile app

            -

            Survive and fight against enemies

            -

            LokiCraft is not just about building and exploring. It is also about surviving and fighting against enemies. In survival mode, you have to gather resources, craft tools and weapons, and protect yourself from monsters, zombies, spiders, skeletons, and other hostile creatures. You also have to manage your hunger and health bars. You can also hunt animals for food or tame them as pets. You can also join or create multiplayer servers and play with other players online.

            -

            How to play LokiCraft

            -

            LokiCraft has two main modes that you can choose from: creative mode and survival mode. Here is how to play each mode:

            -

            Creative mode

            -

            Creative mode is the mode where you can unleash your creativity and build anything you want without any limitations or restrictions. You have access to unlimited blocks, items, resources, and tools. You can also fly around the world and place or remove blocks as you wish. You don't have to worry about enemies or hunger or health bars in creative mode. You can just focus on creating your own masterpiece.

            -

            Survival mode

            -

            Survival mode is the mode where you have to survive in a harsh environment with limited resources and dangers. You have to gather resources from the world, such as wood, stone, iron, coal, etc., and craft them into useful items, such as tools, weapons, armor, etc. You also have to build shelters to protect yourself from enemies that spawn at night or in dark places. You also have to manage your hunger and health bars by eating food and healing yourself. You can also explore the world and find dungeons, villages, temples, and other structures that may contain loot or enemies. Survival mode is more challenging and exciting than creative mode.

            -

            What is LokiCraft APK Mod?

            -

            LokiCraft APK Mod is a modified version of the original LokiCraft game that gives you some extra features and benefits that are not available in the official version. APK stands for Android Package Kit, which is a file format that allows you to install applications on your Android device. Mod means modification, which means that the APK file has been altered or hacked to provide you with some advantages or enhancements.

            -

            Benefits of LokiCraft APK Mod

            -

            LokiCraft APK Mod has many benefits that make it more enjoyable and convenient than the original game. Here are some of them:

            -

            Unlock all skins and textures

            -

            LokiCraft APK Mod allows you to unlock all the skins and textures that are normally locked or require in-app purchases in the official game. You can change the appearance of your character and the blocks in the game with different skins and textures. You can also access some exclusive skins and textures that are not available in the original game.

            -

            Remove ads and pop-ups

            -

            LokiCraft APK Mod removes all the annoying ads and pop-ups that interrupt your gameplay and ruin your experience. You can play the game without any distractions or interruptions. You can also save your data and battery by not loading any ads or pop-ups.

            -

            Enjoy unlimited resources and items

            -

            LokiCraft APK Mod gives you unlimited resources and items in both creative mode and survival mode. You don't have to gather or craft anything in the game. You can just use any resource or item you want without any limitations or restrictions. You can also use some rare or special items that are hard to find or obtain in the original game.

            -

            How to download and install LokiCraft APK Mod

            -

            If you want to download and install LokiCraft APK Mod on your device, you need to follow these simple steps:

            -

            Step 1: Download the APK file from a trusted source

            -

            You need to download the LokiCraft APK Mod file from a trusted source that provides safe and virus-free downloads. You can use this link to download the latest version of LokiCraft APK Mod for free.

            -

            Step 2: Enable unknown sources on your device

            -

            You need to enable unknown sources on your device to allow the installation of applications from sources other than the Google Play Store. To do this, go to Settings > Security > Unknown Sources and toggle it on.

            -

            Step 3: Install the APK file and launch the game

            -

            You need to locate the downloaded APK file on your device and tap on it to start the installation process. Follow the instructions on the screen and wait for the installation to complete. Once done, you can launch the game from your app drawer or home screen and enjoy LokiCraft APK Mod.

            -

            Conclusion

            -

            LokiCraft is a fun and creative sandbox game that lets you create your own world and explore endless possibilities. You can also enjoy LokiCraft with some extra features and benefits by downloading the LokiCraft APK Mod, which unlocks all skins and textures, removes ads and pop-ups, and gives you unlimited resources and items. You can download and install LokiCraft APK Mod by following the steps above. We hope you found this article helpful and informative. If you have any questions or feedback, please feel free to leave a comment below.

            -

            FAQs

            -

            Here are some frequently asked questions about LokiCraft APK Mod:

            -

            Is LokiCraft APK Mod safe to use?

            -

            LokiCraft APK Mod is safe to use as long as you download it from a trusted source that provides virus-free downloads. However, you should always be careful when installing applications from unknown sources, as they may contain malware or spyware that can harm your device or steal your personal information.

            -

            Is LokiCraft APK Mod legal?

            -

            LokiCraft APK Mod is not legal, as it violates the terms and conditions of the original game developer. By using LokiCraft APK Mod, you are infringing on their intellectual property rights and risking legal action from them. Therefore, we do not endorse or recommend using LokiCraft APK Mod, and we are not responsible for any consequences that may arise from using it.

            -

            Does LokiCraft APK Mod work on iOS devices?

            -

            No, LokiCraft APK Mod does not work on iOS devices, as it is only compatible with Android devices. If you want to play LokiCraft on your iOS device, you need to download the official version of LokiCraft from the App Store.

            -

            Can I play LokiCraft APK Mod online with other players?

            -

            Yes, you can play LokiCraft APK Mod online with other players who are also using the same modded version of the game. However, you may not be able to join or create servers that are running the original version of the game, as they may detect and ban you for using a modified version. You may also face some compatibility or stability issues when playing online with LokiCraft APK Mod.

            -

            Can I update LokiCraft APK Mod to the latest version?

            -

            No, you cannot update LokiCraft APK Mod to the latest version, as it is not supported by the original game developer. If you want to update LokiCraft to the latest version, you need to uninstall LokiCraft APK Mod and install the official version of LokiCraft from the Google Play Store. However, you may lose some of the features and benefits that LokiCraft APK Mod provides.

            197e85843d
            -
            -
            \ No newline at end of file diff --git a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download Messenger APK for Samsung J2 Prime and Chat with Friends.md b/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download Messenger APK for Samsung J2 Prime and Chat with Friends.md deleted file mode 100644 index e7ad4824a26b6e04f5ec3fc002a6abc2dd15ef99..0000000000000000000000000000000000000000 --- a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download Messenger APK for Samsung J2 Prime and Chat with Friends.md +++ /dev/null @@ -1,92 +0,0 @@ - -

            How to Download and Install Messenger APK for Samsung J2 Prime

            -

            If you are looking for a way to chat with your friends on Facebook without using the official app, you might want to try Messenger APK. This is a modified version of the original Facebook Messenger app that offers more features and customization options. In this article, we will show you how to download and install Messenger APK for Samsung J2 Prime, a popular Android smartphone.

            -

            messenger apk for samsung j2 prime


            Download Ziphttps://ssurll.com/2uNSMZ



            -

            What is Messenger APK and why do you need it?

            -

            Messenger APK is a modified version of the official Facebook Messenger app that allows you to send and receive text messages, voice messages, photos, videos, stickers, emojis, and more. You can also make free voice and video calls, create group chats, play games, and use various chatbots. Unlike the original app, Messenger APK does not require you to have a Facebook account or use the Facebook app. You can simply sign in with your phone number or use an existing Facebook account if you prefer.

            -

            Messenger APK offers more features and customization options than the original app

            -

            One of the main advantages of using Messenger APK is that it gives you more control over your messaging experience. You can customize the app's appearance, theme, font, color, notification sound, and more. You can also disable some features that you don't need or want, such as stories, ads, sponsored messages, etc. You can also access some hidden features that are not available in the official app, such as dark mode, secret conversations, chat heads, etc.

            -

            Messenger APK is compatible with Samsung J2 Prime and other Android devices

            -

            Another benefit of using Messenger APK is that it works well with Samsung J2 Prime and other Android devices. Samsung J2 Prime is a budget-friendly smartphone that runs on Android 6.0 Marshmallow. It has a 5-inch display, a quad-core processor, 1.5 GB of RAM, 8 GB of internal storage, an 8 MP rear camera, a 5 MP front camera, and a 2600 mAh battery. Messenger APK is designed to run smoothly on low-end devices like Samsung J2 Prime. It does not consume much battery or memory and does not slow down your device.

            -

            How to download Messenger APK for Samsung J2 Prime

            -

            Now that you know what Messenger APK is and why you might want to use it, let's see how you can download it for your Samsung J2 Prime. Here are the steps you need to follow:

            -

            messenger apk download for samsung j2 prime
            -how to install messenger on samsung j2 prime
            -messenger app for samsung j2 prime free download
            -messenger lite apk for samsung j2 prime
            -facebook messenger for samsung j2 prime latest version
            -messenger update for samsung j2 prime
            -messenger video call for samsung j2 prime
            -messenger dark mode apk for samsung j2 prime
            -messenger beta apk for samsung j2 prime
            -messenger mod apk for samsung j2 prime
            -messenger old version apk for samsung j2 prime
            -messenger plus apk for samsung j2 prime
            -messenger pro apk for samsung j2 prime
            -messenger transparent apk for samsung j2 prime
            -messenger new version 2023 apk for samsung j2 prime
            -messenger chat heads apk for samsung j2 prime
            -messenger stickers apk for samsung j2 prime
            -messenger themes apk for samsung j2 prime
            -messenger emoji apk for samsung j2 prime
            -messenger games apk for samsung j2 prime
            -messenger rooms apk for samsung j2 prime
            -messenger voice changer apk for samsung j2 prime
            -messenger lock apk for samsung j2 prime
            -messenger recovery apk for samsung j2 prime
            -messenger backup apk for samsung j2 prime
            -messenger spy apk for samsung j2 prime
            -messenger hack apk for samsung j2 prime
            -messenger clone apk for samsung j2 prime
            -messenger dual app apk for samsung j2 prime
            -messenger hidden chat apk for samsung j2 prime
            -messenger secret conversation apk for samsung j2 prime
            -messenger offline mode apk for samsung j2 prime
            -messenger status saver apk for samsung j2 prime
            -messenger story downloader apk for samsung j2 prime
            -messenger auto reply apk for samsung j2 prime
            -messenger scheduler apk for samsung j2 prime
            -messenger translator apk for samsung j2 prime
            -messenger notification sound changer apk for samsung j2 prime
            -messenger custom ringtone apk for samsung j2 prime
            -messenger color changer apk for samsung j2 prime
            -messenger font changer apk for samsung j2 prime
            -messenger wallpaper changer apk for samsung j2 prime
            -messenger bubble changer apk for samsung j2 prime
            -messenger icon changer apk for samsung j2 prime
            -messenger name changer apk for samsung j2 prime
            -best alternative to facebook messenger app on android 2023 - Samsung J7 Prime, J5 Prime, J3 Prime, J1 Prime, J7, J5, J3, J1, J7 Max, J7 Nxt, J7 Pro, J7 2023, J5 2023, J3 2023, J1 2023, J7 Prime 2023, J5 Prime 2023, J3 Prime 2023, J1 Prime 2023.

            -

            Find a reliable source for the Messenger APK file

            -

            The first thing you need to do is find a trustworthy website that offers the latest version of Messenger APK. You can use Google or any other search engine to look for "Messenger APK download" or "Messenger APK for Samsung J2 Prime". You will find many results, but not all of them are safe or reliable. Some websites may contain malware or viruses that can harm your device or steal your data. To avoid this risk, you should check the reviews and ratings of the website before downloading anything from it. You should also look for websites that have HTTPS in their URL, which means they are secure.

            -

            Check the compatibility and security of the file before downloading

            -

            The next thing you need to do is check the compatibility and security of the Messenger APK file before downloading it. You can do this by looking at the file details, such as the size, version, developer, date, etc. You should also scan the file with an antivirus or anti-malware app to make sure it is free from any harmful elements. You can use any app that you trust, such as Avast, AVG, Kaspersky, etc. If the file is compatible and secure, you can proceed to download it.

            -

            Enable unknown sources on your device settings

            -

            The third thing you need to do is enable unknown sources on your device settings. This is necessary because Messenger APK is not available on the Google Play Store or any other official app store. It is a third-party app that you are downloading from an unknown source. Therefore, you need to allow your device to install apps from sources other than the Play Store. To do this, you need to go to your device settings and look for the security or privacy option. There, you will find a toggle or checkbox for unknown sources. Turn it on and confirm your choice.

            -

            Download and save the file to your device storage

            -

            The final thing you need to do is download and save the file to your device storage. You can do this by tapping on the download link or button on the website where you found the Messenger APK file. You will see a pop-up window asking you where you want to save the file. Choose a location that is easy to access, such as your downloads folder or your SD card. Wait for the download to finish and check if the file is saved correctly.

            -

            How to install Messenger APK for Samsung J2 Prime

            -

            Now that you have downloaded the Messenger APK file for your Samsung J2 Prime, you are ready to install it and use it. Here are the steps you need to follow:

            -

            Locate the downloaded file and tap on it to start the installation

            -

            The first thing you need to do is locate the downloaded file and tap on it to start the installation process. You can use a file manager app or your device's built-in file explorer to find the file. It should be in the location that you chose when you downloaded it. Once you find it, tap on it and you will see a prompt asking you if you want to install this application. Tap on install and proceed.

            -

            Follow the instructions on the screen and grant the necessary permissions

            -

            The next thing you need to do is follow the instructions on the screen and grant the necessary permissions for the app to work properly. You will see a list of permissions that the app requires, such as access to your contacts, camera, microphone, storage, etc. You can review them and decide if you want to allow them or not. If you trust the app and its developer, you can grant all the permissions. If not, you can deny some or all of them. However, keep in mind that denying some permissions may affect the functionality of the app.

            -

            Wait for the installation to complete and launch the app

            -

            The final thing you need to do is wait for the installation to complete and launch the app. You will see a progress bar showing you how much time is left until the installation is done. When it is finished, you will see a message saying that the app is installed. You can then tap on open to launch the app or tap on done to exit the installer. You can also find the app icon on your home screen or app drawer and tap on it to open it.

            -

            Conclusion

            -

            Messenger APK is a great alternative to the official Facebook Messenger app if you want more features and customization options. It is compatible with Samsung J2 Prime and other Android devices and does not require a Facebook account to use it. You can download and install Messenger APK for Samsung J2 Prime by following the steps we have outlined in this article. However, you should be careful about the source and security of the file and the permissions you grant to the app. We hope this article was helpful and informative for you. If you have any questions or feedback, please let us know in the comments below.

            -

            FAQs

            -

            Here are some frequently asked questions about Messenger APK for Samsung J2 Prime:

            -
              -
            • Is Messenger APK safe to use?
            • -

              Messenger APK is generally safe to use if you download it from a reliable source and scan it with an antivirus app before installing it. However, you should be aware that it is not an official app and it may have some bugs or glitches that can affect your device or data. You should also be careful about the permissions you grant to the app and the messages you send or receive through it.

              -
            • Is Messenger APK legal to use?
            • -

              Messenger APK is not illegal to use, but it may violate some terms and conditions of Facebook or Google. This means that you may face some risks or consequences if you use it, such as account suspension, data loss, or legal action. You should use Messenger APK at your own discretion and responsibility.

              -
            • How can I update Messenger APK?
            • -

              Messenger APK does not have an automatic update feature, so you need to manually check for updates and download them from the same source where you got the app. You should also uninstall the previous version of the app before installing the new one to avoid any conflicts or errors.

              -
            • How can I uninstall Messenger APK?
            • -

              You can uninstall Messenger APK like any other app on your device. You can go to your device settings and look for the apps or applications option. There, you will find a list of all the apps installed on your device. You can tap on Messenger APK and then tap on uninstall. You can also long-press on the app icon on your home screen or app drawer and drag it to the uninstall option.

              -
            • What are some alternatives to Messenger APK?
            • -

              If you are not satisfied with Messenger APK or want to try something else, there are many other messaging apps that you can use on your Samsung J2 Prime or other Android devices. Some of them are WhatsApp, Telegram, Signal, Viber, Line, etc. They all have their own features and advantages that you can compare and choose from.

              -

            401be4b1e0
            -
            -
            \ No newline at end of file diff --git a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download and Play World Bus Simulator Ultimate Mod APK - No Ads No Limits No Worries.md b/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download and Play World Bus Simulator Ultimate Mod APK - No Ads No Limits No Worries.md deleted file mode 100644 index 1158a7c09ff97ab5382a11c2c6703d9ec6a214de..0000000000000000000000000000000000000000 --- a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download and Play World Bus Simulator Ultimate Mod APK - No Ads No Limits No Worries.md +++ /dev/null @@ -1,105 +0,0 @@ - -

            World Bus Simulator Ultimate Mod APK: A Realistic and Fun Driving Experience

            -

            Do you love driving buses and exploring different cities? Do you want to experience the thrill of being a bus driver and managing your own company? If yes, then you should try World Bus Simulator Ultimate, a popular simulation game that lets you drive various buses across the world. And if you want to make the game even more fun and exciting, you should download World Bus Simulator Ultimate Mod APK, a modified version of the game that gives you unlimited money, resources, and features. In this article, we will tell you everything you need to know about World Bus Simulator Ultimate and its mod apk, including what it is, what are its features, why you should download it, and how to download and install it.

            -

            What is World Bus Simulator Ultimate?

            -

            World Bus Simulator Ultimate is a realistic and immersive bus driving game that lets you experience the life of a bus driver. You can choose from different types of buses, such as city buses, school buses, double-decker buses, and more, and drive them on various maps, such as Europe, USA, Brazil, Turkey, and more. You can also customize your buses with different colors, stickers, accessories, and upgrades. You can create your own routes and schedules, pick up and drop off passengers, follow traffic rules, deal with different weather conditions, and earn money and reputation. You can also create your own bus company and hire other drivers to work for you. You can compete with other players online and rank on the leaderboards. You can also interact with your passengers and get feedback from them.

            -

            world bus simulator ultimate mod apk


            DOWNLOAD ⚹⚹⚹ https://ssurll.com/2uNZFF



            -

            Features of World Bus Simulator Ultimate

            -

            - Realistic bus physics and graphics

            -

            World Bus Simulator Ultimate has realistic bus physics that make you feel like you are driving a real bus. You can control the steering wheel, pedals, gears, indicators, lights, horn, doors, windows, mirrors, and more. You can also see the interior and exterior of your bus in high-quality graphics. You can enjoy the scenery of different cities and landscapes as you drive.

            -

            - Multiple game modes and maps

            -

            World Bus Simulator Ultimate has multiple game modes that suit your preferences and skills. You can play in career mode, where you have to complete missions and objectives to earn money and reputation. You can play in free mode, where you can drive freely without any restrictions. You can play in multiplayer mode, where you can join or create online rooms and play with other players. You can also play in sandbox mode, where you can create your own maps and scenarios. You can choose from different maps that represent different countries and regions, such as Europe, USA, Brazil, Turkey, and more.

            -

            - Customizable buses and routes

            -

            World Bus Simulator Ultimate has a variety of buses that you can choose from. You can drive city buses, school buses, double-decker buses, articulated buses, minibuses, coaches, and more. You can also customize your buses with different colors, stickers, accessories, and upgrades. You can improve the performance of your buses by upgrading the engine, transmission, brakes, suspension, tires, fuel tank capacity etc. You can also create your own routes by selecting the starting point , destination point , stops , time , distance , fare , etc.

            -

            - Online multiplayer and leaderboards

            -

            World Bus Simulator Ultimate has an online multiplayer feature that lets you play with other players from around the world. You can join or create online rooms and chat with other players. You can also see the location and status of other players on the map. You can cooperate or compete with other players and rank on the leaderboards. You can also invite your friends to play with you and create your own private rooms.

            -

            - Passenger interactions and feedback

            -

            World Bus Simulator Ultimate has realistic passenger interactions that make you feel like you are dealing with real people. You can see the passengers boarding and leaving your bus, sitting on the seats, talking to each other, using their phones, etc. You can also hear their voices and comments. You can interact with your passengers by using the microphone, announcing the stops, greeting them, apologizing for delays, etc. You can also get feedback from your passengers based on your driving skills, punctuality, comfort, etc.

            -

            Why download World Bus Simulator Ultimate Mod APK?

            -

            World Bus Simulator Ultimate is a fun and addictive game that will keep you entertained for hours. However, it also has some limitations and drawbacks that may affect your gaming experience. For example, you may have to watch ads to get extra money or resources. You may have to spend real money to buy some buses or maps. You may have to wait for a long time to unlock some features or levels. You may also encounter some bugs or glitches that may ruin your gameplay.

            -

            That's why you should download World Bus Simulator Ultimate Mod APK, a modified version of the game that gives you unlimited money, resources, and features. With World Bus Simulator Ultimate Mod APK, you can enjoy the game without any restrictions or interruptions. Here are some of the benefits of World Bus Simulator Ultimate Mod APK:

            -

            world bus simulator ultimate mod apk unlimited money
            -world bus simulator ultimate mod apk download for android
            -world bus simulator ultimate mod apk latest version
            -world bus simulator ultimate mod apk free shopping
            -world bus simulator ultimate mod apk no ads
            -world bus simulator ultimate mod apk offline
            -world bus simulator ultimate mod apk hack
            -world bus simulator ultimate mod apk revdl
            -world bus simulator ultimate mod apk rexdl
            -world bus simulator ultimate mod apk 2.0.9
            -world bus simulator ultimate mod apk 2023
            -world bus simulator ultimate mod apk android 1
            -world bus simulator ultimate mod apk obb
            -world bus simulator ultimate mod apk unlimited everything
            -world bus simulator ultimate mod apk all unlocked
            -world bus simulator ultimate mod apk data
            -world bus simulator ultimate mod apk pure
            -world bus simulator ultimate mod apk happymod
            -world bus simulator ultimate mod apk an1
            -world bus simulator ultimate mod apk vip
            -world bus simulator ultimate mod apk premium
            -world bus simulator ultimate mod apk pro
            -world bus simulator ultimate mod apk full version
            -world bus simulator ultimate mod apk mega
            -world bus simulator ultimate mod apk new update
            -world bus simulator ultimate mod apk online
            -world bus simulator ultimate mod apk original
            -world bus simulator ultimate mod apk old version
            -world bus simulator ultimate mod apk unlimited coins
            -world bus simulator ultimate mod apk unlimited gems
            -world bus simulator ultimate mod apk unlimited fuel
            -world bus simulator ultimate mod apk unlocked skins
            -world bus simulator ultimate mod apk unlocked buses
            -world bus simulator ultimate mod apk unlocked routes
            -world bus simulator ultimate mod apk unlocked countries
            -world bus simulator ultimate mod apk unlimited xp
            -world bus simulator ultimate mod apk unlimited tickets
            -world bus simulator ultimate mod apk unlimited gold
            -world bus simulator ultimate mod apk unlimited diamonds
            -world bus simulator ultimate mod apk high graphics
            -world bus simulator ultimate mod apk low mb
            -world bus simulator ultimate mod apk cheat menu
            -world bus simulator ultimate mod apk god mode
            -world bus simulator ultimate mod apk easy win
            -world bus simulator ultimate mod apk realistic physics
            -world bus simulator ultimate mod apk multiplayer mode
            -world bus simulator ultimate mod apk career mode
            -world bus simulator ultimate mod apk sandbox mode

            -

            Benefits of World Bus Simulator Ultimate Mod APK

            -

            - Unlimited money and resources

            -

            With World Bus Simulator Ultimate Mod APK, you will get unlimited money and resources that you can use to buy and upgrade anything you want in the game. You don't have to watch ads or spend real money to get more money or resources. You can buy any bus, map, accessory, upgrade, etc. that you like. You can also create as many routes and schedules as you want. You can also hire as many drivers as you want for your company.

            -

            - No ads and interruptions

            -

            With World Bus Simulator Ultimate Mod APK, you will not see any ads or pop-ups that may annoy you or distract you from your gameplay. You don't have to watch ads to get extra money or resources. You don't have to wait for ads to load or skip them. You can enjoy the game without any interruptions or delays.

            -

            - All buses and maps unlocked

            -

            With World Bus Simulator Ultimate Mod APK, you will get access to all the buses and maps that are available in the game. You don't have to wait for a long time to unlock them or complete certain missions or objectives to get them. You can choose from any bus or map that you like and drive them on any route that you want.

            -

            - Free and easy to install

            -

            World Bus Simulator Ultimate Mod APK is free and easy to install on your device. You don't need to root your device or use any complicated tools or methods to install it. You just need to follow some simple steps that we will explain later in this article.

            -

            How to download and install World Bus Simulator Ultimate Mod APK?

            -

            If you are interested in downloading and installing World Bus Simulator Ultimate Mod APK on your device, you just need to follow these simple steps:

            -

            Step-by-step guide for downloading and installing World Bus Simulator Ultimate Mod APK

            -
              -
            1. Click on this link to download the World Bus Simulator Ultimate Mod APK file on your device.
            2. -
            3. Go to your device settings and enable the option "Unknown sources" to allow the installation of apps from unknown sources.
            4. -
            5. Locate the downloaded file in your device storage and tap on it to start the installation process.
            6. -
            7. Follow the instructions on the screen and wait for the installation to finish.
            8. -
            9. Launch the game and enjoy!
            10. -
            -

            Conclusion

            -

            World Bus Simulator Ultimate is a realistic and fun bus driving game that lets you experience the life of a bus driver. You can drive various buses across different maps, customize your buses and routes, create your own company, play with other players online, interact with your passengers, and more. However, if you want to make the game even more fun and exciting, you should download World Bus Simulator Ultimate Mod APK, a modified version of the game that gives you unlimited money, resources, and features. With World Bus Simulator Ultimate Mod APK, you can enjoy the game without any restrictions or interruptions. You can buy and upgrade anything you want, you can play without ads, you can access all the buses and maps, and you can install it for free and easily. World Bus Simulator Ultimate Mod APK is the best way to enjoy the game to the fullest. So, what are you waiting for? Download it now and start your bus driving adventure!

            -

            If you have any questions or doubts about World Bus Simulator Ultimate or its mod apk, you can check out these FAQs that we have prepared for you:

            -

            FAQs

            -
              -
            • Q: Is World Bus Simulator Ultimate Mod APK safe to use?
            • -
            • A: Yes, World Bus Simulator Ultimate Mod APK is safe to use. It does not contain any viruses, malware, or spyware that may harm your device or data. It is also compatible with most Android devices and versions.
            • -
            • Q: Do I need an internet connection to play World Bus Simulator Ultimate Mod APK?
            • -
            • A: No, you do not need an internet connection to play World Bus Simulator Ultimate Mod APK. You can play it offline without any problems. However, if you want to play online multiplayer mode, you will need an internet connection.
            • -
            • Q: Will I get banned from the game if I use World Bus Simulator Ultimate Mod APK?
            • -
            • A: No, you will not get banned from the game if you use World Bus Simulator Ultimate Mod APK. The mod apk is undetectable by the game servers and does not affect your account or progress. You can play the game normally without any worries.
            • -
            • Q: How can I update World Bus Simulator Ultimate Mod APK?
            • -
            • A: To update World Bus Simulator Ultimate Mod APK, you just need to follow the same steps that you followed to download and install it. You can check this link for the latest version of the mod apk and download it on your device. Then, you can install it over the existing version without losing your data or settings.
            • -
            • Q: How can I contact the developers of World Bus Simulator Ultimate or its mod apk?
            • -
            • A: If you have any feedback, suggestions, complaints, or queries about World Bus Simulator Ultimate or its mod apk, you can contact the developers through their official website or their social media accounts . They will be happy to hear from you and assist you with your issues.
            • -

            197e85843d
            -
            -
            \ No newline at end of file diff --git a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Enjoy Fun and Competitive Multiplayer Games with 2 Jugadores APK.md b/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Enjoy Fun and Competitive Multiplayer Games with 2 Jugadores APK.md deleted file mode 100644 index 644d4582529ea741fa1d7d705a9faae259e05910..0000000000000000000000000000000000000000 --- a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Enjoy Fun and Competitive Multiplayer Games with 2 Jugadores APK.md +++ /dev/null @@ -1,170 +0,0 @@ -
            -

            2 jugadores apk: los mejores juegos para disfrutar con tus amigos

            -

            ¿Te gusta jugar con tus amigos en el mismo dispositivo? ¿Quieres divertirte con juegos sencillos pero adictivos que te mantengan entretenido durante horas? Entonces, los juegos de 2 jugadores apk son lo que estás buscando. Estos son juegos que puedes descargar e instalar en tu teléfono o tableta Android, y que te permiten jugar con una, dos, tres o más personas en el mismo dispositivo. Hay juegos de todo tipo: carreras, peleas, deportes, puzzles, estrategia, etc. Solo tienes que elegir el que más te guste y retar a tus amigos a ver quién es el mejor. En este artículo, te vamos a explicar qué son los juegos de 2 jugadores apk, cómo descargarlos e instalarlos, y cuáles son los mejores que puedes encontrar en la actualidad. ¡Sigue leyendo y prepárate para la diversión!

            -

            2 jugadores apk


            Download Filehttps://ssurll.com/2uNTnd



            -

            ¿Qué son los juegos de 2 jugadores apk?

            -

            Los juegos de 2 jugadores apk son juegos que se pueden jugar por dos o más personas en el mismo dispositivo Android. APK es el formato de archivo que se usa para instalar aplicaciones y juegos en este sistema operativo. Los juegos de 2 jugadores apk se pueden descargar desde diferentes fuentes, como Google Play, APKPure o APKCombo. Estos juegos suelen tener reglas simples y fáciles de entender, y se pueden jugar con los dedos, tocando la pantalla, o con botones virtuales. Algunos también tienen la opción de jugar online o offline, con otros jugadores alrededor del mundo o sin conexión a internet.

            -

            Características de los juegos de 2 jugadores apk

            -

            Los juegos de 2 jugadores apk tienen algunas características comunes que los hacen muy atractivos para los usuarios. Algunas de estas características son:

            -
              -
            • Son gratuitos o tienen un precio muy bajo.
            • -
            • No requieren mucho espacio de almacenamiento ni recursos del dispositivo.
            • -
            • Son compatibles con la mayoría de los modelos y marcas de teléfonos y tabletas Android.
            • -
            • Tienen gráficos coloridos y sonidos divertidos.
            • -
            • Son variados y ofrecen diferentes géneros y temáticas.
            • -
            • Son fáciles de jugar y aprender.
            • -
            • Son ideales para pasar el rato con amigos o familiares.
            • -
            -

            Ventajas de los juegos de 2 jugadores apk

            -

            Los juegos de 2 jugadores apk también

            tienen muchas ventajas que los hacen muy populares entre los usuarios. Algunas de estas ventajas son:

            -
              -
            • Promueven la interacción social y el compañerismo.
            • -
            • Estimulan la competencia sana y el desafío personal.
            • -
            • Desarrollan habilidades cognitivas, como la memoria, la atención, la lógica y la estrategia.
            • -
            • Mejoran la coordinación motora, la destreza y los reflejos.
            • -
            • Proporcionan entretenimiento y diversión sin límites.
            • -
            -

            Desventajas de los juegos de 2 jugadores apk

            -

            Por otro lado, los juegos de 2 jugadores apk también tienen algunas desventajas que hay que tener en cuenta. Algunas de estas desventajas son:

            -
              -
            • Pueden generar adicción y dependencia si se abusa de ellos.
            • -
            • Pueden provocar conflictos y discusiones si no se respeta el juego limpio y las normas de convivencia.
            • -
            • Pueden afectar negativamente al rendimiento académico o laboral si se descuida el tiempo dedicado a otras actividades.
            • -
            • Pueden causar problemas de salud, como fatiga visual, dolor de cabeza, estrés o insomnio si no se juega con moderación y precaución.
            • -
            • Pueden contener publicidad o compras integradas que pueden resultar molestas o costosas.
            • -
            -

            ¿Cómo descargar e instalar los juegos de 2 jugadores apk?

            -

            Si quieres disfrutar de los juegos de 2 jugadores apk, lo primero que tienes que hacer es descargarlos e instalarlos en tu dispositivo Android. Para ello, debes seguir estos pasos:

            -

            Juegos de dos jugadores - 2 apk
            -12 Minijuegos - 2 Jugadores apk
            -2 Jugadores-Reboun apk
            -Juegos de 2 jugadores en el mismo teléfono apk
            -44 Minijuegos para 2 jugadores apk
            -2 Jugadores-Tanques apk
            -Juegos de mesa para 2 jugadores apk
            -2 Jugadores-Basketball apk
            -Juegos de carreras para 2 jugadores apk
            -2 Jugadores-Futbolín apk
            -Juegos de peleas para 2 jugadores apk
            -2 Jugadores-Ping Pong apk
            -Juegos de aventuras para 2 jugadores apk
            -2 Jugadores-Ajedrez apk
            -Juegos de estrategia para 2 jugadores apk
            -2 Jugadores-Damas apk
            -Juegos de habilidad para 2 jugadores apk
            -2 Jugadores-Golf apk
            -Juegos de puzzles para 2 jugadores apk
            -2 Jugadores-Billar apk
            -Juegos de acción para 2 jugadores apk
            -2 Jugadores-Badminton apk
            -Juegos de deportes para 2 jugadores apk
            -2 Jugadores-Volleyball apk
            -Juegos de arcade para 2 jugadores apk
            -2 Jugadores-Tiro con arco apk
            -Juegos de simulación para 2 jugadores apk
            -2 Jugadores-Carrusel apk
            -Juegos de terror para 2 jugadores apk
            -2 Jugadores-Zombies apk
            -Juegos de música para 2 jugadores apk
            -2 Jugadores-Piano Tiles apk
            -Juegos de trivia para 2 jugadores apk
            -2 Jugadores-Quién quiere ser millonario apk
            -Juegos de palabras para 2 jugadores apk
            -2 Jugadores-Ahorcado apk
            -Juegos de memoria para 2 jugadores apk
            -2 Jugadores-Memorama apk
            -Juegos de dibujo para 2 jugadores apk
            -2 Jugadores-Pintar y adivinar apk
            -Juegos de cocina para 2 jugadores apk
            -2 Jugadores-Pizza Master apk
            -Juegos de moda para 2 jugadores apk
            -2 Jugadores-Diseñar vestidos apk
            -Juegos de animales para 2 jugadores apk
            -2 Jugadores-Cuidar mascotas apk
            -Juegos de educación para 2 jugadores apk
            -2 Jugadores-Aprender inglés apk
            -Juegos de magia para 2 jugadores apk

            -

            Requisitos mínimos para jugar a los juegos de 2 jugadores apk

            -

            Antes de descargar e instalar los juegos de 2 jugadores apk, debes asegurarte de que tu dispositivo cumple con los requisitos mínimos para poder ejecutarlos correctamente. Estos requisitos pueden variar según el juego, pero en general se recomienda tener:

            -
              -
            • Un sistema operativo Android 4.4 o superior.
            • -
            • Una memoria RAM de al menos 1 GB.
            • -
            • Un espacio de almacenamiento libre de al menos 100 MB.
            • -
            • Una conexión a internet estable y segura.
            • -
            -

            Pasos para descargar e instalar los juegos de 2 jugadores apk

            -

            Una vez que hayas comprobado que tu dispositivo cumple con los requisitos mínimos, puedes proceder a descargar e instalar los juegos de 2 jugadores apk siguiendo estos pasos:

            -
              -
            1. Elige el juego que quieres descargar desde alguna fuente confiable, como Google Play, APKPure o APKCombo. Puedes buscar el nombre del juego en el buscador o navegar por las categorías y rankings disponibles.
            2. -
            3. Pulsa sobre el botón de descargar o instalar y espera a que se complete la descarga del archivo APK en tu dispositivo. El archivo APK es el formato que contiene la aplicación o el juego que quieres instalar.
            4. -
            5. Abre el archivo APK desde tu gestor de archivos o desde la barra de notificaciones. Si te aparece un mensaje de advertencia sobre la instalación de aplicaciones desconocidas, debes habilitar la opción de permitir fuentes desconocidas desde los ajustes de seguridad de tu dispositivo.
            6. -
            7. Sigue las instrucciones que te indique el instalador y acepta los permisos que te solicite el juego. Espera a que se complete la instalación y pulsa sobre el icono del juego para abrirlo y empezar a jugar.
            8. -

            Recomendaciones para jugar a los juegos de 2 jugadores apk

            -

            Para que tu experiencia con los juegos de 2 jugadores apk sea lo más satisfactoria posible, te recomendamos que sigas estas recomendaciones:

            -
              -
            • Elige el juego que más se adapte a tus gustos y preferencias. Hay juegos de todo tipo y para todos los públicos, así que seguro que encuentras el que más te divierta.
            • -
            • Juega con personas que conozcas y que tengan un nivel similar al tuyo. Así evitarás frustraciones o aburrimiento por la diferencia de habilidad o interés.
            • -
            • Respeta las reglas del juego y el fair play. No hagas trampas, no insultes ni molestes a tu rival, y reconoce su victoria o derrota con deportividad.
            • -
            • No juegues durante mucho tiempo seguido ni en condiciones inadecuadas. Haz pausas cada cierto tiempo, descansa la vista, hidrátate y juega en un lugar cómodo y bien iluminado.
            • -
            • Disfruta del juego y diviértete. No te tomes el juego demasiado en serio ni te obsesiones con ganar o perder. Lo importante es pasar un buen rato con tus amigos.
            • -
            -

            ¿Cuáles son los mejores juegos de 2 jugadores apk?

            -

            Ahora que ya sabes qué son los juegos de 2 jugadores apk, cómo descargarlos e instalarlos, y qué recomendaciones seguir para jugarlos, te preguntarás cuáles son los mejores juegos de este tipo que puedes encontrar en la actualidad. Pues bien, hay muchos juegos de 2 jugadores apk que merecen la pena, pero nosotros hemos seleccionado tres que nos parecen especialmente divertidos y entretenidos. Estos son:

            -

            Juegos de dos jugadores - 2

            -

            Descripción del juego

            -

            Juegos de dos jugadores - 2 es una colección de juegos de 2 jugadores apk que incluye 24 mini juegos diferentes. Estos juegos son de varios géneros, como acción, deportes, carreras, puzzles, etc. Algunos ejemplos son: boxeo, fútbol, ping pong, ajedrez, damas, tanques, aviones, etc. Este juego es ideal para jugar con tus amigos en cualquier momento y lugar, ya que solo necesitas un dispositivo Android y ganas de divertirte.

            -

            Modos de juego y características principales

            -

            Juegos de dos jugadores - 2 tiene dos modos de juego: uno para jugar con otro jugador en el mismo dispositivo, y otro para jugar solo contra la inteligencia artificial. Cada mini juego tiene sus propias reglas y objetivos, que se explican antes de empezar a jugar. Algunas de las características principales de este juego son:

            -
              -
            • Tiene gráficos sencillos pero bonitos y coloridos.
            • -
            • Tiene controles fáciles e intuitivos.
            • -
            • Tiene sonidos divertidos y música agradable.
            • -
            • Tiene una gran variedad de juegos para todos los gustos.
            • -
            • Tiene un tamaño pequeño y no consume mucha batería.
            • -

            Opiniones de los usuarios y valoración del juego

            -

            Juegos de dos jugadores - 2 tiene una valoración de 4.1 sobre 5 en Google Play, con más de 10 millones de descargas y más de 100 mil comentarios. La mayoría de los usuarios opinan que este juego es muy divertido y adictivo, y que tiene una gran variedad de juegos para elegir. Algunas de las opiniones más destacadas son:

            -
            -

            "Me encanta este juego, es muy entretenido y divertido, se lo recomiendo a todos los que quieran pasar un buen rato con sus amigos o familiares."

            -

            "Es un juego muy bueno, tiene muchos juegos diferentes y se puede jugar con otra persona en el mismo celular, es muy bueno para jugar cuando estás aburrido."

            -

            "Es un juego muy completo, tiene muchos mini juegos y son muy divertidos, además no ocupa mucho espacio ni consume mucha batería, lo recomiendo mucho."

            -
            -

            Juegos de 2 jugadores

            -

            Descripción del juego

            -

            Juegos de 2 jugadores es otro juego de 2 jugadores apk que también ofrece una colección de mini juegos para jugar con tus amigos. Este juego tiene 18 mini juegos diferentes, que van desde carreras de coches, peleas de robots, batallas de tanques, hasta juegos de mesa, como el tres en raya o el cuatro en línea. Este juego es perfecto para pasar el rato con tus amigos y demostrar quién es el mejor en cada juego.

            -

            Modos de juego y características principales

            -

            Juegos de 2 jugadores también tiene dos modos de juego: uno para jugar con otro jugador en el mismo dispositivo, y otro para jugar solo contra la inteligencia artificial. Cada mini juego tiene sus propias reglas y objetivos, que se muestran antes de empezar a jugar. Algunas de las características principales de este juego son:

            -
              -
            • Tiene gráficos simples pero atractivos y animados.
            • -
            • Tiene controles fáciles e intuitivos.
            • -
            • Tiene sonidos divertidos y música agradable.
            • -
            • Tiene una gran variedad de juegos para todos los gustos.
            • -
            • Tiene un tamaño pequeño y no consume mucha batería.
            • -

            Opiniones de los usuarios y valoración del juego

            -

            Juegos de 2 jugadores tiene una valoración de 4.2 sobre 5 en Google Play, con más de 5 millones de descargas y más de 50 mil comentarios. La mayoría de los usuarios opinan que este juego es muy divertido y adictivo, y que tiene una gran variedad de juegos para elegir. Algunas de las opiniones más destacadas son:

            -
            -

            "Es un juego muy bueno, tiene muchos juegos diferentes y se puede jugar con otra persona en el mismo celular, es muy bueno para jugar cuando estás aburrido."

            -

            "Me gusta mucho este juego, es muy entretenido y divertido, se lo recomiendo a todos los que quieran pasar un buen rato con sus amigos o familiares."

            -

            "Es un juego muy completo, tiene muchos mini juegos y son muy divertidos, además no ocupa mucho espacio ni consume mucha batería, lo recomiendo mucho."

            -
            -

            2 Player games : the Challenge

            -

            Descripción del juego

            -

            2 Player games : the Challenge es otro juego de 2 jugadores apk que también ofrece una colección de mini juegos para jugar con tus amigos. Este juego tiene 16 mini juegos diferentes, que van desde carreras de motos, peleas de espadas, batallas de naves, hasta juegos de habilidad, como el tiro al blanco o el equilibrio. Este juego es ideal para jugar con tus amigos y retarlos a ver quién es el mejor en cada juego.

            -

            Modos de juego y características principales

            -

            2 Player games : the Challenge también tiene dos modos de juego: uno para jugar con otro jugador en el mismo dispositivo, y otro para jugar solo contra la inteligencia artificial. Cada mini juego tiene sus propias reglas y objetivos, que se muestran antes de empezar a jugar. Algunas de las características principales de este juego son:

            -
              -
            • Tiene gráficos modernos y realistas.
            • -
            • Tiene controles fáciles e intuitivos.
            • -
            • Tiene sonidos divertidos y música agradable.
            • -
            • Tiene una gran variedad de juegos para todos los gustos.
            • -
            • Tiene un tamaño pequeño y no consume mucha batería.
            • -
            que se quiera descargar, pulsar sobre el botón de descargar o instalar, esperar a que se complete la descarga del archivo APK, abrir el archivo APK desde el gestor de archivos o desde la barra de notificaciones, seguir las instrucciones del instalador y aceptar los permisos que solicite el juego, esperar a que se complete la instalación y pulsar sobre el icono del juego para abrirlo y empezar a jugar.

            -
          • ¿Cuáles son los mejores juegos de 2 jugadores apk?
          • -

            Hay muchos juegos de 2 jugadores apk que merecen la pena, pero nosotros hemos seleccionado tres que nos parecen especialmente divertidos y entretenidos. Estos son: Juegos de dos jugadores - 2, Juegos de 2 jugadores o 2 Player games : the Challenge. Estos juegos tienen una gran variedad de mini juegos para todos los gustos, y te garantizan horas de diversión y entretenimiento.

            -
          • ¿Qué ventajas tienen los juegos de 2 jugadores apk?
          • -

            Los juegos de 2 jugadores apk tienen muchas ventajas, como: promueven la interacción social y el compañerismo, estimulan la competencia sana y el desafío personal, desarrollan habilidades cognitivas y motrices, mejoran la coordinación y los reflejos, proporcionan entretenimiento y diversión sin límites, son gratuitos o tienen un precio muy bajo, no requieren mucho espacio ni recursos, son compatibles con la mayoría de los dispositivos, tienen gráficos coloridos y sonidos divertidos, son variados y ofrecen diferentes géneros y temáticas, y son fáciles de jugar y aprender.

            -
          • ¿Qué desventajas tienen los juegos de 2 jugadores apk?
          • -

            Los juegos de 2 jugadores apk también tienen algunas desventajas, como: pueden generar adicción y dependencia si se abusa de ellos, pueden provocar conflictos y discusiones si no se respeta el juego limpio y las normas de convivencia, pueden afectar negativamente al rendimiento académico o laboral si se descuida el tiempo dedicado a otras actividades, pueden causar problemas de salud, como fatiga visual, dolor de cabeza, estrés o insomnio si no se juega con moderación y precaución, y pueden contener publicidad o compras integradas que pueden resultar molestas o costosas.

            -
          • ¿Qué recomendaciones hay que seguir para jugar a los juegos de 2 jugadores apk?
          • -

            Para jugar a los juegos de 2 jugadores apk se recomienda seguir estas recomendaciones: elegir el juego que más se adapte a los gustos y preferencias de cada uno, jugar con personas que se conozcan y que tengan un nivel similar al propio, respetar las reglas del juego y el fair play, no jugar durante mucho tiempo seguido ni en condiciones inadecuadas, hacer pausas cada cierto tiempo, descansar la vista, hidratarse y jugar en un lugar cómodo y bien iluminado, disfrutar del juego y divertirse sin tomárselo demasiado en serio ni obsesionarse con ganar o perder.

            197e85843d
            -
            -
            \ No newline at end of file diff --git a/spaces/siya02/Konakni-TTS/ttsv/src/glow_tts/utils.py b/spaces/siya02/Konakni-TTS/ttsv/src/glow_tts/utils.py deleted file mode 100644 index a591aa319ccb264110111cda55c4a232b41aae74..0000000000000000000000000000000000000000 --- a/spaces/siya02/Konakni-TTS/ttsv/src/glow_tts/utils.py +++ /dev/null @@ -1,282 +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): - assert os.path.isfile(checkpoint_path) - checkpoint_dict = torch.load(checkpoint_path, map_location="cpu") - iteration = 1 - if "iteration" in checkpoint_dict.keys(): - iteration = checkpoint_dict["iteration"] - if "learning_rate" in checkpoint_dict.keys(): - learning_rate = checkpoint_dict["learning_rate"] - if optimizer is not None and "optimizer" in checkpoint_dict.keys(): - 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 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={}): - 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") - - -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() - 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, 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, help="JSON file for configuration") - parser.add_argument("-m", "--model", type=str, help="Model name") - # parser.add_argument('-g', '--gan', type=str, - # help='Model name') - parser.add_argument("-l", "--logs", type=str, help="logs name") - # parser.add_argument('-s', '--mels', type=str, - # help='logs name') - - args = parser.parse_args() - # model_dir = os.path.join("./logs", args.model) - 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 not config_path : config_path = config_save_path - - 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.log_dir = args.logs - # hparams.mels_dir = args.mels - # hparams.gan_dir = args.gan - 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/skf15963/summary/fengshen/models/PPVAE/pluginVAE.py b/spaces/skf15963/summary/fengshen/models/PPVAE/pluginVAE.py deleted file mode 100644 index 8841d64ca9d2cc63764015053a021103dfee24dd..0000000000000000000000000000000000000000 --- a/spaces/skf15963/summary/fengshen/models/PPVAE/pluginVAE.py +++ /dev/null @@ -1,180 +0,0 @@ -import torch -import torch.nn as nn -import torch.nn.functional as F -from torch.utils.data import DataLoader -from transformers.modeling_utils import PreTrainedModel -from transformers.configuration_utils import PretrainedConfig - -from fengshen.models.DAVAE.DAVAEModel import DAVAEModel -from fengshen.models.PPVAE.utils import * - -device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - -class Encoder(nn.Module): - def __init__(self, latent_dim=128, bottle_dim=20) -> None: - super().__init__() - self.fc1 = nn.Linear(latent_dim, latent_dim//2) - self.fc2 = nn.Linear(latent_dim//2, latent_dim//4) - self.mean = nn.Linear(latent_dim//4, bottle_dim) - self.log_var = nn.Linear(latent_dim//4, bottle_dim) - - def kl_loss(self, mean, log_var): - return (-0.5 * (1 + log_var - mean**2 - log_var.exp()).sum(-1)).mean() - - def sampling(self, mean, log_var): - epsilon = torch.randn(mean.shape[0], mean.shape[-1], device=mean.device) - return mean + (log_var / 2).exp() * epsilon.unsqueeze(1) - - def forward(self, z): - ''' - :param z: shape (b, latent_dim) - ''' - z = self.fc1(z) - z = F.leaky_relu(z) - z = F.leaky_relu(self.fc2(z)) - z_mean = self.mean(z) - - z_log_var = self.log_var(z) - kl_loss = self.kl_loss(z_mean, z_log_var) - enc_z = self.sampling(z_mean, z_log_var) - - if not self.training: - enc_z = z_mean - - return enc_z, kl_loss - -class Decoder(nn.Module): - def __init__(self, latent_dim=128, bottle_dim=20) -> None: - super().__init__() - self.fc1 = nn.Linear(bottle_dim, latent_dim//4) - self.fc2 = nn.Linear(latent_dim//4, latent_dim//2) - self.fc3 = nn.Linear(latent_dim//2, latent_dim) - - def forward(self, enc_z): - z = F.leaky_relu(self.fc1(enc_z)) - z = F.leaky_relu(self.fc2(z)) - z = self.fc3(z) - return z - -class PluginVAE(nn.Module): - def __init__(self, config) -> None: - super().__init__() - self.kl_weight = config.kl_weight - self.beta = config.beta - self.encoder = Encoder(config.latent_dim, config.bottle_dim) - self.decoder = Decoder(config.latent_dim, config.bottle_dim) - - def set_beta(self, beta): - self.beta = beta - - def forward(self, z): - enc_z, kl_loss = self.encoder(z) - z_out = self.decoder(enc_z) - return z_out, kl_loss - - def loss(self, z): - z_out, kl_loss = self.forward(z) - z_loss = ((z_out-z)**2).mean() - loss = z_loss + self.kl_weight * (kl_loss-self.beta).abs() - return loss, kl_loss - -class PPVAEPretrainedModel(PreTrainedModel): - def _init_weights(self, module): - """ Initialize the weights """ - pass # to bypass the not implement error - -class PPVAEModel(PPVAEPretrainedModel): - config_class = PretrainedConfig - def __init__(self, config:PretrainedConfig) -> None: - super().__init__(config=config) - self.config =config - self.pluginvae = PluginVAE(self.config) - self.vae_model = DAVAEModel(self.config) - - def train_plugin(self,encoder_tokenizer,decoder_tokenizer,input_texts,negative_samples=None): - # 输入:pluginVAE,label,train_data_dict - # 输出:pluginVAE - self.vae_model.set_tokenizers(encoder_tokenizer,decoder_tokenizer) - pos=self.get_latent(input_texts) - pos_batch_size = self.config.batch_size - total_epoch = self.config.total_epoch - pos_dataset = CustomDataset(pos) - pos_dataloader = DataLoader( - pos_dataset, - batch_size=pos_batch_size, - shuffle=True - ) - neg =None - if negative_samples is not None: - neg=self.get_latent(negative_samples) - neg_batch_size = int(pos_batch_size*(neg.shape[0]/pos.shape[0])) - neg_dataset = CustomDataset(neg) - neg_dataloader = DataLoader( - neg_dataset, - batch_size=neg_batch_size, - shuffle=True - ) - optimizer = torch.optim.Adam( - params=self.pluginvae.parameters(), - lr=self.config.ppvae_lr, betas=(self.config.mu, self.config.nu) - ) - gamma = self.config.gamma - iter_num = 0 - early_stopper = EarlyStopping() - min_loss = 10.0 - for epoch in range(total_epoch): - self.pluginvae.train() - total_pos_loss = 0.0 - total_neg_loss = 0.0 - total_loss = 0.0 - total_pos_kl = 0.0 - for i, data in enumerate(pos_dataloader): - if self.config.get_dymanic_beta: - self.pluginvae.set_beta(self.get_beta_weight(iter_num,self.config.beta,self.config.beta_total_step)) - iter_num += 1 - pos_loss,pos_kl = self.pluginvae.loss(data) - neg_loss = 0.0 - if neg is not None: - neg_data = next(iter(neg_dataloader)) - neg_loss,loss_kl = self.pluginvae.loss(neg_data) - if neg_loss.item()>self.config.neg_loss_threshold*pos_loss.item(): - # print("neg_loss exceed, detached") - neg_loss = neg_loss.detach() - total_neg_loss += neg_loss.item() - loss = pos_loss - gamma*neg_loss - optimizer.zero_grad() - loss.backward() - optimizer.step() - - total_pos_loss += pos_loss.item() - total_loss += loss.item() - total_pos_kl += pos_kl.item() - avg_loss = total_loss/len(pos_dataloader) - avg_kl_loss = total_pos_kl/len(pos_dataloader) - if avg_loss= length - - @staticmethod - def _get_square_subsequent_mask(sz, device, diagonal=0, fw=True): - r"""Generate a square mask for the sequence. The masked positions are filled with float('-inf'). - Unmasked positions are filled with float(0.0). - """ - mask = (torch.triu(torch.ones(sz, sz, device=device), diagonal=diagonal) == 1) - if fw: mask = mask.transpose(0, 1) - mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0)) - return mask - - @staticmethod - def _get_location_mask(sz, device=None): - mask = torch.eye(sz, device=device) - mask = mask.float().masked_fill(mask == 1, float('-inf')) - return mask diff --git a/spaces/spencer/socm/models.py b/spaces/spencer/socm/models.py deleted file mode 100644 index 89d749a1bcb10c25d6249ecd5456f720503a2ad8..0000000000000000000000000000000000000000 --- a/spaces/spencer/socm/models.py +++ /dev/null @@ -1,113 +0,0 @@ -import json -from PIL import Image - -import requests -import streamlit as st -from transformers import CLIPProcessor, CLIPModel - -from embeddings import logger - -HF_TOKEN = st.secrets["hf_api.key"] -#with open("hf_api.key") as f: -# HF_TOKEN = f.read().strip() - - -class HuggingFaceHosted: - def __init__(self, model_id, api_token, verbose=False): - self.model_id = model_id - self.api_token = api_token - self.verbose = verbose - - def query(self, data): - headers = {"Authorization": f"Bearer {self.api_token}"} - API_URL = f"https://api-inference.huggingface.co/models/{self.model_id}" - response = requests.request("POST", API_URL, headers=headers, data=data) - return json.loads(response.content.decode("utf-8")) - - def fill_mask(self, text): - data = json.dumps({"inputs": text}) - return self.query(data) - - def text_generation(self, text, **parameters): - payload = { - "inputs": text, - "parameters": parameters, - } - if self.verbose: - logger.info(payload) - data = json.dumps(payload) - return self.query(data) - - def summarization(self, text, do_sample=False): - data = json.dumps({"inputs": text, "parameters": {"do_sample": do_sample}}) - return self.query(data) - - def question_answering(self, question, context): - data = json.dumps( - { - "inputs": { - "question": question, - "context": context, - } - } - ) - return self.query(data) - - -class CLIP: - def __init__(self, model_id="openai/clip-vit-large-patch14"): - self.model_id = model_id - self.model = CLIPModel.from_pretrained(model_id) - self.processor = CLIPProcessor.from_pretrained(model_id) - - def get_image_emb(self, image): - if isinstance(image, str): - image = Image.open(image) - image_inputs = self.processor(images=image, return_tensors="pt", padding=True) - out = self.model.get_image_features(**image_inputs) - - return out.detach().numpy() - - def get_text_emb(self, text): - text_inputs = self.processor(text=text, return_tensors="pt", padding=True) - out = self.model.get_text_features(**text_inputs) - - return out.detach().numpy() - - def __repr__(self): - return f"CLIP Local <{self.model_id}>" - - -class GPTJ(HuggingFaceHosted): - def __init__( - self, model_id="EleutherAI/gpt-j-6B", api_token=HF_TOKEN, verbose=False - ): - super().__init__(model_id, api_token, verbose=verbose) - - def __call__(self, text, **parameters): - return self.text_generation(text, **parameters) - - def __repr__(self): - return f"GPTJ Hosted <{self.model_id}>" - - -class MaskEncoder(HuggingFaceHosted): - def __init__(self, model_id="roberta-large", api_token=HF_TOKEN, verbose=False): - super().__init__(model_id, api_token, verbose=verbose) - - def __call__(self, text): - return self.fill_mask(text) - - def __repr__(self): - return f"MaskEncoder Hosted <{self.model_id}>" - - -class T2T(HuggingFaceHosted): - def __init__(self, model_id="bigscience/T0pp", api_token=HF_TOKEN, verbose=False): - super().__init__(model_id, api_token, verbose=verbose) - - def __call__(self, text, **parameters): - return self.text_generation(text, **parameters) - - def __repr__(self): - return f"T2T Hosted <{self.model_id}>" diff --git a/spaces/sriramelango/Social_Classification_Public/fairseq/examples/speech_text_joint_to_text/criterions/__init__.py b/spaces/sriramelango/Social_Classification_Public/fairseq/examples/speech_text_joint_to_text/criterions/__init__.py deleted file mode 100644 index 7faae73119321af0b34fe8e26499a2ef5577291a..0000000000000000000000000000000000000000 --- a/spaces/sriramelango/Social_Classification_Public/fairseq/examples/speech_text_joint_to_text/criterions/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import importlib -import os - - -for file in os.listdir(os.path.dirname(__file__)): - if file.endswith(".py") and not file.startswith("_"): - criterion_name = file[: file.find(".py")] - importlib.import_module( - "examples.speech_text_joint_to_text.criterions." + criterion_name - ) diff --git a/spaces/stomexserde/gpt4-ui/Examples/Autodesk 2015 Xforce Keygen Torrent !!EXCLUSIVE!!.md b/spaces/stomexserde/gpt4-ui/Examples/Autodesk 2015 Xforce Keygen Torrent !!EXCLUSIVE!!.md deleted file mode 100644 index 48680208fb6ae382016fbd1cc82de78d1889990f..0000000000000000000000000000000000000000 --- a/spaces/stomexserde/gpt4-ui/Examples/Autodesk 2015 Xforce Keygen Torrent !!EXCLUSIVE!!.md +++ /dev/null @@ -1,71 +0,0 @@ -
            -

            Autodesk 2015 Xforce Keygen Torrent: A Comprehensive Overview

            -

            If you are looking for a way to activate Autodesk products of the 2015 version, such as AutoCAD, 3ds Max, Maya, Revit, and more, you may have come across Autodesk 2015 Xforce Keygen Torrent. This is a software that can generate product keys for various Autodesk products and allow you to use them without paying for a license. However, before you decide to use this software, you should be aware of the risks, benefits, features, and alternatives of it. In this article, I will provide you with a comprehensive overview of Autodesk 2015 Xforce Keygen Torrent, based on the information I found from various web sources. I hope this will help you make an informed decision.

            -

            Risks

            -

            Using Autodesk 2015 Xforce Keygen Torrent comes with significant project integrity, data security, financial and legal risks. Here are some of them:

            -

            Autodesk 2015 Xforce Keygen Torrent


            Downloadhttps://urlgoal.com/2uI7T8



            -
              -
            • Poor performance: Nonvalid software lacks stability, causing applications to crash at critical moments. You may experience integrity issues in your designs, processes, products or structures.
            • -
            • Hidden malware, lost data: You’ll have an increased risk of exposure to malware that can compromise data, including your work. Companies that install nonvalid software on their network face a 1 in 3 chance of obtaining malware.*
            • -
            • Legal and financial impact: Using nonvalid software puts you at risk for copyright infringement or other potential legal claims. Resolving claims and malware attacks can require a significant financial investment.
            • -
            -

            *Source: Risks of AutoCAD Torrents, Cracks & Keygens | Genuine | Autodesk

            -

            Benefits

            -

            Using Autodesk 2015 Xforce Keygen Torrent may seem appealing for some users who want to save money and access the latest features of Autodesk products. Here are some of the benefits of using this software:

            -
              -
            • Free activation: You can generate product keys for various Autodesk products and use them without paying for a license.
            • -
            • Access to all features: You can enjoy all the functionalities and enhancements of the Autodesk products of the 2015 version.
            • -
            • Easy to use: You can download and install the software easily and follow the instructions to activate your desired product.
            • -
            -

            Features

            -

            Autodesk 2015 Xforce Keygen Torrent is a software that can help you activate Autodesk products of the 2015 version. Here are some of the main features of this software:

            -
              -
            • Compatible with Windows and Mac OS: You can use this software on both Windows and Mac operating systems.
            • -
            • Supports multiple languages: You can choose from different languages for the user interface and the product keys.
            • -
            • Covers a wide range of products: You can generate product keys for various Autodesk products, such as AutoCAD, 3ds Max, Maya, Revit, and more.
            • -
            • Works offline: You do not need an internet connection to use this software.
            • -
            -

            Alternatives

            -

            Using Autodesk 2015 Xforce Keygen Torrent is not the only way to activate Autodesk products of the 2015 version. There are some other options that you can consider, such as:

            -
              -
            • Buying a genuine license: This is the most recommended and legal way to use Autodesk products. You can purchase a license from the official Autodesk website or an authorized reseller. You can choose from different types of licenses, such as subscription, perpetual, or network. By buying a genuine license, you can enjoy the benefits of technical support, updates, security, and compliance.
            • -
            • Using a trial version: If you want to test the features and performance of Autodesk products before buying a license, you can use a trial version for free for a limited time. You can download the trial version from the official Autodesk website and use it for up to 30 days. However, you should note that some features may not be available in the trial version and you cannot save or print your work.
            • -
            • Using an educational version: If you are a student, teacher, or academic institution, you can use an educational version of Autodesk products for free for educational purposes. You can access the educational version from the Autodesk Education Community website and use it for up to 3 years. However, you should note that the educational version is not intended for commercial use and has a watermark on the output.
            • -
            -

            Installation guide

            -

            If you decide to use Autodesk 2015 Xforce Keygen Torrent, you should follow these steps to install and use it:

            -
              -
            1. Download the software: You can download Autodesk 2015 Xforce Keygen Torrent from various torrent websites or file-sharing platforms. However, you should be careful about the source and the file size, as some of them may contain viruses or malware.
            2. -
            3. Extract the file: After downloading the software, you should extract the file using a program like WinRAR or 7-Zip. You should see a folder named X-Force 2015.
            4. -
            5. Run the keygen: Inside the folder, you should find a file named xf-adsk2015_x64.exe or xf-adsk2015_x86.exe, depending on your operating system. You should run this file as administrator by right-clicking on it and selecting Run as administrator.
            6. -
            7. Select your product: A window will appear with a list of Autodesk products. You should select the product that you want to activate from the drop-down menu.
            8. -
            9. Generate a product key: After selecting your product, you should click on Patch and then Generate. A product key will be generated for your product.
            10. -
            11. Copy and paste the product key: You should copy the product key from the keygen window and paste it into the activation window of your Autodesk product. You should also enter your name and organization in the required fields.
            12. -
            13. Activate your product: After entering the product key and other information, you should click on Activate and then Next. Your product will be activated and ready to use.
            14. -
            -

            Conclusion

            -

            In conclusion, Autodesk 2015 Xforce Keygen Torrent is a software that can help you activate Autodesk products of the 2015 version without paying for a license. However, using this software comes with significant risks, such as poor performance, hidden malware, lost data, legal and financial impact. Therefore, you should weigh the benefits and features of this software against the risks and alternatives before using it. The best way to use Autodesk products is to buy a genuine license from the official website or an authorized reseller. This way, you can enjoy the full functionality, security, support, and updates of your products.

            -

            FAQs

            -

            Here are some common questions and answers about Autodesk 2015 Xforce Keygen Torrent:

            -
              -
            1. Is Autodesk 2015 Xforce Keygen Torrent safe?
            2. -

              No, using Autodesk 2015 Xforce Keygen Torrent is not safe. You may expose your computer and data to malware that can compromise your security and privacy. You may also face legal and financial consequences for violating the terms of use of Autodesk products.

              -

              -
            3. Is Autodesk 2015 Xforce Keygen Torrent legal?
            4. -

              No, using Autodesk 2015 Xforce Keygen Torrent is not legal. You are infringing on the intellectual property rights of Autodesk by using their products without paying for a license. You may be subject to civil or criminal penalties for piracy or counterfeiting.

              -
            5. How do I uninstall Autodesk 2015 Xforce Keygen Torrent?
            6. -

              If you want to uninstall Autodesk 2015 Xforce Keygen Torrent, you should follow these steps:

              -
                -
              1. Delete the software: You should delete the folder named X-Force 2015 from your computer. You can also use a program like CCleaner or Revo Uninstaller to remove any traces of the software from your registry and system files.
              2. -
              3. Uninstall the Autodesk products: You should uninstall the Autodesk products that you activated with the software. You can do this by going to the Control Panel and selecting Programs and Features. You should select the Autodesk products and click on Uninstall.
              4. -
              5. Scan your computer: You should scan your computer with a reliable antivirus or anti-malware program to detect and remove any potential threats that may have been introduced by the software. You should also update your security software and firewall regularly to protect your computer from future attacks.
              6. -
              -
            7. How do I update Autodesk 2015 Xforce Keygen Torrent?
            8. -

              You cannot update Autodesk 2015 Xforce Keygen Torrent, as it is not an official product of Autodesk. The software is only compatible with the 2015 version of Autodesk products and does not support any newer versions. If you want to use the latest features and updates of Autodesk products, you should buy a genuine license from the official website or an authorized reseller.

              -
            9. How do I contact Autodesk 2015 Xforce Keygen Torrent support?
            10. -

              You cannot contact Autodesk 2015 Xforce Keygen Torrent support, as it is not an official product of Autodesk. The software is not endorsed or authorized by Autodesk and does not provide any technical support or customer service. If you encounter any problems or issues with the software, you are on your own. If you want to get support from Autodesk, you should buy a genuine license from the official website or an authorized reseller.

              -
            11. Where can I find more information about Autodesk 2015 Xforce Keygen Torrent?
            12. -

              You can find more information about Autodesk 2015 Xforce Keygen Torrent from various web sources, such as blogs, forums, reviews, or tutorials. However, you should be careful about the credibility and accuracy of these sources, as some of them may contain false or misleading information. You should also avoid clicking on any suspicious links or downloading any unknown files that may harm your computer or data. The best way to find more information about Autodesk products is to visit the official website or contact an authorized reseller.

              -

            b2dd77e56b
            -
            -
            \ No newline at end of file diff --git a/spaces/stomexserde/gpt4-ui/Examples/Downland Skymedi Fix 4gb To 8gbl !!BETTER!!.md b/spaces/stomexserde/gpt4-ui/Examples/Downland Skymedi Fix 4gb To 8gbl !!BETTER!!.md deleted file mode 100644 index 643f0a1b11981ab4f094d6a8b19ff429c5892ea5..0000000000000000000000000000000000000000 --- a/spaces/stomexserde/gpt4-ui/Examples/Downland Skymedi Fix 4gb To 8gbl !!BETTER!!.md +++ /dev/null @@ -1,21 +0,0 @@ -
            -

            How to Use Downland Skymedi Fix to Increase Your USB Flash Drive Capacity

            -

            If you have a USB flash drive that has a low capacity, such as 4GB, you might want to increase it to a higher capacity, such as 8GB. This can be useful if you need more space to store your files, photos, videos, or music. However, buying a new USB flash drive can be expensive and time-consuming. Fortunately, there is a way to use a software tool called Downland Skymedi Fix to increase your USB flash drive capacity without spending any money or replacing your device.

            -

            Downland Skymedi Fix 4gb To 8gbl


            Download Ziphttps://urlgoal.com/2uIc08



            -

            Downland Skymedi Fix is a software tool that can restore and increase the capacity of USB flash drives that use the SK6213/SK6215 or SK62XX/SK66XX controllers. These controllers are produced by Skymedi, a company that specializes in flash memory solutions. Downland Skymedi Fix can detect the original capacity of your USB flash drive and modify it to a higher capacity by using a special algorithm. This can help you get more storage space on your USB flash drive without losing any data or quality.

            -

            However, before you use Downland Skymedi Fix, you should be aware of some risks and limitations. First, Downland Skymedi Fix only works with USB flash drives that use the Skymedi controllers mentioned above. You can check the controller model of your USB flash drive by using a tool like ChipGenius or Flash Drive Information Extractor. If your USB flash drive uses a different controller, Downland Skymedi Fix will not work and may damage your device. Second, Downland Skymedi Fix may not be compatible with some operating systems or antivirus programs. You should disable any antivirus software before running Downland Skymedi Fix and make sure you have administrator rights on your computer. Third, Downland Skymedi Fix may not be able to increase the capacity of your USB flash drive beyond its physical limit. For example, if your USB flash drive has a physical limit of 8GB, you cannot increase it to 16GB using Downland Skymedi Fix. Fourth, Downland Skymedi Fix may cause some errors or data loss on your USB flash drive after increasing its capacity. You should backup any important files on your USB flash drive before using Downland Skymedi Fix and format your device after the process is completed.

            -

            If you are willing to accept these risks and limitations, you can follow these steps to use Downland Skymedi Fix to increase your USB flash drive capacity:

            -

            -
              -
            1. Download Downland Skymedi Fix from this link. This is a SoundCloud file that contains the software tool as an attachment. You can download it by clicking on the "More" button and then selecting "Download file".
            2. -
            3. Extract the ZIP file and run the SKYMEDI.exe file as an administrator.
            4. -
            5. Insert your USB flash drive into your computer and wait for it to be detected by the software.
            6. -
            7. Select your USB flash drive from the drop-down menu and click on "Fix".
            8. -
            9. Wait for the software to scan and modify your USB flash drive capacity. This may take several minutes depending on the size of your device.
            10. -
            11. When the process is finished, you will see a message saying "Fix Success". Click on "OK" and close the software.
            12. -
            13. Remove your USB flash drive from your computer and reinsert it. You should see that its capacity has increased to 8GB or more.
            14. -
            15. Format your USB flash drive using FAT32 or NTFS file system to avoid any errors or data loss.
            16. -
            -

            Congratulations! You have successfully used Downland Skymedi Fix to increase your USB flash drive capacity. You can now enjoy more storage space on your device without spending any money or replacing it.

            81aa517590
            -
            -
            \ No newline at end of file diff --git a/spaces/stomexserde/gpt4-ui/Examples/Hospital Management System Project Source Code.md b/spaces/stomexserde/gpt4-ui/Examples/Hospital Management System Project Source Code.md deleted file mode 100644 index 455f0b71ba0126dc1d1470098e224c49ffd3cae5..0000000000000000000000000000000000000000 --- a/spaces/stomexserde/gpt4-ui/Examples/Hospital Management System Project Source Code.md +++ /dev/null @@ -1,42 +0,0 @@ -
            -

            How to Create a Hospital Management System Project with PHP and MySQL

            -

            A hospital management system is a software application that helps to manage the daily operations of a hospital, such as patient records, appointments, billing, inventory, and more. A hospital management system can improve the efficiency and quality of health care services, as well as reduce costs and errors.

            -

            In this article, we will show you how to create a hospital management system project with PHP and MySQL. PHP is a popular server-side scripting language that can interact with databases and generate dynamic web pages. MySQL is a widely used open-source relational database management system that can store and retrieve data for web applications.

            -

            Hospital management system project source code


            Download --->>> https://urlgoal.com/2uIa4y



            -

            We will use the following steps to create our hospital management system project:

            -
              -
            1. Download and install XAMPP, which is a software package that contains Apache web server, PHP, MySQL, and other tools.
            2. -
            3. Create a database named "hospital" and import the SQL file from this link, which contains the tables and data for our project.
            4. -
            5. Download the source code files from this link, which contain the PHP scripts, HTML templates, CSS stylesheets, and images for our project.
            6. -
            7. Copy the source code files to the "htdocs" folder inside the XAMPP installation directory.
            8. -
            9. Open a web browser and type "http://localhost" in the address bar to access our project.
            10. -
            -

            Our hospital management system project has three main modules: admin panel, patient panel, and doctor panel. Each module has different features and functionalities, such as:

            -
              -
            • Admin panel: The admin can manage the hospital departments, doctors, patients, appointments, treatments, prescriptions, medicines, reports, and settings.
            • -
            • Patient panel: The patient can register an account, make an appointment, view their profile, treatment records, prescription records, and logout.
            • -
            • Doctor panel: The doctor can login with their credentials, view their profile, pending appointments, approved appointments, patient details, treatment records, prescription records, and logout.
            • -
            -

            We hope this article has helped you to learn how to create a hospital management system project with PHP and MySQL. You can download the source code files and modify them according to your needs. You can also explore other open-source projects related to hospital management systems on GitHub.

            - -

            How to Test a Hospital Management System Project

            -

            After creating a hospital management system project with PHP and MySQL, it is important to test its functionality and performance before deploying it to the production environment. Testing a hospital management system project involves verifying that the system meets the requirements and specifications, as well as identifying and fixing any errors or bugs.

            -

            There are different types of testing that can be performed on a hospital management system project, such as:

            -
              -
            • Unit testing: This type of testing checks the individual components or modules of the system, such as functions, classes, or methods. Unit testing can be done using tools like PHPUnit, which is a framework for testing PHP code.
            • -
            • Integration testing: This type of testing checks the interaction and communication between different components or modules of the system, such as database queries, web services, or APIs. Integration testing can be done using tools like Postman, which is a platform for testing and developing APIs.
            • -
            • Functional testing: This type of testing checks the functionality and usability of the system from the user's perspective, such as user interface, navigation, features, workflows, etc. Functional testing can be done using tools like Selenium, which is a framework for automating web browser actions.
            • -
            • Performance testing: This type of testing checks the speed, reliability, and scalability of the system under different load conditions, such as number of users, requests, data volume, etc. Performance testing can be done using tools like JMeter, which is a tool for load testing and measuring performance.
            • -
            • Security testing: This type of testing checks the security and privacy of the system from external threats, such as unauthorized access, data breaches, malware attacks, etc. Security testing can be done using tools like OWASP ZAP, which is a tool for finding vulnerabilities and security issues in web applications.
            • -
            -

            To test a hospital management system project effectively, it is recommended to follow a systematic and structured approach, such as:

            -
              -
            1. Plan the test: Define the scope, objectives, criteria, and strategy of the test. Identify the test cases, scenarios, data, and tools that will be used for the test. Allocate the roles and responsibilities of the test team.
            2. -
            3. Design the test: Create the test scripts, procedures, and scenarios that will be executed for the test. Define the expected results and outcomes of each test case.
            4. -
            5. Execute the test: Run the test scripts and scenarios on the system using the selected tools and data. Record the actual results and outcomes of each test case.
            6. -
            7. Analyze the test: Compare the actual results and outcomes with the expected ones. Identify any discrepancies, errors, or bugs that occurred during the test. Report and document the findings and issues of the test.
            8. -
            9. Improve the system: Fix any errors or bugs that were found during the test. Implement any changes or enhancements that are required to improve the system. Repeat the test cycle until all issues are resolved and all requirements are met.
            10. -
            -

            We hope this article has helped you to learn how to test a hospital management system project with PHP and MySQL. You can use this guide as a reference for conducting your own tests on your hospital management system project.

            81aa517590
            -
            -
            \ No newline at end of file diff --git a/spaces/stomexserde/gpt4-ui/Examples/Inner Circle Discography Torrent.md b/spaces/stomexserde/gpt4-ui/Examples/Inner Circle Discography Torrent.md deleted file mode 100644 index c4c1b061640f1608bdcc7cc97d54c12dd8c7a7b8..0000000000000000000000000000000000000000 --- a/spaces/stomexserde/gpt4-ui/Examples/Inner Circle Discography Torrent.md +++ /dev/null @@ -1,17 +0,0 @@ - -Here is a possible title and article with html formatting for the keyword "Inner Circle Discography Torrent": - -

            Download Inner Circle Discography Torrent for Free

            -

            Inner Circle is a Jamaican reggae band that was formed in 1968. The band is best known for their hit songs "Bad Boys", "Sweat (A La La La La Long)" and "Games People Play". They have released over 20 albums and have sold millions of copies worldwide.

            -

            Inner Circle Discography Torrent


            Download File === https://urlgoal.com/2uI8dG



            -

            If you are a fan of Inner Circle and want to enjoy their music offline, you can download their discography torrent for free from this website. You will get access to all their albums, singles, remixes and live performances in high quality mp3 format. You will also get the album covers, lyrics and tracklists for each release.

            -

            To download Inner Circle discography torrent, you need to have a torrent client installed on your device. You can use any popular torrent client such as uTorrent, BitTorrent or qBittorrent. Then, you need to click on the download link below and open it with your torrent client. The download will start automatically and you can choose where to save the files on your device.

            -

            Downloading Inner Circle discography torrent is fast and easy. You can enjoy their music anytime and anywhere you want. However, please note that downloading copyrighted content without permission is illegal and may have legal consequences. We do not condone or encourage piracy and we are not responsible for any damages or losses that may occur from using this website. Please support the artists by buying their original CDs or streaming their music online.

            -Download Inner Circle Discography Torrent HereHere is a possible continuation of the article: - -

            Inner Circle is one of the most influential and successful reggae bands of all time. They have been active for over five decades and have collaborated with many artists such as Lauryn Hill, Wyclef Jean, Slightly Stoopid and Damian Marley. They have also performed at many festivals and events such as Reggae Sunsplash, Glastonbury, Woodstock and the Nobel Peace Prize Concert.

            -

            Their discography torrent includes all their studio albums from 1974 to 2014, such as Rock the Boat, Everything Is Great, Bad to the Bone, Reggae Dancer and State of da World. It also includes their compilation albums, such as The Best of Inner Circle, Big Tings and Blazzin' Fire. You will also find their singles, such as "Da Bomb", "Speak My Language" and "One Way". Additionally, you will get their remixes and live albums, such as Inner Circle Live in Australia and Inner Circle Live at Montreux.

            -

            -

            Downloading Inner Circle discography torrent is a great way to explore their music and learn more about their history and culture. You will discover their roots in ska and rocksteady, their transition to reggae and pop, and their evolution to dancehall and hip hop. You will also appreciate their lyrics that touch on social issues, love, spirituality and fun. Inner Circle discography torrent is a must-have for any reggae lover.

            7196e7f11a
            -
            -
            \ No newline at end of file diff --git a/spaces/sub314xxl/MetaGPT/metagpt/memory/memory.py b/spaces/sub314xxl/MetaGPT/metagpt/memory/memory.py deleted file mode 100644 index bf9f0541c79b426008c9b4f0548729dabcb4273f..0000000000000000000000000000000000000000 --- a/spaces/sub314xxl/MetaGPT/metagpt/memory/memory.py +++ /dev/null @@ -1,95 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" -@Time : 2023/5/20 12:15 -@Author : alexanderwu -@File : memory.py -""" -from collections import defaultdict -from typing import Iterable, Type - -from metagpt.actions import Action -from metagpt.schema import Message - - -class Memory: - """The most basic memory: super-memory""" - - def __init__(self): - """Initialize an empty storage list and an empty index dictionary""" - self.storage: list[Message] = [] - self.index: dict[Type[Action], list[Message]] = defaultdict(list) - - def add(self, message: Message): - """Add a new message to storage, while updating the index""" - if message in self.storage: - return - self.storage.append(message) - if message.cause_by: - self.index[message.cause_by].append(message) - - def add_batch(self, messages: Iterable[Message]): - for message in messages: - self.add(message) - - def get_by_role(self, role: str) -> list[Message]: - """Return all messages of a specified role""" - return [message for message in self.storage if message.role == role] - - def get_by_content(self, content: str) -> list[Message]: - """Return all messages containing a specified content""" - return [message for message in self.storage if content in message.content] - - def delete(self, message: Message): - """Delete the specified message from storage, while updating the index""" - self.storage.remove(message) - if message.cause_by and message in self.index[message.cause_by]: - self.index[message.cause_by].remove(message) - - def clear(self): - """Clear storage and index""" - self.storage = [] - self.index = defaultdict(list) - - def count(self) -> int: - """Return the number of messages in storage""" - return len(self.storage) - - def try_remember(self, keyword: str) -> list[Message]: - """Try to recall all messages containing a specified keyword""" - return [message for message in self.storage if keyword in message.content] - - def get(self, k=0) -> list[Message]: - """Return the most recent k memories, return all when k=0""" - return self.storage[-k:] - - def remember(self, observed: list[Message], k=0) -> list[Message]: - """remember the most recent k memories from observed Messages, return all when k=0""" - already_observed = self.get(k) - news: list[Message] = [] - for i in observed: - if i in already_observed: - continue - news.append(i) - return news - - def get_by_action(self, action: Type[Action]) -> list[Message]: - """Return all messages triggered by a specified Action""" - return self.index[action] - - def get_by_actions(self, actions: Iterable[Type[Action]]) -> list[Message]: - """Return all messages triggered by specified Actions""" - rsp = [] - for action in actions: - if action not in self.index: - continue - rsp += self.index[action] - return rsp - - def get_by_tags(self, tags: list) -> list[Message]: - """Return messages with specified tags""" - result = [] - for m in self.storage: - if m.is_contain_tags(tags): - result.append(m) - return result diff --git a/spaces/sudokush/goofyai-3d_render_style_xl__generator/README.md b/spaces/sudokush/goofyai-3d_render_style_xl__generator/README.md deleted file mode 100644 index 0526bc8918a69f2eab7e64e9582be96ec5389f02..0000000000000000000000000000000000000000 --- a/spaces/sudokush/goofyai-3d_render_style_xl__generator/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Goofyai-3d Render Style Xl Generator -emoji: 🏃 -colorFrom: indigo -colorTo: blue -sdk: gradio -sdk_version: 3.44.4 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/supertori/files/stable-diffusion-webui/javascript/ui.js b/spaces/supertori/files/stable-diffusion-webui/javascript/ui.js deleted file mode 100644 index b7a8268a8fcdf9821cb3af31efea9e0283da1bfe..0000000000000000000000000000000000000000 --- a/spaces/supertori/files/stable-diffusion-webui/javascript/ui.js +++ /dev/null @@ -1,338 +0,0 @@ -// various functions for interaction with ui.py not large enough to warrant putting them in separate files - -function set_theme(theme){ - gradioURL = window.location.href - if (!gradioURL.includes('?__theme=')) { - window.location.replace(gradioURL + '?__theme=' + theme); - } -} - -function selected_gallery_index(){ - var buttons = gradioApp().querySelectorAll('[style="display: block;"].tabitem div[id$=_gallery] .gallery-item') - var button = gradioApp().querySelector('[style="display: block;"].tabitem div[id$=_gallery] .gallery-item.\\!ring-2') - - var result = -1 - buttons.forEach(function(v, i){ if(v==button) { result = i } }) - - return result -} - -function extract_image_from_gallery(gallery){ - if(gallery.length == 1){ - return [gallery[0]] - } - - index = selected_gallery_index() - - if (index < 0 || index >= gallery.length){ - return [null] - } - - return [gallery[index]]; -} - -function args_to_array(args){ - res = [] - for(var i=0;i label > textarea"); - - if(counter.parentElement == prompt.parentElement){ - return - } - - prompt.parentElement.insertBefore(counter, prompt) - counter.classList.add("token-counter") - prompt.parentElement.style.position = "relative" - - promptTokecountUpdateFuncs[id] = function(){ update_token_counter(id_button); } - textarea.addEventListener("input", promptTokecountUpdateFuncs[id]); - } - - registerTextarea('txt2img_prompt', 'txt2img_token_counter', 'txt2img_token_button') - registerTextarea('txt2img_neg_prompt', 'txt2img_negative_token_counter', 'txt2img_negative_token_button') - registerTextarea('img2img_prompt', 'img2img_token_counter', 'img2img_token_button') - registerTextarea('img2img_neg_prompt', 'img2img_negative_token_counter', 'img2img_negative_token_button') - - show_all_pages = gradioApp().getElementById('settings_show_all_pages') - settings_tabs = gradioApp().querySelector('#settings div') - if(show_all_pages && settings_tabs){ - settings_tabs.appendChild(show_all_pages) - show_all_pages.onclick = function(){ - gradioApp().querySelectorAll('#settings > div').forEach(function(elem){ - elem.style.display = "block"; - }) - } - } -}) - -onOptionsChanged(function(){ - elem = gradioApp().getElementById('sd_checkpoint_hash') - sd_checkpoint_hash = opts.sd_checkpoint_hash || "" - shorthash = sd_checkpoint_hash.substr(0,10) - - if(elem && elem.textContent != shorthash){ - elem.textContent = shorthash - elem.title = sd_checkpoint_hash - elem.href = "https://google.com/search?q=" + sd_checkpoint_hash - } -}) - -let txt2img_textarea, img2img_textarea = undefined; -let wait_time = 800 -let token_timeouts = {}; - -function update_txt2img_tokens(...args) { - update_token_counter("txt2img_token_button") - if (args.length == 2) - return args[0] - return args; -} - -function update_img2img_tokens(...args) { - update_token_counter("img2img_token_button") - if (args.length == 2) - return args[0] - return args; -} - -function update_token_counter(button_id) { - if (token_timeouts[button_id]) - clearTimeout(token_timeouts[button_id]); - token_timeouts[button_id] = setTimeout(() => gradioApp().getElementById(button_id)?.click(), wait_time); -} - -function restart_reload(){ - document.body.innerHTML='

            Reloading...

            '; - setTimeout(function(){location.reload()},2000) - - return [] -} - -// Simulate an `input` DOM event for Gradio Textbox component. Needed after you edit its contents in javascript, otherwise your edits -// will only visible on web page and not sent to python. -function updateInput(target){ - let e = new Event("input", { bubbles: true }) - Object.defineProperty(e, "target", {value: target}) - target.dispatchEvent(e); -} - - -var desiredCheckpointName = null; -function selectCheckpoint(name){ - desiredCheckpointName = name; - gradioApp().getElementById('change_checkpoint').click() -} diff --git a/spaces/supertori/files/stable-diffusion-webui/webui.py b/spaces/supertori/files/stable-diffusion-webui/webui.py deleted file mode 100644 index 7a89c60e1a3690ce95e682f934374388068e52d7..0000000000000000000000000000000000000000 --- a/spaces/supertori/files/stable-diffusion-webui/webui.py +++ /dev/null @@ -1,325 +0,0 @@ -import os -import sys -import time -import importlib -import signal -import re -from fastapi import FastAPI -from fastapi.middleware.cors import CORSMiddleware -from fastapi.middleware.gzip import GZipMiddleware -from packaging import version - -import logging -logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage()) - -from modules import paths, timer, import_hook, errors - -startup_timer = timer.Timer() - -import torch -startup_timer.record("import torch") - -import gradio -startup_timer.record("import gradio") - -import ldm.modules.encoders.modules -startup_timer.record("import ldm") - -from modules import extra_networks, ui_extra_networks_checkpoints -from modules import extra_networks_hypernet, ui_extra_networks_hypernets, ui_extra_networks_textual_inversion -from modules.call_queue import wrap_queued_call, queue_lock, wrap_gradio_gpu_call - -# Truncate version number of nightly/local build of PyTorch to not cause exceptions with CodeFormer or Safetensors -if ".dev" in torch.__version__ or "+git" in torch.__version__: - torch.__long_version__ = torch.__version__ - torch.__version__ = re.search(r'[\d.]+[\d]', torch.__version__).group(0) - -from modules import shared, devices, sd_samplers, upscaler, extensions, localization, ui_tempdir, ui_extra_networks -import modules.codeformer_model as codeformer -import modules.face_restoration -import modules.gfpgan_model as gfpgan -import modules.img2img - -import modules.lowvram -import modules.scripts -import modules.sd_hijack -import modules.sd_models -import modules.sd_vae -import modules.txt2img -import modules.script_callbacks -import modules.textual_inversion.textual_inversion -import modules.progress - -import modules.ui -from modules import modelloader -from modules.shared import cmd_opts -import modules.hypernetworks.hypernetwork - -startup_timer.record("other imports") - - -if cmd_opts.server_name: - server_name = cmd_opts.server_name -else: - server_name = "0.0.0.0" if cmd_opts.listen else None - - -def check_versions(): - if shared.cmd_opts.skip_version_check: - return - - expected_torch_version = "1.13.1" - - if version.parse(torch.__version__) < version.parse(expected_torch_version): - errors.print_error_explanation(f""" -You are running torch {torch.__version__}. -The program is tested to work with torch {expected_torch_version}. -To reinstall the desired version, run with commandline flag --reinstall-torch. -Beware that this will cause a lot of large files to be downloaded, as well as -there are reports of issues with training tab on the latest version. - -Use --skip-version-check commandline argument to disable this check. - """.strip()) - - expected_xformers_version = "0.0.16rc425" - if shared.xformers_available: - import xformers - - if version.parse(xformers.__version__) < version.parse(expected_xformers_version): - errors.print_error_explanation(f""" -You are running xformers {xformers.__version__}. -The program is tested to work with xformers {expected_xformers_version}. -To reinstall the desired version, run with commandline flag --reinstall-xformers. - -Use --skip-version-check commandline argument to disable this check. - """.strip()) - - -def initialize(): - check_versions() - - extensions.list_extensions() - localization.list_localizations(cmd_opts.localizations_dir) - startup_timer.record("list extensions") - - if cmd_opts.ui_debug_mode: - shared.sd_upscalers = upscaler.UpscalerLanczos().scalers - modules.scripts.load_scripts() - return - - modelloader.cleanup_models() - modules.sd_models.setup_model() - startup_timer.record("list SD models") - - codeformer.setup_model(cmd_opts.codeformer_models_path) - startup_timer.record("setup codeformer") - - gfpgan.setup_model(cmd_opts.gfpgan_models_path) - startup_timer.record("setup gfpgan") - - modelloader.list_builtin_upscalers() - startup_timer.record("list builtin upscalers") - - modules.scripts.load_scripts() - startup_timer.record("load scripts") - - modelloader.load_upscalers() - startup_timer.record("load upscalers") - - modules.sd_vae.refresh_vae_list() - startup_timer.record("refresh VAE") - - modules.textual_inversion.textual_inversion.list_textual_inversion_templates() - startup_timer.record("refresh textual inversion templates") - - try: - modules.sd_models.load_model() - except Exception as e: - errors.display(e, "loading stable diffusion model") - print("", file=sys.stderr) - print("Stable diffusion model failed to load, exiting", file=sys.stderr) - exit(1) - startup_timer.record("load SD checkpoint") - - shared.opts.data["sd_model_checkpoint"] = shared.sd_model.sd_checkpoint_info.title - - shared.opts.onchange("sd_model_checkpoint", wrap_queued_call(lambda: modules.sd_models.reload_model_weights())) - shared.opts.onchange("sd_vae", wrap_queued_call(lambda: modules.sd_vae.reload_vae_weights()), call=False) - shared.opts.onchange("sd_vae_as_default", wrap_queued_call(lambda: modules.sd_vae.reload_vae_weights()), call=False) - shared.opts.onchange("temp_dir", ui_tempdir.on_tmpdir_changed) - startup_timer.record("opts onchange") - - shared.reload_hypernetworks() - startup_timer.record("reload hypernets") - - ui_extra_networks.intialize() - ui_extra_networks.register_page(ui_extra_networks_textual_inversion.ExtraNetworksPageTextualInversion()) - ui_extra_networks.register_page(ui_extra_networks_hypernets.ExtraNetworksPageHypernetworks()) - ui_extra_networks.register_page(ui_extra_networks_checkpoints.ExtraNetworksPageCheckpoints()) - - extra_networks.initialize() - extra_networks.register_extra_network(extra_networks_hypernet.ExtraNetworkHypernet()) - startup_timer.record("extra networks") - - if cmd_opts.tls_keyfile is not None and cmd_opts.tls_keyfile is not None: - - try: - if not os.path.exists(cmd_opts.tls_keyfile): - print("Invalid path to TLS keyfile given") - if not os.path.exists(cmd_opts.tls_certfile): - print(f"Invalid path to TLS certfile: '{cmd_opts.tls_certfile}'") - except TypeError: - cmd_opts.tls_keyfile = cmd_opts.tls_certfile = None - print("TLS setup invalid, running webui without TLS") - else: - print("Running with TLS") - startup_timer.record("TLS") - - # make the program just exit at ctrl+c without waiting for anything - def sigint_handler(sig, frame): - print(f'Interrupted with signal {sig} in {frame}') - os._exit(0) - - signal.signal(signal.SIGINT, sigint_handler) - - -def setup_cors(app): - if cmd_opts.cors_allow_origins and cmd_opts.cors_allow_origins_regex: - app.add_middleware(CORSMiddleware, allow_origins=cmd_opts.cors_allow_origins.split(','), allow_origin_regex=cmd_opts.cors_allow_origins_regex, allow_methods=['*'], allow_credentials=True, allow_headers=['*']) - elif cmd_opts.cors_allow_origins: - app.add_middleware(CORSMiddleware, allow_origins=cmd_opts.cors_allow_origins.split(','), allow_methods=['*'], allow_credentials=True, allow_headers=['*']) - elif cmd_opts.cors_allow_origins_regex: - app.add_middleware(CORSMiddleware, allow_origin_regex=cmd_opts.cors_allow_origins_regex, allow_methods=['*'], allow_credentials=True, allow_headers=['*']) - - -def create_api(app): - from modules.api.api import Api - api = Api(app, queue_lock) - return api - - -def wait_on_server(demo=None): - while 1: - time.sleep(0.5) - if shared.state.need_restart: - shared.state.need_restart = False - time.sleep(0.5) - demo.close() - time.sleep(0.5) - break - - -def api_only(): - initialize() - - app = FastAPI() - setup_cors(app) - app.add_middleware(GZipMiddleware, minimum_size=1000) - api = create_api(app) - - modules.script_callbacks.app_started_callback(None, app) - - print(f"Startup time: {startup_timer.summary()}.") - api.launch(server_name="0.0.0.0" if cmd_opts.listen else "127.0.0.1", port=cmd_opts.port if cmd_opts.port else 7861) - - -def webui(): - launch_api = cmd_opts.api - initialize() - - while 1: - if shared.opts.clean_temp_dir_at_start: - ui_tempdir.cleanup_tmpdr() - startup_timer.record("cleanup temp dir") - - modules.script_callbacks.before_ui_callback() - startup_timer.record("scripts before_ui_callback") - - shared.demo = modules.ui.create_ui() - startup_timer.record("create ui") - - if cmd_opts.gradio_queue: - shared.demo.queue(64) - - gradio_auth_creds = [] - if cmd_opts.gradio_auth: - gradio_auth_creds += [x.strip() for x in cmd_opts.gradio_auth.strip('"').replace('\n', '').split(',') if x.strip()] - if cmd_opts.gradio_auth_path: - with open(cmd_opts.gradio_auth_path, 'r', encoding="utf8") as file: - for line in file.readlines(): - gradio_auth_creds += [x.strip() for x in line.split(',') if x.strip()] - - app, local_url, share_url = shared.demo.launch( - share=cmd_opts.share, - server_name=server_name, - server_port=cmd_opts.port, - ssl_keyfile=cmd_opts.tls_keyfile, - ssl_certfile=cmd_opts.tls_certfile, - debug=cmd_opts.gradio_debug, - auth=[tuple(cred.split(':')) for cred in gradio_auth_creds] if gradio_auth_creds else None, - inbrowser=cmd_opts.autolaunch, - prevent_thread_lock=True - ) - # after initial launch, disable --autolaunch for subsequent restarts - cmd_opts.autolaunch = False - - startup_timer.record("gradio launch") - - # gradio uses a very open CORS policy via app.user_middleware, which makes it possible for - # an attacker to trick the user into opening a malicious HTML page, which makes a request to the - # running web ui and do whatever the attacker wants, including installing an extension and - # running its code. We disable this here. Suggested by RyotaK. - app.user_middleware = [x for x in app.user_middleware if x.cls.__name__ != 'CORSMiddleware'] - - setup_cors(app) - - app.add_middleware(GZipMiddleware, minimum_size=1000) - - modules.progress.setup_progress_api(app) - - if launch_api: - create_api(app) - - ui_extra_networks.add_pages_to_demo(app) - - modules.script_callbacks.app_started_callback(shared.demo, app) - startup_timer.record("scripts app_started_callback") - - print(f"Startup time: {startup_timer.summary()}.") - - wait_on_server(shared.demo) - print('Restarting UI...') - - sd_samplers.set_samplers() - - modules.script_callbacks.script_unloaded_callback() - extensions.list_extensions() - - localization.list_localizations(cmd_opts.localizations_dir) - - modelloader.forbid_loaded_nonbuiltin_upscalers() - modules.scripts.reload_scripts() - modules.script_callbacks.model_loaded_callback(shared.sd_model) - modelloader.load_upscalers() - - for module in [module for name, module in sys.modules.items() if name.startswith("modules.ui")]: - importlib.reload(module) - - modules.sd_models.list_models() - - shared.reload_hypernetworks() - - ui_extra_networks.intialize() - ui_extra_networks.register_page(ui_extra_networks_textual_inversion.ExtraNetworksPageTextualInversion()) - ui_extra_networks.register_page(ui_extra_networks_hypernets.ExtraNetworksPageHypernetworks()) - ui_extra_networks.register_page(ui_extra_networks_checkpoints.ExtraNetworksPageCheckpoints()) - - extra_networks.initialize() - extra_networks.register_extra_network(extra_networks_hypernet.ExtraNetworkHypernet()) - - -if __name__ == "__main__": - if cmd_opts.nowebui: - api_only() - else: - webui() diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/2001 Hyundai Elantra Service Manual Download 2021.md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/2001 Hyundai Elantra Service Manual Download 2021.md deleted file mode 100644 index 85f7ac147a3d0bf5328c00c335f5aba22ad42607..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/2001 Hyundai Elantra Service Manual Download 2021.md +++ /dev/null @@ -1,29 +0,0 @@ - -

            How to Download a 2001 Hyundai Elantra Service Manual for Free

            -

            If you own a 2001 Hyundai Elantra, you may want to have a service manual that covers all the maintenance and repair procedures for your car. A service manual can help you diagnose problems, troubleshoot issues, and perform routine checks on your vehicle. But where can you find a free service manual for your 2001 Hyundai Elantra?

            -

            2001 hyundai elantra service manual download


            Download Ziphttps://cinurl.com/2uEXcv



            -

            Fortunately, there are some online sources that offer free PDF downloads of Hyundai Elantra service manuals. These manuals are not official Hyundai publications, but they are based on the factory workshop manuals that Hyundai technicians use. They contain detailed information on the engine, transmission, brakes, suspension, electrical system, wiring diagrams, and more. Here are some of the websites that offer free Hyundai Elantra service manuals:

            -
              -
            • OnlyManuals.com: This website has 146 Hyundai Elantra manuals covering a total of 32 years of production. You can find the 2001 Hyundai Elantra service manual by selecting the year and model from the drop-down menu. You can then view the first 10 pages of the manual online or download the full PDF file for free[^1^].
            • -
            • ManualsLib.com: This website has the owner's manual for the 2001 Hyundai Elantra. The owner's manual is different from the service manual, as it provides basic information on the features and operation of your car. However, it also includes some useful tips on how to maintain your car and what to do in an emergency[^2^]. You can browse the manual online or download it as a PDF file for free.
            • -
            • AllCarManuals.com: This website has the factory service manual for the Hyundai Elantra XD model years 2001 to 2006. The XD is the third generation of the Elantra, which was sold in North America as the 2001 to 2006 model years. The factory service manual is a comprehensive guide that covers all aspects of servicing and repairing your car[^3^]. You can download it as a ZIP file containing PDF files for free.
            • -
            -

            These are some of the best online sources for downloading a free service manual for your 2001 Hyundai Elantra. However, you should be aware that these manuals are not endorsed by Hyundai and may not be updated or accurate. Therefore, you should always consult a qualified Hyundai technician before attempting any repairs or modifications on your car.

            - -

            Why do you need a service manual for your 2001 Hyundai Elantra? A service manual is a valuable resource that can help you keep your car in good condition and save money on repairs. A service manual can help you with the following tasks:

            -
              -
            • Performing regular maintenance: A service manual will tell you when and how to perform routine maintenance on your car, such as changing the oil, replacing the air filter, checking the tire pressure, and more. Performing regular maintenance can prevent major problems and extend the life of your car.
            • -
            • Diagnosing problems: A service manual will help you identify the cause of any problems or malfunctions that may occur with your car. For example, if your check engine light comes on, you can use the service manual to find out what the trouble code means and how to fix it.
            • -
            • Troubleshooting issues: A service manual will provide you with step-by-step instructions on how to troubleshoot and resolve any issues that may arise with your car. For example, if your car won't start, you can use the service manual to check the battery, the starter, the fuel system, and other possible causes.
            • -
            • Performing repairs: A service manual will show you how to perform various repairs on your car, such as replacing the brake pads, changing the spark plugs, adjusting the valves, and more. Performing repairs yourself can save you money and time.
            • -
            -

            How to use a service manual for your 2001 Hyundai Elantra? A service manual is a useful tool that can help you maintain and repair your car. However, you should use it with caution and common sense. Here are some tips on how to use a service manual for your 2001 Hyundai Elantra:

            -

            -
              -
            • Read the manual carefully: Before attempting any maintenance or repair on your car, you should read the relevant section of the service manual carefully. Make sure you understand the procedures, the warnings, and the precautions. If you are not sure about something, ask a professional for advice.
            • -
            • Follow the instructions: When performing any maintenance or repair on your car, you should follow the instructions in the service manual exactly. Do not skip any steps or make any changes. Doing so may result in damage to your car or injury to yourself.
            • -
            • Use the right tools and parts: When performing any maintenance or repair on your car, you should use the right tools and parts for the job. Do not use any tools or parts that are not specified in the service manual. Using the wrong tools or parts may result in damage to your car or injury to yourself.
            • -
            • Be safe: When performing any maintenance or repair on your car, you should always be safe. Wear protective clothing and gloves, avoid working near hot or moving parts, disconnect the battery before working on electrical components, and use jack stands when lifting your car. Never work on your car when it is running or when you are under the influence of alcohol or drugs.
            • -

            d5da3c52bf
            -
            -
            \ No newline at end of file diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Body Language Books In Hindi Pdf 29.md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Body Language Books In Hindi Pdf 29.md deleted file mode 100644 index c822b1db0a6b54a4d07392310d598093c29de916..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Body Language Books In Hindi Pdf 29.md +++ /dev/null @@ -1,12 +0,0 @@ -
            -

            Body Language Books In Hindi Pdf 29: शरीर की भाषा को समझने के लिए सर्वश्रेष्ठ पुस्तकें

            - -

            शरीर की भाषा या बॉडी लैंग्वेज हमारे संचार का एक महत्वपूर्ण हिस्सा है। हम अपने शब्दों के साथ-साथ अपने शरीर के इशारों से भी अपनी भावनाओं, विचारों और नियत को प्रकट करते हैं। अगर हम किसी की बॉडी लैंग्वेज को सही ढंग से पढ़ना और समझना सीख लें, तो हमें उनके मन में क्या चल रहा है, यह पता लगाने में मदद मिलेगी।

            - -

            बॉडी लैंग्वेज को समझने के लिए, हमें कुछ मूलभूत सिद्धांतों, संकेतों और मुद्राओं का पता होना चाहिए। हमें पता होना चाहिए कि हमारे हाथ, पैर, मुह, आंखें, सिर, कंधे, पीठ, सीना, पेट, होंठ, नाक, कान, पसलियां, हिप्स, मस्तिष्क, स्पंदन, स्वास, पसीना, मसलना, हलका-हलका होना, हलका-हलका होना, हलका-हलका होना, हलका-हलका होना, हलक

            -

            Body Language Books In Hindi Pdf 29


            Download File ★★★★★ https://cinurl.com/2uEXdZ



            -

            का होना आदि हमारे भावों को प्रदर्शित करते हैं। इस पुस्तक में, हम आपको इन सभी बॉडी लैंग्वेज के तत्वों के बारे में बताएंगे और आपको यह सिखाएंगे कि कैसे आप इन्हें पढ़कर किसी की मनोदशा, स्वभाव, रुचि, आकर्षण, सहमति, असहमति, झूठ, सत्य, संकोच, आत्मविश्वास, अहंकार, सम्मान, अपमान, प्रेम, नफरत, प्रतिस्पर्धा, सहयोग, समर्पण, प्रतिरोध, प्रेरणा, मनोरंजन, मनोरोग, सुरक्षा, खतरा आदि का पता लगा सकें।

            - -

            Body Language Books In Hindi Pdf 29: शरीर की भाषा को समझने के लिए सर्वश्रेष्ठ पुस्तकें में हमने कुछ प्रसिद्ध और महत्वपूर्ण पुस्तकों का चुनाव किया है। ये पुस्तकें हमें बॉडी लैंग्वेज की महत्ता, मूल-सिद्धांत, प्रकार, प्रयोग, सुलभता, सुलझाने की कला, प्रासंगिकता और प्रभाव के बारे में समृद्ध ज्ञान प्रदान करती हैं। हमने हर पुस्तक का संक्षिप्त परिचय, मुख्य-मुख्य-लेखकों के बारे में, पुस्तक में प्रस्तुत मुख्य-मुख्य-पहलु , पुस्तक की महत्ता , पुस्तक की संपृक्‍ति , पुस्‍तक की स्‍पर्‍धा , पुस्‍तक की मूल्‍य , पुस्‍तक की स्‍पर्‍धा , पुस्‍तक की मूल्‍य , पुस्‍तक की स्‍पर्‍धा , पुस्‍तक की मूल्‍

            3cee63e6c2
            -
            -
            \ No newline at end of file diff --git a/spaces/surmensipa/VITS-Umamusume-voice-synthesizer/logs/Adata Classic Ch94 Driver Windows 7 91.md b/spaces/surmensipa/VITS-Umamusume-voice-synthesizer/logs/Adata Classic Ch94 Driver Windows 7 91.md deleted file mode 100644 index 46064ed47478ca9d1bb05fd25511b36178d1dcb9..0000000000000000000000000000000000000000 --- a/spaces/surmensipa/VITS-Umamusume-voice-synthesizer/logs/Adata Classic Ch94 Driver Windows 7 91.md +++ /dev/null @@ -1,23 +0,0 @@ - -

            How to Install ADATA Classic CH94 Driver on Windows 7 91

            -

            If you have an ADATA Classic CH94 external hard drive and want to use it on your Windows 7 91 computer, you may need to install a driver first. A driver is a software that helps your computer communicate with your device. Without a driver, your computer may not recognize your device or may not work properly with it.

            -

            In this article, we will show you how to download and install the ADATA Classic CH94 driver on Windows 7 91 step by step. Follow these instructions carefully and you will be able to use your external hard drive without any problems.

            -

            adata classic ch94 driver windows 7 91


            Download Ziphttps://urluss.com/2uCHma



            -

            Step 1: Download the ADATA Classic CH94 Driver

            -

            The first thing you need to do is to download the ADATA Classic CH94 driver from the official website. Here is the link: https://www.adata.com/en/support/driver/external-hdd/ch94/

            -

            On this page, you will see a list of drivers for different operating systems. Scroll down and find the one that says "Windows 7 91". Click on the download button and save the file to your computer.

            -

            Step 2: Extract the ADATA Classic CH94 Driver

            -

            The file you downloaded is a compressed zip file. You need to extract it before you can install it. To do this, right-click on the file and select "Extract All". Choose a destination folder where you want to save the extracted files and click "Extract".

            -

            After the extraction is done, you will see a folder named "CH94_Win7_91_Driver". Open it and you will see two files: "Setup.exe" and "Readme.txt". The first one is the installer and the second one is the instruction manual.

            -

            Step 3: Install the ADATA Classic CH94 Driver

            -

            Now you are ready to install the ADATA Classic CH94 driver on your computer. To do this, double-click on the "Setup.exe" file and follow the on-screen instructions. You may need to accept some terms and conditions and choose a location for the driver.

            -

            When the installation is complete, you will see a message that says "Installation Complete". Click "Finish" and restart your computer.

            -

            Step 4: Connect Your ADATA Classic CH94 External Hard Drive

            -

            The last step is to connect your ADATA Classic CH94 external hard drive to your computer. To do this, plug one end of the USB cable into your device and the other end into an available USB port on your computer.

            -

            Your computer should automatically detect your device and assign it a drive letter. You can access your device from the File Explorer or My Computer. You can also check the Device Manager to see if your device is recognized correctly.

            -

            -

            Conclusion

            -

            Congratulations! You have successfully installed the ADATA Classic CH94 driver on Windows 7 91. Now you can enjoy using your external hard drive with your computer without any issues.

            -

            If you have any questions or problems with the installation process, you can refer to the "Readme.txt" file or contact ADATA customer support for assistance.

            d5da3c52bf
            -
            -
            \ No newline at end of file diff --git a/spaces/surmensipa/VITS-Umamusume-voice-synthesizer/logs/Angry Birds Rio V1.1.0 Cracked READ NFO-THETA [CRACKED].md b/spaces/surmensipa/VITS-Umamusume-voice-synthesizer/logs/Angry Birds Rio V1.1.0 Cracked READ NFO-THETA [CRACKED].md deleted file mode 100644 index f5d4a18da9656d61ab291e8611618fa0465f7cf7..0000000000000000000000000000000000000000 --- a/spaces/surmensipa/VITS-Umamusume-voice-synthesizer/logs/Angry Birds Rio V1.1.0 Cracked READ NFO-THETA [CRACKED].md +++ /dev/null @@ -1,118 +0,0 @@ - -

            Angry Birds Rio v1.1.0 Cracked READ NFO-THETA - A Fun and Addictive Game for PC

            - -

            If you are a fan of the Angry Birds franchise, you will love Angry Birds Rio v1.1.0 Cracked READ NFO-THETA, the third installment of the popular game series. This game is based on the animated movie Rio, and features the same characters and settings as the film. You will join the Angry Birds as they are captured, caged, and taken to Rio de Janeiro, where they meet new friends and work together to escape from their captors.

            -

            Angry Birds Rio v1.1.0 Cracked READ NFO-THETA


            DOWNLOAD » https://urluss.com/2uCFWn



            - -

            Angry Birds Rio v1.1.0 Cracked READ NFO-THETA is a fun and addictive game that will keep you entertained for hours. You will have to use your slingshot to launch the birds at the cages, the marmosets, and other obstacles that stand in your way. You will also have to use your strategy and skill to aim accurately and hit the targets with the least number of birds possible. You will also have to collect stars, fruits, and other items to unlock new levels and achievements.

            - -

            Angry Birds Rio v1.1.0 Cracked READ NFO-THETA has two episodes: Smugglers' Den and Jungle Escape, each with 30 levels of increasing difficulty. You will also have access to six bonus levels that you can unlock by finding hidden golden fruits in the main levels. You will also have four special birds that you can use in the game: Blu and Jewel, the macaws from the movie; Pedro and Nico, the samba-loving birds; and Rafael, the toucan who helps Blu and Jewel.

            - -

            How to Download and Install Angry Birds Rio v1.1.0 Cracked READ NFO-THETA

            - -

            To download and install Angry Birds Rio v1.1.0 Cracked READ NFO-THETA, you will need a PC running Windows XP/Vista/7/8/10/11, 32-bit or 64-bit. You will also need a reliable internet connection to download the game from various sources. The game is not very large, so it should not take long to download.

            - -

            Here are some steps to download and install Angry Birds Rio v1.1.0 Cracked READ NFO-THETA:

            - -
              -
            1. Go to any source that offers Angry Birds Rio v1.1.0 Cracked READ NFO-THETA, such as RLSLOG.net, Wixsite.com, Pastebin.com, Archive.org, or Trello.com.
            2. -
            3. Click on the download link or button and follow the instructions on the screen.
            4. -
            5. Wait for the download to complete and save the file on your PC.
            6. -
            7. Double-click on the file and run the installation wizard.
            8. -
            9. Follow the instructions on the screen to install the game on your PC.
            10. -
            11. Use the key from 'Serial.txt' to activate the game after applying the patch.
            12. -
            13. Launch the game from your desktop or start menu and enjoy!
            14. -
            - -

            Tips and Tricks for Angry Birds Rio v1.1.0 Cracked READ NFO-THETA

            - -

            Angry Birds Rio v1.1.0 Cracked READ NFO-THETA is a game that requires strategy, skill, and luck. Here are some tips and tricks to help you master this game:

            -

            - -
              -
            • Pay attention to the physics of the game and use it to your advantage. You can use gravity, momentum, bounce, ricochet, and other effects to hit your targets more effectively.
            • -
            • Try to hit multiple targets with one bird by using combos and chain reactions.
            • -
            • Use different types of birds according to their abilities and characteristics. For example, use Red for direct hits, Blue for breaking glass, Yellow for speeding up, Black for exploding, White for dropping eggs, Green for boomeranging, Big Brother for smashing through anything, Blu for sticking to surfaces, Jewel for flying fast and cutting through objects, Pedro and Nico for spinning around and hitting multiple targets, and Rafael for gliding over obstacles.
            • -
            • Aim for weak points and vulnerable spots on the cages, marmosets, and other obstacles.
            • -
            • Look for hidden golden fruits in each level to unlock bonus levels.
            • -
            • Have fun!
            • -
            - -

            Conclusion

            - -

            Angry Birds Rio v1.1.0 Cracked READ NFO-THETA is a game that will appeal to anyone who loves Angry Birds games or Rio movies. It is a game that will entertain you with its fun and addictive gameplay, challenge you with its physics-based puzzles, and delight you with its colorful and charming graphics. It is also a game that you can download for free and play offline. So what are you waiting for? Download Angry Birds Rio v1.1.0 Cracked READ NFO-THETA today and join the Angry Birds in their Rio adventure!

            -

            What are the Features of Angry Birds Rio v1.1.0 Cracked READ NFO-THETA

            - -

            Angry Birds Rio v1.1.0 Cracked READ NFO-THETA is a game that has many features that make it unique and enjoyable. Here are some of the features of this game:

            - -
              -
            • It has high-quality graphics and sound effects that match the theme and mood of the game. You will see the beautiful scenery of Rio de Janeiro, hear the lively music and sounds of the city, and feel the emotions of the birds and their enemies.
            • -
            • It has a captivating storyline that follows the plot of the movie Rio. You will see how the Angry Birds are kidnapped and taken to Rio, how they meet Blu and Jewel and their friends, how they escape from their cages and fight against the smugglers and their marmoset minions, and how they celebrate their freedom and friendship.
            • -
            • It has a variety of gameplay modes that offer different challenges and rewards. You can play the Career Game mode, where you have to complete 60 levels in two episodes, or the Nonstop Game mode, where you can play endlessly until you run out of birds or time. You can also play the Bonus Game mode, where you can unlock six extra levels by finding hidden golden fruits in the main levels.
            • -
            • It has a lot of replay value and content that will keep you hooked for a long time. You can try to get three stars on each level by using as few birds as possible, collect all the fruits and items to unlock more content, earn achievements and trophies to show off your skills, and compare your scores with your friends and other players online.
            • -
            • It has a crack and a patch that make it easy to install and play on your PC. You don't need to buy or register the game, you just need to download it from any source that offers it, such as RLSLOG.net, Wixsite.com, Pastebin.com, Archive.org, or Trello.com. You just need to follow some simple steps to install and activate the game using the key from 'Serial.txt' after applying the patch.
            • -
            - -

            Angry Birds Rio v1.1.0 Cracked READ NFO-THETA is a game that has many features that make it unique and enjoyable. It is a game that will give you hours of fun and entertainment with its high-quality graphics and sound effects, its captivating storyline, its variety of gameplay modes, its replay value and content, and its crack and patch.

            -

            How to Play Angry Birds Rio v1.1.0 Cracked READ NFO-THETA

            - -

            Angry Birds Rio v1.1.0 Cracked READ NFO-THETA is a game that is easy to play but hard to master. Here are some basic instructions on how to play this game:

            - -
              -
            1. Select a level from the map screen and click on the play button.
            2. -
            3. On the level screen, you will see a slingshot on the left and a number of birds on the bottom. You will also see cages, marmosets, and other obstacles on the right.
            4. -
            5. Drag a bird from the bottom to the slingshot and pull it back to adjust the angle and power of your shot.
            6. -
            7. Release the bird and watch it fly towards the target. You can also tap on the screen to activate the bird's special ability.
            8. -
            9. Try to hit as many cages, marmosets, and other obstacles as possible with each bird. The more damage you cause, the more points you get.
            10. -
            11. You can also collect stars, fruits, and other items that appear on the screen for extra points and bonuses.
            12. -
            13. You complete a level when you free all the caged birds or eliminate all the marmosets. You can also replay a level to improve your score or get three stars.
            14. -
            - -

            Why You Should Play Angry Birds Rio v1.1.0 Cracked READ NFO-THETA

            - -

            Angry Birds Rio v1.1.0 Cracked READ NFO-THETA is a game that you should play for many reasons. Here are some of the reasons why you should play this game:

            - -
              -
            • It is fun and addictive. You will enjoy launching the birds at the cages, marmosets, and other obstacles and watching them explode and fall. You will also enjoy trying to get the best score and unlock all the content in the game.
            • -
            • It is challenging and rewarding. You will face different types of levels, enemies, and situations that will test your skills and strategy. You will also feel satisfied when you complete a level or achieve a goal in the game.
            • -
            • It is educational and informative. You will learn about the movie Rio and its characters, settings, and themes. You will also learn about the real-life issues of animal trafficking and conservation that are addressed in the movie and the game.
            • -
            • It is creative and original. You will see how the Angry Birds franchise is adapted to the Rio movie and how it creates a unique and engaging gameplay experience. You will also see how the game uses humor, animation, and music to enhance its appeal.
            • -
            - -

            Angry Birds Rio v1.1.0 Cracked READ NFO-THETA is a game that you should play for many reasons. It is a game that will provide you with fun, challenge, education, and creativity. It is also a game that you can download for free and play offline. So what are you waiting for? Download Angry Birds Rio v1.1.0 Cracked READ NFO-THETA today and join the Angry Birds in their Rio adventure!

            -

            What are the Pros and Cons of Angry Birds Rio v1.1.0 Cracked READ NFO-THETA

            - -

            Angry Birds Rio v1.1.0 Cracked READ NFO-THETA is a game that has many pros and cons that you should consider before playing it. Here are some of the pros and cons of this game:

            - -

            Pros

            - -
              -
            • It is free and easy to download and install. You don't need to pay or register anything to play this game. You just need to follow some simple steps to download it from any source that offers it, such as RLSLOG.net, Wixsite.com, Pastebin.com, Archive.org, or Trello.com.
            • -
            • It is compatible and accessible. You can play this game on any PC running Windows XP/Vista/7/8/10/11, 32-bit or 64-bit. You can also play this game offline without any internet connection.
            • -
            • It is fun and addictive. You will enjoy launching the birds at the cages, marmosets, and other obstacles and watching them explode and fall. You will also enjoy trying to get the best score and unlock all the content in the game.
            • -
            • It is challenging and rewarding. You will face different types of levels, enemies, and situations that will test your skills and strategy. You will also feel satisfied when you complete a level or achieve a goal in the game.
            • -
            • It is educational and informative. You will learn about the movie Rio and its characters, settings, and themes. You will also learn about the real-life issues of animal trafficking and conservation that are addressed in the movie and the game.
            • -
            • It is creative and original. You will see how the Angry Birds franchise is adapted to the Rio movie and how it creates a unique and engaging gameplay experience. You will also see how the game uses humor, animation, and music to enhance its appeal.
            • -
            - -

            Cons

            - -
              -
            • It is cracked and patched. You may encounter some problems or errors when playing this game because it is not an official or authorized version of the game. You may also face some legal or ethical issues when playing this game because it violates the rights of the original developers and publishers of the game.
            • -
            • It is outdated and unsupported. You may not be able to play this game on newer versions of Windows or with newer hardware or software. You may also not be able to get any updates or fixes for this game because it is not maintained or supported by anyone.
            • -
            • It is repetitive and boring. You may get bored or tired of playing this game after a while because it does not offer much variety or innovation in its gameplay or content. You may also find this game too easy or too hard depending on your skill level or preference.
            • -
            • It is addictive and distracting. You may spend too much time or energy playing this game and neglect your other responsibilities or interests. You may also develop some negative habits or behaviors when playing this game such as procrastination, isolation, frustration, or aggression.
            • -
            - -

            Angry Birds Rio v1.1.0 Cracked READ NFO-THETA is a game that has many pros and cons that you should consider before playing it. It is a game that can provide you with fun, challenge, education, and creativity, but it can also cause you some problems, errors, boredom, or addiction. It is up to you to decide whether you want to play this game or not.

            -

            Conclusion

            - -

            Angry Birds Rio v1.1.0 Cracked READ NFO-THETA is a game that you may or may not want to play depending on your preferences and circumstances. It is a game that has many features, pros, and cons that you should weigh before downloading and installing it. It is a game that can give you hours of fun and entertainment with its high-quality graphics and sound effects, its captivating storyline, its variety of gameplay modes, its replay value and content, and its crack and patch. But it is also a game that can cause you some problems and errors with its cracked and patched version, its outdated and unsupported status, its repetitive and boring gameplay, and its addictive and distracting nature. It is up to you to decide whether you want to play this game or not.

            - -

            If you do decide to play this game, you can download it for free from any source that offers it, such as RLSLOG.net, Wixsite.com, Pastebin.com, Archive.org, or Trello.com. You just need to follow some simple steps to download and install the game on your PC running Windows XP/Vista/7/8/10/11, 32-bit or 64-bit. You just need to use the key from 'Serial.txt' to activate the game after applying the patch. You can then launch the game from your desktop or start menu and enjoy!

            - -

            If you don't decide to play this game, you can still enjoy the Angry Birds franchise by playing other official or authorized versions of the game on different platforms such as iOS, Android, Mac OS X, Windows Phone, Facebook, Google Chrome, Roku, etc. You can also watch the movie Rio or its sequel Rio 2 to see the story and characters that inspired this game. You can also support the original developers and publishers of the game by buying or registering the game from their official websites or stores.

            - -

            Angry Birds Rio v1.1.0 Cracked READ NFO-THETA is a game that you may or may not want to play depending on your preferences and circumstances. It is a game that has many features, pros, and cons that you should weigh before downloading and installing it. It is a game that can give you hours of fun and entertainment but also cause you some problems and errors. It is up to you to decide whether you want to play this game or not.

            3cee63e6c2
            -
            -
            \ No newline at end of file diff --git a/spaces/svjack/ControlNet-Pose-Chinese/annotator/uniformer/mmcv/utils/timer.py b/spaces/svjack/ControlNet-Pose-Chinese/annotator/uniformer/mmcv/utils/timer.py deleted file mode 100644 index e3db7d497d8b374e18b5297e0a1d6eb186fd8cba..0000000000000000000000000000000000000000 --- a/spaces/svjack/ControlNet-Pose-Chinese/annotator/uniformer/mmcv/utils/timer.py +++ /dev/null @@ -1,118 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from time import time - - -class TimerError(Exception): - - def __init__(self, message): - self.message = message - super(TimerError, self).__init__(message) - - -class Timer: - """A flexible Timer class. - - :Example: - - >>> import time - >>> import annotator.uniformer.mmcv as mmcv - >>> with mmcv.Timer(): - >>> # simulate a code block that will run for 1s - >>> time.sleep(1) - 1.000 - >>> with mmcv.Timer(print_tmpl='it takes {:.1f} seconds'): - >>> # simulate a code block that will run for 1s - >>> time.sleep(1) - it takes 1.0 seconds - >>> timer = mmcv.Timer() - >>> time.sleep(0.5) - >>> print(timer.since_start()) - 0.500 - >>> time.sleep(0.5) - >>> print(timer.since_last_check()) - 0.500 - >>> print(timer.since_start()) - 1.000 - """ - - def __init__(self, start=True, print_tmpl=None): - self._is_running = False - self.print_tmpl = print_tmpl if print_tmpl else '{:.3f}' - if start: - self.start() - - @property - def is_running(self): - """bool: indicate whether the timer is running""" - return self._is_running - - def __enter__(self): - self.start() - return self - - def __exit__(self, type, value, traceback): - print(self.print_tmpl.format(self.since_last_check())) - self._is_running = False - - def start(self): - """Start the timer.""" - if not self._is_running: - self._t_start = time() - self._is_running = True - self._t_last = time() - - def since_start(self): - """Total time since the timer is started. - - Returns (float): Time in seconds. - """ - if not self._is_running: - raise TimerError('timer is not running') - self._t_last = time() - return self._t_last - self._t_start - - def since_last_check(self): - """Time since the last checking. - - Either :func:`since_start` or :func:`since_last_check` is a checking - operation. - - Returns (float): Time in seconds. - """ - if not self._is_running: - raise TimerError('timer is not running') - dur = time() - self._t_last - self._t_last = time() - return dur - - -_g_timers = {} # global timers - - -def check_time(timer_id): - """Add check points in a single line. - - This method is suitable for running a task on a list of items. A timer will - be registered when the method is called for the first time. - - :Example: - - >>> import time - >>> import annotator.uniformer.mmcv as mmcv - >>> for i in range(1, 6): - >>> # simulate a code block - >>> time.sleep(i) - >>> mmcv.check_time('task1') - 2.000 - 3.000 - 4.000 - 5.000 - - Args: - timer_id (str): Timer identifier. - """ - if timer_id not in _g_timers: - _g_timers[timer_id] = Timer() - return 0 - else: - return _g_timers[timer_id].since_last_check() diff --git a/spaces/svjack/stable-diffusion.search.embedding/Lex.py b/spaces/svjack/stable-diffusion.search.embedding/Lex.py deleted file mode 100644 index c091ce1028ab665a359f53f9e22fb5cf4cfd9763..0000000000000000000000000000000000000000 --- a/spaces/svjack/stable-diffusion.search.embedding/Lex.py +++ /dev/null @@ -1,50 +0,0 @@ -import httpx -import random -import string -import uuid -import re - -class Lexica: - def __init__(self, query, negativePrompt="", guidanceScale: int = 7, portrait: bool = True, cookie=None): - self.query = query - self.negativePrompt = negativePrompt - self.guidanceScale = guidanceScale - self.portrait = portrait - self.cookie = cookie - - def images(self): - response = httpx.post("https://lexica.art/api/infinite-prompts", json={ - "text": self.query, - "searchMode": "images", - "source": "search", - "model": "lexica-aperture-v2" - }) - - prompts = [f"https://image.lexica.art/full_jpg/{ids['id']}" for ids in response.json()["images"]] - - return prompts - - def _generate_random_string(self, length): - chars = string.ascii_letters + string.digits - result_str = ''.join(random.choice(chars) for _ in range(length)) - - return result_str - - def generate(self): - response = httpx.post("https://z.lexica.art/api/generator", headers={ - "cookie": self.cookie - }, json={ - "requestId": str(uuid.uuid4()), - "id": self._generate_random_string(20), - "prompt": self.query, - "negativePrompt": self.negativePrompt, - "guidanceScale": self.guidanceScale, - "width": 512 if self.portrait else 768, - "height": 768 if self.portrait else 512, - "enableHiresFix": False, - "model": "lexica-aperture-v2", - "generateSources": [] - }, timeout=50 - ) - - return [f"https://image.lexica.art/full_jpg/{ids['id']}" for ids in response.json()["images"]] diff --git a/spaces/team7/talk_with_wind/efficientat/models/preprocess.py b/spaces/team7/talk_with_wind/efficientat/models/preprocess.py deleted file mode 100644 index 6c2f2995636e56a67d875e93f1d57925e045082f..0000000000000000000000000000000000000000 --- a/spaces/team7/talk_with_wind/efficientat/models/preprocess.py +++ /dev/null @@ -1,67 +0,0 @@ -import torch.nn as nn -import torchaudio -import torch - - -class AugmentMelSTFT(nn.Module): - def __init__(self, n_mels=128, sr=32000, win_length=800, hopsize=320, n_fft=1024, freqm=48, timem=192, - fmin=0.0, fmax=None, fmin_aug_range=10, fmax_aug_range=2000): - torch.nn.Module.__init__(self) - # adapted from: https://github.com/CPJKU/kagglebirds2020/commit/70f8308b39011b09d41eb0f4ace5aa7d2b0e806e - - self.win_length = win_length - self.n_mels = n_mels - self.n_fft = n_fft - self.sr = sr - self.fmin = fmin - if fmax is None: - fmax = sr // 2 - fmax_aug_range // 2 - print(f"Warning: FMAX is None setting to {fmax} ") - self.fmax = fmax - self.hopsize = hopsize - self.register_buffer('window', - torch.hann_window(win_length, periodic=False), - persistent=False) - assert fmin_aug_range >= 1, f"fmin_aug_range={fmin_aug_range} should be >=1; 1 means no augmentation" - assert fmax_aug_range >= 1, f"fmax_aug_range={fmax_aug_range} should be >=1; 1 means no augmentation" - self.fmin_aug_range = fmin_aug_range - self.fmax_aug_range = fmax_aug_range - - self.register_buffer("preemphasis_coefficient", torch.as_tensor([[[-.97, 1]]]), persistent=False) - if freqm == 0: - self.freqm = torch.nn.Identity() - else: - self.freqm = torchaudio.transforms.FrequencyMasking(freqm, iid_masks=True) - if timem == 0: - self.timem = torch.nn.Identity() - else: - self.timem = torchaudio.transforms.TimeMasking(timem, iid_masks=True) - - def forward(self, x): - x = nn.functional.conv1d(x.unsqueeze(1), self.preemphasis_coefficient).squeeze(1) - x = torch.stft(x, self.n_fft, hop_length=self.hopsize, win_length=self.win_length, - center=True, normalized=False, window=self.window, return_complex=False) - x = (x ** 2).sum(dim=-1) # power mag - fmin = self.fmin + torch.randint(self.fmin_aug_range, (1,)).item() - fmax = self.fmax + self.fmax_aug_range // 2 - torch.randint(self.fmax_aug_range, (1,)).item() - # don't augment eval data - if not self.training: - fmin = self.fmin - fmax = self.fmax - - mel_basis, _ = torchaudio.compliance.kaldi.get_mel_banks(self.n_mels, self.n_fft, self.sr, - fmin, fmax, vtln_low=100.0, vtln_high=-500., vtln_warp_factor=1.0) - mel_basis = torch.as_tensor(torch.nn.functional.pad(mel_basis, (0, 1), mode='constant', value=0), - device=x.device) - with torch.cuda.amp.autocast(enabled=False): - melspec = torch.matmul(mel_basis, x) - - melspec = (melspec + 0.00001).log() - - if self.training: - melspec = self.freqm(melspec) - melspec = self.timem(melspec) - - melspec = (melspec + 4.5) / 5. # fast normalization - - return melspec diff --git a/spaces/terfces0erbo/CollegeProjectV2/Abbyy Finereader 12 Crack Serial.md b/spaces/terfces0erbo/CollegeProjectV2/Abbyy Finereader 12 Crack Serial.md deleted file mode 100644 index fd166acc4f50eb13bb99ffb047bc90c5f494bad7..0000000000000000000000000000000000000000 --- a/spaces/terfces0erbo/CollegeProjectV2/Abbyy Finereader 12 Crack Serial.md +++ /dev/null @@ -1,20 +0,0 @@ - -

            How to Crack ABBYY FineReader 12 Professional Edition

            -

            If you are looking for a way to use ABBYY FineReader 12 Professional Edition without paying for a license, you might be tempted to download a crack or a serial key from the internet. However, this is not only illegal, but also risky, as you might expose your computer to malware, viruses, or other threats. Moreover, you might not get the full functionality and performance of the original software, as cracks and serial keys often come with limitations, errors, or bugs.

            -

            Therefore, the best and safest way to use ABBYY FineReader 12 Professional Edition is to purchase a legal license from the official website of ABBYY. By doing so, you will get access to all the features and updates of the software, as well as technical support and customer service. You will also avoid any legal issues or penalties that might arise from using pirated software.

            -

            abbyy finereader 12 crack serial


            DOWNLOAD ::: https://bytlly.com/2uGm2g



            -

            However, if you still want to try ABBYY FineReader 12 Professional Edition for free before buying it, you can download a trial version from the official website of ABBYY. The trial version will allow you to use the software for 30 days with no limitations or restrictions. You will be able to test all the functions and capabilities of the software and see how it works for your needs. After the trial period expires, you will need to purchase a license to continue using the software.

            -

            In conclusion, cracking ABBYY FineReader 12 Professional Edition is not a good idea, as it might harm your computer and violate the law. The best way to use the software is to buy a legal license from the official website of ABBYY. Alternatively, you can download a trial version for free and use it for 30 days.

            - -

            By buying ABBYY FineReader 12 Professional Edition, you will enjoy many benefits that will boost your productivity and efficiency. Some of these benefits are:

            -
              -
            • You will be able to easily achieve superior OCR results with verification and editing tools that allow you to correct any errors or inconsistencies in the recognized text.
            • -
            • You will be able to create searchable digital archives from your scanned documents, PDFs, and images, and organize them according to your preferences. You will also be able to extract text from scanned documents for quoting or reusing in other applications.
            • -
            • You will be able to create e-books for reading on portable devices from your scanned books, magazines, or articles. You can choose from various formats such as EPUB, FB2, or MOBI.
            • -
            • You will be able to save time and resources by using one-click Tasks that enable you to perform common actions with fewer steps. For example, you can scan to Microsoft Word, scan to PDF, or scan and email with just one click.
            • -
            • You will be able to work with documents in almost any language, as ABBYY FineReader 12 Professional Edition supports text recognition in 190 languages, including Arabic, Chinese, Japanese, Korean, and Hebrew.
            • -
            -

            As you can see, buying ABBYY FineReader 12 Professional Edition is a smart investment that will help you work with documents more effectively and conveniently. You can buy it from the official website of ABBYY or from other authorized resellers.

            -

            d5da3c52bf
            -
            -
            \ No newline at end of file diff --git a/spaces/teticio/audio-diffusion/app.py b/spaces/teticio/audio-diffusion/app.py deleted file mode 100644 index 772e86bf8f821bbdc048fad2555bf95b6cdfe62a..0000000000000000000000000000000000000000 --- a/spaces/teticio/audio-diffusion/app.py +++ /dev/null @@ -1,50 +0,0 @@ -import argparse - -import gradio as gr - -from audiodiffusion import AudioDiffusion - - -def generate_spectrogram_audio_and_loop(model_id): - audio_diffusion = AudioDiffusion(model_id=model_id) - image, (sample_rate, - audio) = audio_diffusion.generate_spectrogram_and_audio() - loop = AudioDiffusion.loop_it(audio, sample_rate) - if loop is None: - loop = audio - return image, (sample_rate, audio), (sample_rate, loop) - - -demo = gr.Interface( - fn=generate_spectrogram_audio_and_loop, - title="Audio Diffusion", - description="Generate audio using Huggingface diffusers.\ - The models without 'latent' or 'ddim' give better results but take about \ - 20 minutes without a GPU. For GPU, you can use \ - [colab](https://colab.research.google.com/github/teticio/audio-diffusion/blob/master/notebooks/gradio_app.ipynb) \ - to run this app.", - inputs=[ - gr.Dropdown(label="Model", - choices=[ - "teticio/audio-diffusion-256", - "teticio/audio-diffusion-breaks-256", - "teticio/audio-diffusion-instrumental-hiphop-256", - "teticio/audio-diffusion-ddim-256", - "teticio/latent-audio-diffusion-256", - "teticio/latent-audio-diffusion-ddim-256" - ], - value="teticio/latent-audio-diffusion-ddim-256") - ], - outputs=[ - gr.Image(label="Mel spectrogram", image_mode="L"), - gr.Audio(label="Audio"), - gr.Audio(label="Loop"), - ], - allow_flagging="never") - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--port", type=int) - parser.add_argument("--server", type=int) - args = parser.parse_args() - demo.launch(server_name=args.server or "0.0.0.0", server_port=args.port) diff --git a/spaces/tialenAdioni/chat-gpt-api/logs/Agilent VEE Pro 93 Crackrar A Review of the User Experience and Feedback.md b/spaces/tialenAdioni/chat-gpt-api/logs/Agilent VEE Pro 93 Crackrar A Review of the User Experience and Feedback.md deleted file mode 100644 index 78036ccc903f450ab9b3d2dd920a692063a7d4b0..0000000000000000000000000000000000000000 --- a/spaces/tialenAdioni/chat-gpt-api/logs/Agilent VEE Pro 93 Crackrar A Review of the User Experience and Feedback.md +++ /dev/null @@ -1,124 +0,0 @@ - -

            Agilent VEE Pro 9.3 Crackrar: A Comprehensive Guide

            -

            If you are looking for a way to automate your test and measurement tasks with ease and efficiency, you might have heard of Agilent VEE Pro 9.3 Crackrar. But what is it exactly and how can you use it? In this article, we will answer these questions and more, so you can decide if this software is right for you.

            -

            What is Agilent VEE Pro 9.3?

            -

            Agilent VEE Pro 9.3 is a graphical programming tool that allows you to create and execute test and measurement applications without writing any code. You can use it to control instruments from various manufacturers, perform data acquisition and analysis, generate reports and graphs, and more.

            -

            Agilent VEE Pro 93 Crackrar


            Download ✪✪✪ https://urlcod.com/2uK5sc



            -

            According to Keysight, the developer of Agilent VEE Pro, this software has several features that make it easy to use and powerful, such as:

            -
              -
            • Wide connectivity with GPIB, Serial, LAN and other interfaces
            • -
            • Faster performance with multithreading and multi-core programming
            • -
            • Greater ease of use with more sample programs, SCPI completion, conditional breakpoints, etc.
            • -
            • Support for latest industry standards such as LXI and database integration
            • -
            -

            What is a crackrar file?

            -

            A crackrar file is a compressed file that contains a cracked version of a software program. A cracked version is a modified version that bypasses the original license protection and allows you to use the software without paying for it.

            -

            Agilent VEE Pro 9.3 crack download
            -Agilent VEE Pro 9.3 crack torrent
            -Agilent VEE Pro 9.3 crack keygen
            -Agilent VEE Pro 9.3 crack serial
            -Agilent VEE Pro 9.3 crack patch
            -Agilent VEE Pro 9.3 crack license
            -Agilent VEE Pro 9.3 crack activation
            -Agilent VEE Pro 9.3 crack full version
            -Agilent VEE Pro 9.3 crack free
            -Agilent VEE Pro 9.3 crack rar
            -Agilent VEE Pro 9.3 crack zip
            -Agilent VEE Pro 9.3 crack exe
            -Agilent VEE Pro 9.3 crack iso
            -Agilent VEE Pro 9.3 crack nulled
            -Agilent VEE Pro 9.3 crack hacked
            -Agilent VEE Pro 9.3 crack weebly
            -Agilent VEE Pro 9.3 crack wixsite
            -Agilent VEE Pro 9.3 crack yolasite
            -Agilent VEE Pro 9.3 crack soundcloud
            -Agilent VEE Pro 9.3 crack lumion
            -Agilent VEE Pro 9.3 keygen download
            -Agilent VEE Pro 9.3 keygen torrent
            -Agilent VEE Pro 9.3 keygen serial
            -Agilent VEE Pro 9.3 keygen patch
            -Agilent VEE Pro 9.3 keygen license
            -Agilent VEE Pro 9.3 keygen activation
            -Agilent VEE Pro 9.3 keygen full version
            -Agilent VEE Pro 9.3 keygen free
            -Agilent VEE Pro 9.3 keygen rar
            -Agilent VEE Pro 9.3 keygen zip
            -Agilent VEE Pro 9.3 keygen exe
            -Agilent VEE Pro 9.3 keygen iso
            -Agilent VEE Pro 9.3 keygen nulled
            -Agilent VEE Pro 9.3 keygen hacked
            -Agilent VEE Pro 9.3 serial download
            -Agilent VEE Pro 9.3 serial torrent
            -Agilent VEE Pro 9.3 serial patch
            -Agilent VEE Pro 9.3 serial license
            -Agilent VEE Pro 9.3 serial activation
            -Agilent VEE Pro 9.3 serial full version
            -Agilent VEE Pro 9.3 serial free
            -Agilent VEE Pro 9.3 serial rar
            -Agilent VEE Pro 9.3 serial zip
            -Agilent VEE Pro 9.3 serial exe
            -Agilent VEE Pro 9.3 serial iso
            -Agilent VEE Pro 9.3 serial nulled
            -Agilent VEE Pro 9.3 serial hacked
            -How to install agilent vee pro 93 crackrar?
            -Where to download agilent vee pro 93 crackrar?
            -What is agilent vee pro and why do you need it?

            -

            A crackrar file usually consists of two parts: the setup.exe file that installs the software on your PC, and the keygen.exe file that generates a license key for activating the software.

            -

            Why use Agilent VEE Pro 9.3 Crackrar?

            -

            The main reason why some people use Agilent VEE Pro 9.3 Crackrar is to save money. The official version of Agilent VEE Pro 9.3 costs $1,995 for a single license, which might be too expensive for some users who only need it for occasional or personal use.

            -

            Another reason why some people use Agilent VEE Pro 9.3 Crackrar is to test the software before buying it. Although Keysight offers a free trial version of Agilent VEE Pro for 30 days, some users might want to extend their evaluation period or try out all the features without any limitations.

            -

            How to download and install Agilent VEE Pro 9.3 Crackrar

            -

            If you decide to use Agilent VEE Pro 9.3 Crackrar, you need to follow these steps:

            -

            Step 1: Download the crackrar file from a reliable source

            -

            The first thing you need to do is to find a trustworthy website that offers the download link for Agilent VEE Pro 9.3 Crackrar. You can search on Google or other search engines for keywords like "Agilent VEE Pro 9.3 Crackrar download" or "Agilent VEE Pro 9.3 Crackrar free". However, be careful not to click on any suspicious or malicious links that might harm your PC or steal your personal information.

            -

            One of the websites that claims to provide Agilent VEE Pro 9.3 Crackrar is https://cracksgurus.com/crack/Agilent-VEE-Pro-v93-keygen-by-NiTROUS-bee6b0a6f7.html. We do not endorse or recommend this website or any other website that offers illegal downloads of software programs. Use them at your own risk.

            -

            Step 2: Extract the crackrar file using WinRAR or other software

            -

            After downloading the crackrar file, you need to extract its contents using WinRAR or other software that can handle rar files. You can download WinRAR from https://www.win-rar.com/download.html. To extract the crackrar file, right-click on it and select "Extract here" or "Extract to folder". You should see two files: setup.exe and keygen.exe.

            -

            Step 3: Run the setup.exe file and follow the instructions

            -

            To install Agilent VEE Pro 9.3 on your PC, run the setup.exe file and follow the instructions on the screen. You might need to accept some terms and conditions, choose a destination folder, select some components, etc.

            -

            Step 4: Enter the license key or use the keygen to generate one

            -

            To activate Agilent VEE Pro 9.3, you need to enter a valid license key or use the keygen.exe file to generate one. To enter a license key, open Agilent VEE Pro after installation and go to Help > License Manager > Add License Key > Enter License Key Manually > OK.

            -

            To generate a license key, run the keygen.exe file and click on Generate button. You should see a random string of characters that represents your license key. Copy it and paste it in the License Key field in Agilent VEE Pro License Manager.

            -

            How to use Agilent VEE Pro 9.3 Crackrar for test and measurement tasks

            -

            If you successfully installed and activated Agilent VEE Pro 9.3 Crackrar on your PC, you can start using it for your test and measurement tasks.

            -

            Step 1: Connect your instruments to your PC using GPIB, Serial, LAN or other interfaces

            -

            To control your instruments from Agilent VEE Pro, you need to connect them to your PC using appropriate interfaces such as GPIB (General Purpose Interface Bus), Serial (RS-232), LAN (Local Area Network) or others depending on your instruments' specifications.

            -

            You also need to install Keysight IO Libraries Suite on your PC if you haven't already done so. This software enables communication between your PC and your instruments via various interfaces.

            -

            Step 2: Launch Agilent VEE Pro 9.3 and create a new project or open an existing one

            -

            To start working with Agilent VEE Pro, launch it from your desktop or start menu shortcut and create a new project by clicking on File > New > Project > OK or open an existing project by clicking on File > Open > Project > Browse > OK.

            -

            A project in Agilent VEE Pro consists of one or more worksheets where you can design your workflow and data analysis using graphical objects called devices.

            -

            Step 3: Use the graphical programming tool to design your workflow and data analysis

            -```html

            Step 4: Run your project and view the results in real time or export them to other formats

            -

            To run your project and view the results in Agilent VEE Pro, you need to click on the Run button on the toolbar or press F5 on your keyboard. You can also use the Debug mode to step through your project and check for errors or bugs.

            -

            As your project runs, you can see the results on the devices that display data such as graphs, tables, meters, etc. You can also export your results to other formats such as Excel, Word, HTML, XML, etc. by using the File > Export menu or the Export device.

            -

            Benefits and drawbacks of using Agilent VEE Pro 9.3 Crackrar

            -

            Using Agilent VEE Pro 9.3 Crackrar has some advantages and disadvantages that you should be aware of before deciding to use it.

            -

            Benefits

            -
              -
            • You can save money by using a cracked version of Agilent VEE Pro instead of buying the official version.
            • -
            • You can test the software for a longer period of time or with full features without any limitations.
            • -
            • You can enjoy the benefits of Agilent VEE Pro such as easy graphical programming, wide connectivity, faster performance, etc.
            • -
            -

            Drawbacks

            -
              -
            • You might violate the intellectual property rights of Keysight by using a cracked version of their software without their permission.
            • -
            • You might expose your PC to viruses, malware, spyware or other threats by downloading and installing a crackrar file from an untrusted source.
            • -
            • You might encounter errors, bugs, crashes or compatibility issues by using a cracked version of Agilent VEE Pro that might not be updated or supported by Keysight.
            • -
            • You might miss out on some features, updates or technical support that are only available for the official version of Agilent VEE Pro.
            • -
            -

            Conclusion

            -

            In conclusion, Agilent VEE Pro 9.3 Crackrar is a graphical programming tool that allows you to automate your test and measurement tasks without writing any code. It has many features that make it easy to use and powerful, such as wide connectivity, faster performance, greater ease of use, etc.

            -

            However, using Agilent VEE Pro 9.3 Crackrar also has some risks and drawbacks that you should consider before using it. You might violate the intellectual property rights of Keysight, expose your PC to threats, encounter errors or bugs, or miss out on some features or support.

            -

            Therefore, we recommend that you use Agilent VEE Pro 9.3 Crackrar only for testing purposes and not for commercial or professional use. If you like the software and want to use it legally and safely, you should buy the official version of Agilent VEE Pro from Keysight or their authorized sales partners.

            -

            If you want to learn more about Agilent VEE Pro and how to use it for your test and measurement tasks, you can visit https://www.keysight.com/us/en/product/W4000D/vee-pro-9-33.html or check out some of the code samples and tutorials available online.

            -

            FAQs

            -
              -
            1. What is the difference between Agilent VEE Pro and Agilent VEE Express?
              Agilent VEE Express is a free version of Agilent VEE Pro that has limited features and functionality. It does not support database integration, LXI compliance, multithreading or multi-core programming. It also has fewer sample programs and devices than Agilent VEE Pro.
            2. -
            3. How can I get a free trial version of Agilent VEE Pro?
              You can get a free trial version of Agilent VEE Pro for 30 days by visiting https://www.keysight.com/us/en/lib/software-detail/computer-software/keysight-vee-pro-software-1525226.html and clicking on "Download". You will need to fill out a form with your contact information and agree to some terms and conditions before downloading the software.
            4. -
            5. How can I upgrade my existing version of Agilent VEE Pro to Agilent VEE Pro 9.33?
              If you have an existing version of Agilent VEE Pro (9.0, 9.2, 9.3 or 9.32), you can upgrade it to Agilent VEE Pro 9.33 for free by visiting https://www.keysight.com/us/en/product/W4000D/vee-pro-9-33.html and clicking on "Download". You will need to enter your license key or serial number before downloading the software.
            6. -
            7. How can I get technical support for Agilent VEE Pro?
              If you have any questions or issues with Agilent VEE Pro, you can get technical support from Keysight by visiting https://www.keysight.com/us/en/contact.html and choosing your region and product category. You can also access online resources such as manuals, videos, forums, etc. by visiting https://www.keysight.com/us/en/support.html.
            8. -
            9. How can I learn more about graphical programming with Agilent VEE Pro?
              If you want to learn more about graphical programming with Agilent VEE Pro, you can check out some of the online courses available from Keysight University at https://www.keysight.com/us/en/services/education-services/keysight-university.html. You can also find some books and articles on graphical programming with Agilent VEE Pro at https://www.amazon.com/s?k=agilent+vee+pro&i=stripbooks&ref=nb_sb_noss.
            10. -
            -

            0a6ba089eb
            -
            -
            \ No newline at end of file diff --git a/spaces/tialenAdioni/chat-gpt-api/logs/Download TPW 1.5 for Windows 7 64 bit An Alternative to Turbo Pascal 7.md b/spaces/tialenAdioni/chat-gpt-api/logs/Download TPW 1.5 for Windows 7 64 bit An Alternative to Turbo Pascal 7.md deleted file mode 100644 index 315e89273e2d4cea8cd38831c8a961c042e99089..0000000000000000000000000000000000000000 --- a/spaces/tialenAdioni/chat-gpt-api/logs/Download TPW 1.5 for Windows 7 64 bit An Alternative to Turbo Pascal 7.md +++ /dev/null @@ -1,67 +0,0 @@ - -

            How to Download TPW 1.5 for Windows 7 64 Bit

            -

            If you are looking for a way to download TPW 1.5 for Windows 7 64 Bit, you have come to the right place. In this article, we will show you what TPW 1.5 is, why you need it for Windows 7 64 Bit, how to download it from a reliable source, how to install it on your computer, how to run it on your system, and what are some alternatives to TPW 1.5 for Windows 7 64 Bit.

            -

            TPW stands for Turbo Pascal for Windows, and it is a Pascal compiler and integrated development environment (IDE) that was developed by Borland in the early 1990s. It was one of the most popular tools for Pascal programming at that time, and it had many features that made it easy and convenient to use.

            -

            download tpw 1.5 for windows 7 64 bit


            Downloadhttps://urlcod.com/2uK3To



            -

            What is TPW 1.5?

            -

            A brief introduction to TPW 1.5 and its features

            -

            TPW 1.5 is the latest version of Turbo Pascal for Windows, and it was released in 1992. It supports both DOS and Windows applications, and it has a graphical user interface (GUI) that allows you to create and edit your source code, compile and debug your programs, and run them on your system.

            -

            Some of the features of TPW 1.5 are:

            -

            download tpw 15 exe for windows 7 64 bit[^1^]
            -download turbo pascal for windows 1.5 64 bit[^2^]
            -download pascal xe tpw 1.5 alternative for windows 7[^3^]
            -download tpw 1.5 for windows 7 free
            -download tpw 1.5 for windows 7 full version
            -download tpw 1.5 for windows 7 with crack
            -download tpw 1.5 for windows 7 offline installer
            -download tpw 1.5 for windows 7 zip file
            -download tpw 1.5 for windows 7 portable
            -download tpw 1.5 for windows 7 software informer
            -download tpw 1.5 for windows 7 youtube tutorial
            -download tpw 1.5 for windows 7 borland turbo pascal
            -download tpw 1.5 for windows 7 kest soft
            -download tpw 1.5 for windows 7 ide
            -download tpw 1.5 for windows 7 compiler
            -download tpw 1.5 for windows 7 programming language
            -download tpw 1.5 for windows 7 dosbox
            -download tpw 1.5 for windows 7 cp/m-86
            -download tpw 1.5 for windows 7 vulkan sdk
            -download tpw 1.5 for windows 7 nvidia cuda toolkit
            -download tpw 1.5 for windows 7 simply fortran
            -download tpw 1.5 for windows 7 avr burn-o-mat
            -download tpw 1.5 for windows 7 nicelabel sdk
            -download tpw 1.5 for windows 7 pcomm lite
            -download tpw 1.5 for windows 7 ezy pascal
            -download tpw 1.5 for windows 7 pic micro pascal
            -download tpw 1.5 for windows 7 relocates compiled code
            -download tpw 1.5 for windows 7 executable eprom flash ram
            -download tpw 1.5 for windows 7 write code develop programs
            -download tpw 1.5 for windows 7 view values stored variables
            -download tpw 1.5 for windows 7 launch preset script usb device
            -download tpw 1.5 for windows 7 blackbox iso burner
            -download tpw

            -
              -
            • It supports Object Pascal, a version of Pascal that supports object-oriented programming (OOP).
            • -
            • It has a built-in debugger that lets you set breakpoints, watch variables, inspect memory, and step through your code.
            • -
            • It has a code editor that has syntax highlighting, auto-indentation, code completion, code templates, and search and replace functions.
            • -
            • It has a project manager that helps you organize your files and resources into projects.
            • -
            • It has a resource editor that lets you create and edit graphical resources such as icons, cursors, bitmaps, menus, dialogs, and fonts.
            • -
            • It has a form designer that lets you create and edit graphical user interfaces (GUIs) for your applications.
            • -
            • It has a library manager that lets you create and manage libraries of reusable code.
            • -
            • It has a help system that provides you with documentation and examples for the Pascal language and the TPW environment.
            • -
            -

            Why do you need TPW 1.5 for Windows 7 64 Bit?

            -

            The benefits of using TPW 1.5 on Windows 7 64 Bit

            -

            If you are still using Windows 7 on your computer, you might be wondering why you need TPW 1.5 for Windows 7 64 Bit. There are several reasons why TPW 1.5 is a good choice for Pascal programming on Windows 7:

            -
              -
            • TPW 1.5 is compatible with Windows 7, unlike newer versions of Pascal compilers and IDEs that require newer versions of Windows.
            • -
            • TPW 1.5 is lightweight and fast, unlike newer versions of Pascal compilers and IDEs that are heavier and slower.
            • -
            • TPW 1.5 is easy to use and learn, unlike newer versions of Pascal compilers and IDEs that are more complex and difficult.
            • -
            • TPW 1.5 is free and open source, unlike newer versions of Pascal compilers and IDEs that are expensive or proprietary.
            • -
            -

            The compatibility issues of TPW 1.5 with newer versions of Windows

            -application that provides a comprehensive set of tools and features for software development. An IDE typically consists of a code editor, a compiler, a debugger, a project manager, a resource editor, a form designer, a help system, and other components that help you create and manage your software projects.

            -

            What is SourceForge.net?

            -

            SourceForge.net is a website that hosts many open source projects and software. It provides various services and resources for developers and users such as code hosting, version control, bug tracking, mailing lists, forums, wikis, downloads, reviews, and ratings. It is one of the largest and oldest platforms for open source software development and distribution.

            0a6ba089eb
            -
            -
            \ No newline at end of file diff --git a/spaces/tialenAdioni/chat-gpt-api/logs/Hanuman Chalisa Amitabh Bachan Download Mp3 [BETTER].md b/spaces/tialenAdioni/chat-gpt-api/logs/Hanuman Chalisa Amitabh Bachan Download Mp3 [BETTER].md deleted file mode 100644 index 8180fac11483016e4dec8108440617632abd6afe..0000000000000000000000000000000000000000 --- a/spaces/tialenAdioni/chat-gpt-api/logs/Hanuman Chalisa Amitabh Bachan Download Mp3 [BETTER].md +++ /dev/null @@ -1,29 +0,0 @@ - -

            How to Download Hanuman Chalisa by Amitabh Bachchan MP3 Song Online

            -

            Hanuman Chalisa is a devotional hymn dedicated to Lord Hanuman, the monkey god who is believed to be an incarnation of Lord Shiva and a devotee of Lord Rama. Hanuman Chalisa consists of 40 verses that praise the virtues, deeds and powers of Hanuman. It is said that reciting Hanuman Chalisa can bring peace, prosperity and protection to the devotees.

            -

            hanuman chalisa amitabh bachan download mp3


            DOWNLOADhttps://urlcod.com/2uK69G



            -

            There are many versions of Hanuman Chalisa sung by various singers and artists, but one of the most popular and powerful ones is by Amitabh Bachchan, the legendary Bollywood actor. Amitabh Bachchan has lent his voice to Hanuman Chalisa in a soulful and majestic manner, creating a divine atmosphere for the listeners. His rendition of Hanuman Chalisa has been appreciated by millions of fans and followers across the world.

            -

            If you want to download Hanuman Chalisa by Amitabh Bachchan MP3 song online, you can follow these simple steps:

            -
              -
            1. Go to Gaana.com, one of the leading music streaming platforms in India.
            2. -
            3. Search for "Hanuman Chalisa by Amitabh Bachchan" in the search bar or browse through the Hindi songs category.
            4. -
            5. Select the song from the list of results and click on the play button to listen to it online.
            6. -
            7. If you want to download the song offline, you need to have a Gaana Plus subscription, which costs Rs. 99 per month or Rs. 399 per year. You can also get a free trial for 30 days if you are a new user.
            8. -
            9. Once you have a Gaana Plus subscription, you can click on the download icon next to the song and choose the quality of the MP3 file. You can also download the entire album of Hanuman Chalisa by Amitabh Bachchan if you wish.
            10. -
            11. The downloaded song will be saved in your Gaana app library and you can access it anytime without internet connection.
            12. -
            -

            Alternatively, you can also download Hanuman Chalisa by Amitabh Bachchan MP3 song online from other sources such as Bhakti Gaane or YouTube, but make sure that you are downloading from a legal and safe website. You may also need a third-party software or app to convert the video file into an MP3 file.

            -

            Hanuman Chalisa by Amitabh Bachchan is a beautiful and powerful song that can uplift your spirit and fill your heart with devotion. Download it today and enjoy listening to it anytime and anywhere.

            -

            - -

            Some of the benefits of listening to Hanuman Chalisa by Amitabh Bachchan are:

            -
              -
            • It can help you overcome fear, anxiety and stress by invoking the courage and confidence of Hanuman.
            • -
            • It can help you remove obstacles and difficulties in your life by seeking the blessings and grace of Hanuman.
            • -
            • It can help you increase your concentration, memory and intelligence by following the example of Hanuman, who is considered to be the epitome of wisdom and knowledge.
            • -
            • It can help you develop devotion, loyalty and love for Lord Rama and Lord Hanuman, who are the ideal role models for every human being.
            • -
            • It can help you attain peace, happiness and prosperity by harmonizing your body, mind and soul with the divine vibrations of Hanuman Chalisa.
            • -
            -

            Hanuman Chalisa by Amitabh Bachchan is not just a song, but a mantra that can transform your life. It can connect you with the supreme power and energy of Lord Hanuman, who is always ready to help his devotees. It can inspire you to live a life of service, sacrifice and dedication. It can fill your heart with joy, gratitude and faith. It can make you a better person and a better devotee.

            e93f5a0c3f
            -
            -
            \ No newline at end of file diff --git a/spaces/tialenAdioni/chat-gpt-api/logs/Jaane Tu... Ya Jaane Na In Hindi Movie.md b/spaces/tialenAdioni/chat-gpt-api/logs/Jaane Tu... Ya Jaane Na In Hindi Movie.md deleted file mode 100644 index ce35bdf390eeb35984c3b550838dc0b621486878..0000000000000000000000000000000000000000 --- a/spaces/tialenAdioni/chat-gpt-api/logs/Jaane Tu... Ya Jaane Na In Hindi Movie.md +++ /dev/null @@ -1,27 +0,0 @@ - -Here is a possible title and article for the keyword "Jaane Tu... Ya Jaane Na In Hindi Movie": - -

            Jaane Tu... Ya Jaane Na: A Romantic Comedy That Will Make You Laugh and Cry

            -

            Jaane Tu... Ya Jaane Na is a 2008 Hindi movie directed by Abbas Tyrewala and produced by Aamir Khan. It stars Imran Khan and Genelia D'Souza as two college friends who fall in love with each other, but are too afraid to admit it. The movie also features a talented ensemble cast of supporting actors, such as Ratna Pathak Shah, Naseeruddin Shah, Arbaaz Khan, Sohail Khan, and Paresh Rawal.

            -

            The movie is a refreshing take on the romantic comedy genre, with witty dialogues, catchy songs, and realistic characters. The movie explores the themes of friendship, love, family, and identity, as the protagonists go through various ups and downs in their relationship. The movie also has a twist ending that will surprise and delight the viewers.

            -

            Jaane Tu... Ya Jaane Na In Hindi Movie


            Download Filehttps://urlcod.com/2uKaLS



            -

            Jaane Tu... Ya Jaane Na was a critical and commercial success, earning positive reviews from critics and audiences alike. It was one of the highest-grossing movies of 2008 and won several awards, including the Filmfare Award for Best Debut (Male) for Imran Khan. The movie also launched the careers of Imran Khan and Genelia D'Souza, who became popular stars in Bollywood.

            -

            If you are looking for a fun and heartwarming movie to watch with your loved ones, Jaane Tu... Ya Jaane Na is the perfect choice. You will laugh, cry, and sing along with the characters as they discover the true meaning of love. Jaane Tu... Ya Jaane Na is available to stream on Netflix, Amazon Prime Video, and YouTube.

            Here is a possible continuation of the article: - -

            Jaane Tu... Ya Jaane Na is not just a movie, but a phenomenon that has captured the hearts of millions of fans. The movie is full of memorable scenes, dialogues, and trivia that make it a cult classic. Here are some of the interesting facts about the movie that you may not know:

            -
              -
            • The movie was originally titled "Jai", but was changed to "Jaane Tu... Ya Jaane Na" after Aamir Khan suggested it.
            • -
            • The movie marked the debut of Imran Khan, who is Aamir Khan's nephew and Mansoor Khan's son. Imran had previously appeared as a child actor in Qayamat Se Qayamat Tak and Jo Jeeta Wohi Sikandar.
            • -
            • The movie also marked the debut of Prateik Babbar, who is the son of late actress Smita Patil and actor-politician Raj Babbar. Prateik played the role of Amit, Aditi's brother, who has a crush on Meghna, Jai's girlfriend.
            • -
            • The movie featured cameo appearances by Aamir Khan and his wife Kiran Rao as two passengers at the airport who witness Jai's heroic act. Aamir also lent his voice for the narration of the movie.
            • -
            • The movie had a reference to Aamir Khan's iconic song "Papa Kehte Hain" from Qayamat Se Qayamat Tak. In one scene, Jai sings the song to mock Aditi's father, who disapproves of their friendship.
            • -
            • The movie had a reference to another cult classic, Dil Chahta Hai. In one scene, Jai and Aditi are seen watching the movie at a theatre and commenting on it.
            • -
            • The movie had a reference to Zorro, the fictional masked vigilante. Jai's grandfather wanted to name him Zoravar aka Zorro, and Jai also dreams of being Zorro and saving Aditi from danger.
            • -
            • The movie had a reference to Spider-Man, the popular superhero. In one scene, Jai and Meghna watch Spider-Man on their first date and share an upside-down kiss like Spider-Man and Mary Jane.
            • -
            • The movie had a reference to Sholay, the legendary Bollywood film. In one scene, Jai and Aditi ride a bike with a sidecar like Jai and Veeru from Sholay.
            • -
            • The movie had a reference to Titanic, the epic romance film. In one scene, Jai and Aditi pose like Jack and Rose on the bow of a ship.
            • -
            -

            Jaane Tu... Ya Jaane Na is a movie that will make you laugh, cry, and fall in love with its characters. It is a movie that celebrates friendship, love, and life. It is a movie that you can watch over and over again and never get bored. Jaane Tu... Ya Jaane Na is a movie that you should not miss.

            -

            7196e7f11a
            -
            -
            \ No newline at end of file diff --git a/spaces/tomandandy/MusicGen3/audiocraft/quantization/base.py b/spaces/tomandandy/MusicGen3/audiocraft/quantization/base.py deleted file mode 100644 index 1b16c130d266fbd021d3fc29bb9f98c33dd3c588..0000000000000000000000000000000000000000 --- a/spaces/tomandandy/MusicGen3/audiocraft/quantization/base.py +++ /dev/null @@ -1,107 +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. - -""" -Base class for all quantizers. -""" - -from dataclasses import dataclass, field -import typing as tp - -import torch -from torch import nn - - -@dataclass -class QuantizedResult: - x: torch.Tensor - codes: torch.Tensor - bandwidth: torch.Tensor # bandwidth in kb/s used, per batch item. - penalty: tp.Optional[torch.Tensor] = None - metrics: dict = field(default_factory=dict) - - -class BaseQuantizer(nn.Module): - """Base class for quantizers. - """ - - def forward(self, x: torch.Tensor, frame_rate: int) -> QuantizedResult: - """ - Given input tensor x, returns first the quantized (or approximately quantized) - representation along with quantized codes, bandwidth, and any penalty term for the loss. - Finally, this returns a dict of metrics to update logging etc. - Frame rate must be passed so that the bandwidth is properly computed. - """ - raise NotImplementedError() - - def encode(self, x: torch.Tensor) -> torch.Tensor: - """Encode a given input tensor with the specified sample rate at the given bandwidth. - """ - raise NotImplementedError() - - def decode(self, codes: torch.Tensor) -> torch.Tensor: - """Decode the given codes to the quantized representation. - """ - raise NotImplementedError() - - @property - def total_codebooks(self): - """Total number of codebooks. - """ - raise NotImplementedError() - - @property - def num_codebooks(self): - """Number of active codebooks. - """ - raise NotImplementedError() - - def set_num_codebooks(self, n: int): - """Set the number of active codebooks. - """ - raise NotImplementedError() - - -class DummyQuantizer(BaseQuantizer): - """Fake quantizer that actually does not perform any quantization. - """ - def __init__(self): - super().__init__() - - def forward(self, x: torch.Tensor, frame_rate: int): - q = x.unsqueeze(1) - return QuantizedResult(x, q, torch.tensor(q.numel() * 32 * frame_rate / 1000 / len(x)).to(x)) - - def encode(self, x: torch.Tensor) -> torch.Tensor: - """Encode a given input tensor with the specified sample rate at the given bandwidth. - In the case of the DummyQuantizer, the codes are actually identical - to the input and resulting quantized representation as no quantization is done. - """ - return x.unsqueeze(1) - - def decode(self, codes: torch.Tensor) -> torch.Tensor: - """Decode the given codes to the quantized representation. - In the case of the DummyQuantizer, the codes are actually identical - to the input and resulting quantized representation as no quantization is done. - """ - return codes.squeeze(1) - - @property - def total_codebooks(self): - """Total number of codebooks. - """ - return 1 - - @property - def num_codebooks(self): - """Total number of codebooks. - """ - return self.total_codebooks - - def set_num_codebooks(self, n: int): - """Set the number of active codebooks. - """ - raise AttributeError("Cannot override the number of codebooks for the dummy quantizer") diff --git a/spaces/tomofi/MMOCR/mmocr/apis/inference.py b/spaces/tomofi/MMOCR/mmocr/apis/inference.py deleted file mode 100644 index 1a8d5eec4bf5f007e8f4f6e563b0feb1281ccbd7..0000000000000000000000000000000000000000 --- a/spaces/tomofi/MMOCR/mmocr/apis/inference.py +++ /dev/null @@ -1,238 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import warnings - -import mmcv -import numpy as np -import torch -from mmcv.ops import RoIPool -from mmcv.parallel import collate, scatter -from mmcv.runner import load_checkpoint -from mmdet.core import get_classes -from mmdet.datasets import replace_ImageToTensor -from mmdet.datasets.pipelines import Compose - -from mmocr.models import build_detector -from mmocr.utils import is_2dlist -from .utils import disable_text_recog_aug_test - - -def init_detector(config, checkpoint=None, device='cuda:0', cfg_options=None): - """Initialize a detector from config file. - - Args: - config (str or :obj:`mmcv.Config`): Config file path or the config - object. - checkpoint (str, optional): Checkpoint path. If left as None, the model - will not load any weights. - cfg_options (dict): Options to override some settings in the used - config. - - Returns: - nn.Module: The constructed detector. - """ - if isinstance(config, str): - config = mmcv.Config.fromfile(config) - elif not isinstance(config, mmcv.Config): - raise TypeError('config must be a filename or Config object, ' - f'but got {type(config)}') - if cfg_options is not None: - config.merge_from_dict(cfg_options) - if config.model.get('pretrained'): - config.model.pretrained = None - config.model.train_cfg = None - model = build_detector(config.model, test_cfg=config.get('test_cfg')) - if checkpoint is not None: - checkpoint = load_checkpoint(model, checkpoint, map_location='cpu') - if 'CLASSES' in checkpoint.get('meta', {}): - model.CLASSES = checkpoint['meta']['CLASSES'] - else: - warnings.simplefilter('once') - warnings.warn('Class names are not saved in the checkpoint\'s ' - 'meta data, use COCO classes by default.') - model.CLASSES = get_classes('coco') - model.cfg = config # save the config in the model for convenience - model.to(device) - model.eval() - return model - - -def model_inference(model, - imgs, - ann=None, - batch_mode=False, - return_data=False): - """Inference image(s) with the detector. - - Args: - model (nn.Module): The loaded detector. - imgs (str/ndarray or list[str/ndarray] or tuple[str/ndarray]): - Either image files or loaded images. - batch_mode (bool): If True, use batch mode for inference. - ann (dict): Annotation info for key information extraction. - return_data: Return postprocessed data. - Returns: - result (dict): Predicted results. - """ - - if isinstance(imgs, (list, tuple)): - is_batch = True - if len(imgs) == 0: - raise Exception('empty imgs provided, please check and try again') - if not isinstance(imgs[0], (np.ndarray, str)): - raise AssertionError('imgs must be strings or numpy arrays') - - elif isinstance(imgs, (np.ndarray, str)): - imgs = [imgs] - is_batch = False - else: - raise AssertionError('imgs must be strings or numpy arrays') - - is_ndarray = isinstance(imgs[0], np.ndarray) - - cfg = model.cfg - - if batch_mode: - cfg = disable_text_recog_aug_test(cfg, set_types=['test']) - - device = next(model.parameters()).device # model device - - if cfg.data.test.get('pipeline', None) is None: - if is_2dlist(cfg.data.test.datasets): - cfg.data.test.pipeline = cfg.data.test.datasets[0][0].pipeline - else: - cfg.data.test.pipeline = cfg.data.test.datasets[0].pipeline - if is_2dlist(cfg.data.test.pipeline): - cfg.data.test.pipeline = cfg.data.test.pipeline[0] - - if is_ndarray: - cfg = cfg.copy() - # set loading pipeline type - cfg.data.test.pipeline[0].type = 'LoadImageFromNdarray' - - cfg.data.test.pipeline = replace_ImageToTensor(cfg.data.test.pipeline) - test_pipeline = Compose(cfg.data.test.pipeline) - - datas = [] - for img in imgs: - # prepare data - if is_ndarray: - # directly add img - data = dict( - img=img, - ann_info=ann, - img_info=dict(width=img.shape[1], height=img.shape[0]), - bbox_fields=[]) - else: - # add information into dict - data = dict( - img_info=dict(filename=img), - img_prefix=None, - ann_info=ann, - bbox_fields=[]) - if ann is not None: - data.update(dict(**ann)) - - # build the data pipeline - data = test_pipeline(data) - # get tensor from list to stack for batch mode (text detection) - if batch_mode: - if cfg.data.test.pipeline[1].type == 'MultiScaleFlipAug': - for key, value in data.items(): - data[key] = value[0] - datas.append(data) - - if isinstance(datas[0]['img'], list) and len(datas) > 1: - raise Exception('aug test does not support ' - f'inference with batch size ' - f'{len(datas)}') - - data = collate(datas, samples_per_gpu=len(imgs)) - - # process img_metas - if isinstance(data['img_metas'], list): - data['img_metas'] = [ - img_metas.data[0] for img_metas in data['img_metas'] - ] - else: - data['img_metas'] = data['img_metas'].data - - if isinstance(data['img'], list): - data['img'] = [img.data for img in data['img']] - if isinstance(data['img'][0], list): - data['img'] = [img[0] for img in data['img']] - else: - data['img'] = data['img'].data - - # for KIE models - if ann is not None: - data['relations'] = data['relations'].data[0] - data['gt_bboxes'] = data['gt_bboxes'].data[0] - data['texts'] = data['texts'].data[0] - data['img'] = data['img'][0] - data['img_metas'] = data['img_metas'][0] - - if next(model.parameters()).is_cuda: - # scatter to specified GPU - data = scatter(data, [device])[0] - else: - for m in model.modules(): - assert not isinstance( - m, RoIPool - ), 'CPU inference with RoIPool is not supported currently.' - - # forward the model - with torch.no_grad(): - results = model(return_loss=False, rescale=True, **data) - - if not is_batch: - if not return_data: - return results[0] - return results[0], datas[0] - else: - if not return_data: - return results - return results, datas - - -def text_model_inference(model, input_sentence): - """Inference text(s) with the entity recognizer. - - Args: - model (nn.Module): The loaded recognizer. - input_sentence (str): A text entered by the user. - - Returns: - result (dict): Predicted results. - """ - - assert isinstance(input_sentence, str) - - cfg = model.cfg - if cfg.data.test.get('pipeline', None) is None: - if is_2dlist(cfg.data.test.datasets): - cfg.data.test.pipeline = cfg.data.test.datasets[0][0].pipeline - else: - cfg.data.test.pipeline = cfg.data.test.datasets[0].pipeline - if is_2dlist(cfg.data.test.pipeline): - cfg.data.test.pipeline = cfg.data.test.pipeline[0] - test_pipeline = Compose(cfg.data.test.pipeline) - data = {'text': input_sentence, 'label': {}} - - # build the data pipeline - data = test_pipeline(data) - if isinstance(data['img_metas'], dict): - img_metas = data['img_metas'] - else: - img_metas = data['img_metas'].data - - assert isinstance(img_metas, dict) - img_metas = { - 'input_ids': img_metas['input_ids'].unsqueeze(0), - 'attention_masks': img_metas['attention_masks'].unsqueeze(0), - 'token_type_ids': img_metas['token_type_ids'].unsqueeze(0), - 'labels': img_metas['labels'].unsqueeze(0) - } - # forward the model - with torch.no_grad(): - result = model(None, img_metas, return_loss=False) - return result diff --git a/spaces/tomofi/MMOCR/mmocr/datasets/pipelines/transform_wrappers.py b/spaces/tomofi/MMOCR/mmocr/datasets/pipelines/transform_wrappers.py deleted file mode 100644 index c85f3d115082fb3c567e19fd173d886881a1e118..0000000000000000000000000000000000000000 --- a/spaces/tomofi/MMOCR/mmocr/datasets/pipelines/transform_wrappers.py +++ /dev/null @@ -1,128 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import inspect -import random - -import mmcv -import numpy as np -import torchvision.transforms as torchvision_transforms -from mmcv.utils import build_from_cfg -from mmdet.datasets.builder import PIPELINES -from mmdet.datasets.pipelines import Compose -from PIL import Image - - -@PIPELINES.register_module() -class OneOfWrapper: - """Randomly select and apply one of the transforms, each with the equal - chance. - - Warning: - Different from albumentations, this wrapper only runs the selected - transform, but doesn't guarantee the transform can always be applied to - the input if the transform comes with a probability to run. - - Args: - transforms (list[dict|callable]): Candidate transforms to be applied. - """ - - def __init__(self, transforms): - assert isinstance(transforms, list) or isinstance(transforms, tuple) - assert len(transforms) > 0, 'Need at least one transform.' - self.transforms = [] - for t in transforms: - if isinstance(t, dict): - self.transforms.append(build_from_cfg(t, PIPELINES)) - elif callable(t): - self.transforms.append(t) - else: - raise TypeError('transform must be callable or a dict') - - def __call__(self, results): - return random.choice(self.transforms)(results) - - def __repr__(self): - repr_str = self.__class__.__name__ - repr_str += f'(transforms={self.transforms})' - return repr_str - - -@PIPELINES.register_module() -class RandomWrapper: - """Run a transform or a sequence of transforms with probability p. - - Args: - transforms (list[dict|callable]): Transform(s) to be applied. - p (int|float): Probability of running transform(s). - """ - - def __init__(self, transforms, p): - assert 0 <= p <= 1 - self.transforms = Compose(transforms) - self.p = p - - def __call__(self, results): - return results if np.random.uniform() > self.p else self.transforms( - results) - - def __repr__(self): - repr_str = self.__class__.__name__ - repr_str += f'(transforms={self.transforms}, ' - repr_str += f'p={self.p})' - return repr_str - - -@PIPELINES.register_module() -class TorchVisionWrapper: - """A wrapper of torchvision trasnforms. It applies specific transform to - ``img`` and updates ``img_shape`` accordingly. - - Warning: - This transform only affects the image but not its associated - annotations, such as word bounding boxes and polygon masks. Therefore, - it may only be applicable to text recognition tasks. - - Args: - op (str): The name of any transform class in - :func:`torchvision.transforms`. - **kwargs: Arguments that will be passed to initializer of torchvision - transform. - - :Required Keys: - - | ``img`` (ndarray): The input image. - - :Affected Keys: - :Modified: - - | ``img`` (ndarray): The modified image. - :Added: - - | ``img_shape`` (tuple(int)): Size of the modified image. - """ - - def __init__(self, op, **kwargs): - assert type(op) is str - - if mmcv.is_str(op): - obj_cls = getattr(torchvision_transforms, op) - elif inspect.isclass(op): - obj_cls = op - else: - raise TypeError( - f'type must be a str or valid type, but got {type(type)}') - self.transform = obj_cls(**kwargs) - self.kwargs = kwargs - - def __call__(self, results): - assert 'img' in results - # BGR -> RGB - img = results['img'][..., ::-1] - img = Image.fromarray(img) - img = self.transform(img) - img = np.asarray(img) - img = img[..., ::-1] - results['img'] = img - results['img_shape'] = img.shape - return results - - def __repr__(self): - repr_str = self.__class__.__name__ - repr_str += f'(transform={self.transform})' - return repr_str diff --git a/spaces/tomofi/MMOCR/mmocr/models/common/losses/dice_loss.py b/spaces/tomofi/MMOCR/mmocr/models/common/losses/dice_loss.py deleted file mode 100644 index 0777200b967377edec5f141d43805714b96b5ea8..0000000000000000000000000000000000000000 --- a/spaces/tomofi/MMOCR/mmocr/models/common/losses/dice_loss.py +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import torch -import torch.nn as nn - -from mmocr.models.builder import LOSSES - - -@LOSSES.register_module() -class DiceLoss(nn.Module): - - def __init__(self, eps=1e-6): - super().__init__() - assert isinstance(eps, float) - self.eps = eps - - def forward(self, pred, target, mask=None): - - pred = pred.contiguous().view(pred.size()[0], -1) - target = target.contiguous().view(target.size()[0], -1) - - if mask is not None: - mask = mask.contiguous().view(mask.size()[0], -1) - pred = pred * mask - target = target * mask - - a = torch.sum(pred * target) - b = torch.sum(pred) - c = torch.sum(target) - d = (2 * a) / (b + c + self.eps) - - return 1 - d diff --git a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/configs/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco.py b/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/configs/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco.py deleted file mode 100644 index 5d6215d6f6e2f81fa284af0e639f3568429e3a75..0000000000000000000000000000000000000000 --- a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/configs/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco.py +++ /dev/null @@ -1,45 +0,0 @@ -_base_ = './mask_rcnn_r50_fpn_1x_coco.py' -model = dict( - pretrained='open-mmlab://detectron2/resnet50_caffe', - backbone=dict(norm_cfg=dict(requires_grad=False), style='caffe')) -# use caffe img_norm -img_norm_cfg = dict( - mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False) -train_pipeline = [ - dict(type='LoadImageFromFile'), - dict( - type='LoadAnnotations', - with_bbox=True, - with_mask=True, - poly2mask=False), - dict( - type='Resize', - img_scale=[(1333, 640), (1333, 672), (1333, 704), (1333, 736), - (1333, 768), (1333, 800)], - multiscale_mode='value', - keep_ratio=True), - dict(type='RandomFlip', flip_ratio=0.5), - dict(type='Normalize', **img_norm_cfg), - dict(type='Pad', size_divisor=32), - dict(type='DefaultFormatBundle'), - dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']), -] -test_pipeline = [ - dict(type='LoadImageFromFile'), - dict( - type='MultiScaleFlipAug', - img_scale=(1333, 800), - flip=False, - transforms=[ - dict(type='Resize', keep_ratio=True), - dict(type='RandomFlip'), - dict(type='Normalize', **img_norm_cfg), - dict(type='Pad', size_divisor=32), - dict(type='ImageToTensor', keys=['img']), - dict(type='Collect', keys=['img']), - ]) -] -data = dict( - train=dict(pipeline=train_pipeline), - val=dict(pipeline=test_pipeline), - test=dict(pipeline=test_pipeline)) diff --git a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/mmdet/models/losses/pisa_loss.py b/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/mmdet/models/losses/pisa_loss.py deleted file mode 100644 index 4a48adfcd400bb07b719a6fbd5a8af0508820629..0000000000000000000000000000000000000000 --- a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/mmdet/models/losses/pisa_loss.py +++ /dev/null @@ -1,183 +0,0 @@ -import mmcv -import torch - -from mmdet.core import bbox_overlaps - - -@mmcv.jit(derivate=True, coderize=True) -def isr_p(cls_score, - bbox_pred, - bbox_targets, - rois, - sampling_results, - loss_cls, - bbox_coder, - k=2, - bias=0, - num_class=80): - """Importance-based Sample Reweighting (ISR_P), positive part. - - Args: - cls_score (Tensor): Predicted classification scores. - bbox_pred (Tensor): Predicted bbox deltas. - bbox_targets (tuple[Tensor]): A tuple of bbox targets, the are - labels, label_weights, bbox_targets, bbox_weights, respectively. - rois (Tensor): Anchors (single_stage) in shape (n, 4) or RoIs - (two_stage) in shape (n, 5). - sampling_results (obj): Sampling results. - loss_cls (func): Classification loss func of the head. - bbox_coder (obj): BBox coder of the head. - k (float): Power of the non-linear mapping. - bias (float): Shift of the non-linear mapping. - num_class (int): Number of classes, default: 80. - - Return: - tuple([Tensor]): labels, imp_based_label_weights, bbox_targets, - bbox_target_weights - """ - - labels, label_weights, bbox_targets, bbox_weights = bbox_targets - pos_label_inds = ((labels >= 0) & - (labels < num_class)).nonzero().reshape(-1) - pos_labels = labels[pos_label_inds] - - # if no positive samples, return the original targets - num_pos = float(pos_label_inds.size(0)) - if num_pos == 0: - return labels, label_weights, bbox_targets, bbox_weights - - # merge pos_assigned_gt_inds of per image to a single tensor - gts = list() - last_max_gt = 0 - for i in range(len(sampling_results)): - gt_i = sampling_results[i].pos_assigned_gt_inds - gts.append(gt_i + last_max_gt) - if len(gt_i) != 0: - last_max_gt = gt_i.max() + 1 - gts = torch.cat(gts) - assert len(gts) == num_pos - - cls_score = cls_score.detach() - bbox_pred = bbox_pred.detach() - - # For single stage detectors, rois here indicate anchors, in shape (N, 4) - # For two stage detectors, rois are in shape (N, 5) - if rois.size(-1) == 5: - pos_rois = rois[pos_label_inds][:, 1:] - else: - pos_rois = rois[pos_label_inds] - - if bbox_pred.size(-1) > 4: - bbox_pred = bbox_pred.view(bbox_pred.size(0), -1, 4) - pos_delta_pred = bbox_pred[pos_label_inds, pos_labels].view(-1, 4) - else: - pos_delta_pred = bbox_pred[pos_label_inds].view(-1, 4) - - # compute iou of the predicted bbox and the corresponding GT - pos_delta_target = bbox_targets[pos_label_inds].view(-1, 4) - pos_bbox_pred = bbox_coder.decode(pos_rois, pos_delta_pred) - target_bbox_pred = bbox_coder.decode(pos_rois, pos_delta_target) - ious = bbox_overlaps(pos_bbox_pred, target_bbox_pred, is_aligned=True) - - pos_imp_weights = label_weights[pos_label_inds] - # Two steps to compute IoU-HLR. Samples are first sorted by IoU locally, - # then sorted again within the same-rank group - max_l_num = pos_labels.bincount().max() - for label in pos_labels.unique(): - l_inds = (pos_labels == label).nonzero().view(-1) - l_gts = gts[l_inds] - for t in l_gts.unique(): - t_inds = l_inds[l_gts == t] - t_ious = ious[t_inds] - _, t_iou_rank_idx = t_ious.sort(descending=True) - _, t_iou_rank = t_iou_rank_idx.sort() - ious[t_inds] += max_l_num - t_iou_rank.float() - l_ious = ious[l_inds] - _, l_iou_rank_idx = l_ious.sort(descending=True) - _, l_iou_rank = l_iou_rank_idx.sort() # IoU-HLR - # linearly map HLR to label weights - pos_imp_weights[l_inds] *= (max_l_num - l_iou_rank.float()) / max_l_num - - pos_imp_weights = (bias + pos_imp_weights * (1 - bias)).pow(k) - - # normalize to make the new weighted loss value equal to the original loss - pos_loss_cls = loss_cls( - cls_score[pos_label_inds], pos_labels, reduction_override='none') - if pos_loss_cls.dim() > 1: - ori_pos_loss_cls = pos_loss_cls * label_weights[pos_label_inds][:, - None] - new_pos_loss_cls = pos_loss_cls * pos_imp_weights[:, None] - else: - ori_pos_loss_cls = pos_loss_cls * label_weights[pos_label_inds] - new_pos_loss_cls = pos_loss_cls * pos_imp_weights - pos_loss_cls_ratio = ori_pos_loss_cls.sum() / new_pos_loss_cls.sum() - pos_imp_weights = pos_imp_weights * pos_loss_cls_ratio - label_weights[pos_label_inds] = pos_imp_weights - - bbox_targets = labels, label_weights, bbox_targets, bbox_weights - return bbox_targets - - -@mmcv.jit(derivate=True, coderize=True) -def carl_loss(cls_score, - labels, - bbox_pred, - bbox_targets, - loss_bbox, - k=1, - bias=0.2, - avg_factor=None, - sigmoid=False, - num_class=80): - """Classification-Aware Regression Loss (CARL). - - Args: - cls_score (Tensor): Predicted classification scores. - labels (Tensor): Targets of classification. - bbox_pred (Tensor): Predicted bbox deltas. - bbox_targets (Tensor): Target of bbox regression. - loss_bbox (func): Regression loss func of the head. - bbox_coder (obj): BBox coder of the head. - k (float): Power of the non-linear mapping. - bias (float): Shift of the non-linear mapping. - avg_factor (int): Average factor used in regression loss. - sigmoid (bool): Activation of the classification score. - num_class (int): Number of classes, default: 80. - - Return: - dict: CARL loss dict. - """ - pos_label_inds = ((labels >= 0) & - (labels < num_class)).nonzero().reshape(-1) - if pos_label_inds.numel() == 0: - return dict(loss_carl=cls_score.sum()[None] * 0.) - pos_labels = labels[pos_label_inds] - - # multiply pos_cls_score with the corresponding bbox weight - # and remain gradient - if sigmoid: - pos_cls_score = cls_score.sigmoid()[pos_label_inds, pos_labels] - else: - pos_cls_score = cls_score.softmax(-1)[pos_label_inds, pos_labels] - carl_loss_weights = (bias + (1 - bias) * pos_cls_score).pow(k) - - # normalize carl_loss_weight to make its sum equal to num positive - num_pos = float(pos_cls_score.size(0)) - weight_ratio = num_pos / carl_loss_weights.sum() - carl_loss_weights *= weight_ratio - - if avg_factor is None: - avg_factor = bbox_targets.size(0) - # if is class agnostic, bbox pred is in shape (N, 4) - # otherwise, bbox pred is in shape (N, #classes, 4) - if bbox_pred.size(-1) > 4: - bbox_pred = bbox_pred.view(bbox_pred.size(0), -1, 4) - pos_bbox_preds = bbox_pred[pos_label_inds, pos_labels] - else: - pos_bbox_preds = bbox_pred[pos_label_inds] - ori_loss_reg = loss_bbox( - pos_bbox_preds, - bbox_targets[pos_label_inds], - reduction_override='none') / avg_factor - loss_carl = (ori_loss_reg * carl_loss_weights[:, None]).sum() - return dict(loss_carl=loss_carl[None]) diff --git a/spaces/tornadoslims/instruct-pix2pix/stable_diffusion/Stable_Diffusion_v1_Model_Card.md b/spaces/tornadoslims/instruct-pix2pix/stable_diffusion/Stable_Diffusion_v1_Model_Card.md deleted file mode 100644 index ad76ad2ee6da62ad21c8a92e9082a31b272740f3..0000000000000000000000000000000000000000 --- a/spaces/tornadoslims/instruct-pix2pix/stable_diffusion/Stable_Diffusion_v1_Model_Card.md +++ /dev/null @@ -1,144 +0,0 @@ -# Stable Diffusion v1 Model Card -This model card focuses on the model associated with the Stable Diffusion model, available [here](https://github.com/CompVis/stable-diffusion). - -## Model Details -- **Developed by:** Robin Rombach, Patrick Esser -- **Model type:** Diffusion-based text-to-image generation model -- **Language(s):** English -- **License:** [Proprietary](LICENSE) -- **Model Description:** This is a model that can be used to generate and modify images based on text prompts. It is a [Latent Diffusion Model](https://arxiv.org/abs/2112.10752) that uses a fixed, pretrained text encoder ([CLIP ViT-L/14](https://arxiv.org/abs/2103.00020)) as suggested in the [Imagen paper](https://arxiv.org/abs/2205.11487). -- **Resources for more information:** [GitHub Repository](https://github.com/CompVis/stable-diffusion), [Paper](https://arxiv.org/abs/2112.10752). -- **Cite as:** - - @InProceedings{Rombach_2022_CVPR, - author = {Rombach, Robin and Blattmann, Andreas and Lorenz, Dominik and Esser, Patrick and Ommer, Bj\"orn}, - title = {High-Resolution Image Synthesis With Latent Diffusion Models}, - booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, - month = {June}, - year = {2022}, - pages = {10684-10695} - } - -# Uses - -## Direct Use -The model is intended for research purposes only. Possible research areas and -tasks include - -- Safe deployment of models which have the potential to generate harmful content. -- Probing and understanding the limitations and biases of generative models. -- Generation of artworks and use in design and other artistic processes. -- Applications in educational or creative tools. -- Research on generative models. - -Excluded uses are described below. - - ### Misuse, Malicious Use, and Out-of-Scope Use -_Note: This section is taken from the [DALLE-MINI model card](https://huggingface.co/dalle-mini/dalle-mini), but applies in the same way to Stable Diffusion v1_. - -The model should not be used to intentionally create or disseminate images that create hostile or alienating environments for people. This includes generating images that people would foreseeably find disturbing, distressing, or offensive; or content that propagates historical or current stereotypes. - -#### Out-of-Scope Use -The model was not trained to be factual or true representations of people or events, and therefore using the model to generate such content is out-of-scope for the abilities of this model. - -#### Misuse and Malicious Use -Using the model to generate content that is cruel to individuals is a misuse of this model. This includes, but is not limited to: - -- Generating demeaning, dehumanizing, or otherwise harmful representations of people or their environments, cultures, religions, etc. -- Intentionally promoting or propagating discriminatory content or harmful stereotypes. -- Impersonating individuals without their consent. -- Sexual content without consent of the people who might see it. -- Mis- and disinformation -- Representations of egregious violence and gore -- Sharing of copyrighted or licensed material in violation of its terms of use. -- Sharing content that is an alteration of copyrighted or licensed material in violation of its terms of use. - -## Limitations and Bias - -### Limitations - -- The model does not achieve perfect photorealism -- The model cannot render legible text -- The model does not perform well on more difficult tasks which involve compositionality, such as rendering an image corresponding to “A red cube on top of a blue sphere” -- Faces and people in general may not be generated properly. -- The model was trained mainly with English captions and will not work as well in other languages. -- The autoencoding part of the model is lossy -- The model was trained on a large-scale dataset - [LAION-5B](https://laion.ai/blog/laion-5b/) which contains adult material - and is not fit for product use without additional safety mechanisms and - considerations. -- No additional measures were used to deduplicate the dataset. As a result, we observe some degree of memorization for images that are duplicated in the training data. - The training data can be searched at [https://rom1504.github.io/clip-retrieval/](https://rom1504.github.io/clip-retrieval/) to possibly assist in the detection of memorized images. - -### Bias -While the capabilities of image generation models are impressive, they can also reinforce or exacerbate social biases. -Stable Diffusion v1 was primarily trained on subsets of [LAION-2B(en)](https://laion.ai/blog/laion-5b/), -which consists of images that are limited to English descriptions. -Texts and images from communities and cultures that use other languages are likely to be insufficiently accounted for. -This affects the overall output of the model, as white and western cultures are often set as the default. Further, the -ability of the model to generate content with non-English prompts is significantly worse than with English-language prompts. -Stable Diffusion v1 mirrors and exacerbates biases to such a degree that viewer discretion must be advised irrespective of the input or its intent. - - -## Training - -**Training Data** -The model developers used the following dataset for training the model: - -- LAION-5B and subsets thereof (see next section) - -**Training Procedure** -Stable Diffusion v1 is a latent diffusion model which combines an autoencoder with a diffusion model that is trained in the latent space of the autoencoder. During training, - -- Images are encoded through an encoder, which turns images into latent representations. The autoencoder uses a relative downsampling factor of 8 and maps images of shape H x W x 3 to latents of shape H/f x W/f x 4 -- Text prompts are encoded through a ViT-L/14 text-encoder. -- The non-pooled output of the text encoder is fed into the UNet backbone of the latent diffusion model via cross-attention. -- The loss is a reconstruction objective between the noise that was added to the latent and the prediction made by the UNet. - -We currently provide the following checkpoints: - -- `sd-v1-1.ckpt`: 237k steps at resolution `256x256` on [laion2B-en](https://huggingface.co/datasets/laion/laion2B-en). - 194k steps at resolution `512x512` on [laion-high-resolution](https://huggingface.co/datasets/laion/laion-high-resolution) (170M examples from LAION-5B with resolution `>= 1024x1024`). -- `sd-v1-2.ckpt`: Resumed from `sd-v1-1.ckpt`. - 515k steps at resolution `512x512` on [laion-aesthetics v2 5+](https://laion.ai/blog/laion-aesthetics/) (a subset of laion2B-en with estimated aesthetics score `> 5.0`, and additionally -filtered to images with an original size `>= 512x512`, and an estimated watermark probability `< 0.5`. The watermark estimate is from the [LAION-5B](https://laion.ai/blog/laion-5b/) metadata, the aesthetics score is estimated using the [LAION-Aesthetics Predictor V2](https://github.com/christophschuhmann/improved-aesthetic-predictor)). -- `sd-v1-3.ckpt`: Resumed from `sd-v1-2.ckpt`. 195k steps at resolution `512x512` on "laion-aesthetics v2 5+" and 10\% dropping of the text-conditioning to improve [classifier-free guidance sampling](https://arxiv.org/abs/2207.12598). -- `sd-v1-4.ckpt`: Resumed from `sd-v1-2.ckpt`. 225k steps at resolution `512x512` on "laion-aesthetics v2 5+" and 10\% dropping of the text-conditioning to improve [classifier-free guidance sampling](https://arxiv.org/abs/2207.12598). - -- **Hardware:** 32 x 8 x A100 GPUs -- **Optimizer:** AdamW -- **Gradient Accumulations**: 2 -- **Batch:** 32 x 8 x 2 x 4 = 2048 -- **Learning rate:** warmup to 0.0001 for 10,000 steps and then kept constant - -## Evaluation Results -Evaluations with different classifier-free guidance scales (1.5, 2.0, 3.0, 4.0, -5.0, 6.0, 7.0, 8.0) and 50 PLMS sampling -steps show the relative improvements of the checkpoints: - -![pareto](assets/v1-variants-scores.jpg) - -Evaluated using 50 PLMS steps and 10000 random prompts from the COCO2017 validation set, evaluated at 512x512 resolution. Not optimized for FID scores. - -## Environmental Impact - -**Stable Diffusion v1** **Estimated Emissions** -Based on that information, we estimate the following CO2 emissions using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700). The hardware, runtime, cloud provider, and compute region were utilized to estimate the carbon impact. - -- **Hardware Type:** A100 PCIe 40GB -- **Hours used:** 150000 -- **Cloud Provider:** AWS -- **Compute Region:** US-east -- **Carbon Emitted (Power consumption x Time x Carbon produced based on location of power grid):** 11250 kg CO2 eq. - -## Citation - @InProceedings{Rombach_2022_CVPR, - author = {Rombach, Robin and Blattmann, Andreas and Lorenz, Dominik and Esser, Patrick and Ommer, Bj\"orn}, - title = {High-Resolution Image Synthesis With Latent Diffusion Models}, - booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, - month = {June}, - year = {2022}, - pages = {10684-10695} - } - -*This model card was written by: Robin Rombach and Patrick Esser and is based on the [DALL-E Mini model card](https://huggingface.co/dalle-mini/dalle-mini).* diff --git a/spaces/tribe-ai/document-qa-comparator/README.md b/spaces/tribe-ai/document-qa-comparator/README.md deleted file mode 100644 index 30e6aba0a8feff241e5d58a2ac1bf0c408f64277..0000000000000000000000000000000000000000 --- a/spaces/tribe-ai/document-qa-comparator/README.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Document Question Answer Comparator -emoji: 🤖🦾⚙️ -colorFrom: white -colorTo: white -sdk: gradio -sdk_version: 3.18.0 -app_file: app.py -pinned: false -license: mit ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference - -## Setup + Run -``` -pip install -r requirements.txt -python app.py -``` \ No newline at end of file diff --git a/spaces/triggah61/chingu-music/audiocraft/quantization/__init__.py b/spaces/triggah61/chingu-music/audiocraft/quantization/__init__.py deleted file mode 100644 index 836d6eb518978480c6b95d6f29ce4f84a9428793..0000000000000000000000000000000000000000 --- a/spaces/triggah61/chingu-music/audiocraft/quantization/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -# flake8: noqa -from .vq import ResidualVectorQuantizer -from .base import BaseQuantizer, DummyQuantizer, QuantizedResult diff --git a/spaces/trttung1610/musicgen/audiocraft/data/audio_utils.py b/spaces/trttung1610/musicgen/audiocraft/data/audio_utils.py deleted file mode 100644 index 565b63a4ef78dcd802dda932b42ebe518ffe7397..0000000000000000000000000000000000000000 --- a/spaces/trttung1610/musicgen/audiocraft/data/audio_utils.py +++ /dev/null @@ -1,177 +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. -"""Various utilities for audio convertion (pcm format, sample rate and channels), -and volume normalization.""" -import sys -import typing as tp - -import julius -import torch -import torchaudio - - -def convert_audio_channels(wav: torch.Tensor, channels: int = 2) -> torch.Tensor: - """Convert audio to the given number of channels. - - Args: - wav (torch.Tensor): Audio wave of shape [B, C, T]. - channels (int): Expected number of channels as output. - Returns: - torch.Tensor: Downmixed or unchanged audio wave [B, C, T]. - """ - *shape, src_channels, length = wav.shape - if src_channels == channels: - pass - elif channels == 1: - # Case 1: - # The caller asked 1-channel audio, and the stream has multiple - # channels, downmix all channels. - wav = wav.mean(dim=-2, keepdim=True) - elif src_channels == 1: - # Case 2: - # The caller asked for multiple channels, but the input file has - # a single channel, replicate the audio over all channels. - wav = wav.expand(*shape, channels, length) - elif src_channels >= channels: - # Case 3: - # The caller asked for multiple channels, and the input file has - # more channels than requested. In that case return the first channels. - wav = wav[..., :channels, :] - else: - # Case 4: What is a reasonable choice here? - raise ValueError('The audio file has less channels than requested but is not mono.') - return wav - - -def convert_audio(wav: torch.Tensor, from_rate: float, - to_rate: float, to_channels: int) -> torch.Tensor: - """Convert audio to new sample rate and number of audio channels.""" - wav = julius.resample_frac(wav, int(from_rate), int(to_rate)) - wav = convert_audio_channels(wav, to_channels) - return wav - - -def normalize_loudness(wav: torch.Tensor, sample_rate: int, loudness_headroom_db: float = 14, - loudness_compressor: bool = False, energy_floor: float = 2e-3): - """Normalize an input signal to a user loudness in dB LKFS. - Audio loudness is defined according to the ITU-R BS.1770-4 recommendation. - - Args: - wav (torch.Tensor): Input multichannel audio data. - sample_rate (int): Sample rate. - loudness_headroom_db (float): Target loudness of the output in dB LUFS. - loudness_compressor (bool): Uses tanh for soft clipping. - energy_floor (float): anything below that RMS level will not be rescaled. - Returns: - torch.Tensor: Loudness normalized output data. - """ - energy = wav.pow(2).mean().sqrt().item() - if energy < energy_floor: - return wav - transform = torchaudio.transforms.Loudness(sample_rate) - input_loudness_db = transform(wav).item() - # calculate the gain needed to scale to the desired loudness level - delta_loudness = -loudness_headroom_db - input_loudness_db - gain = 10.0 ** (delta_loudness / 20.0) - output = gain * wav - if loudness_compressor: - output = torch.tanh(output) - assert output.isfinite().all(), (input_loudness_db, wav.pow(2).mean().sqrt()) - return output - - -def _clip_wav(wav: torch.Tensor, log_clipping: bool = False, stem_name: tp.Optional[str] = None) -> None: - """Utility function to clip the audio with logging if specified.""" - max_scale = wav.abs().max() - if log_clipping and max_scale > 1: - clamp_prob = (wav.abs() > 1).float().mean().item() - print(f"CLIPPING {stem_name or ''} happening with proba (a bit of clipping is okay):", - clamp_prob, "maximum scale: ", max_scale.item(), file=sys.stderr) - #wav.clamp_(-1, 1) - wav = wav.clone().clamp_(-1, 1) - - -def normalize_audio(wav: torch.Tensor, normalize: bool = True, - strategy: str = 'peak', peak_clip_headroom_db: float = 1, - rms_headroom_db: float = 18, loudness_headroom_db: float = 14, - loudness_compressor: bool = False, log_clipping: bool = False, - sample_rate: tp.Optional[int] = None, - stem_name: tp.Optional[str] = None) -> torch.Tensor: - """Normalize the audio according to the prescribed strategy (see after). - - Args: - wav (torch.Tensor): Audio data. - normalize (bool): if `True` (default), normalizes according to the prescribed - strategy (see after). If `False`, the strategy is only used in case clipping - would happen. - strategy (str): Can be either 'clip', 'peak', or 'rms'. Default is 'peak', - i.e. audio is normalized by its largest value. RMS normalizes by root-mean-square - with extra headroom to avoid clipping. 'clip' just clips. - peak_clip_headroom_db (float): Headroom in dB when doing 'peak' or 'clip' strategy. - rms_headroom_db (float): Headroom in dB when doing 'rms' strategy. This must be much larger - than the `peak_clip` one to avoid further clipping. - loudness_headroom_db (float): Target loudness for loudness normalization. - loudness_compressor (bool): If True, uses tanh based soft clipping. - log_clipping (bool): If True, basic logging on stderr when clipping still - occurs despite strategy (only for 'rms'). - sample_rate (int): Sample rate for the audio data (required for loudness). - stem_name (str, optional): Stem name for clipping logging. - Returns: - torch.Tensor: Normalized audio. - """ - scale_peak = 10 ** (-peak_clip_headroom_db / 20) - scale_rms = 10 ** (-rms_headroom_db / 20) - if strategy == 'peak': - rescaling = (scale_peak / wav.abs().max()) - if normalize or rescaling < 1: - wav = wav * rescaling - elif strategy == 'clip': - wav = wav.clamp(-scale_peak, scale_peak) - elif strategy == 'rms': - mono = wav.mean(dim=0) - rescaling = scale_rms / mono.pow(2).mean().sqrt() - if normalize or rescaling < 1: - wav = wav * rescaling - _clip_wav(wav, log_clipping=log_clipping, stem_name=stem_name) - elif strategy == 'loudness': - assert sample_rate is not None, "Loudness normalization requires sample rate." - wav = normalize_loudness(wav, sample_rate, loudness_headroom_db, loudness_compressor) - _clip_wav(wav, log_clipping=log_clipping, stem_name=stem_name) - else: - assert wav.abs().max() < 1 - assert strategy == '' or strategy == 'none', f"Unexpected strategy: '{strategy}'" - return wav - - -def f32_pcm(wav: torch.Tensor) -> torch.Tensor: - """Convert audio to float 32 bits PCM format. - """ - if wav.dtype.is_floating_point: - return wav - elif wav.dtype == torch.int16: - return wav.float() / 2**15 - elif wav.dtype == torch.int32: - return wav.float() / 2**31 - raise ValueError(f"Unsupported wav dtype: {wav.dtype}") - - -def i16_pcm(wav: torch.Tensor) -> torch.Tensor: - """Convert audio to int 16 bits PCM format. - - ..Warning:: There exist many formula for doing this conversion. None are perfect - due to the asymmetry of the int16 range. One either have possible clipping, DC offset, - or inconsistencies with f32_pcm. If the given wav doesn't have enough headroom, - it is possible that `i16_pcm(f32_pcm)) != Identity`. - """ - if wav.dtype.is_floating_point: - assert wav.abs().max() <= 1 - candidate = (wav * 2 ** 15).round() - if candidate.max() >= 2 ** 15: # clipping would occur - candidate = (wav * (2 ** 15 - 1)).round() - return candidate.short() - else: - assert wav.dtype == torch.int16 - return wav diff --git a/spaces/ty00369/IDEA-CCNL-Taiyi-BLIP-750M-Chinese/README.md b/spaces/ty00369/IDEA-CCNL-Taiyi-BLIP-750M-Chinese/README.md deleted file mode 100644 index 9f4bf47489c1a7571162c038fe642de14f58fbe5..0000000000000000000000000000000000000000 --- a/spaces/ty00369/IDEA-CCNL-Taiyi-BLIP-750M-Chinese/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: IDEA CCNL Taiyi BLIP 750M Chinese -emoji: 🚀 -colorFrom: green -colorTo: blue -sdk: gradio -sdk_version: 3.29.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/uSerNameDDHL/bingo/src/components/chat-suggestions.tsx b/spaces/uSerNameDDHL/bingo/src/components/chat-suggestions.tsx deleted file mode 100644 index 00c2fee295c9e010946046eb71705a5e131f7a5a..0000000000000000000000000000000000000000 --- a/spaces/uSerNameDDHL/bingo/src/components/chat-suggestions.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import React, { useMemo } from 'react' -import Image from 'next/image' -import HelpIcon from '@/assets/images/help.svg' -import { SuggestedResponse } from '@/lib/bots/bing/types' -import { useBing } from '@/lib/hooks/use-bing' -import { atom, useAtom } from 'jotai' - -type Suggestions = SuggestedResponse[] -const helpSuggestions = ['为什么不回应某些主题', '告诉我更多关于必应的资迅', '必应如何使用 AI?'].map((text) => ({ text })) -const suggestionsAtom = atom([]) - -type ChatSuggestionsProps = React.ComponentProps<'div'> & Pick, 'setInput'> & { suggestions?: Suggestions } - -export function ChatSuggestions({ setInput, suggestions = [] }: ChatSuggestionsProps) { - const [currentSuggestions, setSuggestions] = useAtom(suggestionsAtom) - const toggleSuggestions = (() => { - if (currentSuggestions === helpSuggestions) { - setSuggestions(suggestions) - } else { - setSuggestions(helpSuggestions) - } - }) - - useMemo(() => { - setSuggestions(suggestions) - window.scrollBy(0, 2000) - }, [suggestions.length]) - - return currentSuggestions?.length ? ( -
            -
            - - { - currentSuggestions.map(suggestion => ( - - )) - } -
            -
            - ) : null -} diff --git a/spaces/ucalyptus/PTI/makedirs.py b/spaces/ucalyptus/PTI/makedirs.py deleted file mode 100644 index cd304a8337e5962dda206f6a316e57c865661f60..0000000000000000000000000000000000000000 --- a/spaces/ucalyptus/PTI/makedirs.py +++ /dev/null @@ -1,83 +0,0 @@ -import click -import os -import sys -import pickle -import numpy as np -from PIL import Image -import torch -from configs import paths_config, hyperparameters, global_config -from IPython.display import display -import matplotlib.pyplot as plt -from scripts.latent_editor_wrapper import LatentEditorWrapper - - -image_dir_name = '/home/sayantan/processed_images' -use_multi_id_training = False -global_config.device = 'cuda' -paths_config.e4e = '/home/sayantan/PTI/pretrained_models/e4e_ffhq_encode.pt' -paths_config.input_data_id = image_dir_name -paths_config.input_data_path = f'{image_dir_name}' -paths_config.stylegan2_ada_ffhq = '/home/sayantan/PTI/pretrained_models/ffhq.pkl' -paths_config.checkpoints_dir = '/home/sayantan/PTI/' -paths_config.style_clip_pretrained_mappers = '/home/sayantan/PTI/pretrained_models' -hyperparameters.use_locality_regularization = False -hyperparameters.lpips_type = 'squeeze' - -model_id = "MYJJDFVGATAT" - - - -def display_alongside_source_image(images): - res = np.concatenate([np.array(image) for image in images], axis=1) - return Image.fromarray(res) - -def load_generators(model_id, image_name): - with open(paths_config.stylegan2_ada_ffhq, 'rb') as f: - old_G = pickle.load(f)['G_ema'].cuda() - - with open(f'{paths_config.checkpoints_dir}/model_{model_id}_{image_name}.pt', 'rb') as f_new: - new_G = torch.load(f_new).cuda() - - return old_G, new_G - -def plot_syn_images(syn_images,text): - for img in syn_images: - img = (img.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8).detach().cpu().numpy()[0] - plt.axis('off') - resized_image = Image.fromarray(img,mode='RGB').resize((256,256)) - display(resized_image) - #wandb.log({text: [wandb.Image(resized_image, caption="Label")]}) - del img - del resized_image - torch.cuda.empty_cache() - -def syn_images_wandb(img): - img = (img.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8).detach().cpu().numpy()[0] - plt.axis('off') - resized_image = Image.fromarray(img,mode='RGB').resize((256,256)) - return resized_image - -@click.command() -@click.pass_context -@click.option('--image_name', prompt='image name', help='The name for image') - -def makedir(ctx: click.Context,image_name): - generator_type = paths_config.multi_id_model_type if use_multi_id_training else image_name - old_G, new_G = load_generators(model_id, generator_type) - w_path_dir = f'{paths_config.embedding_base_dir}/{paths_config.input_data_id}' - - embedding_dir = f'{w_path_dir}/{paths_config.pti_results_keyword}/{image_name}' - w_pivot = torch.load(f'{embedding_dir}/0.pt') - - old_image = old_G.synthesis(w_pivot, noise_mode='const', force_fp32 = True) - new_image = new_G.synthesis(w_pivot, noise_mode='const', force_fp32 = True) - - latent_editor = LatentEditorWrapper() - latents_after_edit = latent_editor.get_single_interface_gan_edits(w_pivot, [i for i in range(-5,5)]) - - for direction, factor_and_edit in latents_after_edit.items(): - for editkey in factor_and_edit.keys(): - os.makedirs(f"/home/sayantan/PTI/{direction}/{editkey}") - -if __name__ == '__main__': - makedir() diff --git a/spaces/ucinlp/autoprompt/setup.py b/spaces/ucinlp/autoprompt/setup.py deleted file mode 100644 index 175703e237cb34719ddd24796c0454095588035f..0000000000000000000000000000000000000000 --- a/spaces/ucinlp/autoprompt/setup.py +++ /dev/null @@ -1,29 +0,0 @@ -import os -import setuptools -import sys - - -# Load README to get long description. -with open('README.md') as f: - _LONG_DESCRIPTION = f.read() - - -setuptools.setup( - name='autoprompt', - version='0.0.1', - description='AutoPrompt', - long_description=_LONG_DESCRIPTION, - long_description_content_type='text/markdown', - author='UCI NLP', - url='https://github.com/ucinlp/autoprompt', - packages=setuptools.find_packages(), - install_requires=[ ], - extras_require={ - 'test': ['pytest'] - }, - classifiers=[ - 'Intended Audience :: Science/Research', - 'Topic :: Scientific/Engineering :: Artificial Intelligence', - ], - keywords='text nlp machinelearning', -) diff --git a/spaces/upthrustinc/seoAnalyzerGPT/app.py b/spaces/upthrustinc/seoAnalyzerGPT/app.py deleted file mode 100644 index d2794f10036e1ed0717d01aa8fa7acbc1ecd6ba3..0000000000000000000000000000000000000000 --- a/spaces/upthrustinc/seoAnalyzerGPT/app.py +++ /dev/null @@ -1,46 +0,0 @@ -import streamlit as st -from pagespeed import generate_response, process_data -from ask_questions import answer_question -import pandas as pd -import numpy as np - -df = pd.DataFrame() -df=pd.read_csv('processed/embeddings.csv', index_col=0) -df['embeddings'] = df['embeddings'].apply(eval).apply(np.array) -# Set the title - -if "button" not in st.session_state: - st.session_state.button = False - -st.title("PageSpeed Insights") - -#start app -st.write("Enter a URL to get a PageSpeed Insights report") - -# Get the URL from the user -url = st.text_input("URL", "https://www.google.com") - -# If the user clicks the button - -if st.button("Get Report") or st.session_state.button: - with st.spinner(text="Collecting data..."): - st.session_state.button = True - # Get the response - data = generate_response(url) - # Process the data - issues = process_data(data) - # Show the data - - # for each issue in issues, make the title as an st.expander. When the expander is clicked, it shows its description and item. Also add a button in which the user can click to get the answer to the question. - - for index, issue in enumerate(issues): - title = issue["title"] - desc = issue["description"] - item = issue["item"] - - with st.expander(title): - st.write(desc) - if st.button("Fix Issue", key=index): - with st.spinner(text="Finding solution..."): - question = f"Title: {title}\nDescription: {desc}\nItem: {item}" - st.write(answer_question(df, question=issue["description"], debug=False)) \ No newline at end of file diff --git a/spaces/usbethFlerru/sovits-modelsV2/example/CES Edupack 2013 Free Download.md b/spaces/usbethFlerru/sovits-modelsV2/example/CES Edupack 2013 Free Download.md deleted file mode 100644 index 12ea2d2af4f050e6889896828d8ec2c0c6871fb0..0000000000000000000000000000000000000000 --- a/spaces/usbethFlerru/sovits-modelsV2/example/CES Edupack 2013 Free Download.md +++ /dev/null @@ -1,17 +0,0 @@ -

            CES Edupack 2013 free download


            DOWNLOADhttps://urlcod.com/2uyWs8



            - -In this video tutorial we will look at how to download the installer and prepare to install CES EduPack ... Preparing to install CES EduPack -Vor 2 years 6 1:36 -In order to install CES EduPack, download and extract the CES EduPack.exe file to any location. -Then open the ... -CES EduPack installation -Vor year 6 1:26 -In this video tutorial we will look at how to install the CES EduPack installer on your computer. -First of all ... -Installing CES EduPack on your PC -Vor 2 years 3 1:33 -In this video tutorial we will show you how to install the CES EduPack installer on your computer. -To get started ... 8a78ff9644
            -
            -
            -

            diff --git a/spaces/vivsmouret/Dipl0-pepe-diffuser/app.py b/spaces/vivsmouret/Dipl0-pepe-diffuser/app.py deleted file mode 100644 index 4c2da02a033d91ee480f2844f58ce46439f97c3b..0000000000000000000000000000000000000000 --- a/spaces/vivsmouret/Dipl0-pepe-diffuser/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/Dipl0/pepe-diffuser").launch() \ No newline at end of file diff --git a/spaces/w1zrd/MusicGen/audiocraft/data/audio.py b/spaces/w1zrd/MusicGen/audiocraft/data/audio.py deleted file mode 100644 index 2048df6f175d7303bcf5c7b931922fd297908ead..0000000000000000000000000000000000000000 --- a/spaces/w1zrd/MusicGen/audiocraft/data/audio.py +++ /dev/null @@ -1,215 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -""" -Audio IO methods are defined in this module (info, read, write), -We rely on av library for faster read when possible, otherwise on torchaudio. -""" - -from dataclasses import dataclass -from pathlib import Path -import logging -import typing as tp - -import numpy as np -import soundfile -import torch -from torch.nn import functional as F -import torchaudio as ta - -import av - -from .audio_utils import f32_pcm, i16_pcm, normalize_audio - - -_av_initialized = False - - -def _init_av(): - global _av_initialized - if _av_initialized: - return - logger = logging.getLogger('libav.mp3') - logger.setLevel(logging.ERROR) - _av_initialized = True - - -@dataclass(frozen=True) -class AudioFileInfo: - sample_rate: int - duration: float - channels: int - - -def _av_info(filepath: tp.Union[str, Path]) -> AudioFileInfo: - _init_av() - with av.open(str(filepath)) as af: - stream = af.streams.audio[0] - sample_rate = stream.codec_context.sample_rate - duration = float(stream.duration * stream.time_base) - channels = stream.channels - return AudioFileInfo(sample_rate, duration, channels) - - -def _soundfile_info(filepath: tp.Union[str, Path]) -> AudioFileInfo: - info = soundfile.info(filepath) - return AudioFileInfo(info.samplerate, info.duration, info.channels) - - -def audio_info(filepath: tp.Union[str, Path]) -> AudioFileInfo: - # torchaudio no longer returns useful duration informations for some formats like mp3s. - filepath = Path(filepath) - if filepath.suffix in ['.flac', '.ogg']: # TODO: Validate .ogg can be safely read with av_info - # ffmpeg has some weird issue with flac. - return _soundfile_info(filepath) - else: - return _av_info(filepath) - - -def _av_read(filepath: tp.Union[str, Path], seek_time: float = 0, duration: float = -1.) -> tp.Tuple[torch.Tensor, int]: - """FFMPEG-based audio file reading using PyAV bindings. - Soundfile cannot read mp3 and av_read is more efficient than torchaudio. - - Args: - filepath (str or Path): Path to audio file to read. - seek_time (float): Time at which to start reading in the file. - duration (float): Duration to read from the file. If set to -1, the whole file is read. - Returns: - Tuple[torch.Tensor, int]: Tuple containing audio data and sample rate - """ - _init_av() - with av.open(str(filepath)) as af: - stream = af.streams.audio[0] - sr = stream.codec_context.sample_rate - num_frames = int(sr * duration) if duration >= 0 else -1 - frame_offset = int(sr * seek_time) - # we need a small negative offset otherwise we get some edge artifact - # from the mp3 decoder. - af.seek(int(max(0, (seek_time - 0.1)) / stream.time_base), stream=stream) - frames = [] - length = 0 - for frame in af.decode(streams=stream.index): - current_offset = int(frame.rate * frame.pts * frame.time_base) - strip = max(0, frame_offset - current_offset) - buf = torch.from_numpy(frame.to_ndarray()) - if buf.shape[0] != stream.channels: - buf = buf.view(-1, stream.channels).t() - buf = buf[:, strip:] - frames.append(buf) - length += buf.shape[1] - if num_frames > 0 and length >= num_frames: - break - assert frames - # If the above assert fails, it is likely because we seeked past the end of file point, - # in which case ffmpeg returns a single frame with only zeros, and a weird timestamp. - # This will need proper debugging, in due time. - wav = torch.cat(frames, dim=1) - assert wav.shape[0] == stream.channels - if num_frames > 0: - wav = wav[:, :num_frames] - return f32_pcm(wav), sr - - -def audio_read(filepath: tp.Union[str, Path], seek_time: float = 0., - duration: float = -1., pad: bool = False) -> tp.Tuple[torch.Tensor, int]: - """Read audio by picking the most appropriate backend tool based on the audio format. - - Args: - filepath (str or Path): Path to audio file to read. - seek_time (float): Time at which to start reading in the file. - duration (float): Duration to read from the file. If set to -1, the whole file is read. - pad (bool): Pad output audio if not reaching expected duration. - Returns: - Tuple[torch.Tensor, int]: Tuple containing audio data and sample rate. - """ - fp = Path(filepath) - if fp.suffix in ['.flac', '.ogg']: # TODO: check if we can safely use av_read for .ogg - # There is some bug with ffmpeg and reading flac - info = _soundfile_info(filepath) - frames = -1 if duration <= 0 else int(duration * info.sample_rate) - frame_offset = int(seek_time * info.sample_rate) - wav, sr = soundfile.read(filepath, start=frame_offset, frames=frames, dtype=np.float32) - assert info.sample_rate == sr, f"Mismatch of sample rates {info.sample_rate} {sr}" - wav = torch.from_numpy(wav).t().contiguous() - if len(wav.shape) == 1: - wav = torch.unsqueeze(wav, 0) - elif ( - fp.suffix in ['.wav', '.mp3'] and fp.suffix[1:] in ta.utils.sox_utils.list_read_formats() - and duration <= 0 and seek_time == 0 - ): - # Torchaudio is faster if we load an entire file at once. - wav, sr = ta.load(fp) - else: - wav, sr = _av_read(filepath, seek_time, duration) - if pad and duration > 0: - expected_frames = int(duration * sr) - wav = F.pad(wav, (0, expected_frames - wav.shape[-1])) - return wav, sr - - -def audio_write(stem_name: tp.Union[str, Path], - wav: torch.Tensor, sample_rate: int, - format: str = 'wav', mp3_rate: int = 320, normalize: bool = True, - strategy: str = 'peak', peak_clip_headroom_db: float = 1, - rms_headroom_db: float = 18, loudness_headroom_db: float = 14, - loudness_compressor: bool = False, - log_clipping: bool = True, make_parent_dir: bool = True, - add_suffix: bool = True) -> Path: - """Convenience function for saving audio to disk. Returns the filename the audio was written to. - - Args: - stem_name (str or Path): Filename without extension which will be added automatically. - format (str): Either "wav" or "mp3". - mp3_rate (int): kbps when using mp3s. - normalize (bool): if `True` (default), normalizes according to the prescribed - strategy (see after). If `False`, the strategy is only used in case clipping - would happen. - strategy (str): Can be either 'clip', 'peak', or 'rms'. Default is 'peak', - i.e. audio is normalized by its largest value. RMS normalizes by root-mean-square - with extra headroom to avoid clipping. 'clip' just clips. - peak_clip_headroom_db (float): Headroom in dB when doing 'peak' or 'clip' strategy. - rms_headroom_db (float): Headroom in dB when doing 'rms' strategy. This must be much larger - than the `peak_clip` one to avoid further clipping. - loudness_headroom_db (float): Target loudness for loudness normalization. - loudness_compressor (bool): Uses tanh for soft clipping when strategy is 'loudness'. - when strategy is 'loudness'log_clipping (bool): If True, basic logging on stderr when clipping still - occurs despite strategy (only for 'rms'). - make_parent_dir (bool): Make parent directory if it doesn't exist. - Returns: - Path: Path of the saved audio. - """ - assert wav.dtype.is_floating_point, "wav is not floating point" - if wav.dim() == 1: - wav = wav[None] - elif wav.dim() > 2: - raise ValueError("Input wav should be at most 2 dimension.") - assert wav.isfinite().all() - wav = normalize_audio(wav, normalize, strategy, peak_clip_headroom_db, - rms_headroom_db, loudness_headroom_db, log_clipping=log_clipping, - sample_rate=sample_rate, stem_name=str(stem_name)) - kwargs: dict = {} - if format == 'mp3': - suffix = '.mp3' - kwargs.update({"compression": mp3_rate}) - elif format == 'wav': - wav = i16_pcm(wav) - suffix = '.wav' - kwargs.update({"encoding": "PCM_S", "bits_per_sample": 16}) - else: - raise RuntimeError(f"Invalid format {format}. Only wav or mp3 are supported.") - if not add_suffix: - suffix = '' - path = Path(str(stem_name) + suffix) - if make_parent_dir: - path.parent.mkdir(exist_ok=True, parents=True) - try: - ta.save(path, wav, sample_rate, **kwargs) - except Exception: - if path.exists(): - # we do not want to leave half written files around. - path.unlink() - raise - return path diff --git a/spaces/wadhwani-ai/KKMS-Smart-Search-Demo/README.md b/spaces/wadhwani-ai/KKMS-Smart-Search-Demo/README.md deleted file mode 100644 index dd4e360cc1ccd43476efe4c7d627af24568458a3..0000000000000000000000000000000000000000 --- a/spaces/wadhwani-ai/KKMS-Smart-Search-Demo/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: KKMS-Smart-Search-Demo -emoji: 🔥 -colorFrom: blue -colorTo: pink -sdk: gradio -sdk_version: 3.24.1 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/wendys-llc/panoptic-segment-anything/segment_anything/segment_anything/build_sam.py b/spaces/wendys-llc/panoptic-segment-anything/segment_anything/segment_anything/build_sam.py deleted file mode 100644 index 07abfca24e96eced7f13bdefd3212ce1b77b8999..0000000000000000000000000000000000000000 --- a/spaces/wendys-llc/panoptic-segment-anything/segment_anything/segment_anything/build_sam.py +++ /dev/null @@ -1,107 +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 functools import partial - -from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWayTransformer - - -def build_sam_vit_h(checkpoint=None): - return _build_sam( - encoder_embed_dim=1280, - encoder_depth=32, - encoder_num_heads=16, - encoder_global_attn_indexes=[7, 15, 23, 31], - checkpoint=checkpoint, - ) - - -build_sam = build_sam_vit_h - - -def build_sam_vit_l(checkpoint=None): - return _build_sam( - encoder_embed_dim=1024, - encoder_depth=24, - encoder_num_heads=16, - encoder_global_attn_indexes=[5, 11, 17, 23], - checkpoint=checkpoint, - ) - - -def build_sam_vit_b(checkpoint=None): - return _build_sam( - encoder_embed_dim=768, - encoder_depth=12, - encoder_num_heads=12, - encoder_global_attn_indexes=[2, 5, 8, 11], - checkpoint=checkpoint, - ) - - -sam_model_registry = { - "default": build_sam, - "vit_h": build_sam, - "vit_l": build_sam_vit_l, - "vit_b": build_sam_vit_b, -} - - -def _build_sam( - encoder_embed_dim, - encoder_depth, - encoder_num_heads, - encoder_global_attn_indexes, - checkpoint=None, -): - prompt_embed_dim = 256 - image_size = 1024 - vit_patch_size = 16 - image_embedding_size = image_size // vit_patch_size - sam = Sam( - image_encoder=ImageEncoderViT( - depth=encoder_depth, - embed_dim=encoder_embed_dim, - img_size=image_size, - mlp_ratio=4, - norm_layer=partial(torch.nn.LayerNorm, eps=1e-6), - num_heads=encoder_num_heads, - patch_size=vit_patch_size, - qkv_bias=True, - use_rel_pos=True, - global_attn_indexes=encoder_global_attn_indexes, - window_size=14, - out_chans=prompt_embed_dim, - ), - prompt_encoder=PromptEncoder( - embed_dim=prompt_embed_dim, - image_embedding_size=(image_embedding_size, image_embedding_size), - input_image_size=(image_size, image_size), - mask_in_chans=16, - ), - mask_decoder=MaskDecoder( - num_multimask_outputs=3, - transformer=TwoWayTransformer( - depth=2, - embedding_dim=prompt_embed_dim, - mlp_dim=2048, - num_heads=8, - ), - transformer_dim=prompt_embed_dim, - iou_head_depth=3, - iou_head_hidden_dim=256, - ), - pixel_mean=[123.675, 116.28, 103.53], - pixel_std=[58.395, 57.12, 57.375], - ) - sam.eval() - if checkpoint is not None: - with open(checkpoint, "rb") as f: - state_dict = torch.load(f) - sam.load_state_dict(state_dict) - return sam diff --git a/spaces/whocars123/yea/README.md b/spaces/whocars123/yea/README.md deleted file mode 100644 index 30d287c4c695bd19b514c9aef7eb46513a61a3f0..0000000000000000000000000000000000000000 --- a/spaces/whocars123/yea/README.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: yea -emoji: ☪️ -colorFrom: red -colorTo: blue -sdk: docker -pinned: false -duplicated_from: whocars123/yea ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/xdecoder/Demo/utils/inpainting.py b/spaces/xdecoder/Demo/utils/inpainting.py deleted file mode 100644 index 177ada354b818fd9d488b0b2a1117f6c3fef452e..0000000000000000000000000000000000000000 --- a/spaces/xdecoder/Demo/utils/inpainting.py +++ /dev/null @@ -1,172 +0,0 @@ -import sys -import cv2 -import torch -import numpy as np -import gradio as gr -from PIL import Image -from omegaconf import OmegaConf -from einops import repeat -from imwatermark import WatermarkEncoder -from pathlib import Path - -from .ddim import DDIMSampler -from .util import instantiate_from_config - - -torch.set_grad_enabled(False) - - -def put_watermark(img, wm_encoder=None): - if wm_encoder is not None: - img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR) - img = wm_encoder.encode(img, 'dwtDct') - img = Image.fromarray(img[:, :, ::-1]) - return img - - -def initialize_model(config, ckpt): - config = OmegaConf.load(config) - model = instantiate_from_config(config.model) - - model.load_state_dict(torch.load(ckpt)["state_dict"], strict=False) - - device = torch.device( - "cuda") if torch.cuda.is_available() else torch.device("cpu") - model = model.to(device) - sampler = DDIMSampler(model) - - return sampler - - -def make_batch_sd( - image, - mask, - txt, - device, - num_samples=1): - image = np.array(image.convert("RGB")) - image = image[None].transpose(0, 3, 1, 2) - image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0 - - mask = np.array(mask.convert("L")) - mask = mask.astype(np.float32) / 255.0 - mask = mask[None, None] - mask[mask < 0.5] = 0 - mask[mask >= 0.5] = 1 - mask = torch.from_numpy(mask) - - masked_image = image * (mask < 0.5) - - batch = { - "image": repeat(image.to(device=device), "1 ... -> n ...", n=num_samples), - "txt": num_samples * [txt], - "mask": repeat(mask.to(device=device), "1 ... -> n ...", n=num_samples), - "masked_image": repeat(masked_image.to(device=device), "1 ... -> n ...", n=num_samples), - } - return batch - -@torch.no_grad() -def inpaint(sampler, image, mask, prompt, seed, scale, ddim_steps, num_samples=1, w=512, h=512): - device = torch.device( - "cuda") if torch.cuda.is_available() else torch.device("cpu") - model = sampler.model - - print("Creating invisible watermark encoder (see https://github.com/ShieldMnt/invisible-watermark)...") - wm = "SDV2" - wm_encoder = WatermarkEncoder() - wm_encoder.set_watermark('bytes', wm.encode('utf-8')) - - prng = np.random.RandomState(seed) - start_code = prng.randn(num_samples, 4, h // 8, w // 8) - start_code = torch.from_numpy(start_code).to( - device=device, dtype=torch.float32) - - with torch.no_grad(), \ - torch.autocast("cuda"): - batch = make_batch_sd(image, mask, txt=prompt, - device=device, num_samples=num_samples) - - c = model.cond_stage_model.encode(batch["txt"]) - - c_cat = list() - for ck in model.concat_keys: - cc = batch[ck].float() - if ck != model.masked_image_key: - bchw = [num_samples, 4, h // 8, w // 8] - cc = torch.nn.functional.interpolate(cc, size=bchw[-2:]) - else: - cc = model.get_first_stage_encoding( - model.encode_first_stage(cc)) - c_cat.append(cc) - c_cat = torch.cat(c_cat, dim=1) - - # cond - cond = {"c_concat": [c_cat], "c_crossattn": [c]} - - # uncond cond - uc_cross = model.get_unconditional_conditioning(num_samples, "") - uc_full = {"c_concat": [c_cat], "c_crossattn": [uc_cross]} - - shape = [model.channels, h // 8, w // 8] - samples_cfg, intermediates = sampler.sample( - ddim_steps, - num_samples, - shape, - cond, - verbose=False, - eta=1.0, - unconditional_guidance_scale=scale, - unconditional_conditioning=uc_full, - x_T=start_code, - ) - x_samples_ddim = model.decode_first_stage(samples_cfg) - - result = torch.clamp((x_samples_ddim + 1.0) / 2.0, - min=0.0, max=1.0) - - result = result.cpu().numpy().transpose(0, 2, 3, 1) * 255 - return [put_watermark(Image.fromarray(img.astype(np.uint8)), wm_encoder) for img in result] - -def pad_image(input_image): - pad_w, pad_h = np.max(((2, 2), np.ceil( - np.array(input_image.size) / 64).astype(int)), axis=0) * 64 - input_image.size - im_padded = Image.fromarray( - np.pad(np.array(input_image), ((0, pad_h), (0, pad_w), (0, 0)), mode='edge')) - return im_padded - -# sampler = initialize_model(sys.argv[1], sys.argv[2]) -@torch.no_grad() -def predict(model, input_image, prompt, ddim_steps, num_samples, scale, seed): - """_summary_ - - Args: - input_image (_type_): dict - - image: PIL.Image. Input image. - - mask: PIL.Image. Mask image. - prompt (_type_): string to be used as prompt. - ddim_steps (_type_): typical 45 - num_samples (_type_): typical 4 - scale (_type_): typical 10.0 Guidance Scale. - seed (_type_): typical 1529160519 - - """ - init_image = input_image["image"].convert("RGB") - init_mask = input_image["mask"].convert("RGB") - image = pad_image(init_image) # resize to integer multiple of 32 - mask = pad_image(init_mask) # resize to integer multiple of 32 - width, height = image.size - print("Inpainting...", width, height) - - result = inpaint( - sampler=model, - image=image, - mask=mask, - prompt=prompt, - seed=seed, - scale=scale, - ddim_steps=ddim_steps, - num_samples=num_samples, - h=height, w=width - ) - - return result \ No newline at end of file diff --git a/spaces/xdecoder/Instruct-X-Decoder/utils/Config.py b/spaces/xdecoder/Instruct-X-Decoder/utils/Config.py deleted file mode 100644 index bc9877e4910a2ccfc2ac0d851c5c87ce1e134450..0000000000000000000000000000000000000000 --- a/spaces/xdecoder/Instruct-X-Decoder/utils/Config.py +++ /dev/null @@ -1,26 +0,0 @@ -from fvcore.common.config import CfgNode as _CfgNode - -class CfgNode(_CfgNode): - """ - The same as `fvcore.common.config.CfgNode`, but different in: - - 1. Use unsafe yaml loading by default. - Note that this may lead to arbitrary code execution: you must not - load a config file from untrusted sources before manually inspecting - the content of the file. - 2. Support config versioning. - When attempting to merge an old config, it will convert the old config automatically. - - .. automethod:: clone - .. automethod:: freeze - .. automethod:: defrost - .. automethod:: is_frozen - .. automethod:: load_yaml_with_base - .. automethod:: merge_from_list - .. automethod:: merge_from_other_cfg - """ - - def merge_from_dict(self, dict): - pass - -node = CfgNode() \ No newline at end of file diff --git a/spaces/xfys/yolov5_tracking/trackers/strong_sort/deep/reid/torchreid/data/datasets/__init__.py b/spaces/xfys/yolov5_tracking/trackers/strong_sort/deep/reid/torchreid/data/datasets/__init__.py deleted file mode 100644 index afb02a2bf2ce740ade52cb974a862e8987222088..0000000000000000000000000000000000000000 --- a/spaces/xfys/yolov5_tracking/trackers/strong_sort/deep/reid/torchreid/data/datasets/__init__.py +++ /dev/null @@ -1,119 +0,0 @@ -from __future__ import print_function, absolute_import - -from .image import ( - GRID, PRID, CUHK01, CUHK02, CUHK03, MSMT17, CUHKSYSU, VIPeR, SenseReID, - Market1501, DukeMTMCreID, University1652, iLIDS -) -from .video import PRID2011, Mars, DukeMTMCVidReID, iLIDSVID -from .dataset import Dataset, ImageDataset, VideoDataset - -__image_datasets = { - 'market1501': Market1501, - 'cuhk03': CUHK03, - 'dukemtmcreid': DukeMTMCreID, - 'msmt17': MSMT17, - 'viper': VIPeR, - 'grid': GRID, - 'cuhk01': CUHK01, - 'ilids': iLIDS, - 'sensereid': SenseReID, - 'prid': PRID, - 'cuhk02': CUHK02, - 'university1652': University1652, - 'cuhksysu': CUHKSYSU -} - -__video_datasets = { - 'mars': Mars, - 'ilidsvid': iLIDSVID, - 'prid2011': PRID2011, - 'dukemtmcvidreid': DukeMTMCVidReID -} - - -def init_image_dataset(name, **kwargs): - """Initializes an image dataset.""" - avai_datasets = list(__image_datasets.keys()) - if name not in avai_datasets: - raise ValueError( - 'Invalid dataset name. Received "{}", ' - 'but expected to be one of {}'.format(name, avai_datasets) - ) - return __image_datasets[name](**kwargs) - - -def init_video_dataset(name, **kwargs): - """Initializes a video dataset.""" - avai_datasets = list(__video_datasets.keys()) - if name not in avai_datasets: - raise ValueError( - 'Invalid dataset name. Received "{}", ' - 'but expected to be one of {}'.format(name, avai_datasets) - ) - return __video_datasets[name](**kwargs) - - -def register_image_dataset(name, dataset): - """Registers a new image dataset. - - Args: - name (str): key corresponding to the new dataset. - dataset (Dataset): the new dataset class. - - Examples:: - - import torchreid - import NewDataset - torchreid.data.register_image_dataset('new_dataset', NewDataset) - # single dataset case - datamanager = torchreid.data.ImageDataManager( - root='reid-data', - sources='new_dataset' - ) - # multiple dataset case - datamanager = torchreid.data.ImageDataManager( - root='reid-data', - sources=['new_dataset', 'dukemtmcreid'] - ) - """ - global __image_datasets - curr_datasets = list(__image_datasets.keys()) - if name in curr_datasets: - raise ValueError( - 'The given name already exists, please choose ' - 'another name excluding {}'.format(curr_datasets) - ) - __image_datasets[name] = dataset - - -def register_video_dataset(name, dataset): - """Registers a new video dataset. - - Args: - name (str): key corresponding to the new dataset. - dataset (Dataset): the new dataset class. - - Examples:: - - import torchreid - import NewDataset - torchreid.data.register_video_dataset('new_dataset', NewDataset) - # single dataset case - datamanager = torchreid.data.VideoDataManager( - root='reid-data', - sources='new_dataset' - ) - # multiple dataset case - datamanager = torchreid.data.VideoDataManager( - root='reid-data', - sources=['new_dataset', 'ilidsvid'] - ) - """ - global __video_datasets - curr_datasets = list(__video_datasets.keys()) - if name in curr_datasets: - raise ValueError( - 'The given name already exists, please choose ' - 'another name excluding {}'.format(curr_datasets) - ) - __video_datasets[name] = dataset diff --git a/spaces/xfys/yolov5_tracking/trackers/strong_sort/deep/reid_model_factory.py b/spaces/xfys/yolov5_tracking/trackers/strong_sort/deep/reid_model_factory.py deleted file mode 100644 index ed0542dd6269397c962f3285f3e61b15a7fb1fa4..0000000000000000000000000000000000000000 --- a/spaces/xfys/yolov5_tracking/trackers/strong_sort/deep/reid_model_factory.py +++ /dev/null @@ -1,215 +0,0 @@ -import torch -from collections import OrderedDict - - - -__model_types = [ - 'resnet50', 'mlfn', 'hacnn', 'mobilenetv2_x1_0', 'mobilenetv2_x1_4', - 'osnet_x1_0', 'osnet_x0_75', 'osnet_x0_5', 'osnet_x0_25', - 'osnet_ibn_x1_0', 'osnet_ain_x1_0'] - -__trained_urls = { - - # market1501 models ######################################################## - 'resnet50_market1501.pt': - 'https://drive.google.com/uc?id=1dUUZ4rHDWohmsQXCRe2C_HbYkzz94iBV', - 'resnet50_dukemtmcreid.pt': - 'https://drive.google.com/uc?id=17ymnLglnc64NRvGOitY3BqMRS9UWd1wg', - 'resnet50_msmt17.pt': - 'https://drive.google.com/uc?id=1ep7RypVDOthCRIAqDnn4_N-UhkkFHJsj', - - 'resnet50_fc512_market1501.pt': - 'https://drive.google.com/uc?id=1kv8l5laX_YCdIGVCetjlNdzKIA3NvsSt', - 'resnet50_fc512_dukemtmcreid.pt': - 'https://drive.google.com/uc?id=13QN8Mp3XH81GK4BPGXobKHKyTGH50Rtx', - 'resnet50_fc512_msmt17.pt': - 'https://drive.google.com/uc?id=1fDJLcz4O5wxNSUvImIIjoaIF9u1Rwaud', - - 'mlfn_market1501.pt': - 'https://drive.google.com/uc?id=1wXcvhA_b1kpDfrt9s2Pma-MHxtj9pmvS', - 'mlfn_dukemtmcreid.pt': - 'https://drive.google.com/uc?id=1rExgrTNb0VCIcOnXfMsbwSUW1h2L1Bum', - 'mlfn_msmt17.pt': - 'https://drive.google.com/uc?id=18JzsZlJb3Wm7irCbZbZ07TN4IFKvR6p-', - - 'hacnn_market1501.pt': - 'https://drive.google.com/uc?id=1LRKIQduThwGxMDQMiVkTScBwR7WidmYF', - 'hacnn_dukemtmcreid.pt': - 'https://drive.google.com/uc?id=1zNm6tP4ozFUCUQ7Sv1Z98EAJWXJEhtYH', - 'hacnn_msmt17.pt': - 'https://drive.google.com/uc?id=1MsKRtPM5WJ3_Tk2xC0aGOO7pM3VaFDNZ', - - 'mobilenetv2_x1_0_market1501.pt': - 'https://drive.google.com/uc?id=18DgHC2ZJkjekVoqBWszD8_Xiikz-fewp', - 'mobilenetv2_x1_0_dukemtmcreid.pt': - 'https://drive.google.com/uc?id=1q1WU2FETRJ3BXcpVtfJUuqq4z3psetds', - 'mobilenetv2_x1_0_msmt17.pt': - 'https://drive.google.com/uc?id=1j50Hv14NOUAg7ZeB3frzfX-WYLi7SrhZ', - - 'mobilenetv2_x1_4_market1501.pt': - 'https://drive.google.com/uc?id=1t6JCqphJG-fwwPVkRLmGGyEBhGOf2GO5', - 'mobilenetv2_x1_4_dukemtmcreid.pt': - 'https://drive.google.com/uc?id=12uD5FeVqLg9-AFDju2L7SQxjmPb4zpBN', - 'mobilenetv2_x1_4_msmt17.pt': - 'https://drive.google.com/uc?id=1ZY5P2Zgm-3RbDpbXM0kIBMPvspeNIbXz', - - 'osnet_x1_0_market1501.pt': - 'https://drive.google.com/uc?id=1vduhq5DpN2q1g4fYEZfPI17MJeh9qyrA', - 'osnet_x1_0_dukemtmcreid.pt': - 'https://drive.google.com/uc?id=1QZO_4sNf4hdOKKKzKc-TZU9WW1v6zQbq', - 'osnet_x1_0_msmt17.pt': - 'https://drive.google.com/uc?id=112EMUfBPYeYg70w-syK6V6Mx8-Qb9Q1M', - - 'osnet_x0_75_market1501.pt': - 'https://drive.google.com/uc?id=1ozRaDSQw_EQ8_93OUmjDbvLXw9TnfPer', - 'osnet_x0_75_dukemtmcreid.pt': - 'https://drive.google.com/uc?id=1IE3KRaTPp4OUa6PGTFL_d5_KQSJbP0Or', - 'osnet_x0_75_msmt17.pt': - 'https://drive.google.com/uc?id=1QEGO6WnJ-BmUzVPd3q9NoaO_GsPNlmWc', - - 'osnet_x0_5_market1501.pt': - 'https://drive.google.com/uc?id=1PLB9rgqrUM7blWrg4QlprCuPT7ILYGKT', - 'osnet_x0_5_dukemtmcreid.pt': - 'https://drive.google.com/uc?id=1KoUVqmiST175hnkALg9XuTi1oYpqcyTu', - 'osnet_x0_5_msmt17.pt': - 'https://drive.google.com/uc?id=1UT3AxIaDvS2PdxzZmbkLmjtiqq7AIKCv', - - 'osnet_x0_25_market1501.pt': - 'https://drive.google.com/uc?id=1z1UghYvOTtjx7kEoRfmqSMu-z62J6MAj', - 'osnet_x0_25_dukemtmcreid.pt': - 'https://drive.google.com/uc?id=1eumrtiXT4NOspjyEV4j8cHmlOaaCGk5l', - 'osnet_x0_25_msmt17.pt': - 'https://drive.google.com/uc?id=1sSwXSUlj4_tHZequ_iZ8w_Jh0VaRQMqF', - - ####### market1501 models ################################################## - 'resnet50_msmt17.pt': - 'https://drive.google.com/uc?id=1yiBteqgIZoOeywE8AhGmEQl7FTVwrQmf', - 'osnet_x1_0_msmt17.pt': - 'https://drive.google.com/uc?id=1IosIFlLiulGIjwW3H8uMRmx3MzPwf86x', - 'osnet_x0_75_msmt17.pt': - 'https://drive.google.com/uc?id=1fhjSS_7SUGCioIf2SWXaRGPqIY9j7-uw', - - 'osnet_x0_5_msmt17.pt': - 'https://drive.google.com/uc?id=1DHgmb6XV4fwG3n-CnCM0zdL9nMsZ9_RF', - 'osnet_x0_25_msmt17.pt': - 'https://drive.google.com/uc?id=1Kkx2zW89jq_NETu4u42CFZTMVD5Hwm6e', - 'osnet_ibn_x1_0_msmt17.pt': - 'https://drive.google.com/uc?id=1q3Sj2ii34NlfxA4LvmHdWO_75NDRmECJ', - 'osnet_ain_x1_0_msmt17.pt': - 'https://drive.google.com/uc?id=1SigwBE6mPdqiJMqhuIY4aqC7--5CsMal', -} - - -def show_downloadeable_models(): - print('\nAvailable .pt ReID models for automatic download') - print(list(__trained_urls.keys())) - - -def get_model_url(model): - if model.name in __trained_urls: - return __trained_urls[model.name] - else: - None - - -def is_model_in_model_types(model): - if model.name in __model_types: - return True - else: - return False - - -def get_model_name(model): - for x in __model_types: - if x in model.name: - return x - return None - - -def download_url(url, dst): - """Downloads file from a url to a destination. - - Args: - url (str): url to download file. - dst (str): destination path. - """ - from six.moves import urllib - print('* url="{}"'.format(url)) - print('* destination="{}"'.format(dst)) - - def _reporthook(count, block_size, total_size): - global start_time - if count == 0: - start_time = time.time() - return - duration = time.time() - start_time - progress_size = int(count * block_size) - speed = int(progress_size / (1024*duration)) - percent = int(count * block_size * 100 / total_size) - sys.stdout.write( - '\r...%d%%, %d MB, %d KB/s, %d seconds passed' % - (percent, progress_size / (1024*1024), speed, duration) - ) - sys.stdout.flush() - - urllib.request.urlretrieve(url, dst, _reporthook) - sys.stdout.write('\n') - - -def load_pretrained_weights(model, weight_path): - r"""Loads pretrianed weights to model. - - Features:: - - Incompatible layers (unmatched in name or size) will be ignored. - - Can automatically deal with keys containing "module.". - - Args: - model (nn.Module): network model. - weight_path (str): path to pretrained weights. - - Examples:: - >>> from torchreid.utils import load_pretrained_weights - >>> weight_path = 'log/my_model/model-best.pth.tar' - >>> load_pretrained_weights(model, weight_path) - """ - checkpoint = torch.load(weight_path) - if 'state_dict' in checkpoint: - state_dict = checkpoint['state_dict'] - else: - state_dict = checkpoint - - model_dict = model.state_dict() - new_state_dict = OrderedDict() - matched_layers, discarded_layers = [], [] - - for k, v in state_dict.items(): - if k.startswith('module.'): - k = k[7:] # discard module. - - if k in model_dict and model_dict[k].size() == v.size(): - new_state_dict[k] = v - matched_layers.append(k) - else: - discarded_layers.append(k) - - model_dict.update(new_state_dict) - model.load_state_dict(model_dict) - - if len(matched_layers) == 0: - warnings.warn( - 'The pretrained weights "{}" cannot be loaded, ' - 'please check the key names manually ' - '(** ignored and continue **)'.format(weight_path) - ) - else: - print( - 'Successfully loaded pretrained weights from "{}"'. - format(weight_path) - ) - if len(discarded_layers) > 0: - print( - '** The following layers are discarded ' - 'due to unmatched keys or layer size: {}'. - format(discarded_layers) - ) - diff --git a/spaces/xin/PatentSolver/App/run_normal_folder.py b/spaces/xin/PatentSolver/App/run_normal_folder.py deleted file mode 100644 index f9ae95de7e4190baf0a99ec55c81e31d7d301cb2..0000000000000000000000000000000000000000 --- a/spaces/xin/PatentSolver/App/run_normal_folder.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -# @File : run_normal_folder.py -# @Author: nixin -# @Date : 2021/11/11 -from App.bin import constants -from App.bin.InputHandler import InputHandler -from App.bin.PatentHandler import PatentHandler -from App.bin.CorpusProcessor import CorpusProcessor -import time - -start_time = time.time() - -input_folder = constants.DATA_INPUT + 'US_patents' -files_extension = "*." + 'txt' - -iInput = InputHandler(input_folder, files_extension) -input_data = iInput.get_input() - -pretreat_data = PatentHandler(input_data) -clean_patent_data = pretreat_data.pretreat_data() - - -process_data = CorpusProcessor(clean_patent_data,input_folder, files_extension) -processed_data = process_data.process_corpus() - -print("Process is finished within %s seconds" % round(time.time() - start_time,2)) \ No newline at end of file diff --git a/spaces/xu1998hz/sescore_german_mt/app.py b/spaces/xu1998hz/sescore_german_mt/app.py deleted file mode 100644 index 6afe99c765959abbf8b089f1afc77e88503b3cb5..0000000000000000000000000000000000000000 --- a/spaces/xu1998hz/sescore_german_mt/app.py +++ /dev/null @@ -1,73 +0,0 @@ -import evaluate -import sys -from pathlib import Path -from evaluate.utils import infer_gradio_input_types, json_to_string_type, parse_readme, parse_gradio_data, parse_test_cases - - -def launch_gradio_widget(metric): - """Launches `metric` widget with Gradio.""" - - try: - import gradio as gr - except ImportError as error: - logger.error("To create a metric widget with Gradio make sure gradio is installed.") - raise error - - local_path = Path(sys.path[0]) - # if there are several input types, use first as default. - if isinstance(metric.features, list): - (feature_names, feature_types) = zip(*metric.features[0].items()) - else: - (feature_names, feature_types) = zip(*metric.features.items()) - gradio_input_types = infer_gradio_input_types(feature_types) - - def compute(data): - return metric.compute(**parse_gradio_data(data, gradio_input_types)) - - header_html = '''
            - -
            -

            About SEScore

            - -

            SEScore is a reference-based text-generation evaluation metric that requires no pre-human-annotated error data, - described in our paper "Not All Errors are Equal: Learning Text Generation Metrics using - Stratified Error Synthesis" from EMNLP 2022.

            - -

            Its effectiveness over prior methods like BLEU, BERTScore, BARTScore, PRISM, COMET and BLEURT has been demonstrated on a diverse set of language generation tasks, including - translation, captioning, and web text generation. Readers have even described SEScore as "one unsupervised evaluation to rule them all" - and we are very excited to share it with you!

            - -

            Try it yourself!

            -

            Provide sample (gold) reference text and (model output) predicted text below and see how SEScore rates them! It is most performant - in a relative ranking setting, so in general it will rank better predictions higher than worse ones. Providing useful - absolute numbers based on SEScore is an ongoing direction of investigation.

            - '''.replace('\n',' ') - - - tail_markdown = parse_readme(local_path / "description.md") - - - iface = gr.Interface( - fn=compute, - inputs=gr.inputs.Dataframe( - headers=feature_names, - col_count=len(feature_names), - row_count=2, - datatype=json_to_string_type(gradio_input_types), - ), - outputs=gr.outputs.Textbox(label=metric.name), - description=header_html, - #title=f"SEScore Metric Usage Example", - article=tail_markdown, - # TODO: load test cases and use them to populate examples - # examples=[parse_test_cases(test_cases, feature_names, gradio_input_types)] - ) - - print(dir(iface)) - - iface.launch() - - - -module = evaluate.load("xu1998hz/sescore") -launch_gradio_widget(module) diff --git a/spaces/xuetao/bingo3/src/components/ui/alert-dialog.tsx b/spaces/xuetao/bingo3/src/components/ui/alert-dialog.tsx deleted file mode 100644 index 17fec4d16510328deacc1416569173c97761ef72..0000000000000000000000000000000000000000 --- a/spaces/xuetao/bingo3/src/components/ui/alert-dialog.tsx +++ /dev/null @@ -1,150 +0,0 @@ -'use client' - -import * as React from 'react' -import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog' - -import { cn } from '@/lib/utils' -import { buttonVariants } from '@/components/ui/button' - -const AlertDialog = AlertDialogPrimitive.Root - -const AlertDialogTrigger = AlertDialogPrimitive.Trigger - -const AlertDialogPortal = ({ - className, - children, - ...props -}: AlertDialogPrimitive.AlertDialogPortalProps) => ( - -
            - {children} -
            -
            -) -AlertDialogPortal.displayName = AlertDialogPrimitive.Portal.displayName - -const AlertDialogOverlay = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, children, ...props }, ref) => ( - -)) -AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName - -const AlertDialogContent = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - - - - -)) -AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName - -const AlertDialogHeader = ({ - className, - ...props -}: React.HTMLAttributes) => ( -
            -) -AlertDialogHeader.displayName = 'AlertDialogHeader' - -const AlertDialogFooter = ({ - className, - ...props -}: React.HTMLAttributes) => ( -
            -) -AlertDialogFooter.displayName = 'AlertDialogFooter' - -const AlertDialogTitle = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName - -const AlertDialogDescription = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -AlertDialogDescription.displayName = - AlertDialogPrimitive.Description.displayName - -const AlertDialogAction = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName - -const AlertDialogCancel = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName - -export { - AlertDialog, - AlertDialogTrigger, - AlertDialogContent, - AlertDialogHeader, - AlertDialogFooter, - AlertDialogTitle, - AlertDialogDescription, - AlertDialogAction, - AlertDialogCancel -} diff --git a/spaces/yderre-aubay/midi-player-demo/src/common/geometry/Point.ts b/spaces/yderre-aubay/midi-player-demo/src/common/geometry/Point.ts deleted file mode 100644 index 014cc1c6316a07dd9a06dbb7545ca08f2da843c5..0000000000000000000000000000000000000000 --- a/spaces/yderre-aubay/midi-player-demo/src/common/geometry/Point.ts +++ /dev/null @@ -1,20 +0,0 @@ -export interface IPoint { - x: number - y: number -} - -export function pointSub(v1: IPoint, v2: IPoint) { - return { - x: v1.x - v2.x, - y: v1.y - v2.y, - } -} - -export function pointAdd(v1: IPoint, v2: IPoint) { - return { - x: v1.x + v2.x, - y: v1.y + v2.y, - } -} - -export const zeroPoint = { x: 0, y: 0 } diff --git a/spaces/ygtxr1997/ReliableSwap_Demo/third_party/GPEN/face_model/op/upfirdn2d.cpp b/spaces/ygtxr1997/ReliableSwap_Demo/third_party/GPEN/face_model/op/upfirdn2d.cpp deleted file mode 100644 index d2e633dc896433c205e18bc3e455539192ff968e..0000000000000000000000000000000000000000 --- a/spaces/ygtxr1997/ReliableSwap_Demo/third_party/GPEN/face_model/op/upfirdn2d.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include - - -torch::Tensor upfirdn2d_op(const torch::Tensor& input, const torch::Tensor& kernel, - int up_x, int up_y, int down_x, int down_y, - int pad_x0, int pad_x1, int pad_y0, int pad_y1); - -#define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x " must be a CUDA tensor") -#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous") -#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) - -torch::Tensor upfirdn2d(const torch::Tensor& input, const torch::Tensor& kernel, - int up_x, int up_y, int down_x, int down_y, - int pad_x0, int pad_x1, int pad_y0, int pad_y1) { - CHECK_CUDA(input); - CHECK_CUDA(kernel); - - return upfirdn2d_op(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1); -} - -PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { - m.def("upfirdn2d", &upfirdn2d, "upfirdn2d (CUDA)"); -} \ No newline at end of file diff --git a/spaces/yizhangliu/Grounded-Segment-Anything/GroundingDINO/groundingdino/__init__.py b/spaces/yizhangliu/Grounded-Segment-Anything/GroundingDINO/groundingdino/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/generation_flax_utils.py b/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/generation_flax_utils.py deleted file mode 100644 index 8cb3ad5873c4a632fec126e535d6f626d65aa61d..0000000000000000000000000000000000000000 --- a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/generation_flax_utils.py +++ /dev/null @@ -1,28 +0,0 @@ -# coding=utf-8 -# Copyright 2021 The Google AI Flax Team Authors, and The HuggingFace Inc. team. -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import warnings - -from .generation import FlaxGenerationMixin - - -class FlaxGenerationMixin(FlaxGenerationMixin): - # warning at import time - warnings.warn( - "Importing `FlaxGenerationMixin` from `src/transformers/generation_flax_utils.py` is deprecated and will " - "be removed in Transformers v5. Import as `from transformers import FlaxGenerationMixin` instead.", - FutureWarning, - ) diff --git a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/audio_spectrogram_transformer/convert_audio_spectrogram_transformer_original_to_pytorch.py b/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/audio_spectrogram_transformer/convert_audio_spectrogram_transformer_original_to_pytorch.py deleted file mode 100644 index 32e0f33d04fdb242bc4fc37c3906dee90510ebc4..0000000000000000000000000000000000000000 --- a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/audio_spectrogram_transformer/convert_audio_spectrogram_transformer_original_to_pytorch.py +++ /dev/null @@ -1,279 +0,0 @@ -# coding=utf-8 -# Copyright 2022 The HuggingFace Inc. team. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Convert Audio Spectrogram Transformer checkpoints from the original repository. URL: https://github.com/YuanGongND/ast""" - - -import argparse -import json -from pathlib import Path - -import torch -import torchaudio -from datasets import load_dataset -from huggingface_hub import hf_hub_download - -from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification -from transformers.utils import logging - - -logging.set_verbosity_info() -logger = logging.get_logger(__name__) - - -def get_audio_spectrogram_transformer_config(model_name): - config = ASTConfig() - - if "10-10" in model_name: - pass - elif "speech-commands" in model_name: - config.max_length = 128 - elif "12-12" in model_name: - config.time_stride = 12 - config.frequency_stride = 12 - elif "14-14" in model_name: - config.time_stride = 14 - config.frequency_stride = 14 - elif "16-16" in model_name: - config.time_stride = 16 - config.frequency_stride = 16 - else: - raise ValueError("Model not supported") - - repo_id = "huggingface/label-files" - if "speech-commands" in model_name: - config.num_labels = 35 - filename = "speech-commands-v2-id2label.json" - else: - config.num_labels = 527 - filename = "audioset-id2label.json" - - id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r")) - id2label = {int(k): v for k, v in id2label.items()} - config.id2label = id2label - config.label2id = {v: k for k, v in id2label.items()} - - return config - - -def rename_key(name): - if "module.v" in name: - name = name.replace("module.v", "audio_spectrogram_transformer") - if "cls_token" in name: - name = name.replace("cls_token", "embeddings.cls_token") - if "dist_token" in name: - name = name.replace("dist_token", "embeddings.distillation_token") - if "pos_embed" in name: - name = name.replace("pos_embed", "embeddings.position_embeddings") - if "patch_embed.proj" in name: - name = name.replace("patch_embed.proj", "embeddings.patch_embeddings.projection") - # transformer blocks - if "blocks" in name: - name = name.replace("blocks", "encoder.layer") - if "attn.proj" in name: - name = name.replace("attn.proj", "attention.output.dense") - if "attn" in name: - name = name.replace("attn", "attention.self") - if "norm1" in name: - name = name.replace("norm1", "layernorm_before") - if "norm2" in name: - name = name.replace("norm2", "layernorm_after") - if "mlp.fc1" in name: - name = name.replace("mlp.fc1", "intermediate.dense") - if "mlp.fc2" in name: - name = name.replace("mlp.fc2", "output.dense") - # final layernorm - if "audio_spectrogram_transformer.norm" in name: - name = name.replace("audio_spectrogram_transformer.norm", "audio_spectrogram_transformer.layernorm") - # classifier head - if "module.mlp_head.0" in name: - name = name.replace("module.mlp_head.0", "classifier.layernorm") - if "module.mlp_head.1" in name: - name = name.replace("module.mlp_head.1", "classifier.dense") - - return name - - -def convert_state_dict(orig_state_dict, config): - for key in orig_state_dict.copy().keys(): - val = orig_state_dict.pop(key) - - if "qkv" in key: - key_split = key.split(".") - layer_num = int(key_split[3]) - dim = config.hidden_size - if "weight" in key: - orig_state_dict[ - f"audio_spectrogram_transformer.encoder.layer.{layer_num}.attention.attention.query.weight" - ] = val[:dim, :] - orig_state_dict[ - f"audio_spectrogram_transformer.encoder.layer.{layer_num}.attention.attention.key.weight" - ] = val[dim : dim * 2, :] - orig_state_dict[ - f"audio_spectrogram_transformer.encoder.layer.{layer_num}.attention.attention.value.weight" - ] = val[-dim:, :] - else: - orig_state_dict[ - f"audio_spectrogram_transformer.encoder.layer.{layer_num}.attention.attention.query.bias" - ] = val[:dim] - orig_state_dict[ - f"audio_spectrogram_transformer.encoder.layer.{layer_num}.attention.attention.key.bias" - ] = val[dim : dim * 2] - orig_state_dict[ - f"audio_spectrogram_transformer.encoder.layer.{layer_num}.attention.attention.value.bias" - ] = val[-dim:] - else: - orig_state_dict[rename_key(key)] = val - - return orig_state_dict - - -def remove_keys(state_dict): - ignore_keys = [ - "module.v.head.weight", - "module.v.head.bias", - "module.v.head_dist.weight", - "module.v.head_dist.bias", - ] - for k in ignore_keys: - state_dict.pop(k, None) - - -@torch.no_grad() -def convert_audio_spectrogram_transformer_checkpoint(model_name, pytorch_dump_folder_path, push_to_hub=False): - """ - Copy/paste/tweak model's weights to our Audio Spectrogram Transformer structure. - """ - config = get_audio_spectrogram_transformer_config(model_name) - - model_name_to_url = { - "ast-finetuned-audioset-10-10-0.4593": ( - "https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1" - ), - "ast-finetuned-audioset-10-10-0.450": ( - "https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1" - ), - "ast-finetuned-audioset-10-10-0.448": ( - "https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1" - ), - "ast-finetuned-audioset-10-10-0.448-v2": ( - "https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1" - ), - "ast-finetuned-audioset-12-12-0.447": ( - "https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1" - ), - "ast-finetuned-audioset-14-14-0.443": ( - "https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1" - ), - "ast-finetuned-audioset-16-16-0.442": ( - "https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1" - ), - "ast-finetuned-speech-commands-v2": ( - "https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1" - ), - } - - # load original state_dict - checkpoint_url = model_name_to_url[model_name] - state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu") - # remove some keys - remove_keys(state_dict) - # rename some keys - new_state_dict = convert_state_dict(state_dict, config) - - # load 🤗 model - model = ASTForAudioClassification(config) - model.eval() - - model.load_state_dict(new_state_dict) - - # verify outputs on dummy input - # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 - mean = -4.2677393 if "speech-commands" not in model_name else -6.845978 - std = 4.5689974 if "speech-commands" not in model_name else 5.5654526 - max_length = 1024 if "speech-commands" not in model_name else 128 - feature_extractor = ASTFeatureExtractor(mean=mean, std=std, max_length=max_length) - - if "speech-commands" in model_name: - dataset = load_dataset("speech_commands", "v0.02", split="validation") - waveform = dataset[0]["audio"]["array"] - else: - filepath = hf_hub_download( - repo_id="nielsr/audio-spectogram-transformer-checkpoint", - filename="sample_audio.flac", - repo_type="dataset", - ) - - waveform, _ = torchaudio.load(filepath) - waveform = waveform.squeeze().numpy() - - inputs = feature_extractor(waveform, sampling_rate=16000, return_tensors="pt") - - # forward pass - outputs = model(**inputs) - logits = outputs.logits - - if model_name == "ast-finetuned-audioset-10-10-0.4593": - expected_slice = torch.tensor([-0.8760, -7.0042, -8.6602]) - elif model_name == "ast-finetuned-audioset-10-10-0.450": - expected_slice = torch.tensor([-1.1986, -7.0903, -8.2718]) - elif model_name == "ast-finetuned-audioset-10-10-0.448": - expected_slice = torch.tensor([-2.6128, -8.0080, -9.4344]) - elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": - expected_slice = torch.tensor([-1.5080, -7.4534, -8.8917]) - elif model_name == "ast-finetuned-audioset-12-12-0.447": - expected_slice = torch.tensor([-0.5050, -6.5833, -8.0843]) - elif model_name == "ast-finetuned-audioset-14-14-0.443": - expected_slice = torch.tensor([-0.3826, -7.0336, -8.2413]) - elif model_name == "ast-finetuned-audioset-16-16-0.442": - expected_slice = torch.tensor([-1.2113, -6.9101, -8.3470]) - elif model_name == "ast-finetuned-speech-commands-v2": - expected_slice = torch.tensor([6.1589, -8.0566, -8.7984]) - else: - raise ValueError("Unknown model name") - if not torch.allclose(logits[0, :3], expected_slice, atol=1e-4): - raise ValueError("Logits don't match") - print("Looks ok!") - - if pytorch_dump_folder_path is not None: - Path(pytorch_dump_folder_path).mkdir(exist_ok=True) - print(f"Saving model {model_name} to {pytorch_dump_folder_path}") - model.save_pretrained(pytorch_dump_folder_path) - print(f"Saving feature extractor to {pytorch_dump_folder_path}") - feature_extractor.save_pretrained(pytorch_dump_folder_path) - - if push_to_hub: - print("Pushing model and feature extractor to the hub...") - model.push_to_hub(f"MIT/{model_name}") - feature_extractor.push_to_hub(f"MIT/{model_name}") - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - # Required parameters - parser.add_argument( - "--model_name", - default="ast-finetuned-audioset-10-10-0.4593", - type=str, - help="Name of the Audio Spectrogram Transformer model you'd like to convert.", - ) - parser.add_argument( - "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." - ) - parser.add_argument( - "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." - ) - - args = parser.parse_args() - convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub) diff --git a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/auto/tokenization_auto.py b/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/auto/tokenization_auto.py deleted file mode 100644 index 094d3351e8c0d8d82a4dba6fc126253e62b65047..0000000000000000000000000000000000000000 --- a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/auto/tokenization_auto.py +++ /dev/null @@ -1,825 +0,0 @@ -# coding=utf-8 -# Copyright 2018 The HuggingFace Inc. team. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -""" Auto Tokenizer class.""" - -import importlib -import json -import os -import warnings -from collections import OrderedDict -from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union - -from ...configuration_utils import PretrainedConfig -from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code -from ...tokenization_utils import PreTrainedTokenizer -from ...tokenization_utils_base import TOKENIZER_CONFIG_FILE -from ...utils import cached_file, extract_commit_hash, is_sentencepiece_available, is_tokenizers_available, logging -from ..encoder_decoder import EncoderDecoderConfig -from .auto_factory import _LazyAutoMapping -from .configuration_auto import ( - CONFIG_MAPPING_NAMES, - AutoConfig, - config_class_to_model_type, - model_type_to_module_name, - replace_list_option_in_docstrings, -) - - -if is_tokenizers_available(): - from ...tokenization_utils_fast import PreTrainedTokenizerFast -else: - PreTrainedTokenizerFast = None - - -logger = logging.get_logger(__name__) - -if TYPE_CHECKING: - # This significantly improves completion suggestion performance when - # the transformers package is used with Microsoft's Pylance language server. - TOKENIZER_MAPPING_NAMES: OrderedDict[str, Tuple[Optional[str], Optional[str]]] = OrderedDict() -else: - TOKENIZER_MAPPING_NAMES = OrderedDict( - [ - ( - "albert", - ( - "AlbertTokenizer" if is_sentencepiece_available() else None, - "AlbertTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("align", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)), - ("bark", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)), - ("bart", ("BartTokenizer", "BartTokenizerFast")), - ( - "barthez", - ( - "BarthezTokenizer" if is_sentencepiece_available() else None, - "BarthezTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("bartpho", ("BartphoTokenizer", None)), - ("bert", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)), - ("bert-generation", ("BertGenerationTokenizer" if is_sentencepiece_available() else None, None)), - ("bert-japanese", ("BertJapaneseTokenizer", None)), - ("bertweet", ("BertweetTokenizer", None)), - ( - "big_bird", - ( - "BigBirdTokenizer" if is_sentencepiece_available() else None, - "BigBirdTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("bigbird_pegasus", ("PegasusTokenizer", "PegasusTokenizerFast" if is_tokenizers_available() else None)), - ("biogpt", ("BioGptTokenizer", None)), - ("blenderbot", ("BlenderbotTokenizer", "BlenderbotTokenizerFast")), - ("blenderbot-small", ("BlenderbotSmallTokenizer", None)), - ("blip", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)), - ("blip-2", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)), - ("bloom", (None, "BloomTokenizerFast" if is_tokenizers_available() else None)), - ("bridgetower", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)), - ("bros", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)), - ("byt5", ("ByT5Tokenizer", None)), - ( - "camembert", - ( - "CamembertTokenizer" if is_sentencepiece_available() else None, - "CamembertTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("canine", ("CanineTokenizer", None)), - ("chinese_clip", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)), - ( - "clap", - ( - "RobertaTokenizer", - "RobertaTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ( - "clip", - ( - "CLIPTokenizer", - "CLIPTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ( - "clipseg", - ( - "CLIPTokenizer", - "CLIPTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ( - "code_llama", - ( - "CodeLlamaTokenizer" if is_sentencepiece_available() else None, - "CodeLlamaTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("codegen", ("CodeGenTokenizer", "CodeGenTokenizerFast" if is_tokenizers_available() else None)), - ("convbert", ("ConvBertTokenizer", "ConvBertTokenizerFast" if is_tokenizers_available() else None)), - ( - "cpm", - ( - "CpmTokenizer" if is_sentencepiece_available() else None, - "CpmTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("cpmant", ("CpmAntTokenizer", None)), - ("ctrl", ("CTRLTokenizer", None)), - ("data2vec-audio", ("Wav2Vec2CTCTokenizer", None)), - ("data2vec-text", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)), - ("deberta", ("DebertaTokenizer", "DebertaTokenizerFast" if is_tokenizers_available() else None)), - ( - "deberta-v2", - ( - "DebertaV2Tokenizer" if is_sentencepiece_available() else None, - "DebertaV2TokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("distilbert", ("DistilBertTokenizer", "DistilBertTokenizerFast" if is_tokenizers_available() else None)), - ( - "dpr", - ( - "DPRQuestionEncoderTokenizer", - "DPRQuestionEncoderTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("electra", ("ElectraTokenizer", "ElectraTokenizerFast" if is_tokenizers_available() else None)), - ("ernie", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)), - ("ernie_m", ("ErnieMTokenizer" if is_sentencepiece_available() else None, None)), - ("esm", ("EsmTokenizer", None)), - ("flaubert", ("FlaubertTokenizer", None)), - ("fnet", ("FNetTokenizer", "FNetTokenizerFast" if is_tokenizers_available() else None)), - ("fsmt", ("FSMTTokenizer", None)), - ("funnel", ("FunnelTokenizer", "FunnelTokenizerFast" if is_tokenizers_available() else None)), - ("git", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)), - ("gpt-sw3", ("GPTSw3Tokenizer" if is_sentencepiece_available() else None, None)), - ("gpt2", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)), - ("gpt_bigcode", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)), - ("gpt_neo", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)), - ("gpt_neox", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)), - ("gpt_neox_japanese", ("GPTNeoXJapaneseTokenizer", None)), - ("gptj", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)), - ("gptsan-japanese", ("GPTSanJapaneseTokenizer", None)), - ("groupvit", ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None)), - ("herbert", ("HerbertTokenizer", "HerbertTokenizerFast" if is_tokenizers_available() else None)), - ("hubert", ("Wav2Vec2CTCTokenizer", None)), - ("ibert", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)), - ("idefics", (None, "LlamaTokenizerFast" if is_tokenizers_available() else None)), - ("instructblip", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)), - ("jukebox", ("JukeboxTokenizer", None)), - ("layoutlm", ("LayoutLMTokenizer", "LayoutLMTokenizerFast" if is_tokenizers_available() else None)), - ("layoutlmv2", ("LayoutLMv2Tokenizer", "LayoutLMv2TokenizerFast" if is_tokenizers_available() else None)), - ("layoutlmv3", ("LayoutLMv3Tokenizer", "LayoutLMv3TokenizerFast" if is_tokenizers_available() else None)), - ("layoutxlm", ("LayoutXLMTokenizer", "LayoutXLMTokenizerFast" if is_tokenizers_available() else None)), - ("led", ("LEDTokenizer", "LEDTokenizerFast" if is_tokenizers_available() else None)), - ("lilt", ("LayoutLMv3Tokenizer", "LayoutLMv3TokenizerFast" if is_tokenizers_available() else None)), - ( - "llama", - ( - "LlamaTokenizer" if is_sentencepiece_available() else None, - "LlamaTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("longformer", ("LongformerTokenizer", "LongformerTokenizerFast" if is_tokenizers_available() else None)), - ( - "longt5", - ( - "T5Tokenizer" if is_sentencepiece_available() else None, - "T5TokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("luke", ("LukeTokenizer", None)), - ("lxmert", ("LxmertTokenizer", "LxmertTokenizerFast" if is_tokenizers_available() else None)), - ("m2m_100", ("M2M100Tokenizer" if is_sentencepiece_available() else None, None)), - ("marian", ("MarianTokenizer" if is_sentencepiece_available() else None, None)), - ( - "mbart", - ( - "MBartTokenizer" if is_sentencepiece_available() else None, - "MBartTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ( - "mbart50", - ( - "MBart50Tokenizer" if is_sentencepiece_available() else None, - "MBart50TokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("mega", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)), - ("megatron-bert", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)), - ("mgp-str", ("MgpstrTokenizer", None)), - ( - "mistral", - ( - "LlamaTokenizer" if is_sentencepiece_available() else None, - "LlamaTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("mluke", ("MLukeTokenizer" if is_sentencepiece_available() else None, None)), - ("mobilebert", ("MobileBertTokenizer", "MobileBertTokenizerFast" if is_tokenizers_available() else None)), - ("mpnet", ("MPNetTokenizer", "MPNetTokenizerFast" if is_tokenizers_available() else None)), - ("mpt", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)), - ("mra", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)), - ( - "mt5", - ( - "MT5Tokenizer" if is_sentencepiece_available() else None, - "MT5TokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("musicgen", ("T5Tokenizer", "T5TokenizerFast" if is_tokenizers_available() else None)), - ("mvp", ("MvpTokenizer", "MvpTokenizerFast" if is_tokenizers_available() else None)), - ("nezha", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)), - ( - "nllb", - ( - "NllbTokenizer" if is_sentencepiece_available() else None, - "NllbTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ( - "nllb-moe", - ( - "NllbTokenizer" if is_sentencepiece_available() else None, - "NllbTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ( - "nystromformer", - ( - "AlbertTokenizer" if is_sentencepiece_available() else None, - "AlbertTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("oneformer", ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None)), - ("openai-gpt", ("OpenAIGPTTokenizer", "OpenAIGPTTokenizerFast" if is_tokenizers_available() else None)), - ("opt", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)), - ("owlvit", ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None)), - ( - "pegasus", - ( - "PegasusTokenizer" if is_sentencepiece_available() else None, - "PegasusTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ( - "pegasus_x", - ( - "PegasusTokenizer" if is_sentencepiece_available() else None, - "PegasusTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ( - "perceiver", - ( - "PerceiverTokenizer", - None, - ), - ), - ( - "persimmon", - ( - "LlamaTokenizer" if is_sentencepiece_available() else None, - "LlamaTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("phobert", ("PhobertTokenizer", None)), - ("pix2struct", ("T5Tokenizer", "T5TokenizerFast" if is_tokenizers_available() else None)), - ("plbart", ("PLBartTokenizer" if is_sentencepiece_available() else None, None)), - ("prophetnet", ("ProphetNetTokenizer", None)), - ("qdqbert", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)), - ("rag", ("RagTokenizer", None)), - ("realm", ("RealmTokenizer", "RealmTokenizerFast" if is_tokenizers_available() else None)), - ( - "reformer", - ( - "ReformerTokenizer" if is_sentencepiece_available() else None, - "ReformerTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ( - "rembert", - ( - "RemBertTokenizer" if is_sentencepiece_available() else None, - "RemBertTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("retribert", ("RetriBertTokenizer", "RetriBertTokenizerFast" if is_tokenizers_available() else None)), - ("roberta", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)), - ( - "roberta-prelayernorm", - ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None), - ), - ("roc_bert", ("RoCBertTokenizer", None)), - ("roformer", ("RoFormerTokenizer", "RoFormerTokenizerFast" if is_tokenizers_available() else None)), - ("rwkv", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)), - ("speech_to_text", ("Speech2TextTokenizer" if is_sentencepiece_available() else None, None)), - ("speech_to_text_2", ("Speech2Text2Tokenizer", None)), - ("speecht5", ("SpeechT5Tokenizer" if is_sentencepiece_available() else None, None)), - ("splinter", ("SplinterTokenizer", "SplinterTokenizerFast")), - ( - "squeezebert", - ("SqueezeBertTokenizer", "SqueezeBertTokenizerFast" if is_tokenizers_available() else None), - ), - ( - "switch_transformers", - ( - "T5Tokenizer" if is_sentencepiece_available() else None, - "T5TokenizerFast" if is_tokenizers_available() else None, - ), - ), - ( - "t5", - ( - "T5Tokenizer" if is_sentencepiece_available() else None, - "T5TokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("tapas", ("TapasTokenizer", None)), - ("tapex", ("TapexTokenizer", None)), - ("transfo-xl", ("TransfoXLTokenizer", None)), - ( - "umt5", - ( - "T5Tokenizer" if is_sentencepiece_available() else None, - "T5TokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("vilt", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)), - ("visual_bert", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)), - ("vits", ("VitsTokenizer", None)), - ("wav2vec2", ("Wav2Vec2CTCTokenizer", None)), - ("wav2vec2-conformer", ("Wav2Vec2CTCTokenizer", None)), - ("wav2vec2_phoneme", ("Wav2Vec2PhonemeCTCTokenizer", None)), - ("whisper", ("WhisperTokenizer", "WhisperTokenizerFast" if is_tokenizers_available() else None)), - ("xclip", ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None)), - ( - "xglm", - ( - "XGLMTokenizer" if is_sentencepiece_available() else None, - "XGLMTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ("xlm", ("XLMTokenizer", None)), - ("xlm-prophetnet", ("XLMProphetNetTokenizer" if is_sentencepiece_available() else None, None)), - ( - "xlm-roberta", - ( - "XLMRobertaTokenizer" if is_sentencepiece_available() else None, - "XLMRobertaTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ( - "xlm-roberta-xl", - ( - "XLMRobertaTokenizer" if is_sentencepiece_available() else None, - "XLMRobertaTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ( - "xlnet", - ( - "XLNetTokenizer" if is_sentencepiece_available() else None, - "XLNetTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ( - "xmod", - ( - "XLMRobertaTokenizer" if is_sentencepiece_available() else None, - "XLMRobertaTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ( - "yoso", - ( - "AlbertTokenizer" if is_sentencepiece_available() else None, - "AlbertTokenizerFast" if is_tokenizers_available() else None, - ), - ), - ] - ) - -TOKENIZER_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, TOKENIZER_MAPPING_NAMES) - -CONFIG_TO_TYPE = {v: k for k, v in CONFIG_MAPPING_NAMES.items()} - - -def tokenizer_class_from_name(class_name: str): - if class_name == "PreTrainedTokenizerFast": - return PreTrainedTokenizerFast - - for module_name, tokenizers in TOKENIZER_MAPPING_NAMES.items(): - if class_name in tokenizers: - module_name = model_type_to_module_name(module_name) - - module = importlib.import_module(f".{module_name}", "transformers.models") - try: - return getattr(module, class_name) - except AttributeError: - continue - - for config, tokenizers in TOKENIZER_MAPPING._extra_content.items(): - for tokenizer in tokenizers: - if getattr(tokenizer, "__name__", None) == class_name: - return tokenizer - - # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main - # init and we return the proper dummy to get an appropriate error message. - main_module = importlib.import_module("transformers") - if hasattr(main_module, class_name): - return getattr(main_module, class_name) - - return None - - -def get_tokenizer_config( - pretrained_model_name_or_path: Union[str, os.PathLike], - cache_dir: Optional[Union[str, os.PathLike]] = None, - force_download: bool = False, - resume_download: bool = False, - proxies: Optional[Dict[str, str]] = None, - token: Optional[Union[bool, str]] = None, - revision: Optional[str] = None, - local_files_only: bool = False, - subfolder: str = "", - **kwargs, -): - """ - Loads the tokenizer configuration from a pretrained model tokenizer configuration. - - Args: - pretrained_model_name_or_path (`str` or `os.PathLike`): - This can be either: - - - a string, the *model id* of a pretrained model configuration hosted inside a model repo on - huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced - under a user or organization name, like `dbmdz/bert-base-german-cased`. - - a path to a *directory* containing a configuration file saved using the - [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`. - - cache_dir (`str` or `os.PathLike`, *optional*): - Path to a directory in which a downloaded pretrained model configuration should be cached if the standard - cache should not be used. - force_download (`bool`, *optional*, defaults to `False`): - Whether or not to force to (re-)download the configuration files and override the cached versions if they - exist. - resume_download (`bool`, *optional*, defaults to `False`): - Whether or not to delete incompletely received file. Attempts to resume the download if such a file exists. - proxies (`Dict[str, str]`, *optional*): - A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', - 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. - token (`str` or *bool*, *optional*): - The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated - when running `huggingface-cli login` (stored in `~/.huggingface`). - revision (`str`, *optional*, defaults to `"main"`): - The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a - git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any - identifier allowed by git. - local_files_only (`bool`, *optional*, defaults to `False`): - If `True`, will only try to load the tokenizer configuration from local files. - subfolder (`str`, *optional*, defaults to `""`): - In case the tokenizer config is located inside a subfolder of the model repo on huggingface.co, you can - specify the folder name here. - - - - Passing `token=True` is required when you want to use a private model. - - - - Returns: - `Dict`: The configuration of the tokenizer. - - Examples: - - ```python - # Download configuration from huggingface.co and cache. - tokenizer_config = get_tokenizer_config("bert-base-uncased") - # This model does not have a tokenizer config so the result will be an empty dict. - tokenizer_config = get_tokenizer_config("xlm-roberta-base") - - # Save a pretrained tokenizer locally and you can reload its config - from transformers import AutoTokenizer - - tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") - tokenizer.save_pretrained("tokenizer-test") - tokenizer_config = get_tokenizer_config("tokenizer-test") - ```""" - use_auth_token = kwargs.pop("use_auth_token", None) - if use_auth_token is not None: - warnings.warn( - "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.", FutureWarning - ) - if token is not None: - raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.") - token = use_auth_token - - commit_hash = kwargs.get("_commit_hash", None) - resolved_config_file = cached_file( - pretrained_model_name_or_path, - TOKENIZER_CONFIG_FILE, - cache_dir=cache_dir, - force_download=force_download, - resume_download=resume_download, - proxies=proxies, - token=token, - revision=revision, - local_files_only=local_files_only, - subfolder=subfolder, - _raise_exceptions_for_missing_entries=False, - _raise_exceptions_for_connection_errors=False, - _commit_hash=commit_hash, - ) - if resolved_config_file is None: - logger.info("Could not locate the tokenizer configuration file, will try to use the model config instead.") - return {} - commit_hash = extract_commit_hash(resolved_config_file, commit_hash) - - with open(resolved_config_file, encoding="utf-8") as reader: - result = json.load(reader) - result["_commit_hash"] = commit_hash - return result - - -class AutoTokenizer: - r""" - This is a generic tokenizer class that will be instantiated as one of the tokenizer classes of the library when - created with the [`AutoTokenizer.from_pretrained`] class method. - - This class cannot be instantiated directly using `__init__()` (throws an error). - """ - - def __init__(self): - raise EnvironmentError( - "AutoTokenizer is designed to be instantiated " - "using the `AutoTokenizer.from_pretrained(pretrained_model_name_or_path)` method." - ) - - @classmethod - @replace_list_option_in_docstrings(TOKENIZER_MAPPING_NAMES) - def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): - r""" - Instantiate one of the tokenizer classes of the library from a pretrained model vocabulary. - - The tokenizer class to instantiate is selected based on the `model_type` property of the config object (either - passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's missing, by - falling back to using pattern matching on `pretrained_model_name_or_path`: - - List options - - Params: - pretrained_model_name_or_path (`str` or `os.PathLike`): - Can be either: - - - A string, the *model id* of a predefined tokenizer hosted inside a model repo on huggingface.co. - Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a - user or organization name, like `dbmdz/bert-base-german-cased`. - - A path to a *directory* containing vocabulary files required by the tokenizer, for instance saved - using the [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`. - - A path or url to a single saved vocabulary file if and only if the tokenizer only requires a - single vocabulary file (like Bert or XLNet), e.g.: `./my_model_directory/vocab.txt`. (Not - applicable to all derived classes) - inputs (additional positional arguments, *optional*): - Will be passed along to the Tokenizer `__init__()` method. - config ([`PretrainedConfig`], *optional*) - The configuration object used to determine the tokenizer class to instantiate. - cache_dir (`str` or `os.PathLike`, *optional*): - Path to a directory in which a downloaded pretrained model configuration should be cached if the - standard cache should not be used. - force_download (`bool`, *optional*, defaults to `False`): - Whether or not to force the (re-)download the model weights and configuration files and override the - cached versions if they exist. - resume_download (`bool`, *optional*, defaults to `False`): - Whether or not to delete incompletely received files. Will attempt to resume the download if such a - file exists. - proxies (`Dict[str, str]`, *optional*): - A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', - 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request. - revision (`str`, *optional*, defaults to `"main"`): - The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a - git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any - identifier allowed by git. - subfolder (`str`, *optional*): - In case the relevant files are located inside a subfolder of the model repo on huggingface.co (e.g. for - facebook/rag-token-base), specify it here. - use_fast (`bool`, *optional*, defaults to `True`): - Use a [fast Rust-based tokenizer](https://huggingface.co/docs/tokenizers/index) if it is supported for - a given model. If a fast tokenizer is not available for a given model, a normal Python-based tokenizer - is returned instead. - tokenizer_type (`str`, *optional*): - Tokenizer type to be loaded. - trust_remote_code (`bool`, *optional*, defaults to `False`): - Whether or not to allow for custom models defined on the Hub in their own modeling files. This option - should only be set to `True` for repositories you trust and in which you have read the code, as it will - execute code present on the Hub on your local machine. - kwargs (additional keyword arguments, *optional*): - Will be passed to the Tokenizer `__init__()` method. Can be used to set special tokens like - `bos_token`, `eos_token`, `unk_token`, `sep_token`, `pad_token`, `cls_token`, `mask_token`, - `additional_special_tokens`. See parameters in the `__init__()` for more details. - - Examples: - - ```python - >>> from transformers import AutoTokenizer - - >>> # Download vocabulary from huggingface.co and cache. - >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") - - >>> # Download vocabulary from huggingface.co (user-uploaded) and cache. - >>> tokenizer = AutoTokenizer.from_pretrained("dbmdz/bert-base-german-cased") - - >>> # If vocabulary files are in a directory (e.g. tokenizer was saved using *save_pretrained('./test/saved_model/')*) - >>> # tokenizer = AutoTokenizer.from_pretrained("./test/bert_saved_model/") - - >>> # Download vocabulary from huggingface.co and define model-specific arguments - >>> tokenizer = AutoTokenizer.from_pretrained("roberta-base", add_prefix_space=True) - ```""" - use_auth_token = kwargs.pop("use_auth_token", None) - if use_auth_token is not None: - warnings.warn( - "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.", FutureWarning - ) - if kwargs.get("token", None) is not None: - raise ValueError( - "`token` and `use_auth_token` are both specified. Please set only the argument `token`." - ) - kwargs["token"] = use_auth_token - - config = kwargs.pop("config", None) - kwargs["_from_auto"] = True - - use_fast = kwargs.pop("use_fast", True) - tokenizer_type = kwargs.pop("tokenizer_type", None) - trust_remote_code = kwargs.pop("trust_remote_code", None) - - # First, let's see whether the tokenizer_type is passed so that we can leverage it - if tokenizer_type is not None: - tokenizer_class = None - tokenizer_class_tuple = TOKENIZER_MAPPING_NAMES.get(tokenizer_type, None) - - if tokenizer_class_tuple is None: - raise ValueError( - f"Passed `tokenizer_type` {tokenizer_type} does not exist. `tokenizer_type` should be one of " - f"{', '.join(c for c in TOKENIZER_MAPPING_NAMES.keys())}." - ) - - tokenizer_class_name, tokenizer_fast_class_name = tokenizer_class_tuple - - if use_fast: - if tokenizer_fast_class_name is not None: - tokenizer_class = tokenizer_class_from_name(tokenizer_fast_class_name) - else: - logger.warning( - "`use_fast` is set to `True` but the tokenizer class does not have a fast version. " - " Falling back to the slow version." - ) - if tokenizer_class is None: - tokenizer_class = tokenizer_class_from_name(tokenizer_class_name) - - if tokenizer_class is None: - raise ValueError(f"Tokenizer class {tokenizer_class_name} is not currently imported.") - - return tokenizer_class.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) - - # Next, let's try to use the tokenizer_config file to get the tokenizer class. - tokenizer_config = get_tokenizer_config(pretrained_model_name_or_path, **kwargs) - if "_commit_hash" in tokenizer_config: - kwargs["_commit_hash"] = tokenizer_config["_commit_hash"] - config_tokenizer_class = tokenizer_config.get("tokenizer_class") - tokenizer_auto_map = None - if "auto_map" in tokenizer_config: - if isinstance(tokenizer_config["auto_map"], (tuple, list)): - # Legacy format for dynamic tokenizers - tokenizer_auto_map = tokenizer_config["auto_map"] - else: - tokenizer_auto_map = tokenizer_config["auto_map"].get("AutoTokenizer", None) - - # If that did not work, let's try to use the config. - if config_tokenizer_class is None: - if not isinstance(config, PretrainedConfig): - config = AutoConfig.from_pretrained( - pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs - ) - config_tokenizer_class = config.tokenizer_class - if hasattr(config, "auto_map") and "AutoTokenizer" in config.auto_map: - tokenizer_auto_map = config.auto_map["AutoTokenizer"] - - has_remote_code = tokenizer_auto_map is not None - has_local_code = config_tokenizer_class is not None or type(config) in TOKENIZER_MAPPING - trust_remote_code = resolve_trust_remote_code( - trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code - ) - - if has_remote_code and trust_remote_code: - if use_fast and tokenizer_auto_map[1] is not None: - class_ref = tokenizer_auto_map[1] - else: - class_ref = tokenizer_auto_map[0] - tokenizer_class = get_class_from_dynamic_module(class_ref, pretrained_model_name_or_path, **kwargs) - _ = kwargs.pop("code_revision", None) - if os.path.isdir(pretrained_model_name_or_path): - tokenizer_class.register_for_auto_class() - return tokenizer_class.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) - elif config_tokenizer_class is not None: - tokenizer_class = None - if use_fast and not config_tokenizer_class.endswith("Fast"): - tokenizer_class_candidate = f"{config_tokenizer_class}Fast" - tokenizer_class = tokenizer_class_from_name(tokenizer_class_candidate) - if tokenizer_class is None: - tokenizer_class_candidate = config_tokenizer_class - tokenizer_class = tokenizer_class_from_name(tokenizer_class_candidate) - if tokenizer_class is None: - raise ValueError( - f"Tokenizer class {tokenizer_class_candidate} does not exist or is not currently imported." - ) - return tokenizer_class.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) - - # Otherwise we have to be creative. - # if model is an encoder decoder, the encoder tokenizer class is used by default - if isinstance(config, EncoderDecoderConfig): - if type(config.decoder) is not type(config.encoder): # noqa: E721 - logger.warning( - f"The encoder model config class: {config.encoder.__class__} is different from the decoder model " - f"config class: {config.decoder.__class__}. It is not recommended to use the " - "`AutoTokenizer.from_pretrained()` method in this case. Please use the encoder and decoder " - "specific tokenizer classes." - ) - config = config.encoder - - model_type = config_class_to_model_type(type(config).__name__) - if model_type is not None: - tokenizer_class_py, tokenizer_class_fast = TOKENIZER_MAPPING[type(config)] - if tokenizer_class_fast and (use_fast or tokenizer_class_py is None): - return tokenizer_class_fast.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) - else: - if tokenizer_class_py is not None: - return tokenizer_class_py.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) - else: - raise ValueError( - "This tokenizer cannot be instantiated. Please make sure you have `sentencepiece` installed " - "in order to use this tokenizer." - ) - - raise ValueError( - f"Unrecognized configuration class {config.__class__} to build an AutoTokenizer.\n" - f"Model type should be one of {', '.join(c.__name__ for c in TOKENIZER_MAPPING.keys())}." - ) - - def register(config_class, slow_tokenizer_class=None, fast_tokenizer_class=None, exist_ok=False): - """ - Register a new tokenizer in this mapping. - - - Args: - config_class ([`PretrainedConfig`]): - The configuration corresponding to the model to register. - slow_tokenizer_class ([`PretrainedTokenizer`], *optional*): - The slow tokenizer to register. - fast_tokenizer_class ([`PretrainedTokenizerFast`], *optional*): - The fast tokenizer to register. - """ - if slow_tokenizer_class is None and fast_tokenizer_class is None: - raise ValueError("You need to pass either a `slow_tokenizer_class` or a `fast_tokenizer_class") - if slow_tokenizer_class is not None and issubclass(slow_tokenizer_class, PreTrainedTokenizerFast): - raise ValueError("You passed a fast tokenizer in the `slow_tokenizer_class`.") - if fast_tokenizer_class is not None and issubclass(fast_tokenizer_class, PreTrainedTokenizer): - raise ValueError("You passed a slow tokenizer in the `fast_tokenizer_class`.") - - if ( - slow_tokenizer_class is not None - and fast_tokenizer_class is not None - and issubclass(fast_tokenizer_class, PreTrainedTokenizerFast) - and fast_tokenizer_class.slow_tokenizer_class != slow_tokenizer_class - ): - raise ValueError( - "The fast tokenizer class you are passing has a `slow_tokenizer_class` attribute that is not " - "consistent with the slow tokenizer class you passed (fast tokenizer has " - f"{fast_tokenizer_class.slow_tokenizer_class} and you passed {slow_tokenizer_class}. Fix one of those " - "so they match!" - ) - - # Avoid resetting a set slow/fast tokenizer if we are passing just the other ones. - if config_class in TOKENIZER_MAPPING._extra_content: - existing_slow, existing_fast = TOKENIZER_MAPPING[config_class] - if slow_tokenizer_class is None: - slow_tokenizer_class = existing_slow - if fast_tokenizer_class is None: - fast_tokenizer_class = existing_fast - - TOKENIZER_MAPPING.register(config_class, (slow_tokenizer_class, fast_tokenizer_class), exist_ok=exist_ok) diff --git a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/convnext/configuration_convnext.py b/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/convnext/configuration_convnext.py deleted file mode 100644 index 0cba78040579064266f27d09b90a29cd2e408718..0000000000000000000000000000000000000000 --- a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/convnext/configuration_convnext.py +++ /dev/null @@ -1,141 +0,0 @@ -# coding=utf-8 -# Copyright 2022 Meta Platforms, Inc. and The HuggingFace Inc. team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -""" ConvNeXT model configuration""" - -from collections import OrderedDict -from typing import Mapping - -from packaging import version - -from ...configuration_utils import PretrainedConfig -from ...onnx import OnnxConfig -from ...utils import logging -from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices - - -logger = logging.get_logger(__name__) - -CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP = { - "facebook/convnext-tiny-224": "https://huggingface.co/facebook/convnext-tiny-224/resolve/main/config.json", - # See all ConvNeXT models at https://huggingface.co/models?filter=convnext -} - - -class ConvNextConfig(BackboneConfigMixin, PretrainedConfig): - r""" - This is the configuration class to store the configuration of a [`ConvNextModel`]. It is used to instantiate an - ConvNeXT model according to the specified arguments, defining the model architecture. Instantiating a configuration - with the defaults will yield a similar configuration to that of the ConvNeXT - [facebook/convnext-tiny-224](https://huggingface.co/facebook/convnext-tiny-224) architecture. - - Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the - documentation from [`PretrainedConfig`] for more information. - - Args: - num_channels (`int`, *optional*, defaults to 3): - The number of input channels. - patch_size (`int`, optional, defaults to 4): - Patch size to use in the patch embedding layer. - num_stages (`int`, optional, defaults to 4): - The number of stages in the model. - hidden_sizes (`List[int]`, *optional*, defaults to [96, 192, 384, 768]): - Dimensionality (hidden size) at each stage. - depths (`List[int]`, *optional*, defaults to [3, 3, 9, 3]): - Depth (number of blocks) for each stage. - hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`): - The non-linear activation function (function or string) in each block. If string, `"gelu"`, `"relu"`, - `"selu"` and `"gelu_new"` are supported. - initializer_range (`float`, *optional*, defaults to 0.02): - The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - layer_norm_eps (`float`, *optional*, defaults to 1e-12): - The epsilon used by the layer normalization layers. - layer_scale_init_value (`float`, *optional*, defaults to 1e-6): - The initial value for the layer scale. - drop_path_rate (`float`, *optional*, defaults to 0.0): - The drop rate for stochastic depth. - out_features (`List[str]`, *optional*): - If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc. - (depending on how many stages the model has). If unset and `out_indices` is set, will default to the - corresponding stages. If unset and `out_indices` is unset, will default to the last stage. - out_indices (`List[int]`, *optional*): - If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how - many stages the model has). If unset and `out_features` is set, will default to the corresponding stages. - If unset and `out_features` is unset, will default to the last stage. - - Example: - ```python - >>> from transformers import ConvNextConfig, ConvNextModel - - >>> # Initializing a ConvNext convnext-tiny-224 style configuration - >>> configuration = ConvNextConfig() - - >>> # Initializing a model (with random weights) from the convnext-tiny-224 style configuration - >>> model = ConvNextModel(configuration) - - >>> # Accessing the model configuration - >>> configuration = model.config - ```""" - model_type = "convnext" - - def __init__( - self, - num_channels=3, - patch_size=4, - num_stages=4, - hidden_sizes=None, - depths=None, - hidden_act="gelu", - initializer_range=0.02, - layer_norm_eps=1e-12, - layer_scale_init_value=1e-6, - drop_path_rate=0.0, - image_size=224, - out_features=None, - out_indices=None, - **kwargs, - ): - super().__init__(**kwargs) - - self.num_channels = num_channels - self.patch_size = patch_size - self.num_stages = num_stages - self.hidden_sizes = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes - self.depths = [3, 3, 9, 3] if depths is None else depths - self.hidden_act = hidden_act - self.initializer_range = initializer_range - self.layer_norm_eps = layer_norm_eps - self.layer_scale_init_value = layer_scale_init_value - self.drop_path_rate = drop_path_rate - self.image_size = image_size - self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)] - self._out_features, self._out_indices = get_aligned_output_features_output_indices( - out_features=out_features, out_indices=out_indices, stage_names=self.stage_names - ) - - -class ConvNextOnnxConfig(OnnxConfig): - torch_onnx_minimum_version = version.parse("1.11") - - @property - def inputs(self) -> Mapping[str, Mapping[int, str]]: - return OrderedDict( - [ - ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), - ] - ) - - @property - def atol_for_validation(self) -> float: - return 1e-5 diff --git a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/efficientformer/convert_efficientformer_original_pytorch_checkpoint_to_pytorch.py b/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/efficientformer/convert_efficientformer_original_pytorch_checkpoint_to_pytorch.py deleted file mode 100644 index 7431cd6136a593e7bd65f33d847e6b9346abfe46..0000000000000000000000000000000000000000 --- a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/efficientformer/convert_efficientformer_original_pytorch_checkpoint_to_pytorch.py +++ /dev/null @@ -1,252 +0,0 @@ -# coding=utf-8 -# Copyright 2022 The HuggingFace Inc. team. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Convert EfficientFormer checkpoints from the original repository. - -URL: https://github.com/snap-research/EfficientFormer -""" - -import argparse -import re -from pathlib import Path - -import requests -import torch -from PIL import Image -from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor - -from transformers import ( - EfficientFormerConfig, - EfficientFormerForImageClassificationWithTeacher, - EfficientFormerImageProcessor, -) -from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling - - -def rename_key(old_name, num_meta4D_last_stage): - new_name = old_name - - if "patch_embed" in old_name: - _, layer, param = old_name.split(".") - - if layer == "0": - new_name = old_name.replace("0", "convolution1") - elif layer == "1": - new_name = old_name.replace("1", "batchnorm_before") - elif layer == "3": - new_name = old_name.replace("3", "convolution2") - else: - new_name = old_name.replace("4", "batchnorm_after") - - if "network" in old_name and re.search(r"\d\.\d", old_name): - two_digit_num = r"\b\d{2}\b" - if bool(re.search(two_digit_num, old_name)): - match = re.search(r"\d\.\d\d.", old_name).group() - else: - match = re.search(r"\d\.\d.", old_name).group() - if int(match[0]) < 6: - trimmed_name = old_name.replace(match, "") - trimmed_name = trimmed_name.replace("network", match[0] + ".meta4D_layers.blocks." + match[2:-1]) - new_name = "intermediate_stages." + trimmed_name - else: - trimmed_name = old_name.replace(match, "") - if int(match[2]) < num_meta4D_last_stage: - trimmed_name = trimmed_name.replace("network", "meta4D_layers.blocks." + match[2]) - else: - layer_index = str(int(match[2]) - num_meta4D_last_stage) - trimmed_name = trimmed_name.replace("network", "meta3D_layers.blocks." + layer_index) - if "norm1" in old_name: - trimmed_name = trimmed_name.replace("norm1", "layernorm1") - elif "norm2" in old_name: - trimmed_name = trimmed_name.replace("norm2", "layernorm2") - elif "fc1" in old_name: - trimmed_name = trimmed_name.replace("fc1", "linear_in") - elif "fc2" in old_name: - trimmed_name = trimmed_name.replace("fc2", "linear_out") - - new_name = "last_stage." + trimmed_name - - elif "network" in old_name and re.search(r".\d.", old_name): - new_name = old_name.replace("network", "intermediate_stages") - - if "fc" in new_name: - new_name = new_name.replace("fc", "convolution") - elif ("norm1" in new_name) and ("layernorm1" not in new_name): - new_name = new_name.replace("norm1", "batchnorm_before") - elif ("norm2" in new_name) and ("layernorm2" not in new_name): - new_name = new_name.replace("norm2", "batchnorm_after") - if "proj" in new_name: - new_name = new_name.replace("proj", "projection") - if "dist_head" in new_name: - new_name = new_name.replace("dist_head", "distillation_classifier") - elif "head" in new_name: - new_name = new_name.replace("head", "classifier") - elif "patch_embed" in new_name: - new_name = "efficientformer." + new_name - elif new_name == "norm.weight" or new_name == "norm.bias": - new_name = new_name.replace("norm", "layernorm") - new_name = "efficientformer." + new_name - else: - new_name = "efficientformer.encoder." + new_name - - return new_name - - -def convert_torch_checkpoint(checkpoint, num_meta4D_last_stage): - for key in checkpoint.copy().keys(): - val = checkpoint.pop(key) - checkpoint[rename_key(key, num_meta4D_last_stage)] = val - - return checkpoint - - -# We will verify our results on a COCO image -def prepare_img(): - url = "http://images.cocodataset.org/val2017/000000039769.jpg" - image = Image.open(requests.get(url, stream=True).raw) - - return image - - -def convert_efficientformer_checkpoint( - checkpoint_path: Path, efficientformer_config_file: Path, pytorch_dump_path: Path, push_to_hub: bool -): - orig_state_dict = torch.load(checkpoint_path, map_location="cpu")["model"] - config = EfficientFormerConfig.from_json_file(efficientformer_config_file) - model = EfficientFormerForImageClassificationWithTeacher(config) - model_name = "_".join(checkpoint_path.split("/")[-1].split(".")[0].split("_")[:-1]) - - num_meta4D_last_stage = config.depths[-1] - config.num_meta3d_blocks + 1 - new_state_dict = convert_torch_checkpoint(orig_state_dict, num_meta4D_last_stage) - - model.load_state_dict(new_state_dict) - model.eval() - - pillow_resamplings = { - "bilinear": PILImageResampling.BILINEAR, - "bicubic": PILImageResampling.BICUBIC, - "nearest": PILImageResampling.NEAREST, - } - - # prepare image - image = prepare_img() - image_size = 256 - crop_size = 224 - processor = EfficientFormerImageProcessor( - size={"shortest_edge": image_size}, - crop_size={"height": crop_size, "width": crop_size}, - resample=pillow_resamplings["bicubic"], - ) - pixel_values = processor(images=image, return_tensors="pt").pixel_values - - # original processing pipeline - image_transforms = Compose( - [ - Resize(image_size, interpolation=pillow_resamplings["bicubic"]), - CenterCrop(crop_size), - ToTensor(), - Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD), - ] - ) - original_pixel_values = image_transforms(image).unsqueeze(0) - - assert torch.allclose(original_pixel_values, pixel_values) - - outputs = model(pixel_values) - logits = outputs.logits - - expected_shape = (1, 1000) - - if "l1" in model_name: - expected_logits = torch.Tensor( - [-0.1312, 0.4353, -1.0499, -0.5124, 0.4183, -0.6793, -1.3777, -0.0893, -0.7358, -2.4328] - ) - assert torch.allclose(logits[0, :10], expected_logits, atol=1e-3) - assert logits.shape == expected_shape - elif "l3" in model_name: - expected_logits = torch.Tensor( - [-1.3150, -1.5456, -1.2556, -0.8496, -0.7127, -0.7897, -0.9728, -0.3052, 0.3751, -0.3127] - ) - assert torch.allclose(logits[0, :10], expected_logits, atol=1e-3) - assert logits.shape == expected_shape - elif "l7" in model_name: - expected_logits = torch.Tensor( - [-1.0283, -1.4131, -0.5644, -1.3115, -0.5785, -1.2049, -0.7528, 0.1992, -0.3822, -0.0878] - ) - assert logits.shape == expected_shape - else: - raise ValueError( - f"Unknown model checkpoint: {checkpoint_path}. Supported version of efficientformer are l1, l3 and l7" - ) - - # Save Checkpoints - Path(pytorch_dump_path).mkdir(exist_ok=True) - model.save_pretrained(pytorch_dump_path) - print(f"Checkpoint successfuly converted. Model saved at {pytorch_dump_path}") - processor.save_pretrained(pytorch_dump_path) - print(f"Processor successfuly saved at {pytorch_dump_path}") - - if push_to_hub: - print("Pushing model to the hub...") - - model.push_to_hub( - repo_id=f"Bearnardd/{pytorch_dump_path}", - commit_message="Add model", - use_temp_dir=True, - ) - processor.push_to_hub( - repo_id=f"Bearnardd/{pytorch_dump_path}", - commit_message="Add image processor", - use_temp_dir=True, - ) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - # Required parameters - parser.add_argument( - "--pytorch_model_path", - default=None, - type=str, - required=True, - help="Path to EfficientFormer pytorch checkpoint.", - ) - parser.add_argument( - "--config_file", - default=None, - type=str, - required=True, - help="The json file for EfficientFormer model config.", - ) - parser.add_argument( - "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." - ) - - parser.add_argument("--push_to_hub", action="store_true", help="Push model and image processor to the hub") - parser.add_argument( - "--no-push_to_hub", - dest="push_to_hub", - action="store_false", - help="Do not push model and image processor to the hub", - ) - parser.set_defaults(push_to_hub=True) - - args = parser.parse_args() - convert_efficientformer_checkpoint( - checkpoint_path=args.pytorch_model_path, - efficientformer_config_file=args.config_file, - pytorch_dump_path=args.pytorch_dump_path, - push_to_hub=args.push_to_hub, - ) diff --git a/spaces/yizhangliu/ImgCleaner/README.md b/spaces/yizhangliu/ImgCleaner/README.md deleted file mode 100644 index 9b212c4e29ff727a17db2cafefdcbe4d151f28d7..0000000000000000000000000000000000000000 --- a/spaces/yizhangliu/ImgCleaner/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: ImgCleaner -emoji: 📊 -colorFrom: blue -colorTo: yellow -sdk: gradio -sdk_version: 3.9.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/ynhe/AskAnything/models/grit_src/third_party/CenterNet2/detectron2/checkpoint/catalog.py b/spaces/ynhe/AskAnything/models/grit_src/third_party/CenterNet2/detectron2/checkpoint/catalog.py deleted file mode 100644 index 9a85736754a0de4550df96c22f38fc515bd02d71..0000000000000000000000000000000000000000 --- a/spaces/ynhe/AskAnything/models/grit_src/third_party/CenterNet2/detectron2/checkpoint/catalog.py +++ /dev/null @@ -1,115 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import logging - -from detectron2.utils.file_io import PathHandler, PathManager - - -class ModelCatalog(object): - """ - Store mappings from names to third-party models. - """ - - S3_C2_DETECTRON_PREFIX = "https://dl.fbaipublicfiles.com/detectron" - - # MSRA models have STRIDE_IN_1X1=True. False otherwise. - # NOTE: all BN models here have fused BN into an affine layer. - # As a result, you should only load them to a model with "FrozenBN". - # Loading them to a model with regular BN or SyncBN is wrong. - # Even when loaded to FrozenBN, it is still different from affine by an epsilon, - # which should be negligible for training. - # NOTE: all models here uses PIXEL_STD=[1,1,1] - # NOTE: Most of the BN models here are no longer used. We use the - # re-converted pre-trained models under detectron2 model zoo instead. - C2_IMAGENET_MODELS = { - "MSRA/R-50": "ImageNetPretrained/MSRA/R-50.pkl", - "MSRA/R-101": "ImageNetPretrained/MSRA/R-101.pkl", - "FAIR/R-50-GN": "ImageNetPretrained/47261647/R-50-GN.pkl", - "FAIR/R-101-GN": "ImageNetPretrained/47592356/R-101-GN.pkl", - "FAIR/X-101-32x8d": "ImageNetPretrained/20171220/X-101-32x8d.pkl", - "FAIR/X-101-64x4d": "ImageNetPretrained/FBResNeXt/X-101-64x4d.pkl", - "FAIR/X-152-32x8d-IN5k": "ImageNetPretrained/25093814/X-152-32x8d-IN5k.pkl", - } - - C2_DETECTRON_PATH_FORMAT = ( - "{prefix}/{url}/output/train/{dataset}/{type}/model_final.pkl" # noqa B950 - ) - - C2_DATASET_COCO = "coco_2014_train%3Acoco_2014_valminusminival" - C2_DATASET_COCO_KEYPOINTS = "keypoints_coco_2014_train%3Akeypoints_coco_2014_valminusminival" - - # format: {model_name} -> part of the url - C2_DETECTRON_MODELS = { - "35857197/e2e_faster_rcnn_R-50-C4_1x": "35857197/12_2017_baselines/e2e_faster_rcnn_R-50-C4_1x.yaml.01_33_49.iAX0mXvW", # noqa B950 - "35857345/e2e_faster_rcnn_R-50-FPN_1x": "35857345/12_2017_baselines/e2e_faster_rcnn_R-50-FPN_1x.yaml.01_36_30.cUF7QR7I", # noqa B950 - "35857890/e2e_faster_rcnn_R-101-FPN_1x": "35857890/12_2017_baselines/e2e_faster_rcnn_R-101-FPN_1x.yaml.01_38_50.sNxI7sX7", # noqa B950 - "36761737/e2e_faster_rcnn_X-101-32x8d-FPN_1x": "36761737/12_2017_baselines/e2e_faster_rcnn_X-101-32x8d-FPN_1x.yaml.06_31_39.5MIHi1fZ", # noqa B950 - "35858791/e2e_mask_rcnn_R-50-C4_1x": "35858791/12_2017_baselines/e2e_mask_rcnn_R-50-C4_1x.yaml.01_45_57.ZgkA7hPB", # noqa B950 - "35858933/e2e_mask_rcnn_R-50-FPN_1x": "35858933/12_2017_baselines/e2e_mask_rcnn_R-50-FPN_1x.yaml.01_48_14.DzEQe4wC", # noqa B950 - "35861795/e2e_mask_rcnn_R-101-FPN_1x": "35861795/12_2017_baselines/e2e_mask_rcnn_R-101-FPN_1x.yaml.02_31_37.KqyEK4tT", # noqa B950 - "36761843/e2e_mask_rcnn_X-101-32x8d-FPN_1x": "36761843/12_2017_baselines/e2e_mask_rcnn_X-101-32x8d-FPN_1x.yaml.06_35_59.RZotkLKI", # noqa B950 - "48616381/e2e_mask_rcnn_R-50-FPN_2x_gn": "GN/48616381/04_2018_gn_baselines/e2e_mask_rcnn_R-50-FPN_2x_gn_0416.13_23_38.bTlTI97Q", # noqa B950 - "37697547/e2e_keypoint_rcnn_R-50-FPN_1x": "37697547/12_2017_baselines/e2e_keypoint_rcnn_R-50-FPN_1x.yaml.08_42_54.kdzV35ao", # noqa B950 - "35998355/rpn_R-50-C4_1x": "35998355/12_2017_baselines/rpn_R-50-C4_1x.yaml.08_00_43.njH5oD9L", # noqa B950 - "35998814/rpn_R-50-FPN_1x": "35998814/12_2017_baselines/rpn_R-50-FPN_1x.yaml.08_06_03.Axg0r179", # noqa B950 - "36225147/fast_R-50-FPN_1x": "36225147/12_2017_baselines/fast_rcnn_R-50-FPN_1x.yaml.08_39_09.L3obSdQ2", # noqa B950 - } - - @staticmethod - def get(name): - if name.startswith("Caffe2Detectron/COCO"): - return ModelCatalog._get_c2_detectron_baseline(name) - if name.startswith("ImageNetPretrained/"): - return ModelCatalog._get_c2_imagenet_pretrained(name) - raise RuntimeError("model not present in the catalog: {}".format(name)) - - @staticmethod - def _get_c2_imagenet_pretrained(name): - prefix = ModelCatalog.S3_C2_DETECTRON_PREFIX - name = name[len("ImageNetPretrained/") :] - name = ModelCatalog.C2_IMAGENET_MODELS[name] - url = "/".join([prefix, name]) - return url - - @staticmethod - def _get_c2_detectron_baseline(name): - name = name[len("Caffe2Detectron/COCO/") :] - url = ModelCatalog.C2_DETECTRON_MODELS[name] - if "keypoint_rcnn" in name: - dataset = ModelCatalog.C2_DATASET_COCO_KEYPOINTS - else: - dataset = ModelCatalog.C2_DATASET_COCO - - if "35998355/rpn_R-50-C4_1x" in name: - # this one model is somehow different from others .. - type = "rpn" - else: - type = "generalized_rcnn" - - # Detectron C2 models are stored in the structure defined in `C2_DETECTRON_PATH_FORMAT`. - url = ModelCatalog.C2_DETECTRON_PATH_FORMAT.format( - prefix=ModelCatalog.S3_C2_DETECTRON_PREFIX, url=url, type=type, dataset=dataset - ) - return url - - -class ModelCatalogHandler(PathHandler): - """ - Resolve URL like catalog://. - """ - - PREFIX = "catalog://" - - def _get_supported_prefixes(self): - return [self.PREFIX] - - def _get_local_path(self, path, **kwargs): - logger = logging.getLogger(__name__) - catalog_path = ModelCatalog.get(path[len(self.PREFIX) :]) - logger.info("Catalog entry {} points to {}".format(path, catalog_path)) - return PathManager.get_local_path(catalog_path, **kwargs) - - def _open(self, path, mode="r", **kwargs): - return PathManager.open(self._get_local_path(path), mode, **kwargs) - - -PathManager.register_handler(ModelCatalogHandler()) diff --git a/spaces/yock116/ChuanhuChatGPT/run_macOS.command b/spaces/yock116/ChuanhuChatGPT/run_macOS.command deleted file mode 100644 index 62af07283093d8e580763d7acfe493c3d88e7b08..0000000000000000000000000000000000000000 --- a/spaces/yock116/ChuanhuChatGPT/run_macOS.command +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash - -# 获取脚本所在目录 -script_dir=$(dirname "$0") - -# 将工作目录更改为脚本所在目录 -cd "$script_dir" - -# 检查Git仓库是否有更新 -git remote update -pwd - -if ! git status -uno | grep 'up to date' > /dev/null; then - # 如果有更新,关闭当前运行的服务器 - pkill -f ChuanhuChatbot.py - - # 拉取最新更改 - git pull - - # 安装依赖 - pip3 install -r requirements.txt - - # 重新启动服务器 - nohup python3 ChuanhuChatbot.py & -fi diff --git a/spaces/yueranseo/mygpt/modules/models/tokenization_moss.py b/spaces/yueranseo/mygpt/modules/models/tokenization_moss.py deleted file mode 100644 index 626315eb9e429ada99a15b04b9736c05e6743ffe..0000000000000000000000000000000000000000 --- a/spaces/yueranseo/mygpt/modules/models/tokenization_moss.py +++ /dev/null @@ -1,368 +0,0 @@ -"""Tokenization classes for Moss""" - -import json -import os -import numpy as np -import regex as re - -from functools import lru_cache -from typing import TYPE_CHECKING, List, Optional, Tuple, Union - -from transformers.utils import is_tf_available, is_torch_available, logging -from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer - - -if TYPE_CHECKING: - if is_torch_available(): - import torch - if is_tf_available(): - import tensorflow as tf - - -logger = logging.get_logger(__name__) - -VOCAB_FILES_NAMES = { - "vocab_file": "vocab.json", - "merges_file": "merges.txt", -} - -PRETRAINED_VOCAB_FILES_MAP = { - "vocab_file": { - "fnlp/moss-moon-003-base": "https://huggingface.co/fnlp/moss-moon-003-base/resolve/main/vocab.json", - "fnlp/moss-moon-003-sft": "https://huggingface.co/fnlp/moss-moon-003-sft/resolve/main/vocab.json", - "fnlp/moss-moon-003-sft-plugin": "https://huggingface.co/fnlp/moss-moon-003-sft-plugin/resolve/main/vocab.json", - }, - "merges_file": { - "fnlp/moss-moon-003-base": "https://huggingface.co/fnlp/moss-moon-003-base/resolve/main/merges.txt", - "fnlp/moss-moon-003-sft": "https://huggingface.co/fnlp/moss-moon-003-sft/resolve/main/merges.txt", - "fnlp/moss-moon-003-sft-plugin": "https://huggingface.co/fnlp/moss-moon-003-sft-plugin/resolve/main/merges.txt", - }, -} - -PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { - "fnlp/moss-moon-003-base": 2048, - "fnlp/moss-moon-003-sft": 2048, - "fnlp/moss-moon-003-sft-plugin": 2048, -} - - -@lru_cache() -def bytes_to_unicode(): - """ - Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control - characters the bpe code barfs on. - - The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab - if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for - decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup - tables between utf-8 bytes and unicode strings. - """ - bs = ( - list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1)) - ) - cs = bs[:] - n = 0 - for b in range(2**8): - if b not in bs: - bs.append(b) - cs.append(2**8 + n) - n += 1 - cs = [chr(n) for n in cs] - return dict(zip(bs, cs)) - - -def get_pairs(word): - """ - Return set of symbol pairs in a word. - - Word is represented as tuple of symbols (symbols being variable-length strings). - """ - pairs = set() - prev_char = word[0] - for char in word[1:]: - pairs.add((prev_char, char)) - prev_char = char - return pairs - - -class MossTokenizer(PreTrainedTokenizer): - """ - Construct a Moss tokenizer. Based on byte-level Byte-Pair-Encoding. - - This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will - be encoded differently whether it is at the beginning of the sentence (without space) or not: - - You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you - call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance. - - - - When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one). - - - - This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to - this superclass for more information regarding those methods. - - Args: - vocab_file (`str`): - Path to the vocabulary file. - merges_file (`str`): - Path to the merges file. - errors (`str`, *optional*, defaults to `"replace"`): - Paradigm to follow when decoding bytes to UTF-8. See - [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information. - unk_token (`str`, *optional*, defaults to `<|endoftext|>`): - The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this - token instead. - bos_token (`str`, *optional*, defaults to `<|endoftext|>`): - The beginning of sequence token. - eos_token (`str`, *optional*, defaults to `<|endoftext|>`): - The end of sequence token. - add_prefix_space (`bool`, *optional*, defaults to `False`): - Whether or not to add an initial space to the input. This allows to treat the leading word just as any - other word. (Moss tokenizer detect beginning of words by the preceding space). - """ - - vocab_files_names = VOCAB_FILES_NAMES - pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP - max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES - model_input_names = ["input_ids", "attention_mask"] - - def __init__( - self, - vocab_file, - merges_file, - errors="replace", - unk_token="<|endoftext|>", - bos_token="<|endoftext|>", - eos_token="", - pad_token=None, - add_prefix_space=False, - add_bos_token=False, - **kwargs, - ): - bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token - eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token - unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token - pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token - super().__init__( - errors=errors, - unk_token=unk_token, - bos_token=bos_token, - eos_token=eos_token, - pad_token=pad_token, - add_prefix_space=add_prefix_space, - add_bos_token=add_bos_token, - **kwargs, - ) - self.add_bos_token = add_bos_token - - with open(vocab_file, encoding="utf-8") as vocab_handle: - self.encoder = json.load(vocab_handle) - self.decoder = {v: k for k, v in self.encoder.items()} - self.errors = errors # how to handle errors in decoding - self.byte_encoder = bytes_to_unicode() - self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} - with open(merges_file, encoding="utf-8") as merges_handle: - bpe_merges = merges_handle.read().split("\n")[1:-1] - bpe_merges = [tuple(merge.split()) for merge in bpe_merges] - self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges)))) - self.cache = {} - self.add_prefix_space = add_prefix_space - - # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions - self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""") - - @property - def vocab_size(self): - return len(self.encoder) - - def get_vocab(self): - return dict(self.encoder, **self.added_tokens_encoder) - - def bpe(self, token): - if token in self.cache: - return self.cache[token] - word = tuple(token) - pairs = get_pairs(word) - - if not pairs: - return token - - while True: - bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf"))) - if bigram not in self.bpe_ranks: - break - first, second = bigram - new_word = [] - i = 0 - while i < len(word): - try: - j = word.index(first, i) - except ValueError: - new_word.extend(word[i:]) - break - else: - new_word.extend(word[i:j]) - i = j - - if word[i] == first and i < len(word) - 1 and word[i + 1] == second: - new_word.append(first + second) - i += 2 - else: - new_word.append(word[i]) - i += 1 - new_word = tuple(new_word) - word = new_word - if len(word) == 1: - break - else: - pairs = get_pairs(word) - word = " ".join(word) - self.cache[token] = word - return word - - def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None): - if self.add_bos_token: - bos_token_ids = [self.bos_token_id] - else: - bos_token_ids = [] - - output = bos_token_ids + token_ids_0 - - if token_ids_1 is None: - return output - - return output + bos_token_ids + token_ids_1 - - def _tokenize(self, text): - """Tokenize a string.""" - bpe_tokens = [] - for token in re.findall(self.pat, text): - token = "".join( - self.byte_encoder[b] for b in token.encode("utf-8") - ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) - bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" ")) - return bpe_tokens - - def _convert_token_to_id(self, token): - """Converts a token (str) in an id using the vocab.""" - return self.encoder.get(token, self.encoder.get(self.unk_token)) - - def _convert_id_to_token(self, index): - """Converts an index (integer) in a token (str) using the vocab.""" - return self.decoder.get(index) - - def convert_tokens_to_string(self, tokens): - """Converts a sequence of tokens (string) in a single string.""" - text = "".join(tokens) - text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors) - return text - - def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: - if not os.path.isdir(save_directory): - logger.error(f"Vocabulary path ({save_directory}) should be a directory") - return - vocab_file = os.path.join( - save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] - ) - merge_file = os.path.join( - save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] - ) - - with open(vocab_file, "w", encoding="utf-8") as f: - f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n") - - index = 0 - with open(merge_file, "w", encoding="utf-8") as writer: - writer.write("#version: 0.2\n") - for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]): - if index != token_index: - logger.warning( - f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive." - " Please check that the tokenizer is not corrupted!" - ) - index = token_index - writer.write(" ".join(bpe_tokens) + "\n") - index += 1 - - return vocab_file, merge_file - - def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs): - add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space) - if is_split_into_words or add_prefix_space: - text = " " + text - return (text, kwargs) - - def decode( - self, - token_ids: Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"], - skip_special_tokens: bool = False, - clean_up_tokenization_spaces: bool = None, - truncate_before_pattern: Optional[List[str]] = None, - **kwargs, - ) -> str: - """ - Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special - tokens and clean up tokenization spaces. - - Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`. - - Args: - token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`): - List of tokenized input ids. Can be obtained using the `__call__` method. - skip_special_tokens (`bool`, *optional*, defaults to `False`): - Whether or not to remove special tokens in the decoding. - clean_up_tokenization_spaces (`bool`, *optional*): - Whether or not to clean up the tokenization spaces. If `None`, will default to - `self.clean_up_tokenization_spaces` (available in the `tokenizer_config`). - truncate_before_pattern (`List[str]`, *optional*, defaults to `None`): - A list of regular expression strings that will be used to truncate the returned string. This can be - used to remove extra pieces of code (e.g. truncate if observing a comment symbol "#" at the beginning - of a new line). An example pattern could be `["^#", re.escape("<|endoftext|>"), "^'''", "\n\n\n"]`. - kwargs (additional keyword arguments, *optional*): - Will be passed to the underlying model specific decode method. - - Returns: - `str`: The decoded sentence. - """ - decoded_text = super()._decode( - token_ids=token_ids, - skip_special_tokens=skip_special_tokens, - clean_up_tokenization_spaces=clean_up_tokenization_spaces, - **kwargs, - ) - - if truncate_before_pattern is not None and len(truncate_before_pattern) > 0: - decoded_text = self.truncate(decoded_text, truncate_before_pattern) - - return decoded_text - - def truncate(self, completion, truncate_before_pattern): - def find_re(string, pattern, start_pos): - m = pattern.search(string, start_pos) - return m.start() if m else -1 - - terminals = [re.compile(pattern, re.MULTILINE) for pattern in truncate_before_pattern] - - prints = list(re.finditer("^print", completion, re.MULTILINE)) - - if len(prints) > 1: - completion = completion[: prints[1].start()] - - defs = list(re.finditer("^def", completion, re.MULTILINE)) - - if len(defs) > 1: - completion = completion[: defs[1].start()] - - start_pos = 0 - - terminals_pos = [ - pos for pos in [find_re(completion, terminal, start_pos) for terminal in terminals] if pos != -1 - ] - - if len(terminals_pos) > 0: - return completion[: min(terminals_pos)] - else: - return completion diff --git a/spaces/yufiofficial/MusicGenQ/audiocraft/models/lm.py b/spaces/yufiofficial/MusicGenQ/audiocraft/models/lm.py deleted file mode 100644 index c8aad8f06797eef3293605056e1de14d07c56c2a..0000000000000000000000000000000000000000 --- a/spaces/yufiofficial/MusicGenQ/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/yunfei0710/gpt-academic/crazy_functions/test_project/latex/attention/background.tex b/spaces/yunfei0710/gpt-academic/crazy_functions/test_project/latex/attention/background.tex deleted file mode 100644 index 785069dc0f9143bad24e640056dd1072d5c6e5b5..0000000000000000000000000000000000000000 --- a/spaces/yunfei0710/gpt-academic/crazy_functions/test_project/latex/attention/background.tex +++ /dev/null @@ -1,58 +0,0 @@ -The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU \citep{extendedngpu}, ByteNet \citep{NalBytenet2017} and ConvS2S \citep{JonasFaceNet2017}, all of which use convolutional neural networks as basic building block, computing hidden representations in parallel for all input and output positions. In these models, the number of operations required to relate signals from two arbitrary input or output positions grows in the distance between positions, linearly for ConvS2S and logarithmically for ByteNet. This makes it more difficult to learn dependencies between distant positions \citep{hochreiter2001gradient}. In the Transformer this is reduced to a constant number of operations, albeit at the cost of reduced effective resolution due to averaging attention-weighted positions, an effect we counteract with Multi-Head Attention as described in section~\ref{sec:attention}. - -Self-attention, sometimes called intra-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence. Self-attention has been used successfully in a variety of tasks including reading comprehension, abstractive summarization, textual entailment and learning task-independent sentence representations \citep{cheng2016long, decomposableAttnModel, paulus2017deep, lin2017structured}. - -End-to-end memory networks are based on a recurrent attention mechanism instead of sequence-aligned recurrence and have been shown to perform well on simple-language question answering and language modeling tasks \citep{sukhbaatar2015}. - -To the best of our knowledge, however, the Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequence-aligned RNNs or convolution. -In the following sections, we will describe the Transformer, motivate self-attention and discuss its advantages over models such as \citep{neural_gpu, NalBytenet2017} and \citep{JonasFaceNet2017}. - - -%\citep{JonasFaceNet2017} report new SOTA on machine translation for English-to-German (EnDe), Enlish-to-French (EnFr) and English-to-Romanian language pairs. - -%For example,! in MT, we must draw information from both input and previous output words to translate an output word accurately. An attention layer \citep{bahdanau2014neural} can connect a very large number of positions at low computation cost, making it an essential ingredient in competitive recurrent models for machine translation. - -%A natural question to ask then is, "Could we replace recurrence with attention?". \marginpar{Don't know if it's the most natural question to ask given the previous statements. Also, need to say that the complexity table summarizes these statements} Such a model would be blessed with the computational efficiency of attention and the power of cross-positional communication. In this work, show that pure attention models work remarkably well for MT, achieving new SOTA results on EnDe and EnFr, and can be trained in under $2$ days on xyz architecture. - -%After the seminal models introduced in \citep{sutskever14, bahdanau2014neural, cho2014learning}, recurrent models have become the dominant solution for both sequence modeling and sequence-to-sequence transduction. Many efforts such as \citep{wu2016google,luong2015effective,jozefowicz2016exploring} have pushed the boundaries of machine translation (MT) and language modeling with recurrent endoder-decoder and recurrent language models. Recent effort \citep{shazeer2017outrageously} has successfully combined the power of conditional computation with sequence models to train very large models for MT, pushing SOTA at lower computational cost. - -%Recurrent models compute a vector of hidden states $h_t$, for each time step $t$ of computation. $h_t$ is a function of both the input at time $t$ and the previous hidden state $h_t$. This dependence on the previous hidden state precludes processing all timesteps at once, instead requiring long sequences of sequential operations. In practice, this results in greatly reduced computational efficiency, as on modern computing hardware, a single operation on a large batch is much faster than a large number of operations on small batches. The problem gets worse at longer sequence lengths. Although sequential computation is not a severe bottleneck at inference time, as autoregressively generating each output requires all previous outputs, the inability to compute scores at all output positions at once hinders us from rapidly training our models over large datasets. Although impressive work such as \citep{Kuchaiev2017Factorization} is able to significantly accelerate the training of LSTMs with factorization tricks, we are still bound by the linear dependence on sequence length. - -%If the model could compute hidden states at each time step using only the inputs and outputs, it would be liberated from the dependence on results from previous time steps during training. This line of thought is the foundation of recent efforts such as the Markovian neural GPU \citep{neural_gpu}, ByteNet \citep{NalBytenet2017} and ConvS2S \citep{JonasFaceNet2017}, all of which use convolutional neural networks as a building block to compute hidden representations simultaneously for all timesteps, resulting in $O(1)$ sequential time complexity. \citep{JonasFaceNet2017} report new SOTA on machine translation for English-to-German (EnDe), Enlish-to-French (EnFr) and English-to-Romanian language pairs. - -%A crucial component for accurate sequence prediction is modeling cross-positional communication. For example, in MT, we must draw information from both input and previous output words to translate an output word accurately. An attention layer \citep{bahdanau2014neural} can connect a very large number of positions at a low computation cost, also $O(1)$ sequential time complexity, making it an essential ingredient in recurrent encoder-decoder architectures for MT. A natural question to ask then is, "Could we replace recurrence with attention?". \marginpar{Don't know if it's the most natural question to ask given the previous statements. Also, need to say that the complexity table summarizes these statements} Such a model would be blessed with the computational efficiency of attention and the power of cross-positional communication. In this work, show that pure attention models work remarkably well for MT, achieving new SOTA results on EnDe and EnFr, and can be trained in under $2$ days on xyz architecture. - - - -%Note: Facebook model is no better than RNNs in this regard, since it requires a number of layers proportional to the distance you want to communicate. Bytenet is more promising, since it requires a logarithmnic number of layers (does bytenet have SOTA results)? - -%Note: An attention layer can connect a very large number of positions at a low computation cost in O(1) sequential operations. This is why encoder-decoder attention has been so successful in seq-to-seq models so far. It is only natural, then, to also use attention to connect the timesteps of the same sequence. - -%Note: I wouldn't say that long sequences are not a problem during inference. It would be great if we could infer with no long sequences. We could just say later on that, while our training graph is constant-depth, our model still requires sequential operations in the decoder part during inference due to the autoregressive nature of the model. - -%\begin{table}[h!] -%\caption{Attention models are quite efficient for cross-positional communications when sequence length is smaller than channel depth. $n$ represents the sequence length and $d$ represents the channel depth.} -%\label{tab:op_complexities} -%\begin{center} -%\vspace{-5pt} -%\scalebox{0.75}{ - -%\begin{tabular}{l|c|c|c} -%\hline \hline -%Layer Type & Receptive & Complexity & Sequential \\ -% & Field & & Operations \\ -%\hline -%Pointwise Feed-Forward & $1$ & $O(n \cdot d^2)$ & $O(1)$ \\ -%\hline -%Recurrent & $n$ & $O(n \cdot d^2)$ & $O(n)$ \\ -%\hline -%Convolutional & $r$ & $O(r \cdot n \cdot d^2)$ & $O(1)$ \\ -%\hline -%Convolutional (separable) & $r$ & $O(r \cdot n \cdot d + n %\cdot d^2)$ & $O(1)$ \\ -%\hline -%Attention & $r$ & $O(r \cdot n \cdot d)$ & $O(1)$ \\ -%\hline \hline -%\end{tabular} -%} -%\end{center} -%\end{table} \ No newline at end of file diff --git a/spaces/zhang-wei-jian/docker/node_modules/has-tostringtag/test/index.js b/spaces/zhang-wei-jian/docker/node_modules/has-tostringtag/test/index.js deleted file mode 100644 index 0679afdfa78bffebe91fda3023491bba375b53a6..0000000000000000000000000000000000000000 --- a/spaces/zhang-wei-jian/docker/node_modules/has-tostringtag/test/index.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var test = require('tape'); -var hasSymbolToStringTag = require('../'); -var runSymbolTests = require('./tests'); - -test('interface', function (t) { - t.equal(typeof hasSymbolToStringTag, 'function', 'is a function'); - t.equal(typeof hasSymbolToStringTag(), 'boolean', 'returns a boolean'); - t.end(); -}); - -test('Symbol.toStringTag exists', { skip: !hasSymbolToStringTag() }, function (t) { - runSymbolTests(t); - t.end(); -}); - -test('Symbol.toStringTag does not exist', { skip: hasSymbolToStringTag() }, function (t) { - t.equal(typeof Symbol === 'undefined' ? 'undefined' : typeof Symbol.toStringTag, 'undefined', 'global Symbol.toStringTag is undefined'); - t.end(); -}); diff --git a/spaces/zhang-wei-jian/docker/node_modules/picomatch/index.js b/spaces/zhang-wei-jian/docker/node_modules/picomatch/index.js deleted file mode 100644 index d2f2bc59d0ac7c40b35c574c45bcedbf26263d75..0000000000000000000000000000000000000000 --- a/spaces/zhang-wei-jian/docker/node_modules/picomatch/index.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('./lib/picomatch'); diff --git a/spaces/zhang-wei-jian/docker/node_modules/simple-update-notifier/node_modules/semver/ranges/max-satisfying.js b/spaces/zhang-wei-jian/docker/node_modules/simple-update-notifier/node_modules/semver/ranges/max-satisfying.js deleted file mode 100644 index 6e3d993c67860c941fb68e66911d40e174e09ab3..0000000000000000000000000000000000000000 --- a/spaces/zhang-wei-jian/docker/node_modules/simple-update-notifier/node_modules/semver/ranges/max-satisfying.js +++ /dev/null @@ -1,25 +0,0 @@ -const SemVer = require('../classes/semver') -const Range = require('../classes/range') - -const maxSatisfying = (versions, range, options) => { - let max = null - let maxSV = null - let rangeObj = null - try { - rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) - } - } - }) - return max -} -module.exports = maxSatisfying diff --git a/spaces/zhigangjiang/3D-Room-Layout-Estimation_LGT-Net/utils/__init__.py b/spaces/zhigangjiang/3D-Room-Layout-Estimation_LGT-Net/utils/__init__.py deleted file mode 100644 index 02f1ee32e3c69bcf40722de4d5fb831ede759aae..0000000000000000000000000000000000000000 --- a/spaces/zhigangjiang/3D-Room-Layout-Estimation_LGT-Net/utils/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -""" -@date: 2021/06/19 -@description: -""" \ No newline at end of file diff --git a/spaces/zhuyuheng/IMossGPT/run_Windows.bat b/spaces/zhuyuheng/IMossGPT/run_Windows.bat deleted file mode 100644 index 4c18f9ccaeea0af972301ffdf48778641221f76d..0000000000000000000000000000000000000000 --- a/spaces/zhuyuheng/IMossGPT/run_Windows.bat +++ /dev/null @@ -1,5 +0,0 @@ -@echo off -echo Opening ChuanhuChatGPT... - -REM Open powershell via bat -start powershell.exe -NoExit -Command "python ./ChuanhuChatbot.py" diff --git a/spaces/ziguo/Real-ESRGAN/Training.md b/spaces/ziguo/Real-ESRGAN/Training.md deleted file mode 100644 index 64704e1d2e1f334984232afd12b245235b274a9e..0000000000000000000000000000000000000000 --- a/spaces/ziguo/Real-ESRGAN/Training.md +++ /dev/null @@ -1,100 +0,0 @@ -# :computer: How to Train Real-ESRGAN - -The training codes have been released.
            -Note that the codes have a lot of refactoring. So there may be some bugs/performance drops. Welcome to report issues and I will also retrain the models. - -## Overview - -The training has been divided into two stages. These two stages have the same data synthesis process and training pipeline, except for the loss functions. Specifically, - -1. We first train Real-ESRNet with L1 loss from the pre-trained model ESRGAN. -1. We then use the trained Real-ESRNet model as an initialization of the generator, and train the Real-ESRGAN with a combination of L1 loss, perceptual loss and GAN loss. - -## Dataset Preparation - -We use DF2K (DIV2K and Flickr2K) + OST datasets for our training. Only HR images are required.
            -You can download from : - -1. DIV2K: http://data.vision.ee.ethz.ch/cvl/DIV2K/DIV2K_train_HR.zip -2. Flickr2K: https://cv.snu.ac.kr/research/EDSR/Flickr2K.tar -3. OST: https://openmmlab.oss-cn-hangzhou.aliyuncs.com/datasets/OST_dataset.zip - -For the DF2K dataset, we use a multi-scale strategy, *i.e.*, we downsample HR images to obtain several Ground-Truth images with different scales. - -We then crop DF2K images into sub-images for faster IO and processing. - -You need to prepare a txt file containing the image paths. The following are some examples in `meta_info_DF2Kmultiscale+OST_sub.txt` (As different users may have different sub-images partitions, this file is not suitable for your purpose and you need to prepare your own txt file): - -```txt -DF2K_HR_sub/000001_s001.png -DF2K_HR_sub/000001_s002.png -DF2K_HR_sub/000001_s003.png -... -``` - -## Train Real-ESRNet - -1. Download pre-trained model [ESRGAN](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth) into `experiments/pretrained_models`. - ```bash - wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth -P experiments/pretrained_models - ``` -1. Modify the content in the option file `options/train_realesrnet_x4plus.yml` accordingly: - ```yml - train: - name: DF2K+OST - type: RealESRGANDataset - dataroot_gt: datasets/DF2K # modify to the root path of your folder - meta_info: realesrgan/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt # modify to your own generate meta info txt - io_backend: - type: disk - ``` -1. If you want to perform validation during training, uncomment those lines and modify accordingly: - ```yml - # Uncomment these for validation - # val: - # name: validation - # type: PairedImageDataset - # dataroot_gt: path_to_gt - # dataroot_lq: path_to_lq - # io_backend: - # type: disk - - ... - - # Uncomment these for validation - # validation settings - # val: - # val_freq: !!float 5e3 - # save_img: True - - # metrics: - # psnr: # metric name, can be arbitrary - # type: calculate_psnr - # crop_border: 4 - # test_y_channel: false - ``` -1. Before the formal training, you may run in the `--debug` mode to see whether everything is OK. We use four GPUs for training: - ```bash - CUDA_VISIBLE_DEVICES=0,1,2,3 \ - python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --launcher pytorch --debug - ``` -1. The formal training. We use four GPUs for training. We use the `--auto_resume` argument to automatically resume the training if necessary. - ```bash - CUDA_VISIBLE_DEVICES=0,1,2,3 \ - python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --launcher pytorch --auto_resume - ``` - -## Train Real-ESRGAN - -1. After the training of Real-ESRNet, you now have the file `experiments/train_RealESRNetx4plus_1000k_B12G4_fromESRGAN/model/net_g_1000000.pth`. If you need to specify the pre-trained path to other files, modify the `pretrain_network_g` value in the option file `train_realesrgan_x4plus.yml`. -1. Modify the option file `train_realesrgan_x4plus.yml` accordingly. Most modifications are similar to those listed above. -1. Before the formal training, you may run in the `--debug` mode to see whether everything is OK. We use four GPUs for training: - ```bash - CUDA_VISIBLE_DEVICES=0,1,2,3 \ - python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --launcher pytorch --debug - ``` -1. The formal training. We use four GPUs for training. We use the `--auto_resume` argument to automatically resume the training if necessary. - ```bash - CUDA_VISIBLE_DEVICES=0,1,2,3 \ - python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --launcher pytorch --auto_resume - ```